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 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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user