Spaces:
Sleeping
Sleeping
ci: deploy backend from 72c5565aa7b434db62c53d5aab4d22839e89db59
Browse files- database.py +227 -9
- main.py +407 -97
- models.py +36 -15
- requirements.txt +3 -0
database.py
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from sqlalchemy import inspect, text
|
| 2 |
from sqlmodel import create_engine, SQLModel, Session, select, func
|
| 3 |
-
from models import User, Category, Transaction, TransactionType, PaymentMethod
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
|
| 6 |
# Get database URL from environment variable, default to local sqlite
|
| 7 |
database_url = os.getenv("DATABASE_URL", "sqlite:///database.db")
|
|
@@ -26,6 +32,7 @@ DEFAULT_PAYMENT_METHODS = [
|
|
| 26 |
{"name": "Bit", "icon": "๐ฑ"},
|
| 27 |
{"name": "PayBox", "icon": "๐ฆ"},
|
| 28 |
{"name": "ืืขืืจื ืื ืงืืืช", "icon": "๐ฆ"},
|
|
|
|
| 29 |
]
|
| 30 |
|
| 31 |
DEFAULT_CATEGORIES = [
|
|
@@ -44,11 +51,120 @@ DEFAULT_CATEGORIES = [
|
|
| 44 |
{"name": "ืืืืจ", "type": TransactionType.EXPENSE, "icon": "๐ ", "color": "#4D96FF"},
|
| 45 |
{"name": "ื ืืกืื", "type": TransactionType.EXPENSE, "icon": "๐ข", "color": "#8338EC"},
|
| 46 |
{"name": "ืคืื ื ืกืื", "type": TransactionType.EXPENSE, "icon": "๐ณ", "color": "#2A9D8F"},
|
|
|
|
| 47 |
{"name": "ืฉืืจ", "type": TransactionType.INCOME, "icon": "๐ฐ", "color": "#34C759"},
|
| 48 |
{"name": "ืงืฆืืืืช", "type": TransactionType.INCOME, "icon": "๐๏ธ", "color": "#007AFF"},
|
| 49 |
{"name": "ืืื ืกืืช ืฉืื ืืช", "type": TransactionType.INCOME, "icon": "โ", "color": "#2EC4B6"},
|
| 50 |
]
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
def create_db_and_tables():
|
| 53 |
SQLModel.metadata.create_all(engine)
|
| 54 |
ensure_schema_updates()
|
|
@@ -60,21 +176,75 @@ def get_session():
|
|
| 60 |
|
| 61 |
def ensure_schema_updates():
|
| 62 |
inspector = inspect(engine)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
category_columns = {column["name"] for column in inspector.get_columns("category")}
|
| 64 |
if "budget" not in category_columns:
|
| 65 |
with engine.begin() as connection:
|
| 66 |
-
connection.execute(text(
|
|
|
|
|
|
|
| 67 |
transaction_columns = {column["name"] for column in inspector.get_columns("transaction")}
|
| 68 |
-
|
|
|
|
| 69 |
with engine.begin() as connection:
|
| 70 |
-
connection.execute(text('ALTER TABLE "transaction"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
def _seed_users(session: Session):
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
def _seed_payment_methods(session: Session):
|
| 80 |
existing_names = {pm.name for pm in session.exec(select(PaymentMethod)).all()}
|
|
@@ -99,6 +269,10 @@ def _seed_categories(session: Session):
|
|
| 99 |
|
| 100 |
desired_category = desired_categories.get(category.name)
|
| 101 |
if desired_category is None and category_transaction_count == 0:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
session.delete(category)
|
| 103 |
continue
|
| 104 |
|
|
@@ -115,9 +289,53 @@ def _seed_categories(session: Session):
|
|
| 115 |
if category["name"] not in present_names:
|
| 116 |
session.add(Category(**category))
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
def seed_data():
|
| 119 |
with Session(engine) as session:
|
| 120 |
_seed_users(session)
|
| 121 |
_seed_payment_methods(session)
|
| 122 |
_seed_categories(session)
|
|
|
|
|
|
|
|
|
|
| 123 |
session.commit()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import bcrypt
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
from sqlalchemy import inspect, text
|
| 6 |
from sqlmodel import create_engine, SQLModel, Session, select, func
|
| 7 |
+
from models import User, Category, SubCategory, Transaction, TransactionType, PaymentMethod, BudgetHistory
|
| 8 |
+
|
| 9 |
+
# Force load .env from the current directory (server/)
|
| 10 |
+
load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))
|
| 11 |
|
| 12 |
# Get database URL from environment variable, default to local sqlite
|
| 13 |
database_url = os.getenv("DATABASE_URL", "sqlite:///database.db")
|
|
|
|
| 32 |
{"name": "Bit", "icon": "๐ฑ"},
|
| 33 |
{"name": "PayBox", "icon": "๐ฆ"},
|
| 34 |
{"name": "ืืขืืจื ืื ืงืืืช", "icon": "๐ฆ"},
|
| 35 |
+
{"name": "ืืืจืืช ืงืืข", "icon": "๐"},
|
| 36 |
]
|
| 37 |
|
| 38 |
DEFAULT_CATEGORIES = [
|
|
|
|
| 51 |
{"name": "ืืืืจ", "type": TransactionType.EXPENSE, "icon": "๐ ", "color": "#4D96FF"},
|
| 52 |
{"name": "ื ืืกืื", "type": TransactionType.EXPENSE, "icon": "๐ข", "color": "#8338EC"},
|
| 53 |
{"name": "ืคืื ื ืกืื", "type": TransactionType.EXPENSE, "icon": "๐ณ", "color": "#2A9D8F"},
|
| 54 |
+
{"name": "ืืืืืืืช ืืืฉืื ืชืืืช", "type": TransactionType.EXPENSE, "icon": "๐ฆ", "color": "#5B2C6F"},
|
| 55 |
{"name": "ืฉืืจ", "type": TransactionType.INCOME, "icon": "๐ฐ", "color": "#34C759"},
|
| 56 |
{"name": "ืงืฆืืืืช", "type": TransactionType.INCOME, "icon": "๐๏ธ", "color": "#007AFF"},
|
| 57 |
{"name": "ืืื ืกืืช ืฉืื ืืช", "type": TransactionType.INCOME, "icon": "โ", "color": "#2EC4B6"},
|
| 58 |
]
|
| 59 |
|
| 60 |
+
DEFAULT_SUBCATEGORIES = {
|
| 61 |
+
# ืืืื ืืคืืจืื (Budget: 3250)
|
| 62 |
+
"ืืืื ืืคืืจืื": [
|
| 63 |
+
{"name": "ืืืื", "icon": "๐", "budget": 2500},
|
| 64 |
+
{"name": "ืืืื ืืืื / ืืขืืืื", "icon": "๐ฑ", "budget": 200},
|
| 65 |
+
{"name": "ืืจ ืืื", "icon": "๐ง", "budget": 150},
|
| 66 |
+
{"name": "ืคืืจืื ืืืืืืืืงื", "icon": "๐", "budget": 400},
|
| 67 |
+
],
|
| 68 |
+
# ืคื ืื ืืืืื ืืชืืืืืื (Budget: 750)
|
| 69 |
+
"ืคื ืื ืืืืื ืืชืืืืืื": [
|
| 70 |
+
{"name": "ืืืืืืื ืืืืคืขืื", "icon": "๐ช", "budget": 50},
|
| 71 |
+
{"name": "ืืืื ืืืืืจืื", "icon": "๐จ", "budget": 0},
|
| 72 |
+
{"name": "ืืืจืืืช", "icon": "๐ฒ", "budget": 0},
|
| 73 |
+
{"name": "ืืกืขืื ืืืืื ืืืืฅ", "icon": "๐ฝ๏ธ", "budget": 700},
|
| 74 |
+
],
|
| 75 |
+
# ืืืืื ืืื ืขืื (Budget: 600)
|
| 76 |
+
"ืืืืื ืืื ืขืื": [
|
| 77 |
+
{"name": "ืืืืื ืืื ืขืื - ืืืื", "icon": "๐", "budget": 0},
|
| 78 |
+
{"name": "ืืืืื ืืืจืื", "icon": "๐", "budget": 300},
|
| 79 |
+
{"name": "ืืืืื ืืืืื", "icon": "๐ถ", "budget": 300},
|
| 80 |
+
],
|
| 81 |
+
# ืชืืืืช ืืืช (Budget: 250)
|
| 82 |
+
"ืชืืืืช ืืืช": [
|
| 83 |
+
{"name": "ืชืืืืช ืืืช - ืืืื", "icon": "๐ก", "budget": 200},
|
| 84 |
+
{"name": "ืจืืืื", "icon": "๐ช", "budget": 0},
|
| 85 |
+
{"name": "ืืืฆืจื ืืฉืื ืืืืงืืจืื ืืงื", "icon": "๐บ", "budget": 0},
|
| 86 |
+
{"name": "ืืฉืืงืื ืฆืขืฆืืขืื ืืกืคืจืื", "icon": "๐", "budget": 50},
|
| 87 |
+
{"name": "ืืื ืืืช", "icon": "๐ณ", "budget": 0},
|
| 88 |
+
{"name": "ืฆืืื ืืื ื", "icon": "๐ฑ", "budget": 0},
|
| 89 |
+
],
|
| 90 |
+
# ืืืืงืช ืืืช (Budget: 1591)
|
| 91 |
+
"ืืืืงืช ืืืช": [
|
| 92 |
+
{"name": "ืืื ืืืืื", "icon": "๐ง", "budget": 221},
|
| 93 |
+
{"name": "ืืฉืื", "icon": "๐ก", "budget": 1000},
|
| 94 |
+
{"name": "ืื", "icon": "๐ฅ", "budget": 100},
|
| 95 |
+
{"name": "ื ืืงืืื", "icon": "๐งน", "budget": 270},
|
| 96 |
+
],
|
| 97 |
+
# ืืืคืื (Budget: 460)
|
| 98 |
+
"ืืืคืื": [
|
| 99 |
+
{"name": "ืืกืคืจื", "icon": "โ๏ธ", "budget": 160},
|
| 100 |
+
{"name": "ืฆืืคืืจื ืืื ืืืืืช", "icon": "๐
", "budget": 300},
|
| 101 |
+
],
|
| 102 |
+
# ืืื ืื (Budget: 4559)
|
| 103 |
+
"ืืื ืื": [
|
| 104 |
+
{"name": "ืืื ืื - ืืืื", "icon": "๐", "budget": 4559},
|
| 105 |
+
],
|
| 106 |
+
# ืืืจืืขืื (Budget: 100)
|
| 107 |
+
"ืืืจืืขืื": [
|
| 108 |
+
{"name": "ืืืจืืข ืืขืืืื / ืืืืจืื", "icon": "๐", "budget": 100},
|
| 109 |
+
],
|
| 110 |
+
# ืืจืืืืช (Budget: 1436)
|
| 111 |
+
"ืืจืืืืช": [
|
| 112 |
+
{"name": "ืืจืืืืช - ืืืื", "icon": "โ๏ธ", "budget": 600},
|
| 113 |
+
{"name": "ืืืคืื ืจืืฉื", "icon": "๐ง ", "budget": 836},
|
| 114 |
+
],
|
| 115 |
+
# ืชืืืืจื (Budget: 1987)
|
| 116 |
+
"ืชืืืืจื": [
|
| 117 |
+
{"name": "ืืืง", "icon": "โฝ", "budget": 500},
|
| 118 |
+
{"name": "ืืืืื ืจืื", "icon": "๐ก๏ธ", "budget": 530},
|
| 119 |
+
{"name": "ืื ืื", "icon": "๐
ฟ๏ธ", "budget": 63},
|
| 120 |
+
{"name": "ืืืืฉื ืืืจื", "icon": "๐ฃ๏ธ", "budget": 50},
|
| 121 |
+
{"name": "ืจืืฉืื ืจืื", "icon": "๐", "budget": 394},
|
| 122 |
+
{"name": "ืชืืืืงืช ืจืื", "icon": "๐ง", "budget": 150},
|
| 123 |
+
],
|
| 124 |
+
# ืืฉืคืื (Budget: 250)
|
| 125 |
+
"ืืฉืคืื": [
|
| 126 |
+
{"name": "ืืืจืืขื ืฉืืืืช ืืืฉืคืื", "icon": "๐", "budget": 250},
|
| 127 |
+
],
|
| 128 |
+
# ืชืงืฉืืจืช (Budget: 199)
|
| 129 |
+
"ืชืงืฉืืจืช": [
|
| 130 |
+
{"name": "ืืืคืื ื ืืื ืื ืืื", "icon": "๐", "budget": 43},
|
| 131 |
+
{"name": "ืฉืืจืืชื ืชืืื", "icon": "๐บ", "budget": 156},
|
| 132 |
+
],
|
| 133 |
+
# ืืืืจ (Budget: 3700)
|
| 134 |
+
"ืืืืจ": [
|
| 135 |
+
{"name": "ืฉืืจ ืืืจื", "icon": "๐ ", "budget": 2500},
|
| 136 |
+
{"name": "ืืืกื ืืืฉืื / ืืขื ืืืช", "icon": "๐๏ธ", "budget": 790},
|
| 137 |
+
{"name": "ืืจื ืื ื", "icon": "๐", "budget": 350},
|
| 138 |
+
{"name": "ืืืืื ื ืืก ืืชืืืื", "icon": "๐", "budget": 60},
|
| 139 |
+
],
|
| 140 |
+
# ื ืืกืื (Budget: 950)
|
| 141 |
+
"ื ืืกืื": [
|
| 142 |
+
{"name": "ืืคืงืืืช ืืืกืืื ืืช - ืืืื", "icon": "๐ฐ", "budget": 950},
|
| 143 |
+
],
|
| 144 |
+
# ืคืื ื ืกืื (Budget: 257)
|
| 145 |
+
"ืคืื ื ืกืื": [
|
| 146 |
+
{"name": "ืืืืื ืืืื", "icon": "๐ก๏ธ", "budget": 120},
|
| 147 |
+
{"name": "ืขืืืืช", "icon": "๐ธ", "budget": 137},
|
| 148 |
+
],
|
| 149 |
+
# ืืืืืืืช ืืืฉืื ืชืืืช
|
| 150 |
+
"ืืืืืืืช ืืืฉืื ืชืืืช": [
|
| 151 |
+
{"name": "ืืฉืื ืชื ืืืช ืืงืืืืฅ", "icon": "๐ ", "budget": 2450},
|
| 152 |
+
],
|
| 153 |
+
# ืฉืืจ (Income - Budget: 21500)
|
| 154 |
+
"ืฉืืจ": [
|
| 155 |
+
{"name": "ืฉืืจ ืขืืืื 1", "icon": "๐ผ", "budget": 21500},
|
| 156 |
+
],
|
| 157 |
+
# ืงืฆืืืืช (Income - Budget: 611)
|
| 158 |
+
"ืงืฆืืืืช": [
|
| 159 |
+
{"name": "ืงืฆืืช ืืืืื", "icon": "๐ถ", "budget": 611},
|
| 160 |
+
],
|
| 161 |
+
# ืืื ืกืืช ืฉืื ืืช (Income - Budget: 750)
|
| 162 |
+
"ืืื ืกืืช ืฉืื ืืช": [
|
| 163 |
+
{"name": "ืืื ืกื ืื ืืก ืื ืคืื ื ืกื", "icon": "๐", "budget": 0},
|
| 164 |
+
{"name": "ืืื ืกืืช ืฉืื ืืช - ืืืื", "icon": "๐ต", "budget": 750},
|
| 165 |
+
],
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
def create_db_and_tables():
|
| 169 |
SQLModel.metadata.create_all(engine)
|
| 170 |
ensure_schema_updates()
|
|
|
|
| 176 |
|
| 177 |
def ensure_schema_updates():
|
| 178 |
inspector = inspect(engine)
|
| 179 |
+
|
| 180 |
+
# User table updates
|
| 181 |
+
user_columns = {column["name"] for column in inspector.get_columns("user")}
|
| 182 |
+
if "username" not in user_columns:
|
| 183 |
+
with engine.begin() as connection:
|
| 184 |
+
connection.execute(text('ALTER TABLE "user" ADD COLUMN username VARCHAR'))
|
| 185 |
+
if "hashed_password" not in user_columns:
|
| 186 |
+
with engine.begin() as connection:
|
| 187 |
+
connection.execute(text('ALTER TABLE "user" ADD COLUMN hashed_password VARCHAR'))
|
| 188 |
+
|
| 189 |
+
# Category table updates
|
| 190 |
category_columns = {column["name"] for column in inspector.get_columns("category")}
|
| 191 |
if "budget" not in category_columns:
|
| 192 |
with engine.begin() as connection:
|
| 193 |
+
connection.execute(text('ALTER TABLE "category" ADD COLUMN budget FLOAT'))
|
| 194 |
+
|
| 195 |
+
# Transaction table updates
|
| 196 |
transaction_columns = {column["name"] for column in inspector.get_columns("transaction")}
|
| 197 |
+
# Rename description to notes
|
| 198 |
+
if "description" in transaction_columns and "notes" not in transaction_columns:
|
| 199 |
with engine.begin() as connection:
|
| 200 |
+
connection.execute(text('ALTER TABLE "transaction" RENAME COLUMN description TO notes'))
|
| 201 |
+
|
| 202 |
+
# Ensure notes column exists (for fresh DB where RENAME wouldn't run)
|
| 203 |
+
if "notes" not in transaction_columns and "description" not in transaction_columns:
|
| 204 |
+
with engine.begin() as connection:
|
| 205 |
+
connection.execute(text('ALTER TABLE "transaction" ADD COLUMN notes VARCHAR'))
|
| 206 |
+
|
| 207 |
+
# Add sub_category_id to transaction
|
| 208 |
+
if "sub_category_id" not in transaction_columns:
|
| 209 |
+
with engine.begin() as connection:
|
| 210 |
+
connection.execute(text('ALTER TABLE "transaction" ADD COLUMN sub_category_id INTEGER'))
|
| 211 |
+
|
| 212 |
+
# Add payee to transaction
|
| 213 |
+
if "payee" not in transaction_columns:
|
| 214 |
+
with engine.begin() as connection:
|
| 215 |
+
connection.execute(text('ALTER TABLE "transaction" ADD COLUMN payee VARCHAR'))
|
| 216 |
+
|
| 217 |
+
def get_password_hash(password: str) -> str:
|
| 218 |
+
pwd_bytes = password.encode('utf-8')
|
| 219 |
+
salt = bcrypt.gensalt()
|
| 220 |
+
hashed = bcrypt.hashpw(pwd_bytes, salt)
|
| 221 |
+
return hashed.decode('utf-8')
|
| 222 |
|
| 223 |
def _seed_users(session: Session):
|
| 224 |
+
eliram_pwd = os.getenv("ELIRAM_PASSWORD")
|
| 225 |
+
tali_pwd = os.getenv("TALI_PASSWORD")
|
| 226 |
+
|
| 227 |
+
users_to_seed = [
|
| 228 |
+
{"name": "Eliram", "username": "eliram", "password": eliram_pwd},
|
| 229 |
+
{"name": "Tali", "username": "tali", "password": tali_pwd},
|
| 230 |
+
]
|
| 231 |
|
| 232 |
+
for user_data in users_to_seed:
|
| 233 |
+
existing_user = session.exec(select(User).where(User.username == user_data["username"])).first()
|
| 234 |
+
|
| 235 |
+
if existing_user:
|
| 236 |
+
if user_data["password"]:
|
| 237 |
+
existing_user.hashed_password = get_password_hash(user_data["password"])
|
| 238 |
+
session.add(existing_user)
|
| 239 |
+
else:
|
| 240 |
+
pwd = user_data["password"] or os.urandom(24).hex()
|
| 241 |
+
session.add(User(
|
| 242 |
+
name=user_data["name"],
|
| 243 |
+
username=user_data["username"],
|
| 244 |
+
hashed_password=get_password_hash(pwd),
|
| 245 |
+
icon="๐ฑ"
|
| 246 |
+
))
|
| 247 |
+
session.commit()
|
| 248 |
|
| 249 |
def _seed_payment_methods(session: Session):
|
| 250 |
existing_names = {pm.name for pm in session.exec(select(PaymentMethod)).all()}
|
|
|
|
| 269 |
|
| 270 |
desired_category = desired_categories.get(category.name)
|
| 271 |
if desired_category is None and category_transaction_count == 0:
|
| 272 |
+
# Delete subcategories first to avoid foreign key constraints
|
| 273 |
+
orphaned_subs = session.exec(select(SubCategory).where(SubCategory.category_id == category.id)).all()
|
| 274 |
+
for sub in orphaned_subs:
|
| 275 |
+
session.delete(sub)
|
| 276 |
session.delete(category)
|
| 277 |
continue
|
| 278 |
|
|
|
|
| 289 |
if category["name"] not in present_names:
|
| 290 |
session.add(Category(**category))
|
| 291 |
|
| 292 |
+
def _seed_subcategories(session: Session):
|
| 293 |
+
"""Seed subcategories based on DEFAULT_SUBCATEGORIES mapping."""
|
| 294 |
+
all_categories = session.exec(select(Category)).all()
|
| 295 |
+
category_map = {cat.name: cat for cat in all_categories}
|
| 296 |
+
|
| 297 |
+
for category_name, subcategories in DEFAULT_SUBCATEGORIES.items():
|
| 298 |
+
category = category_map.get(category_name)
|
| 299 |
+
if not category:
|
| 300 |
+
continue
|
| 301 |
+
|
| 302 |
+
# Get existing subcategories for this category
|
| 303 |
+
existing_subcats = session.exec(
|
| 304 |
+
select(SubCategory).where(SubCategory.category_id == category.id)
|
| 305 |
+
).all()
|
| 306 |
+
existing_subcat_names = {sub.name for sub in existing_subcats}
|
| 307 |
+
|
| 308 |
+
# Add new subcategories
|
| 309 |
+
for subcat_data in subcategories:
|
| 310 |
+
if subcat_data["name"] not in existing_subcat_names:
|
| 311 |
+
session.add(SubCategory(
|
| 312 |
+
name=subcat_data["name"],
|
| 313 |
+
icon=subcat_data["icon"],
|
| 314 |
+
budget=subcat_data.get("budget"),
|
| 315 |
+
category_id=category.id
|
| 316 |
+
))
|
| 317 |
+
|
| 318 |
+
def _seed_budget_history(session: Session):
|
| 319 |
+
"""Ensure all subcategories with a budget have at least one entry in BudgetHistory."""
|
| 320 |
+
subcategories = session.exec(select(SubCategory).where(SubCategory.budget != None)).all()
|
| 321 |
+
for sub in subcategories:
|
| 322 |
+
existing_history = session.exec(
|
| 323 |
+
select(BudgetHistory).where(BudgetHistory.sub_category_id == sub.id)
|
| 324 |
+
).first()
|
| 325 |
+
if not existing_history:
|
| 326 |
+
# Seed an initial history entry for older months
|
| 327 |
+
session.add(BudgetHistory(
|
| 328 |
+
sub_category_id=sub.id,
|
| 329 |
+
budget=sub.budget or 0,
|
| 330 |
+
updated_at=datetime(2024, 1, 1) # Far enough in the past
|
| 331 |
+
))
|
| 332 |
+
|
| 333 |
def seed_data():
|
| 334 |
with Session(engine) as session:
|
| 335 |
_seed_users(session)
|
| 336 |
_seed_payment_methods(session)
|
| 337 |
_seed_categories(session)
|
| 338 |
+
_seed_subcategories(session)
|
| 339 |
+
session.commit() # Commit subcategories so they have IDs
|
| 340 |
+
_seed_budget_history(session)
|
| 341 |
session.commit()
|
main.py
CHANGED
|
@@ -1,52 +1,143 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 3 |
from sqlalchemy import and_
|
| 4 |
from sqlmodel import Session, select, func
|
| 5 |
-
from
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
import os
|
| 8 |
|
| 9 |
-
from database import create_db_and_tables, get_session
|
| 10 |
-
from models import User, Category, Transaction, TransactionType, PaymentMethod
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
app = FastAPI(title="Spender API")
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
@app.middleware("http")
|
| 41 |
async def log_requests(request: Request, call_next):
|
| 42 |
-
|
|
|
|
| 43 |
response = await call_next(request)
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
return response
|
| 46 |
|
| 47 |
@app.on_event("startup")
|
| 48 |
def on_startup():
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
@app.get("/")
|
| 52 |
def root():
|
|
@@ -60,30 +151,128 @@ def root():
|
|
| 60 |
def health_check():
|
| 61 |
return {"ok": True}
|
| 62 |
|
| 63 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
@app.get("/users", response_model=List[User])
|
| 65 |
-
def get_users(session: Session = Depends(get_session)):
|
| 66 |
return session.exec(select(User)).all()
|
| 67 |
|
| 68 |
-
# Categories
|
| 69 |
@app.get("/categories", response_model=List[Category])
|
| 70 |
-
def get_categories(session: Session = Depends(get_session)):
|
| 71 |
return session.exec(select(Category)).all()
|
| 72 |
|
| 73 |
@app.post("/categories", response_model=Category)
|
| 74 |
-
def create_category(category: Category, session: Session = Depends(get_session)):
|
| 75 |
session.add(category)
|
| 76 |
session.commit()
|
| 77 |
session.refresh(category)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
return category
|
| 79 |
|
| 80 |
@app.patch("/categories/{category_id}", response_model=Category)
|
| 81 |
-
def update_category(category_id: int, category: Category, session: Session = Depends(get_session)):
|
| 82 |
db_category = session.get(Category, category_id)
|
| 83 |
if not db_category:
|
| 84 |
raise HTTPException(status_code=404, detail="Category not found")
|
| 85 |
|
| 86 |
category_data = category.dict(exclude_unset=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
for key, value in category_data.items():
|
| 88 |
setattr(db_category, key, value)
|
| 89 |
|
|
@@ -93,7 +282,7 @@ def update_category(category_id: int, category: Category, session: Session = Dep
|
|
| 93 |
return db_category
|
| 94 |
|
| 95 |
@app.delete("/categories/{category_id}")
|
| 96 |
-
def delete_category(category_id: int, session: Session = Depends(get_session)):
|
| 97 |
category = session.get(Category, category_id)
|
| 98 |
if not category:
|
| 99 |
raise HTTPException(status_code=404, detail="Category not found")
|
|
@@ -102,20 +291,81 @@ def delete_category(category_id: int, session: Session = Depends(get_session)):
|
|
| 102 |
session.commit()
|
| 103 |
return {"ok": True}
|
| 104 |
|
| 105 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
@app.get("/payment-methods", response_model=List[PaymentMethod])
|
| 107 |
-
def get_payment_methods(session: Session = Depends(get_session)):
|
| 108 |
return session.exec(select(PaymentMethod)).all()
|
| 109 |
|
| 110 |
@app.post("/payment-methods", response_model=PaymentMethod)
|
| 111 |
-
def create_payment_method(payment_method: PaymentMethod, session: Session = Depends(get_session)):
|
| 112 |
session.add(payment_method)
|
| 113 |
session.commit()
|
| 114 |
session.refresh(payment_method)
|
| 115 |
return payment_method
|
| 116 |
|
| 117 |
@app.patch("/payment-methods/{pm_id}", response_model=PaymentMethod)
|
| 118 |
-
def update_payment_method(pm_id: int, payment_method: PaymentMethod, session: Session = Depends(get_session)):
|
| 119 |
db_pm = session.get(PaymentMethod, pm_id)
|
| 120 |
if not db_pm:
|
| 121 |
raise HTTPException(status_code=404, detail="Payment Method not found")
|
|
@@ -130,7 +380,7 @@ def update_payment_method(pm_id: int, payment_method: PaymentMethod, session: Se
|
|
| 130 |
return db_pm
|
| 131 |
|
| 132 |
@app.delete("/payment-methods/{pm_id}")
|
| 133 |
-
def delete_payment_method(pm_id: int, session: Session = Depends(get_session)):
|
| 134 |
pm = session.get(PaymentMethod, pm_id)
|
| 135 |
if not pm:
|
| 136 |
raise HTTPException(status_code=404, detail="Payment Method not found")
|
|
@@ -139,12 +389,9 @@ def delete_payment_method(pm_id: int, session: Session = Depends(get_session)):
|
|
| 139 |
session.commit()
|
| 140 |
return {"ok": True}
|
| 141 |
|
| 142 |
-
# Transactions
|
| 143 |
-
from datetime import datetime, timedelta
|
| 144 |
-
|
| 145 |
# Helper to add months
|
| 146 |
def add_months(sourcedate, months):
|
| 147 |
-
import calendar
|
| 148 |
month = sourcedate.month - 1 + months
|
| 149 |
year = sourcedate.year + month // 12
|
| 150 |
month = month % 12 + 1
|
|
@@ -152,43 +399,71 @@ def add_months(sourcedate, months):
|
|
| 152 |
return datetime(year, month, day, sourcedate.hour, sourcedate.minute, sourcedate.second)
|
| 153 |
|
| 154 |
@app.post("/transactions", response_model=List[Transaction])
|
| 155 |
-
def create_transaction(transaction: Transaction, session: Session = Depends(get_session)):
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
new_t = Transaction(
|
| 164 |
-
amount=transaction.amount,
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
date=
|
| 168 |
type=transaction.type,
|
| 169 |
-
is_installment=
|
| 170 |
-
|
| 171 |
-
total_installments=transaction.total_installments,
|
| 172 |
-
user_id=transaction.user_id,
|
| 173 |
category_id=transaction.category_id,
|
| 174 |
-
|
|
|
|
| 175 |
)
|
| 176 |
session.add(new_t)
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
session.refresh(transaction)
|
| 186 |
-
return [transaction]
|
| 187 |
-
|
| 188 |
@app.get("/transactions/installments")
|
| 189 |
-
def get_installment_plans(session: Session = Depends(get_session)):
|
| 190 |
-
# Returns only active/future installments grouped by their original purchase
|
| 191 |
-
# For now, just return all transactions that are installments
|
| 192 |
return session.exec(
|
| 193 |
select(Transaction)
|
| 194 |
.where(Transaction.is_installment == True)
|
|
@@ -197,25 +472,57 @@ def get_installment_plans(session: Session = Depends(get_session)):
|
|
| 197 |
|
| 198 |
@app.get("/transactions", response_model=List[Transaction])
|
| 199 |
def get_transactions(
|
| 200 |
-
user_id: Optional[int] = None,
|
| 201 |
limit: int = Query(default=100, le=500),
|
| 202 |
-
session: Session = Depends(get_session)
|
|
|
|
| 203 |
):
|
| 204 |
statement = select(Transaction).order_by(Transaction.date.desc()).limit(limit)
|
| 205 |
-
if user_id:
|
| 206 |
-
statement = statement.where(Transaction.user_id == user_id)
|
| 207 |
return session.exec(statement).all()
|
| 208 |
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
@app.get("/insights/category_summary")
|
| 211 |
def get_category_summary(
|
| 212 |
type: TransactionType = TransactionType.EXPENSE,
|
| 213 |
-
|
| 214 |
-
|
| 215 |
):
|
| 216 |
join_condition = Transaction.category_id == Category.id
|
| 217 |
-
if user_id:
|
| 218 |
-
join_condition = and_(join_condition, Transaction.user_id == user_id)
|
| 219 |
|
| 220 |
results = session.exec(
|
| 221 |
select(
|
|
@@ -248,21 +555,15 @@ def get_category_summary(
|
|
| 248 |
|
| 249 |
@app.get("/insights/total_summary")
|
| 250 |
def get_total_summary(
|
| 251 |
-
|
| 252 |
-
|
| 253 |
):
|
| 254 |
income_statement = select(func.sum(Transaction.amount)).where(Transaction.type == TransactionType.INCOME)
|
| 255 |
expense_statement = select(func.sum(Transaction.amount)).where(Transaction.type == TransactionType.EXPENSE)
|
| 256 |
budget_statement = select(func.sum(Category.budget)).where(Category.type == TransactionType.EXPENSE)
|
| 257 |
|
| 258 |
-
if user_id:
|
| 259 |
-
income_statement = income_statement.where(Transaction.user_id == user_id)
|
| 260 |
-
expense_statement = expense_statement.where(Transaction.user_id == user_id)
|
| 261 |
-
|
| 262 |
income = session.exec(income_statement).one() or 0
|
| 263 |
-
|
| 264 |
expense = session.exec(expense_statement).one() or 0
|
| 265 |
-
|
| 266 |
total_budget = session.exec(budget_statement).one() or 0
|
| 267 |
|
| 268 |
return {
|
|
@@ -272,6 +573,15 @@ def get_total_summary(
|
|
| 272 |
"total_budget": total_budget,
|
| 273 |
}
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
if __name__ == "__main__":
|
| 276 |
import uvicorn
|
| 277 |
-
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import calendar
|
| 4 |
+
import unicodedata
|
| 5 |
+
import bcrypt
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
|
| 9 |
+
from fastapi import FastAPI, Depends, HTTPException, Query, Request, status
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
+
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
| 12 |
from sqlalchemy import and_
|
| 13 |
from sqlmodel import Session, select, func
|
| 14 |
+
from jose import JWTError, jwt
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
from database import create_db_and_tables, get_password_hash, get_session
|
| 17 |
+
from models import User, Category, SubCategory, Transaction, TransactionType, PaymentMethod, BudgetHistory
|
| 18 |
|
| 19 |
+
# Auth Configuration
|
| 20 |
+
SECRET_KEY = os.getenv("JWT_SECRET", "this-is-a-very-secret-key-for-development")
|
| 21 |
+
ALGORITHM = "HS256"
|
| 22 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 30 # 30 days
|
| 23 |
+
|
| 24 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
| 25 |
+
|
| 26 |
+
# Setup logging
|
| 27 |
+
logging.basicConfig(level=logging.INFO)
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
|
| 30 |
app = FastAPI(title="Spender API")
|
| 31 |
|
| 32 |
+
# Track initial client requests to log "Server is ready" at the correct time
|
| 33 |
+
initial_endpoints_hit = set()
|
| 34 |
+
required_initial_endpoints = {
|
| 35 |
+
"/users",
|
| 36 |
+
"/transactions",
|
| 37 |
+
"/categories",
|
| 38 |
+
"/payment-methods",
|
| 39 |
+
"/insights/budget_history",
|
| 40 |
+
"/subcategories"
|
| 41 |
+
}
|
| 42 |
+
ready_logged = False
|
| 43 |
+
|
| 44 |
+
# iOS / RTL keyboards and password managers sometimes inject zero-width or bidi chars.
|
| 45 |
+
_ZW_AND_BIDI = frozenset(
|
| 46 |
+
"\u200b\u200c\u200d\ufeff\u200e\u200f\u202a\u202b\u202c\u202d\u202e"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def sanitize_login_password(plain: str) -> str:
|
| 51 |
+
if not plain:
|
| 52 |
+
return ""
|
| 53 |
+
s = unicodedata.normalize("NFC", plain)
|
| 54 |
+
s = "".join(c for c in s if c not in _ZW_AND_BIDI)
|
| 55 |
+
return s.strip()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def sanitize_login_username(name: str) -> str:
|
| 59 |
+
if not name:
|
| 60 |
+
return ""
|
| 61 |
+
s = unicodedata.normalize("NFC", str(name))
|
| 62 |
+
s = "".join(c for c in s if c not in _ZW_AND_BIDI)
|
| 63 |
+
return s.strip().lower()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def verify_password(plain_password: str, hashed_password: str):
|
| 67 |
+
try:
|
| 68 |
+
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
| 69 |
+
except Exception:
|
| 70 |
+
return False
|
| 71 |
+
|
| 72 |
+
def create_access_token(data: dict):
|
| 73 |
+
to_encode = data.copy()
|
| 74 |
+
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 75 |
+
to_encode.update({"exp": expire})
|
| 76 |
+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 77 |
+
return encoded_jwt
|
| 78 |
+
|
| 79 |
+
async def get_current_user(token: str = Depends(oauth2_scheme), session: Session = Depends(get_session)):
|
| 80 |
+
credentials_exception = HTTPException(
|
| 81 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 82 |
+
detail="Could not validate credentials",
|
| 83 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 84 |
)
|
| 85 |
+
try:
|
| 86 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 87 |
+
username: str = payload.get("sub")
|
| 88 |
+
if username is None:
|
| 89 |
+
raise credentials_exception
|
| 90 |
+
except JWTError:
|
| 91 |
+
raise credentials_exception
|
| 92 |
+
|
| 93 |
+
user = session.exec(select(User).where(User.username == username)).first()
|
| 94 |
+
if user is None:
|
| 95 |
+
raise credentials_exception
|
| 96 |
+
return user
|
| 97 |
+
|
| 98 |
+
# Ultra-permissive CORS for debugging
|
| 99 |
+
app.add_middleware(
|
| 100 |
+
CORSMiddleware,
|
| 101 |
+
allow_origins=["*"],
|
| 102 |
+
allow_credentials=False,
|
| 103 |
+
allow_methods=["*"],
|
| 104 |
+
allow_headers=["*"],
|
| 105 |
+
expose_headers=["*"],
|
| 106 |
+
)
|
| 107 |
|
| 108 |
@app.middleware("http")
|
| 109 |
async def log_requests(request: Request, call_next):
|
| 110 |
+
global ready_logged
|
| 111 |
+
logger.info(f"INCOMING: {request.method} {request.url.path}")
|
| 112 |
response = await call_next(request)
|
| 113 |
+
logger.info(f"OUTGOING: {request.method} {request.url.path} - Status: {response.status_code}")
|
| 114 |
+
|
| 115 |
+
# Track completion of initial data load
|
| 116 |
+
if not ready_logged and response.status_code == 200:
|
| 117 |
+
path = request.url.path
|
| 118 |
+
if path in required_initial_endpoints:
|
| 119 |
+
if path not in initial_endpoints_hit:
|
| 120 |
+
initial_endpoints_hit.add(path)
|
| 121 |
+
remaining = required_initial_endpoints - initial_endpoints_hit
|
| 122 |
+
if not remaining:
|
| 123 |
+
print("\n\033[32m" + "โ
Server is ready! Client has successfully loaded all initial data." + "\033[0m\n")
|
| 124 |
+
ready_logged = True
|
| 125 |
+
else:
|
| 126 |
+
print(f"\033[33mโณ Waiting for initial data load... ({len(initial_endpoints_hit)}/{len(required_initial_endpoints)}): {path} loaded.\033[0m")
|
| 127 |
+
|
| 128 |
return response
|
| 129 |
|
| 130 |
@app.on_event("startup")
|
| 131 |
def on_startup():
|
| 132 |
+
import threading
|
| 133 |
+
def init_db():
|
| 134 |
+
try:
|
| 135 |
+
create_db_and_tables()
|
| 136 |
+
print("\n\033[32mโ
Database initialized successfully\033[0m")
|
| 137 |
+
except Exception as e:
|
| 138 |
+
print(f"\n\033[33mโ ๏ธ DB init warning: {e}\033[0m")
|
| 139 |
+
threading.Thread(target=init_db, daemon=True).start()
|
| 140 |
+
print("\n\033[34m๐ก Spender API started. Waiting for client to load initial data...\033[0m")
|
| 141 |
|
| 142 |
@app.get("/")
|
| 143 |
def root():
|
|
|
|
| 151 |
def health_check():
|
| 152 |
return {"ok": True}
|
| 153 |
|
| 154 |
+
# Login
|
| 155 |
+
@app.post("/token")
|
| 156 |
+
async def login_for_access_token(
|
| 157 |
+
request: Request,
|
| 158 |
+
form_data: OAuth2PasswordRequestForm = Depends(),
|
| 159 |
+
session: Session = Depends(get_session),
|
| 160 |
+
):
|
| 161 |
+
raw_username = form_data.username or ""
|
| 162 |
+
raw_password = form_data.password or ""
|
| 163 |
+
username = sanitize_login_username(raw_username)
|
| 164 |
+
password = sanitize_login_password(raw_password)
|
| 165 |
+
client_host = request.client.host if request.client else "unknown"
|
| 166 |
+
user_agent = request.headers.get("user-agent", "")[:200]
|
| 167 |
+
|
| 168 |
+
if raw_password != password or raw_username != username:
|
| 169 |
+
logger.info(
|
| 170 |
+
"Login: normalized credentials (zero-width/bidi/NFC/trim/case); "
|
| 171 |
+
"password_altered=%s username_altered=%s ua=%r ip=%s",
|
| 172 |
+
raw_password != password,
|
| 173 |
+
raw_username != username,
|
| 174 |
+
user_agent,
|
| 175 |
+
client_host,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
user = session.exec(select(User).where(User.username == username)).first()
|
| 179 |
+
if not user:
|
| 180 |
+
logger.warning(
|
| 181 |
+
"Login failed: user not found; username=%r len=%s ua=%r ip=%s",
|
| 182 |
+
username,
|
| 183 |
+
len(username),
|
| 184 |
+
user_agent,
|
| 185 |
+
client_host,
|
| 186 |
+
)
|
| 187 |
+
raise HTTPException(
|
| 188 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 189 |
+
detail="Incorrect username or password",
|
| 190 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 191 |
+
)
|
| 192 |
+
if not verify_password(password, user.hashed_password):
|
| 193 |
+
logger.warning(
|
| 194 |
+
"Login failed: bad password for user=%r pwd_len=%s ua=%r ip=%s",
|
| 195 |
+
username,
|
| 196 |
+
len(password),
|
| 197 |
+
user_agent,
|
| 198 |
+
client_host,
|
| 199 |
+
)
|
| 200 |
+
raise HTTPException(
|
| 201 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 202 |
+
detail="Incorrect username or password",
|
| 203 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 204 |
+
)
|
| 205 |
+
logger.info("Login success: user=%r ip=%s", username, client_host)
|
| 206 |
+
access_token = create_access_token(data={"sub": user.username})
|
| 207 |
+
return {"access_token": access_token, "token_type": "bearer", "user_id": user.id, "name": user.name}
|
| 208 |
+
|
| 209 |
+
# Me
|
| 210 |
+
@app.get("/me")
|
| 211 |
+
async def read_users_me(current_user: User = Depends(get_current_user)):
|
| 212 |
+
return current_user
|
| 213 |
+
|
| 214 |
+
@app.post("/change-password")
|
| 215 |
+
async def change_password(
|
| 216 |
+
old_password: str = Query(...),
|
| 217 |
+
new_password: str = Query(...),
|
| 218 |
+
current_user: User = Depends(get_current_user),
|
| 219 |
+
session: Session = Depends(get_session)
|
| 220 |
+
):
|
| 221 |
+
old_password = sanitize_login_password(old_password)
|
| 222 |
+
new_password = sanitize_login_password(new_password)
|
| 223 |
+
if not verify_password(old_password, current_user.hashed_password):
|
| 224 |
+
raise HTTPException(status_code=400, detail="Incorrect old password")
|
| 225 |
+
|
| 226 |
+
current_user.hashed_password = get_password_hash(new_password)
|
| 227 |
+
session.add(current_user)
|
| 228 |
+
session.commit()
|
| 229 |
+
return {"ok": True}
|
| 230 |
+
|
| 231 |
+
# Users (Protected)
|
| 232 |
@app.get("/users", response_model=List[User])
|
| 233 |
+
def get_users(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 234 |
return session.exec(select(User)).all()
|
| 235 |
|
| 236 |
+
# Categories (Protected)
|
| 237 |
@app.get("/categories", response_model=List[Category])
|
| 238 |
+
def get_categories(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 239 |
return session.exec(select(Category)).all()
|
| 240 |
|
| 241 |
@app.post("/categories", response_model=Category)
|
| 242 |
+
def create_category(category: Category, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 243 |
session.add(category)
|
| 244 |
session.commit()
|
| 245 |
session.refresh(category)
|
| 246 |
+
|
| 247 |
+
# Log initial budget if it exists
|
| 248 |
+
if category.budget is not None:
|
| 249 |
+
history = BudgetHistory(
|
| 250 |
+
category_id=category.id,
|
| 251 |
+
budget=category.budget,
|
| 252 |
+
updated_at=datetime.utcnow()
|
| 253 |
+
)
|
| 254 |
+
session.add(history)
|
| 255 |
+
session.commit()
|
| 256 |
+
|
| 257 |
return category
|
| 258 |
|
| 259 |
@app.patch("/categories/{category_id}", response_model=Category)
|
| 260 |
+
def update_category(category_id: int, category: Category, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 261 |
db_category = session.get(Category, category_id)
|
| 262 |
if not db_category:
|
| 263 |
raise HTTPException(status_code=404, detail="Category not found")
|
| 264 |
|
| 265 |
category_data = category.dict(exclude_unset=True)
|
| 266 |
+
|
| 267 |
+
# Check if budget is being updated
|
| 268 |
+
if "budget" in category_data and category_data["budget"] != db_category.budget:
|
| 269 |
+
history = BudgetHistory(
|
| 270 |
+
category_id=category_id,
|
| 271 |
+
budget=category_data["budget"] if category_data["budget"] is not None else 0,
|
| 272 |
+
updated_at=datetime.utcnow()
|
| 273 |
+
)
|
| 274 |
+
session.add(history)
|
| 275 |
+
|
| 276 |
for key, value in category_data.items():
|
| 277 |
setattr(db_category, key, value)
|
| 278 |
|
|
|
|
| 282 |
return db_category
|
| 283 |
|
| 284 |
@app.delete("/categories/{category_id}")
|
| 285 |
+
def delete_category(category_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 286 |
category = session.get(Category, category_id)
|
| 287 |
if not category:
|
| 288 |
raise HTTPException(status_code=404, detail="Category not found")
|
|
|
|
| 291 |
session.commit()
|
| 292 |
return {"ok": True}
|
| 293 |
|
| 294 |
+
# SubCategories (Protected)
|
| 295 |
+
@app.get("/subcategories", response_model=List[SubCategory])
|
| 296 |
+
def get_subcategories(category_id: Optional[int] = None, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 297 |
+
statement = select(SubCategory)
|
| 298 |
+
if category_id:
|
| 299 |
+
statement = statement.where(SubCategory.category_id == category_id)
|
| 300 |
+
return session.exec(statement).all()
|
| 301 |
+
|
| 302 |
+
@app.post("/subcategories", response_model=SubCategory)
|
| 303 |
+
def create_subcategory(subcategory: SubCategory, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 304 |
+
session.add(subcategory)
|
| 305 |
+
session.commit()
|
| 306 |
+
session.refresh(subcategory)
|
| 307 |
+
|
| 308 |
+
# Log initial budget if it exists
|
| 309 |
+
if subcategory.budget is not None:
|
| 310 |
+
history = BudgetHistory(
|
| 311 |
+
sub_category_id=subcategory.id,
|
| 312 |
+
budget=subcategory.budget,
|
| 313 |
+
updated_at=datetime.utcnow()
|
| 314 |
+
)
|
| 315 |
+
session.add(history)
|
| 316 |
+
session.commit()
|
| 317 |
+
|
| 318 |
+
return subcategory
|
| 319 |
+
|
| 320 |
+
@app.patch("/subcategories/{subcategory_id}", response_model=SubCategory)
|
| 321 |
+
def update_subcategory(subcategory_id: int, subcategory: SubCategory, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 322 |
+
db_subcategory = session.get(SubCategory, subcategory_id)
|
| 323 |
+
if not db_subcategory:
|
| 324 |
+
raise HTTPException(status_code=404, detail="SubCategory not found")
|
| 325 |
+
|
| 326 |
+
data = subcategory.dict(exclude_unset=True)
|
| 327 |
+
|
| 328 |
+
# Check if budget is being updated
|
| 329 |
+
if "budget" in data and data["budget"] != db_subcategory.budget:
|
| 330 |
+
history = BudgetHistory(
|
| 331 |
+
sub_category_id=subcategory_id,
|
| 332 |
+
budget=data["budget"] if data["budget"] is not None else 0,
|
| 333 |
+
updated_at=datetime.utcnow()
|
| 334 |
+
)
|
| 335 |
+
session.add(history)
|
| 336 |
+
|
| 337 |
+
for key, value in data.items():
|
| 338 |
+
setattr(db_subcategory, key, value)
|
| 339 |
+
|
| 340 |
+
session.add(db_subcategory)
|
| 341 |
+
session.commit()
|
| 342 |
+
session.refresh(db_subcategory)
|
| 343 |
+
return db_subcategory
|
| 344 |
+
|
| 345 |
+
@app.delete("/subcategories/{subcategory_id}")
|
| 346 |
+
def delete_subcategory(subcategory_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 347 |
+
subcategory = session.get(SubCategory, subcategory_id)
|
| 348 |
+
if not subcategory:
|
| 349 |
+
raise HTTPException(status_code=404, detail="SubCategory not found")
|
| 350 |
+
|
| 351 |
+
session.delete(subcategory)
|
| 352 |
+
session.commit()
|
| 353 |
+
return {"ok": True}
|
| 354 |
+
|
| 355 |
+
# Payment Methods (Protected)
|
| 356 |
@app.get("/payment-methods", response_model=List[PaymentMethod])
|
| 357 |
+
def get_payment_methods(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 358 |
return session.exec(select(PaymentMethod)).all()
|
| 359 |
|
| 360 |
@app.post("/payment-methods", response_model=PaymentMethod)
|
| 361 |
+
def create_payment_method(payment_method: PaymentMethod, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 362 |
session.add(payment_method)
|
| 363 |
session.commit()
|
| 364 |
session.refresh(payment_method)
|
| 365 |
return payment_method
|
| 366 |
|
| 367 |
@app.patch("/payment-methods/{pm_id}", response_model=PaymentMethod)
|
| 368 |
+
def update_payment_method(pm_id: int, payment_method: PaymentMethod, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 369 |
db_pm = session.get(PaymentMethod, pm_id)
|
| 370 |
if not db_pm:
|
| 371 |
raise HTTPException(status_code=404, detail="Payment Method not found")
|
|
|
|
| 380 |
return db_pm
|
| 381 |
|
| 382 |
@app.delete("/payment-methods/{pm_id}")
|
| 383 |
+
def delete_payment_method(pm_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 384 |
pm = session.get(PaymentMethod, pm_id)
|
| 385 |
if not pm:
|
| 386 |
raise HTTPException(status_code=404, detail="Payment Method not found")
|
|
|
|
| 389 |
session.commit()
|
| 390 |
return {"ok": True}
|
| 391 |
|
| 392 |
+
# Transactions (Protected - SHARED ACCESS)
|
|
|
|
|
|
|
| 393 |
# Helper to add months
|
| 394 |
def add_months(sourcedate, months):
|
|
|
|
| 395 |
month = sourcedate.month - 1 + months
|
| 396 |
year = sourcedate.year + month // 12
|
| 397 |
month = month % 12 + 1
|
|
|
|
| 399 |
return datetime(year, month, day, sourcedate.hour, sourcedate.minute, sourcedate.second)
|
| 400 |
|
| 401 |
@app.post("/transactions", response_model=List[Transaction])
|
| 402 |
+
def create_transaction(transaction: Transaction, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 403 |
+
try:
|
| 404 |
+
if transaction.amount <= 0:
|
| 405 |
+
raise HTTPException(status_code=400, detail="Amount must be positive")
|
| 406 |
+
if not transaction.sub_category_id:
|
| 407 |
+
raise HTTPException(status_code=400, detail="Sub-category is required")
|
| 408 |
+
|
| 409 |
+
user_id = transaction.user_id or current_user.id
|
| 410 |
+
|
| 411 |
+
# Parse date string to datetime if needed (SQLite requires datetime objects)
|
| 412 |
+
if isinstance(transaction.date, str):
|
| 413 |
+
date_str = transaction.date.replace('Z', '+00:00')
|
| 414 |
+
parsed_date = datetime.fromisoformat(date_str)
|
| 415 |
+
else:
|
| 416 |
+
parsed_date = transaction.date or datetime.utcnow()
|
| 417 |
+
|
| 418 |
+
if transaction.is_installment and transaction.total_installments and transaction.total_installments > 1:
|
| 419 |
+
created_transactions = []
|
| 420 |
+
base_notes = transaction.notes
|
| 421 |
+
for i in range(1, transaction.total_installments + 1):
|
| 422 |
+
new_date = add_months(parsed_date, i - 1)
|
| 423 |
+
new_t = Transaction(
|
| 424 |
+
amount=transaction.amount,
|
| 425 |
+
notes=f"{base_notes} ({i}/{transaction.total_installments})",
|
| 426 |
+
payee=transaction.payee,
|
| 427 |
+
date=new_date,
|
| 428 |
+
type=transaction.type,
|
| 429 |
+
is_installment=True,
|
| 430 |
+
installment_number=i,
|
| 431 |
+
total_installments=transaction.total_installments,
|
| 432 |
+
user_id=user_id,
|
| 433 |
+
category_id=transaction.category_id,
|
| 434 |
+
sub_category_id=transaction.sub_category_id if transaction.sub_category_id != 0 else None,
|
| 435 |
+
payment_method_id=transaction.payment_method_id if transaction.payment_method_id != 0 else None
|
| 436 |
+
)
|
| 437 |
+
session.add(new_t)
|
| 438 |
+
created_transactions.append(new_t)
|
| 439 |
+
session.commit()
|
| 440 |
+
for t in created_transactions:
|
| 441 |
+
session.refresh(t)
|
| 442 |
+
return created_transactions
|
| 443 |
+
else:
|
| 444 |
new_t = Transaction(
|
| 445 |
+
amount=transaction.amount,
|
| 446 |
+
notes=transaction.notes,
|
| 447 |
+
payee=transaction.payee,
|
| 448 |
+
date=parsed_date,
|
| 449 |
type=transaction.type,
|
| 450 |
+
is_installment=False,
|
| 451 |
+
user_id=user_id,
|
|
|
|
|
|
|
| 452 |
category_id=transaction.category_id,
|
| 453 |
+
sub_category_id=transaction.sub_category_id if transaction.sub_category_id != 0 else None,
|
| 454 |
+
payment_method_id=transaction.payment_method_id if transaction.payment_method_id != 0 else None
|
| 455 |
)
|
| 456 |
session.add(new_t)
|
| 457 |
+
session.commit()
|
| 458 |
+
session.refresh(new_t)
|
| 459 |
+
return [new_t]
|
| 460 |
+
except Exception as e:
|
| 461 |
+
logger.error(f"Error creating transaction: {str(e)}", exc_info=True)
|
| 462 |
+
if isinstance(e, HTTPException):
|
| 463 |
+
raise e
|
| 464 |
+
raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
| 465 |
@app.get("/transactions/installments")
|
| 466 |
+
def get_installment_plans(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
|
|
|
|
|
|
| 467 |
return session.exec(
|
| 468 |
select(Transaction)
|
| 469 |
.where(Transaction.is_installment == True)
|
|
|
|
| 472 |
|
| 473 |
@app.get("/transactions", response_model=List[Transaction])
|
| 474 |
def get_transactions(
|
|
|
|
| 475 |
limit: int = Query(default=100, le=500),
|
| 476 |
+
session: Session = Depends(get_session),
|
| 477 |
+
current_user: User = Depends(get_current_user)
|
| 478 |
):
|
| 479 |
statement = select(Transaction).order_by(Transaction.date.desc()).limit(limit)
|
|
|
|
|
|
|
| 480 |
return session.exec(statement).all()
|
| 481 |
|
| 482 |
+
@app.patch("/transactions/{transaction_id}", response_model=Transaction)
|
| 483 |
+
def update_transaction(transaction_id: int, transaction: Transaction, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 484 |
+
db_transaction = session.get(Transaction, transaction_id)
|
| 485 |
+
if not db_transaction:
|
| 486 |
+
raise HTTPException(status_code=404, detail="Transaction not found")
|
| 487 |
+
|
| 488 |
+
transaction_data = transaction.dict(exclude_unset=True)
|
| 489 |
+
if "amount" in transaction_data and transaction_data["amount"] <= 0:
|
| 490 |
+
raise HTTPException(status_code=400, detail="Amount must be positive")
|
| 491 |
+
|
| 492 |
+
# Validate sub_category_id is not being cleared
|
| 493 |
+
if "sub_category_id" in transaction_data and not transaction_data["sub_category_id"]:
|
| 494 |
+
raise HTTPException(status_code=400, detail="Sub-category is required")
|
| 495 |
+
|
| 496 |
+
# Handle 0 as None for optional foreign keys
|
| 497 |
+
if "payment_method_id" in transaction_data and transaction_data["payment_method_id"] == 0:
|
| 498 |
+
transaction_data["payment_method_id"] = None
|
| 499 |
+
|
| 500 |
+
for key, value in transaction_data.items():
|
| 501 |
+
setattr(db_transaction, key, value)
|
| 502 |
+
|
| 503 |
+
session.add(db_transaction)
|
| 504 |
+
session.commit()
|
| 505 |
+
session.refresh(db_transaction)
|
| 506 |
+
return db_transaction
|
| 507 |
+
|
| 508 |
+
@app.delete("/transactions/{transaction_id}")
|
| 509 |
+
def delete_transaction(transaction_id: int, session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
|
| 510 |
+
transaction = session.get(Transaction, transaction_id)
|
| 511 |
+
if not transaction:
|
| 512 |
+
raise HTTPException(status_code=404, detail="Transaction not found")
|
| 513 |
+
|
| 514 |
+
session.delete(transaction)
|
| 515 |
+
session.commit()
|
| 516 |
+
return {"ok": True}
|
| 517 |
+
|
| 518 |
+
# Insights (Protected - SHARED DATA)
|
| 519 |
@app.get("/insights/category_summary")
|
| 520 |
def get_category_summary(
|
| 521 |
type: TransactionType = TransactionType.EXPENSE,
|
| 522 |
+
session: Session = Depends(get_session),
|
| 523 |
+
current_user: User = Depends(get_current_user)
|
| 524 |
):
|
| 525 |
join_condition = Transaction.category_id == Category.id
|
|
|
|
|
|
|
| 526 |
|
| 527 |
results = session.exec(
|
| 528 |
select(
|
|
|
|
| 555 |
|
| 556 |
@app.get("/insights/total_summary")
|
| 557 |
def get_total_summary(
|
| 558 |
+
session: Session = Depends(get_session),
|
| 559 |
+
current_user: User = Depends(get_current_user)
|
| 560 |
):
|
| 561 |
income_statement = select(func.sum(Transaction.amount)).where(Transaction.type == TransactionType.INCOME)
|
| 562 |
expense_statement = select(func.sum(Transaction.amount)).where(Transaction.type == TransactionType.EXPENSE)
|
| 563 |
budget_statement = select(func.sum(Category.budget)).where(Category.type == TransactionType.EXPENSE)
|
| 564 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
income = session.exec(income_statement).one() or 0
|
|
|
|
| 566 |
expense = session.exec(expense_statement).one() or 0
|
|
|
|
| 567 |
total_budget = session.exec(budget_statement).one() or 0
|
| 568 |
|
| 569 |
return {
|
|
|
|
| 573 |
"total_budget": total_budget,
|
| 574 |
}
|
| 575 |
|
| 576 |
+
@app.get("/insights/budget_history")
|
| 577 |
+
def get_budget_history(
|
| 578 |
+
session: Session = Depends(get_session),
|
| 579 |
+
current_user: User = Depends(get_current_user)
|
| 580 |
+
):
|
| 581 |
+
history = session.exec(select(BudgetHistory).order_by(BudgetHistory.updated_at.desc())).all()
|
| 582 |
+
return history
|
| 583 |
+
|
| 584 |
if __name__ == "__main__":
|
| 585 |
import uvicorn
|
| 586 |
+
# Use port 8000 locally
|
| 587 |
+
uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
|
models.py
CHANGED
|
@@ -10,45 +10,66 @@ class TransactionType(str, Enum):
|
|
| 10 |
class User(SQLModel, table=True):
|
| 11 |
id: Optional[int] = Field(default=None, primary_key=True)
|
| 12 |
name: str
|
|
|
|
|
|
|
| 13 |
icon: str = "๐ค"
|
| 14 |
|
| 15 |
transactions: List["Transaction"] = Relationship(back_populates="user")
|
| 16 |
|
| 17 |
-
class PaymentMethod(SQLModel, table=True):
|
| 18 |
-
id: Optional[int] = Field(default=None, primary_key=True)
|
| 19 |
-
name: str
|
| 20 |
-
icon: str = "๐ณ"
|
| 21 |
-
|
| 22 |
-
transactions: List["Transaction"] = Relationship(back_populates="payment_method")
|
| 23 |
-
|
| 24 |
class Category(SQLModel, table=True):
|
| 25 |
id: Optional[int] = Field(default=None, primary_key=True)
|
| 26 |
name: str
|
| 27 |
type: TransactionType
|
| 28 |
icon: str = "๐ฐ"
|
| 29 |
-
color: str = "#
|
| 30 |
budget: Optional[float] = Field(default=None)
|
| 31 |
|
|
|
|
| 32 |
transactions: List["Transaction"] = Relationship(back_populates="category")
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
class Transaction(SQLModel, table=True):
|
| 35 |
id: Optional[int] = Field(default=None, primary_key=True)
|
| 36 |
amount: float
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
date: datetime = Field(default_factory=datetime.utcnow)
|
| 40 |
type: TransactionType
|
| 41 |
|
| 42 |
# Installments
|
| 43 |
is_installment: bool = Field(default=False)
|
| 44 |
-
installment_number: Optional[int] =
|
| 45 |
-
total_installments: Optional[int] =
|
| 46 |
-
parent_transaction_id: Optional[int] = Field(default=None) # To group installments
|
| 47 |
|
| 48 |
user_id: int = Field(foreign_key="user.id")
|
| 49 |
-
category_id: int = Field(foreign_key="category.id")
|
|
|
|
| 50 |
payment_method_id: Optional[int] = Field(default=None, foreign_key="paymentmethod.id")
|
| 51 |
|
| 52 |
user: User = Relationship(back_populates="transactions")
|
| 53 |
category: Category = Relationship(back_populates="transactions")
|
|
|
|
| 54 |
payment_method: Optional[PaymentMethod] = Relationship(back_populates="transactions")
|
|
|
|
| 10 |
class User(SQLModel, table=True):
|
| 11 |
id: Optional[int] = Field(default=None, primary_key=True)
|
| 12 |
name: str
|
| 13 |
+
username: str = Field(unique=True, index=True)
|
| 14 |
+
hashed_password: str
|
| 15 |
icon: str = "๐ค"
|
| 16 |
|
| 17 |
transactions: List["Transaction"] = Relationship(back_populates="user")
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
class Category(SQLModel, table=True):
|
| 20 |
id: Optional[int] = Field(default=None, primary_key=True)
|
| 21 |
name: str
|
| 22 |
type: TransactionType
|
| 23 |
icon: str = "๐ฐ"
|
| 24 |
+
color: str = "#007AFF"
|
| 25 |
budget: Optional[float] = Field(default=None)
|
| 26 |
|
| 27 |
+
sub_categories: List["SubCategory"] = Relationship(back_populates="category")
|
| 28 |
transactions: List["Transaction"] = Relationship(back_populates="category")
|
| 29 |
|
| 30 |
+
class SubCategory(SQLModel, table=True):
|
| 31 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 32 |
+
name: str
|
| 33 |
+
icon: str = "๐"
|
| 34 |
+
budget: Optional[float] = Field(default=None)
|
| 35 |
+
|
| 36 |
+
category_id: int = Field(foreign_key="category.id", ondelete="CASCADE", index=True)
|
| 37 |
+
category: Category = Relationship(back_populates="sub_categories")
|
| 38 |
+
transactions: List["Transaction"] = Relationship(back_populates="sub_category")
|
| 39 |
+
|
| 40 |
+
class PaymentMethod(SQLModel, table=True):
|
| 41 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 42 |
+
name: str
|
| 43 |
+
icon: str = "๐ณ"
|
| 44 |
+
|
| 45 |
+
transactions: List["Transaction"] = Relationship(back_populates="payment_method")
|
| 46 |
+
|
| 47 |
+
class BudgetHistory(SQLModel, table=True):
|
| 48 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 49 |
+
category_id: Optional[int] = Field(default=None, foreign_key="category.id", ondelete="CASCADE", index=True)
|
| 50 |
+
sub_category_id: Optional[int] = Field(default=None, foreign_key="subcategory.id", ondelete="CASCADE", index=True)
|
| 51 |
+
budget: float
|
| 52 |
+
updated_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
| 53 |
+
|
| 54 |
class Transaction(SQLModel, table=True):
|
| 55 |
id: Optional[int] = Field(default=None, primary_key=True)
|
| 56 |
amount: float
|
| 57 |
+
notes: str # Renamed from description
|
| 58 |
+
payee: Optional[str] = Field(default=None) # ืืื ืฉืืื
|
| 59 |
+
date: datetime = Field(default_factory=datetime.utcnow, index=True)
|
| 60 |
type: TransactionType
|
| 61 |
|
| 62 |
# Installments
|
| 63 |
is_installment: bool = Field(default=False)
|
| 64 |
+
installment_number: Optional[int] = None
|
| 65 |
+
total_installments: Optional[int] = None
|
|
|
|
| 66 |
|
| 67 |
user_id: int = Field(foreign_key="user.id")
|
| 68 |
+
category_id: int = Field(foreign_key="category.id", ondelete="CASCADE", index=True)
|
| 69 |
+
sub_category_id: Optional[int] = Field(default=None, foreign_key="subcategory.id", ondelete="CASCADE")
|
| 70 |
payment_method_id: Optional[int] = Field(default=None, foreign_key="paymentmethod.id")
|
| 71 |
|
| 72 |
user: User = Relationship(back_populates="transactions")
|
| 73 |
category: Category = Relationship(back_populates="transactions")
|
| 74 |
+
sub_category: Optional[SubCategory] = Relationship(back_populates="transactions")
|
| 75 |
payment_method: Optional[PaymentMethod] = Relationship(back_populates="transactions")
|
requirements.txt
CHANGED
|
@@ -5,3 +5,6 @@ python-dotenv
|
|
| 5 |
alembic
|
| 6 |
pydantic-settings
|
| 7 |
psycopg2-binary
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
alembic
|
| 6 |
pydantic-settings
|
| 7 |
psycopg2-binary
|
| 8 |
+
passlib[bcrypt]
|
| 9 |
+
python-jose[cryptography]
|
| 10 |
+
python-multipart
|