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]>
This commit is contained in:
@@ -64,8 +64,12 @@ func main() {
|
||||
recurringSvc := service.NewRecurringService(recurringRepo, manualTxRepo)
|
||||
recurringHandler := handler.NewRecurringHandler(recurringSvc)
|
||||
|
||||
accountRepo := repository.NewAccountRepository(pool)
|
||||
accountSvc := service.NewAccountService(accountRepo)
|
||||
accountHandler := handler.NewAccountHandler(accountSvc)
|
||||
|
||||
dashboardRepo := repository.NewDashboardRepository(pool)
|
||||
dashboardSvc := service.NewDashboardService(dashboardRepo, recurringSvc)
|
||||
dashboardSvc := service.NewDashboardService(dashboardRepo, recurringSvc, accountRepo)
|
||||
dashboardHandler := handler.NewDashboardHandler(dashboardSvc)
|
||||
|
||||
r.Get("/health", handler.Health)
|
||||
@@ -92,6 +96,11 @@ func main() {
|
||||
r.Post("/recurring/{id}/ignore", recurringHandler.Ignore)
|
||||
r.Delete("/recurring/{id}/ignore", recurringHandler.Unignore)
|
||||
|
||||
r.Get("/accounts", accountHandler.List)
|
||||
r.Post("/accounts", accountHandler.Create)
|
||||
r.Put("/accounts/{id}", accountHandler.Update)
|
||||
r.Delete("/accounts/{id}", accountHandler.Delete)
|
||||
|
||||
r.Get("/dashboard", dashboardHandler.Get)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
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)
|
||||
}
|
||||
@@ -17,8 +17,11 @@ var m002 string
|
||||
//go:embed sql/003_recurring_ignores.sql
|
||||
var m003 string
|
||||
|
||||
//go:embed sql/004_accounts.sql
|
||||
var m004 string
|
||||
|
||||
func Run(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
migrations := []string{m001, m002, m003}
|
||||
migrations := []string{m001, m002, m003, m004}
|
||||
for i, sql := range migrations {
|
||||
if _, err := pool.Exec(ctx, sql); err != nil {
|
||||
return fmt.Errorf("migration %03d: %w", i+1, err)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
type VARCHAR(20) NOT NULL DEFAULT 'checking'
|
||||
CHECK (type IN ('checking', 'savings', 'investment', 'credit')),
|
||||
initial_balance NUMERIC(12, 2) NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS account_id INTEGER
|
||||
REFERENCES accounts (id) ON DELETE SET NULL;
|
||||
|
||||
INSERT INTO schema_migrations (version) VALUES (4) ON CONFLICT DO NOTHING;
|
||||
@@ -0,0 +1,17 @@
|
||||
package model
|
||||
|
||||
type Account struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
InitialBalance float64 `json:"initial_balance"`
|
||||
Balance float64 `json:"balance"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type AccountInput struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
InitialBalance float64 `json:"initial_balance"`
|
||||
}
|
||||
@@ -28,6 +28,7 @@ type DashboardData struct {
|
||||
TotalIncome float64 `json:"total_income"`
|
||||
TotalExpenses float64 `json:"total_expenses"`
|
||||
SavingsPct float64 `json:"savings_pct"`
|
||||
TotalPatrimony float64 `json:"total_patrimony"`
|
||||
ByCategory []CategoryTotal `json:"by_category"`
|
||||
MonthlyEvolution []MonthEvolution `json:"monthly_evolution"`
|
||||
RecentTransactions []RecentTransaction `json:"recent_transactions"`
|
||||
|
||||
@@ -10,6 +10,7 @@ type Transaction struct {
|
||||
Type string `json:"type"` // income | expense
|
||||
Source string `json:"source"` // manual | import
|
||||
CategoryID *int `json:"category_id"`
|
||||
AccountID *int `json:"account_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"financeiro-carvalho/internal/model"
|
||||
)
|
||||
|
||||
type AccountRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAccountRepository(pool *pgxpool.Pool) *AccountRepository {
|
||||
return &AccountRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *AccountRepository) List(ctx context.Context) ([]model.Account, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT
|
||||
a.id, a.name, a.type, a.initial_balance,
|
||||
a.created_at::text, a.updated_at::text,
|
||||
a.initial_balance
|
||||
+ COALESCE(SUM(CASE WHEN t.type = 'income' THEN t.amount ELSE 0 END), 0)
|
||||
- COALESCE(SUM(CASE WHEN t.type = 'expense' THEN t.amount ELSE 0 END), 0)
|
||||
AS balance
|
||||
FROM accounts a
|
||||
LEFT JOIN transactions t ON t.account_id = a.id
|
||||
GROUP BY a.id
|
||||
ORDER BY a.created_at
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []model.Account
|
||||
for rows.Next() {
|
||||
var a model.Account
|
||||
if err := rows.Scan(&a.ID, &a.Name, &a.Type, &a.InitialBalance, &a.CreatedAt, &a.UpdatedAt, &a.Balance); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *AccountRepository) GetByID(ctx context.Context, id int) (*model.Account, error) {
|
||||
var a model.Account
|
||||
err := r.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
a.id, a.name, a.type, a.initial_balance,
|
||||
a.created_at::text, a.updated_at::text,
|
||||
a.initial_balance
|
||||
+ COALESCE(SUM(CASE WHEN t.type = 'income' THEN t.amount ELSE 0 END), 0)
|
||||
- COALESCE(SUM(CASE WHEN t.type = 'expense' THEN t.amount ELSE 0 END), 0)
|
||||
AS balance
|
||||
FROM accounts a
|
||||
LEFT JOIN transactions t ON t.account_id = a.id
|
||||
WHERE a.id = $1
|
||||
GROUP BY a.id
|
||||
`, id).Scan(&a.ID, &a.Name, &a.Type, &a.InitialBalance, &a.CreatedAt, &a.UpdatedAt, &a.Balance)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (r *AccountRepository) Create(ctx context.Context, in model.AccountInput) (*model.Account, error) {
|
||||
var a model.Account
|
||||
err := r.pool.QueryRow(ctx, `
|
||||
INSERT INTO accounts (name, type, initial_balance)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, name, type, initial_balance, created_at::text, updated_at::text
|
||||
`, in.Name, in.Type, in.InitialBalance).
|
||||
Scan(&a.ID, &a.Name, &a.Type, &a.InitialBalance, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.Balance = a.InitialBalance
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (r *AccountRepository) Update(ctx context.Context, id int, in model.AccountInput) (*model.Account, error) {
|
||||
row := r.pool.QueryRow(ctx, `
|
||||
UPDATE accounts SET name=$1, type=$2, initial_balance=$3, updated_at=NOW()
|
||||
WHERE id=$4
|
||||
RETURNING id, name, type, initial_balance, created_at::text, updated_at::text
|
||||
`, in.Name, in.Type, in.InitialBalance, id)
|
||||
var a model.Account
|
||||
if err := row.Scan(&a.ID, &a.Name, &a.Type, &a.InitialBalance, &a.CreatedAt, &a.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// recalculate balance
|
||||
full, err := r.GetByID(ctx, a.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return full, nil
|
||||
}
|
||||
|
||||
func (r *AccountRepository) Delete(ctx context.Context, id int) error {
|
||||
_, err := r.pool.Exec(ctx, `DELETE FROM accounts WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *AccountRepository) TotalPatrimony(ctx context.Context) (float64, error) {
|
||||
var total float64
|
||||
err := r.pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(SUM(
|
||||
a.initial_balance
|
||||
+ COALESCE((
|
||||
SELECT SUM(CASE WHEN type='income' THEN amount ELSE -amount END)
|
||||
FROM transactions WHERE account_id = a.id
|
||||
), 0)
|
||||
), 0)
|
||||
FROM accounts a
|
||||
`).Scan(&total)
|
||||
return total, err
|
||||
}
|
||||
@@ -28,7 +28,7 @@ func NewManualTransactionRepository(db *pgxpool.Pool) ManualTransactionRepositor
|
||||
|
||||
func (r *manualTxRepo) List(ctx context.Context, month string) ([]model.Transaction, error) {
|
||||
query := `
|
||||
SELECT id, date::text, amount, description, type, source, category_id, created_at, updated_at
|
||||
SELECT id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at
|
||||
FROM transactions`
|
||||
args := []any{}
|
||||
if month != "" {
|
||||
@@ -46,7 +46,7 @@ func (r *manualTxRepo) List(ctx context.Context, month string) ([]model.Transact
|
||||
var out []model.Transaction
|
||||
for rows.Next() {
|
||||
var t model.Transaction
|
||||
if err := rows.Scan(&t.ID, &t.Date, &t.Amount, &t.Description, &t.Type, &t.Source, &t.CategoryID, &t.CreatedAt, &t.UpdatedAt); err != nil {
|
||||
if err := rows.Scan(&t.ID, &t.Date, &t.Amount, &t.Description, &t.Type, &t.Source, &t.CategoryID, &t.AccountID, &t.CreatedAt, &t.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, t)
|
||||
@@ -57,9 +57,9 @@ func (r *manualTxRepo) List(ctx context.Context, month string) ([]model.Transact
|
||||
func (r *manualTxRepo) GetByID(ctx context.Context, id int) (*model.Transaction, error) {
|
||||
var t model.Transaction
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT id, date::text, amount, description, type, source, category_id, created_at, updated_at
|
||||
SELECT id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at
|
||||
FROM transactions WHERE id = $1`, id).
|
||||
Scan(&t.ID, &t.Date, &t.Amount, &t.Description, &t.Type, &t.Source, &t.CategoryID, &t.CreatedAt, &t.UpdatedAt)
|
||||
Scan(&t.ID, &t.Date, &t.Amount, &t.Description, &t.Type, &t.Source, &t.CategoryID, &t.AccountID, &t.CreatedAt, &t.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
@@ -69,11 +69,11 @@ func (r *manualTxRepo) GetByID(ctx context.Context, id int) (*model.Transaction,
|
||||
func (r *manualTxRepo) Create(ctx context.Context, t model.Transaction) (*model.Transaction, error) {
|
||||
var out model.Transaction
|
||||
err := r.db.QueryRow(ctx, `
|
||||
INSERT INTO transactions (date, amount, description, type, source, category_id)
|
||||
VALUES ($1, $2, $3, $4, 'manual', $5)
|
||||
RETURNING id, date::text, amount, description, type, source, category_id, created_at, updated_at`,
|
||||
t.Date, t.Amount, t.Description, t.Type, t.CategoryID).
|
||||
Scan(&out.ID, &out.Date, &out.Amount, &out.Description, &out.Type, &out.Source, &out.CategoryID, &out.CreatedAt, &out.UpdatedAt)
|
||||
INSERT INTO transactions (date, amount, description, type, source, category_id, account_id)
|
||||
VALUES ($1, $2, $3, $4, 'manual', $5, $6)
|
||||
RETURNING id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at`,
|
||||
t.Date, t.Amount, t.Description, t.Type, t.CategoryID, t.AccountID).
|
||||
Scan(&out.ID, &out.Date, &out.Amount, &out.Description, &out.Type, &out.Source, &out.CategoryID, &out.AccountID, &out.CreatedAt, &out.UpdatedAt)
|
||||
return &out, err
|
||||
}
|
||||
|
||||
@@ -81,11 +81,11 @@ func (r *manualTxRepo) Update(ctx context.Context, t model.Transaction) (*model.
|
||||
var out model.Transaction
|
||||
err := r.db.QueryRow(ctx, `
|
||||
UPDATE transactions
|
||||
SET date = $1, amount = $2, description = $3, type = $4, category_id = $5, updated_at = NOW()
|
||||
WHERE id = $6 AND source = 'manual'
|
||||
RETURNING id, date::text, amount, description, type, source, category_id, created_at, updated_at`,
|
||||
t.Date, t.Amount, t.Description, t.Type, t.CategoryID, t.ID).
|
||||
Scan(&out.ID, &out.Date, &out.Amount, &out.Description, &out.Type, &out.Source, &out.CategoryID, &out.CreatedAt, &out.UpdatedAt)
|
||||
SET date=$1, amount=$2, description=$3, type=$4, category_id=$5, account_id=$6, updated_at=NOW()
|
||||
WHERE id=$7 AND source='manual'
|
||||
RETURNING id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at`,
|
||||
t.Date, t.Amount, t.Description, t.Type, t.CategoryID, t.AccountID, t.ID).
|
||||
Scan(&out.ID, &out.Date, &out.Amount, &out.Description, &out.Type, &out.Source, &out.CategoryID, &out.AccountID, &out.CreatedAt, &out.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"financeiro-carvalho/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAccountEmptyName = errors.New("account name cannot be empty")
|
||||
ErrAccountInvalidType = errors.New("account type must be checking, savings, investment, or credit")
|
||||
)
|
||||
|
||||
var validAccountTypes = map[string]bool{
|
||||
"checking": true, "savings": true, "investment": true, "credit": true,
|
||||
}
|
||||
|
||||
type AccountRepo interface {
|
||||
List(ctx context.Context) ([]model.Account, error)
|
||||
GetByID(ctx context.Context, id int) (*model.Account, error)
|
||||
Create(ctx context.Context, in model.AccountInput) (*model.Account, error)
|
||||
Update(ctx context.Context, id int, in model.AccountInput) (*model.Account, error)
|
||||
Delete(ctx context.Context, id int) error
|
||||
TotalPatrimony(ctx context.Context) (float64, error)
|
||||
}
|
||||
|
||||
type AccountService struct {
|
||||
repo AccountRepo
|
||||
}
|
||||
|
||||
func NewAccountService(repo AccountRepo) *AccountService {
|
||||
return &AccountService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *AccountService) validate(in model.AccountInput) error {
|
||||
if in.Name == "" {
|
||||
return ErrAccountEmptyName
|
||||
}
|
||||
if !validAccountTypes[in.Type] {
|
||||
return ErrAccountInvalidType
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AccountService) List(ctx context.Context) ([]model.Account, error) {
|
||||
return s.repo.List(ctx)
|
||||
}
|
||||
|
||||
func (s *AccountService) Create(ctx context.Context, in model.AccountInput) (*model.Account, error) {
|
||||
if err := s.validate(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.Create(ctx, in)
|
||||
}
|
||||
|
||||
func (s *AccountService) Update(ctx context.Context, id int, in model.AccountInput) (*model.Account, error) {
|
||||
if err := s.validate(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repo.Update(ctx, id, in)
|
||||
}
|
||||
|
||||
func (s *AccountService) Delete(ctx context.Context, id int) error {
|
||||
return s.repo.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func (s *AccountService) TotalPatrimony(ctx context.Context) (float64, error) {
|
||||
return s.repo.TotalPatrimony(ctx)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package service_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"financeiro-carvalho/internal/model"
|
||||
"financeiro-carvalho/internal/service"
|
||||
)
|
||||
|
||||
type mockAccountRepo struct {
|
||||
items []model.Account
|
||||
}
|
||||
|
||||
func (m *mockAccountRepo) List(_ context.Context) ([]model.Account, error) { return m.items, nil }
|
||||
func (m *mockAccountRepo) GetByID(_ context.Context, id int) (*model.Account, error) {
|
||||
for _, a := range m.items {
|
||||
if a.ID == id {
|
||||
cp := a
|
||||
return &cp, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func (m *mockAccountRepo) Create(_ context.Context, in model.AccountInput) (*model.Account, error) {
|
||||
a := model.Account{ID: len(m.items) + 1, Name: in.Name, Type: in.Type, InitialBalance: in.InitialBalance, Balance: in.InitialBalance}
|
||||
m.items = append(m.items, a)
|
||||
return &a, nil
|
||||
}
|
||||
func (m *mockAccountRepo) Update(_ context.Context, id int, in model.AccountInput) (*model.Account, error) {
|
||||
for i, a := range m.items {
|
||||
if a.ID == id {
|
||||
m.items[i].Name = in.Name
|
||||
cp := m.items[i]
|
||||
return &cp, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func (m *mockAccountRepo) Delete(_ context.Context, _ int) error { return nil }
|
||||
func (m *mockAccountRepo) TotalPatrimony(_ context.Context) (float64, error) { return 0, nil }
|
||||
|
||||
func TestCreateAccount_EmptyName(t *testing.T) {
|
||||
svc := service.NewAccountService(&mockAccountRepo{})
|
||||
_, err := svc.Create(context.Background(), model.AccountInput{Name: "", Type: "checking", InitialBalance: 0})
|
||||
if err != service.ErrAccountEmptyName {
|
||||
t.Fatalf("expected ErrAccountEmptyName, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAccount_InvalidType(t *testing.T) {
|
||||
svc := service.NewAccountService(&mockAccountRepo{})
|
||||
_, err := svc.Create(context.Background(), model.AccountInput{Name: "Nubank", Type: "bitcoin"})
|
||||
if err != service.ErrAccountInvalidType {
|
||||
t.Fatalf("expected ErrAccountInvalidType, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAccount_OK(t *testing.T) {
|
||||
svc := service.NewAccountService(&mockAccountRepo{})
|
||||
a, err := svc.Create(context.Background(), model.AccountInput{Name: "Nubank", Type: "checking", InitialBalance: 1000})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Name != "Nubank" || a.Balance != 1000 {
|
||||
t.Errorf("unexpected account: %+v", a)
|
||||
}
|
||||
}
|
||||
@@ -13,13 +13,18 @@ type DashboardRepo interface {
|
||||
RecentTransactions(ctx context.Context, month string) ([]model.RecentTransaction, error)
|
||||
}
|
||||
|
||||
type PatrimonySource interface {
|
||||
TotalPatrimony(ctx context.Context) (float64, error)
|
||||
}
|
||||
|
||||
type DashboardService struct {
|
||||
repo DashboardRepo
|
||||
recurrSvc *RecurringService
|
||||
patrimony PatrimonySource
|
||||
}
|
||||
|
||||
func NewDashboardService(repo DashboardRepo, recurrSvc *RecurringService) *DashboardService {
|
||||
return &DashboardService{repo: repo, recurrSvc: recurrSvc}
|
||||
func NewDashboardService(repo DashboardRepo, recurrSvc *RecurringService, patrimony PatrimonySource) *DashboardService {
|
||||
return &DashboardService{repo: repo, recurrSvc: recurrSvc, patrimony: patrimony}
|
||||
}
|
||||
|
||||
func (s *DashboardService) Get(ctx context.Context, month string) (*model.DashboardData, error) {
|
||||
@@ -69,11 +74,17 @@ func (s *DashboardService) Get(ctx context.Context, month string) (*model.Dashbo
|
||||
recent = []model.RecentTransaction{}
|
||||
}
|
||||
|
||||
patrimony, err := s.patrimony.TotalPatrimony(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &model.DashboardData{
|
||||
Month: month,
|
||||
TotalIncome: income,
|
||||
TotalExpenses: expenses,
|
||||
SavingsPct: savingsPct,
|
||||
TotalPatrimony: patrimony,
|
||||
ByCategory: byCategory,
|
||||
MonthlyEvolution: evolution,
|
||||
RecentTransactions: recent,
|
||||
|
||||
@@ -26,9 +26,13 @@ func (m *mockDashboardRepo) RecentTransactions(_ context.Context, _ string) ([]m
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type mockPatrimony struct{}
|
||||
|
||||
func (m *mockPatrimony) TotalPatrimony(_ context.Context) (float64, error) { return 0, nil }
|
||||
|
||||
func newDashboardSvc(income, expenses float64) *service.DashboardService {
|
||||
recurrSvc := service.NewRecurringService(newMockRecurring(nil), &mockTxRepo{})
|
||||
return service.NewDashboardService(&mockDashboardRepo{income: income, expenses: expenses}, recurrSvc)
|
||||
return service.NewDashboardService(&mockDashboardRepo{income: income, expenses: expenses}, recurrSvc, &mockPatrimony{})
|
||||
}
|
||||
|
||||
func TestDashboard_SavingsPct_40(t *testing.T) {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<RouterLink to="/categorias">Categorias</RouterLink>
|
||||
<RouterLink to="/transacoes">Transações</RouterLink>
|
||||
<RouterLink to="/importar">Importar</RouterLink>
|
||||
<RouterLink to="/contas">Contas</RouterLink>
|
||||
<RouterLink to="/configuracoes">Configurações</RouterLink>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
@@ -24,6 +24,11 @@ const router = createRouter({
|
||||
name: 'transactions',
|
||||
component: () => import('../views/TransactionsView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/contas',
|
||||
name: 'accounts',
|
||||
component: () => import('../views/AccountsView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/configuracoes',
|
||||
name: 'settings',
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api } from '@/services/api'
|
||||
|
||||
export interface Account {
|
||||
id: number
|
||||
name: string
|
||||
type: 'checking' | 'savings' | 'investment' | 'credit'
|
||||
initial_balance: number
|
||||
balance: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface AccountInput {
|
||||
name: string
|
||||
type: string
|
||||
initial_balance: number
|
||||
}
|
||||
|
||||
export const useAccountsStore = defineStore('accounts', () => {
|
||||
const accounts = ref<Account[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
async function fetchAll() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
accounts.value = await api.get<Account[]>('/accounts')
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function create(input: AccountInput) {
|
||||
const item = await api.post<Account>('/accounts', input)
|
||||
accounts.value.push(item)
|
||||
return item
|
||||
}
|
||||
|
||||
async function update(id: number, input: AccountInput) {
|
||||
const item = await api.put<Account>(`/accounts/${id}`, input)
|
||||
const idx = accounts.value.findIndex((a) => a.id === id)
|
||||
if (idx !== -1) accounts.value[idx] = item
|
||||
return item
|
||||
}
|
||||
|
||||
async function remove(id: number) {
|
||||
await api.delete(`/accounts/${id}`)
|
||||
accounts.value = accounts.value.filter((a) => a.id !== id)
|
||||
}
|
||||
|
||||
return { accounts, loading, error, fetchAll, create, update, remove }
|
||||
})
|
||||
@@ -30,6 +30,7 @@ export interface DashboardData {
|
||||
total_income: number
|
||||
total_expenses: number
|
||||
savings_pct: number
|
||||
total_patrimony: number
|
||||
by_category: CategoryTotal[]
|
||||
monthly_evolution: MonthEvolution[]
|
||||
recent_transactions: RecentTransaction[]
|
||||
|
||||
@@ -10,6 +10,7 @@ export interface Transaction {
|
||||
type: 'income' | 'expense'
|
||||
source: 'manual' | 'import'
|
||||
category_id: number | null
|
||||
account_id: number | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -20,6 +21,7 @@ export interface TransactionInput {
|
||||
description: string
|
||||
type: 'income' | 'expense'
|
||||
category_id: number | null
|
||||
account_id: number | null
|
||||
}
|
||||
|
||||
export const useTransactionsStore = defineStore('transactions', () => {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useAccountsStore, type AccountInput } from '@/stores/accounts'
|
||||
|
||||
const store = useAccountsStore()
|
||||
|
||||
onMounted(() => store.fetchAll())
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
checking: 'Conta Corrente',
|
||||
savings: 'Poupança',
|
||||
investment: 'Investimento',
|
||||
credit: 'Cartão de Crédito',
|
||||
}
|
||||
|
||||
const blank = (): AccountInput => ({ name: '', type: 'checking', initial_balance: 0 })
|
||||
const form = ref(blank())
|
||||
const editId = ref<number | null>(null)
|
||||
const initialRaw = ref('')
|
||||
const formError = ref<string | null>(null)
|
||||
|
||||
function parseAmount(s: string) {
|
||||
return parseFloat(s.replace(/\./g, '').replace(',', '.')) || 0
|
||||
}
|
||||
|
||||
function startEdit(id: number) {
|
||||
const a = store.accounts.find((x) => x.id === id)
|
||||
if (!a) return
|
||||
editId.value = id
|
||||
form.value = { name: a.name, type: a.type, initial_balance: a.initial_balance }
|
||||
initialRaw.value = a.initial_balance.toLocaleString('pt-BR', { minimumFractionDigits: 2 })
|
||||
formError.value = null
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
editId.value = null
|
||||
form.value = blank()
|
||||
initialRaw.value = ''
|
||||
formError.value = null
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
formError.value = null
|
||||
form.value.initial_balance = parseAmount(initialRaw.value)
|
||||
try {
|
||||
if (editId.value !== null) {
|
||||
await store.update(editId.value, form.value)
|
||||
cancelEdit()
|
||||
} else {
|
||||
await store.create(form.value)
|
||||
form.value = blank()
|
||||
initialRaw.value = ''
|
||||
}
|
||||
} catch (e: any) {
|
||||
formError.value = e.message
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id: number, name: string) {
|
||||
if (!confirm(`Excluir conta "${name}"?`)) return
|
||||
await store.remove(id)
|
||||
}
|
||||
|
||||
function fmt(v: number) {
|
||||
return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<h1>Contas Bancárias</h1>
|
||||
|
||||
<form class="form-card" @submit.prevent="submit">
|
||||
<h2>{{ editId !== null ? 'Editar conta' : 'Nova conta' }}</h2>
|
||||
<div class="form-row">
|
||||
<input v-model="form.name" placeholder="Ex: Nubank Corrente" required class="input-name" />
|
||||
<select v-model="form.type" class="input-sm">
|
||||
<option value="checking">Conta Corrente</option>
|
||||
<option value="savings">Poupança</option>
|
||||
<option value="investment">Investimento</option>
|
||||
<option value="credit">Cartão de Crédito</option>
|
||||
</select>
|
||||
<input v-model="initialRaw" placeholder="Saldo inicial (ex: 1.500,00)" class="input-sm input-amount" />
|
||||
</div>
|
||||
<p v-if="formError" class="form-error">{{ formError }}</p>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary">{{ editId !== null ? 'Salvar' : 'Adicionar' }}</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>
|
||||
|
||||
<div v-else>
|
||||
<div class="total-bar" v-if="store.accounts.length > 0">
|
||||
<span>Patrimônio total</span>
|
||||
<strong>{{ fmt(store.accounts.reduce((s, a) => s + a.balance, 0)) }}</strong>
|
||||
</div>
|
||||
|
||||
<ul class="account-list">
|
||||
<li
|
||||
v-for="a in store.accounts"
|
||||
:key="a.id"
|
||||
class="account-item"
|
||||
:class="{ editing: editId === a.id }"
|
||||
>
|
||||
<div class="account-info">
|
||||
<strong>{{ a.name }}</strong>
|
||||
<span class="account-meta">{{ typeLabels[a.type] }} · Saldo inicial {{ fmt(a.initial_balance) }}</span>
|
||||
</div>
|
||||
<div class="account-right">
|
||||
<span class="account-balance" :class="a.balance >= 0 ? 'positive' : 'negative'">
|
||||
{{ fmt(a.balance) }}
|
||||
</span>
|
||||
<div class="item-actions">
|
||||
<button class="btn btn-sm" @click="startEdit(a.id)">Editar</button>
|
||||
<button class="btn btn-sm btn-danger" @click="remove(a.id, a.name)">Excluir</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="store.accounts.length === 0" class="empty">Nenhuma conta cadastrada</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page { max-width: 640px; margin: 0 auto; padding: 1.5rem 1rem; font-family: sans-serif; }
|
||||
h1 { font-size: 1.5rem; margin-bottom: 1.25rem; }
|
||||
h2 { font-size: 0.95rem; font-weight: 600; margin: 0 0 0.75rem; }
|
||||
.form-card { background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem; }
|
||||
.form-row { display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center; }
|
||||
.input-name { flex: 1; min-width: 160px; padding: 0.45rem 0.6rem; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.875rem; }
|
||||
.input-sm { padding: 0.45rem 0.6rem; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.875rem; }
|
||||
.input-amount { width: 140px; }
|
||||
.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-sm { padding: 0.25rem 0.6rem; }
|
||||
.btn-danger { color: #dc2626; border-color: #fca5a5; }
|
||||
.total-bar { display: flex; justify-content: space-between; align-items: center; background: #1e293b; color: #f8fafc; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; font-size: 0.9rem; }
|
||||
.total-bar strong { font-size: 1.1rem; }
|
||||
.account-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 0.5rem; }
|
||||
.account-item { display: flex; align-items: center; justify-content: space-between; padding: 0.75rem 1rem; border: 1px solid #e5e7eb; border-radius: 8px; background: #fff; flex-wrap: wrap; gap: 0.5rem; }
|
||||
.account-item.editing { border-color: #4f46e5; box-shadow: 0 0 0 2px #e0e7ff; }
|
||||
.account-info { display: flex; flex-direction: column; gap: 0.2rem; }
|
||||
.account-meta { font-size: 0.8rem; color: #6b7280; }
|
||||
.account-right { display: flex; align-items: center; gap: 1rem; }
|
||||
.account-balance { font-size: 1.1rem; font-weight: 700; }
|
||||
.positive { color: #059669; }
|
||||
.negative { color: #dc2626; }
|
||||
.item-actions { display: flex; gap: 0.4rem; }
|
||||
.empty { color: #9ca3af; text-align: center; padding: 2rem; }
|
||||
</style>
|
||||
@@ -76,6 +76,13 @@ const maxEvolution = computed(() => {
|
||||
<div class="savings-pct">{{ store.data.savings_pct.toFixed(1) }}%</div>
|
||||
<div class="savings-target">Meta: 40%</div>
|
||||
</div>
|
||||
<div class="card patrimony-card" v-if="store.data.total_patrimony > 0 || store.data.total_patrimony < 0">
|
||||
<div class="card-label">Patrimônio</div>
|
||||
<div class="card-value" :class="store.data.total_patrimony >= 0 ? 'income' : 'expense'">
|
||||
{{ fmt(store.data.total_patrimony) }}
|
||||
</div>
|
||||
<div class="savings-target">todas as contas</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom section: two columns on wide, stacked on mobile -->
|
||||
@@ -171,7 +178,7 @@ h2 { font-size: 0.95rem; font-weight: 600; margin: 0 0 0.75rem; color: #374151;
|
||||
}
|
||||
|
||||
/* Summary */
|
||||
.summary-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.75rem; margin-bottom: 1rem; }
|
||||
.summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 0.75rem; margin-bottom: 1rem; }
|
||||
@media (max-width: 600px) { .summary-grid { grid-template-columns: 1fr 1fr; } }
|
||||
|
||||
.card { background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; padding: 1rem; }
|
||||
|
||||
@@ -2,15 +2,18 @@
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useTransactionsStore, type TransactionInput } from '@/stores/transactions'
|
||||
import { useCategoriesStore } from '@/stores/categories'
|
||||
import { useAccountsStore } from '@/stores/accounts'
|
||||
|
||||
const store = useTransactionsStore()
|
||||
const catStore = useCategoriesStore()
|
||||
const accStore = useAccountsStore()
|
||||
|
||||
const currentMonth = ref(new Date().toISOString().slice(0, 7))
|
||||
|
||||
onMounted(() => {
|
||||
store.fetchAll(currentMonth.value)
|
||||
catStore.fetchAll()
|
||||
accStore.fetchAll()
|
||||
})
|
||||
|
||||
function changeMonth(delta: number) {
|
||||
@@ -26,6 +29,7 @@ const blank = (): TransactionInput => ({
|
||||
description: '',
|
||||
type: 'expense',
|
||||
category_id: null,
|
||||
account_id: null,
|
||||
})
|
||||
|
||||
const form = ref(blank())
|
||||
@@ -41,7 +45,7 @@ function startEdit(id: number) {
|
||||
const t = store.transactions.find((x) => x.id === id)
|
||||
if (!t || t.source !== 'manual') return
|
||||
editId.value = id
|
||||
form.value = { date: t.date, amount: t.amount, description: t.description, type: t.type as any, category_id: t.category_id }
|
||||
form.value = { date: t.date, amount: t.amount, description: t.description, type: t.type as any, category_id: t.category_id, account_id: t.account_id }
|
||||
amountRaw.value = t.amount.toLocaleString('pt-BR', { minimumFractionDigits: 2 })
|
||||
formError.value = null
|
||||
}
|
||||
@@ -118,6 +122,10 @@ function catName(id: number | null) {
|
||||
<option :value="null">Sem categoria</option>
|
||||
<option v-for="c in catStore.categories" :key="c.id" :value="c.id">{{ c.name }}</option>
|
||||
</select>
|
||||
<select v-model="form.account_id" class="input-sm">
|
||||
<option :value="null">Sem conta</option>
|
||||
<option v-for="a in accStore.accounts" :key="a.id" :value="a.id">{{ a.name }}</option>
|
||||
</select>
|
||||
<input v-model="form.description" placeholder="Descrição" required class="input-desc" />
|
||||
</div>
|
||||
<p v-if="formError" class="form-error">{{ formError }}</p>
|
||||
|
||||
Reference in New Issue
Block a user