feat(#17): CRUD de categorias — API Go + tela Vue + testes unitários

API REST /api/categories (GET/POST/PUT/DELETE) com regras de negócio:
categorias padrão não podem ser excluídas; categorias com transações vinculadas
também bloqueadas. Tela Vue com formulário inline de criação/edição, indicador
visual de categorias padrão e botão de exclusão condicional.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
2026-05-26 20:11:54 -03:00
co-authored by Claude Sonnet 4.6
parent a3d8f363a5
commit d6782d51a5
12 changed files with 720 additions and 1 deletions
+10 -1
View File
@@ -15,6 +15,8 @@ import (
"financeiro-carvalho/internal/db"
"financeiro-carvalho/internal/handler"
"financeiro-carvalho/internal/migration"
"financeiro-carvalho/internal/repository"
"financeiro-carvalho/internal/service"
"financeiro-carvalho/static"
)
@@ -46,10 +48,17 @@ func main() {
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
categoryRepo := repository.NewCategoryRepository(pool)
categorySvc := service.NewCategoryService(categoryRepo)
categoryHandler := handler.NewCategoryHandler(categorySvc)
r.Get("/health", handler.Health)
r.Route("/api", func(r chi.Router) {
// API routes added here as features are built
r.Get("/categories", categoryHandler.List)
r.Post("/categories", categoryHandler.Create)
r.Put("/categories/{id}", categoryHandler.Update)
r.Delete("/categories/{id}", categoryHandler.Delete)
})
// Serve Vue SPA — non-API routes fall through to index.html
+92
View File
@@ -0,0 +1,92 @@
package handler
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"financeiro-carvalho/internal/model"
"financeiro-carvalho/internal/repository"
"financeiro-carvalho/internal/service"
)
type CategoryHandler struct {
svc *service.CategoryService
}
func NewCategoryHandler(svc *service.CategoryService) *CategoryHandler {
return &CategoryHandler{svc: svc}
}
func (h *CategoryHandler) List(w http.ResponseWriter, r *http.Request) {
cats, err := h.svc.List(r.Context())
if err != nil {
respondError(w, http.StatusInternalServerError, "failed to list categories")
return
}
if cats == nil {
cats = []model.Category{}
}
respondJSON(w, http.StatusOK, cats)
}
func (h *CategoryHandler) Create(w http.ResponseWriter, r *http.Request) {
var in model.CategoryInput
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
respondError(w, http.StatusBadRequest, "invalid JSON")
return
}
cat, err := h.svc.Create(r.Context(), in)
if err != nil {
respondError(w, http.StatusBadRequest, err.Error())
return
}
respondJSON(w, http.StatusCreated, cat)
}
func (h *CategoryHandler) 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.CategoryInput
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
respondError(w, http.StatusBadRequest, "invalid JSON")
return
}
cat, err := h.svc.Update(r.Context(), id, in)
if errors.Is(err, repository.ErrNotFound) {
respondError(w, http.StatusNotFound, "category not found")
return
}
if err != nil {
respondError(w, http.StatusBadRequest, err.Error())
return
}
respondJSON(w, http.StatusOK, cat)
}
func (h *CategoryHandler) 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
}
err = h.svc.Delete(r.Context(), id)
switch {
case errors.Is(err, repository.ErrNotFound):
respondError(w, http.StatusNotFound, "category not found")
case errors.Is(err, service.ErrDefaultCategory):
respondError(w, http.StatusConflict, err.Error())
case errors.Is(err, service.ErrHasTransactions):
respondError(w, http.StatusConflict, err.Error())
case err != nil:
respondError(w, http.StatusInternalServerError, "failed to delete")
default:
w.WriteHeader(http.StatusNoContent)
}
}
+16
View File
@@ -0,0 +1,16 @@
package handler
import (
"encoding/json"
"net/http"
)
func respondJSON(w http.ResponseWriter, status int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(data)
}
func respondError(w http.ResponseWriter, status int, msg string) {
respondJSON(w, status, map[string]string{"error": msg})
}
+17
View File
@@ -0,0 +1,17 @@
package model
import "time"
type Category struct {
ID int `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
IsDefault bool `json:"is_default"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CategoryInput struct {
Name string `json:"name"`
Color string `json:"color"`
}
+106
View File
@@ -0,0 +1,106 @@
package repository
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"financeiro-carvalho/internal/model"
)
var ErrNotFound = errors.New("not found")
type CategoryRepository interface {
List(ctx context.Context) ([]model.Category, error)
GetByID(ctx context.Context, id int) (*model.Category, error)
Create(ctx context.Context, name, color string) (*model.Category, error)
Update(ctx context.Context, id int, name, color string) (*model.Category, error)
Delete(ctx context.Context, id int) error
HasTransactions(ctx context.Context, id int) (bool, error)
}
type categoryRepo struct{ db *pgxpool.Pool }
func NewCategoryRepository(db *pgxpool.Pool) CategoryRepository {
return &categoryRepo{db: db}
}
func (r *categoryRepo) List(ctx context.Context) ([]model.Category, error) {
rows, err := r.db.Query(ctx, `
SELECT id, name, color, is_default, created_at, updated_at
FROM categories
ORDER BY is_default DESC, name ASC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []model.Category
for rows.Next() {
var c model.Category
if err := rows.Scan(&c.ID, &c.Name, &c.Color, &c.IsDefault, &c.CreatedAt, &c.UpdatedAt); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
func (r *categoryRepo) GetByID(ctx context.Context, id int) (*model.Category, error) {
var c model.Category
err := r.db.QueryRow(ctx, `
SELECT id, name, color, is_default, created_at, updated_at
FROM categories WHERE id = $1`, id).
Scan(&c.ID, &c.Name, &c.Color, &c.IsDefault, &c.CreatedAt, &c.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return &c, err
}
func (r *categoryRepo) Create(ctx context.Context, name, color string) (*model.Category, error) {
var c model.Category
err := r.db.QueryRow(ctx, `
INSERT INTO categories (name, color)
VALUES ($1, $2)
RETURNING id, name, color, is_default, created_at, updated_at`,
name, color).
Scan(&c.ID, &c.Name, &c.Color, &c.IsDefault, &c.CreatedAt, &c.UpdatedAt)
return &c, err
}
func (r *categoryRepo) Update(ctx context.Context, id int, name, color string) (*model.Category, error) {
var c model.Category
err := r.db.QueryRow(ctx, `
UPDATE categories
SET name = $1, color = $2, updated_at = NOW()
WHERE id = $3
RETURNING id, name, color, is_default, created_at, updated_at`,
name, color, id).
Scan(&c.ID, &c.Name, &c.Color, &c.IsDefault, &c.CreatedAt, &c.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return &c, err
}
func (r *categoryRepo) Delete(ctx context.Context, id int) error {
tag, err := r.db.Exec(ctx, `DELETE FROM categories WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (r *categoryRepo) HasTransactions(ctx context.Context, id int) (bool, error) {
var count int
err := r.db.QueryRow(ctx,
`SELECT COUNT(*) FROM transactions WHERE category_id = $1`, id).
Scan(&count)
return count > 0, err
}
+83
View File
@@ -0,0 +1,83 @@
package service
import (
"context"
"errors"
"strings"
"financeiro-carvalho/internal/model"
"financeiro-carvalho/internal/repository"
)
var (
ErrDefaultCategory = errors.New("default categories cannot be deleted")
ErrHasTransactions = errors.New("category has linked transactions")
ErrEmptyName = errors.New("name is required")
ErrInvalidColor = errors.New("color must be a valid hex color (e.g. #FF5733)")
)
type CategoryService struct {
repo repository.CategoryRepository
}
func NewCategoryService(repo repository.CategoryRepository) *CategoryService {
return &CategoryService{repo: repo}
}
func (s *CategoryService) List(ctx context.Context) ([]model.Category, error) {
return s.repo.List(ctx)
}
func (s *CategoryService) Create(ctx context.Context, in model.CategoryInput) (*model.Category, error) {
if err := validateInput(in); err != nil {
return nil, err
}
return s.repo.Create(ctx, strings.TrimSpace(in.Name), in.Color)
}
func (s *CategoryService) Update(ctx context.Context, id int, in model.CategoryInput) (*model.Category, error) {
if err := validateInput(in); err != nil {
return nil, err
}
return s.repo.Update(ctx, id, strings.TrimSpace(in.Name), in.Color)
}
func (s *CategoryService) Delete(ctx context.Context, id int) error {
cat, err := s.repo.GetByID(ctx, id)
if err != nil {
return err
}
if cat.IsDefault {
return ErrDefaultCategory
}
hasTx, err := s.repo.HasTransactions(ctx, id)
if err != nil {
return err
}
if hasTx {
return ErrHasTransactions
}
return s.repo.Delete(ctx, id)
}
func validateInput(in model.CategoryInput) error {
if strings.TrimSpace(in.Name) == "" {
return ErrEmptyName
}
if !isValidHexColor(in.Color) {
return ErrInvalidColor
}
return nil
}
func isValidHexColor(c string) bool {
if len(c) != 7 || c[0] != '#' {
return false
}
for _, ch := range c[1:] {
if !((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')) {
return false
}
}
return true
}
+131
View File
@@ -0,0 +1,131 @@
package service_test
import (
"context"
"testing"
"financeiro-carvalho/internal/model"
"financeiro-carvalho/internal/repository"
"financeiro-carvalho/internal/service"
)
// mockCategoryRepo implements repository.CategoryRepository in memory.
type mockCategoryRepo struct {
categories []model.Category
txCount map[int]int // category_id → transaction count
}
func newMockRepo(cats []model.Category) *mockCategoryRepo {
return &mockCategoryRepo{categories: cats, txCount: map[int]int{}}
}
func (m *mockCategoryRepo) List(_ context.Context) ([]model.Category, error) {
return m.categories, nil
}
func (m *mockCategoryRepo) GetByID(_ context.Context, id int) (*model.Category, error) {
for _, c := range m.categories {
if c.ID == id {
cp := c
return &cp, nil
}
}
return nil, repository.ErrNotFound
}
func (m *mockCategoryRepo) Create(_ context.Context, name, color string) (*model.Category, error) {
c := model.Category{ID: len(m.categories) + 1, Name: name, Color: color}
m.categories = append(m.categories, c)
return &c, nil
}
func (m *mockCategoryRepo) Update(_ context.Context, id int, name, color string) (*model.Category, error) {
for i, c := range m.categories {
if c.ID == id {
m.categories[i].Name = name
m.categories[i].Color = color
cp := m.categories[i]
return &cp, nil
}
}
return nil, repository.ErrNotFound
}
func (m *mockCategoryRepo) Delete(_ context.Context, id int) error {
for i, c := range m.categories {
if c.ID == id {
m.categories = append(m.categories[:i], m.categories[i+1:]...)
return nil
}
}
return repository.ErrNotFound
}
func (m *mockCategoryRepo) HasTransactions(_ context.Context, id int) (bool, error) {
return m.txCount[id] > 0, nil
}
// ── tests ──────────────────────────────────────────────────────────────────────
func TestDeleteDefaultCategory_Rejected(t *testing.T) {
repo := newMockRepo([]model.Category{
{ID: 1, Name: "Saúde", Color: "#EF4444", IsDefault: true},
})
svc := service.NewCategoryService(repo)
err := svc.Delete(context.Background(), 1)
if err != service.ErrDefaultCategory {
t.Fatalf("expected ErrDefaultCategory, got %v", err)
}
}
func TestDeleteCategoryWithTransactions_Rejected(t *testing.T) {
repo := newMockRepo([]model.Category{
{ID: 2, Name: "Lazer", Color: "#10B981", IsDefault: false},
})
repo.txCount[2] = 3
svc := service.NewCategoryService(repo)
err := svc.Delete(context.Background(), 2)
if err != service.ErrHasTransactions {
t.Fatalf("expected ErrHasTransactions, got %v", err)
}
}
func TestDeleteUserCategory_OK(t *testing.T) {
repo := newMockRepo([]model.Category{
{ID: 3, Name: "Minha Cat", Color: "#123456", IsDefault: false},
})
svc := service.NewCategoryService(repo)
if err := svc.Delete(context.Background(), 3); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestCreateCategory_EmptyName_Rejected(t *testing.T) {
svc := service.NewCategoryService(newMockRepo(nil))
_, err := svc.Create(context.Background(), model.CategoryInput{Name: " ", Color: "#123456"})
if err != service.ErrEmptyName {
t.Fatalf("expected ErrEmptyName, got %v", err)
}
}
func TestCreateCategory_InvalidColor_Rejected(t *testing.T) {
svc := service.NewCategoryService(newMockRepo(nil))
_, err := svc.Create(context.Background(), model.CategoryInput{Name: "X", Color: "red"})
if err != service.ErrInvalidColor {
t.Fatalf("expected ErrInvalidColor, got %v", err)
}
}
func TestCreateCategory_OK(t *testing.T) {
svc := service.NewCategoryService(newMockRepo(nil))
cat, err := svc.Create(context.Background(), model.CategoryInput{Name: "Nova", Color: "#AABBCC"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if cat.Name != "Nova" || cat.Color != "#AABBCC" {
t.Fatalf("unexpected result: %+v", cat)
}
}
+31
View File
@@ -1,3 +1,34 @@
<script setup lang="ts">
</script>
<template>
<header class="app-header">
<span class="app-title">💰 Financeiro Carvalho</span>
<nav class="app-nav">
<RouterLink to="/">Início</RouterLink>
<RouterLink to="/categorias">Categorias</RouterLink>
</nav>
</header>
<RouterView />
</template>
<style>
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; background: #f8fafc; color: #1e293b; }
a { color: inherit; text-decoration: none; }
</style>
<style scoped>
.app-header {
display: flex;
align-items: center;
gap: 2rem;
padding: 0.75rem 1.5rem;
background: #1e293b;
color: #f8fafc;
}
.app-title { font-weight: 700; font-size: 1rem; }
.app-nav { display: flex; gap: 1.25rem; }
.app-nav a { font-size: 0.875rem; opacity: 0.8; }
.app-nav a.router-link-active { opacity: 1; text-decoration: underline; }
</style>
+5
View File
@@ -9,6 +9,11 @@ const router = createRouter({
name: 'home',
component: HomeView,
},
{
path: '/categorias',
name: 'categories',
component: () => import('../views/CategoriesView.vue'),
},
],
})
+20
View File
@@ -0,0 +1,20 @@
const BASE = '/api'
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method,
headers: body ? { 'Content-Type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
})
if (res.status === 204) return undefined as T
const data = await res.json()
if (!res.ok) throw new Error(data.error ?? 'Erro desconhecido')
return data as T
}
export const api = {
get: <T>(path: string) => request<T>('GET', path),
post: <T>(path: string, body: unknown) => request<T>('POST', path, body),
put: <T>(path: string, body: unknown) => request<T>('PUT', path, body),
delete: (path: string) => request<void>('DELETE', path),
}
+50
View File
@@ -0,0 +1,50 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api } from '@/services/api'
export interface Category {
id: number
name: string
color: string
is_default: boolean
created_at: string
updated_at: string
}
export const useCategoriesStore = defineStore('categories', () => {
const categories = ref<Category[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
async function fetchAll() {
loading.value = true
error.value = null
try {
categories.value = await api.get<Category[]>('/categories')
} catch (e: any) {
error.value = e.message
} finally {
loading.value = false
}
}
async function create(name: string, color: string) {
const cat = await api.post<Category>('/categories', { name, color })
categories.value.push(cat)
return cat
}
async function update(id: number, name: string, color: string) {
const cat = await api.put<Category>(`/categories/${id}`, { name, color })
const idx = categories.value.findIndex((c) => c.id === id)
if (idx !== -1) categories.value[idx] = cat
return cat
}
async function remove(id: number) {
await api.delete(`/categories/${id}`)
categories.value = categories.value.filter((c) => c.id !== id)
}
return { categories, loading, error, fetchAll, create, update, remove }
})
+159
View File
@@ -0,0 +1,159 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useCategoriesStore } from '@/stores/categories'
const store = useCategoriesStore()
onMounted(() => store.fetchAll())
const form = ref({ name: '', color: '#6B7280' })
const editId = ref<number | null>(null)
const formError = ref<string | null>(null)
function startEdit(id: number, name: string, color: string) {
editId.value = id
form.value = { name, color }
formError.value = null
}
function cancelEdit() {
editId.value = null
form.value = { name: '', color: '#6B7280' }
formError.value = null
}
async function submit() {
formError.value = null
try {
if (editId.value !== null) {
await store.update(editId.value, form.value.name, form.value.color)
cancelEdit()
} else {
await store.create(form.value.name, form.value.color)
form.value = { name: '', color: '#6B7280' }
}
} catch (e: any) {
formError.value = e.message
}
}
async function remove(id: number, name: string) {
if (!confirm(`Excluir a categoria "${name}"?`)) return
try {
await store.remove(id)
} catch (e: any) {
alert(e.message)
}
}
</script>
<template>
<div class="page">
<h1>Categorias</h1>
<form class="form-card" @submit.prevent="submit">
<h2>{{ editId !== null ? 'Editar categoria' : 'Nova categoria' }}</h2>
<div class="field-row">
<input
v-model="form.name"
placeholder="Nome da categoria"
required
class="input-name"
/>
<div class="color-field">
<input type="color" v-model="form.color" class="input-color" />
<span class="color-hex">{{ form.color }}</span>
</div>
</div>
<p v-if="formError" class="form-error">{{ formError }}</p>
<div class="form-actions">
<button type="submit" class="btn btn-primary">
{{ editId !== null ? 'Salvar' : 'Criar' }}
</button>
<button v-if="editId !== null" type="button" class="btn btn-ghost" @click="cancelEdit">
Cancelar
</button>
</div>
</form>
<p v-if="store.loading">Carregando</p>
<p v-else-if="store.error" class="form-error">{{ store.error }}</p>
<ul v-else class="category-list">
<li
v-for="cat in store.categories"
:key="cat.id"
class="category-item"
:class="{ editing: editId === cat.id }"
>
<span class="color-dot" :style="{ background: cat.color }" />
<span class="cat-name">{{ cat.name }}</span>
<span v-if="cat.is_default" class="badge">padrão</span>
<div class="cat-actions">
<button class="btn btn-sm" @click="startEdit(cat.id, cat.name, cat.color)">Editar</button>
<button
v-if="!cat.is_default"
class="btn btn-sm btn-danger"
@click="remove(cat.id, cat.name)"
>
Excluir
</button>
</div>
</li>
</ul>
</div>
</template>
<style scoped>
.page {
max-width: 640px;
margin: 0 auto;
padding: 1.5rem 1rem;
font-family: sans-serif;
}
h1 { margin-bottom: 1.25rem; font-size: 1.5rem; }
h2 { margin: 0 0 0.75rem; font-size: 1rem; font-weight: 600; }
.form-card {
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 1rem;
margin-bottom: 1.5rem;
}
.field-row { display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap; }
.input-name { flex: 1; min-width: 0; padding: 0.5rem 0.75rem; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.95rem; }
.color-field { display: flex; align-items: center; gap: 0.25rem; }
.input-color { width: 2.5rem; height: 2.5rem; border: none; cursor: pointer; border-radius: 4px; padding: 0; }
.color-hex { font-size: 0.8rem; color: #6b7280; width: 4rem; }
.form-error { color: #dc2626; font-size: 0.875rem; margin: 0.5rem 0 0; }
.form-actions { margin-top: 0.75rem; display: flex; gap: 0.5rem; }
.btn {
padding: 0.4rem 1rem;
border: 1px solid #d1d5db;
border-radius: 6px;
cursor: pointer;
font-size: 0.875rem;
background: #fff;
}
.btn-primary { background: #4f46e5; color: #fff; border-color: #4f46e5; }
.btn-ghost { background: transparent; }
.btn-danger { color: #dc2626; border-color: #fca5a5; }
.btn-sm { padding: 0.25rem 0.6rem; }
.category-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 0.5rem; }
.category-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.65rem 0.75rem;
border: 1px solid #e5e7eb;
border-radius: 8px;
background: #fff;
}
.category-item.editing { border-color: #4f46e5; box-shadow: 0 0 0 2px #e0e7ff; }
.color-dot { width: 1rem; height: 1rem; border-radius: 50%; flex-shrink: 0; }
.cat-name { flex: 1; font-size: 0.95rem; }
.badge { font-size: 0.7rem; background: #f3f4f6; color: #6b7280; padding: 0.15rem 0.4rem; border-radius: 4px; }
.cat-actions { display: flex; gap: 0.4rem; }
</style>