package server import ( "context" "fmt" "net/http" "time" "git.javil.eu/jacob1123/budgeteer/postgres" "git.javil.eu/jacob1123/budgeteer/postgres/numeric" "github.com/gin-gonic/gin" "github.com/google/uuid" ) func getFirstOfMonth(year, month int, location *time.Location) time.Time { return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, location) } func getFirstOfMonthTime(date time.Time) time.Time { var monthM time.Month year, monthM, _ := date.Date() month := int(monthM) return getFirstOfMonth(year, month, date.Location()) } type CategoryWithBalance struct { *postgres.GetCategoriesRow Available numeric.Numeric Activity numeric.Numeric Assigned numeric.Numeric } func NewCategoryWithBalance(category *postgres.GetCategoriesRow) CategoryWithBalance { return CategoryWithBalance{ GetCategoriesRow: category, Available: numeric.Zero(), Activity: numeric.Zero(), Assigned: numeric.Zero(), } } func (h *Handler) budgetingForMonth(c *gin.Context) { budgetID := c.Param("budgetid") budgetUUID, err := uuid.Parse(budgetID) if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budgetid missing from URL"}) return } budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID) if err != nil { c.AbortWithError(http.StatusBadRequest, err) return } firstOfMonth, err := getDate(c) if err != nil { c.Redirect(http.StatusTemporaryRedirect, "/budget/"+budget.ID.String()) return } firstOfNextMonth := firstOfMonth.AddDate(0, 1, 0) data, err := h.prepareBudgeting(c.Request.Context(), budget, firstOfNextMonth, firstOfMonth) if err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } c.JSON(http.StatusOK, data) } func (h *Handler) prepareBudgeting(ctx context.Context, budget postgres.Budget, firstOfNextMonth time.Time, firstOfMonth time.Time) (BudgetingForMonthResponse, error) { categories, err := h.Service.GetCategories(ctx, budget.ID) if err != nil { return BudgetingForMonthResponse{}, fmt.Errorf("error loading categories: %w", err) } cumultativeBalances, err := h.Service.GetCumultativeBalances(ctx, budget.ID) if err != nil { return BudgetingForMonthResponse{}, fmt.Errorf("error loading balances: %w", err) } categoriesWithBalance, moneyUsed := h.calculateBalances( budget, firstOfNextMonth, firstOfMonth, categories, cumultativeBalances) availableBalance := h.getAvailableBalance(budget, moneyUsed, cumultativeBalances, firstOfNextMonth) for i := range categoriesWithBalance { cat := &categoriesWithBalance[i] if cat.ID != budget.IncomeCategoryID { continue } cat.Available = availableBalance } data := BudgetingForMonthResponse{categoriesWithBalance, availableBalance} return data, nil } type BudgetingForMonthResponse struct { Categories []CategoryWithBalance AvailableBalance numeric.Numeric } func (*Handler) getAvailableBalance(budget postgres.Budget, moneyUsed numeric.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow, firstOfNextMonth time.Time, ) numeric.Numeric { availableBalance := moneyUsed for _, bal := range cumultativeBalances { if bal.CategoryID != budget.IncomeCategoryID { continue } if !bal.Date.Before(firstOfNextMonth) { continue } availableBalance.AddI(bal.Transactions) availableBalance.AddI(bal.Assignments) } return availableBalance } type BudgetingResponse struct { Accounts []postgres.GetAccountsWithBalanceRow Budget postgres.Budget } func (h *Handler) budgeting(c *gin.Context) { budgetID := c.Param("budgetid") budgetUUID, err := uuid.Parse(budgetID) if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budgetid missing from URL"}) return } h.returnBudgetingData(c, budgetUUID) } func (h *Handler) returnBudgetingData(c *gin.Context, budgetUUID uuid.UUID) { budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID) if err != nil { c.AbortWithError(http.StatusNotFound, err) return } accounts, err := h.Service.GetAccountsWithBalance(c.Request.Context(), budgetUUID) if err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } data := BudgetingResponse{accounts, budget} c.JSON(http.StatusOK, data) } func (h *Handler) calculateBalances(budget postgres.Budget, firstOfNextMonth time.Time, firstOfMonth time.Time, categories []postgres.GetCategoriesRow, cumultativeBalances []postgres.GetCumultativeBalancesRow, ) ([]CategoryWithBalance, numeric.Numeric) { categoriesWithBalance := []CategoryWithBalance{} moneyUsed2 := numeric.Zero() moneyUsed := &moneyUsed2 for i := range categories { cat := &categories[i] // do not show hidden categories categoryWithBalance := h.CalculateCategoryBalances(cat, cumultativeBalances, firstOfNextMonth, moneyUsed, firstOfMonth, budget) categoriesWithBalance = append(categoriesWithBalance, categoryWithBalance) } return categoriesWithBalance, *moneyUsed } func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow, cumultativeBalances []postgres.GetCumultativeBalancesRow, firstOfNextMonth time.Time, moneyUsed *numeric.Numeric, firstOfMonth time.Time, budget postgres.Budget, ) CategoryWithBalance { categoryWithBalance := NewCategoryWithBalance(cat) for _, bal := range cumultativeBalances { if bal.CategoryID != cat.ID { continue } // skip everything in the future if !bal.Date.Before(firstOfNextMonth) { continue } moneyUsed.SubI(bal.Assignments) categoryWithBalance.Available.AddI(bal.Assignments) categoryWithBalance.Available.AddI(bal.Transactions) if !categoryWithBalance.Available.IsPositive() && bal.Date.Before(firstOfMonth) { moneyUsed.AddI(categoryWithBalance.Available) categoryWithBalance.Available = numeric.Zero() } if bal.Date.Before(firstOfNextMonth) { categoryWithBalance.Activity = bal.Transactions categoryWithBalance.Assigned = bal.Assignments } } return categoryWithBalance }