Files
carvalho-finances/apps/api/internal/handler/account.go
T
Mlcavalho1andClaude Sonnet 4.6 9a964423fd feat(#21): contas bancárias e patrimônio consolidado
CRUD de contas (corrente/poupança/investimento/cartão) com saldo calculado
automaticamente. account_id nullable em transactions. Widget patrimônio no
dashboard. Tela /contas. Seletor de conta nas transações manuais.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-05-26 21:34:56 -03:00

88 lines
2.3 KiB
Go

package handler
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"financeiro-carvalho/internal/model"
"financeiro-carvalho/internal/service"
)
type AccountHandler struct {
svc *service.AccountService
}
func NewAccountHandler(svc *service.AccountService) *AccountHandler {
return &AccountHandler{svc: svc}
}
func (h *AccountHandler) List(w http.ResponseWriter, r *http.Request) {
items, err := h.svc.List(r.Context())
if err != nil {
respondError(w, http.StatusInternalServerError, "failed to list accounts")
return
}
if items == nil {
items = []model.Account{}
}
respondJSON(w, http.StatusOK, items)
}
func (h *AccountHandler) Create(w http.ResponseWriter, r *http.Request) {
var in model.AccountInput
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
respondError(w, http.StatusBadRequest, "invalid JSON")
return
}
out, err := h.svc.Create(r.Context(), in)
if err != nil {
if errors.Is(err, service.ErrAccountEmptyName) || errors.Is(err, service.ErrAccountInvalidType) {
respondError(w, http.StatusUnprocessableEntity, err.Error())
return
}
respondError(w, http.StatusInternalServerError, "failed to create account")
return
}
respondJSON(w, http.StatusCreated, out)
}
func (h *AccountHandler) Update(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
respondError(w, http.StatusBadRequest, "invalid id")
return
}
var in model.AccountInput
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
respondError(w, http.StatusBadRequest, "invalid JSON")
return
}
out, err := h.svc.Update(r.Context(), id, in)
if err != nil {
if errors.Is(err, service.ErrAccountEmptyName) || errors.Is(err, service.ErrAccountInvalidType) {
respondError(w, http.StatusUnprocessableEntity, err.Error())
return
}
respondError(w, http.StatusInternalServerError, "failed to update account")
return
}
respondJSON(w, http.StatusOK, out)
}
func (h *AccountHandler) Delete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
respondError(w, http.StatusBadRequest, "invalid id")
return
}
if err := h.svc.Delete(r.Context(), id); err != nil {
respondError(w, http.StatusInternalServerError, "failed to delete account")
return
}
w.WriteHeader(http.StatusNoContent)
}