diff --git a/apps/api/cmd/server/main.go b/apps/api/cmd/server/main.go index 10055ee..70bc65a 100644 --- a/apps/api/cmd/server/main.go +++ b/apps/api/cmd/server/main.go @@ -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) }) diff --git a/apps/api/internal/handler/account.go b/apps/api/internal/handler/account.go new file mode 100644 index 0000000..4c10c31 --- /dev/null +++ b/apps/api/internal/handler/account.go @@ -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) +} diff --git a/apps/api/internal/migration/migration.go b/apps/api/internal/migration/migration.go index 190239b..a5b588b 100644 --- a/apps/api/internal/migration/migration.go +++ b/apps/api/internal/migration/migration.go @@ -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) diff --git a/apps/api/internal/migration/sql/004_accounts.sql b/apps/api/internal/migration/sql/004_accounts.sql new file mode 100644 index 0000000..df269b6 --- /dev/null +++ b/apps/api/internal/migration/sql/004_accounts.sql @@ -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; diff --git a/apps/api/internal/model/account.go b/apps/api/internal/model/account.go new file mode 100644 index 0000000..f3c7d52 --- /dev/null +++ b/apps/api/internal/model/account.go @@ -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"` +} diff --git a/apps/api/internal/model/dashboard.go b/apps/api/internal/model/dashboard.go index f556854..889e712 100644 --- a/apps/api/internal/model/dashboard.go +++ b/apps/api/internal/model/dashboard.go @@ -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"` diff --git a/apps/api/internal/model/transaction.go b/apps/api/internal/model/transaction.go index ce2645b..3f5d77d 100644 --- a/apps/api/internal/model/transaction.go +++ b/apps/api/internal/model/transaction.go @@ -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"` } diff --git a/apps/api/internal/repository/account.go b/apps/api/internal/repository/account.go new file mode 100644 index 0000000..4e3656a --- /dev/null +++ b/apps/api/internal/repository/account.go @@ -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 +} diff --git a/apps/api/internal/repository/transaction_manual.go b/apps/api/internal/repository/transaction_manual.go index 6a58915..36d55aa 100644 --- a/apps/api/internal/repository/transaction_manual.go +++ b/apps/api/internal/repository/transaction_manual.go @@ -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 } diff --git a/apps/api/internal/service/account.go b/apps/api/internal/service/account.go new file mode 100644 index 0000000..5172c58 --- /dev/null +++ b/apps/api/internal/service/account.go @@ -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) +} diff --git a/apps/api/internal/service/account_test.go b/apps/api/internal/service/account_test.go new file mode 100644 index 0000000..0d0eb72 --- /dev/null +++ b/apps/api/internal/service/account_test.go @@ -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) + } +} diff --git a/apps/api/internal/service/dashboard.go b/apps/api/internal/service/dashboard.go index 2fb274d..0028f45 100644 --- a/apps/api/internal/service/dashboard.go +++ b/apps/api/internal/service/dashboard.go @@ -13,13 +13,18 @@ type DashboardRepo interface { RecentTransactions(ctx context.Context, month string) ([]model.RecentTransaction, error) } -type DashboardService struct { - repo DashboardRepo - recurrSvc *RecurringService +type PatrimonySource interface { + TotalPatrimony(ctx context.Context) (float64, error) } -func NewDashboardService(repo DashboardRepo, recurrSvc *RecurringService) *DashboardService { - return &DashboardService{repo: repo, recurrSvc: recurrSvc} +type DashboardService struct { + repo DashboardRepo + recurrSvc *RecurringService + patrimony PatrimonySource +} + +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, diff --git a/apps/api/internal/service/dashboard_test.go b/apps/api/internal/service/dashboard_test.go index 0b1ed09..737719d 100644 --- a/apps/api/internal/service/dashboard_test.go +++ b/apps/api/internal/service/dashboard_test.go @@ -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) { diff --git a/apps/web/src/App.vue b/apps/web/src/App.vue index 4d2b5af..09a7e60 100644 --- a/apps/web/src/App.vue +++ b/apps/web/src/App.vue @@ -9,6 +9,7 @@ Categorias Transações Importar + Contas Configurações diff --git a/apps/web/src/router/index.ts b/apps/web/src/router/index.ts index 7b42dc6..1174d3c 100644 --- a/apps/web/src/router/index.ts +++ b/apps/web/src/router/index.ts @@ -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', diff --git a/apps/web/src/stores/accounts.ts b/apps/web/src/stores/accounts.ts new file mode 100644 index 0000000..95ae48b --- /dev/null +++ b/apps/web/src/stores/accounts.ts @@ -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([]) + const loading = ref(false) + const error = ref(null) + + async function fetchAll() { + loading.value = true + error.value = null + try { + accounts.value = await api.get('/accounts') + } catch (e: any) { + error.value = e.message + } finally { + loading.value = false + } + } + + async function create(input: AccountInput) { + const item = await api.post('/accounts', input) + accounts.value.push(item) + return item + } + + async function update(id: number, input: AccountInput) { + const item = await api.put(`/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 } +}) diff --git a/apps/web/src/stores/dashboard.ts b/apps/web/src/stores/dashboard.ts index 2973afb..c6f8bbe 100644 --- a/apps/web/src/stores/dashboard.ts +++ b/apps/web/src/stores/dashboard.ts @@ -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[] diff --git a/apps/web/src/stores/transactions.ts b/apps/web/src/stores/transactions.ts index f594abe..cdc853d 100644 --- a/apps/web/src/stores/transactions.ts +++ b/apps/web/src/stores/transactions.ts @@ -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', () => { diff --git a/apps/web/src/views/AccountsView.vue b/apps/web/src/views/AccountsView.vue new file mode 100644 index 0000000..b4d564e --- /dev/null +++ b/apps/web/src/views/AccountsView.vue @@ -0,0 +1,156 @@ + + + + + diff --git a/apps/web/src/views/HomeView.vue b/apps/web/src/views/HomeView.vue index f3f1192..064a4db 100644 --- a/apps/web/src/views/HomeView.vue +++ b/apps/web/src/views/HomeView.vue @@ -76,6 +76,13 @@ const maxEvolution = computed(() => {
{{ store.data.savings_pct.toFixed(1) }}%
Meta: 40%
+
+
Patrimônio
+
+ {{ fmt(store.data.total_patrimony) }} +
+
todas as contas
+
@@ -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; } diff --git a/apps/web/src/views/TransactionsView.vue b/apps/web/src/views/TransactionsView.vue index 1af6b07..2e7cc26 100644 --- a/apps/web/src/views/TransactionsView.vue +++ b/apps/web/src/views/TransactionsView.vue @@ -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) { +

{{ formError }}