-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
167 lines (119 loc) · 4.05 KB
/
database.py
File metadata and controls
167 lines (119 loc) · 4.05 KB
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
from sqlalchemy import create_engine, Column, Integer, String, Float, Date, UniqueConstraint, func
from sqlalchemy.orm import declarative_base, sessionmaker
import pandas as pd
engine = create_engine("sqlite:///expenses.db", echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Expense(Base):
__tablename__ = "expenses"
id = Column(Integer, primary_key=True)
date = Column(Date, nullable=False)
description = Column(String, nullable=False)
amount = Column(Float, nullable=False)
category = Column(String, nullable=False)
__table_args__ = (
UniqueConstraint("date", "description", "amount", name="unique_expense"),
)
Base.metadata.create_all(engine)
def insert_expenses(df: pd.DataFrame):
session = Session()
inserted = 0
skipped = 0
for _, row in df.iterrows():
try:
expense = Expense(
date=row["date"],
description=str(row["description"]),
amount=float(row["amount"]),
category=str(row["category"])
)
session.add(expense)
session.commit()
inserted += 1
except Exception:
session.rollback()
skipped += 1
session.close()
return inserted, skipped
def fetch_expenses_by_category(category=None):
session = Session()
query = session.query(Expense)
if category and category != "All":
query = query.filter(Expense.category == category)
results = query.all()
session.close()
return pd.DataFrame(
[(r.date, r.description, r.amount, r.category) for r in results],
columns=["date", "description", "amount", "category"]
)
def get_total_spent(category=None):
session = Session()
query = session.query(func.sum(Expense.amount))
if category and category != "All":
query = query.filter(Expense.category == category)
total = query.scalar()
session.close()
return total or 0
def get_category_summary(category=None):
session = Session()
query = session.query(
Expense.category,
func.sum(Expense.amount).label("total")
)
if category and category != "All":
query = query.filter(Expense.category == category)
results = query.group_by(Expense.category).all()
session.close()
return pd.DataFrame(results, columns=["category", "total"])
def get_monthly_summary(category=None):
session = Session()
query = session.query(
func.strftime("%Y-%m", Expense.date).label("month"),
func.sum(Expense.amount).label("total")
)
if category and category != "All":
query = query.filter(Expense.category == category)
results = query.group_by("month").all()
session.close()
return pd.DataFrame(results, columns=["month", "total"])
# Budget Model
class Budget(Base):
__tablename__ = "budgets"
id = Column(Integer, primary_key=True)
month = Column(String, nullable=False)
category = Column(String, nullable=False) # "Total" or category name
amount = Column(Float, nullable=False)
__table_args__ = (
UniqueConstraint("month", "category", name="unique_budget"),
)
Base.metadata.create_all(engine)
# Budget Functions
def set_budget(month, category, amount):
session = Session()
try:
budget = Budget(
month=month,
category=category,
amount=amount
)
session.add(budget)
session.commit()
except:
session.rollback()
session.query(Budget).filter_by(
month=month,
category=category
).update({"amount": amount})
session.commit()
session.close()
def get_budget(month, category=None):
session = Session()
query = session.query(Budget).filter(Budget.month == month)
if category:
query = query.filter(Budget.category == category)
results = query.all()
session.close()
return pd.DataFrame(
[(r.month, r.category, r.amount) for r in results],
columns=["month", "category", "amount"]
)