From 1f3da3376ab2b38cee6ab379eaf6a9bf0b6ab781 Mon Sep 17 00:00:00 2001 From: Peter Turi Date: Tue, 21 Jan 2025 10:45:55 +0100 Subject: [PATCH] feat: implement period value calculation of the invoice We are calculating the period value of the invoice based on the line items min/max period values. --- .../billing/service/invoicecalc/calculator.go | 1 + .../billing/service/invoicecalc/period.go | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 openmeter/billing/service/invoicecalc/period.go 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 +}