diff --git a/openmeter/billing/service/invoicecalc/calculator.go b/openmeter/billing/service/invoicecalc/calculator.go index 7561af6d0..6e4ae9602 100644 --- a/openmeter/billing/service/invoicecalc/calculator.go +++ b/openmeter/billing/service/invoicecalc/calculator.go @@ -10,6 +10,7 @@ import ( var InvoiceCalculations = []Calculation{ DraftUntilIfMissing, RecalculateDetailedLinesAndTotals, + CalculateInvoicePeriod, } type Calculation func(*billing.Invoice, CalculatorDependencies) error diff --git a/openmeter/billing/service/invoicecalc/period.go b/openmeter/billing/service/invoicecalc/period.go new file mode 100644 index 000000000..f3599ecd3 --- /dev/null +++ b/openmeter/billing/service/invoicecalc/period.go @@ -0,0 +1,36 @@ +package invoicecalc + +import "github.com/openmeterio/openmeter/openmeter/billing" + +// CalculateInvoicePeriod calculates the period of the invoice based on the lines. +func CalculateInvoicePeriod(invoice *billing.Invoice, deps CalculatorDependencies) error { + var period *billing.Period + + for _, line := range invoice.Lines.OrEmpty() { + if line.DeletedAt != nil || line.Status != billing.InvoiceLineStatusValid { + continue + } + + if period == nil { + period = &billing.Period{ + Start: line.Period.Start, + End: line.Period.End, + } + continue + } + + if line.Period.Start.Before(period.Start) { + period.Start = line.Period.Start + } + + if line.Period.End.After(period.End) { + period.End = line.Period.End + } + } + + if period != nil { + invoice.Period = period + } + + return nil +}