Repository navigation
feat(invoice): query usage by customer - #3208
Conversation
📝 WalkthroughWalkthroughAdds optional customer key snapshotting to invoices end-to-end: schema/migrations, Ent models/builders, adapter/service logic, and API exposure. Transitions quantity snapshotting from subject-keys to a streaming-aware customer interface. Updates streaming query params/ClickHouse to accept generic customers. Extends OpenAPI/specs and tests accordingly. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
✨ Finishing Touches
🧪 Generate unit tests
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. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 8
🔭 Outside diff range comments (6)
openmeter/app/stripe/httpdriver/checkout_session.go (1)
79-95: Guard against nil customer when resolving by key to avoid panicIf GetCustomer returns (nil, nil) for a missing key, cus.GetCustomerID() will panic. Add a nil-check and return a NotFound-style error.
Apply:
cus, err := h.customerService.GetCustomer(ctx, customer.GetCustomerInput{ CustomerKey: lo.ToPtr( customer.CustomerKey{ Namespace: namespace, Key: *customerKey, }, ), }) if err != nil { return CreateAppStripeCheckoutSessionRequest{}, fmt.Errorf("failed to get customer by key: %w", err) } + if cus == nil { + return CreateAppStripeCheckoutSessionRequest{}, models.NewGenericNotFoundError( + fmt.Errorf("customer with key %q not found", *customerKey), + ) + } - customerId = lo.ToPtr(cus.GetCustomerID()) + customerId = lo.ToPtr(cus.GetCustomerID())openmeter/billing/service/invoicestate.go (1)
714-736: Nil dereference risk when CollectionAt is nil in snapshotQuantityAsNeededclock.Now().Before(*m.Invoice.CollectionAt) will panic if CollectionAt is nil. Guard the deref.
Apply this diff:
- // We don't have the snapshot and the collection date is in the future - if m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) { + // We don't have the snapshot and the collection date is in the future + if m.Invoice.CollectionAt != nil && m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) { return nil }openmeter/billing/adapter/invoice.go (1)
674-701: Expose Customer.Key in API: OK. Also fix possible nil dereference for CollectionAtMapping invoice.CustomerKey into API’s InvoiceCustomer.Key looks correct.
However, CollectionAt is mapped via invoice.CollectionAt.In(time.UTC), which will panic when invoice.CollectionAt is nil. Use the same helper as other time fields.
Apply this diff:
- CollectionAt: lo.ToPtr(invoice.CollectionAt.In(time.UTC)), + CollectionAt: convert.TimePtrIn(invoice.CollectionAt, time.UTC),Consider adding/adjusting a unit/integration test to cover the presence/absence of CustomerKey and nil CollectionAt serialization.
openmeter/streaming/clickhouse/meter_query.go (2)
306-315: Guard empty subject lists and dedupe subjects to avoid malformed SQLIn huandu/go-sqlbuilder, calling
Or()with zero arguments emits an empty condition fragment, which can produce invalid or unintended WHERE clauses. Duplicated subject keys also bloat the generated SQL. Update the filter block inopenmeter/streaming/clickhouse/meter_query.goas follows:--- a/openmeter/streaming/clickhouse/meter_query.go +++ b/openmeter/streaming/clickhouse/meter_query.go @@ -303,11 +303,20 @@ func (m *MeterQuery) buildQuery(d *QueryDefinition) sqlbuilder.Builder { - if len(d.FilterCustomer) > 0 { - var subjects []string - for _, customer := range d.FilterCustomer { - subjects = append(subjects, customer.GetUsageAttribution().SubjectKeys...) - } - query = query.Where(query.Or(slicesx.Map(subjects, mapFunc)...)) - } + if len(d.FilterCustomer) > 0 { + // Collect all subject keys + var subjects []string + for _, c := range d.FilterCustomer { + subjects = append(subjects, c.GetUsageAttribution().SubjectKeys...) + } + // Remove duplicates (using lo.Uniq or slicesx.Unique) + subjects = lo.Uniq(subjects) + + switch len(subjects) { + case 0: + // No subjects → filter matches nothing + query = query.Where("1 = 0") + default: + // Build OR(...) only when there is at least one predicate + query = query.Where(query.Or(slicesx.Map(subjects, mapFunc)...)) + } + }• Add an import for deduplication, e.g.
import "github.com/samber/lo"—or use
slicesx.Unique(subjects)if available.
• This ensures you never callOr()with zero args and keeps your SQL lean.
183-186: Ensurecustomer_idIs Always Selected When Grouping By ItThe current logic in meter_query.go only appends a derived
customer_idcolumn to selectColumns whenFilterCustomeris non-empty. If a caller specifiesGroupBy: []string{"customer_id"}without any filters, the query willGROUP BY customer_idon a column that was never selected.• In openmeter/streaming/clickhouse/meter_query.go around lines 183–186 and 197–218:
Problem:
if groupByKey == "customer_id" { groupByColumns = append(groupByColumns, "customer_id") continue } … if len(d.FilterCustomer) > 0 { // builds CASE … AS customer_id selectColumns = append(selectColumns, caseBuilder.String()) }No
customer_idin selectColumns whenFilterCustomeris empty.Fix Option A: always select the raw
customer_idfor grouping keys, e.g.:if groupByKey == "customer_id" { groupByColumns = append(groupByColumns, "customer_id")
}selectColumns = append(selectColumns, "customer_id") continue- **Fix Option B**: reject or validate upstream whenever `GroupBy` includes `"customer_id"` but `FilterCustomer` is empty.• Add or update unit tests to cover the case of grouping by
"customer_id"without filters.
• Ensure generated SQL always has a matchingcustomer_idin itsSELECTlist when included inGROUP BY.openmeter/ent/db/migrate/schema.go (1)
552-609: Data backfill recommendation for customer_keyAdding the column alone leaves historical invoices with NULL customer_key. If downstream queries rely on it, consider a backfill in the up migration:
UPDATE billing_invoices bi SET customer_key = c.key FROM customers c WHERE bi.namespace = c.namespace AND bi.customer_id = c.id AND bi.customer_key IS NULL;If needed, we can wrap this in a separate migration and run it in batches to avoid long locks.
🧹 Nitpick comments (14)
tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql (1)
1-2: Consider adding an index (and optional backfill) for customer_keyIf you plan to filter/order by customer_key, add an index (e.g., composite on namespace, customer_key) to avoid table scans. If older invoices should expose the key, a follow-up backfill migration may be warranted.
Example index (optional, separate migration recommended):
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_billing_invoices_namespace_customer_key ON billing_invoices(namespace, customer_key) WHERE customer_key IS NOT NULL;openmeter/customer/customer.go (1)
14-19: Interface shape looks good for meter queriesMeterCustomer exposes minimal identity and attribution for metering. Consider clarifying doc comment to indicate GetID returns the string ID (not NamespacedID) to avoid confusion with GetCustomerID().
-// MeterCustomer is a customer that can be used in a meter query +// MeterCustomer provides the minimal identity and attribution required for meter queries. +// Note: GetID returns the raw customer ID string (not NamespacedID). Use GetCustomerID() on concrete types if you need the namespaced form.openmeter/meter/httphandler/mapping.go (1)
145-147: Interface widening is fine; minor nit on allocationReturning customer.Customer as customer.MeterCustomer is correct. Optionally, avoid the lo.Map overhead with a simple preallocated loop.
- params.FilterCustomer = lo.Map(filterCustomer, func(c customer.Customer, _ int) customer.MeterCustomer { - return c - }) + customers := make([]customer.MeterCustomer, len(filterCustomer)) + for i := range filterCustomer { + customers[i] = filterCustomer[i] + } + params.FilterCustomer = customersopenmeter/app/httpdriver/customer.go (2)
141-144: Unify field name to CustomerID (Go convention)There’s an inconsistency between CustomerId (lowercase d) in UpsertCustomerDataRequest and CustomerID used elsewhere (e.g., DeleteCustomerDataRequest.CustomerID). Recommend renaming to CustomerID and updating references for clarity and consistency.
type UpsertCustomerDataRequest struct { - CustomerId customer.CustomerID + CustomerID customer.CustomerID Data []api.CustomerAppData } @@ return httptransport.NewHandlerWithArgs( func(ctx context.Context, r *http.Request, params UpsertCustomerDataParams) (UpsertCustomerDataRequest, error) { @@ - return UpsertCustomerDataRequest{ - CustomerId: cus.GetCustomerID(), - Data: body, - }, nil + return UpsertCustomerDataRequest{ + CustomerID: cus.GetCustomerID(), + Data: body, + }, nil }, func(ctx context.Context, req UpsertCustomerDataRequest) (UpsertCustomerDataResponse, error) { for _, apiCustomerData := range req.Data { - customerApp, customerData, err := h.toCustomerData(ctx, req.CustomerId, apiCustomerData) + customerApp, customerData, err := h.toCustomerData(ctx, req.CustomerID, apiCustomerData) if err != nil { return nil, err } err = customerApp.UpsertCustomerData(ctx, app.UpsertAppInstanceCustomerDataInput{ - CustomerID: req.CustomerId, + CustomerID: req.CustomerID, Data: customerData, }) if err != nil { return nil, err } }Also applies to: 148-156, 102-106
121-123: Nit: fix error message typoChange “field to decode” to “failed to decode”.
- return UpsertCustomerDataRequest{}, fmt.Errorf("field to decode upsert customer data request: %w", err) + return UpsertCustomerDataRequest{}, fmt.Errorf("failed to decode upsert customer data request: %w", err)test/billing/suite.go (1)
399-406: Optional: use GetCustomerID() for consistencyCreateDraftInvoice builds customer.CustomerID manually. You can simplify to use the same accessor as elsewhere.
- invoice, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{ - Customer: customer.CustomerID{ - ID: in.Customer.ID, - Namespace: in.Customer.Namespace, - }, - AsOf: lo.ToPtr(now), - }) + invoice, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{ + Customer: in.Customer.GetCustomerID(), + AsOf: lo.ToPtr(now), + })openmeter/ent/schema/billing.go (1)
978-990: Consider indexing (namespace, customer_key) for lookup performanceIf invoices will be queried/filtered by customer_key, add a non-unique composite index to avoid full scans.
func (BillingInvoice) Indexes() []ent.Index { return []ent.Index{ index.Fields("namespace", "id"), index.Fields("namespace", "customer_id"), + index.Fields("namespace", "customer_key"), index.Fields("namespace", "status"), index.Fields("status_details_cache"). Annotations( entsql.IndexTypes(map[string]string{ dialect.Postgres: "GIN", }), ), } }openmeter/streaming/query_params.go (1)
51-59: Validation: support grouping by customer_key as wellNow that FilterCustomer carries Key via MeterCustomer, allow multiple filters when grouped by customer_key and require a filter when grouping by customer_key.
- // This is required because otherwise the response would be ambiguous - if len(p.FilterCustomer) > 1 && !slices.Contains(p.GroupBy, "customer_id") { - errs = append(errs, errors.New("multiple customer filters are only allowed with customer_id group by")) - } + // This is required because otherwise the response would be ambiguous + if len(p.FilterCustomer) > 1 && !(slices.Contains(p.GroupBy, "customer_id") || slices.Contains(p.GroupBy, "customer_key")) { + errs = append(errs, errors.New("multiple customer filters are only allowed with customer_id or customer_key group by")) + } @@ - // This is required for now because we don't support customer_id without a filter - // To support this we need to map all subjects to customer_ids - if slices.Contains(p.GroupBy, "customer_id") && len(p.FilterCustomer) == 0 { - errs = append(errs, errors.New("customer filter is required with customer_id group by")) - } + // This is required for now because we don't support customer dimension without a filter + // To support this we need to map all subjects to customers + if (slices.Contains(p.GroupBy, "customer_id") || slices.Contains(p.GroupBy, "customer_key")) && len(p.FilterCustomer) == 0 { + errs = append(errs, errors.New("customer filter is required with customer_id/customer_key group by")) + }To validate viability, please confirm that downstream query code recognizes "customer_key" as a grouping dimension. If not yet supported, consider tracking it as a follow-up issue and keep this change scoped to "customer_id" only for now.
openmeter/billing/service/invoicestate.go (1)
716-717: Naming nit: “Snapshoted” fieldsQuantitySnapshotedAt is likely intended to be “Snapshotted” or “SnapshotTakenAt”. Consider renaming for clarity (follow-up, non-blocking).
Also applies to: 740-741
openmeter/billing/service/lineservice/feeline.go (1)
31-33: Signature updated to InvoiceCustomer: OKfeeLine.SnapshotQuantity now accepts billing.InvoiceCustomer. No functional impact here; consistent with interface change.
Consider a brief comment/docstring explaining why fee lines do nothing during quantity snapshotting for future readers.
openmeter/ent/db/billinginvoice.go (1)
843-847: Consider redacting customer_key in String() to avoid leaking identifiersString() often ends up in logs. If customer_key is considered sensitive (or externally meaningful), consider redacting or omitting it from String() output.
- if v := _m.CustomerKey; v != nil { - builder.WriteString("customer_key=") - builder.WriteString(*v) - } + if v := _m.CustomerKey; v != nil { + builder.WriteString("customer_key=<redacted>") + }openmeter/streaming/clickhouse/meter_query.go (1)
197-221: Optional: de-duplicate CASE WHEN clauses for customer_id mappingRepeated WHEN branches for the same subject are redundant. Dedupe to keep the SQL lean.
- for _, customer := range d.FilterCustomer { - for _, subjectKey := range customer.GetUsageAttribution().SubjectKeys { + m := map[string]string{} + for _, customer := range d.FilterCustomer { + for _, subjectKey := range customer.GetUsageAttribution().SubjectKeys { + // last-wins if duplicates; adjust as needed + m[subjectKey] = customer.GetID() + } + } + for subjectKey, id := range m { str := fmt.Sprintf( "WHEN %s = '%s' THEN '%s' ", getColumn("subject"), sqlbuilder.Escape(subjectKey), - sqlbuilder.Escape(customer.GetID()), + sqlbuilder.Escape(id), ) caseBuilder.WriteString(str) } - } +openmeter/billing/service/invoice.go (1)
163-166: Fix misleading error messageThe error message is misleading. The check verifies if
customerProfile.Customeris nil, not the entire customer profile.if customerProfile.Customer == nil { - return invoice, fmt.Errorf("customer profile is nil") + return invoice, fmt.Errorf("customer is nil in customer profile") }test/billing/invoice_test.go (1)
130-130: Optional consistency clean-up: prefer GetCustomerID() everywhereThere are still spots in this file constructing customer.CustomerID inline (e.g., InvoicePendingLinesInput in TestCreateInvoice and others). Not wrong, but for consistency and readability you may prefer to use customerEntity.GetCustomerID() everywhere.
I can generate a focused diff to update the remaining inline constructions if you want.
Also applies to: 164-164, 457-457, 633-633, 1406-1406, 1563-1563, 1580-1580, 1883-1883, 2096-2096, 2327-2327, 2383-2383, 2421-2421, 2460-2460, 2640-2640, 2790-2790, 2802-2802, 2813-2813, 3159-3159, 3518-3518, 3543-3543, 3600-3600, 3643-3643, 3694-3694, 3754-3754, 3804-3804, 3860-3860, 3933-3933, 3965-3965, 3996-3996, 4044-4044, 4062-4062, 4081-4081
📜 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 (50)
openmeter/app/httpdriver/customer.go(3 hunks)openmeter/app/stripe/adapter/stripe.go(1 hunks)openmeter/app/stripe/entity/app/customer.go(1 hunks)openmeter/app/stripe/httpdriver/checkout_session.go(1 hunks)openmeter/app/stripe/httpdriver/customer.go(3 hunks)openmeter/billing/adapter/invoice.go(2 hunks)openmeter/billing/httpdriver/invoice_test.go(1 hunks)openmeter/billing/invoice.go(1 hunks)openmeter/billing/service/invoice.go(2 hunks)openmeter/billing/service/invoiceline.go(4 hunks)openmeter/billing/service/invoicestate.go(1 hunks)openmeter/billing/service/lineservice/feeline.go(1 hunks)openmeter/billing/service/lineservice/meters.go(4 hunks)openmeter/billing/service/lineservice/service.go(1 hunks)openmeter/billing/service/lineservice/usagebasedline.go(2 hunks)openmeter/billing/service/lineservice/usagebasedlineflat.go(1 hunks)openmeter/billing/worker/subscription/sync_test.go(12 hunks)openmeter/customer/customer.go(2 hunks)openmeter/customer/httpdriver/customer.go(3 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(1 hunks)openmeter/meter/httphandler/mapping.go(1 hunks)openmeter/productcatalog/subscription/http/get.go(1 hunks)openmeter/streaming/clickhouse/meter_query.go(3 hunks)openmeter/streaming/clickhouse/meter_query_test.go(3 hunks)openmeter/streaming/query_params.go(1 hunks)openmeter/subscription/service/service.go(1 hunks)openmeter/subscription/service/service_test.go(2 hunks)test/app/custominvoicing/invocing_test.go(4 hunks)test/app/stripe/appstripe.go(16 hunks)test/app/stripe/fixture.go(1 hunks)test/app/stripe/invoice_test.go(6 hunks)test/billing/collection_test.go(8 hunks)test/billing/customeroverride_test.go(1 hunks)test/billing/discount_test.go(6 hunks)test/billing/invoice_test.go(38 hunks)test/billing/subscription_test.go(3 hunks)test/billing/suite.go(1 hunks)test/billing/tax_test.go(4 hunks)test/billing/ubpflatfee_test.go(7 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.down.sql(1 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql(1 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:
test/billing/ubpflatfee_test.gotest/billing/invoice_test.go
🧬 Code Graph Analysis (41)
openmeter/app/httpdriver/customer.go (5)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)api/client/javascript/src/client/schemas.ts (1)
CustomerId(10830-10830)api/api.gen.go (1)
CustomerId(2279-2282)api/client/go/client.gen.go (1)
CustomerId(2109-2112)
openmeter/billing/service/lineservice/usagebasedline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/customer/httpdriver/customer.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/customersubjects/where.go (1)
CustomerID(64-66)
openmeter/customer/customer.go (5)
openmeter/billing/invoice.go (1)
CustomerUsageAttribution(565-565)api/client/javascript/src/client/schemas.ts (2)
CustomerUsageAttribution(10837-10838)Customer(10821-10821)api/api.gen.go (2)
CustomerUsageAttribution(2341-2344)Customer(2156-2206)api/client/go/client.gen.go (2)
CustomerUsageAttribution(2171-2174)Customer(1986-2036)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)
openmeter/ent/db/billinginvoice_create.go (2)
openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/productcatalog/subscription/http/get.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
test/billing/suite.go (1)
api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/streaming/query_params.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
test/app/stripe/fixture.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
test/billing/tax_test.go (2)
api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/billing/service/lineservice/feeline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/ent/db/setorclear.go (1)
openmeter/ent/db/billinginvoice_update.go (2)
BillingInvoiceUpdate(25-29)BillingInvoiceUpdateOne(1424-1429)
test/billing/ubpflatfee_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/subscription/service/service.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
openmeter/billing/service/invoicestate.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/app/custominvoicing/invocing_test.go (4)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/runtime.go (1)
openmeter/ent/db/billinginvoice/billinginvoice.go (4)
CustomerNameValidator(291-291)CustomerIDValidator(293-293)SourceBillingProfileIDValidator(295-295)CurrencyValidator(297-297)
openmeter/billing/service/lineservice/service.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/ent/db/mutation.go (5)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/api.gen.go (1)
CustomerKey(2285-2287)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/ent/db/billinginvoice.go (6)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/api.gen.go (1)
CustomerKey(2285-2287)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/httpdriver/invoice_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/meter/httphandler/mapping.go (3)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/billing/subscription_test.go (1)
openmeter/billing/customeroverride.go (2)
CustomerOverride(19-33)GetCustomerOverrideInput(167-170)
openmeter/streaming/clickhouse/meter_query_test.go (1)
openmeter/customer/customer.go (2)
MeterCustomer(15-19)Customer(24-34)
openmeter/streaming/clickhouse/meter_query.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
test/billing/discount_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/billing/customeroverride_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/billingcustomeroverride/where.go (1)
CustomerID(91-93)
test/billing/collection_test.go (4)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/billinginvoice/where.go (3)
openmeter/ent/schema/billing.go (5)
BillingInvoice(818-820)BillingInvoice(822-837)BillingInvoice(839-976)BillingInvoice(978-990)BillingInvoice(992-1034)openmeter/ent/db/predicate/predicate.go (1)
BillingInvoice(65-65)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/adapter/invoice.go (6)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerKey(127-130)api/client/go/client.gen.go (2)
Customer(1986-2036)CustomerKey(2115-2117)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/ent/schema/customer.go (5)
Customer(17-19)Customer(21-29)Customer(31-39)Customer(41-54)Customer(56-68)openmeter/ent/db/customer/where.go (1)
Key(137-139)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)
test/app/stripe/invoice_test.go (2)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
openmeter/subscription/service/service_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
openmeter/billing/worker/subscription/sync_test.go (4)
api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/api.gen.go (1)
Customer(2156-2206)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/billing/service/invoice.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/billing/invoice.go (1)
NewInvoiceCustomer(577-585)
openmeter/billing/invoice.go (3)
openmeter/customer/customer.go (3)
MeterCustomer(15-19)Customer(24-34)CustomerUsageAttribution(163-165)api/client/go/client.gen.go (3)
Customer(1986-2036)Address(891-912)CustomerUsageAttribution(2171-2174)pkg/models/model.go (1)
Address(192-200)
openmeter/billing/service/invoiceline.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/go/client.gen.go (1)
Customer(1986-2036)openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/ent/db/migrate/schema.go (2)
openmeter/ent/db/billinginvoice/billinginvoice.go (1)
Columns(206-263)openmeter/ent/db/customer/customer.go (1)
Columns(103-123)
test/app/stripe/appstripe.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/app/app.go (1)
GetAppInstanceCustomerDataInput(37-39)
openmeter/billing/service/lineservice/meters.go (2)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/ent/db/billinginvoice/billinginvoice.go (9)
openmeter/ent/db/customer/customer.go (1)
OrderOption(153-153)openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)
OrderOption(300-300)openmeter/ent/db/app/app.go (1)
OrderOption(140-140)openmeter/ent/db/billinginvoiceusagebasedlineconfig/billinginvoiceusagebasedlineconfig.go (1)
OrderOption(80-80)openmeter/ent/db/billinginvoiceflatfeelineconfig/billinginvoiceflatfeelineconfig.go (1)
OrderOption(84-84)openmeter/ent/db/billingworkflowconfig/billingworkflowconfig.go (1)
OrderOption(136-136)openmeter/ent/db/billingprofile/billingprofile.go (1)
OrderOption(175-175)openmeter/ent/db/billingcustomeroverride/billingcustomeroverride.go (1)
OrderOption(132-132)openmeter/ent/db/billinginvoicevalidationissue/billinginvoicevalidationissue.go (1)
OrderOption(110-110)
⏰ 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). (9)
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Quickstart
- GitHub Check: Lint
- GitHub Check: Commit hooks
- GitHub Check: Developer environment
- GitHub Check: Build
- GitHub Check: Test
- GitHub Check: Analyze (go)
🔇 Additional comments (78)
openmeter/productcatalog/subscription/http/get.go (1)
102-102: GetCustomerID change verified; no leftover GetID usagesThe grep search for
cus.GetID()inopenmeter/productcatalog/subscription/httpreturned no results, confirming there are no remaining call sites using the old method. The switch tocus.GetCustomerID()is correct and types align with downstreamListinput.No further action required.
tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.down.sql (1)
1-2: Down migration looks correctDropping a nullable column added by the up migration is safe. No dependent constraints or indexes referenced here.
test/app/custominvoicing/invocing_test.go (1)
167-167: Tests correctly migrate to typed CustomerID via GetCustomerID()All updated call sites now pass customer.CustomerID, matching input types. Looks good.
Also applies to: 224-224, 335-335, 362-362
openmeter/ent/db/billinginvoice/billinginvoice.go (3)
75-76: New FieldCustomerKey constant matches schemaName and casing align with the migration (customer_key). Good addition.
236-236: Columns updated to include customer_keyColumn list updated; ValidColumn and selectors will reflect it. All good.
467-471: Approve addition of ByCustomerKey helperThe
ByCustomerKeyfunction now mirrors other order helpers, and the corresponding predicateCustomerKey(v string) predicate.BillingInvoicealready exists inopenmeter/ent/db/billinginvoice/where.go:210. No further changes needed.openmeter/customer/customer.go (2)
54-62: GetCustomerID convenience is clear and correctConstructs a valid CustomerID from ManagedResource fields. LGTM.
36-41: No breaking change: GetID still returns a string
TheGetID()method’s signature and return type haven’t changed—it continues to returnstring. The newGetCustomerID()method was added to return aCustomerIDstruct without replacing the original. All existing.GetID()callers thus remain correct and require no updates.Likely an incorrect or invalid review comment.
openmeter/billing/worker/subscription/sync_test.go (1)
502-502: Consistent migration in tests to CustomerID via GetCustomerID()All updated inputs now pass customer.CustomerID as required. Remaining string-ID usages are in list/get helpers that accept strings, which is consistent.
Also applies to: 520-520, 548-548, 1266-1266, 1435-1435, 2609-2609, 2818-2818, 2974-2974, 3011-3011, 3301-3301, 3471-3471, 3757-3757
openmeter/app/stripe/entity/app/customer.go (1)
21-21: Switch to GetCustomerID aligns with ValidateCustomerByID signaturePassing a typed CustomerID is correct and consistent with downstream usage.
openmeter/subscription/service/service.go (1)
482-482: CustomerID refactor validatedThe change is safe:
UpdateCustomerInput.CustomerIDis defined ascustomer.CustomerID, andcust.GetCustomerID()returns the same type. No further action needed.test/billing/ubpflatfee_test.go (1)
59-59: Tests updated to typed CustomerID — LGTMSwitching to cust.GetCustomerID() matches the new API. No behavioral changes; inputs remain correct.
Also applies to: 89-89, 103-103, 159-159, 185-185, 239-239, 265-265
test/billing/tax_test.go (1)
204-204: Consistent CustomerID usage in tests — LGTMAlignment with GetCustomerID() is correct; no functional change.
Also applies to: 247-247, 274-274, 300-300
test/app/stripe/fixture.go (1)
125-125: Fixture aligned to GetCustomerID — LGTMTyped CustomerID is the right value to pass here.
openmeter/app/httpdriver/customer.go (2)
55-56: Accessor rename aligned with new APISwitching to cus.GetCustomerID() is correct and consistent with the refactor.
208-213: Accessor rename aligned with new APIUsing cus.GetCustomerID() here is correct and consistent.
test/billing/suite.go (1)
334-339: LGTM: pass Customer via GetCustomerID()This matches the new accessor and expected input type.
openmeter/billing/httpdriver/invoice_test.go (1)
54-58: LGTM: consistent use of GetCustomerID()Accessor rename applied correctly in test setup.
openmeter/ent/schema/billing.go (1)
849-852: Add snapshot field: consider immutability policycustomer_key is added as optional/nillable. If this field is intended as a snapshot at invoice creation (similar to customer_id), consider making it Immutable() to prevent later mutation; if edits are allowed as part of correction flows, keeping it mutable is fine. Please confirm intended lifecycle.
openmeter/subscription/service/service_test.go (1)
100-105: LGTM: UpdateCustomerInput now uses GetCustomerID()Accessor updates are correct and consistent with refactor.
Also applies to: 145-149
openmeter/streaming/query_params.go (1)
17-17: Ignore:FilterCustomertype change does not introduce a breaking API changeAll internal call sites and the public HTTP API remain unaffected:
- openmeter/meter/httphandler/mapping.go converts the incoming
[]stringfilterCustomerIdinto[]customer.MeterCustomer.- All existing code in streaming/clickhouse, billing/service, and tests have been updated to pass
[]customer.MeterCustomer.- The generated HTTP client and server models (api/api.gen.go, client.gen.go, JavaScript schemas) continue to use
FilterCustomerId []string.No action required.
Likely an incorrect or invalid review comment.
test/billing/collection_test.go (1)
79-81: LGTM: consistent use of GetCustomerID() in collection flow testsAll updated call sites correctly use the new accessor.
Also applies to: 170-171, 281-284, 292-294, 334-337, 358-361, 435-438, 459-462
openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
96-103: LGTM: signature updated to accept InvoiceCustomerMatches new Line interface; parameter names omitted appropriately since they are unused in this implementation.
test/billing/discount_test.go (1)
88-88: Switched to GetCustomerID: consistent with new APIAll updated call sites correctly use customerEntity.GetCustomerID() matching the refactor. No issues.
Also applies to: 137-137, 283-283, 329-329, 370-370, 414-414
openmeter/billing/service/invoicestate.go (1)
735-735: Pass full InvoiceCustomer to snapshot: change looks correctPassing m.Invoice.Customer into snapshotLineQuantitiesInParallel aligns with the new signature and usage-based snapshotting by customer. LGTM.
test/billing/customeroverride_test.go (1)
467-469: GetCustomerID usage in GetCustomerApp input is correctThe test now passes cust.GetCustomerID(), aligned with the new accessor. Looks good.
test/billing/subscription_test.go (1)
273-274: GetCustomerID migration: correct and consistentAll four updated calls to GetCustomerID() match the new input type. No issues.
Also applies to: 282-283, 290-291, 299-300
test/app/stripe/invoice_test.go (1)
294-295: Tests updated to GetCustomerID: OKAll updated invocations (CreatePendingInvoiceLines, InvoicePendingLines, and Stripe CreateInvoiceInput) correctly use GetCustomerID(). Assertions remain coherent.
Also applies to: 470-472, 489-494, 1141-1143, 1151-1157
openmeter/streaming/clickhouse/meter_query_test.go (1)
267-291: FilterCustomer typed to []MeterCustomer: compatible and clearSwitching to []customer.MeterCustomer while instantiating concrete customer.Customer values is appropriate and exercises the interface. Expected SQL assertions still align.
Also applies to: 307-323
openmeter/billing/service/lineservice/service.go (1)
217-221: Breaking Change Verified: SnapshotQuantity signature updated across all implementationsI ran searches across the codebase and confirmed:
- openmeter/billing/service/lineservice/service.go – interface signature now takes billing.InvoiceCustomer
- openmeter/billing/service/lineservice/usagebasedline.go – implementation updated accordingly
- No remaining definitions expecting []string and no call sites passing SubjectKeys
Everything is aligned—no further changes needed.
openmeter/customer/httpdriver/customer.go (1)
209-211: Types Verified: No Action NeededAll usages of
GetCustomerID()align with the newCustomerIDtype (an alias ofmodels.NamespacedID), andDeleteCustomerInputis defined asCustomerID. No further changes are required.openmeter/ent/db/runtime.go (1)
469-486: BillingInvoice descriptor indices and migrations are in sync
- The new
customer_keyfield is defined inent/schema/billing.goand present in all generated code underopenmeter/ent/db/.- Migration scripts
20250811130613_add_billing_invoice_customer_key.up.sqland its down counterpart correctly add/drop the column.- The descriptor offsets in
openmeter/ent/db/runtime.gomatch the updated field ordering.No further changes required.
openmeter/ent/db/setorclear.go (1)
772-784: SetOrClearCustomerKey helpers mirror established patternMatches existing SetOrClear* methods. This keeps the update API consistent and ergonomic.
openmeter/ent/db/billinginvoice.go (3)
85-86: Add CustomerKey to BillingInvoice entityField addition looks correct and JSON tags align with existing naming.
261-262: Include FieldCustomerKey in scanValuesCorrectly scanned as sql.NullString alongside similar optional string fields.
472-478: assignValues case for customer_keyType checking and assignment follow the expected pattern for nullable strings.
openmeter/streaming/clickhouse/meter_query.go (2)
26-27: queryMeter.FilterCustomer now []customer.MeterCustomerGood abstraction. Decouples query from concrete customer struct and aligns with MeterCustomer interface.
203-214: Use of getters (GetUsageAttribution/GetID) is correct with MeterCustomerMapping CASE statements with escaped values is consistent with prior approach.
Also applies to: 211-211
test/app/stripe/appstripe.go (1)
201-202: Tests: adopt GetCustomerID consistentlyUpdates look correct; typed CustomerID flows through all test inputs and assertions.
Also applies to: 216-216, 244-245, 256-256, 276-277, 333-334, 344-345, 355-356, 367-367, 375-375, 389-390, 403-404, 643-643, 671-674, 736-737, 760-760
openmeter/billing/service/lineservice/usagebasedline.go (1)
151-175: SnapshotQuantity(customer) propagation is correctSwitching from []subjectKeys to billing.InvoiceCustomer and forwarding it to getFeatureUsage is consistent with the PR intent.
Also applies to: 157-164
openmeter/billing/service/invoice.go (2)
167-169: LGTM! Proper use of InvoiceCustomer constructorThe change correctly uses the
NewInvoiceCustomerconstructor to create a customer snapshot for quantity calculation, aligning with the new customer-centric architecture.
1087-1087: LGTM! Consistent use of constructor patternGood use of the
NewInvoiceCustomerconstructor to ensure all fields are properly initialized, maintaining consistency with the rest of the codebase.openmeter/billing/service/lineservice/meters.go (1)
11-11: LGTM! Clean migration to customer-based filteringAll changes correctly implement the transition from subject-based to customer-based filtering:
- Proper import of the customer package
- Correct field type change to
billing.InvoiceCustomer- Appropriate validation update
- Proper use of
FilterCustomerwith theMeterCustomerinterfaceAlso applies to: 21-21, 38-40, 59-61
openmeter/ent/db/billinginvoice_update.go (1)
487-505: LGTM! Generated code follows established patternsThe generated methods for the
CustomerKeyfield correctly follow the ent framework's patterns for nullable string fields, providing appropriate setter, nullable setter, and clear methods.Also applies to: 1187-1192, 1881-1899, 2611-2616
openmeter/billing/invoice.go (1)
572-631: LGTM! Well-implemented InvoiceCustomer with proper interface complianceExcellent implementation of the
InvoiceCustomertype:
- Compile-time interface assertion ensures type safety
- Constructor properly snapshots customer data
- Clear documentation explains the purpose
- Interface methods correctly implement
MeterCustomer- Validation logic properly handles required fields and empty key validation
openmeter/billing/service/invoiceline.go (1)
309-311: LGTM! Consistent migration to customer-based quantity snapshottingAll changes correctly implement the transition from subject-based to customer-based quantity snapshotting:
- Function signatures properly updated to use
billing.InvoiceCustomer- All call sites correctly pass the customer object
- Maintains consistency with the broader architectural change
Also applies to: 319-319, 345-347, 394-396
openmeter/ent/db/mutation.go (9)
11369-11375: Add customer_key field to mutation struct: LGTMThe nullable pointer field matches the new column and aligns with other optional string fields.
14247-14247: Fields() capacity bump matches new fieldCapacity increased to 55. This aligns with adding customer_key. No issues.
14332-14334: Include customer_key when set: LGTMConditionally appending FieldCustomerKey mirrors patterns used for other optional fields.
14477-14479: Field(name) supports customer_key: LGTMDelegating to CustomerKey() matches existing field handlers.
14596-14598: OldField(name) supports customer_key: LGTMDelegating to OldCustomerKey(ctx) is correct and consistent with other fields.
14855-14861: SetField(name,value) integration: LGTMType assertion to string and delegating to SetCustomerKey is correct. Once the setter removes the cleared flag (see prior comment), this path will be fully consistent.
15125-15127: ClearedFields includes customer_key: LGTMProperly surfaces cleared state for this nullable field.
15235-15237: ClearField handles customer_key: LGTMDelegates to ClearCustomerKey(), consistent with other fields.
15372-15374: ResetField handles customer_key: LGTMDelegates to ResetCustomerKey(), matches established pattern.
test/billing/invoice_test.go (17)
130-130: Typed customer ID usage (GetCustomerID) — LGTMSwitching CreatePendingInvoiceLinesInput.Customer to customerEntity.GetCustomerID() is correct and strengthens type-safety at call sites.
Also applies to: 164-164
299-299: Validating InvoiceCustomer.Key in expectations — LGTMAsserting Key propagation in the expected invoice is a good addition aligned with the new snapshot semantics.
457-457: Typed customer ID usage in TestCreateInvoice — LGTMUsing GetCustomerID() here is consistent with the updated API. Looks good.
633-633: Typed customer ID usage when staging more lines — LGTMConsistent application of the new accessor. No issues found.
1406-1406: UBP progressive invoicing: typed customer ID — LGTMAll updated invocations correctly pass MeterCustomer/CustomerID via GetCustomerID().
Also applies to: 1563-1563, 1580-1580
1883-1883: Mid-period invoice (pt2): typed customer ID — LGTMConsistent and correct.
2096-2096: End-of-period invoice: typed customer ID — LGTMNo issues.
2327-2327: Graduating flat fee tier tests: typed customer ID — LGTMChanges align with the new API contract.
Also applies to: 2383-2383, 2421-2421, 2460-2460
2640-2640: Non-progressive invoicing: typed customer ID — LGTMAll updated fields are correct and consistent.
Also applies to: 2790-2790, 2802-2802, 2813-2813
3159-3159: Gathering invoice recalculation: typed customer ID — LGTMGood usage.
3518-3518: Namespace-locked tests: typed customer ID — LGTMThe changes align with the locking tests and new input requirements.
Also applies to: 3543-3543
3600-3600: Progressive billing late: typed customer ID — LGTMConsistent application in both create and invoice-now calls.
Also applies to: 3643-3643
3694-3694: Progressive billing override: typed customer ID — LGTMCorrect and consistent with override usage.
Also applies to: 3754-3754
3804-3804: Sorting lines test: typed customer ID — LGTMUpdates look good.
Also applies to: 3860-3860
3933-3933: Gathering invoice period persisting: typed customer ID — LGTMNo issues with typed ID changes across create/invoice-now/retry contexts.
Also applies to: 3965-3965, 3996-3996
4032-4032: DeleteCustomer uses typed ID — LGTMThe DeleteCustomer call now using GetCustomerID() matches the updated service interface and reduces mistakes. Good change.
4044-4044: Deleted-customer scenarios: typed customer ID — LGTMAll the affected calls now pass typed IDs correctly. The test semantics remain intact.
Also applies to: 4062-4062, 4081-4081
openmeter/ent/db/billinginvoice_create.go (2)
348-360: Add customer_key across create and upsert — LGTM
- SetCustomerKey and SetNillableCustomerKey mirror patterns used by other optional fields.
- createSpec correctly writes FieldCustomerKey and sets _node.CustomerKey when provided.
- UpsertOne and UpsertBulk include Set/Update/Clear helpers.
No correctness issues spotted; generated code remains consistent with ent conventions.
Also applies to: 1056-1059, 1740-1756, 2637-2656, 3758-3777
2094-2123: Review Upsert UpdateNewValues: Shouldcustomer_keybe immutable on conflict?The generated
UpdateNewValueshandlers for both single and bulk upserts currently ignore only these fields on conflict:
- ID
- Namespace
- CreatedAt
- CustomerID
- SourceBillingProfileID
- Currency
- TaxAppID
- InvoicingAppID
- PaymentAppID
They do not ignore
customer_key, so an upsert will overwrite it with the new create value on conflict. If your domain expectscustomer_keyto remain constant once inserted—similar tocustomer_idorcurrency—you should add it to the ignore list:• BillingInvoiceUpsertOne.UpdateNewValues (openmeter/ent/db/billinginvoice_create.go ≈ lines 2094–2123)
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { … if _, exists := u.create.mutation.PaymentAppID(); exists { s.SetIgnore(billinginvoice.FieldPaymentAppID) } + if _, exists := u.create.mutation.CustomerKey(); exists { + s.SetIgnore(billinginvoice.FieldCustomerKey) + } }))• BillingInvoiceUpsertBulk.UpdateNewValues (openmeter/ent/db/billinginvoice_create.go ≈ lines 3213–3244)
for _, b := range u.create.builders { … if _, exists := b.mutation.PaymentAppID(); exists { s.SetIgnore(billinginvoice.FieldPaymentAppID) } + if _, exists := b.mutation.CustomerKey(); exists { + s.SetIgnore(billinginvoice.FieldCustomerKey) + } }Please confirm whether
customer_keyshould be treated as immutable on conflict (and, if so, I can supply a patch).openmeter/ent/db/billinginvoice/where.go (2)
209-213: Alias predicate CustomerKey mirrors pattern and looks correctMatches how other alias helpers are defined (e.g., SupplierTaxCode). No issues.
2038-2112: Complete predicate helper set for customer_key added correctlyThe EQ/NEQ/In/NotIn/GT/GTE/LT/LTE/Contains/HasPrefix/HasSuffix/IsNil/NotNil/EqualFold/ContainsFold set mirrors other string fields. Assuming customer_key is Optional() + Nillable() in ent schema (as described), this is consistent.
To be safe, please confirm the ent schema marks customer_key as Optional() and Nillable(), and that FieldCustomerKey is defined in openmeter/ent/db/billinginvoice/billinginvoice.go. If you want, I can generate a quick script to grep for these.
openmeter/ent/db/migrate/schema.go (2)
618-649: Foreign key column offsets updated — mapping looks correctAfter inserting customer_key at index 29, later columns shifted by +1. These FKs now reference:
- [50] tax_app_id
- [51] invoicing_app_id
- [52] payment_app_id
- [53] source_billing_profile_id
- [54] workflow_config_id
- [55] customer_id
This aligns with the updated BillingInvoicesColumns order. LGTM.
If you want an automated sanity check, I can provide a script to print the BillingInvoicesColumns order from billinginvoice.go and ensure these names correspond to the referenced indices at runtime.
670-673: Index billinginvoice_namespace_customer_id offset adjusted — OKIndex now uses [1] namespace and [55] customer_id, matching the new positions.
There was a problem hiding this comment.
Actionable comments posted: 3
🔭 Outside diff range comments (5)
openmeter/billing/service/invoicestate.go (1)
725-729: Potential nil dereference on CollectionAtThis dereferences m.Invoice.CollectionAt without a nil guard. While CollectionAt likely has a default at creation, defensive code prevents panics for legacy/edge cases.
Consider:
- // We don't have the snapshot and the collection date is in the future - if m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) { + // We don't have the snapshot and the collection date is in the future + collAt := lo.FromPtrOr(m.Invoice.CollectionAt, m.Invoice.CreatedAt) + if m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(collAt) { return nil }test/billing/suite.go (1)
259-266: Bug: sorted lines are not used in the output loopYou sort l but then iterate over i.Lines.OrEmpty(), losing the ordering.
- for _, line := range i.Lines.OrEmpty() { + for _, line := range l {Also applies to: 268-300
openmeter/billing/adapter/invoice.go (1)
341-356: Snapshot CustomerKey on invoice creationThe Ent builder already exposes
SetNillableCustomerKey(*string)(andSetCustomerKey(string)) onBillingInvoiceCreate. To ensure invoices capture the customer’s key at creation time, add this to the mutation chain before callingSave:• File:
openmeter/billing/adapter/invoice.go
Location: inside theif customer.BillingAddress != nil { … }block or right after setting the customer name, beforecreateMut.Save(ctx)Suggested diff:
if customer.BillingAddress != nil { createMut = createMut. // Customer contacts SetNillableCustomerAddressCountry(customer.BillingAddress.Country). SetNillableCustomerAddressPostalCode(customer.BillingAddress.PostalCode). SetNillableCustomerAddressState(customer.BillingAddress.State). SetNillableCustomerAddressCity(customer.BillingAddress.City). SetNillableCustomerAddressLine1(customer.BillingAddress.Line1). SetNillableCustomerAddressLine2(customer.BillingAddress.Line2). SetNillableCustomerAddressPhoneNumber(customer.BillingAddress.PhoneNumber) } createMut = createMut. SetCustomerName(customer.Name). + // Snapshot customer key at creation + SetNillableCustomerKey(customer.Key) newInvoice, err := createMut.Save(ctx)If you prefer to guard against a nil pointer explicitly:
if customer.Key != nil { createMut = createMut.SetCustomerKey(*customer.Key) }test/app/stripe/appstripe.go (1)
158-161: Incorrect require.Nil usage (asserting nil on the wrong value)You’re passing nil as the asserted value. The intended assertion is on updateApp.GetAppBase().Description.
Apply:
- require.Nil(t, nil, updateApp.GetAppBase().Description, "Description must be updated") + require.Nil(t, updateApp.GetAppBase().Description, "Description must be nil")openmeter/billing/service/invoiceline.go (1)
13-13: Remove unused import "customer" to fix compilation.The file no longer references the customer package after switching SnapshotQuantity to InvoiceCustomer. This import will cause a compile error.
Apply this diff:
import ( "context" "errors" "fmt" "github.com/samber/lo" "github.com/openmeterio/openmeter/api" "github.com/openmeterio/openmeter/openmeter/billing" "github.com/openmeterio/openmeter/openmeter/billing/service/lineservice" - "github.com/openmeterio/openmeter/openmeter/customer" "github.com/openmeterio/openmeter/pkg/currencyx" "github.com/openmeterio/openmeter/pkg/framework/transaction" "github.com/openmeterio/openmeter/pkg/pagination" "github.com/openmeterio/openmeter/pkg/slicesx" "github.com/openmeterio/openmeter/pkg/sortx" )
🧹 Nitpick comments (18)
openmeter/ent/schema/billing.go (1)
849-852: Consider indexing customer_key for query performanceIf invoices will be queried by customer_key, add a composite index to avoid full scans.
Apply this diff to add an index (skipping NULLs) alongside existing BillingInvoice indexes:
func (BillingInvoice) Indexes() []ent.Index { return []ent.Index{ index.Fields("namespace", "id"), index.Fields("namespace", "customer_id"), + index.Fields("namespace", "customer_key"). + Annotations( + entsql.IndexWhere("customer_key IS NOT NULL AND deleted_at IS NULL"), + ), index.Fields("namespace", "status"), index.Fields("status_details_cache"). Annotations( entsql.IndexTypes(map[string]string{ dialect.Postgres: "GIN", }), ), } }openmeter/app/stripe/entity/app/customer.go (1)
20-22: Add a defensive nil check before dereferencing customerSwitch to GetCustomerID() is correct. To avoid a potential nil deref, guard against a nil customer pointer.
func (a App) ValidateCustomer(ctx context.Context, customer *customer.Customer, capabilities []app.CapabilityType) error { - return a.ValidateCustomerByID(ctx, customer.GetCustomerID(), capabilities) + if customer == nil { + return fmt.Errorf("customer is nil") + } + return a.ValidateCustomerByID(ctx, customer.GetCustomerID(), capabilities) }test/billing/suite.go (1)
401-406: Optional: use GetCustomerID() here for consistencyYou can simplify and keep consistency with the earlier change by using GetCustomerID() instead of manually constructing customer.CustomerID.
- invoice, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{ - Customer: customer.CustomerID{ - ID: in.Customer.ID, - Namespace: in.Customer.Namespace, - }, - AsOf: lo.ToPtr(now), - }) + invoice, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{ + Customer: in.Customer.GetCustomerID(), + AsOf: lo.ToPtr(now), + })openmeter/streaming/query_params.go (1)
17-17: Type change LGTM; consider dedup + ambiguity guardrailsSwitching to []customer.MeterCustomer is correct and matches the new interface.
Also consider:
- Deduping FilterCustomer by GetID() to avoid ambiguous duplicates.
- If both FilterSubject and FilterCustomer are set with multiples, require both group by "subject" and "customer_id" to avoid ambiguous aggregates.
Also applies to: 51-59
openmeter/app/httpdriver/customer.go (1)
141-144: LGTM: Upsert handler uses GetCustomerID()CustomerId field is correctly set from cus.GetCustomerID().
Consider renaming the struct field CustomerId to CustomerID for Go naming consistency (if not constrained by external interfaces).
test/app/custominvoicing/invocing_test.go (1)
362-364: LGTM: invoice pending lines use GetCustomerID() (payment-status-only)Test remains coherent after accessor change.
Minor: the filename is invocing_test.go; consider renaming to invoicing_test.go for clarity.
test/billing/tax_test.go (1)
204-205: Switch to GetCustomerID() in tests looks correctThe CreatePendingInvoiceLinesInput and InvoicePendingLinesInput now expect a CustomerID. Using the customer instance’s GetCustomerID() is correct, including in generateDraftInvoice. Variable name “customer” shadows the import in-scope but is type-safe here.
If helpful for readability, consider renaming the local variable to cust to avoid shadowing the package name.
Also applies to: 247-248, 274-275, 299-300
openmeter/app/stripe/httpdriver/checkout_session.go (1)
93-94: Use of GetCustomerID() is correct hereConverting the value to a pointer via lo.ToPtr(cus.GetCustomerID()) matches the request type and is safe. LGTM.
If you want to avoid a generic helper, a purely stdlib option is:
cid := cus.GetCustomerID(); customerId = &cidopenmeter/billing/service/invoice.go (1)
163-168: Nil guard + switch to InvoiceCustomer for snapshotGood move to ensure customer is present and pass a richer customer shape into snapshotting. Consider returning a more descriptive error to aid debugging.
- return invoice, fmt.Errorf("customer profile is nil") + return invoice, fmt.Errorf("customer missing on customer override for invoice [%s]", invoice.ID)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
467-471: Add ByCustomerKey ordering helper — OKMatches existing ordering helpers. Consider adding a DB index on customer_key to support sort/filter performance at scale.
openmeter/streaming/clickhouse/meter_query.go (2)
205-211: CASE mapping for customer_id — consider dedup/ambiguity guard
- If multiple customers include the same subject key, the mapping is order-dependent. Consider guarding against ambiguous overlaps or deduplicating by last-write-wins with a set.
- For large inputs, the CASE can grow big; dedup subject keys to reduce SQL size.
Apply minimal dedup before building CASE:
- for _, customer := range d.FilterCustomer { - for _, subjectKey := range customer.GetUsageAttribution().SubjectKeys { + seen := map[string]struct{}{} + for _, customer := range d.FilterCustomer { + for _, subjectKey := range customer.GetUsageAttribution().SubjectKeys { + if _, ok := seen[subjectKey]; ok { + continue + } + seen[subjectKey] = struct{}{} str := fmt.Sprintf( "WHEN %s = '%s' THEN '%s' ", getColumn("subject"), sqlbuilder.Escape(subjectKey), sqlbuilder.Escape(customer.GetID()), ) caseBuilder.WriteString(str) } }If overlaps are possible, decide on a deterministic rule (e.g., error out or pick the first).
311-312: Subject filter from customers — consider dedup to minimize OR listDeduplicate subjects collected from customers to keep the WHERE OR list compact.
- var subjects []string - for _, customer := range d.FilterCustomer { - subjects = append(subjects, customer.GetUsageAttribution().SubjectKeys...) - } + subjSet := map[string]struct{}{} + for _, customer := range d.FilterCustomer { + for _, s := range customer.GetUsageAttribution().SubjectKeys { + subjSet[s] = struct{}{} + } + } + subjects := make([]string, 0, len(subjSet)) + for s := range subjSet { + subjects = append(subjects, s) + }openmeter/billing/service/invoiceline.go (1)
319-368: Parallel snapshot API refactor aligns with new Line.SnapshotQuantity signature.The worker pool logic remains the same; only the parameter type changed. Consider adopting errgroup with context cancellation in a follow-up to short-circuit on first error, but not blocking for this PR.
openmeter/ent/db/migrate/schema.go (1)
582-583: Customer key column addition looks correct; consider indexing for query performanceAdding nullable customer_key is correct for backfill and aligns with snapshot semantics.
- Suggest adding a partial index on (namespace, customer_key) to speed up lookups by customer key, with a WHERE customer_key IS NOT NULL predicate to avoid bloating index on legacy rows.
Do not modify generated code. Add the index in the ent schema (openmeter/ent/schema/billing.go), then re-generate.
Example (ent schema):
import "entgo.io/ent/dialect/entsql" import "entgo.io/ent/schema/index" func (BillingInvoice) Indexes() []ent.Index { return []ent.Index{ index.Fields("namespace", "customer_key"). StorageKey("billinginvoice_namespace_customer_key"). Annotations(entsql.IndexWhere("customer_key IS NOT NULL")), } }openmeter/ent/db/billinginvoice_update.go (1)
487-506: Consider enforcing snapshot consistency between customer_id and customer_key at write-timeTo prevent drift (e.g., clearing customer_key while customer_id is set), consider:
- A domain-layer invariant (preferred): when setting/changing the Customer edge, set the snapshot key too; disallow clearing key if customer_id is present.
- Alternatively, add an ent hook (BeforeSave/Mutate) to backfill/validate customer_key based on the linked customer.
This avoids inconsistent invoices during partial updates.
If you already added such logic, ignore. Otherwise, I can draft an ent Hook ensuring this invariant. Want me to open a follow-up?
openmeter/customer/customer.go (1)
36-41: Clarify docstrings to reduce ambiguity between ID vs namespaced CustomerIDRecommend making comments explicit that GetID returns the raw (non-namespaced) ID, while GetCustomerID returns the namespaced composite. This helps avoid future misuses.
-// GetID returns the customer id +// GetID returns the raw customer ID (without namespace) -// GetCustomerID returns the customer id -// This is a convenience method to get the customer id as a CustomerID -// It is used to avoid having to create a CustomerID struct in the codebase +// GetCustomerID returns the namespaced customer ID (Namespace + ID). +// Convenience helper to avoid constructing CustomerID at call sites.Also applies to: 54-63
openmeter/ent/db/billinginvoice_create.go (1)
2099-2123: Consider immutability semantics for customer_key during upsertIf customer_key is meant to snapshot the state at creation, you may want to ignore it in UpdateNewValues (as done for fields like ID, namespace, customer_id). Otherwise upsert can overwrite the snapshot.
Would you like a follow-up diff to add SetIgnore(billinginvoice.FieldCustomerKey) here?
openmeter/billing/invoice.go (1)
576-585: Avoid shadowing the imported package name ‘customer’ in NewInvoiceCustomerParameter name ‘customer’ shadows the imported package within the function scope. Rename for clarity.
-func NewInvoiceCustomer(customer customer.Customer) InvoiceCustomer { - return InvoiceCustomer{ - Key: customer.Key, - CustomerID: customer.ID, - Name: customer.Name, - BillingAddress: customer.BillingAddress, - UsageAttribution: customer.UsageAttribution, - } +func NewInvoiceCustomer(c customer.Customer) InvoiceCustomer { + return InvoiceCustomer{ + Key: c.Key, + CustomerID: c.ID, + Name: c.Name, + BillingAddress: c.BillingAddress, + UsageAttribution: c.UsageAttribution, + } }
📜 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 (50)
openmeter/app/httpdriver/customer.go(3 hunks)openmeter/app/stripe/adapter/stripe.go(1 hunks)openmeter/app/stripe/entity/app/customer.go(1 hunks)openmeter/app/stripe/httpdriver/checkout_session.go(1 hunks)openmeter/app/stripe/httpdriver/customer.go(3 hunks)openmeter/billing/adapter/invoice.go(2 hunks)openmeter/billing/httpdriver/invoice_test.go(1 hunks)openmeter/billing/invoice.go(1 hunks)openmeter/billing/service/invoice.go(2 hunks)openmeter/billing/service/invoiceline.go(4 hunks)openmeter/billing/service/invoicestate.go(1 hunks)openmeter/billing/service/lineservice/feeline.go(1 hunks)openmeter/billing/service/lineservice/meters.go(4 hunks)openmeter/billing/service/lineservice/service.go(1 hunks)openmeter/billing/service/lineservice/usagebasedline.go(2 hunks)openmeter/billing/service/lineservice/usagebasedlineflat.go(1 hunks)openmeter/billing/worker/subscription/sync_test.go(12 hunks)openmeter/customer/customer.go(2 hunks)openmeter/customer/httpdriver/customer.go(3 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(1 hunks)openmeter/meter/httphandler/mapping.go(1 hunks)openmeter/productcatalog/subscription/http/get.go(1 hunks)openmeter/streaming/clickhouse/meter_query.go(3 hunks)openmeter/streaming/clickhouse/meter_query_test.go(3 hunks)openmeter/streaming/query_params.go(1 hunks)openmeter/subscription/service/service.go(1 hunks)openmeter/subscription/service/service_test.go(2 hunks)test/app/custominvoicing/invocing_test.go(4 hunks)test/app/stripe/appstripe.go(16 hunks)test/app/stripe/fixture.go(1 hunks)test/app/stripe/invoice_test.go(6 hunks)test/billing/collection_test.go(8 hunks)test/billing/customeroverride_test.go(1 hunks)test/billing/discount_test.go(6 hunks)test/billing/invoice_test.go(38 hunks)test/billing/subscription_test.go(3 hunks)test/billing/suite.go(1 hunks)test/billing/tax_test.go(4 hunks)test/billing/ubpflatfee_test.go(7 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.down.sql(1 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql(1 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:
test/billing/ubpflatfee_test.gotest/billing/invoice_test.go
🧬 Code Graph Analysis (44)
openmeter/billing/httpdriver/invoice_test.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/billing/service/lineservice/service.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/billing/service/lineservice/feeline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
test/billing/subscription_test.go (1)
openmeter/billing/customeroverride.go (2)
CustomerOverride(19-33)GetCustomerOverrideInput(167-170)
openmeter/ent/db/runtime.go (10)
openmeter/ent/db/billinginvoice/billinginvoice.go (4)
CustomerNameValidator(291-291)CustomerIDValidator(293-293)SourceBillingProfileIDValidator(295-295)CurrencyValidator(297-297)openmeter/ent/db/subscription/subscription.go (2)
CustomerIDValidator(151-151)CurrencyValidator(153-153)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)
CustomerIDValidator(87-87)openmeter/ent/db/customersubjects/customersubjects.go (1)
CustomerIDValidator(64-64)openmeter/ent/db/appcustomer/appcustomer.go (1)
CustomerIDValidator(84-84)openmeter/ent/db/customer/customer.go (1)
CurrencyValidator(147-147)openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)
CurrencyValidator(260-260)openmeter/ent/db/plan/plan.go (1)
CurrencyValidator(123-123)openmeter/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.go (1)
CurrencyValidator(139-139)openmeter/ent/db/addon/addon.go (1)
CurrencyValidator(124-124)
openmeter/subscription/service/service_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
openmeter/ent/db/setorclear.go (1)
openmeter/ent/db/billinginvoice_update.go (2)
BillingInvoiceUpdate(25-29)BillingInvoiceUpdateOne(1424-1429)
openmeter/app/stripe/httpdriver/customer.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
openmeter/productcatalog/subscription/http/get.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
test/billing/discount_test.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)
openmeter/ent/db/billinginvoice_update.go (5)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/app/httpdriver/customer.go (5)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)api/api.gen.go (1)
CustomerId(2279-2282)api/client/javascript/src/client/schemas.ts (1)
CustomerId(10830-10830)api/client/go/client.gen.go (1)
CustomerId(2109-2112)
openmeter/billing/adapter/invoice.go (5)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerKey(127-130)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/ent/schema/customer.go (5)
Customer(17-19)Customer(21-29)Customer(31-39)Customer(41-54)Customer(56-68)openmeter/ent/db/customer/where.go (1)
Key(137-139)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)
openmeter/customer/httpdriver/customer.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/customersubjects/where.go (1)
CustomerID(64-66)
openmeter/streaming/clickhouse/meter_query.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
openmeter/billing/worker/subscription/sync_test.go (6)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)openmeter/ent/db/predicate/predicate.go (1)
Customer(153-153)
openmeter/billing/service/invoicestate.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/app/custominvoicing/invocing_test.go (4)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/app/stripe/fixture.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
test/billing/collection_test.go (4)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/billing/ubpflatfee_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/billinginvoice/where.go (3)
openmeter/ent/db/billinginvoice.go (2)
BillingInvoice(25-143)BillingInvoice(253-270)openmeter/ent/db/predicate/predicate.go (1)
BillingInvoice(65-65)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/service/invoice.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)openmeter/billing/invoice.go (1)
NewInvoiceCustomer(577-585)
openmeter/ent/db/billinginvoice/billinginvoice.go (1)
openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)
OrderOption(300-300)
test/billing/customeroverride_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/billingcustomeroverride/where.go (1)
CustomerID(91-93)
openmeter/billing/service/lineservice/usagebasedline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/subscription/service/service.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
openmeter/streaming/query_params.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
test/billing/suite.go (3)
api/api.gen.go (1)
Customer(2156-2206)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/meter/httphandler/mapping.go (1)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)
openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/ent/db/billinginvoice.go (5)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
test/app/stripe/appstripe.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/app/app.go (1)
GetAppInstanceCustomerDataInput(37-39)
openmeter/customer/customer.go (2)
openmeter/billing/invoice.go (1)
CustomerUsageAttribution(565-565)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)
openmeter/ent/db/mutation.go (2)
openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
test/billing/tax_test.go (5)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/client/go/client.gen.go (1)
Customer(1986-2036)openmeter/ent/db/predicate/predicate.go (1)
Customer(153-153)
openmeter/ent/db/billinginvoice_create.go (6)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/api.gen.go (1)
CustomerKey(2285-2287)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/streaming/clickhouse/meter_query_test.go (1)
openmeter/customer/customer.go (2)
MeterCustomer(15-19)Customer(24-34)
openmeter/billing/service/lineservice/meters.go (2)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/ent/db/migrate/schema.go (1)
openmeter/ent/db/billinginvoice/billinginvoice.go (1)
Columns(206-263)
openmeter/billing/service/invoiceline.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
test/app/stripe/invoice_test.go (2)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
test/billing/invoice_test.go (5)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/client/go/client.gen.go (1)
Customer(1986-2036)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)
openmeter/billing/invoice.go (4)
openmeter/customer/customer.go (3)
MeterCustomer(15-19)Customer(24-34)CustomerUsageAttribution(163-165)api/client/go/client.gen.go (3)
Customer(1986-2036)Address(891-912)CustomerUsageAttribution(2171-2174)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)pkg/models/model.go (1)
Address(192-200)
🔇 Additional comments (80)
openmeter/subscription/service/service.go (1)
482-482: Swapped to GetCustomerID in UpdateCustomer: aligned with API migrationChange looks correct and consistent with the new CustomerID accessor.
openmeter/billing/httpdriver/invoice_test.go (1)
56-56: Test input now uses GetCustomerID: consistent with CreatePendingInvoiceLinesInputGood alignment with the new identifier semantics in tests.
openmeter/app/stripe/adapter/stripe.go (1)
389-389: Confirm input validation covers targetCustomerThe
CreateCheckoutSessionInput.Validate()inopenmeter/app/stripe/entity/input.go(lines 308–311) enforces that at least one ofCreateCustomerInputorCustomerIDis provided:if i.CreateCustomerInput == nil && i.CustomerID == nil { return errors.New("create customer input or customer id or customer key is required") }Since the adapter’s
CreateCheckoutSessionis wired directly to this input type and no other codepath bypasses validation,targetCustomerwill always be set beforeGetCustomerID()is called.— No further action required.
test/billing/customeroverride_test.go (1)
467-468: Updated to GetCustomerID in GetCustomerApp inputMatches the new CustomerID accessor across the suite.
test/billing/ubpflatfee_test.go (1)
59-60: Tests migrated to GetCustomerIDAll call sites consistently use the new accessor. Looks good.
Also applies to: 89-91, 102-105, 159-161, 184-186, 239-241, 265-267
openmeter/billing/service/invoicestate.go (1)
735-736: No PII risk in snapshot logging – safe to pass full InvoiceCustomer
A scan of snapshotLineQuantitiesInParallel (and its SnapshotQuantity implementations in usagebasedline*, usagebasedlineflat.go, and feeline.go) plus all fmt/Info/Error/Warn usages found no logging of the InvoiceCustomer struct. No action required.openmeter/subscription/service/service_test.go (2)
102-110: UpdateCustomer tests: switched to GetCustomerIDMatches the production signature change for UpdateCustomerInput.
147-156: UpdateCustomer tests: switched to GetCustomerIDConsistent migration across test cases.
openmeter/productcatalog/subscription/http/get.go (1)
101-104: LGTM: use CustomerID structUsing cus.GetCustomerID() here aligns with downstream expectations where Namespace and ID are used separately.
openmeter/meter/httphandler/mapping.go (1)
144-146: No change needed for interface implementation
SinceGetID,GetKey, andGetUsageAttributionare defined with value receivers onCustomer, the value typeCustomeralready satisfies theMeterCustomerinterface. Returningc(the value) is correct and will compile. You can keep the existing code as-is.Likely an incorrect or invalid review comment.
test/billing/discount_test.go (1)
88-88: LGTM: migrated to CustomerIDUsing GetCustomerID() for CreatePendingInvoiceLines and InvoicePendingLines inputs is correct and consistent with the new API.
Also applies to: 137-137, 283-283, 329-329, 371-371, 415-415
test/billing/collection_test.go (1)
79-79: LGTM: consistent CustomerID migration across testsAll updated call sites now pass CustomerID, aligning with the refactor. Tests should compile and exercise the intended paths.
Also applies to: 170-170, 281-281, 292-292, 335-335, 359-359, 436-436, 460-460
test/app/stripe/fixture.go (1)
124-126: LGTM: Upsert uses CustomerIDSwitching to customer.GetCustomerID() here matches the service expectation for a strongly-typed CustomerID.
test/billing/subscription_test.go (1)
273-273: LGTM: GetCustomerOverride inputs now use CustomerIDThese updates correctly pass customer.CustomerID as required by GetCustomerOverrideInput.
Also applies to: 282-282, 290-290, 299-299
openmeter/billing/service/lineservice/feeline.go (1)
31-33: LGTM: signature aligns with InvoiceCustomer-based snapshottingfeeLine doesn’t need quantity snapshotting; updated signature ensures it still satisfies the Line interface without unnecessary logic.
test/billing/suite.go (1)
336-336: Correct switch to GetCustomerID()Using in.Customer.GetCustomerID() aligns with the new CustomerID accessor and repo-wide changes.
openmeter/customer/httpdriver/customer.go (3)
209-211: LGTM: Update uses GetCustomerID()Using cus.GetCustomerID() ensures the namespaced ID is propagated correctly.
261-262: LGTM: Delete returns CustomerIDReturning cus.GetCustomerID() matches the DeleteCustomerInput alias and avoids manual construction.
360-363: LGTM: Entitlement value request uses CustomerIDSwitch aligns this path with the new accessor.
tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.down.sql (1)
1-2: No index added forcustomer_key—down migration is correct as-isI’ve verified the up migration (tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql) and confirmed there is no
CREATE INDEX … customer_key. Dropping the column alone fully reverts the change.openmeter/app/httpdriver/customer.go (2)
55-56: LGTM: List handler uses GetCustomerID()Correct propagation of the namespaced CustomerID.
207-213: LGTM: Delete handler uses GetCustomerID()Consistent with the rest of the codebase.
test/app/custominvoicing/invocing_test.go (3)
167-169: LGTM: gathering lines use GetCustomerID()Test inputs now pass the namespaced CustomerID as expected.
224-226: LGTM: invoice pending lines use GetCustomerID()Consistent with the updated API surface.
335-337: LGTM: gathering lines use GetCustomerID() (payment-status-only)Good alignment with the new accessor.
openmeter/app/stripe/httpdriver/customer.go (3)
55-56: LGTM: GetCustomerStripeAppData uses GetCustomerID()Correctly passes the namespaced CustomerID to downstream logic.
112-115: LGTM: UpsertCustomerStripeAppData uses GetCustomerID()Accurate and consistent with the switch across the repo.
189-191: LGTM: CreateStripeCustomerPortalSession uses GetCustomerID()Portal session flow now uses the proper CustomerID type.
openmeter/billing/service/lineservice/service.go (1)
217-218: No stale []string usages detected
Ran the provided regex across the repository and found no lingeringSnapshotQuantitysignatures or call sites using[]string. Compilation and existing tests should surface any remaining mismatches—if you encounter any, update those call sites to usebilling.InvoiceCustomer.openmeter/billing/worker/subscription/sync_test.go (1)
501-502: No further changes required for.GetID()in subscription tests
The only remaining.GetID()calls (sync_test.go lines 76, 496, 564) are onappSandboxfor sandbox IDs—not on customer objects—and these still correctly supply raw IDs in the new MeterCustomer flow. All customer‐ID accessors have been updated.openmeter/billing/service/invoice.go (1)
1087-1088: Centralized construction with NewInvoiceCustomerUsing billing.NewInvoiceCustomer avoids duplication and keeps the simulated invoice in sync with runtime snapshot semantics. LGTM.
openmeter/billing/adapter/invoice.go (2)
502-507: UpdateInvoice: set/clear CustomerKey — LGTMThis correctly persists updates to the invoice’s customer key snapshot.
675-689: Expose Customer.Key on read — LGTMMapping DB customer_key to the API’s InvoiceCustomer.Key is correct and matches the schema.
openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
96-101: Flat-fee SnapshotQuantity matches new signature and initializes pre-period qty
- Accepts billing.InvoiceCustomer per the new interface.
- Initializes MeteredQuantity, Quantity, and both pre-period fields to zero/1 as expected for flat fees.
LGTM.openmeter/ent/db/billinginvoice/billinginvoice.go (2)
75-76: Add FieldCustomerKey constant — OKConstant name and value align with schema and related usages.
236-236: Include FieldCustomerKey in Columns — OKEnsures ValidColumn recognizes the new field; consistent with ent patterns.
test/app/stripe/appstripe.go (1)
201-202: Replace remaining customer.GetID() with GetCustomerID()
A leftover call tocustomer.GetID()was found and needs migration:
- openmeter/streaming/clickhouse/meter_query.go:210
- sqlbuilder.Escape(customer.GetID()),
- sqlbuilder.Escape(customer.GetCustomerID().ID),
Please update this call to use `GetCustomerID()` (and reference its `.ID` field as needed). > Likely an incorrect or invalid review comment. </details> <details> <summary>openmeter/streaming/clickhouse/meter_query_test.go (1)</summary> `267-291`: **MeterCustomer satisfied by value receivers – no pointer change needed** The `Customer` type in openmeter/customer/customer.go defines `GetID`, `GetKey`, and `GetUsageAttribution` with value receivers, so a `customer.Customer` literal already implements the `MeterCustomer` interface. The existing code compiles and runs correctly; you can ignore the pointer-suggestion. > Likely an incorrect or invalid review comment. </details> <details> <summary>openmeter/ent/db/billinginvoice.go (1)</summary> `85-86`: **CustomerKey field plumbed through entity/scan/assign/string — OK** - Struct field addition and JSON tag are correct. - scanValues/assignValues use sql.NullString consistently. - String() includes customer_key when present. All ent patterns look consistent. Confirm the migration added customer_key with the same nullability and type, and that runtime descriptors were updated. Also applies to: 261-262, 472-478, 843-847 </details> <details> <summary>openmeter/billing/service/lineservice/usagebasedline.go (1)</summary> `151-175`: **SnapshotQuantity now uses InvoiceCustomer — OK** Switching from subject keys to the richer InvoiceCustomer is sound. Validation still guards empty subject keys. No issues spotted. </details> <details> <summary>openmeter/streaming/clickhouse/meter_query.go (1)</summary> `26-26`: **Query param type change to []customer.MeterCustomer — OK** Aligns with the new interface and upstream changes. </details> <details> <summary>test/app/stripe/invoice_test.go (1)</summary> `294-294`: **Migration to Customer.GetCustomerID() — OK** All updated usages (create pending lines, invoice generation, and stripe mocks) look correct and consistent with the new API. Also applies to: 471-471, 488-488, 1098-1098, 1141-1141, 1151-1151 </details> <details> <summary>openmeter/ent/db/setorclear.go (1)</summary> `772-784`: **SetOrClearCustomerKey helpers — OK** Matches existing SetOrClear pattern and complements generated Set/Clear methods. </details> <details> <summary>openmeter/ent/db/runtime.go (1)</summary> `469-486`: **Confirm BillingInvoice descriptor indices and validators** Please manually verify that the hard-coded indices in openmeter/ent/db/runtime.go (lines 469–486) correctly align with your schema and that each referenced field has at least one validator or default value: • Ensure BillingInvoice.Fields() (in openmeter/ent/schema/…) returns its slice in the exact order you expect—so index 3 maps to customer_name, 8→customer_id, 9→source_billing_profile_id, 15→currency, and 28→collection_at. • Confirm each of those fields is defined with at least one validator in the Ent schema (Validators[0] will exist). • Verify collection_at has a default configured (DefaultCollectionAt). Without inspecting the schema file directly, we can’t rule out runtime panics if any index or validator is missing—please double-check these offsets. </details> <details> <summary>openmeter/billing/service/lineservice/meters.go (4)</summary> `11-11`: **New customer import is necessary and correct.** Importing customer for the MeterCustomer interface is required for FilterCustomer usage. LGTM. --- `21-22`: **Switch to Customer-centric input is correct.** Replacing Subjects with a single InvoiceCustomer matches the new design. Keeps type-safety and avoids dangling subject lists. --- `38-40`: **Customer validation instead of non-empty subjects.** Calling Customer.Validate() and error-wrapping as “customer: …” provides clearer feedback. Good change. --- `59-62`: **QueryParams now filters by customer (via MeterCustomer).** Using FilterCustomer: []customer.MeterCustomer{in.Customer} is aligned with the new streaming API. Date range mapping remains unchanged. LGTM. </details> <details> <summary>test/billing/invoice_test.go (3)</summary> `128-156`: **Consistently switching to Customer.GetCustomerID() across tests — LGTM.** The updates uniformly pass the composite CustomerID (ID + Namespace) where required, reducing mistakes from mixing IDs and namespaces. Also applies to: 162-166, 455-459, 631-636, 1404-1408, 1561-1565, 1578-1582, 1882-1886, 2094-2098, 2788-2792, 2800-2805, 2811-2816, 3323-3327, 3351-3355, 3442-3446, 3470-3474, 3598-3604, 3641-3644, 3692-3697, 3752-3756, 3801-3806, 3858-3863, 3931-3945, 3962-3977, 4041-4056, 4080-4093 --- `298-301`: **Asserting InvoiceCustomer.Key in expectations is good coverage.** Adding Key to the expected invoice customer validates persistence of customer_key and equality semantics. Nice. --- `4032-4033`: **DeleteCustomer now takes CustomerID — LGTM.** The test covers the new signature and deletion flow; subsequent scenarios validate pre/post-deletion behavior correctly. </details> <details> <summary>openmeter/billing/service/invoiceline.go (2)</summary> `309-311`: **Snapshotting quantities now uses the full InvoiceCustomer.** Passing invoice.Customer into the parallel snapshotter aligns line services with customer-centric usage. Good change. --- `394-396`: **SnapshotLineQuantity updated to pass InvoiceCustomer — LGTM.** Directly passing input.Invoice.Customer maintains consistency with the new interfaces. </details> <details> <summary>openmeter/ent/db/migrate/schema.go (2)</summary> `616-651`: **Foreign key column indices validated successfully** All foreign key column references in `openmeter/ent/db/migrate/schema.go` (Lines 617–648) have been shifted correctly to indices 50–55 after inserting `customer_key`. No stale or mismatched indexes remain. --- `670-683`: **Verify runtime index metadata for BillingInvoice** The schema migration in openmeter/ent/db/migrate/schema.go now defines these indexes with updated column positions: - billinginvoice_namespace_customer_id → columns [1], [55] - billinginvoice_namespace_status → columns [1], [42] - billinginvoice_status_details_cache → column [43] Ensure that the generated table descriptors in openmeter/ent/db/runtime.go include matching index definitions (names and column positions) to prevent scan mismatches at runtime. • Open openmeter/ent/db/runtime.go and verify presence of: – billinginvoice_namespace_customer_id – billinginvoice_namespace_status – billinginvoice_status_details_cache • If they’re missing or out of sync, re-run your Ent code generation (e.g. `go generate ./ent`) and commit the updated runtime descriptors. </details> <details> <summary>openmeter/ent/db/billinginvoice_update.go (4)</summary> `487-506`: **New setters for customer_key on BillingInvoiceUpdate mirror existing conventions** SetCustomerKey, SetNillableCustomerKey, and ClearCustomerKey follow the established pattern for optional string fields. LGTM. --- `1187-1192`: **sqlSave correctly handles set/clear for customer_key** Field is propagated via SetField/ClearField with TypeString. This ensures both updates and null clears behave as expected. --- `1881-1900`: **New setters for customer_key on BillingInvoiceUpdateOne are consistent** SetCustomerKey, SetNillableCustomerKey, ClearCustomerKey match the update-one flow; consistent with other fields. LGTM. --- `2611-2616`: **UpdateOne sqlSave path includes customer_key; clear semantics included** SetField/ClearField wiring mirrors the multi-update path. Looks good. </details> <details> <summary>openmeter/ent/db/mutation.go (12)</summary> `11372-11372`: **Struct field addition looks correct** Adding customer_key as a nullable string on BillingInvoiceMutation is consistent with optional field handling. --- `12764-12779`: **OldCustomerKey() semantics look correct** UpdateOne-only restriction, ID requirement, and old value retrieval match the established pattern in this file. --- `12781-12791`: **Clear/cleared-check are correct** ClearCustomerKey and CustomerKeyCleared follow the standard clearedFields pattern. --- `12794-12797`: **Reset method is consistent** ResetCustomerKey resets the pointer and removes the cleared flag; consistent with other Reset* implementations. --- `14247-14247`: **Capacity bump acknowledges new field** Increasing the preallocation from 54 to 55 is harmless and aligns with adding a field. --- `14332-14334`: **Fields() wiring includes customer_key** Correctly appends FieldCustomerKey when set. --- `14477-14478`: **Field() switch returns CustomerKey()** Returns the expected (string, bool) pair for FieldCustomerKey; consistent with other string fields. --- `14596-14597`: **OldField() switch returns OldCustomerKey(ctx)** Pattern matches other optional string fields that return (*string, error). --- `14855-14861`: **SetField() supports FieldCustomerKey** Type assertion to string and delegation to SetCustomerKey are correct; once SetCustomerKey clears the cleared flag, this path is solid. --- `15125-15127`: **ClearedFields() includes FieldCustomerKey** Correctly lists the field when cleared. --- `15235-15237`: **ClearField() handles FieldCustomerKey** Delegates to ClearCustomerKey as expected. --- `15372-15374`: **ResetField() handles FieldCustomerKey** Delegates to ResetCustomerKey; consistent with other fields. </details> <details> <summary>openmeter/customer/customer.go (2)</summary> `14-21`: **LGTM: MeterCustomer interface and conformance assertion** The interface shape matches the usage needs (ID, Key, UsageAttribution). Compile-time assertion is a good guard. --- `36-63`: **All Customer.GetID() call sites validated – no breaking changes detected** I searched across the codebase for both `GetID()` and `GetCustomerID()` usages. Every call site that needs the full `CustomerID` struct now correctly uses `GetCustomerID()`, and the remaining `GetID()` calls (including in streaming and billing modules) all expect a plain `string`. No updates are required. </details> <details> <summary>openmeter/ent/db/billinginvoice_create.go (3)</summary> `348-361`: **Add SetCustomerKey / SetNillableCustomerKey: looks correct** Builder API mirrors existing patterns; nillable variant guards nil correctly. --- `1056-1059`: **Persist customer_key in createSpec: correct field wiring** Field type and assignment to node are consistent with billinginvoice.FieldCustomerKey. --- `1740-1756`: **Upsert Set/Update/Clear for customer_key: consistent with ent codegen patterns** All three upsert entry points expose the same operations; naming matches other fields. Also applies to: 2637-2656, 3758-3777 </details> <details> <summary>openmeter/billing/invoice.go (2)</summary> `572-575`: **LGTM: InvoiceCustomer implements MeterCustomer** Good compile-time guard to keep interface stability across refactors. --- `587-597`: **InvoiceCustomer snapshot and accessors: looks good** - Fields cover the snapshot needs (ID, Key, Name, Address, UsageAttribution). - Accessor methods correctly satisfy MeterCustomer. - Validate enforces non-empty CustomerID and Name, and non-empty Key when present. Also applies to: 598-615, 616-631 </details> <details> <summary>openmeter/ent/db/billinginvoice/where.go (2)</summary> `209-213`: **Add CustomerKey equality helper: consistent with other “Field()” shortcuts** Matches the pattern of “Field() is identical to FieldEQ”. --- `2038-2111`: **Full predicate suite for customer_key: complete and correct** Covers EQ/NEQ, In/NotIn, GT/GTE/LT/LTE, Contains/HasPrefix/HasSuffix, IsNil/NotNil, and fold variants, aligned with a nullable string column. </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
There was a problem hiding this comment.
Actionable comments posted: 3
🔭 Outside diff range comments (6)
openmeter/app/stripe/entity/app/customer.go (2)
123-130: Also validate non-empty email for SendInvoiceStripe requires a valid email; an empty string should be treated as missing.
- if stripeCustomer.Email == nil { + if stripeCustomer.Email == nil || *stripeCustomer.Email == "" { return app.NewAppCustomerPreConditionError( a.GetID(), a.GetType(), &customerID, fmt.Sprintf("stripe customer missing email: in order to create invoices that are sent to the stripe customer, the stripe customer %s must have a valid email", stripeCustomerData.StripeCustomerID), ) }
138-147: Possible nil dereference: stripeCustomer.Tax may be nil
stripeCustomer.Taxcan be nil; accessingAutomaticTaxwould panic. Guard before the switch.if slices.Contains(capabilities, app.CapabilityTypeCalculateTax) && customerBillingProfile.MergedProfile.WorkflowConfig.Tax.Enabled { // If tax is enforced, we need to ensure that the customer has a tax location if customerBillingProfile.MergedProfile.WorkflowConfig.Tax.Enforced { - switch stripeCustomer.Tax.AutomaticTax { + if stripeCustomer.Tax == nil { + return app.NewAppCustomerPreConditionError( + a.GetID(), + a.GetType(), + &customerID, + fmt.Sprintf("stripe tax: missing tax settings for customer %s", stripeCustomerData.StripeCustomerID), + ) + } + switch stripeCustomer.Tax.AutomaticTax {openmeter/customer/httpdriver/customer.go (1)
197-214: Guard against nil customer in request handlers to prevent panicsThese three request constructors call
cus.GetCustomerID()without checking whethercusis nil. Ifh.service.GetCustomerever returns(nil, nil), that will cause a panic. Add a nil check immediately after the service call:Affected handlers in
openmeter/customer/httpdriver/customer.go:
- UpdateCustomer (lines ~197–214)
- DeleteCustomer (lines ~244–262)
- GetCustomerEntitlementValue (lines ~343–364)
Proposed minimal diffs:
--- a/openmeter/customer/httpdriver/customer.go +++ b/openmeter/customer/httpdriver/customer.go @@ func (h *handler) UpdateCustomer() UpdateCustomerHandler { - cus, err := h.service.GetCustomer(ctx, customer.GetCustomerInput{…}) + cus, err := h.service.GetCustomer(ctx, customer.GetCustomerInput{…}) if err != nil { return UpdateCustomerRequest{}, err } + if cus == nil { + return UpdateCustomerRequest{}, fmt.Errorf("customer not found") + } req := UpdateCustomerRequest{ CustomerID: cus.GetCustomerID(), @@ func (h *handler) DeleteCustomer() DeleteCustomerHandler { - cus, err := h.service.GetCustomer(ctx, customer.GetCustomerInput{…}) + cus, err := h.service.GetCustomer(ctx, customer.GetCustomerInput{…}) if err != nil { return DeleteCustomerRequest{}, err } + if cus == nil { + return DeleteCustomerRequest{}, fmt.Errorf("customer not found") + } return cus.GetCustomerID(), nil @@ func (h *handler) GetCustomerEntitlementValue() GetCustomerEntitlementValueHandler { - cus, err := h.service.GetCustomer(ctx, customer.GetCustomerInput{…}) + cus, err := h.service.GetCustomer(ctx, customer.GetCustomerInput{…}) if err != nil { return GetCustomerEntitlementValueRequest{}, err } + if cus == nil { + return GetCustomerEntitlementValueRequest{}, fmt.Errorf("customer not found") + } return GetCustomerEntitlementValueRequest{ FeatureKey: params.FeatureKey, CustomerID: cus.GetCustomerID(),openmeter/billing/service/invoicestate.go (1)
726-728: Potential nil dereference on CollectionAtclock.Now().Before(*m.Invoice.CollectionAt) can panic when CollectionAt is nil. Guard the pointer before dereferencing.
- // We don't have the snapshot and the collection date is in the future -if m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) { + // We don't have the snapshot and the collection date is in the future +if m.Invoice.QuantitySnapshotedAt == nil && m.Invoice.CollectionAt != nil && clock.Now().Before(*m.Invoice.CollectionAt) { return nil }openmeter/billing/adapter/invoice.go (1)
352-355: Creation path does not snapshot Customer.Key to the invoicePR objective says to snapshot Customer.Key; Update path handles it, mapping reads it, but CreateInvoice doesn’t set it. Persist Key on create to ensure newly created invoices carry customer_key.
Proposed change:
createMut = createMut. SetCustomerName(customer.Name) + // Snapshot optional customer key on create + .SetNillableCustomerKey(customer.Key)openmeter/billing/service/invoiceline.go (1)
319-337: Potential deadlock on context cancellation; make error channel capacity safe and avoid per-worker ctx.Err sendsIf ctx is canceled while lines remain, each worker can attempt to send ctx.Err to errCh. Since errCh is buffered to len(lines), this can overflow (workers > lines), block a goroutine in defer before it signals done, and deadlock the wait on doneCh.
Recommended minimal changes:
- Buffer errCh to len(lines) + number_of_workers.
- Don’t send ctx.Err from every worker; just return early. At the end, if there were no other errors, return ctx.Err.
Example diff:
func (s *Service) snapshotLineQuantitiesInParallel(ctx context.Context, customer billing.InvoiceCustomer, lines lineservice.Lines) error { - linesCh := make(chan lineservice.Line, len(lines)) - errCh := make(chan error, len(lines)) - doneCh := make(chan struct{}) + linesCh := make(chan lineservice.Line, len(lines)) + // Ensure capacity for per-line errors plus up to per-worker terminal errors (panic, etc.). + workerCount := 0 + for range s.maxParallelQuantitySnapshots { + workerCount++ + } + errCh := make(chan error, len(lines)+workerCount) + doneCh := make(chan struct{}) @@ for line := range linesCh { - if ctx.Err() != nil { - errCh <- ctx.Err() - return - } + if ctx.Err() != nil { + // Stop this worker; top-level will surface ctx.Err() if no other errors occurred. + return + } if err := line.SnapshotQuantity(ctx, customer); err != nil { errCh <- fmt.Errorf("line[%s]: snapshotting quantity: %w", line.ID(), err) } } @@ // Collect snapshot errors errs := []error{} for err := range errCh { if err != nil { errs = append(errs, err) } } - return errors.Join(errs...) + if len(errs) == 0 && ctx.Err() != nil { + return ctx.Err() + } + return errors.Join(errs...) }This removes the deadlock risk and preserves error semantics.
Also applies to: 341-346, 353-355, 359-368
🧹 Nitpick comments (15)
openmeter/app/stripe/entity/app/customer.go (3)
58-59: Wrap non-typed error for context consistencyReturn a wrapped error for consistency with other error paths.
- return err + return fmt.Errorf("failed to get stripe customer: %w", err)
71-71: Fix typo in comment“capabilitie” -> “capabilities”.
- // Validate customer for payment capabilitie + // Validate customer for payment capabilities
201-204: Improve cast error message with type detailIncluding the actual type greatly speeds up debugging.
- if !ok { - return fmt.Errorf("error casting stripe customer data") - } + if !ok { + return fmt.Errorf("invalid stripe customer data type: %T", input.Data) + }tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.down.sql (1)
1-2: Use IF EXISTS to make the down migration idempotent.Dropping the column is correct for reversing the up migration. Consider making it resilient:
-ALTER TABLE "billing_invoices" DROP COLUMN "customer_key"; +ALTER TABLE "billing_invoices" DROP COLUMN IF EXISTS "customer_key";Also note this is data-destructive (expected for down).
tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql (1)
1-2: Add IF NOT EXISTS and consider documenting/indexing the new column.
- Idempotency:
-ALTER TABLE "billing_invoices" ADD COLUMN "customer_key" character varying NULL; +ALTER TABLE "billing_invoices" ADD COLUMN IF NOT EXISTS "customer_key" character varying NULL;
- Optional: Add a column comment for schema clarity:
COMMENT ON COLUMN "billing_invoices"."customer_key" IS 'Snapshot of the customer key at the time of invoice creation';
- If you plan to filter by customer_key, consider adding an index in a follow-up migration to avoid table scans.
openmeter/customer/customer.go (1)
36-41: GetID now returns string (breaking semantic change). Verify all call sites.This redefines GetID() to return the raw ID string (previously many call sites expected a namespaced ID). Ensure all usages expecting a CustomerID were migrated to GetCustomerID().
Consider clarifying the comment, e.g., “GetID returns the raw (non-namespaced) ID. Use GetCustomerID() for the namespaced identifier.”
test/billing/suite.go (1)
336-336: LGTM: CreateGatheringInvoice uses CustomerIDGood switch to in.Customer.GetCustomerID().
For consistency, consider using GetCustomerID() in CreateDraftInvoice as well (currently it constructs customer.CustomerID manually around Lines 401-405).
openmeter/app/stripe/httpdriver/checkout_session.go (1)
93-93: LGTM: resolve customer by key with GetCustomerID()The pointer to CustomerID is the correct shape for downstream calls. Consider minor naming cleanup for local vars to match Go conventions.
Example cleanup (optional):
- customerId -> customerID
- appId -> appID
- stripeCustomerId -> stripeCustomerID
openmeter/app/stripe/adapter/stripe.go (1)
389-389: Guard against nil targetCustomer (defensive)If input validation elsewhere ever regresses, calling GetCustomerID() on a nil targetCustomer would panic. Consider an early check.
Minimal defensive guard:
- customerID := targetCustomer.GetCustomerID() + if targetCustomer == nil { + return appstripeentity.CreateCheckoutSessionOutput{}, models.NewGenericValidationError( + fmt.Errorf("no customer reference provided"), + ) + } + customerID := targetCustomer.GetCustomerID()Please confirm CreateCheckoutSessionInput.Validate() guarantees at least one of CustomerID/CreateCustomerInput is set. If so, feel free to skip the guard; otherwise, the above adds safety.
openmeter/subscription/service/service.go (1)
482-483: Switch to GetCustomerID() is correct and consistent with the new APIThe field now expects a CustomerID value; using cust.GetCustomerID() aligns with the broader refactor. No functional issues found.
If you want to harden against concurrent updates, consider a narrow update that only sets Currency when NULL at the DB level (e.g., a SetCurrencyIfNil(CustomerID, Currency) path) to avoid clobbering concurrent customer updates.
openmeter/customer/httpdriver/customer.go (1)
209-211: Migration to GetCustomerID() looks goodUsing cus.GetCustomerID() matches the new CustomerID workflow and types expected by the respective inputs.
Consider adding a brief comment on why we re-fetch the customer (to resolve key vs ID) before constructing the request.
Also applies to: 261-262, 363-363
openmeter/ent/schema/billing.go (1)
849-852: Consider indexing customer_key to support lookup performanceYou added where/order support for customer_key across the DB layer. If queries will filter/order by customer_key, add an index (preferably partial) to avoid full scans.
Example Index (partial, non-unique):
// In func (BillingInvoice) Indexes() []ent.Index index.Fields("namespace", "customer_key"). Annotations( entsql.IndexWhere("customer_key IS NOT NULL AND deleted_at IS NULL"), ),Remember to include a migration to create/drop this index alongside the column migration.
openmeter/streaming/query_params.go (1)
17-18: Migration to []MeterCustomer is correct; validation remains coherentThe existing rules around multiple customers and groupBy "customer_id" still apply and make sense with MeterCustomer.
Add a short field comment documenting that MeterCustomer is an interface implemented by Customer to clarify accepted values for future readers.
openmeter/billing/service/lineservice/feeline.go (1)
31-33: Optional: document intentional no-opConsider a short comment explaining fee lines don’t snapshot quantities to prevent future confusion.
-func (l feeLine) SnapshotQuantity(context.Context, billing.InvoiceCustomer) error { +// Fee lines do not track usage; quantity snapshot is a no-op by design. +func (l feeLine) SnapshotQuantity(context.Context, billing.InvoiceCustomer) error { return nil }openmeter/billing/adapter/invoice.go (1)
502-507: Use SetOrClear helper for CustomerKey to simplify and match project styleCurrent if/else is fine but inconsistent with other setters using SetOrClear*. Prefer the generated helper.
Apply:
- if in.Customer.Key != nil { - updateQuery = updateQuery.SetCustomerKey(*in.Customer.Key) - } else { - updateQuery = updateQuery.ClearCustomerKey() - } + updateQuery = updateQuery.SetOrClearCustomerKey(in.Customer.Key)
📜 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 (50)
openmeter/app/httpdriver/customer.go(3 hunks)openmeter/app/stripe/adapter/stripe.go(1 hunks)openmeter/app/stripe/entity/app/customer.go(1 hunks)openmeter/app/stripe/httpdriver/checkout_session.go(1 hunks)openmeter/app/stripe/httpdriver/customer.go(3 hunks)openmeter/billing/adapter/invoice.go(2 hunks)openmeter/billing/httpdriver/invoice_test.go(1 hunks)openmeter/billing/invoice.go(1 hunks)openmeter/billing/service/invoice.go(2 hunks)openmeter/billing/service/invoiceline.go(4 hunks)openmeter/billing/service/invoicestate.go(1 hunks)openmeter/billing/service/lineservice/feeline.go(1 hunks)openmeter/billing/service/lineservice/meters.go(4 hunks)openmeter/billing/service/lineservice/service.go(1 hunks)openmeter/billing/service/lineservice/usagebasedline.go(2 hunks)openmeter/billing/service/lineservice/usagebasedlineflat.go(1 hunks)openmeter/billing/worker/subscription/sync_test.go(12 hunks)openmeter/customer/customer.go(2 hunks)openmeter/customer/httpdriver/customer.go(3 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(1 hunks)openmeter/meter/httphandler/mapping.go(1 hunks)openmeter/productcatalog/subscription/http/get.go(1 hunks)openmeter/streaming/clickhouse/meter_query.go(3 hunks)openmeter/streaming/clickhouse/meter_query_test.go(3 hunks)openmeter/streaming/query_params.go(1 hunks)openmeter/subscription/service/service.go(1 hunks)openmeter/subscription/service/service_test.go(2 hunks)test/app/custominvoicing/invocing_test.go(4 hunks)test/app/stripe/appstripe.go(16 hunks)test/app/stripe/fixture.go(1 hunks)test/app/stripe/invoice_test.go(6 hunks)test/billing/collection_test.go(8 hunks)test/billing/customeroverride_test.go(1 hunks)test/billing/discount_test.go(6 hunks)test/billing/invoice_test.go(38 hunks)test/billing/subscription_test.go(3 hunks)test/billing/suite.go(1 hunks)test/billing/tax_test.go(4 hunks)test/billing/ubpflatfee_test.go(7 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.down.sql(1 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql(1 hunks)
🔥 Files not summarized due to errors (1)
- openmeter/app/stripe/entity/app/customer.go: Error: Server error: no LLM provider could handle the message
🧰 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/usagebasedlineflat.gotest/billing/invoice_test.gotest/billing/ubpflatfee_test.go
🧬 Code Graph Analysis (43)
openmeter/billing/service/lineservice/service.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
test/billing/tax_test.go (4)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/app/stripe/httpdriver/customer.go (5)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)api/client/javascript/src/client/schemas.ts (1)
CustomerId(10830-10830)api/api.gen.go (1)
CustomerId(2279-2282)api/client/go/client.gen.go (1)
CustomerId(2109-2112)
test/billing/subscription_test.go (1)
openmeter/billing/customeroverride.go (2)
CustomerOverride(19-33)GetCustomerOverrideInput(167-170)
openmeter/ent/db/runtime.go (1)
openmeter/ent/db/billinginvoice/billinginvoice.go (4)
CustomerNameValidator(291-291)CustomerIDValidator(293-293)SourceBillingProfileIDValidator(295-295)CurrencyValidator(297-297)
openmeter/billing/httpdriver/invoice_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/billing/collection_test.go (4)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/setorclear.go (1)
openmeter/ent/db/billinginvoice_update.go (2)
BillingInvoiceUpdate(25-29)BillingInvoiceUpdateOne(1424-1429)
test/app/stripe/invoice_test.go (5)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerID(112-112)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)openmeter/ent/db/predicate/predicate.go (1)
Customer(153-153)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
openmeter/ent/db/billinginvoice/billinginvoice.go (2)
openmeter/ent/db/customer/customer.go (1)
OrderOption(153-153)openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)
OrderOption(300-300)
openmeter/subscription/service/service.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
openmeter/streaming/query_params.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
test/app/stripe/fixture.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
openmeter/productcatalog/subscription/http/get.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
test/billing/discount_test.go (1)
api/client/go/client.gen.go (1)
Customer(1986-2036)
test/app/stripe/appstripe.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/app/app.go (1)
GetAppInstanceCustomerDataInput(37-39)
openmeter/app/httpdriver/customer.go (5)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)api/client/javascript/src/client/schemas.ts (1)
CustomerId(10830-10830)api/api.gen.go (1)
CustomerId(2279-2282)api/client/go/client.gen.go (1)
CustomerId(2109-2112)
openmeter/subscription/service/service_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
openmeter/meter/httphandler/mapping.go (3)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/billing/customeroverride_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/billingcustomeroverride/where.go (1)
CustomerID(91-93)
test/billing/suite.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/mutation.go (2)
openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/customer/httpdriver/customer.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/customersubjects/where.go (1)
CustomerID(64-66)
openmeter/billing/service/lineservice/feeline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/billing/service/lineservice/usagebasedline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/ent/db/migrate/schema.go (2)
openmeter/ent/db/billinginvoice/billinginvoice.go (1)
Columns(206-263)openmeter/ent/db/customer/customer.go (1)
Columns(103-123)
openmeter/ent/db/billinginvoice_update.go (5)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/service/invoice.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/billing/invoice.go (1)
NewInvoiceCustomer(577-585)
openmeter/billing/service/lineservice/meters.go (3)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)openmeter/billing/invoiceline.go (2)
Line(305-319)Period(82-85)
openmeter/ent/db/billinginvoice/where.go (3)
openmeter/ent/db/billinginvoice.go (2)
BillingInvoice(25-143)BillingInvoice(253-270)openmeter/ent/db/predicate/predicate.go (1)
BillingInvoice(65-65)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
test/billing/invoice_test.go (2)
openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/ent/schema/customer.go (5)
Customer(17-19)Customer(21-29)Customer(31-39)Customer(41-54)Customer(56-68)
openmeter/billing/adapter/invoice.go (7)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerKey(127-130)api/client/javascript/src/client/schemas.ts (2)
Customer(10821-10821)CustomerKey(10831-10831)api/client/go/client.gen.go (2)
Customer(1986-2036)CustomerKey(2115-2117)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/ent/schema/customer.go (5)
Customer(17-19)Customer(21-29)Customer(31-39)Customer(41-54)Customer(56-68)openmeter/ent/db/customer/where.go (1)
Key(137-139)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)
test/app/custominvoicing/invocing_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/streaming/clickhouse/meter_query.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
openmeter/ent/db/billinginvoice_create.go (2)
openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/service/invoicestate.go (2)
api/client/go/client.gen.go (1)
Customer(1986-2036)openmeter/customer/customer.go (1)
Customer(24-34)
openmeter/billing/invoice.go (2)
openmeter/customer/customer.go (3)
MeterCustomer(15-19)Customer(24-34)CustomerUsageAttribution(163-165)pkg/models/model.go (1)
Address(192-200)
openmeter/billing/service/invoiceline.go (1)
openmeter/billing/invoice.go (2)
InvoiceCustomer(590-596)Invoice(330-341)
openmeter/streaming/clickhouse/meter_query_test.go (1)
openmeter/customer/customer.go (2)
MeterCustomer(15-19)Customer(24-34)
test/billing/ubpflatfee_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/billinginvoice.go (6)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/api.gen.go (1)
CustomerKey(2285-2287)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/worker/subscription/sync_test.go (4)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)
🔇 Additional comments (84)
openmeter/productcatalog/subscription/http/get.go (1)
101-104: Use of GetCustomerID is correct and consistent.The switch to cus.GetCustomerID() cleanly aligns with the namespaced ID usage and downstream expects (Namespaces/Customers split). No issues.
openmeter/app/stripe/httpdriver/customer.go (1)
55-56: LGTM: Switched to GetCustomerID in all three handlers.All three handlers now pass a namespaced CustomerID, aligning with the updated service contracts. Looks good.
Also applies to: 112-115, 189-191
test/billing/discount_test.go (1)
88-89: Tests correctly updated to use GetCustomerID.Consistently passing a namespaced CustomerID into billing flows. No issues spotted.
Also applies to: 137-138, 283-285, 329-331, 371-373, 415-416
openmeter/customer/customer.go (2)
14-22: MeterCustomer interface introduction looks solid.Clear contract for meter-facing components; compile-time assertion ensures conformance.
54-62: Convenience GetCustomerID() method is appropriate.Creates the proper namespaced identifier and reduces boilerplate across call sites. Good addition.
test/billing/subscription_test.go (1)
273-274: Updated to GetCustomerID in tests is correct.Input now matches the expected namespaced CustomerID in GetCustomerOverrideInput. Looks good.
Also applies to: 282-284, 290-292, 299-301
test/billing/customeroverride_test.go (1)
467-469: Switch to GetCustomerID aligns with the updated API.The GetCustomerApp input now receives a namespaced CustomerID. LGTM.
test/app/custominvoicing/invocing_test.go (4)
167-167: LGTM: use Customer.GetCustomerID()Swapping to the structured CustomerID aligns with the new API. All good.
224-224: LGTM: InvoicePendingLines uses CustomerIDThe change is correct and consistent with the updated inputs.
335-335: LGTM: pending lines use CustomerIDCorrect switch to GetCustomerID().
362-362: LGTM: invoicing uses CustomerIDCorrect and consistent.
test/billing/tax_test.go (4)
204-204: LGTM: CreatePendingInvoiceLines uses CustomerIDCorrect migration to GetCustomerID().
247-247: LGTM: InvoicePendingLines uses CustomerIDLooks good.
275-275: LGTM: helper generateDraftInvoice uses CustomerIDOn point.
299-299: LGTM: InvoicePendingLines uses CustomerIDConsistent with the new API.
openmeter/billing/worker/subscription/sync_test.go (10)
501-501: LGTM: InvoicePendingLines uses CustomerIDCorrect update.
520-520: LGTM: CreatePendingInvoiceLines uses CustomerIDAll good.
548-548: LGTM: InvoicePendingLines uses CustomerIDLooks right.
1265-1265: LGTM: draft invoice creation uses CustomerIDCorrect and consistent.
2817-2817: LGTM: draft invoices use CustomerIDGood migration.
2974-2974: LGTM: issued invoice creation uses CustomerIDOn point.
3011-3011: LGTM: draft invoice #2 uses CustomerIDConsistent change.
3301-3301: LGTM: draft invoice uses CustomerIDCorrect.
3471-3471: LGTM: draft invoice uses CustomerIDLooks good.
3757-3757: LGTM: draft invoice uses CustomerIDAll good.
test/billing/ubpflatfee_test.go (7)
59-59: LGTM: CreatePendingInvoiceLines uses CustomerIDCorrect migration.
89-89: LGTM: progressive billing check uses CustomerIDLooks good.
103-103: LGTM: InvoicePendingLines uses CustomerIDOn point.
159-159: LGTM: CreatePendingInvoiceLines uses CustomerIDCorrect.
185-185: LGTM: InvoicePendingLines uses CustomerIDAll good.
239-239: LGTM: CreatePendingInvoiceLines uses CustomerIDConsistent with API.
265-265: LGTM: CreatePendingInvoiceLines (empty period) uses CustomerIDLooks right.
test/app/stripe/fixture.go (1)
125-125: LGTM: Upsert customer data uses CustomerIDCorrect and consistent with the migration.
openmeter/billing/httpdriver/invoice_test.go (1)
56-57: LGTM: test updated to pass CustomerIDUsing cust.GetCustomerID() matches billing.CreatePendingInvoiceLinesInput expectations after the refactor.
openmeter/subscription/service/service_test.go (1)
100-111: LGTM: UpdateCustomerInput now receives CustomerID via GetCustomerID()Both updates correctly align with the new CustomerID shape. No additional changes needed.
Also applies to: 145-157
test/app/stripe/invoice_test.go (1)
292-299: LGTM: consistent migration to GetCustomerID() across billing and Stripe app testsAll adjusted call-sites now provide the CustomerID value expected by CreatePendingInvoiceLines, InvoicePendingLines, and CreateInvoiceInput after the refactor. Mocks and assertions remain coherent.
Also applies to: 468-472, 486-494, 1096-1102, 1139-1143, 1148-1154
openmeter/streaming/clickhouse/meter_query_test.go (1)
267-291: LGTM: tests adjusted to []MeterCustomer without changing semanticsProviding concrete customer.Customer values in a []MeterCustomer slice is idiomatic and exercises the new interface shape. Expected SQL remains unchanged.
Also applies to: 307-323
openmeter/billing/service/lineservice/feeline.go (1)
31-33: Signature aligned; no-op appropriate for fee linesThe method matches the updated interface and fee lines don’t need quantity snapshotting. Good to go.
openmeter/billing/service/invoicestate.go (1)
735-735: Use of InvoiceCustomer in snapshot path is correctPassing m.Invoice.Customer aligns with the updated snapshot contract and usage-by-customer flow.
openmeter/meter/httphandler/mapping.go (1)
144-146: Correct adaptation to []MeterCustomerMapping concrete customers to the MeterCustomer interface slice is the right way to satisfy the new type without unsafe conversions.
openmeter/app/httpdriver/customer.go (1)
55-56: Switch to GetCustomerID() is consistent with new APIAll three handlers now populate CustomerID using GetCustomerID(), matching the expected types in requests.
Also applies to: 142-144, 208-209
openmeter/billing/service/lineservice/service.go (1)
217-217: AllSnapshotQuantityimplementations now acceptbilling.InvoiceCustomerVerified across:
feeline.gousagebasedline.gousagebasedlineflat.goservice.goAll implementations match the updated interface signature.
test/billing/collection_test.go (1)
80-80: Tests updated to GetCustomerID()Refactor is consistent and keeps test inputs aligned with the new API.
Also applies to: 170-170, 281-281, 293-293, 335-335, 359-359, 436-436, 461-461
openmeter/ent/db/setorclear.go (1)
772-784: SetOrClearCustomerKey helpers mirror existing patternHelpers are correct and consistent with other fields. Assuming the underlying setters/clearers are generated, this is good to merge.
Confirm that billinginvoice_update.go contains SetCustomerKey/ClearCustomerKey to back these helpers so they won’t be lost on re-generation.
openmeter/ent/db/billinginvoice.go (1)
85-86: CustomerKey field is correctly wired through ent entity, scanner, and stringerThe additions are consistent with ent conventions and the broader schema changes.
Also applies to: 261-263, 472-479, 843-847
openmeter/ent/db/runtime.go (1)
469-486: Approved: BillingInvoice reindexing and migrations are consistent
All artifacts for the newcustomer_keyfield have been verified and align correctly:• Schema update (
openmeter/ent/schema/billing.go) includesfield.String("customer_key").
• Generated code (openmeter/ent/db/billinginvoice/*.go) definesFieldCustomerKey, ordering helpers, and predicates.
• Migration files (tools/migrate/migrations/…_add_billing_invoice_customer_key.up.sql&.down.sql) are present.No further changes required.
openmeter/billing/adapter/invoice.go (1)
674-676: Customer.Key mapping on read path is correctMapping invoice.CustomerKey into InvoiceCustomer.Key matches the new API field. LGTM.
openmeter/billing/service/lineservice/usagebasedline.go (1)
151-165: SnapshotQuantity input change to InvoiceCustomer is consistent and correctSignature change and forwarding Customer in getFeatureUsage align with the broader refactor. No functional issues spotted.
test/app/stripe/appstripe.go (1)
201-205: No remainingcustomer.GetID()calls in Stripe tests
A search forcustomer.GetID()undertest/app/stripereturned no matches. All customer ID references have been migrated toGetCustomerID(). RemainingGetID()calls are on other entities (apps, discounts, etc.) and aren’t impacted by this change. LGTM.test/billing/invoice_test.go (2)
298-307: Expectation includes Customer.Key on InvoiceCustomerThe test now expects Key to be present on invoices, which depends on persisting it at creation. Ensure CreateInvoice sets customer_key (see adapter comment) to keep this test green.
130-136: Adoption of GetCustomerID() in billing tests is consistentI ran a repo-wide search for
.GetID()intest/billing/. All matches refer to other entity types (apps, discounts, versions) and not tocustomerEntity. There are no remaining legacy calls tocustomerEntity.GetID(). LGTM.openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
96-103: Good: signature aligned and initial quantities correctly zeroed
- Accepting billing.InvoiceCustomer matches the interface change across line services.
- Initializing MeteredPreLinePeriodQuantity alongside PreLinePeriodQuantity keeps invariants consistent for flat-fee UBP lines.
No further changes needed here.
openmeter/billing/service/invoice.go (1)
163-166: Defensive nil-check is correct hereThe explicit check for a missing Customer prevents a panic before snapshotting quantities. Good addition.
openmeter/ent/db/billinginvoice/billinginvoice.go (3)
75-76: Expose FieldCustomerKey constantAdding FieldCustomerKey keeps parity with other fields and enables consistent reference in predicates/orderings. Looks good.
236-236: Columns updated to include customer_keyIncluding FieldCustomerKey in Columns is correct and aligns with schema.go. No issues.
467-470: Order helper ByCustomerKey added — OKByCustomerKey mirrors existing order helpers. Consider also exposing predicates in where.go for equality and IS NULL/NOT NULL checks if not already present.
If not already added, I can generate the where.go predicates for CustomerKey (EQ, NEQ, IsNil, NotNil). Want me to open a follow-up?
openmeter/billing/service/lineservice/meters.go (2)
38-40: Validation improved: customer validation is enforcedWrapping the error provides useful context. This is correct and keeps the API surface consistent after the shift to MeterCustomer.
59-62: Pointer conversion isn’t needed—InvoiceCustomer value already satisfies MeterCustomer
All methods in the MeterCustomer interface use value receivers, and InvoiceCustomer implements them on the value type, so passingin.Customer(not&in.Customer) correctly satisfies the interface.• openmeter/customer/customer.go:15–19 defines MeterCustomer with only value‐receiver methods.
• openmeter/billing/invoice.go:600–614 implements GetID/GetKey/GetUsageAttribution on(i InvoiceCustomer).No change required.
Likely an incorrect or invalid review comment.
openmeter/streaming/clickhouse/meter_query.go (1)
26-26: LGTM! Proper interface adoption for customer filtering.The migration from concrete
customer.Customertocustomer.MeterCustomerinterface is well-implemented, enabling polymorphic usage across different customer types (e.g., InvoiceCustomer). The accessor method pattern follows Go best practices for interfaces.Also applies to: 205-210, 311-311
openmeter/ent/db/billinginvoice_update.go (1)
487-505: Generated code looks correct for CustomerKey field operations.The auto-generated ent code properly implements the CustomerKey field with standard Set/SetNillable/Clear methods, consistent with other optional fields in the BillingInvoice entity.
Also applies to: 1187-1192, 1881-1899, 2611-2616
openmeter/billing/invoice.go (4)
572-585: Excellent use of compile-time interface assertion and proper snapshot creation.The compile-time assertion
var _ customer.MeterCustomer = &InvoiceCustomer{}ensures interface compliance at compile time, preventing runtime errors. TheNewInvoiceCustomerconstructor correctly creates an immutable snapshot of customer data for invoicing purposes.
587-596: Well-structured InvoiceCustomer with proper field ordering.The addition of the optional
Keyfield follows the existing patterns and maintains consistency with thecustomer.Customerstructure. The documentation clearly explains the snapshot nature of this struct.
598-614: Clean MeterCustomer interface implementation.The accessor methods correctly implement the
customer.MeterCustomerinterface, providing a consistent API for meter queries to access customer data regardless of the concrete type.
616-631: Robust validation logic for InvoiceCustomer fields.The updated validation correctly enforces:
- Required
CustomerIDfield- Optional but non-empty
Keyfield (prevents empty string keys)- Required
NamefieldThis ensures data integrity at the domain level.
openmeter/ent/db/mutation.go (10)
11369-11375: Add mutation state for customer_key — consistent with schemaThe new customer_key field in the mutation struct aligns with billinginvoice.FieldCustomerKey (see openmeter/ent/db/billinginvoice/billinginvoice.go:75). Placement and naming follow existing patterns.
14247-14247: Preallocation bump for Fields()Capacity updated to 55 to account for the new field. Good to keep preallocations in sync.
14332-14334: Include customer_key in mutated Fields()Correctly appends FieldCustomerKey when set in the mutation.
14477-14479: Expose customer_key via Field(name)Switch case returns CustomerKey() as expected for string fields.
14596-14598: Expose previous value via OldField(name)OldCustomerKey(ctx) routed correctly for FieldCustomerKey. Matches pattern used by other fields.
14855-14861: SetField: type-safe assignment for customer_keyType assertion to string and delegation to SetCustomerKey is correct and consistent with other string fields.
15125-15127: ClearedFields(): include customer_key when clearedProperly surfaces the cleared state for this optional field.
15235-15237: ClearField routing for customer_keyClearCustomerKey invoked for FieldCustomerKey. Matches established pattern.
15372-15374: ResetField routing for customer_keyResetCustomerKey hooked into ResetField switch. Consistent with other optional fields.
12750-12798: customer_key wiring fully implemented and verified
All create/update builders, mutation methods, query predicates, and the migration script includecustomer_key, mirroring the patterns forsupplier_tax_code. No further changes needed.Key verifications:
- ent/db/billinginvoice_update.go & billinginvoice_create.go: Set/Clear/SetNillable/Upsert methods for
CustomerKey.- ent/db/mutation.go: ClearCustomerKey, CustomerKeyCleared, ResetCustomerKey, OldCustomerKey.
- ent/db/billinginvoice/billinginvoice.go: FieldCustomerKey constant and scan logic.
- ent/db/billinginvoice/where.go & order.go: All CustomerKey predicates and
ByCustomerKey.- tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql (and corresponding down script).
openmeter/billing/service/invoiceline.go (3)
309-311: Passing full customer object to snapshot is correct and aligns with the new APISwitching to invoice.Customer here matches the updated lineservice.SnapshotQuantity(ctx, customer) contract and removes reliance on subject keys. Looks good.
345-347: Line snapshotting against billing.InvoiceCustomerForwarding the full customer object here is consistent with the updated line.SnapshotQuantity signature. Good change.
394-396: SnapshotLineQuantity: correct propagation of input.Invoice.CustomerUpdated call site matches the new API and keeps the single-line snapshot path aligned with the bulk path.
openmeter/ent/db/billinginvoice_create.go (5)
348-360: Create builder setters for customer_key look correctSetCustomerKey and SetNillableCustomerKey mirror ent’s generated patterns for optional string fields. No issues.
1056-1059: CreateSpec writes customer_key correctly (optional pointer field)Field assignment matches schema: use FieldCustomerKey with TypeString and set _node.CustomerKey = &value. Good.
1740-1756: Upsert builder: Set/Update/Clear for customer_keyThe upsert mutation helpers for customer_key are complete and consistent with other optional fields.
2637-2656: UpsertOne helper methods for customer_keyCorrect forwarding to the underlying Upsert setters. Matches generator conventions.
3758-3777: UpsertBulk helper methods for customer_keyBulk upsert helpers are present and consistent with single-node upsert APIs.
openmeter/ent/db/billinginvoice/where.go (2)
209-213: Alias predicate CustomerKey addedCustomerKey(v string) aligns with the established pattern (alias to EQ). No problems spotted.
2038-2111: Full predicate set for customer_key is complete and consistentEQ/NEQ/In/NotIn/GT/GTE/LT/LTE/Contains/HasPrefix/HasSuffix/IsNil/NotNil/EqualFold/ContainsFold are all present for an optional string field. Looks good.
5f42f3b to
4a50554
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
🔭 Outside diff range comments (5)
openmeter/streaming/clickhouse/meter_query.go (1)
182-186: Potential runtime error: group by customer_id without selecting itYou add "customer_id" to groupByColumns (Lines 182-186) but only SELECT it when len(FilterCustomer) > 0 (Lines 198-222). If a caller sets GroupBy to include "customer_id" with an empty FilterCustomer, the query will not select that column, causing inconsistent SELECT/GROUP BY shape and scan errors.
Guard early:
@@ func (d *queryMeter) toSQL() (string, []interface{}, error) { - // (existing code above) + // Validate that if grouping/filtering by customer_id, we can actually produce the column + if slices.Contains(d.GroupBy, "customer_id") && len(d.FilterCustomer) == 0 { + return "", nil, fmt.Errorf("groupBy 'customer_id' requires FilterCustomer to be set") + } + if vals, ok := d.FilterGroupBy["customer_id"]; ok && len(vals) > 0 && len(d.FilterCustomer) == 0 { + return "", nil, fmt.Errorf("filter by 'customer_id' requires FilterCustomer to be set") + }Alternatively, always SELECT a constant empty customer_id when FilterCustomer is empty, but rejecting early is clearer and safer.
Also applies to: 198-222
openmeter/billing/service/invoicestate.go (1)
726-728: Possible nil dereference on CollectionAtclock.Now().Before(*m.Invoice.CollectionAt) will panic if CollectionAt is nil.
Fix:
- if m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) { + if m.Invoice.CollectionAt != nil && m.Invoice.QuantitySnapshotedAt == nil && clock.Now().Before(*m.Invoice.CollectionAt) { return nil }openmeter/billing/adapter/invoice.go (1)
275-365: Missing: snapshot Customer.Key on invoice creationPer the PR goal to snapshot Customer.Key to InvoiceCustomer, CreateInvoice does not persist CustomerKey. Add it during creation.
Add after setting CustomerName:
createMut = createMut.SetNillableCustomerKey(customer.Key)Full context (around where CustomerName is set):
createMut = createMut. SetCustomerName(customer.Name). SetNillableCustomerKey(customer.Key)openmeter/billing/service/invoiceline.go (2)
59-59: Rename misspelled function across its definition and all call sitesThe helper is consistently defined and called as
transcationForInvoiceManipulationbut appears to contain a typo. To improve clarity and prevent future confusion, rename it totransactionForInvoiceManipulationand update every occurrence:• openmeter/billing/service/service.go:154
– Changefunc transcationForInvoiceManipulation[…]to
func transactionForInvoiceManipulation[…]
• openmeter/billing/service/invoiceline.go:59
– Update the call from
transcationForInvoiceManipulation(ctx, …)
to
transactionForInvoiceManipulation(ctx, …)Be sure to run a global search for
transcationForInvoiceManipulationto catch any remaining references and adjust imports or tests as needed.
319-369: Refactor snapshotLineQuantitiesInParallel: ensure at least one worker & avoid parameter shadowingThe service is already on Go 1.24.1, so
for range <int>is supported. We still need to guard against zero workers (which would skip all snapshots) and prevent thecustomerparameter from shadowing the importedcustomerpackage.Please update
openmeter/billing/service/invoiceline.goas follows:
- Change the function signature to rename
customer→invCustomer.- Compute
workers := s.maxParallelQuantitySnapshotsand default to 1 if ≤ 0.- Use a classic
for i := 0; i < workers; i++loop instead of ranging over the raw int.- Swap all references of the old
customerparameter toinvCustomer.-func (s *Service) snapshotLineQuantitiesInParallel(ctx context.Context, customer billing.InvoiceCustomer, lines lineservice.Lines) error { +func (s *Service) snapshotLineQuantitiesInParallel(ctx context.Context, invCustomer billing.InvoiceCustomer, lines lineservice.Lines) error { linesCh := make(chan lineservice.Line, len(lines)) errCh := make(chan error, len(lines)) doneCh := make(chan struct{}) // Feed the channel for _, line := range lines { linesCh <- line } close(linesCh) - // Start workers - for range s.maxParallelQuantitySnapshots { + // Determine number of workers (at least 1) + workers := s.maxParallelQuantitySnapshots + if workers <= 0 { + workers = 1 + } + // Start workers + for i := 0; i < workers; i++ { go func() { defer func() { if r := recover(); r != nil { errCh <- fmt.Errorf("snapshotting line quantity: %v", r) } doneCh <- struct{}{} }() for line := range linesCh { if ctx.Err() != nil { errCh <- ctx.Err() return } - if err := line.SnapshotQuantity(ctx, customer); err != nil { + if err := line.SnapshotQuantity(ctx, invCustomer); err != nil { errCh <- fmt.Errorf("line[%s]: snapshotting quantity: %w", line.ID(), err) } } }() } - // Wait for all workers to finish - for range s.maxParallelQuantitySnapshots { + // Wait for all workers to finish + for i := 0; i < workers; i++ { <-doneCh } close(errCh) // ... rest unchanged ...
🧹 Nitpick comments (12)
openmeter/app/stripe/entity/app/customer.go (1)
21-21: Use of GetCustomerID is correct; minor readability nitThe accessor change is correct. Minor nit: the parameter name customer shadows the imported customer package, which can reduce readability in larger functions. Consider renaming the parameter (e.g., c or cus) to avoid shadowing.
openmeter/customer/customer.go (1)
14-22: Interface introduction is sound; clarify ID semantics in docMeterCustomer cleanly abstracts the minimal identity and attribution needed for meters, and the compile-time assertion adds safety. Given the prior semantic of GetID returning a namespaced ID, consider strengthening the comment to explicitly state that GetID returns only the raw ID string (not namespaced), and use GetCustomerID() for the namespaced identity. This helps avoid confusion for consumers migrating code.
openmeter/meter/httphandler/mapping.go (1)
144-146: Map to []MeterCustomer: consider avoiding lo.Map for a tiny allocation winOptional: replace lo.Map with a simple preallocated loop to avoid a functional allocation and keep dependencies minimal.
Apply:
- params.FilterCustomer = lo.Map(filterCustomer, func(c customer.Customer, _ int) customer.MeterCustomer { - return c - }) + params.FilterCustomer = make([]customer.MeterCustomer, len(filterCustomer)) + for i := range filterCustomer { + params.FilterCustomer[i] = filterCustomer[i] + }openmeter/customer/httpdriver/customer.go (1)
374-377: Nit: operation name mismatchThis handler returns an entitlement value but uses operation name "getCustomer". Consider renaming to "getCustomerEntitlementValue" for observability/trace clarity.
openmeter/streaming/clickhouse/meter_query.go (2)
203-214: Avoid variable shadowing and dedupe subject keys to keep SQL lean
- The loop variable named customer shadows the imported package; rename to c for clarity.
- Dedupe subject keys to avoid redundant OR clauses and bloated CASE expressions.
Apply:
- for _, customer := range d.FilterCustomer { - for _, subjectKey := range customer.GetUsageAttribution().SubjectKeys { + for _, c := range d.FilterCustomer { + for _, subjectKey := range c.GetUsageAttribution().SubjectKeys { str := fmt.Sprintf( "WHEN %s = '%s' THEN '%s' ", getColumn("subject"), sqlbuilder.Escape(subjectKey), - sqlbuilder.Escape(customer.GetID()), + sqlbuilder.Escape(c.GetID()), ) caseBuilder.WriteString(str) } }And (see subjectWhere below) dedupe subjects before building the WHERE.
310-315: Dedupe subjects to reduce redundant OR predicatessubjects may contain duplicates across customers. Use lo.Uniq to shrink the predicate set.
- var subjects []string - for _, customer := range d.FilterCustomer { - subjects = append(subjects, customer.GetUsageAttribution().SubjectKeys...) - } - query = query.Where(query.Or(slicesx.Map(subjects, mapFunc)...)) + var subjects []string + for _, c := range d.FilterCustomer { + subjects = append(subjects, c.GetUsageAttribution().SubjectKeys...) + } + subjects = lo.Uniq(subjects) + query = query.Where(query.Or(slicesx.Map(subjects, mapFunc)...))test/app/custominvoicing/invocing_test.go (1)
1-1: Nit: filename typoConsider renaming invocing_test.go to invoicing_test.go.
openmeter/app/stripe/httpdriver/customer.go (1)
71-74: Nit: ID vs Id namingPublic fields in Go commonly use “ID” not “Id”. Consider normalizing CustomerId/customerId to CustomerID for consistency (non-blocking).
Also applies to: 151-154
openmeter/streaming/clickhouse/meter_query_test.go (1)
307-319: Same pointer preference here for MeterCustomerUse pointers to ensure interface conformance and avoid struct copies.
- FilterCustomer: []customer.MeterCustomer{ - customer.Customer{ + FilterCustomer: []customer.MeterCustomer{ + &customer.Customer{openmeter/billing/invoice.go (1)
616-625: Stricter validation is good; minor naming nit
- Enforcing non-empty CustomerID and non-empty Key when provided is appropriate.
- Nit: In NewInvoiceCustomer, consider renaming the parameter from “customer customer.Customer” to “c customer.Customer” to avoid shadowing the imported package name and improve readability.
Example:
func NewInvoiceCustomer(c customer.Customer) InvoiceCustomer { return InvoiceCustomer{ Key: c.Key, CustomerID: c.ID, Name: c.Name, BillingAddress: c.BillingAddress, UsageAttribution: c.UsageAttribution, } }test/billing/invoice_test.go (1)
128-155: Consider a small test helper to reduce repetition.There are many similar CreatePendingInvoiceLines/InvoicePendingLines inputs differing only in a few fields. A small helper (e.g., makePendingLinesInput(ns, custID, currency, lines ...)) would improve test readability and reduce duplication.
Also applies to: 455-492, 630-668, 1403-1416, 2324-2350, 3322-3350, 3441-3467, 3597-3635, 3691-3746, 3801-3848, 3929-3956, 3962-4006, 4041-4096
openmeter/billing/service/invoiceline.go (1)
24-29: Remove duplicate line field initialization.Namespace/Status/Currency are set twice (pre-loop and again in FromEntities mapper). Keep one; suggest removing the mapper duplication to avoid drift.
Apply within the mapper:
- lineServices, err := s.lineService.FromEntities(lo.Map(input.Lines, func(l *billing.Line, _ int) *billing.Line { - l.Namespace = input.Customer.Namespace - l.Status = billing.InvoiceLineStatusValid - l.Currency = input.Currency - - return l - })) + lineServices, err := s.lineService.FromEntities(lo.Map(input.Lines, func(l *billing.Line, _ int) *billing.Line { + return l + }))Also applies to: 61-66
📜 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 (50)
openmeter/app/httpdriver/customer.go(3 hunks)openmeter/app/stripe/adapter/stripe.go(1 hunks)openmeter/app/stripe/entity/app/customer.go(1 hunks)openmeter/app/stripe/httpdriver/checkout_session.go(1 hunks)openmeter/app/stripe/httpdriver/customer.go(3 hunks)openmeter/billing/adapter/invoice.go(2 hunks)openmeter/billing/httpdriver/invoice_test.go(1 hunks)openmeter/billing/invoice.go(1 hunks)openmeter/billing/service/invoice.go(2 hunks)openmeter/billing/service/invoiceline.go(4 hunks)openmeter/billing/service/invoicestate.go(1 hunks)openmeter/billing/service/lineservice/feeline.go(1 hunks)openmeter/billing/service/lineservice/meters.go(4 hunks)openmeter/billing/service/lineservice/service.go(1 hunks)openmeter/billing/service/lineservice/usagebasedline.go(2 hunks)openmeter/billing/service/lineservice/usagebasedlineflat.go(1 hunks)openmeter/billing/worker/subscription/sync_test.go(12 hunks)openmeter/customer/customer.go(2 hunks)openmeter/customer/httpdriver/customer.go(3 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(1 hunks)openmeter/meter/httphandler/mapping.go(1 hunks)openmeter/productcatalog/subscription/http/get.go(1 hunks)openmeter/streaming/clickhouse/meter_query.go(3 hunks)openmeter/streaming/clickhouse/meter_query_test.go(3 hunks)openmeter/streaming/query_params.go(1 hunks)openmeter/subscription/service/service.go(1 hunks)openmeter/subscription/service/service_test.go(2 hunks)test/app/custominvoicing/invocing_test.go(4 hunks)test/app/stripe/appstripe.go(16 hunks)test/app/stripe/fixture.go(1 hunks)test/app/stripe/invoice_test.go(6 hunks)test/billing/collection_test.go(8 hunks)test/billing/customeroverride_test.go(1 hunks)test/billing/discount_test.go(6 hunks)test/billing/invoice_test.go(38 hunks)test/billing/subscription_test.go(3 hunks)test/billing/suite.go(1 hunks)test/billing/tax_test.go(4 hunks)test/billing/ubpflatfee_test.go(7 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.down.sql(1 hunks)tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql(1 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:
test/billing/ubpflatfee_test.gotest/billing/invoice_test.go
🧬 Code Graph Analysis (43)
openmeter/billing/httpdriver/invoice_test.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/app/stripe/fixture.go (2)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
openmeter/billing/service/lineservice/service.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/productcatalog/subscription/http/get.go (1)
openmeter/customer/customer.go (1)
CustomerID(112-112)
openmeter/subscription/service/service.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
test/billing/tax_test.go (2)
api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/billing/customeroverride_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/billingcustomeroverride/where.go (1)
CustomerID(91-93)
openmeter/app/stripe/httpdriver/customer.go (4)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)api/client/javascript/src/client/schemas.ts (1)
CustomerId(10830-10830)api/client/go/client.gen.go (1)
CustomerId(2109-2112)
openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/customer/httpdriver/customer.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/customersubjects/where.go (1)
CustomerID(64-66)
openmeter/billing/service/lineservice/feeline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
test/billing/suite.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/billinginvoice_update.go (5)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
test/app/stripe/appstripe.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/app/app.go (1)
GetAppInstanceCustomerDataInput(37-39)
test/billing/subscription_test.go (1)
openmeter/billing/customeroverride.go (2)
CustomerOverride(19-33)GetCustomerOverrideInput(167-170)
openmeter/ent/db/billinginvoice/billinginvoice.go (1)
openmeter/ent/db/customer/customer.go (1)
OrderOption(153-153)
openmeter/ent/db/runtime.go (1)
openmeter/ent/db/billinginvoice/billinginvoice.go (4)
CustomerNameValidator(291-291)CustomerIDValidator(293-293)SourceBillingProfileIDValidator(295-295)CurrencyValidator(297-297)
openmeter/app/httpdriver/customer.go (4)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)api/client/javascript/src/client/schemas.ts (1)
CustomerId(10830-10830)api/client/go/client.gen.go (1)
CustomerId(2109-2112)
openmeter/streaming/query_params.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
openmeter/billing/service/lineservice/usagebasedline.go (1)
openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)
openmeter/streaming/clickhouse/meter_query.go (1)
openmeter/customer/customer.go (1)
MeterCustomer(15-19)
openmeter/subscription/service/service_test.go (3)
openmeter/customer/customer.go (1)
CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)openmeter/ent/db/subscription/where.go (1)
CustomerID(116-118)
test/billing/ubpflatfee_test.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/setorclear.go (1)
openmeter/ent/db/billinginvoice_update.go (2)
BillingInvoiceUpdate(25-29)BillingInvoiceUpdateOne(1424-1429)
openmeter/billing/service/invoicestate.go (1)
openmeter/customer/customer.go (1)
Customer(24-34)
test/billing/discount_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/client/javascript/src/client/schemas.ts (1)
Customer(10821-10821)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/billing/worker/subscription/sync_test.go (5)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)openmeter/ent/db/predicate/predicate.go (1)
Customer(153-153)
test/billing/collection_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)tools/migrate/testdata/sqlcgen/20250703081943/db/models.go (1)
Customer(401-420)api/client/go/client.gen.go (1)
Customer(1986-2036)
openmeter/ent/db/billinginvoice/where.go (3)
openmeter/ent/db/billinginvoice.go (2)
BillingInvoice(25-143)BillingInvoice(253-270)openmeter/ent/schema/billing.go (5)
BillingInvoice(818-820)BillingInvoice(822-837)BillingInvoice(839-976)BillingInvoice(978-990)BillingInvoice(992-1034)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/adapter/invoice.go (7)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerKey(127-130)api/client/javascript/src/client/schemas.ts (2)
Customer(10821-10821)CustomerKey(10831-10831)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/ent/schema/customer.go (5)
Customer(17-19)Customer(21-29)Customer(31-39)Customer(41-54)Customer(56-68)api/client/go/client.gen.go (2)
Customer(1986-2036)CustomerKey(2115-2117)openmeter/ent/db/customer/where.go (1)
Key(137-139)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)
openmeter/ent/db/billinginvoice_create.go (7)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/api.gen.go (1)
CustomerKey(2285-2287)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)pkg/set/set.go (1)
Set(5-8)
test/app/stripe/invoice_test.go (2)
openmeter/customer/customer.go (2)
Customer(24-34)CustomerID(112-112)openmeter/ent/db/billinginvoice/where.go (1)
CustomerID(230-232)
openmeter/ent/db/mutation.go (6)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/api.gen.go (1)
CustomerKey(2285-2287)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/streaming/clickhouse/meter_query_test.go (1)
openmeter/customer/customer.go (2)
MeterCustomer(15-19)Customer(24-34)
openmeter/billing/service/invoice.go (2)
openmeter/customer/customer.go (1)
Customer(24-34)openmeter/billing/invoice.go (1)
NewInvoiceCustomer(577-585)
openmeter/customer/customer.go (2)
openmeter/billing/invoice.go (1)
CustomerUsageAttribution(565-565)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)
openmeter/billing/service/invoiceline.go (2)
api/client/go/client.gen.go (2)
Customer(1986-2036)Invoice(3035-3149)openmeter/billing/invoice.go (2)
InvoiceCustomer(590-596)Invoice(330-341)
test/app/custominvoicing/invocing_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)api/api.gen.go (1)
Customer(2156-2206)api/client/go/client.gen.go (1)
Customer(1986-2036)
test/billing/invoice_test.go (3)
openmeter/customer/customer.go (1)
Customer(24-34)openmeter/ent/db/customer.go (2)
Customer(20-64)Customer(131-146)openmeter/ent/schema/customer.go (5)
Customer(17-19)Customer(21-29)Customer(31-39)Customer(41-54)Customer(56-68)
openmeter/ent/db/billinginvoice.go (6)
openmeter/customer/customer.go (1)
CustomerKey(127-130)openmeter/ent/db/billinginvoice/where.go (1)
CustomerKey(210-212)api/client/javascript/src/client/schemas.ts (1)
CustomerKey(10831-10831)api/api.gen.go (1)
CustomerKey(2285-2287)api/client/go/client.gen.go (1)
CustomerKey(2115-2117)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldCustomerKey(76-76)
openmeter/billing/service/lineservice/meters.go (3)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)openmeter/billing/invoice.go (1)
InvoiceCustomer(590-596)openmeter/billing/invoiceline.go (1)
Period(82-85)
openmeter/meter/httphandler/mapping.go (1)
openmeter/customer/customer.go (2)
Customer(24-34)MeterCustomer(15-19)
openmeter/billing/invoice.go (3)
openmeter/customer/customer.go (3)
MeterCustomer(15-19)Customer(24-34)CustomerUsageAttribution(163-165)api/client/go/client.gen.go (3)
Customer(1986-2036)Address(891-912)CustomerUsageAttribution(2171-2174)pkg/models/model.go (1)
Address(192-200)
🔇 Additional comments (78)
openmeter/subscription/service/service_test.go (2)
102-102: Correct migration to GetCustomerIDUsing cust.GetCustomerID() matches UpdateCustomerInput.CustomerID’s expected type and aligns with the repo-wide API change.
147-147: Correct migration to GetCustomerIDConsistent with the new accessor; no functional risks introduced.
openmeter/subscription/service/service.go (1)
482-482: LGTM: UpdateCustomer now receives CustomerID via GetCustomerIDThis is the correct accessor post-migration and respects the non-nil customer precondition above. No behavior change beyond the accessor.
openmeter/customer/customer.go (4)
36-41: GetID() implementation is correctReturns the raw ID string, matching the new MeterCustomer contract and intended usage in meter queries.
42-47: GetKey() implementation is correctReturns the optional key pointer; aligns with the interface and existing struct field semantics.
48-53: GetUsageAttribution() implementation is correctSimple pass-through; no issues.
54-63: GetCustomerID() convenience method looks goodConstructs a proper namespaced CustomerID from the struct. This is the right replacement for prior GetID usages that expected a namespaced identifier.
openmeter/productcatalog/subscription/http/get.go (1)
102-102: Correct migration to GetCustomerIDUsing cus.GetCustomerID() to populate ListCustomerSubscriptionsRequest.CustomerID aligns with the new API and downstream List call which uses Namespace and ID as strings.
openmeter/billing/worker/subscription/sync_test.go (1)
501-506: LGTM: Move to Customer.GetCustomerID() matches new input typesAll these call sites now pass customer.CustomerID, aligning with CreatePendingInvoiceLinesInput/InvoicePendingLinesInput.Customer. Consistent and correct across scenarios.
Also applies to: 520-522, 547-549, 1265-1267, 1435-1437, 2609-2611, 2974-2976, 3010-3012, 3301-3303
openmeter/ent/db/migrate/schema.go (1)
618-651: Column index shifts for FKs and indexes appear correct after insertionThe references to BillingInvoicesColumns were bumped to account for the inserted column. This looks internally consistent for:
- Foreign keys to apps/profile/workflow/customer
- Indexes (namespace_customer_id, namespace_status, status_details_cache)
Please re-generate ent code and run a quick migration diff to ensure no missed references remain.
Also applies to: 670-689
test/billing/customeroverride_test.go (1)
467-469: LGTM: GetCustomerApp now receives CustomerIDSwitching to cust.GetCustomerID() matches the updated GetCustomerAppInput contract.
test/app/stripe/fixture.go (1)
124-127: LGTM: UpsertCustomerData uses GetCustomerID()The app UpsertCustomerData now receives a namespaced CustomerID. Matches the new ID model.
test/billing/suite.go (1)
334-338: LGTM: CreatePendingInvoiceLines uses GetCustomerID()The helper now passes a namespaced customer identifier, consistent with input type changes.
openmeter/billing/httpdriver/invoice_test.go (1)
55-58: LGTM: Gathering invoice test updated to GetCustomerID()This aligns the test with the new contract on CreatePendingInvoiceLinesInput.
openmeter/app/httpdriver/customer.go (1)
54-56: LGTM: HTTP handlers now use Customer.GetCustomerID()
- ListCustomerData: req.CustomerID set via cus.GetCustomerID()
- UpsertCustomerData: CustomerId populated via cus.GetCustomerID()
- DeleteCustomerData: CustomerID populated via cus.GetCustomerID()
These match the service layer’s new identity type and keep namespace intact.
Also applies to: 141-143, 207-209
openmeter/app/stripe/adapter/stripe.go (1)
389-389: Confirmed: targetCustomer is always set by input.Validate()The
Validate()implementation inopenmeter/app/stripe/entity/input.go(lines 308–336) enforces that exactly one ofCreateCustomerInputorCustomerIDis non-nil (mutually exclusive and at least one required). Sinceadapter.CreateCheckoutSessioncallsinput.Validate()before branching oninput.CustomerIDandinput.CreateCustomerInput,targetCustomeris guaranteed to be initialized in exactly one of those blocks and never nil when callingtargetCustomer.GetCustomerID().test/billing/discount_test.go (1)
88-88: Tests updated to use GetCustomerID() — LGTMThe switch to passing CustomerID aligns with the API changes.
Also applies to: 137-137, 283-283, 329-329, 370-370, 414-414
test/billing/ubpflatfee_test.go (1)
59-59: Consistent migration to GetCustomerID() in testsChanges are correct and consistent with the new identity model.
Also applies to: 90-90, 103-103, 185-185, 239-239, 265-265
openmeter/billing/service/lineservice/feeline.go (1)
31-33: Signature updated to InvoiceCustomer — OKNo-op SnapshotQuantity for fee lines makes sense; parameters anonymous to avoid unused warnings. Consistent with the interface change.
openmeter/streaming/query_params.go (1)
17-17: FilterCustomer now []MeterCustomer — downstream usage validated
Verified that all references in openmeter/streaming query builders only call MeterCustomer.GetID() and GetUsageAttribution(), and no other methods (e.g. GetKey) are used. No further updates required.test/billing/tax_test.go (1)
205-205: Adopt GetCustomerID() in tax tests — LGTMConsistent with the new customer ID flow.
Also applies to: 247-247, 275-275, 300-300
openmeter/customer/httpdriver/customer.go (3)
208-211: Switch to GetCustomerID is correct hereUsing cus.GetCustomerID() aligns with the new API and expected type for UpdateCustomerInput.CustomerID.
360-363: Correct: entitlement query now uses GetCustomerIDThe change to pass CustomerID is consistent with the refactor.
261-261: Ignore nonexistentDeleteCustomerRequestalias
I searched the repo and did not find anyDeleteCustomerRequesttype—onlyDeleteCustomerInput. In the customer package that input is correctly aliased toCustomerID, so returningcus.GetCustomerID()is valid. You can disregard this feedback.Likely an incorrect or invalid review comment.
openmeter/streaming/clickhouse/meter_query.go (1)
26-26: Type change to []customer.MeterCustomer is aligned with new interfaceField type update looks correct and consistent with the broader migration.
openmeter/ent/schema/billing.go (1)
849-852: No immediate index needed for customer_key
Thecustomer_keyfield is optional and nullable and is only set/cleared (e.g. in openmeter/billing/adapter/invoice.go), but there are currently no queries filtering or ordering by it. We can hold off on adding an index—if you later introduce invoice lookups bycustomer_key, add a composite index on(namespace, customer_key)at that time.test/app/custominvoicing/invocing_test.go (4)
167-169: Tests updated to use GetCustomerID — goodChange aligns with the new input type for CreatePendingInvoiceLinesInput.Customer.
223-226: LGTM: InvoicePendingLinesInput now uses CustomerIDConsistent with the refactor.
335-337: LGTM: CreatePendingInvoiceLines uses CustomerIDConsistent with earlier changes.
361-364: LGTM: InvoicePendingLines uses CustomerIDRefactor consistency maintained.
openmeter/billing/service/lineservice/service.go (1)
215-219: SnapshotQuantity signature update is applied correctly
All implementations and call sites now use
SnapshotQuantity(ctx context.Context, customer billing.InvoiceCustomer)
No remaining references to the old signature were found.• Implementer:
– openmeter/billing/service/lineservice/usagebasedline.go:151
• Call sites:
– openmeter/billing/service/invoiceline.go:345–347
– openmeter/billing/service/invoiceline.go:394–396openmeter/app/stripe/httpdriver/customer.go (3)
55-56: GetCustomerStripeAppData now uses CustomerID — correctType-safe and aligned with billing.GetCustomerApp signature.
112-115: Upsert path updated to CustomerId = GetCustomerID — correctMatches GetCustomerApp and UpsertCustomerData expectations.
189-191: Portal session creation now uses CustomerID — correctConsistent with service.CreatePortalSession inputs.
openmeter/billing/service/invoicestate.go (1)
735-736: Passing full InvoiceCustomer to snapshot is correctMatches new snapshotLineQuantitiesInParallel signature and unifies customer context.
openmeter/billing/service/lineservice/usagebasedlineflat.go (1)
96-103: Signature updated; unused param intentionally unnamed — goodSnapshotQuantity correctly sets fixed quantities for flat-fee UBP; the unnamed customer param avoids lints.
openmeter/ent/db/setorclear.go (1)
772-784: Add SetOrClearCustomerKey wrappers — consistent and correctMatches existing SetOrClear pattern: nil clears via ClearCustomerKey(), non-nil sets via SetCustomerKey(*v). No issues.
test/billing/collection_test.go (1)
79-79: Switch to GetCustomerID() is correct and aligns with typed APIInputs now expect customer.CustomerID; using customer.GetCustomerID() ensures type-safety across CreatePendingInvoiceLines/InvoicePendingLines.
Also applies to: 170-170, 281-281, 293-293, 335-335, 359-359, 436-436, 460-460
openmeter/app/stripe/httpdriver/checkout_session.go (1)
93-93: Use cus.GetCustomerID() when resolving customer by key — goodConverts to pointer with lo.ToPtr for downstream request; consistent with the rest of the handler.
test/billing/subscription_test.go (1)
273-273: Update tests to GetCustomerID() — correct refactorGetCustomerOverrideInput expects customer.CustomerID; updates ensure compile-time safety and clarity.
Also applies to: 282-282, 290-290, 299-299
test/app/stripe/invoice_test.go (1)
294-294: CustomerID accessor changes look goodAll call sites now pass a typed customer.CustomerID, matching service interfaces and mocks.
Also applies to: 470-470, 489-489, 1098-1098, 1141-1141, 1152-1152, 1512-1512
test/app/stripe/appstripe.go (1)
201-201: Consistent migration to GetCustomerID() across app/stripe testsAll updated inputs/expectations now use the typed CustomerID. Matches app and service APIs.
Also applies to: 215-215, 245-245, 255-255, 276-276, 304-304, 333-333, 345-345, 356-356, 366-366, 375-375, 389-389, 403-403, 643-643, 673-673, 737-737, 761-761
openmeter/ent/db/billinginvoice.go (2)
85-86: Add CustomerKey column to BillingInvoice — integration looks complete
- Struct field added with proper json tag.
- scanValues/assignValues handle sql.NullString for customer_key.
- String() emits customer_key when present.
Assuming matching ent descriptors/migrations are included, this is good.
Also applies to: 261-263, 472-478, 843-847
85-86: Migration and ent schema wiring for customer_key verifiedAll necessary updates for the new
customer_keyfield are in place:
- tools/migrate/migrations/20250811130613_add_billing_invoice_customer_key.up.sql & .down.sql add/drop the column.
- openmeter/ent/db/migrate/schema.go (line 582) includes
{Name: "customer_key", Type: field.TypeString, Nullable: true}.- openmeter/ent/db/billinginvoice.go defines
FieldCustomerKey = "customer_key"and the struct field.- openmeter/ent/db/billinginvoice/where.go provides all predicates for
customer_key.No further action needed.
openmeter/billing/service/lineservice/meters.go (1)
11-11: Refactor usage queries to use InvoiceCustomer/MeterCustomer — correct and safer
- Importing customer and switching to FilterCustomer aligns with the new interface.
- Validate now defers to Customer.Validate(), replacing ad-hoc subject checks.
- QueryParams From/To unchanged; copies for pre-line computations remain correct.
Looks good.
Also applies to: 21-21, 38-40, 59-62
openmeter/billing/service/lineservice/usagebasedline.go (1)
151-175: Switch to InvoiceCustomer for usage resolution looks goodSignature and input refactor are consistent with the broader PR; passing Customer into getFeatureUsage is correct.
openmeter/ent/db/billinginvoice/billinginvoice.go (1)
75-77: CustomerKey integration in generated model is consistent
- FieldCustomerKey constant added
- Columns updated to include FieldCustomerKey
- ByCustomerKey OrderOption added
All align with schema changes and expected Ent patterns.
Also applies to: 236-236, 467-471
openmeter/ent/db/runtime.go (1)
469-486: Generated descriptor index shifts look correctIndex adjustments for CustomerName, CustomerID, SourceBillingProfileID, Currency, CollectionAt match the insertion of customer_key. No issues.
openmeter/streaming/clickhouse/meter_query_test.go (1)
267-291: No change needed:customer.CustomersatisfiesMeterCustomervia value receiversThe
GetIDandGetCustomerIDmethods onCustomerare defined with value receivers, so bothCustomervalues and*Customerpointers satisfy thecustomer.MeterCustomerinterface. Using a value literal here is correct and does not prevent interface implementation. You can safely ignore the suggested pointer conversion.Likely an incorrect or invalid review comment.
openmeter/billing/adapter/invoice.go (2)
502-507: Update path handles CustomerKey correctlySet/Clear for CustomerKey is correct and reversible. Good.
674-689: Mapping Customer.Key from DB is correctInvoiceCustomer.Key <- invoice.CustomerKey mapping is consistent.
openmeter/billing/service/invoice.go (2)
163-166: Guarding against nil customer profileGood defensive check to prevent panics downstream.
167-169: Use of NewInvoiceCustomer centralizes constructionPassing a full InvoiceCustomer into snapshot and simulate flows is the right abstraction.
Also applies to: 1087-1087
openmeter/billing/invoice.go (2)
572-585: InvoiceCustomer implements MeterCustomer and adds a clean constructorInterface assertion and NewInvoiceCustomer are appropriate and keep usage consistent.
598-615: Getter implementations are straightforward and correctGetID, GetKey, GetUsageAttribution correctly expose required fields.
test/billing/invoice_test.go (2)
130-130: CustomerID migration usage looks good.All updated call sites passing customerEntity.GetCustomerID() (and related composite IDs) align with the new API and improve type safety. No issues spotted.
Also applies to: 164-164, 457-457, 633-633, 1406-1406, 1564-1564, 1581-1581, 1883-1883, 2096-2096, 2327-2327, 2384-2384, 2461-2461, 2641-2641, 2691-2691, 2790-2790, 2802-2802, 2813-2813, 3325-3325, 3385-3385, 3472-3473, 3518-3519, 3543-3544, 3600-3602, 3642-3644, 3694-3696, 3754-3756, 3804-3806, 3860-3862, 3933-3935, 3965-3967, 3996-3998, 4032-4033, 4044-4046, 4062-4064, 4081-4083
299-307: InvoiceCustomer.Key assertion addition is correct.Populating expected invoice with Key: customerEntity.Key matches the new public model (Key is a pointer). LGTM.
openmeter/ent/db/billinginvoice_update.go (3)
1187-1192: UpdateSpec wiring for customer_key is correct.Field set/clear for customer_key is properly added to the bulk update path.
2611-2616: UpdateOne wiring for customer_key is correct.Field set/clear for customer_key is properly added to the single-entity update path.
487-506: customer_key column supports nulls
Verified that thecustomer_keycolumn is added ascharacter varying NULLin the migration and markedNullablein the ent schema (Optional().Nillable()).ClearCustomerKeywon’t violate constraints.openmeter/billing/service/invoiceline.go (2)
309-312: Passing full InvoiceCustomer to snapshot is correct.The change to pass invoice.Customer into snapshotLineQuantitiesInParallel aligns with the new usage model. LGTM.
394-399: SnapshotLineQuantity now using full InvoiceCustomer: LGTM.The call site update to pass input.Invoice.Customer matches the refactored LineService API.
openmeter/ent/db/mutation.go (10)
11372-11372: Struct field addition looks correctPointer type and placement align with other nillable string fields in the mutation struct.
12781-12797: Clear/Cleared/Reset helpers are consistentClearCustomerKey, CustomerKeyCleared, and ResetCustomerKey mirror the established pattern for optional fields.
14247-14247: Fields() preallocation updatedCapacity increased from 54 to 55 to account for the new field. Good.
14332-14334: Fields() includes customer_key when setCorrectly appends FieldCustomerKey when the mutation value is non-nil.
14477-14479: Field(name) supports customer_keyCase correctly returns the current value via CustomerKey().
14596-14598: OldField(name) supports customer_keyDelegates to OldCustomerKey(ctx) with the usual UpdateOne guardrails. Looks good.
14855-14861: SetField(name, value) supports customer_keyType assertion to string and delegation to SetCustomerKey are correct. Note: fix in SetCustomerKey to clear the clearedFields marker (see earlier comment).
15125-15127: ClearedFields includes customer_keyCorrectly surfaces FieldCustomerKey when cleared.
15235-15237: ClearField(name) supports customer_keyDelegates to ClearCustomerKey as expected.
15372-15374: ResetField(name) supports customer_keyDelegates to ResetCustomerKey as expected.
openmeter/ent/db/billinginvoice_create.go (5)
348-360: Create builder setters for customer_key: LGTMSetters are consistent with the field’s Optional/Nillable semantics.
1056-1059: Persisting customer_key in createSpec: LGTMField wiring uses FieldCustomerKey with TypeString and assigns to the node pointer correctly for a nullable string.
2637-2656: UpsertOne wrappers for customer_key: LGTMDelegation to Upsert setters mirrors the established pattern for other fields.
3758-3777: UpsertBulk wrappers for customer_key: LGTMBulk wrappers consistently mirror the single-upsert API surface.
1740-1756: Verify immutability of customer_key on upsert conflictsIn both BillingInvoiceUpsertOne.UpdateNewValues (lines 2093–2140) and BillingInvoiceUpsertBulk.UpdateNewValues (lines 3201–3260), customer_key is not currently added to the ignored‐fields list. If customer_key should be a write-once “snapshot” at invoice creation, you’ll need to update each resolver block:
• In BillingInvoiceUpsertOne.UpdateNewValues:
if _, exists := u.create.mutation.PaymentAppID(); exists { s.SetIgnore(billinginvoice.FieldPaymentAppID) } + if _, exists := u.create.mutation.CustomerKey(); exists { + s.SetIgnore(billinginvoice.FieldCustomerKey) + }• In BillingInvoiceUpsertBulk.UpdateNewValues:
if _, exists := b.mutation.PaymentAppID(); exists { s.SetIgnore(billinginvoice.FieldPaymentAppID) } + if _, exists := b.mutation.CustomerKey(); exists { + s.SetIgnore(billinginvoice.FieldCustomerKey) + }Please confirm whether customer_key should remain immutable post-creation. If so, apply the above; otherwise, no change is needed.
openmeter/ent/db/billinginvoice/where.go (1)
209-212: CustomerKey() equality helper added: LGTMShorthand aligns with FieldCustomerKey and mirrors existing pattern (identical to CustomerKeyEQ).
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (1)
openmeter/billing/adapter/invoice.go (1)
504-508: LGTM - Customer key update logic is correctThe update logic properly handles both setting and clearing the customer key based on the input, ensuring the key can be maintained or removed as needed.
🧹 Nitpick comments (3)
api/spec/src/billing/invoices/party.tsp (1)
41-46: Tighten wording to emphasize snapshot nature (optional).Small doc improvement to avoid implying client mutability.
Apply this diff (if you prefer to keep the separate change from the visibility one):
- /** - * An optional unique key of the party (if available) - */ + /** + * Snapshot of the party's unique key at the time of invoicing (if available) + */api/openapi.cloud.yaml (1)
12806-12811: Mark invoice snapshot key as readOnly to reflect immutability.For BillingInvoiceCustomerExtendedDetails the Key is a denormalized snapshot on the invoice and should not be user-modifiable via this schema. Align with id by marking it readOnly.
key: type: string minLength: 1 maxLength: 256 description: An optional unique key of the party (if available) title: Key + readOnly: trueopenmeter/billing/invoice.go (1)
591-597: Consider documenting the key field's purposeWhile the implementation is correct, consider adding a comment explaining that the
Keyfield is an optional customer identifier used for usage attribution and meter queries.type InvoiceCustomer struct { + // Key is an optional customer identifier used for usage attribution and streaming queries Key *string `json:"key,omitempty"` CustomerID string `json:"customerId,omitempty"`
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
api/openapi.cloud.yaml(3 hunks)api/openapi.yaml(3 hunks)api/spec/src/billing/invoices/main.tsp(1 hunks)api/spec/src/billing/invoices/party.tsp(1 hunks)openmeter/billing/adapter/invoice.go(3 hunks)openmeter/billing/httpdriver/invoice.go(1 hunks)openmeter/billing/invoice.go(2 hunks)openmeter/billing/service/lineservice/meters.go(3 hunks)openmeter/customer/customer.go(2 hunks)openmeter/meter/httphandler/mapping.go(1 hunks)openmeter/streaming/clickhouse/meter_query.go(4 hunks)openmeter/streaming/clickhouse/meter_query_test.go(4 hunks)openmeter/streaming/query_params.go(2 hunks)test/billing/invoice_test.go(7 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/meter/httphandler/mapping.go
- openmeter/streaming/clickhouse/meter_query_test.go
🔇 Additional comments (26)
api/spec/src/billing/invoices/main.tsp (1)
13-13: LGTM: Switch toparty.tspaligns with the newBillingParty.key.Import update matches the new model location/shape and keeps the invoices package cohesive.
api/openapi.cloud.yaml (1)
12843-12848: Markkeyas readOnly in the BillingParty schemaNo
requestBodyin the OpenAPI specs references#/components/schemas/BillingParty(all create/update shapes useBillingPartyReplaceUpdate), so it’s safe to makekeyread-only:--- a/api/openapi.cloud.yaml +++ b/api/openapi.cloud.yaml @@ -12843,6 +12843,7 @@ key: type: string minLength: 1 maxLength: 256 description: An optional unique key of the party (if available) title: Key + readOnly: trueapi/openapi.yaml (1)
12976-12981: EnsurekeyIs Immutable in Replace/Update SchemasTo avoid breaking external references when updating a party, don’t allow clients to change its unique
key. In your Replace/Update schema you can either:• Omit the
keyproperty entirely from the request body
• Include it as a readonly field for response parityExample — remove from Replace/Update schema:
- key: - type: string - minLength: 1 - maxLength: 256 - description: An optional unique key of the party (if available) - title: KeyExample — keep but mark immutable:
key: type: string minLength: 1 maxLength: 256 description: An optional unique key of the party (if available) title: Key readOnly: true pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$'Verification checklist:
- Confirm that party keys are immutable once created.
- Ensure Create schema still accepts
keywith the same constraints.- Audit all Replace/Update schemas to enforce this policy.
openmeter/billing/httpdriver/invoice.go (1)
647-647: LGTM - Customer key mapping implemented correctlyThe addition of
Key: c.Keycorrectly maps the customer key from the internalbilling.InvoiceCustomerto the API response, enabling the key to be exposed through the HTTP API.openmeter/billing/adapter/invoice.go (2)
306-308: LGTM - Customer key snapshot implemented correctly on createThe CreateInvoice method now properly snapshots the customer key during invoice creation by setting both the CustomerID and the CustomerKey. This addresses the previous review comment about missing key persistence on creation.
677-677: LGTM - Customer key mapping from databaseThe mapping correctly extracts the customer key from the database field
invoice.CustomerKeyand assigns it to theInvoiceCustomer.Keyfield, completing the round-trip persistence.openmeter/streaming/clickhouse/meter_query.go (4)
17-17: LGTM - Import updated to use streaming interfaceThe import change from customer package to streaming package aligns with the architectural shift toward interface-based streaming customer handling.
26-26: LGTM - FilterCustomer type updated to streaming interfaceChanging
FilterCustomerfrom[]customer.Customerto[]streaming.Customerenables the use of the generic streaming interface, improving modularity and decoupling from specific customer implementations.
205-205: LGTM - Usage attribution accessed through streaming interfaceThe code correctly uses
customer.GetUsageAttribution().SubjectKeysandcustomer.GetUsageAttribution().IDto access the usage attribution data through the new streaming interface, maintaining the same functionality while using the abstracted interface.Also applies to: 210-210
311-311: LGTM - Subject filtering updated consistentlyThe subject filtering logic correctly uses the streaming interface method
customer.GetUsageAttribution().SubjectKeysto collect subject keys for filtering, maintaining consistency with the other usage attribution access patterns.openmeter/streaming/query_params.go (2)
16-16: LGTM - FilterCustomer field updated to use streaming interfaceChanging the field type from
[]customer.Customerto[]Customer(the new streaming interface) enables better abstraction and decoupling from concrete customer implementations.
67-77: Well-designed streaming interface and usage attribution structureThe new
Customerinterface withGetUsageAttribution()method and theCustomerUsageAttributionstruct provide a clean abstraction for streaming usage attribution. The structure includes all necessary fields:
IDfor customer identificationKeyfor optional customer keySubjectKeysfor mapping usage events to customersThis design enables consistent usage attribution handling across different streaming implementations.
openmeter/customer/customer.go (4)
15-15: LGTM - Interface compliance verificationThe compile-time check
var _ streaming.Customer = &Customer{}ensures that the Customer struct properly implements the streaming interface, preventing runtime errors from interface mismatches.
8-8: LGTM - Import added for streaming interfaceThe addition of the streaming package import is necessary to implement the streaming interface and provides access to the
CustomerUsageAttributiontype.
30-38: LGTM - Streaming interface implementationThe
GetUsageAttribution()method correctly implements the streaming interface by mapping the customer's fields to thestreaming.CustomerUsageAttributionstructure. The mapping is accurate:
IDfromc.IDKeyfromc.KeySubjectKeysfromc.UsageAttribution.SubjectKeys
40-48: LGTM - Convenience method for customer IDThe
GetID()method provides a convenient way to construct aCustomerIDfrom the customer's namespace and ID fields, reducing boilerplate code throughout the codebase.openmeter/billing/service/lineservice/meters.go (3)
16-21: LGTM!The change from
Subjects []stringtoCustomer billing.InvoiceCustomeris a good architectural improvement that aligns with the streaming-aware interface pattern.
37-39: LGTM!The validation logic properly delegates to the InvoiceCustomer's own validation and correctly wraps the error with contextual information.
57-61: LGTM!The meter query construction has been properly updated to use the new Customer field via
FilterCustomerinstead ofFilterSubject. The implementation correctly passes the Customer as a single-element slice as required by the streaming interface.test/billing/invoice_test.go (3)
59-80: Good test coverage of the customer key snapshotting feature.The test properly validates the new
Keyfield functionality by setting it during customer creation and verifying its propagation through the invoice workflow. The usage attribution with multiple subject keys provides comprehensive coverage.
299-311: Verify the customer snapshot structureThe test correctly validates that all customer fields are properly snapshotted to the invoice, including the new
Keyfield.
2628-2629: Consistent test updates for subject key changesThe subject key updates from
{"test"}to{"test-subject-1"}are consistently applied across multiple test scenarios, ensuring the new usage attribution pattern is properly tested.openmeter/billing/invoice.go (4)
19-19: LGTM!The import of the streaming package is necessary for implementing the streaming.Customer interface.
573-586: Well-designed constructor for InvoiceCustomerThe
NewInvoiceCustomerconstructor properly encapsulates the conversion fromcustomer.CustomertoInvoiceCustomer, ensuring all relevant fields are copied for snapshotting purposes.
599-607: Correct implementation of the streaming interfaceThe
GetUsageAttributionmethod correctly maps InvoiceCustomer fields to thestreaming.CustomerUsageAttributionstructure, properly implementing thestreaming.Customerinterface.
609-624: Comprehensive validation logicThe validation method properly enforces:
- CustomerID is required
- Key, if provided, cannot be empty
- Name is required
This ensures data integrity when creating invoice snapshots.
| key: | ||
| type: string | ||
| minLength: 1 | ||
| maxLength: 256 | ||
| description: An optional unique key of the party (if available) | ||
| title: Key |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Allow null to explicitly clear Key on update; document the behavior.
Ent adds SetOrClearCustomerKey and the DB column is nullable. The update schema must accept null to clear; otherwise clients cannot explicitly remove a previously set Key.
- Confirm OpenAPI version to choose proper nullability syntax.
- Verify DB/Ent constraints match min/max length to avoid validation drift.
If your OpenAPI is 3.0.x, prefer nullable: true. If 3.1, prefer type: [string, 'null'].
OpenAPI 3.0.x diff:
BillingPartyReplaceUpdate:
type: object
properties:
key:
type: string
+ nullable: true
minLength: 1
maxLength: 256
- description: An optional unique key of the party (if available)
+ description: An optional unique key of the party (if available). Set to null to clear.
title: KeyOpenAPI 3.1 alternative (if applicable):
key:
- type: string
+ type:
+ - string
+ - 'null'
minLength: 1
maxLength: 256
- description: An optional unique key of the party (if available)
+ description: An optional unique key of the party (if available). Set to null to clear.
title: Key🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== OpenAPI versions =="
rg -n "^openapi:\\s*" -A 0 -B 0 api | sed 's/^/>> /'
echo
echo "== Where is BillingPartyReplaceUpdate used? =="
rg -n "BillingPartyReplaceUpdate" -A 4 -B 4 api | sed 's/^/>> /'
echo
echo "== Check schema and migration for customer_key constraints =="
rg -n "customer_key|CustomerKey" -A 3 -B 3 openmeter | sed 's/^/>> /'
rg -n "customer_key" -A 3 -B 3 tools/migrate | sed 's/^/>> /'Length of output: 70390
Allow null in BillingPartyReplaceUpdate.key to enable explicit clearing
OpenAPI is v3.0.0—use nullable: true on the key property. The database column is already NULL-able and Ent defines it as Optional().Nillable(), and SetOrClearCustomerKey handles null correctly.
Affected files:
- api/openapi.cloud.yaml (components/schemas/BillingPartyReplaceUpdate, lines 12867–12873)
- api/openapi.yaml (components/schemas/BillingPartyReplaceUpdate, lines 12973–12979)
Proposed diff for both specs:
BillingPartyReplaceUpdate:
type: object
properties:
key:
- type: string
+ type: string
+ nullable: true
minLength: 1
maxLength: 256
- description: An optional unique key of the party (if available)
+ description: An optional unique key of the party (if available). Set to null to clear.
title: Key📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| key: | |
| type: string | |
| minLength: 1 | |
| maxLength: 256 | |
| description: An optional unique key of the party (if available) | |
| title: Key | |
| key: | |
| type: string | |
| nullable: true | |
| minLength: 1 | |
| maxLength: 256 | |
| description: An optional unique key of the party (if available). Set to null to clear. | |
| title: Key |
🤖 Prompt for AI Agents
In api/openapi.cloud.yaml around lines 12868–12873 (and likewise in
api/openapi.yaml around lines 12973–12979), the BillingPartyReplaceUpdate.key
schema disallows explicit null which prevents clearing the DB value; add OpenAPI
v3 nullable support by setting nullable: true on the key property (keeping type:
string, minLength/maxLength, description, and title) so clients can send null to
clear the existing key; apply the same nullable: true addition to both specs.
| key: | ||
| type: string | ||
| minLength: 1 | ||
| maxLength: 256 | ||
| description: An optional unique key of the party (if available) | ||
| title: Key |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Add format constraints and mark key as readOnly (align with existing Key semantics).
This schema block appears alongside an id that is readOnly: true. If key is a server-managed/public identifier surfaced in responses (not meant to be mutated on response DTOs), it should also be readOnly: true. Additionally, other schemas in this PR use a normalized key format (slug or ULID). Add a pattern to enforce consistency.
Apply this diff:
key:
type: string
minLength: 1
maxLength: 256
description: An optional unique key of the party (if available)
title: Key
+ readOnly: true
+ pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$'Optional follow-up (preferred for DRY): introduce a reusable schema for keys and reference it here instead of duplicating constraints.
# components/schemas (outside this hunk)
PublicKey:
description: Public, externally stable key. Either a slug or a ULID.
oneOf:
- type: string
pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$'
minLength: 1
maxLength: 256
description: Slug format.
- type: string
pattern: '^[0-9A-HJKMNP-TV-Z]{26}$'
description: ULID format.
# Then replace the inline key schema with:
key:
$ref: '#/components/schemas/PublicKey'
readOnly: trueTo verify consistency across the spec files, run:
🏁 Script executed:
#!/bin/bash
# Check all 'key' properties for the presence of a pattern and readOnly where appropriate.
rg -n -A3 -B2 $'^\\s{2,}key:\\s*$' api | sed -n '1,200p'
# Inspect places where 'title: Key' appears without a pattern constraint:
rg -n -A3 -B3 $'title:\\s*Key' api | rg -n -B10 -A10 -v 'pattern:'
# Inspect Replace/Update schemas that allow mutating keys:
rg -n $'ReplaceUpdate:' -A40 api | rg -n -A5 -B5 $'^\\s{4,}key:'Length of output: 21886
Add readOnly and enforce slug format on the party’s key
To align with existing Key semantics—where public identifiers are server-managed and follow a normalized slug pattern—update the key property at api/openapi.yaml:12914:
key:
type: string
minLength: 1
maxLength: 256
+ readOnly: true
+ pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$'
description: An optional unique key of the party (if available)
title: KeyOptional DRY refactor: define a shared PublicKey component under #/components/schemas and reference it here:
components:
schemas:
PublicKey:
description: Public, externally stable key. Slug or ULID.
oneOf:
- type: string
pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$'
minLength: 1
maxLength: 256
description: Slug format.
- type: string
pattern: '^[0-9A-HJKMNP-TV-Z]{26}$'
description: ULID format.
# Then inline:
key:
$ref: '#/components/schemas/PublicKey'
readOnly: true🤖 Prompt for AI Agents
In api/openapi.yaml around lines 12914-12919, the party `key` property must be
marked as server-managed and constrained to the normalized slug/ULID formats;
update the `key` schema to set readOnly: true and replace the current free
string definition with a reference to a new reusable
`#/components/schemas/PublicKey` that enforces oneOf: a slug pattern (pattern
'^[a-z0-9]+(?:_[a-z0-9]+)*$', minLength:1, maxLength:256) or a ULID pattern
(pattern '^[0-9A-HJKMNP-TV-Z]{26}$'), then change the inline `key` entry to
$ref: '#/components/schemas/PublicKey' and add readOnly: true at that property
location.
| key: | ||
| type: string | ||
| minLength: 1 | ||
| maxLength: 256 | ||
| description: An optional unique key of the party (if available) | ||
| title: Key |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Mirror constraints: enforce key format and mark as readOnly.
For parity with the prior schema and to avoid accepting arbitrary strings, add a pattern constraint and mark key as readOnly: true in response models.
Apply this diff:
key:
type: string
minLength: 1
maxLength: 256
description: An optional unique key of the party (if available)
title: Key
+ readOnly: true
+ pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$'If ULIDs are also valid keys in your domain, prefer referencing a shared PublicKey schema (see previous comment) rather than repeating constraints.
🏁 Script executed:
#!/bin/bash
# List all definitions of “key:” in the OpenAPI spec with a few lines of context
rg -n -C2 'key:' api/openapi.yaml
# Check if there’s a shared PublicKey schema defined or referenced anywhere
rg -n 'PublicKey' api/openapi.yamlLength of output: 8399
Enforce read-only & format on key in Party schema
Please update the key property under the Party model to include both readOnly: true and a pattern constraint:
– File: api/openapi.yaml (around line 12951)
– Schema: Party (properties → key)
key:
type: string
minLength: 1
maxLength: 256
description: An optional unique key of the party (if available)
title: Key
+ readOnly: true
+ pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$'• If your domain also allows hyphens or ULIDs, adjust the regex accordingly.
• Since there’s no existing PublicKey component in this spec, consider extracting these constraints into a shared PublicKey schema if you’ll reuse them elsewhere.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| key: | |
| type: string | |
| minLength: 1 | |
| maxLength: 256 | |
| description: An optional unique key of the party (if available) | |
| title: Key | |
| key: | |
| type: string | |
| minLength: 1 | |
| maxLength: 256 | |
| description: An optional unique key of the party (if available) | |
| title: Key | |
| readOnly: true | |
| pattern: '^[a-z0-9]+(?:_[a-z0-9]+)*$' |
🤖 Prompt for AI Agents
In api/openapi.yaml around lines 12951-12956 the Party schema's key property
needs to be marked readOnly and constrained with a pattern; update the key
property to include readOnly: true and add a suitable regex under pattern (e.g.,
alphanumeric with optional hyphens or an ULID pattern depending on your domain)
and keep minLength/maxLength as-is; if this constraint will be reused, extract
these attributes into a shared component (e.g., PublicKey) and reference it from
Party to avoid duplication.
| /** | ||
| * An optional unique key of the party (if available) | ||
| */ | ||
| @summary("Key") | ||
| key?: ExternalKey; | ||
|
|
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Validate ExternalKey type resolution in this module.
Ensure ExternalKey is in scope via imports transitively available to this file. If it’s not brought in by the current imports, add the required import where ExternalKey is defined.
Run this script to locate the ExternalKey definition and confirm it’s available:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find where ExternalKey is defined (alias/model/scalar)
rg -n --no-heading -S '(^|\b)(alias|model|scalar)\s+ExternalKey\b' -A 3
# Show imports in the modified file to double-check scope
echo
echo "Imports in api/spec/src/billing/invoices/party.tsp:"
sed -n '1,40p' api/spec/src/billing/invoices/party.tsp | rg -n '^import\s+"[^"]+";'Length of output: 622
Add missing import for ExternalKey
The ExternalKey scalar is defined in api/spec/src/types.tsp but isn’t currently imported in api/spec/src/billing/invoices/party.tsp. To bring it into scope, add:
import "../../types";at the top of party.tsp, for example:
import "@typespec/http";
import "@typespec/rest";
import "@typespec/openapi3";
-import "../../customer";
+import "../../customer";
+import "../../types";This ensures ExternalKey resolves correctly.
🤖 Prompt for AI Agents
In api/spec/src/billing/invoices/party.tsp around lines 41 to 46 the scalar type
ExternalKey is used but not imported; add the import by inserting import
"../../types"; at the top of party.tsp so ExternalKey is brought into scope and
the key?: ExternalKey; declaration resolves correctly.
Make key read-only to reflect snapshot semantics and avoid unintended inputs.
Given the PR objective “Snapshot Customer.Key to Billing InvoiceCustomer,” this field should be server-populated and not accepted on create/update. Currently, it lacks a visibility annotation, which will expose it in write operations. Align it with id as read-only.
Apply this diff:
/**
- * An optional unique key of the party (if available)
+ * Snapshot of the party's unique key at the time of invoicing (if available)
*/
@summary("Key")
+ @visibility(Lifecycle.Read)
key?: ExternalKey;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** | |
| * An optional unique key of the party (if available) | |
| */ | |
| @summary("Key") | |
| key?: ExternalKey; | |
| /** | |
| * Snapshot of the party's unique key at the time of invoicing (if available) | |
| */ | |
| @summary("Key") | |
| @visibility(Lifecycle.Read) | |
| key?: ExternalKey; |
🤖 Prompt for AI Agents
In api/spec/src/billing/invoices/party.tsp around lines 41 to 46, the `key`
field is intended to be server-populated snapshot data but currently has no
visibility annotation and will be accepted in write operations; make it
read-only by adding the same visibility annotation used for `id` (e.g.,
@visibility("readOnly")) above the `key` declaration so the field is exposed in
reads only and not accepted on create/update.
Customer.GetUsageAttribution(): CustomerUsageAttributioninterface to streamingCustomer.Keyto BillingInvoiceCustomerkeyto invoice customer APISummary by CodeRabbit
New Features
API
Migrations