-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2064 lines (1755 loc) · 75.7 KB
/
Copy pathapp.py
File metadata and controls
2064 lines (1755 loc) · 75.7 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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import bcrypt
from datetime import datetime, timedelta
import json
from functools import wraps, lru_cache
import uuid
import calendar
import resend
from werkzeug.security import generate_password_hash, check_password_hash
import re
import threading
from queue import Queue
import time
import hashlib
import logging
from dotenv import load_dotenv
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from pymongo import MongoClient, ASCENDING, DESCENDING
from pymongo.errors import ConnectionFailure, OperationFailure
from pymongo.server_api import ServerApi
from bson.objectid import ObjectId
import secrets
import shutil
from tenacity import retry, stop_after_attempt, wait_exponential
# Load environment variables
load_dotenv()
# Configure logging
def setup_logging():
# Create a console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
console_handler.setLevel(logging.INFO)
# Set up app logger
app_logger = logging.getLogger('app')
app_logger.setLevel(logging.INFO)
app_logger.addHandler(console_handler)
# Set up email logger
email_logger = logging.getLogger('email')
email_logger.setLevel(logging.INFO)
email_logger.addHandler(console_handler)
return app_logger, email_logger
# Initialize loggers
app_logger, email_logger = setup_logging()
# Initialize Flask app
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', secrets.token_hex(32))
# Configure session
app.config['SESSION_COOKIE_SECURE'] = os.environ.get('FLASK_ENV') == 'production'
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
# Setup rate limiting
limiter = Limiter(
key_func=get_remote_address,
app=app,
default_limits=["200 per day", "50 per hour"],
storage_uri="memory://"
)
# MongoDB configuration with connection pooling and retry logic
MONGO_URI = os.environ.get('MONGO_URI', 'mongodb://localhost:27017/')
DB_NAME = os.environ.get('DB_NAME', 'finance_manager')
# MongoDB connection settings
MONGO_SETTINGS = {
'maxPoolSize': 50, # Maximum number of connections in the pool
'minPoolSize': 10, # Minimum number of connections in the pool
'maxIdleTimeMS': 30000, # Maximum time a connection can remain idle
'waitQueueTimeoutMS': 5000, # How long to wait for a connection from the pool
'serverSelectionTimeoutMS': 5000, # How long to wait for server selection
'connectTimeoutMS': 5000, # How long to wait for initial connection
'socketTimeoutMS': 30000, # How long to wait for operations
'retryWrites': True, # Enable automatic retry of write operations
'retryReads': True, # Enable automatic retry of read operations
'w': 'majority', # Write concern for better durability
'readPreference': 'secondaryPreferred' # Read from secondary nodes when possible
}
# Initialize MongoDB connection with retry logic
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def get_mongodb_client():
try:
client = MongoClient(MONGO_URI, **MONGO_SETTINGS)
# Test connection
client.server_info()
app_logger.info("Connected to MongoDB successfully")
return client
except ConnectionFailure as e:
app_logger.error(f"Failed to connect to MongoDB: {e}")
raise
try:
client = get_mongodb_client()
db = client[DB_NAME]
except Exception as e:
app_logger.error(f"Failed to initialize MongoDB connection: {e}")
raise
# Database collections
users = db['users']
transactions = db['transactions']
budgets = db['budgets']
settings = db['settings']
email_logs = db['email_logs']
# Create optimized indexes for better query performance
def create_indexes():
try:
# Drop existing indexes first to avoid conflicts
users.drop_indexes()
transactions.drop_indexes()
budgets.drop_indexes()
email_logs.drop_indexes()
# Users collection indexes
users.create_index([("email", ASCENDING)], unique=True)
users.create_index([("created_at", DESCENDING)])
users.create_index([("last_login", DESCENDING)])
# Transactions collection indexes
transactions.create_index([
("user_id", ASCENDING),
("date", DESCENDING)
])
transactions.create_index([
("user_id", ASCENDING),
("type", ASCENDING),
("date", DESCENDING)
])
transactions.create_index([
("user_id", ASCENDING),
("category", ASCENDING),
("date", DESCENDING)
])
transactions.create_index([
("user_id", ASCENDING),
("tags", ASCENDING)
])
transactions.create_index([
("user_id", ASCENDING),
("payment_method", ASCENDING)
])
# Budgets collection indexes
budgets.create_index([
("user_id", ASCENDING),
("category", ASCENDING)
], unique=True)
# Email logs collection indexes
email_logs.create_index([("timestamp", DESCENDING)])
email_logs.create_index([("to", ASCENDING), ("timestamp", DESCENDING)])
email_logs.create_index([("status", ASCENDING)])
app_logger.info("Database indexes created successfully")
except OperationFailure as e:
app_logger.error(f"Error creating indexes: {e}")
# Don't raise the error, just log it
# This allows the application to continue running even if index creation fails
return False
except Exception as e:
app_logger.error(f"Unexpected error creating indexes: {e}")
return False
return True
# Create indexes
create_indexes()
# Helper function for MongoDB operations with retry logic
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def execute_mongo_operation(operation, *args, **kwargs):
try:
return operation(*args, **kwargs)
except ConnectionFailure as e:
app_logger.error(f"MongoDB connection error: {e}")
raise
except OperationFailure as e:
app_logger.error(f"MongoDB operation error: {e}")
raise
# Example of using the helper function for a query
def get_user_by_email(email):
return execute_mongo_operation(
users.find_one,
{'email': email}
)
# Example of using the helper function for an insert
def insert_transaction(transaction_data):
return execute_mongo_operation(
transactions.insert_one,
transaction_data
)
# Example of using the helper function for an update
def update_user_settings(user_id, settings):
return execute_mongo_operation(
users.update_one,
{'_id': ObjectId(user_id)},
{'$set': {'settings': settings}}
)
# Example of using the helper function for aggregation
def get_monthly_stats(user_id, start_date, end_date):
return execute_mongo_operation(
transactions.aggregate,
[
{'$match': {
'user_id': user_id,
'date': {'$gte': start_date, '$lt': end_date}
}},
{'$group': {
'_id': '$type',
'total': {'$sum': '$amount'}
}}
]
)
# Resend email configuration
RESEND_API_KEY = os.environ.get('RESEND_API_KEY')
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'Finance Manager <no-reply@finance-manager.com>')
resend.api_key = RESEND_API_KEY
# Email queue for asynchronous processing
email_queue = Queue(maxsize=1000)
# Background worker for processing emails
def email_worker():
while True:
try:
# Get email task from queue
task = email_queue.get()
if task is None: # Shutdown signal
break
to_email, subject, html_content, from_email = task
# Process the email directly
_send_email_direct(to_email, subject, html_content, from_email)
# Mark task as done
email_queue.task_done()
except Exception as e:
error_msg = str(e)
email_logger.error(f"Error processing email: {error_msg}")
# Don't mark as done if there was an error to prevent queue from emptying
time.sleep(1) # Prevent CPU spinning on repeated errors
# Start email worker threads
def start_email_workers(num_workers=2):
workers = []
for _ in range(num_workers):
t = threading.Thread(target=email_worker, daemon=True)
t.start()
workers.append(t)
return workers
# Direct email sending function (without queuing)
def _send_email_direct(to_email, subject, html_content, from_email=DEFAULT_FROM_EMAIL):
try:
params = {
"from": from_email,
"to": to_email,
"subject": subject,
"html": html_content,
}
response = resend.Emails.send(params)
# Log the email
email_log = {
'to': to_email,
'subject': subject,
'status': 'success' if response.get('id') else 'failed',
'response': response,
'timestamp': datetime.now()
}
email_logs.insert_one(email_log)
email_logger.info(f"Email sent to {to_email}: {subject} (ID: {response.get('id')})")
if response.get('id'):
return True, response.get('id')
else:
email_logger.warning(f"Email sending failed without error: {response}")
return False, "Failed to send email: No ID returned from API"
except Exception as e:
# Log the error
error_msg = str(e)
email_log = {
'to': to_email,
'subject': subject,
'status': 'error',
'error': error_msg,
'timestamp': datetime.now()
}
email_logs.insert_one(email_log)
email_logger.error(f"Email error to {to_email}: {error_msg}")
return False, error_msg
# Enhanced email function with queuing for high load
def send_email(to_email, subject, html_content, from_email=DEFAULT_FROM_EMAIL, queue=True):
if not RESEND_API_KEY:
email_logger.warning("Email sending disabled - RESEND_API_KEY not configured")
return False, "Email sending is disabled (API key not configured)"
if queue:
try:
# Add to queue for background processing
email_queue.put((to_email, subject, html_content, from_email), block=False)
return True, "Email queued for delivery"
except Exception as e:
error_msg = str(e)
email_logger.error(f"Error queueing email: {error_msg}")
# Fall back to direct sending if queue is full
return _send_email_direct(to_email, subject, html_content, from_email)
else:
# Direct sending for cases where immediate confirmation is needed
return _send_email_direct(to_email, subject, html_content, from_email)
# Currency symbols mapping
CURRENCY_SYMBOLS = {
'USD': '$',
'EUR': '€',
'GBP': '£',
'JPY': '¥',
'CAD': 'C$',
'AUD': 'A$',
'INR': '₹'
}
# Email notification types
EMAIL_NOTIFICATION_TYPES = {
'weekly_summary': 'Weekly Summary',
'monthly_report': 'Monthly Report',
'budget_alerts': 'Budget Alerts',
'transaction_confirmations': 'Transaction Confirmations',
'security_alerts': 'Security Alerts'
}
# Context processor for current datetime
@app.context_processor
def inject_now():
return {'now': datetime.utcnow()}
# Login required decorator
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
# Admin required decorator
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session or not is_admin(session['user_id']):
flash('Access denied: Admin privileges required', 'danger')
return redirect(url_for('dashboard'))
return f(*args, **kwargs)
return decorated_function
# Check if user is admin
def is_admin(user_id):
user = users.find_one({'_id': ObjectId(user_id)})
return user and user.get('is_admin', False)
# Simple in-memory caching decorator with time-to-live
def cached(ttl_seconds=300):
def decorator(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
# Create a cache key from the function arguments
key_parts = [func.__name__]
key_parts.extend([str(arg) for arg in args])
key_parts.extend([f"{k}:{v}" for k, v in sorted(kwargs.items())])
cache_key = hashlib.md5(":".join(key_parts).encode()).hexdigest()
# Check cache
now = time.time()
if cache_key in cache:
result, timestamp = cache[cache_key]
if now - timestamp < ttl_seconds:
return result
# Generate fresh result
result = func(*args, **kwargs)
cache[cache_key] = (result, now)
# Clean old cache entries if cache is getting large
if len(cache) > 1000:
old_keys = [k for k, (_, ts) in cache.items() if now - ts > ttl_seconds]
for k in old_keys:
del cache[k]
return result
# Store the cache dictionary on the wrapper for access by cache invalidation
wrapper.cache = cache
return wrapper
return decorator
# Cached version of get_user_settings
@cached(ttl_seconds=30)
def get_user_settings(user_id=None):
"""Get user settings with caching to reduce database load"""
if not user_id and 'user_id' in session:
user_id = session['user_id']
try:
user = users.find_one({'_id': ObjectId(user_id)})
if user and 'settings' in user:
settings = user['settings']
else:
# Default settings if none are found
settings = {
'currency': 'USD',
'date_format': '%Y-%m-%d',
'theme': 'light',
'default_categories': {
'income': ['Salary', 'Freelance', 'Gifts', 'Investments', 'Other'],
'expense': ['Food', 'Housing', 'Transportation', 'Utilities', 'Entertainment', 'Healthcare', 'Education', 'Shopping', 'Personal', 'Other']
},
'email_notifications': {
'weekly_summary': True,
'budget_alerts': True,
'security_alerts': True,
'monthly_report': False,
'transaction_notifications': False
}
}
if 'currency_symbols' not in settings:
settings['currency_symbols'] = CURRENCY_SYMBOLS
return settings
except Exception as e:
app_logger.error(f"Error fetching user settings: {e}")
# Return default settings in case of error
return {
'currency': 'USD',
'date_format': '%Y-%m-%d',
'theme': 'light',
'default_categories': {
'income': ['Salary', 'Other'],
'expense': ['Food', 'Housing', 'Other']
},
'email_notifications': {
'security_alerts': True
},
'currency_symbols': CURRENCY_SYMBOLS
}
# Get currency symbol based on user's settings
def get_currency_symbol(user_id=None):
settings = get_user_settings(user_id)
if settings and 'currency' in settings:
return CURRENCY_SYMBOLS.get(settings['currency'], '$')
return '$'
# Template context processor to inject user settings
@app.context_processor
def inject_user_settings():
if 'user_id' in session:
try:
settings = get_user_settings()
user = users.find_one({'_id': ObjectId(session['user_id'])})
currency = settings.get('currency', 'USD')
currency_symbol = settings.get('currency_symbols', {}).get(currency, '$')
# Email notification types for the settings page
email_notification_types = {
'weekly_summary': 'Weekly Financial Summary',
'budget_alerts': 'Budget Threshold Alerts',
'monthly_report': 'Monthly Financial Report',
'security_alerts': 'Account Security Alerts',
'transaction_notifications': 'Large Transaction Notifications'
}
return {
'settings': settings,
'user': user,
'currency_symbol': currency_symbol,
'email_notification_types': email_notification_types,
'is_admin': is_admin(session['user_id']) if user else False,
'abs': abs # Make abs function available in templates
}
except Exception as e:
app_logger.error(f"Error in inject_user_settings: {e}")
return {'settings': {}, 'currency_symbol': '$', 'email_notification_types': {}, 'abs': abs}
return {'settings': {}, 'currency_symbol': '$', 'email_notification_types': {}, 'abs': abs, 'is_admin': False}
# Handle 404 errors
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
# Handle 500 errors
@app.errorhandler(500)
def server_error(e):
app_logger.error(f"Server error: {e}")
return render_template('500.html'), 500
@app.route('/')
def index():
if 'user_id' in session:
return redirect(url_for('dashboard'))
return render_template('index.html')
@app.route('/register', methods=['GET', 'POST'])
@limiter.limit("10/hour")
def register():
if request.method == 'POST':
try:
email = request.form['email']
password = request.form['password']
# Validate input
if not email or not password:
flash('Email and password are required')
return redirect(url_for('register'))
if len(password) < 8:
flash('Password must be at least 8 characters long')
return redirect(url_for('register'))
# Check if user already exists
if users.find_one({'email': email}):
flash('Email already registered')
return redirect(url_for('register'))
# Hash password
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
# Insert user
user_id = users.insert_one({
'email': email,
'password': hashed_password,
'created_at': datetime.utcnow(),
'settings': {
'currency': 'USD',
'date_format': '%Y-%m-%d',
'theme': 'light',
'default_categories': {
'income': ['Salary', 'Freelance', 'Gifts', 'Investments', 'Other'],
'expense': ['Food', 'Housing', 'Transportation', 'Utilities', 'Entertainment', 'Healthcare', 'Education', 'Shopping', 'Personal', 'Other']
},
'email_notifications': {
'weekly_summary': True,
'budget_alerts': True,
'security_alerts': True,
'monthly_report': False,
'transaction_notifications': False
}
}
}).inserted_id
session['user_id'] = str(user_id)
app_logger.info(f"New user registered: {email}")
# Send welcome email
if RESEND_API_KEY:
html_content = f"""
<html>
<head>
<style>
body {{ font-family: 'Helvetica', 'Arial', sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px; }}
h1, h2 {{ color: #3d5c9f; }}
.container {{ border: 1px solid #ddd; border-radius: 8px; padding: 20px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }}
.header {{ background-color: #3d5c9f; color: white; padding: 20px; border-radius: 8px 8px 0 0; margin: -20px -20px 20px; text-align: center; }}
.footer {{ background-color: #f8f9fa; padding: 15px; border-radius: 0 0 8px 8px; margin: 20px -20px -20px; text-align: center; color: #666; font-size: 0.9em; }}
.btn {{ display: inline-block; background-color: #3d5c9f; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px; margin-top: 15px; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1 style="margin: 0; padding: 0;">Finance Manager</h1>
</div>
<h2>Welcome to Finance Manager!</h2>
<p>Hi {email},</p>
<p>Thank you for registering with Finance Manager. We're excited to help you manage your finances effectively.</p>
<p>Here are some things you can do to get started:</p>
<ul>
<li>Add your income and expenses</li>
<li>Set up budgets for different categories</li>
<li>Review your financial reports</li>
<li>Customize your settings</li>
</ul>
<p>If you have any questions, please don't hesitate to contact us.</p>
<div class="footer">
<p>This is an automated message from Finance Manager. Please do not reply to this email.</p>
<p>© {datetime.now().year} Finance Manager. All rights reserved.</p>
</div>
</div>
</body>
</html>
"""
send_email(
to_email=email,
subject="Welcome to Finance Manager",
html_content=html_content
)
return redirect(url_for('dashboard'))
except Exception as e:
app_logger.error(f"Registration error: {e}")
flash('An error occurred during registration. Please try again.')
return redirect(url_for('register'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
@limiter.limit("20/hour")
def login():
if request.method == 'POST':
try:
email = request.form['email']
password = request.form['password']
user = users.find_one({'email': email})
if user and bcrypt.checkpw(password.encode('utf-8'), user['password']):
session['user_id'] = str(user['_id'])
session.permanent = True
# Update last login timestamp
users.update_one(
{'_id': user['_id']},
{'$set': {'last_login': datetime.utcnow()}}
)
app_logger.info(f"User logged in: {email}")
return redirect(url_for('dashboard'))
else:
app_logger.warning(f"Failed login attempt for: {email}")
flash('Invalid credentials')
except Exception as e:
app_logger.error(f"Login error: {e}")
flash('An error occurred during login. Please try again.')
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
@app.route('/dashboard')
@login_required
def dashboard():
# Get user settings
user_settings = get_user_settings()
# Calculate timeframes
today = datetime.now().date()
current_month_start = datetime(today.year, today.month, 1)
# Calculate total income, expenses, and balance
month_income = transactions.aggregate([
{'$match': {
'user_id': session['user_id'],
'type': 'income',
'date': {'$gte': current_month_start}
}},
{'$group': {'_id': None, 'total': {'$sum': '$amount'}}}
])
income = next(month_income, {}).get('total', 0)
month_expense = transactions.aggregate([
{'$match': {
'user_id': session['user_id'],
'type': 'expense',
'date': {'$gte': current_month_start}
}},
{'$group': {'_id': None, 'total': {'$sum': '$amount'}}}
])
expense = next(month_expense, {}).get('total', 0)
balance = income - expense
# Get recent transactions
recent_transactions = list(transactions.find(
{'user_id': session['user_id']}
).sort('date', -1).limit(5))
# Prepare data for chart
chart_data = {'labels': [], 'income': [], 'expense': []}
months = []
# Get data for the last 6 months
for i in range(5, -1, -1):
month_date = datetime.now().replace(day=1) - timedelta(days=i*30)
month_start = datetime(month_date.year, month_date.month, 1)
month_end = datetime(month_date.year, month_date.month + 1, 1) if month_date.month < 12 else datetime(month_date.year + 1, 1, 1)
month_income = transactions.aggregate([
{'$match': {
'user_id': session['user_id'],
'type': 'income',
'date': {'$gte': month_start, '$lt': month_end}
}},
{'$group': {'_id': None, 'total': {'$sum': '$amount'}}}
])
month_income_total = next(month_income, {}).get('total', 0)
month_expense = transactions.aggregate([
{'$match': {
'user_id': session['user_id'],
'type': 'expense',
'date': {'$gte': month_start, '$lt': month_end}
}},
{'$group': {'_id': None, 'total': {'$sum': '$amount'}}}
])
month_expense_total = next(month_expense, {}).get('total', 0)
chart_data['labels'].append(month_start.strftime('%b %Y'))
chart_data['income'].append(month_income_total)
chart_data['expense'].append(month_expense_total)
# Get budgets for dashboard
user_budgets = list(budgets.find({'user_id': session['user_id']}))
# Calculate spending for each budget
for budget in user_budgets:
category_spending = transactions.aggregate([
{'$match': {
'user_id': session['user_id'],
'category': budget['category'],
'type': 'expense',
'date': {'$gte': current_month_start}
}},
{'$group': {'_id': None, 'total': {'$sum': '$amount'}}}
])
spent = next(category_spending, {}).get('total', 0)
budget['spent'] = spent
budget['remaining'] = budget['amount'] - spent
budget['progress'] = min(100, int((spent / budget['amount']) * 100)) if budget['amount'] > 0 else 100
# Format dates according to user settings
date_format = user_settings.get('date_format', '%Y-%m-%d')
for transaction in recent_transactions:
if 'date' in transaction:
transaction['formatted_date'] = transaction['date'].strftime(date_format)
return render_template('dashboard.html',
income=income,
expense=expense,
balance=balance,
transactions=recent_transactions,
chart_data=chart_data,
chart_data_json=json.dumps(chart_data),
budgets=user_budgets[:4],
user_settings=user_settings)
@app.route('/transactions')
@login_required
def view_transactions():
page = int(request.args.get('page', 1))
limit = 20
skip = (page - 1) * limit
# Get user settings
user_settings = get_user_settings()
date_format = user_settings.get('date_format', '%Y-%m-%d')
# Get transactions with pagination
user_transactions = list(transactions.find(
{'user_id': session['user_id']}
).sort('date', -1).skip(skip).limit(limit))
# Format dates according to user settings
for transaction in user_transactions:
if 'date' in transaction:
transaction['formatted_date'] = transaction['date'].strftime(date_format)
# Get total count for pagination
total = transactions.count_documents({'user_id': session['user_id']})
return render_template('transactions.html',
transactions=user_transactions,
total=total,
page=page,
pages=(total // limit) + (1 if total % limit > 0 else 0))
@app.route('/transactions/add', methods=['GET', 'POST'])
@login_required
def add_transaction():
user_settings = get_user_settings()
if request.method == 'POST':
amount = float(request.form['amount'])
description = request.form['description']
category = request.form['category']
type_ = request.form['type']
date = datetime.strptime(request.form['date'], '%Y-%m-%d')
tags = request.form.get('tags', '').split(',') if request.form.get('tags') else []
tags = [tag.strip() for tag in tags if tag.strip()]
transaction_data = {
'user_id': session['user_id'],
'amount': amount,
'description': description,
'category': category,
'type': type_,
'date': date,
'tags': tags,
'created_at': datetime.utcnow()
}
# Add payment method if provided
if 'payment_method' in request.form and request.form['payment_method']:
transaction_data['payment_method'] = request.form['payment_method']
# Add notes if provided
if 'notes' in request.form and request.form['notes']:
transaction_data['notes'] = request.form['notes']
transactions.insert_one(transaction_data)
flash('Transaction added successfully')
return redirect(url_for('view_transactions'))
# Get user's categories from settings
income_categories = user_settings['default_categories']['income']
expense_categories = user_settings['default_categories']['expense']
return render_template('add_transaction.html',
income_categories=income_categories,
expense_categories=expense_categories,
income_categories_json=json.dumps(income_categories),
expense_categories_json=json.dumps(expense_categories))
@app.route('/transactions/edit/<transaction_id>', methods=['GET', 'POST'])
@login_required
def edit_transaction(transaction_id):
user_settings = get_user_settings()
transaction = transactions.find_one({
'_id': ObjectId(transaction_id),
'user_id': session['user_id']
})
if not transaction:
flash('Transaction not found')
return redirect(url_for('view_transactions'))
if request.method == 'POST':
amount = float(request.form['amount'])
description = request.form['description']
category = request.form['category']
type_ = request.form['type']
date = datetime.strptime(request.form['date'], '%Y-%m-%d')
tags = request.form.get('tags', '').split(',') if request.form.get('tags') else []
tags = [tag.strip() for tag in tags if tag.strip()]
update_data = {
'amount': amount,
'description': description,
'category': category,
'type': type_,
'date': date,
'tags': tags,
'updated_at': datetime.utcnow()
}
# Add payment method if provided
if 'payment_method' in request.form and request.form['payment_method']:
update_data['payment_method'] = request.form['payment_method']
# Add notes if provided
if 'notes' in request.form and request.form['notes']:
update_data['notes'] = request.form['notes']
transactions.update_one(
{'_id': ObjectId(transaction_id)},
{'$set': update_data}
)
flash('Transaction updated successfully')
return redirect(url_for('view_transactions'))
# Get user's categories from settings
income_categories = user_settings['default_categories']['income']
expense_categories = user_settings['default_categories']['expense']
# Prepare tags string
tags_string = ', '.join(transaction.get('tags', []))
return render_template('edit_transaction.html',
transaction=transaction,
income_categories=income_categories,
expense_categories=expense_categories,
income_categories_json=json.dumps(income_categories),
expense_categories_json=json.dumps(expense_categories),
tags_string=tags_string)
@app.route('/transactions/delete/<transaction_id>', methods=['POST'])
@login_required
def delete_transaction(transaction_id):
result = transactions.delete_one({
'_id': ObjectId(transaction_id),
'user_id': session['user_id']
})
if result.deleted_count:
flash('Transaction deleted successfully')
else:
flash('Failed to delete transaction')
return redirect(url_for('view_transactions'))
@app.route('/api/transactions', methods=['GET'])
@login_required
def api_transactions():
start_date = request.args.get('start_date')
end_date = request.args.get('end_date')
category = request.args.get('category')
type_ = request.args.get('type')
query = {'user_id': session['user_id']}
if start_date and end_date:
start = datetime.strptime(start_date, '%Y-%m-%d')
end = datetime.strptime(end_date, '%Y-%m-%d')
query['date'] = {'$gte': start, '$lte': end}
if category:
query['category'] = category
if type_:
query['type'] = type_
results = list(transactions.find(query).sort('date', -1))
# Convert ObjectId to string for JSON serialization
for r in results:
r['_id'] = str(r['_id'])
r['date'] = r['date'].strftime('%Y-%m-%d')
return jsonify(results)
@app.route('/reports')
@login_required
def reports():
# Get categories for filtering
categories = transactions.distinct('category', {'user_id': session['user_id']})
return render_template('reports.html', categories=categories)
@app.route('/api/reports/category', methods=['GET'])
@login_required
def category_report():
# Aggregate spending by category
results = transactions.aggregate([
{'$match': {'user_id': session['user_id']}},
{'$group': {
'_id': '$category',
'total': {'$sum': '$amount'},
'count': {'$sum': 1}
}},
{'$sort': {'total': -1}}
])
report_data = list(results)
return jsonify(report_data)
@app.route('/api/reports/monthly', methods=['GET'])
@login_required
def monthly_report():
year = int(request.args.get('year', datetime.utcnow().year))
# Aggregate monthly income and expenses
results = transactions.aggregate([
{'$match': {