@@ -90,30 +90,27 @@ func (b Budget) Income(db *gorm.DB, month types.Month) (income decimal.Decimal,
9090 return
9191}
9292
93- // Budgeted calculates the sum that has been budgeted for a specific month.
94- func (b Budget ) Budgeted (db * gorm.DB , month types.Month ) (decimal.Decimal , error ) {
95- var budgeted decimal.NullDecimal
96- err := db .
97- Select ("SUM(amount)" ).
93+ // Allocated calculates the sum that has been budgeted for a specific month.
94+ func (b Budget ) Allocated (db * gorm.DB , month types.Month ) (allocated decimal.Decimal , err error ) {
95+ var allocations []Allocation
96+ err = db .
9897 Joins ("JOIN envelopes ON allocations.envelope_id = envelopes.id AND envelopes.deleted_at IS NULL" ).
9998 Joins ("JOIN categories ON envelopes.category_id = categories.id AND categories.deleted_at IS NULL" ).
10099 Joins ("JOIN budgets ON categories.budget_id = budgets.id AND budgets.deleted_at IS NULL" ).
101100 Where ("budgets.id = ?" , b .ID ).
102101 Where ("allocations.month >= date(?)" , month ).
103102 Where ("allocations.month < date(?)" , month .AddDate (0 , 1 )).
104- Table ("allocations" ).
105- Find (& budgeted ).
103+ Find (& allocations ).
106104 Error
107105 if err != nil {
108106 return decimal .Zero , err
109107 }
110108
111- // If no transactions are found, the value is nil
112- if ! budgeted .Valid {
113- return decimal .NewFromFloat (0 ), nil
109+ for _ , a := range allocations {
110+ allocated = allocated .Add (a .Amount )
114111 }
115112
116- return budgeted . Decimal , nil
113+ return
117114}
118115
119116type CategoryEnvelopes struct {
@@ -149,7 +146,7 @@ func (b Budget) Month(db *gorm.DB, month types.Month, baseURL string) (Month, er
149146 }
150147
151148 // Add budgeted sum to response
152- budgeted , err := b .Budgeted (db , result .Month )
149+ budgeted , err := b .Allocated (db , result .Month )
153150 if err != nil {
154151 return Month {}, err
155152 }
0 commit comments