budgeteer/http/budget.go

78 lines
1.7 KiB
Go

package http
import (
"fmt"
"net/http"
"git.javil.eu/jacob1123/budgeteer"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type AllAccountsData struct {
AlwaysNeededData
Account *postgres.Account
Categories []postgres.GetCategoriesRow
Transactions []postgres.GetTransactionsForBudgetRow
}
func (h *Handler) allAccounts(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/login")
return
}
categories, err := h.Service.GetCategories(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
transactions, err := h.Service.GetTransactionsForBudget(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
d := AllAccountsData{
c.MustGet("data").(AlwaysNeededData),
&postgres.Account{
Name: "All accounts",
},
categories,
transactions,
}
c.HTML(http.StatusOK, "account.html", d)
}
type newBudgetInformation struct {
Name string `json:"name"`
}
func (h *Handler) newBudget(c *gin.Context) {
var newBudget newBudgetInformation
err := c.BindJSON(&newBudget)
if err != nil {
c.AbortWithError(http.StatusNotAcceptable, err)
return
}
if newBudget.Name == "" {
c.AbortWithError(http.StatusNotAcceptable, fmt.Errorf("Budget name is needed"))
return
}
userID := c.MustGet("token").(budgeteer.Token).GetID()
budget, err := h.Service.NewBudget(c.Request.Context(), newBudget.Name, userID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, budget)
}