Files
carvalho-finances/apps/api/internal/repository/transaction_manual.go
T
Mlcavalho1andClaude Sonnet 4.6 acbce4edc0 feat: multi-usuário com autenticação JWT
- Tabela `profiles` + coluna `profile_id` em todas as entidades
  (categories, transactions, recurring_expenses, accounts, player_profile,
   xp_events, player_quests, player_achievements, player_cosmetics)
- Dados existentes migrados para profile_id = 1 (Manoel)
- CLI `./api create-user --name <n> --password <p>` cria perfil com
  seed de categorias e player_profile; faz upsert de senha se já existir
- Auth substituída: cookie+APP_PASSWORD → JWT Bearer 24h (HS256)
- Middleware RequireAuth injeta profile_id no context de todas as rotas
- Todos os repositórios filtram por profile_id do context
- Endpoints: POST /api/auth/login, GET /api/auth/me,
  POST /api/auth/change-password, POST /api/logout
- Frontend: auth store usa localStorage (fc_token/fc_profile),
  api.ts envia Authorization header, LoginView usa campo name
- SettingsView reescrita com troca de senha e logout
- docker-compose.yml: remove APP_USERNAME/APP_PASSWORD, adiciona JWT_SECRET

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-05-27 20:04:44 -03:00

138 lines
4.9 KiB
Go

package repository
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"financeiro-carvalho/internal/middleware"
"financeiro-carvalho/internal/model"
)
type ManualTransactionRepository interface {
List(ctx context.Context, month string) ([]model.Transaction, error)
GetByID(ctx context.Context, id int) (*model.Transaction, error)
Create(ctx context.Context, t model.Transaction) (*model.Transaction, error)
Update(ctx context.Context, t model.Transaction) (*model.Transaction, error)
Delete(ctx context.Context, id int) error
DeleteByMonth(ctx context.Context, month string) (int, error)
HasMatchingTransaction(ctx context.Context, categoryID *int, month string, amount float64, txType string) (bool, error)
}
type manualTxRepo struct{ db *pgxpool.Pool }
func NewManualTransactionRepository(db *pgxpool.Pool) ManualTransactionRepository {
return &manualTxRepo{db: db}
}
func (r *manualTxRepo) List(ctx context.Context, month string) ([]model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
query := `
SELECT id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at
FROM transactions WHERE profile_id = $1`
args := []any{pid}
if month != "" {
query += ` AND TO_CHAR(date, 'YYYY-MM') = $2`
args = append(args, month)
}
query += ` ORDER BY date DESC, id DESC`
rows, err := r.db.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
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.AccountID, &t.CreatedAt, &t.UpdatedAt); err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
func (r *manualTxRepo) GetByID(ctx context.Context, id int) (*model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
var t model.Transaction
err := r.db.QueryRow(ctx, `
SELECT id, date::text, amount, description, type, source, category_id, account_id, created_at, updated_at
FROM transactions WHERE id = $1 AND profile_id = $2`, id, pid).
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
}
return &t, err
}
func (r *manualTxRepo) Create(ctx context.Context, t model.Transaction) (*model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
var out model.Transaction
err := r.db.QueryRow(ctx, `
INSERT INTO transactions (date, amount, description, type, source, category_id, account_id, profile_id)
VALUES ($1, $2, $3, $4, 'manual', $5, $6, $7)
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, pid).
Scan(&out.ID, &out.Date, &out.Amount, &out.Description, &out.Type, &out.Source, &out.CategoryID, &out.AccountID, &out.CreatedAt, &out.UpdatedAt)
return &out, err
}
func (r *manualTxRepo) Update(ctx context.Context, t model.Transaction) (*model.Transaction, error) {
pid := middleware.ProfileIDFromCtx(ctx)
var out model.Transaction
err := r.db.QueryRow(ctx, `
UPDATE transactions
SET date=$1, amount=$2, description=$3, type=$4, category_id=$5, account_id=$6, updated_at=NOW()
WHERE id=$7 AND source='manual' AND profile_id=$8
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, pid).
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
}
return &out, err
}
func (r *manualTxRepo) Delete(ctx context.Context, id int) error {
pid := middleware.ProfileIDFromCtx(ctx)
tag, err := r.db.Exec(ctx, `DELETE FROM transactions WHERE id = $1 AND profile_id = $2`, id, pid)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (r *manualTxRepo) DeleteByMonth(ctx context.Context, month string) (int, error) {
pid := middleware.ProfileIDFromCtx(ctx)
tag, err := r.db.Exec(ctx,
`DELETE FROM transactions WHERE TO_CHAR(date, 'YYYY-MM') = $1 AND profile_id = $2`, month, pid)
if err != nil {
return 0, err
}
return int(tag.RowsAffected()), nil
}
func (r *manualTxRepo) HasMatchingTransaction(ctx context.Context, categoryID *int, month string, amount float64, txType string) (bool, error) {
if categoryID == nil {
return false, nil
}
pid := middleware.ProfileIDFromCtx(ctx)
var count int
err := r.db.QueryRow(ctx, `
SELECT COUNT(*) FROM transactions
WHERE category_id = $1
AND TO_CHAR(date, 'YYYY-MM') = $2
AND type = $3
AND amount BETWEEN $4 * 0.9 AND $4 * 1.1
AND profile_id = $5`,
*categoryID, month, txType, amount, pid).Scan(&count)
return count > 0, err
}