@@ -2,7 +2,6 @@ package models
22
33import (
44 "fmt"
5- "time"
65
76 "github.com/envelope-zero/backend/internal/types"
87 "github.com/google/uuid"
@@ -63,11 +62,10 @@ func (b Budget) WithCalculations(db *gorm.DB) (Budget, error) {
6362}
6463
6564// Income returns the income for a budget in a given month.
66- func (b Budget ) Income (db * gorm.DB , month types.Month ) (decimal.Decimal , error ) {
67- var income decimal. NullDecimal
65+ func (b Budget ) Income (db * gorm.DB , month types.Month ) (income decimal.Decimal , err error ) {
66+ var transactions [] Transaction
6867
69- err := db .
70- Select ("SUM(amount)" ).
68+ err = db .
7169 Joins ("JOIN accounts source_account ON transactions.source_account_id = source_account.id AND source_account.deleted_at IS NULL" ).
7270 Joins ("JOIN accounts destination_account ON transactions.destination_account_id = destination_account.id AND destination_account.deleted_at IS NULL" ).
7371 Where ("source_account.external = 1" ).
@@ -79,19 +77,17 @@ func (b Budget) Income(db *gorm.DB, month types.Month) (decimal.Decimal, error)
7977 BudgetID : b .ID ,
8078 },
8179 }).
82- Table ("transactions" ).
83- Find (& income ).
80+ Find (& transactions ).
8481 Error
8582 if err != nil {
8683 return decimal .Zero , err
8784 }
8885
89- // If no transactions are found, the value is nil
90- if ! income .Valid {
91- return decimal .NewFromFloat (0 ), nil
86+ for _ , t := range transactions {
87+ income = income .Add (t .Amount )
9288 }
9389
94- return income . Decimal , nil
90+ return
9591}
9692
9793// Budgeted calculates the sum that has been budgeted for a specific month.
0 commit comments