budgeteer/http/budgeting.go

89 lines
2.1 KiB
Go

package http
import (
"net/http"
"strconv"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type BudgetingData struct {
AlwaysNeededData
Categories []postgres.GetCategoriesWithBalanceRow
AvailableBalance postgres.Numeric
Date time.Time
Next time.Time
Previous time.Time
}
func (h *Handler) budgeting(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/login")
return
}
now := time.Now()
var year, month int
yearString := c.Param("year")
monthString := c.Param("month")
if yearString != "" && monthString != "" {
year, err = strconv.Atoi(yearString)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/budget/"+budgetUUID.String())
return
}
month, err = strconv.Atoi(monthString)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/budget/"+budgetUUID.String())
return
}
} else {
var monthM time.Month
year, monthM, _ = now.Date()
month = int(monthM)
}
firstOfMonth := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, now.Location())
firstOfNextMonth := firstOfMonth.AddDate(0, 1, 0)
firstOfPreviousMonth := firstOfMonth.AddDate(0, -1, 0)
params := postgres.GetCategoriesWithBalanceParams{
BudgetID: budgetUUID,
FromDate: firstOfMonth,
ToDate: firstOfNextMonth,
}
categories, err := h.Service.DB.GetCategoriesWithBalance(c.Request.Context(), params)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
availableParams := postgres.GetAvailableBalanceParams{
BudgetID: budgetUUID,
FromDate: firstOfNextMonth,
}
availableBalance, err := h.Service.DB.GetAvailableBalance(c.Request.Context(), availableParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
d := BudgetingData{
c.MustGet("data").(AlwaysNeededData),
categories,
availableBalance,
firstOfMonth,
firstOfNextMonth,
firstOfPreviousMonth,
}
c.HTML(http.StatusOK, "budgeting.html", d)
}