Spaces:
Sleeping
Sleeping
Download main.py from EliramShemesh/Spender: direct link, hf CLI and curl.
- Browser
- Download file 49.3 kB
-
https://huggingface.co/spaces/EliramShemesh/Spender/resolve/main/main.py
- Command line
-
hf download hf://spaces/EliramShemesh/Spender/main.py
-
curl -L -o main.py https://huggingface.co/spaces/EliramShemesh/Spender/resolve/main/main.py
49.3 kB
import logging
import os
import calendar
import unicodedata
import re
import bcrypt
import json
from typing import List, Optional
from datetime import datetime, timedelta
from fastapi import FastAPI, Depends, HTTPException, Query, Request, status, Body
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy import and_
from sqlmodel import Session, select, func, SQLModel
from jose import JWTError, jwt
from pywebpush import webpush, WebPushException
from database import create_db_and_tables, get_password_hash, get_session
from models import User, Category, SubCategory, Transaction, TransactionType, PaymentMethod, BudgetHistory, InstallmentPlan, PushSubscription
# Auth Configuration
SECRET_KEY = os.getenv("JWT_SECRET", "this-is-a-very-secret-key-for-development")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 30 # 30 days
# VAPID Keys for Web Push notifications
VAPID_PUBLIC_KEY = os.getenv("VAPID_PUBLIC_KEY", "")
VAPID_PRIVATE_KEY = os.getenv("VAPID_PRIVATE_KEY", "")
VAPID_CLAIMS = {
"sub": f"mailto:{os.getenv('VAPID_EMAIL', 'admin@example.com')}"
}
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Setup logging
class ColoredFormatter(logging.Formatter):
"""Custom logging formatter to add colors and timestamps."""
grey = "\x1b[38;20m"
blue = "\x1b[34;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
green = "\x1b[32;20m"
reset = "\x1b[0m"
format_str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
def __init__(self):
super().__init__(datefmt="%Y-%m-%d %H:%M:%S")
self.FORMATTERS = {
logging.DEBUG: logging.Formatter(self.grey + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.INFO: logging.Formatter(self.green + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.WARNING: logging.Formatter(self.yellow + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.ERROR: logging.Formatter(self.red + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.CRITICAL: logging.Formatter(self.bold_red + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S")
}
def format(self, record):
formatter = self.FORMATTERS.get(record.levelno, self.FORMATTERS[logging.INFO])
return formatter.format(record)
# Configure the root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# Clear existing handlers
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
# Create console handler with colored formatter
ch = logging.StreamHandler()
ch.setFormatter(ColoredFormatter())
root_logger.addHandler(ch)
# Also explicitly configure uvicorn loggers to ensure they use our handlers
for logger_name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
l = logging.getLogger(logger_name)
l.handlers = [ch]
l.propagate = False
logger = logging.getLogger("spender")
app = FastAPI(title="Spender API")
# Track initial client requests to log "Server is ready" at the correct time
initial_endpoints_hit = set()
required_initial_endpoints = {
"/users",
"/transactions",
"/categories",
"/payment-methods",
"/insights/budget_history",
"/subcategories"
}
ready_logged = False
# iOS / RTL keyboards and password managers sometimes inject zero-width or bidi chars.
_ZW_AND_BIDI = frozenset(
"\u200b\u200c\u200d\ufeff\u200e\u200f\u202a\u202b\u202c\u202d\u202e"
)
def sanitize_login_password(plain: str) -> str:
if not plain:
return ""
s = unicodedata.normalize("NFC", plain)
s = "".join(c for c in s if c not in _ZW_AND_BIDI)
return s.strip()
def sanitize_login_username(name: str) -> str:
if not name:
return ""
s = unicodedata.normalize("NFC", str(name))
s = "".join(c for c in s if c not in _ZW_AND_BIDI)
return s.strip().lower()
def verify_password(plain_password: str, hashed_password: str):
try:
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
except Exception:
return False
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def get_current_user(token: str = Depends(oauth2_scheme), session: Session = Depends(get_session)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = session.exec(select(User).where(User.username == username)).first()
if user is None:
raise credentials_exception
return user
# Ultra-permissive CORS for debugging
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
@app.middleware("http")
async def log_requests(request: Request, call_next):
global ready_logged
logger.info(f"INCOMING: {request.method} {request.url.path}")
response = await call_next(request)
logger.info(f"OUTGOING: {request.method} {request.url.path} - Status: {response.status_code}")
# Track completion of initial data load
if not ready_logged and response.status_code == 200:
path = request.url.path
if path in required_initial_endpoints:
if path not in initial_endpoints_hit:
initial_endpoints_hit.add(path)
remaining = required_initial_endpoints - initial_endpoints_hit
if not remaining:
print("\n\033[32m" + "✅ Server is ready! Client has successfully loaded all initial data." + "\033[0m\n")
ready_logged = True
else:
print(f"\033[33m⏳ Waiting for initial data load... ({len(initial_endpoints_hit)}/{len(required_initial_endpoints)}): {path} loaded.\033[0m")
return response
@app.on_event("startup")
def on_startup():
try:
create_db_and_tables()
print("\n\033[32m✅ Database initialized successfully\033[0m")
except Exception as e:
print(f"\n\033[33m⚠️ DB init warning: {e}\033[0m")
raise
print("\n\033[34m📡 Spender API started. Waiting for client to load initial data...\033[0m")
@app.get("/")
def root():
return {
"message": "Spender API is running!",
"docs": "/docs",
"health": "/health"
}
@app.get("/health")
def health_check():
return {"ok": True}
# Login
@app.post("/token")
def login_for_access_token(
request: Request,
form_data: OAuth2PasswordRequestForm = Depends(),
session: Session = Depends(get_session),
):
raw_username = form_data.username or ""
raw_password = form_data.password or ""
username = sanitize_login_username(raw_username)
password = sanitize_login_password(raw_password)
client_host = request.client.host if request.client else "unknown"
user_agent = request.headers.get("user-agent", "")[:200]
if raw_password != password or raw_username != username:
logger.info(
"Login: normalized credentials (zero-width/bidi/NFC/trim/case); "
"password_altered=%s username_altered=%s ua=%r ip=%s",
raw_password != password,
raw_username != username,
user_agent,
client_host,
)
user = session.exec(select(User).where(User.username == username)).first()
if not user:
logger.warning(
"Login failed: user not found; username=%r len=%s ua=%r ip=%s",
username,
len(username),
user_agent,
client_host,
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
if not verify_password(password, user.hashed_password):
logger.warning(
"Login failed: bad password for user=%r pwd_len=%s ua=%r ip=%s",
username,
len(password),
user_agent,
client_host,
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
logger.info("Login success: user=%r ip=%s", username, client_host)
access_token = create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer", "user_id": user.id, "name": user.name}
# Me
@app.get("/me")
def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
@app.post("/change-password")
def change_password(
old_password: str = Query(...),
new_password: str = Query(...),
current_user: User = Depends(get_current_user),
session: Session = Depends(get_session)
):
old_password = sanitize_login_password(old_password)
new_password = sanitize_login_password(new_password)
if not verify_password(old_password, current_user.hashed_password):
raise HTTPException(status_code=400, detail="Incorrect old password")
current_user.hashed_password = get_password_hash(new_password)
session.add(current_user)
session.commit()
return {"ok": True}
# Users (Protected)
@app.get("/users", response_model=List[User])
def get_users(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
return session.exec(select(User)).all()
# Categories (Protected)
@app.get("/categories", response_model=List[Category])
def get_categories(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
return session.exec(select(Category)).all()
@app.post("/categories", response_model=Category)
def create_category(category: Category, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
# Normalize type to uppercase for PostgreSQL enum
if isinstance(category.type, str):
category.type = category.type.upper() # type: ignore
session.add(category)
session.commit()
session.refresh(category)
# Log initial budget if it exists
if category.budget is not None:
history = BudgetHistory(
category_id=category.id,
budget=category.budget,
updated_at=datetime.utcnow()
)
session.add(history)
session.commit()
return category
@app.patch("/categories/{category_id}", response_model=Category)
def update_category(category_id: int, category: Category, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
db_category = session.get(Category, category_id)
if not db_category:
raise HTTPException(status_code=404, detail="Category not found")
category_data = category.dict(exclude_unset=True)
# Normalize type to uppercase for PostgreSQL enum
if "type" in category_data and isinstance(category_data["type"], str):
category_data["type"] = category_data["type"].upper()
# Check if budget is being updated
if "budget" in category_data and category_data["budget"] != db_category.budget:
history = BudgetHistory(
category_id=category_id,
budget=category_data["budget"] if category_data["budget"] is not None else 0,
updated_at=datetime.utcnow()
)
session.add(history)
for key, value in category_data.items():
setattr(db_category, key, value)
session.add(db_category)
session.commit()
session.refresh(db_category)
return db_category
@app.delete("/categories/{category_id}")
def delete_category(category_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
category = session.get(Category, category_id)
if not category:
raise HTTPException(status_code=404, detail="Category not found")
# Manually handle cascade if DB doesn't have it set up
# 1. Delete transactions for this category
transactions = session.exec(select(Transaction).where(Transaction.category_id == category_id)).all()
for tx in transactions:
session.delete(tx)
# 2. Delete budget history for this category
history = session.exec(select(BudgetHistory).where(BudgetHistory.category_id == category_id)).all()
for h in history:
session.delete(h)
# 3. Delete subcategories for this category
subcategories = session.exec(select(SubCategory).where(SubCategory.category_id == category_id)).all()
for sub in subcategories:
# Delete transactions for this subcategory first
sub_txs = session.exec(select(Transaction).where(Transaction.sub_category_id == sub.id)).all()
for tx in sub_txs:
session.delete(tx)
# Delete budget history for this subcategory
sub_history = session.exec(select(BudgetHistory).where(BudgetHistory.sub_category_id == sub.id)).all()
for h in sub_history:
session.delete(h)
session.delete(sub)
session.delete(category)
session.commit()
return {"ok": True}
# SubCategories (Protected)
@app.get("/subcategories", response_model=List[SubCategory])
def get_subcategories(category_id: Optional[int] = None, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
statement = select(SubCategory)
if category_id:
statement = statement.where(SubCategory.category_id == category_id)
return session.exec(statement).all()
@app.post("/subcategories", response_model=SubCategory)
def create_subcategory(subcategory: SubCategory, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
session.add(subcategory)
session.commit()
session.refresh(subcategory)
# Log initial budget if it exists
if subcategory.budget is not None:
history = BudgetHistory(
sub_category_id=subcategory.id,
budget=subcategory.budget,
updated_at=datetime.utcnow()
)
session.add(history)
session.commit()
return subcategory
@app.patch("/subcategories/{subcategory_id}", response_model=SubCategory)
def update_subcategory(subcategory_id: int, subcategory: SubCategory, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
db_subcategory = session.get(SubCategory, subcategory_id)
if not db_subcategory:
raise HTTPException(status_code=404, detail="SubCategory not found")
data = subcategory.dict(exclude_unset=True)
# Check if budget is being updated
if "budget" in data and data["budget"] != db_subcategory.budget:
history = BudgetHistory(
sub_category_id=subcategory_id,
budget=data["budget"] if data["budget"] is not None else 0,
updated_at=datetime.utcnow()
)
session.add(history)
for key, value in data.items():
setattr(db_subcategory, key, value)
session.add(db_subcategory)
session.commit()
session.refresh(db_subcategory)
return db_subcategory
@app.delete("/subcategories/{subcategory_id}")
def delete_subcategory(subcategory_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
subcategory = session.get(SubCategory, subcategory_id)
if not subcategory:
raise HTTPException(status_code=404, detail="SubCategory not found")
# 1. Delete transactions for this subcategory
transactions = session.exec(select(Transaction).where(Transaction.sub_category_id == subcategory_id)).all()
for tx in transactions:
session.delete(tx)
# 2. Delete budget history for this subcategory
history = session.exec(select(BudgetHistory).where(BudgetHistory.sub_category_id == subcategory_id)).all()
for h in history:
session.delete(h)
session.delete(subcategory)
session.commit()
return {"ok": True}
# Payment Methods (Protected)
@app.get("/payment-methods", response_model=List[PaymentMethod])
def get_payment_methods(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
return session.exec(select(PaymentMethod)).all()
@app.post("/payment-methods", response_model=PaymentMethod)
def create_payment_method(payment_method: PaymentMethod, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
session.add(payment_method)
session.commit()
session.refresh(payment_method)
return payment_method
@app.patch("/payment-methods/{pm_id}", response_model=PaymentMethod)
def update_payment_method(pm_id: int, payment_method: PaymentMethod, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
db_pm = session.get(PaymentMethod, pm_id)
if not db_pm:
raise HTTPException(status_code=404, detail="Payment Method not found")
pm_data = payment_method.dict(exclude_unset=True)
for key, value in pm_data.items():
setattr(db_pm, key, value)
session.add(db_pm)
session.commit()
session.refresh(db_pm)
return db_pm
@app.delete("/payment-methods/{pm_id}")
def delete_payment_method(pm_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
pm = session.get(PaymentMethod, pm_id)
if not pm:
raise HTTPException(status_code=404, detail="Payment Method not found")
# Manually handle transactions for this payment method
transactions = session.exec(select(Transaction).where(Transaction.payment_method_id == pm_id)).all()
for tx in transactions:
tx.payment_method_id = None
session.add(tx)
session.delete(pm)
session.commit()
return {"ok": True}
# Transactions (Protected - SHARED ACCESS)
# Helper to add months
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month // 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year, month)[1])
return datetime(year, month, day, sourcedate.hour, sourcedate.minute, sourcedate.second)
def month_start(value: datetime) -> datetime:
return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
def strip_installment_suffix(notes: Optional[str]) -> str:
return re.sub(r"\s*\(\d+/\d+\)\s*$", "", notes or "")
def is_standing_order_payment(session: Session, payment_method_id: Optional[int]) -> bool:
if not payment_method_id:
return False
payment_method = session.get(PaymentMethod, payment_method_id)
return bool(payment_method and payment_method.name in ("הוראת קבע", "הו״ק באשראי", "הו\"ק באשראי"))
@app.post("/transactions", response_model=List[Transaction])
def create_transaction(transaction: Transaction, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
try:
logger.info(f"[Transaction] Creating new transaction: amount={transaction.amount}, payee={transaction.payee}, user={current_user.id}")
if transaction.amount <= 0:
raise HTTPException(status_code=400, detail="Amount must be positive")
if not transaction.sub_category_id:
raise HTTPException(status_code=400, detail="Sub-category is required")
# Normalize type to uppercase for PostgreSQL enum
txn_type = TransactionType(transaction.type.upper() if isinstance(transaction.type, str) else transaction.type)
user_id = transaction.user_id or current_user.id
if isinstance(transaction.date, str):
date_str = transaction.date.replace('Z', '+00:00')
parsed_date = datetime.fromisoformat(date_str)
else:
parsed_date = transaction.date or datetime.utcnow()
# Simple duplicate check: same amount, payee, and roughly same time (within 5 mins) for same user
time_window = timedelta(minutes=5)
duplicate = session.exec(
select(Transaction).where(
Transaction.amount == transaction.amount,
Transaction.payee == transaction.payee,
Transaction.user_id == user_id,
Transaction.date >= parsed_date - time_window,
Transaction.date <= parsed_date + time_window
)
).first()
if duplicate:
logger.warning(f"[Transaction] Duplicate detected! Returning existing transaction id={duplicate.id}")
return [duplicate]
plan_id = None
is_standing_order = is_standing_order_payment(session, transaction.payment_method_id)
should_create_plan = is_standing_order or (
transaction.is_installment and transaction.total_installments and transaction.total_installments > 1
)
if should_create_plan:
plan = InstallmentPlan(
amount=transaction.amount,
notes=transaction.notes,
payee=transaction.payee,
start_date=parsed_date,
type=txn_type,
total_installments=None if is_standing_order else transaction.total_installments,
posted_installments=1,
recurring_forever=is_standing_order,
user_id=user_id,
category_id=transaction.category_id,
sub_category_id=transaction.sub_category_id if transaction.sub_category_id != 0 else None,
payment_method_id=transaction.payment_method_id if transaction.payment_method_id != 0 else None,
)
session.add(plan)
session.flush()
plan_id = plan.id
new_t = Transaction(
amount=transaction.amount,
notes=transaction.notes,
payee=transaction.payee,
date=parsed_date,
type=txn_type,
is_installment=bool(plan_id),
installment_number=1 if plan_id else None,
total_installments=None if is_standing_order else (transaction.total_installments if plan_id else None),
installment_plan_id=plan_id,
user_id=user_id,
category_id=transaction.category_id,
sub_category_id=transaction.sub_category_id if transaction.sub_category_id != 0 else None,
payment_method_id=transaction.payment_method_id if transaction.payment_method_id != 0 else None
)
session.add(new_t)
session.commit()
session.refresh(new_t)
# Get subcategory name for push notification
sub_category = session.get(SubCategory, transaction.sub_category_id) if transaction.sub_category_id else None
sub_category_name = sub_category.name if sub_category else 'ללא תת קטגוריה'
# Format amounts without sign (just the number)
amount_formatted = f"₪{transaction.amount:,.0f}"
# Check if this is a standing order
is_standing_order = is_standing_order_payment(session, transaction.payment_method_id)
# Check if this is an installment transaction
is_installment = transaction.total_installments and transaction.total_installments > 1
# Calculate total amount for installments
if is_installment:
total_amount = transaction.amount * transaction.total_installments
total_amount_formatted = f"₪{total_amount:,.0f}"
installments_count = transaction.total_installments
# Send push notification to all subscribed devices
# Use TransactionType enum values (EXPENSE/INCOME) not lowercase
is_expense = transaction.type == TransactionType.EXPENSE
if is_standing_order:
title = "הוראת קבע חדשה"
body = f"הוראת קבע חדשה בגובה {amount_formatted} נוספה בהצלחה תחת {sub_category_name}"
elif is_expense:
title = "הוצאה חדשה"
if is_installment:
body = f"הוצאה חדשה בגובה {total_amount_formatted} מחולקת ל-{installments_count} תשלומים נוספה בהצלחה תחת {sub_category_name}"
else:
body = f"הוצאה חדשה בגובה {amount_formatted} נוספה בהצלחה תחת {sub_category_name}"
else:
title = "הכנסה חדשה"
body = f"הכנסה חדשה בגובה {amount_formatted} נוספה בהצלחה תחת {sub_category_name}"
send_push_notification_to_all(
session,
title=title,
body=body,
data={"transaction_id": new_t.id, "type": transaction.type}
)
return [new_t]
except Exception as e:
logger.error(f"Error creating transaction: {str(e)}", exc_info=True)
if isinstance(e, HTTPException):
raise e
raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
# Import transactions from bank data
@app.post("/transactions/import")
def import_transactions(
data: dict,
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
"""Import multiple transactions from bank export data."""
transactions = data.get("transactions", [])
imported = 0
skipped = 0
errors = []
# Category mapping from bank to app
category_map = {
'דלק, חשמל וגז': 'בית',
'שונות': 'שונות',
'שירותי תקשורת': 'תקשורת',
'מזון וצריכה': 'מזון',
'רפואה ובתי מרקחת': 'בריאות',
'פנאי, בידור וספורט': 'פנאי ובידור',
'תחבורה ורכבים': 'תחבורה',
'': 'שונות',
}
for tx_data in transactions:
try:
# Map category
bank_cat = tx_data.get("category", "")
app_category = category_map.get(bank_cat, bank_cat)
# Find or create category
category = session.exec(
select(Category).where(Category.name == app_category)
).first()
if not category:
# Create new category
is_expense = tx_data.get("direction") == "debit"
category = Category(
name=app_category,
type="EXPENSE" if is_expense else "INCOME",
icon="📦",
color="#666666"
)
session.add(category)
session.commit()
session.refresh(category)
# Map payment method
pm_name = "כרטיס אשראי" if "Credit Card" in tx_data.get("source", "") else "העברה בנקאית"
pm = session.exec(select(PaymentMethod).where(PaymentMethod.name == pm_name)).first()
pm_id = pm.id if pm else 1
# Build notes
notes_parts = []
if tx_data.get("notes"):
notes_parts.append(tx_data["notes"])
if tx_data.get("transaction_type") and tx_data["transaction_type"] != "רגילה":
notes_parts.append(f"סוג: {tx_data['transaction_type']}")
if tx_data.get("card_last4"):
notes_parts.append(f"כרטיס: ****{tx_data['card_last4']}")
if tx_data.get("reference"):
notes_parts.append(f"אסמכתא: {tx_data['reference']}")
notes = " | ".join(notes_parts) if notes_parts else None
# Check for duplicate
existing = session.exec(
select(Transaction).where(
Transaction.amount == tx_data["amount"],
Transaction.date == tx_data["transaction_date"],
Transaction.user_id == current_user.id
)
).first()
if existing:
skipped += 1
continue
# Create transaction
is_expense = tx_data.get("direction") == "debit"
tx = Transaction(
amount=tx_data["amount"],
type=TransactionType.EXPENSE if is_expense else TransactionType.INCOME,
category_id=category.id,
payment_method_id=pm_id,
user_id=current_user.id,
date=tx_data["transaction_date"],
notes=notes,
payee=tx_data.get("merchant", "")[:100],
is_installment="תשלומים" in tx_data.get("transaction_type", ""),
installment_number=None,
total_installments=None
)
session.add(tx)
imported += 1
except Exception as e:
errors.append(f"Error importing {tx_data.get('merchant', 'unknown')}: {str(e)}")
session.commit()
return {
"imported": imported,
"skipped": skipped,
"errors": errors,
"total": len(transactions)
}
@app.get("/transactions/installments", response_model=List[InstallmentPlan])
def get_installment_plans(user_id: Optional[int] = None, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
statement = select(InstallmentPlan)
if user_id is not None:
statement = statement.where(InstallmentPlan.user_id == user_id)
statement = statement.order_by(InstallmentPlan.start_date)
return session.exec(statement).all()
@app.patch("/transactions/installments/{plan_id}", response_model=InstallmentPlan)
def update_installment_plan(
plan_id: int,
plan_update: dict = Body(...),
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
db_plan = session.get(InstallmentPlan, plan_id)
if not db_plan:
raise HTTPException(status_code=404, detail="Installment plan not found")
# Parse date strings to datetime if needed
for date_field in ["start_date", "end_date"]:
if date_field in plan_update and isinstance(plan_update[date_field], str):
try:
date_str = plan_update[date_field].replace('Z', '+00:00')
plan_update[date_field] = datetime.fromisoformat(date_str)
except ValueError:
pass
# Normalize type to enum
if "type" in plan_update and isinstance(plan_update["type"], str):
plan_update["type"] = TransactionType(plan_update["type"].upper())
for key, value in plan_update.items():
if hasattr(db_plan, key):
setattr(db_plan, key, value)
session.add(db_plan)
session.commit()
session.refresh(db_plan)
return db_plan
@app.post("/transactions/installments/{plan_id}/split")
def split_standing_order_plan(
plan_id: int,
plan_update: dict = Body(...),
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
db_plan = session.get(InstallmentPlan, plan_id)
if not db_plan:
raise HTTPException(status_code=404, detail="Installment plan not found")
if not db_plan.recurring_forever:
raise HTTPException(status_code=400, detail="Only standing order plans can be split")
effective_date = plan_update.get("start_date") or plan_update.get("date")
if isinstance(effective_date, str):
effective_date = datetime.fromisoformat(effective_date.replace("Z", "+00:00"))
elif not isinstance(effective_date, datetime):
effective_date = datetime.utcnow()
effective_month_start = month_start(effective_date).replace(tzinfo=None)
if effective_month_start <= month_start(db_plan.start_date):
raise HTTPException(status_code=400, detail="Split date must be after the original plan start month")
amount = plan_update.get("amount", db_plan.amount)
if amount <= 0:
raise HTTPException(status_code=400, detail="Amount must be positive")
sub_category_id = plan_update.get("sub_category_id", db_plan.sub_category_id)
if not sub_category_id:
raise HTTPException(status_code=400, detail="Sub-category is required")
payment_method_id = plan_update.get("payment_method_id", db_plan.payment_method_id)
if payment_method_id == 0:
payment_method_id = None
if not is_standing_order_payment(session, payment_method_id):
raise HTTPException(status_code=400, detail="Payment method must be a standing order")
txn_type = plan_update.get("type", db_plan.type)
if isinstance(txn_type, str):
txn_type = TransactionType(txn_type.upper())
db_plan.end_date = effective_month_start - timedelta(seconds=1)
session.add(db_plan)
new_plan = InstallmentPlan(
amount=amount,
notes=plan_update.get("notes", db_plan.notes),
payee=plan_update.get("payee", db_plan.payee),
start_date=effective_date.replace(tzinfo=None),
type=txn_type,
total_installments=None,
posted_installments=1,
recurring_forever=True,
user_id=plan_update.get("user_id", db_plan.user_id) or current_user.id,
category_id=plan_update.get("category_id", db_plan.category_id),
sub_category_id=sub_category_id,
payment_method_id=payment_method_id,
)
session.add(new_plan)
session.commit()
session.refresh(db_plan)
session.refresh(new_plan)
return {"previous_plan": db_plan, "new_plan": new_plan}
@app.get("/transactions", response_model=List[Transaction])
def get_transactions(
user_id: Optional[int] = None,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
limit: int = Query(default=100, le=5000),
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
statement = select(Transaction)
# Only filter by user_id if it's explicitly provided and valid (> 0)
if user_id is not None and user_id > 0:
statement = statement.where(Transaction.user_id == user_id)
if start_date is not None:
statement = statement.where(Transaction.date >= start_date)
if end_date is not None:
statement = statement.where(Transaction.date <= end_date)
statement = statement.order_by(Transaction.date.desc()).limit(limit)
return session.exec(statement).all()
@app.patch("/transactions/{transaction_id}", response_model=Transaction)
def update_transaction(transaction_id: int, transaction: Transaction, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
db_transaction = session.get(Transaction, transaction_id)
if not db_transaction:
raise HTTPException(status_code=404, detail="Transaction not found")
if month_start(db_transaction.date) < month_start(datetime.utcnow()):
raise HTTPException(status_code=403, detail="Past month transactions cannot be edited")
transaction_data = {
field_name: getattr(transaction, field_name)
for field_name in transaction.model_fields_set
}
if "amount" in transaction_data and transaction_data["amount"] <= 0:
raise HTTPException(status_code=400, detail="Amount must be positive")
# Validate sub_category_id is not being cleared
if "sub_category_id" in transaction_data and not transaction_data["sub_category_id"]:
raise HTTPException(status_code=400, detail="Sub-category is required")
# Handle 0 as None for optional foreign keys
if "payment_method_id" in transaction_data and transaction_data["payment_method_id"] == 0:
transaction_data["payment_method_id"] = None
# Parse date string to datetime if needed
if "date" in transaction_data and isinstance(transaction_data["date"], str):
date_str = transaction_data["date"].replace('Z', '+00:00')
transaction_data["date"] = datetime.fromisoformat(date_str)
# Normalize type to enum
if "type" in transaction_data and isinstance(transaction_data["type"], str):
transaction_data["type"] = TransactionType(transaction_data["type"].upper())
if db_transaction.installment_plan_id:
plan = session.get(InstallmentPlan, db_transaction.installment_plan_id)
if plan:
if "amount" in transaction_data:
plan.amount = transaction_data["amount"]
if "notes" in transaction_data:
plan.notes = transaction_data["notes"]
if "payee" in transaction_data:
plan.payee = transaction_data["payee"]
if "date" in transaction_data:
plan.start_date = transaction_data["date"]
if "type" in transaction_data:
plan.type = transaction_data["type"]
if "category_id" in transaction_data:
plan.category_id = transaction_data["category_id"]
if "sub_category_id" in transaction_data:
plan.sub_category_id = transaction_data["sub_category_id"]
if "payment_method_id" in transaction_data:
plan.payment_method_id = transaction_data["payment_method_id"]
if "total_installments" in transaction_data and transaction_data["total_installments"]:
plan.total_installments = transaction_data["total_installments"]
plan.recurring_forever = False
if "payment_method_id" in transaction_data:
plan.recurring_forever = is_standing_order_payment(session, transaction_data["payment_method_id"])
if plan.recurring_forever:
plan.total_installments = None
session.add(plan)
for key, value in transaction_data.items():
setattr(db_transaction, key, value)
session.add(db_transaction)
session.commit()
session.refresh(db_transaction)
return db_transaction
@app.delete("/transactions/{transaction_id}")
def delete_transaction(transaction_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
transaction = session.get(Transaction, transaction_id)
if not transaction:
raise HTTPException(status_code=404, detail="Transaction not found")
current_month_start = month_start(datetime.utcnow())
if transaction.installment_plan_id:
plan = session.get(InstallmentPlan, transaction.installment_plan_id)
if plan and month_start(transaction.date) < current_month_start:
transaction.installment_plan_id = None
session.add(transaction)
session.delete(plan)
session.commit()
return {"ok": True, "preserved_history": True}
if plan:
session.delete(plan)
# Legacy installment rows: preserve past months and delete only current/future siblings.
if transaction.is_installment and month_start(transaction.date) < current_month_start:
base_notes = strip_installment_suffix(transaction.notes)
candidate_transactions = session.exec(
select(Transaction).where(
Transaction.user_id == transaction.user_id,
Transaction.amount == transaction.amount,
Transaction.category_id == transaction.category_id,
Transaction.sub_category_id == transaction.sub_category_id,
Transaction.payment_method_id == transaction.payment_method_id,
Transaction.total_installments == transaction.total_installments,
Transaction.is_installment == True,
Transaction.date >= current_month_start,
)
).all()
for candidate in candidate_transactions:
if candidate.id == transaction.id:
continue
if strip_installment_suffix(candidate.notes) == base_notes:
session.delete(candidate)
transaction.is_installment = False
session.add(transaction)
session.commit()
return {"ok": True, "preserved_history": True}
session.delete(transaction)
session.commit()
return {"ok": True}
# Insights (Protected - SHARED DATA)
@app.get("/insights/category_summary")
def get_category_summary(
type: TransactionType = TransactionType.EXPENSE,
user_id: Optional[int] = None,
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
join_conditions = [Transaction.category_id == Category.id]
if user_id is not None:
join_conditions.append(Transaction.user_id == user_id)
join_condition = and_(*join_conditions)
results = session.exec(
select(
Category.id,
Category.name,
Category.icon,
Category.color,
Category.budget,
func.coalesce(func.sum(Transaction.amount), 0).label("spent"),
)
.select_from(Category)
.join(Transaction, join_condition, isouter=True)
.where(Category.type == type)
.group_by(Category.id)
.order_by(Category.name)
).all()
return [
{
"id": row[0],
"name": row[1],
"icon": row[2],
"color": row[3],
"budget": row[4],
"spent": row[5],
"remaining": (row[4] or 0) - row[5] if row[4] is not None else None,
}
for row in results
]
@app.get("/insights/total_summary")
def get_total_summary(
user_id: Optional[int] = None,
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
income_filters = [Transaction.type == TransactionType.INCOME]
expense_filters = [Transaction.type == TransactionType.EXPENSE]
if user_id is not None:
income_filters.append(Transaction.user_id == user_id)
expense_filters.append(Transaction.user_id == user_id)
income_statement = select(func.sum(Transaction.amount)).where(*income_filters)
expense_statement = select(func.sum(Transaction.amount)).where(*expense_filters)
budget_statement = select(func.sum(Category.budget)).where(Category.type == TransactionType.EXPENSE)
income = session.exec(income_statement).one() or 0
expense = session.exec(expense_statement).one() or 0
total_budget = session.exec(budget_statement).one() or 0
return {
"income": income,
"expense": expense,
"balance": income - expense,
"total_budget": total_budget,
}
@app.get("/insights/budget_history")
def get_budget_history(
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
history = session.exec(select(BudgetHistory).order_by(BudgetHistory.updated_at.desc())).all()
return history
# Push Notification Endpoints
@app.get("/push/vapid-public-key")
def get_vapid_public_key():
"""Get VAPID public key for client subscription."""
logger.info(f"[Push VAPID] Public key requested. Key configured: {bool(VAPID_PUBLIC_KEY)}")
if not VAPID_PUBLIC_KEY:
logger.warning("[Push VAPID] VAPID_PUBLIC_KEY is not configured!")
return {"publicKey": VAPID_PUBLIC_KEY}
class PushSubscriptionCreate(SQLModel):
endpoint: str
p256dh: str
auth: str
@app.post("/push/subscribe")
def subscribe_to_push(
subscription: PushSubscriptionCreate,
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
"""Subscribe current user to push notifications."""
logger.info(f"[Push Subscribe] Received subscription request from user {current_user.id}")
logger.info(f"[Push Subscribe] Endpoint: {subscription.endpoint[:50]}...")
try:
# Check if subscription already exists
existing = session.exec(
select(PushSubscription).where(
PushSubscription.endpoint == subscription.endpoint,
PushSubscription.user_id == current_user.id
)
).first()
if existing:
logger.info(f"[Push Subscribe] User {current_user.id} already subscribed to this endpoint")
return {"message": "Already subscribed"}
# Create new subscription
new_subscription = PushSubscription(
endpoint=subscription.endpoint,
p256dh=subscription.p256dh,
auth=subscription.auth,
user_id=current_user.id
)
session.add(new_subscription)
session.commit()
logger.info(f"[Push Subscribe] New subscription created for user {current_user.id}")
# Log total subscriptions count
total_subs = session.exec(select(PushSubscription)).all()
logger.info(f"[Push Subscribe] Total subscriptions in DB: {len(total_subs)}")
return {"message": "Subscribed successfully"}
except Exception as e:
logger.error(f"[Push Subscribe] Error creating subscription: {e}")
raise HTTPException(status_code=500, detail=f"Failed to save subscription: {str(e)}")
@app.delete("/push/unsubscribe")
def unsubscribe_from_push(
endpoint: str,
session: Session = Depends(get_session),
current_user: User = Depends(get_current_user)
):
"""Unsubscribe current user from push notifications."""
subscription = session.exec(
select(PushSubscription).where(
PushSubscription.endpoint == endpoint,
PushSubscription.user_id == current_user.id
)
).first()
if subscription:
session.delete(subscription)
session.commit()
return {"message": "Unsubscribed successfully"}
return {"message": "Subscription not found"}
def send_push_notification_to_all(session: Session, title: str, body: str, data: dict = None):
"""Send push notification to all subscribed users."""
logger.info(f"[Push] Attempting to send push notification: {title} - {body}")
logger.info(f"[Push] VAPID_PUBLIC_KEY configured: {bool(VAPID_PUBLIC_KEY)}")
logger.info(f"[Push] VAPID_PRIVATE_KEY configured: {bool(VAPID_PRIVATE_KEY)}")
if not VAPID_PRIVATE_KEY or not VAPID_PUBLIC_KEY:
logger.warning("[Push] VAPID keys not configured, skipping push notification")
return
subscriptions = session.exec(select(PushSubscription)).all()
logger.info(f"[Push] Found {len(subscriptions)} subscriptions")
for sub in subscriptions:
logger.info(f"[Push] Sending to subscription: {sub.endpoint[:50]}...")
try:
subscription_info = {
"endpoint": sub.endpoint,
"keys": {
"p256dh": sub.p256dh,
"auth": sub.auth
}
}
payload = json.dumps({
"title": title,
"body": body,
"tag": "transaction",
"data": data or {}
})
logger.info(f"[Push] Payload: {payload}")
result = webpush(
subscription_info=subscription_info,
data=payload,
vapid_private_key=VAPID_PRIVATE_KEY,
vapid_claims=VAPID_CLAIMS
)
logger.info(f"[Push] WebPush result: {result}")
except WebPushException as e:
logger.error(f"[Push] Failed to send push notification: {e}")
if e.response:
logger.error(f"[Push] Response status: {e.response.status_code}")
logger.error(f"[Push] Response body: {e.response.text}")
# Remove invalid subscription
if e.response and e.response.status_code in [404, 410]:
logger.info(f"[Push] Removing invalid subscription")
session.delete(sub)
session.commit()
except Exception as e:
logger.error(f"[Push] Unexpected error sending push notification: {e}")
if __name__ == "__main__":
import uvicorn
# Configure uvicorn logging to use our custom formatter
log_config = uvicorn.config.LOGGING_CONFIG
log_config["formatters"]["access"]["fmt"] = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
log_config["formatters"]["default"]["fmt"] = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
log_config["formatters"]["access"]["datefmt"] = "%Y-%m-%d %H:%M:%S"
log_config["formatters"]["default"]["datefmt"] = "%Y-%m-%d %H:%M:%S"
# Use port 8000 locally
uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True, log_config=log_config)
import logging
import os
import calendar
import unicodedata
import re
import bcrypt
import json
from typing import List, Optional
from datetime import datetime, timedelta
from fastapi import FastAPI, Depends, HTTPException, Query, Request, status, Body
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy import and_
from sqlmodel import Session, select, func, SQLModel
from jose import JWTError, jwt
from pywebpush import webpush, WebPushException
from database import create_db_and_tables, get_password_hash, get_session
from models import User, Category, SubCategory, Transaction, TransactionType, PaymentMethod, BudgetHistory, InstallmentPlan, PushSubscription
# Auth Configuration
SECRET_KEY = os.getenv("JWT_SECRET", "this-is-a-very-secret-key-for-development")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 30 # 30 days
# VAPID Keys for Web Push notifications
VAPID_PUBLIC_KEY = os.getenv("VAPID_PUBLIC_KEY", "")
VAPID_PRIVATE_KEY = os.getenv("VAPID_PRIVATE_KEY", "")
VAPID_CLAIMS = {
"sub": f"mailto:{os.getenv('VAPID_EMAIL', 'admin@example.com')}"
}
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Setup logging
class ColoredFormatter(logging.Formatter):
"""Custom logging formatter to add colors and timestamps."""
grey = "\x1b[38;20m"
blue = "\x1b[34;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
green = "\x1b[32;20m"
reset = "\x1b[0m"
format_str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
def __init__(self):
super().__init__(datefmt="%Y-%m-%d %H:%M:%S")
self.FORMATTERS = {
logging.DEBUG: logging.Formatter(self.grey + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.INFO: logging.Formatter(self.green + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.WARNING: logging.Formatter(self.yellow + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.ERROR: logging.Formatter(self.red + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S"),
logging.CRITICAL: logging.Formatter(self.bold_red + self.format_str + self.reset, datefmt="%Y-%m-%d %H:%M:%S")
}
def format(self, record):
formatter = self.FORMATTERS.get(record.levelno, self.FORMATTERS[logging.INFO])
return formatter.format(record)
# Configure the root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# Clear existing handlers
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
# Create console handler with colored formatter
ch = logging.StreamHandler()
ch.setFormatter(ColoredFormatter())
root_logger.addHandler(ch)
# Also explicitly configure uvicorn loggers to ensure they use our handlers
for logger_name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
l = logging.getLogger(logger_name)
l.handlers = [ch]
l.propagate = False
logger = logging.getLogger("spender")
app = FastAPI(title="Spender API")
# Track initial client requests to log "Server is ready" at the correct time
initial_endpoints_hit = set()
required_initial_endpoints = {
"/users",
"/transactions",
"/categories",
"/payment-methods",
"/insights/budget_history",
"/subcategories"
}
ready_logged = False
# iOS / RTL keyboards and password managers sometimes inject zero-width or bidi chars.
_ZW_AND_BIDI = frozenset(
"\u200b\u200c\u200d\ufeff\u200e\u200f\u202a\u202b\u202c\u202d\u202e"
)