mirror of
https://github.com/escalante29/WealthySmart.git
synced 2026-05-19 09:28:47 +02:00
Add budget module: FastAPI backend + React frontend
Some checks failed
Deploy to VPS / deploy (push) Failing after 7s
Some checks failed
Deploy to VPS / deploy (push) Failing after 7s
Backend: FastAPI + PostgreSQL with models for accounts, transactions, and categories. Auto-categorization from merchant patterns, token auth, CRUD endpoints, and seed data for 16 categories and 4 bank accounts. Frontend: Login, Dashboard (account balances + recent charges), Transactions (full CRUD table with search/filter), Cash & Transfers view. Dark theme with emerald/cyan accents, responsive layout. Infrastructure: Updated docker-compose for backend + db services, nginx proxy config for API routing, deploy workflow with secrets. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
0
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/v1/__init__.py
Normal file
0
backend/app/api/v1/__init__.py
Normal file
0
backend/app/api/v1/endpoints/__init__.py
Normal file
0
backend/app/api/v1/endpoints/__init__.py
Normal file
51
backend/app/api/v1/endpoints/accounts.py
Normal file
51
backend/app/api/v1/endpoints/accounts.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.auth import get_current_user
|
||||
from app.db import get_session
|
||||
from app.models.models import Account, AccountCreate, AccountRead, AccountUpdate
|
||||
|
||||
router = APIRouter(prefix="/accounts", tags=["accounts"])
|
||||
|
||||
|
||||
@router.get("/", response_model=list[AccountRead])
|
||||
def list_accounts(
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
return session.exec(select(Account)).all()
|
||||
|
||||
|
||||
@router.post("/", response_model=AccountRead, status_code=201)
|
||||
def create_account(
|
||||
data: AccountCreate,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
account = Account.model_validate(data)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
@router.patch("/{account_id}", response_model=AccountRead)
|
||||
def update_account(
|
||||
account_id: int,
|
||||
data: AccountUpdate,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
account = session.get(Account, account_id)
|
||||
if not account:
|
||||
raise HTTPException(status_code=404, detail="Account not found")
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(account, key, value)
|
||||
account.updated_at = datetime.utcnow()
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return account
|
||||
22
backend/app/api/v1/endpoints/auth.py
Normal file
22
backend/app/api/v1/endpoints/auth.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from fastapi import Depends
|
||||
|
||||
from app.auth import create_access_token
|
||||
from app.config import settings
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
||||
if (
|
||||
form_data.username != settings.ADMIN_USERNAME
|
||||
or form_data.password != settings.ADMIN_PASSWORD
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid credentials",
|
||||
)
|
||||
token = create_access_token(form_data.username)
|
||||
return {"access_token": token, "token_type": "bearer"}
|
||||
61
backend/app/api/v1/endpoints/categories.py
Normal file
61
backend/app/api/v1/endpoints/categories.py
Normal file
@@ -0,0 +1,61 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.auth import get_current_user
|
||||
from app.db import get_session
|
||||
from app.models.models import Category, CategoryCreate, CategoryRead, CategoryUpdate
|
||||
|
||||
router = APIRouter(prefix="/categories", tags=["categories"])
|
||||
|
||||
|
||||
@router.get("/", response_model=list[CategoryRead])
|
||||
def list_categories(
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
return session.exec(select(Category)).all()
|
||||
|
||||
|
||||
@router.post("/", response_model=CategoryRead, status_code=201)
|
||||
def create_category(
|
||||
data: CategoryCreate,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
category = Category.model_validate(data)
|
||||
session.add(category)
|
||||
session.commit()
|
||||
session.refresh(category)
|
||||
return category
|
||||
|
||||
|
||||
@router.patch("/{category_id}", response_model=CategoryRead)
|
||||
def update_category(
|
||||
category_id: int,
|
||||
data: CategoryUpdate,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
category = session.get(Category, category_id)
|
||||
if not category:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(category, key, value)
|
||||
session.add(category)
|
||||
session.commit()
|
||||
session.refresh(category)
|
||||
return category
|
||||
|
||||
|
||||
@router.delete("/{category_id}", status_code=204)
|
||||
def delete_category(
|
||||
category_id: int,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
category = session.get(Category, category_id)
|
||||
if not category:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
session.delete(category)
|
||||
session.commit()
|
||||
111
backend/app/api/v1/endpoints/transactions.py
Normal file
111
backend/app/api/v1/endpoints/transactions.py
Normal file
@@ -0,0 +1,111 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlmodel import Session, col, select
|
||||
|
||||
from app.auth import get_current_user
|
||||
from app.db import get_session
|
||||
from app.models.models import (
|
||||
Category,
|
||||
Transaction,
|
||||
TransactionCreate,
|
||||
TransactionRead,
|
||||
TransactionSource,
|
||||
TransactionUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/transactions", tags=["transactions"])
|
||||
|
||||
|
||||
def auto_categorize(merchant: str, session: Session) -> Optional[int]:
|
||||
categories = session.exec(select(Category)).all()
|
||||
merchant_lower = merchant.lower()
|
||||
for cat in categories:
|
||||
if cat.auto_match_patterns:
|
||||
patterns = [p.strip().lower() for p in cat.auto_match_patterns.split(",")]
|
||||
if any(p in merchant_lower for p in patterns if p):
|
||||
return cat.id
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/", response_model=list[TransactionRead])
|
||||
def list_transactions(
|
||||
source: Optional[TransactionSource] = None,
|
||||
search: Optional[str] = None,
|
||||
category_id: Optional[int] = None,
|
||||
limit: int = Query(default=50, le=500),
|
||||
offset: int = 0,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
query = select(Transaction)
|
||||
if source:
|
||||
query = query.where(Transaction.source == source)
|
||||
if category_id:
|
||||
query = query.where(Transaction.category_id == category_id)
|
||||
if search:
|
||||
query = query.where(col(Transaction.merchant).ilike(f"%{search}%"))
|
||||
query = query.order_by(col(Transaction.date).desc()).offset(offset).limit(limit)
|
||||
return session.exec(query).all()
|
||||
|
||||
|
||||
@router.get("/recent", response_model=list[TransactionRead])
|
||||
def recent_transactions(
|
||||
limit: int = Query(default=5, le=20),
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
query = (
|
||||
select(Transaction)
|
||||
.where(Transaction.source == TransactionSource.CREDIT_CARD)
|
||||
.order_by(col(Transaction.date).desc())
|
||||
.limit(limit)
|
||||
)
|
||||
return session.exec(query).all()
|
||||
|
||||
|
||||
@router.post("/", response_model=TransactionRead, status_code=201)
|
||||
def create_transaction(
|
||||
data: TransactionCreate,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
tx = Transaction.model_validate(data)
|
||||
if tx.category_id is None:
|
||||
tx.category_id = auto_categorize(tx.merchant, session)
|
||||
session.add(tx)
|
||||
session.commit()
|
||||
session.refresh(tx)
|
||||
return tx
|
||||
|
||||
|
||||
@router.patch("/{transaction_id}", response_model=TransactionRead)
|
||||
def update_transaction(
|
||||
transaction_id: int,
|
||||
data: TransactionUpdate,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
tx = session.get(Transaction, transaction_id)
|
||||
if not tx:
|
||||
raise HTTPException(status_code=404, detail="Transaction not found")
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(tx, key, value)
|
||||
session.add(tx)
|
||||
session.commit()
|
||||
session.refresh(tx)
|
||||
return tx
|
||||
|
||||
|
||||
@router.delete("/{transaction_id}", status_code=204)
|
||||
def delete_transaction(
|
||||
transaction_id: int,
|
||||
session: Session = Depends(get_session),
|
||||
_user: str = Depends(get_current_user),
|
||||
):
|
||||
tx = session.get(Transaction, transaction_id)
|
||||
if not tx:
|
||||
raise HTTPException(status_code=404, detail="Transaction not found")
|
||||
session.delete(tx)
|
||||
session.commit()
|
||||
9
backend/app/api/v1/router.py
Normal file
9
backend/app/api/v1/router.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1.endpoints import accounts, auth, categories, transactions
|
||||
|
||||
api_router = APIRouter(prefix="/api/v1")
|
||||
api_router.include_router(auth.router)
|
||||
api_router.include_router(accounts.router)
|
||||
api_router.include_router(categories.router)
|
||||
api_router.include_router(transactions.router)
|
||||
27
backend/app/auth.py
Normal file
27
backend/app/auth.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from app.config import settings
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def create_access_token(subject: str) -> str:
|
||||
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
return jwt.encode({"sub": subject, "exp": expire}, settings.SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[ALGORITHM])
|
||||
username: str = payload.get("sub")
|
||||
if username is None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
|
||||
return username
|
||||
except JWTError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
|
||||
15
backend/app/config.py
Normal file
15
backend/app/config.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
DATABASE_URL: str = "postgresql://wealthy_user:wealthy_pass@db:5432/wealthysmart"
|
||||
SECRET_KEY: str = "change-me-in-production"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 30 # 30 days
|
||||
ADMIN_USERNAME: str = "admin"
|
||||
ADMIN_PASSWORD: str = "admin"
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
14
backend/app/db.py
Normal file
14
backend/app/db.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from sqlmodel import SQLModel, Session, create_engine
|
||||
|
||||
from app.config import settings
|
||||
|
||||
engine = create_engine(settings.DATABASE_URL)
|
||||
|
||||
|
||||
def init_db():
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
def get_session():
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
34
backend/app/main.py
Normal file
34
backend/app/main.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.v1.router import api_router
|
||||
from app.config import settings
|
||||
from app.db import init_db
|
||||
from app.seed import seed_db
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_db()
|
||||
seed_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="WealthySmart API", version="0.1.0", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(api_router)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def root():
|
||||
return {"app": "WealthySmart", "version": "0.1.0"}
|
||||
0
backend/app/models/__init__.py
Normal file
0
backend/app/models/__init__.py
Normal file
135
backend/app/models/models.py
Normal file
135
backend/app/models/models.py
Normal file
@@ -0,0 +1,135 @@
|
||||
import enum
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlmodel import Field, Relationship, SQLModel
|
||||
|
||||
|
||||
class TransactionType(str, enum.Enum):
|
||||
COMPRA = "COMPRA"
|
||||
DEVOLUCION = "DEVOLUCION"
|
||||
|
||||
|
||||
class TransactionSource(str, enum.Enum):
|
||||
CREDIT_CARD = "CREDIT_CARD"
|
||||
CASH = "CASH"
|
||||
TRANSFER = "TRANSFER"
|
||||
|
||||
|
||||
class Currency(str, enum.Enum):
|
||||
CRC = "CRC"
|
||||
USD = "USD"
|
||||
|
||||
|
||||
class Bank(str, enum.Enum):
|
||||
BAC = "BAC"
|
||||
BCR = "BCR"
|
||||
DAVIVIENDA = "DAVIVIENDA"
|
||||
|
||||
|
||||
# --- Category ---
|
||||
|
||||
|
||||
class CategoryBase(SQLModel):
|
||||
name: str = Field(index=True, unique=True)
|
||||
icon: str = "tag"
|
||||
auto_match_patterns: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Comma-separated merchant substrings for auto-matching",
|
||||
)
|
||||
|
||||
|
||||
class Category(CategoryBase, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
transactions: list["Transaction"] = Relationship(back_populates="category")
|
||||
|
||||
|
||||
class CategoryCreate(CategoryBase):
|
||||
pass
|
||||
|
||||
|
||||
class CategoryRead(CategoryBase):
|
||||
id: int
|
||||
|
||||
|
||||
class CategoryUpdate(SQLModel):
|
||||
name: Optional[str] = None
|
||||
icon: Optional[str] = None
|
||||
auto_match_patterns: Optional[str] = None
|
||||
|
||||
|
||||
# --- Account ---
|
||||
|
||||
|
||||
class AccountBase(SQLModel):
|
||||
bank: Bank
|
||||
currency: Currency
|
||||
label: str = Field(description="e.g. 'BAC Colones', 'BAC Dólares'")
|
||||
balance: float = 0.0
|
||||
|
||||
|
||||
class Account(AccountBase, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
class AccountCreate(AccountBase):
|
||||
pass
|
||||
|
||||
|
||||
class AccountRead(AccountBase):
|
||||
id: int
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class AccountUpdate(SQLModel):
|
||||
balance: Optional[float] = None
|
||||
label: Optional[str] = None
|
||||
|
||||
|
||||
# --- Transaction ---
|
||||
|
||||
|
||||
class TransactionBase(SQLModel):
|
||||
amount: float
|
||||
currency: Currency = Currency.CRC
|
||||
merchant: str
|
||||
city: Optional[str] = None
|
||||
date: datetime
|
||||
card_type: Optional[str] = None
|
||||
card_last4: Optional[str] = None
|
||||
authorization_code: Optional[str] = None
|
||||
reference: Optional[str] = None
|
||||
transaction_type: TransactionType = TransactionType.COMPRA
|
||||
source: TransactionSource = TransactionSource.CREDIT_CARD
|
||||
bank: Bank = Bank.BAC
|
||||
notes: Optional[str] = None
|
||||
category_id: Optional[int] = Field(default=None, foreign_key="category.id")
|
||||
|
||||
|
||||
class Transaction(TransactionBase, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
category: Optional[Category] = Relationship(back_populates="transactions")
|
||||
|
||||
|
||||
class TransactionCreate(TransactionBase):
|
||||
pass
|
||||
|
||||
|
||||
class TransactionRead(TransactionBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
category: Optional[CategoryRead] = None
|
||||
|
||||
|
||||
class TransactionUpdate(SQLModel):
|
||||
amount: Optional[float] = None
|
||||
currency: Optional[Currency] = None
|
||||
merchant: Optional[str] = None
|
||||
city: Optional[str] = None
|
||||
date: Optional[datetime] = None
|
||||
transaction_type: Optional[TransactionType] = None
|
||||
source: Optional[TransactionSource] = None
|
||||
notes: Optional[str] = None
|
||||
category_id: Optional[int] = None
|
||||
45
backend/app/seed.py
Normal file
45
backend/app/seed.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.db import engine
|
||||
from app.models.models import Account, Bank, Category, Currency
|
||||
|
||||
DEFAULT_CATEGORIES = [
|
||||
("Groceries", "shopping-cart", "automercado,auto mercado,fresh market,macrobiotica,pricesmart,price smart,grassfedcr,pequeno mundo"),
|
||||
("Food & Delivery", "utensils", "uber eats,rappi,mcdonalds,subway,pizza,restaurant,soda,cafe,coyote ugly,el rodeo,steak house"),
|
||||
("Utilities", "zap", "c.n.f.l,cnfl,ice,aya,claro cr telecomunicaciones"),
|
||||
("Transportation", "car", "gasolina,gasolinera,uber rides,didi,parqueo,parking,peaje,estacion de servicio,estac.de serv"),
|
||||
("Shopping", "shopping-bag", "amazon,ebay,ticotek,construplaza,epa,novex,novedades chayfer,total imports,tiendalaliga,gnc live well"),
|
||||
("Entertainment", "film", "netflix,disney,cine,steam,playstation,blizzard,diablo"),
|
||||
("Health", "heart-pulse", "farmacia,hospital,clinica,laboratorio,optica,medicina regenerativa,neumi,doer fitness,kettlebell,lacrosse"),
|
||||
("Education", "graduation-cap", "universidad,udemy,coursera,libro"),
|
||||
("Housing", "home", "hipoteca,alquiler,municipalidad,condominio,bac san jose pensiones"),
|
||||
("Insurance", "shield", "seguro,ins"),
|
||||
("Subscriptions", "repeat", "cloudflare,github,google one,apple,icloud,spotify,openai,claude.ai,cursor,netcup"),
|
||||
("Telecom", "phone", "liberty,tigo,kolbi"),
|
||||
("Parking & Fees", "circle-parking", "centro comercial curridabat,debito compass,cobro administr,compass"),
|
||||
("Auto", "car-front", "auto lavado,lavado"),
|
||||
("Lab & Medical", "microscope", "laboratorio echandi"),
|
||||
("Other", "tag", ""),
|
||||
]
|
||||
|
||||
DEFAULT_ACCOUNTS = [
|
||||
(Bank.BAC, Currency.CRC, "BAC Colones", 0.0),
|
||||
(Bank.BAC, Currency.USD, "BAC Dólares", 0.0),
|
||||
(Bank.BCR, Currency.CRC, "BCR Colones", 0.0),
|
||||
(Bank.DAVIVIENDA, Currency.CRC, "Davivienda Colones", 0.0),
|
||||
]
|
||||
|
||||
|
||||
def seed_db():
|
||||
with Session(engine) as session:
|
||||
existing = session.exec(select(Category)).first()
|
||||
if not existing:
|
||||
for name, icon, patterns in DEFAULT_CATEGORIES:
|
||||
session.add(Category(name=name, icon=icon, auto_match_patterns=patterns))
|
||||
session.commit()
|
||||
|
||||
existing_acc = session.exec(select(Account)).first()
|
||||
if not existing_acc:
|
||||
for bank, currency, label, balance in DEFAULT_ACCOUNTS:
|
||||
session.add(Account(bank=bank, currency=currency, label=label, balance=balance))
|
||||
session.commit()
|
||||
Reference in New Issue
Block a user