import os import bcrypt from datetime import datetime from dotenv import load_dotenv from sqlalchemy import inspect, text from sqlmodel import create_engine, SQLModel, Session, select, func from models import User, Category, SubCategory, Transaction, TransactionType, PaymentMethod, BudgetHistory, InstallmentPlan, PushSubscription # Force load .env from the current directory (server/) load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) # Get database URL from environment variable, default to local sqlite database_url = os.getenv("DATABASE_URL", "sqlite:///database.db") sql_echo = os.getenv("SQL_ECHO", "false").lower() == "true" # Fix for PostgreSQL URL if it starts with postgres:// (SQLAlchemy requires postgresql://) if database_url.startswith("postgres://"): database_url = database_url.replace("postgres://", "postgresql://", 1) connect_args = {} engine_kwargs = {"echo": sql_echo} if database_url.startswith("sqlite"): connect_args = {"check_same_thread": False} else: engine_kwargs["pool_pre_ping"] = True engine_kwargs["pool_size"] = 20 engine_kwargs["max_overflow"] = 10 engine = create_engine(database_url, connect_args=connect_args, **engine_kwargs) DEFAULT_PAYMENT_METHODS = [ {"name": "מזומן", "icon": "💵"}, {"name": "כרטיס אשראי", "icon": "💳"}, {"name": "Bit", "icon": "📱"}, {"name": "PayBox", "icon": "📦"}, {"name": "העברה בנקאית", "icon": "🏦"}, {"name": "הוראת קבע", "icon": "📋"}, {"name": "הו״ק באשראי", "icon": "💳"}, ] DEFAULT_CATEGORIES = [ {"name": "מזון ופארמה", "type": TransactionType.EXPENSE, "icon": "🛒", "color": "#FF6B6B"}, {"name": "פנאי בילוי ותחביבים", "type": TransactionType.EXPENSE, "icon": "🎭", "color": "#F7B801"}, {"name": "ביגוד והנעלה", "type": TransactionType.EXPENSE, "icon": "👟", "color": "#FF8C42"}, {"name": "תכולת בית", "type": TransactionType.EXPENSE, "icon": "🛋️", "color": "#6A4C93"}, {"name": "אחזקת בית", "type": TransactionType.EXPENSE, "icon": "🧰", "color": "#1982C4"}, {"name": "טיפוח", "type": TransactionType.EXPENSE, "icon": "💄", "color": "#D81159"}, {"name": "חינוך", "type": TransactionType.EXPENSE, "icon": "📚", "color": "#4D908E"}, {"name": "אירועים", "type": TransactionType.EXPENSE, "icon": "🎉", "color": "#F15BB5"}, {"name": "בריאות", "type": TransactionType.EXPENSE, "icon": "🩺", "color": "#43AA8B"}, {"name": "תחבורה", "type": TransactionType.EXPENSE, "icon": "🚗", "color": "#577590"}, {"name": "משפחה", "type": TransactionType.EXPENSE, "icon": "👨‍👩‍👧‍👦", "color": "#90BE6D"}, {"name": "תקשורת", "type": TransactionType.EXPENSE, "icon": "📱", "color": "#277DA1"}, {"name": "דיור", "type": TransactionType.EXPENSE, "icon": "🏠", "color": "#4D96FF"}, {"name": "נכסים", "type": TransactionType.EXPENSE, "icon": "🏢", "color": "#8338EC"}, {"name": "פיננסים", "type": TransactionType.EXPENSE, "icon": "💳", "color": "#2A9D8F"}, {"name": "הלוואות ומשכנתאות", "type": TransactionType.EXPENSE, "icon": "🏦", "color": "#5B2C6F"}, {"name": "שכר", "type": TransactionType.INCOME, "icon": "💰", "color": "#34C759"}, {"name": "קצבאות", "type": TransactionType.INCOME, "icon": "🏛️", "color": "#007AFF"}, {"name": "הכנסות שונות", "type": TransactionType.INCOME, "icon": "➕", "color": "#2EC4B6"}, ] DEFAULT_SUBCATEGORIES = { # מזון ופארמה (Budget: 3250) "מזון ופארמה": [ {"name": "מזון", "icon": "🛒", "budget": 2500}, {"name": "אוכל מוכן / בעבודה", "icon": "🍱", "budget": 200}, {"name": "בר מים", "icon": "💧", "budget": 150}, {"name": "פארמה וטואלטיקה", "icon": "💊", "budget": 400}, ], # פנאי בילוי ותחביבים (Budget: 750) "פנאי בילוי ותחביבים": [ {"name": "בילויים ומופעים", "icon": "🎪", "budget": 50}, {"name": "חוגי מבוגרים", "icon": "🎨", "budget": 0}, {"name": "הגרלות", "icon": "🎲", "budget": 0}, {"name": "מסעדה ואוכל בחוץ", "icon": "🍽️", "budget": 700}, ], # ביגוד והנעלה (Budget: 600) "ביגוד והנעלה": [ {"name": "ביגוד והנעלה - כללי", "icon": "👕", "budget": 0}, {"name": "ביגוד הורים", "icon": "👔", "budget": 300}, {"name": "ביגוד ילדים", "icon": "👶", "budget": 300}, ], # תכולת בית (Budget: 250) "תכולת בית": [ {"name": "תכולת בית - כללי", "icon": "🏡", "budget": 200}, {"name": "ריהוט", "icon": "🪑", "budget": 0}, {"name": "מוצרי חשמל ואלקטרוניקה", "icon": "📺", "budget": 0}, {"name": "משחקים צעצועים וספרים", "icon": "📚", "budget": 50}, {"name": "כלי בית", "icon": "🍳", "budget": 0}, {"name": "ציוד גינה", "icon": "🌱", "budget": 0}, ], # אחזקת בית (Budget: 1591) "אחזקת בית": [ {"name": "מים וביוב", "icon": "💧", "budget": 221}, {"name": "חשמל", "icon": "💡", "budget": 1000}, {"name": "גז", "icon": "🔥", "budget": 100}, {"name": "ניקיון", "icon": "🧹", "budget": 270}, ], # טיפוח (Budget: 460) "טיפוח": [ {"name": "מספרה", "icon": "✂️", "budget": 160}, {"name": "ציפורניים וגבות", "icon": "💅", "budget": 300}, ], # חינוך (Budget: 4559) "חינוך": [ {"name": "חינוך - כללי", "icon": "🎓", "budget": 4559}, ], # אירועים (Budget: 100) "אירועים": [ {"name": "אירוע בעבודה / לחברים", "icon": "🎊", "budget": 100}, ], # בריאות (Budget: 1436) "בריאות": [ {"name": "בריאות - כללי", "icon": "⚕️", "budget": 600}, {"name": "טיפול רגשי", "icon": "🧠", "budget": 836}, ], # תחבורה (Budget: 1987) "תחבורה": [ {"name": "דלק", "icon": "⛽", "budget": 500}, {"name": "ביטוח רכב", "icon": "🛡️", "budget": 530}, {"name": "חניה", "icon": "🅿️", "budget": 63}, {"name": "כבישי אגרה", "icon": "🛣️", "budget": 50}, {"name": "רישוי רכב", "icon": "📋", "budget": 394}, {"name": "תחזוקת רכב", "icon": "🔧", "budget": 150}, ], # משפחה (Budget: 250) "משפחה": [ {"name": "אירועי שמחות במשפחה", "icon": "🎈", "budget": 250}, ], # תקשורת (Budget: 199) "תקשורת": [ {"name": "טלפון נייד ונייח", "icon": "📞", "budget": 43}, {"name": "שירותי תוכן", "icon": "📺", "budget": 156}, ], # דיור (Budget: 3700) "דיור": [ {"name": "שכר דירה", "icon": "🏠", "budget": 2500}, {"name": "מיסי יישוב / ועד בית", "icon": "🏛️", "budget": 790}, {"name": "ארנונה", "icon": "📄", "budget": 350}, {"name": "ביטוח נכס ותכולה", "icon": "🔒", "budget": 60}, ], # נכסים (Budget: 950) "נכסים": [ {"name": "הפקדות לחסכונות - כללי", "icon": "💰", "budget": 950}, ], # פיננסים (Budget: 257) "פיננסים": [ {"name": "ביטוח חיים", "icon": "🛡️", "budget": 120}, {"name": "עמלות", "icon": "💸", "budget": 137}, ], # הלוואות ומשכנתאות "הלוואות ומשכנתאות": [ {"name": "משכנתא בית בקיבוץ", "icon": "🏠", "budget": 2450}, ], # שכר (Income - Budget: 21500) "שכר": [ {"name": "שכר עבודה אלירם", "icon": "💼", "budget": 21500}, {"name": "שכר עבודה טלי", "icon": "💼", "budget": 0}, ], # קצבאות (Income - Budget: 611) "קצבאות": [ {"name": "קצבת ילדים", "icon": "👶", "budget": 611}, ], # הכנסות שונות (Income - Budget: 750) "הכנסות שונות": [ {"name": "הכנסה מנכס או פיננסי", "icon": "📈", "budget": 0}, {"name": "הכנסות שונות - כללי", "icon": "💵", "budget": 750}, ], } def create_db_and_tables(): SQLModel.metadata.create_all(engine) ensure_schema_updates() seed_data() def get_session(): with Session(engine) as session: yield session def ensure_schema_updates(): inspector = inspect(engine) # User table updates user_columns = {column["name"] for column in inspector.get_columns("user")} if "username" not in user_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "user" ADD COLUMN username VARCHAR')) if "hashed_password" not in user_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "user" ADD COLUMN hashed_password VARCHAR')) # Category table updates category_columns = {column["name"] for column in inspector.get_columns("category")} if "budget" not in category_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "category" ADD COLUMN budget FLOAT')) # Transaction table updates transaction_columns = {column["name"] for column in inspector.get_columns("transaction")} # Rename description to notes if "description" in transaction_columns and "notes" not in transaction_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "transaction" RENAME COLUMN description TO notes')) # Ensure notes column exists (for fresh DB where RENAME wouldn't run) if "notes" not in transaction_columns and "description" not in transaction_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "transaction" ADD COLUMN notes VARCHAR')) # Add sub_category_id to transaction if "sub_category_id" not in transaction_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "transaction" ADD COLUMN sub_category_id INTEGER')) # Add payee to transaction if "payee" not in transaction_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "transaction" ADD COLUMN payee VARCHAR')) # Add installment_plan_id to transaction if "installment_plan_id" not in transaction_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "transaction" ADD COLUMN installment_plan_id INTEGER')) # InstallmentPlan table updates if "installmentplan" not in inspector.get_table_names(): InstallmentPlan.__table__.create(bind=engine, checkfirst=True) else: installment_plan_columns = {column["name"] for column in inspector.get_columns("installmentplan")} if "recurring_forever" not in installment_plan_columns: with engine.begin() as connection: connection.execute(text('ALTER TABLE "installmentplan" ADD COLUMN recurring_forever BOOLEAN DEFAULT FALSE')) if "end_date" not in installment_plan_columns: with engine.begin() as connection: # PostgreSQL uses TIMESTAMP, SQLite uses DATETIME col_type = "TIMESTAMP" if database_url.startswith("postgres") else "DATETIME" connection.execute(text(f'ALTER TABLE "installmentplan" ADD COLUMN end_date {col_type}')) # Fix total_installments to allow NULL for standing orders # SQLite doesn't support ALTER COLUMN, so we recreate the table if needed # PostgreSQL supports ALTER COLUMN natively if database_url.startswith("sqlite"): with engine.begin() as connection: # Use PRAGMA to check if total_installments has NOT NULL constraint table_info = connection.execute(text('PRAGMA table_info(installmentplan)')).fetchall() total_installments_info = next((row for row in table_info if row[1] == 'total_installments'), None) if total_installments_info and total_installments_info[3] == 1: # notnull = 1 # Read existing data existing_plans = connection.execute(text( 'SELECT id, amount, notes, payee, start_date, type, total_installments, ' 'posted_installments, recurring_forever, user_id, category_id, sub_category_id, payment_method_id, end_date ' 'FROM installmentplan' )).fetchall() # Rename old table connection.execute(text('ALTER TABLE "installmentplan" RENAME TO "installmentplan_old"')) # Create new table with correct schema InstallmentPlan.__table__.drop(bind=engine, checkfirst=True) InstallmentPlan.__table__.create(bind=engine, checkfirst=True) # Migrate data back for plan in existing_plans: connection.execute(text( 'INSERT INTO installmentplan (id, amount, notes, payee, start_date, type, total_installments, ' 'posted_installments, recurring_forever, user_id, category_id, sub_category_id, payment_method_id, end_date) ' 'VALUES (:id, :amount, :notes, :payee, :start_date, :type, :total_installments, ' ':posted_installments, :recurring_forever, :user_id, :category_id, :sub_category_id, :payment_method_id, :end_date)' ), { "id": plan[0], "amount": plan[1], "notes": plan[2], "payee": plan[3], "start_date": plan[4], "type": plan[5], "total_installments": plan[6], "posted_installments": plan[7], "recurring_forever": plan[8], "user_id": plan[9], "category_id": plan[10], "sub_category_id": plan[11], "payment_method_id": plan[12], "end_date": plan[13] }) # Drop old table connection.execute(text('DROP TABLE "installmentplan_old"')) elif database_url.startswith("postgresql") or database_url.startswith("postgres"): # PostgreSQL: use ALTER COLUMN to drop NOT NULL constraint with engine.begin() as connection: try: connection.execute(text( 'ALTER TABLE installmentplan ALTER COLUMN total_installments DROP NOT NULL' )) except Exception as e: # If it fails (e.g., already nullable), just log and continue print(f"DB init note: Could not alter total_installments column (may already be nullable): {e}") def get_password_hash(password: str) -> str: pwd_bytes = password.encode('utf-8') salt = bcrypt.gensalt() hashed = bcrypt.hashpw(pwd_bytes, salt) return hashed.decode('utf-8') def _seed_users(session: Session): eliram_pwd = os.getenv("ELIRAM_PASSWORD") tali_pwd = os.getenv("TALI_PASSWORD") users_to_seed = [ {"name": "Eliram", "username": "eliram", "password": eliram_pwd}, {"name": "Tali", "username": "tali", "password": tali_pwd}, ] for user_data in users_to_seed: existing_user = session.exec(select(User).where(User.username == user_data["username"])).first() if existing_user: if user_data["password"]: existing_user.hashed_password = get_password_hash(user_data["password"]) session.add(existing_user) else: pwd = user_data["password"] or os.urandom(24).hex() session.add(User( name=user_data["name"], username=user_data["username"], hashed_password=get_password_hash(pwd), icon="📱" )) session.commit() def _seed_payment_methods(session: Session): existing_names = {pm.name for pm in session.exec(select(PaymentMethod)).all()} for payment_method in DEFAULT_PAYMENT_METHODS: if payment_method["name"] not in existing_names: session.add(PaymentMethod(**payment_method)) def _seed_categories(session: Session): existing_categories = session.exec(select(Category)).all() desired_categories = {category["name"]: category for category in DEFAULT_CATEGORIES} present_names = set() if not existing_categories: for category in DEFAULT_CATEGORIES: session.add(Category(**category)) return for category in existing_categories: category_transaction_count = session.exec( select(func.count(Transaction.id)).where(Transaction.category_id == category.id) ).one() or 0 desired_category = desired_categories.get(category.name) if desired_category is None and category_transaction_count == 0: # Delete subcategories first to avoid foreign key constraints orphaned_subs = session.exec(select(SubCategory).where(SubCategory.category_id == category.id)).all() for sub in orphaned_subs: # Also delete budget history and transactions for these subcategories sub_history = session.exec(select(BudgetHistory).where(BudgetHistory.sub_category_id == sub.id)).all() for h in sub_history: session.delete(h) sub_txs = session.exec(select(Transaction).where(Transaction.sub_category_id == sub.id)).all() for t in sub_txs: session.delete(t) session.delete(sub) # Delete transactions for the category itself (not belonging to subcategories) cat_txs = session.exec(select(Transaction).where(Transaction.category_id == category.id)).all() for t in cat_txs: session.delete(t) # Delete budget history for the category itself cat_history = session.exec(select(BudgetHistory).where(BudgetHistory.category_id == category.id)).all() for h in cat_history: session.delete(h) session.delete(category) continue if desired_category is None: continue category.type = desired_category["type"] category.icon = desired_category["icon"] category.color = desired_category["color"] session.add(category) present_names.add(category.name) for category in DEFAULT_CATEGORIES: if category["name"] not in present_names: session.add(Category(**category)) def _seed_subcategories(session: Session): """Seed subcategories based on DEFAULT_SUBCATEGORIES mapping.""" all_categories = session.exec(select(Category)).all() category_map = {cat.name: cat for cat in all_categories} for category_name, subcategories in DEFAULT_SUBCATEGORIES.items(): category = category_map.get(category_name) if not category: continue # Get existing subcategories for this category existing_subcats = session.exec( select(SubCategory).where(SubCategory.category_id == category.id) ).all() existing_subcat_names = {sub.name for sub in existing_subcats} # Add new subcategories for subcat_data in subcategories: if subcat_data["name"] not in existing_subcat_names: session.add(SubCategory( name=subcat_data["name"], icon=subcat_data["icon"], budget=subcat_data.get("budget"), category_id=category.id )) def _seed_budget_history(session: Session): """Ensure all subcategories with a budget have at least one entry in BudgetHistory.""" subcategories = session.exec(select(SubCategory).where(SubCategory.budget != None)).all() for sub in subcategories: existing_history = session.exec( select(BudgetHistory).where(BudgetHistory.sub_category_id == sub.id) ).first() if not existing_history: # Seed an initial history entry for older months session.add(BudgetHistory( sub_category_id=sub.id, budget=sub.budget or 0, updated_at=datetime(2024, 1, 1) # Far enough in the past )) def seed_data(): with Session(engine) as session: _seed_users(session) _seed_payment_methods(session) _seed_categories(session) _seed_subcategories(session) session.commit() # Commit subcategories so they have IDs _seed_budget_history(session) session.commit()