Spaces:
Sleeping
Sleeping
File size: 21,701 Bytes
746bbff d5e6687 84cf49e 746bbff d5e6687 ae02bae d5e6687 746bbff 71110b5 d5e6687 746bbff d5e6687 746bbff 5a413f5 746bbff d5e6687 746bbff d5e6687 746bbff d5e6687 746bbff d5e6687 746bbff 927282b 5db03fb 60a4068 3d86a80 55ec02e 3d86a80 60a4068 2fdbfa6 2c3a9ec 60a4068 2c3a9ec 3d86a80 2c3a9ec 3d86a80 2c3a9ec 3d86a80 2c3a9ec 3d86a80 2c3a9ec 2fdbfa6 60a4068 927282b 746bbff d5e6687 746bbff d5e6687 746bbff d5e6687 746bbff 594cd93 746bbff 594cd93 d5e6687 746bbff d5e6687 746bbff d5e6687 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | 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()
|