-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1784 lines (1553 loc) · 67.9 KB
/
app.py
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 inspect
from flask import Flask, redirect, render_template, request, jsonify, session, redirect, url_for, make_response, jsonify, session, request
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from io import BytesIO
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from passlib.hash import scrypt
from config import Config
import datetime
from bson import ObjectId
import traceback
from decimal import Decimal, ROUND_HALF_UP
import random
import json
from bson import json_util
import time
from urllib.parse import urlparse, urlunsplit
from flask import jsonify
from flask_cors import CORS
import pymongo
from pymongo import MongoClient, WriteConcern, ReadPreference, errors
from pymongo.read_concern import ReadConcern
import math
from datetime import datetime, timedelta, timezone
import logging
logging.basicConfig(level=logging.INFO)
app = Flask(__name__)
app.config.from_object(Config)
CORS(app)
# Setup for original MongoDB
parsed_uri = urlparse(app.config['MONGO_URI'])
db_name = parsed_uri.path.lstrip('/').split('?')[0] or 'mongodbank'
# Reconstruct the URI with the correct database name
normalized_uri = urlunsplit((
parsed_uri.scheme,
parsed_uri.netloc,
f'/{db_name}',
parsed_uri.query,
parsed_uri.fragment
))
app.config['MONGO_URI'] = normalized_uri
mongo = PyMongo(app)
client = MongoClient(app.config['MONGO_URI'])
db = client[db_name]
# Setup for normalized MongoDB
normalized_parsed_uri = urlparse(app.config['MONGO_NORMALIZED_URI'])
normalized_db_name = normalized_parsed_uri.path.lstrip('/').split('?')[0] or 'mongodbank_normalized'
app.config['MONGO_NORMALIZED_URI'] = f"{normalized_parsed_uri.scheme}://{normalized_parsed_uri.netloc}/{normalized_db_name}"
normalized_client = MongoClient(app.config['MONGO_NORMALIZED_URI'])
normalized_db = normalized_client[normalized_db_name]
print(f"Connected to original database: {db_name}")
print(f"Connected to normalized database: {normalized_db_name}")
def round_to_penny(amount):
return Decimal(amount).quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
@app.route('/')
def index():
if 'user_id' in session:
return redirect(url_for('dashboard'))
return render_template('index.html')
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
user = mongo.db.customers.find_one({'username': username})
if user:
stored_password = user['password']
if scrypt.verify(password, stored_password):
session['user_id'] = str(user['_id'])
return redirect(url_for('dashboard'))
return 'Invalid username or password', 401
@app.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(url_for('index'))
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/dashboard')
def dashboard():
if 'user_id' not in session:
return redirect(url_for('index'))
user_id = session['user_id']
try:
# Calculate total balance
total_balance_cursor = db.accounts.aggregate([
{"$match": {"customer_id": ObjectId(user_id)}},
{"$group": {"_id": None, "total_balance": {"$sum": "$balance"}}}
])
total_balance_result = list(total_balance_cursor)
total_balance = total_balance_result[0]["total_balance"] if total_balance_result else 0
# Calculate recent transactions
recent_transaction_count = db.transactions.count_documents({
"customer_id": ObjectId(user_id),
"timestamp": {"$gte": datetime.now() - timedelta(days=7)}
})
# Calculate pending reviews
pending_review_count = db.transactions.count_documents({
"customer_id": ObjectId(user_id),
"review_status": {"$exists": False},
"fraud_flags": {"$exists": True, "$ne": []}
})
# Calculate alerts
alert_count = db.alerts.count_documents({"customer_id": ObjectId(user_id)})
user = db.customers.find_one({"_id": ObjectId(user_id)})
accounts = list(db.accounts.find({"customer_id": ObjectId(user_id)}))
return render_template('dashboard.html', user=user, accounts=accounts,
total_balance=total_balance,
recent_transaction_count=recent_transaction_count,
pending_review_count=pending_review_count,
alert_count=alert_count)
except Exception as e:
logging.error(f"Error fetching dashboard metrics: {e}")
return jsonify({'error': 'An error occurred while fetching dashboard metrics.'}), 500
@app.route('/api/accounts/<account_id>', methods=['GET'])
def get_account(account_id):
account = db.accounts.find_one({"_id": ObjectId(account_id)})
if account:
account['_id'] = str(account['_id'])
return jsonify({
'account_type': account.get('account_type'),
'balance': account.get('balance')
})
else:
return jsonify({'error': 'Account not found'}), 404
@app.route('/api/transaction/<transaction_id>', methods=['GET'])
def get_transaction(transaction_id):
transaction = db.transactions.find_one({"_id": ObjectId(transaction_id)})
if transaction:
transaction['_id'] = str(transaction['_id'])
return jsonify({
'account_type': transaction.get('type'),
'amount': transaction.get('amount'),
'from_account': transaction.get('from_account'),
'to_account': transaction.get('to_account'),
'amount': transaction.get('amount'),
'fraud': transaction.get('fraud_flags', [])
})
else:
return jsonify({'error': 'Account not found'}), 404
from bson import ObjectId
from bson.json_util import dumps
import json
@app.route('/api/transactions', methods=['GET'])
def get_transactions():
try:
if 'user_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
account_id = request.args.get('account_id')
page = int(request.args.get('page', 1))
limit = int(request.args.get('limit', 6))
skip = (page - 1) * limit
user_id = ObjectId(session['user_id'])
# If no account_id is provided, fetch transactions for all user's accounts
if not account_id:
user_accounts = list(mongo.db.accounts.find({'customer_id': user_id}))
account_ids = [account['_id'] for account in user_accounts]
query = {'account_id': {'$in': account_ids}}
else:
account_object_id = ObjectId(account_id)
query = {'account_id': account_object_id}
app.logger.info(f"Fetching transactions with query: {query}")
transactions = list(mongo.db.transactions.find(query)
.sort('timestamp', pymongo.DESCENDING)
.skip(skip)
.limit(limit))
app.logger.info(f"Found {len(transactions)} transactions")
serialized_transactions = []
for transaction in transactions:
serialized_transaction = {
'_id': str(transaction['_id']),
'account_id': str(transaction['account_id']),
'type': transaction['type'],
'amount': transaction['amount'],
'timestamp': transaction['timestamp'].isoformat() if isinstance(transaction['timestamp'], datetime) else transaction['timestamp'],
'fraud_flags': transaction.get('fraud_flags', [])
}
if 'from_account' in transaction:
serialized_transaction['from_account'] = str(transaction['from_account'])
from_account = mongo.db.accounts.find_one({"_id": ObjectId(transaction['from_account'])})
if from_account:
serialized_transaction['from_account_name'] = from_account['account_type']
if 'to_account' in transaction:
serialized_transaction['to_account'] = str(transaction['to_account'])
to_account = mongo.db.accounts.find_one({"_id": ObjectId(transaction['to_account'])})
if to_account:
serialized_transaction['to_account_name'] = to_account['account_type']
serialized_transactions.append(serialized_transaction)
total_transactions = mongo.db.transactions.count_documents(query)
total_pages = (total_transactions + limit - 1) // limit
response_data = {
'transactions': serialized_transactions,
'page': page,
'total_pages': total_pages
}
app.logger.info(f"Returning response: {response_data}")
return jsonify(response_data)
except Exception as e:
app.logger.error(f"Error in get_transactions: {str(e)}")
app.logger.error(traceback.format_exc())
return jsonify({'error': 'An error occurred while retrieving transactions'}), 500
@app.route('/api/transaction', methods=['POST'])
def create_transaction():
# Ensure the session is being accessed correctly
if 'user_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
data = request.json
account_id = data.get('account_id')
amount = data.get('amount')
fraud_check = data.get('fraud_check')
location = data.get('location')
account = db.accounts.find_one({'_id': ObjectId(account_id), 'customer_id': ObjectId(session['user_id'])})
if not account:
return jsonify({'error': 'Account not found'}), 404
amount = float(data['amount'])
if data['type'] == 'withdrawal' and account['balance'] < amount:
return jsonify({'error': 'Insufficient funds'}), 400
new_balance = account['balance'] + amount if data['type'] == 'deposit' else account['balance'] - amount
timestamp = datetime.now(timezone.utc) # Correctly getting the current UTC time
# Initialize fraud flags
fraud_flags = []
# Velocity Check
if fraud_check == 'velocity':
velocity_count = db.transactions.count_documents({
'account_id': ObjectId(account_id),
'timestamp': {'$gte': timestamp - timedelta(hours=1)}
})
if velocity_count > 10: # Example threshold
fraud_flags.append('velocity')
# Insert an alert for velocity check
alert = {
"customer_id": ObjectId(session['user_id']),
"account_id": ObjectId(account_id),
"alert_type": "velocity_check",
"message": f"Velocity check triggered: {velocity_count} transactions in the last hour.",
"timestamp": datetime.now(timezone.utc),
"resolved": False
}
db.alerts.insert_one(alert)
# Location Check
if fraud_check == 'location' and location:
previous_transaction = db.transactions.find_one(
{'account_id': ObjectId(account_id)},
sort=[('timestamp', -1)]
)
if previous_transaction and previous_transaction.get('location'):
prev_location = previous_transaction['location']
if calculate_distance(location, prev_location) > 1000: # Example threshold in km
fraud_flags.append('location')
# Insert an alert for location check
alert = {
"customer_id": ObjectId(session['user_id']),
"account_id": ObjectId(account_id),
"alert_type": "location_check",
"message": f"Location check triggered: Distance from last transaction is over 1000 km.",
"timestamp": datetime.now(timezone.utc),
"resolved": False
}
db.alerts.insert_one(alert)
# Create the transaction document
transaction = {
'account_id': ObjectId(account_id),
'amount': amount,
'type': data['type'],
'timestamp': timestamp.isoformat(),
'location': location,
'fraud_flags': fraud_flags,
}
db.transactions.insert_one(transaction)
db.accounts.update_one({'_id': ObjectId(account_id)}, {'$set': {'balance': new_balance}})
return jsonify({'success': True, 'new_balance': new_balance, 'fraud_flags': fraud_flags})
@app.route('/fraud_simulation_dashboard')
def fraud_simulation_dashboard():
if 'user_id' not in session:
return redirect(url_for('index'))
user_id = session['user_id']
accounts = list(mongo.db.accounts.find({'customer_id': ObjectId(user_id)}))
# Debugging
print("Accounts:", accounts) # Check what is being passed to the template
return render_template('fraud_simulation_dashboard.html', accounts=accounts)
@app.route('/get_code/<endpoint>', methods=['GET'])
def get_code(endpoint):
code_snippets = {
'login': {
'title': 'Login Route',
'code': inspect.getsource(login),
'description': 'This route handles user authentication. It checks the provided username and password against the stored values in the database and creates a session upon successful login.',
'docs_link': 'https://docs.mongodb.com/manual/reference/method/db.collection.findOne/' # Example link
},
'velocity_check': {
'title': 'Velocity Check Logic',
'code': '''
# Velocity Check Logic
velocity_count = db.transactions.count_documents({
'account_id': ObjectId(account_id),
'timestamp': {'$gte': timestamp - datetime.timedelta(hours=1)}
})
if velocity_count > 10: # Example threshold
fraud_flags.append('velocity')
'''
},
'location_check': {
'title': 'Location Check Logic',
'code': '''
# Location Check Logic
previous_transaction = db.transactions.find_one(
{'account_id': ObjectId(account_id)},
sort=[('timestamp', -1)]
)
if previous_transaction and location:
prev_location = previous_transaction.get('location')
if prev_location and calculate_distance(location, prev_location) > 1000:
fraud_flags.append('location')
'''
},
'get_transactions': {
'title': 'Get Transactions Route',
'code': inspect.getsource(get_transactions),
'description': 'This route retrieves the latest transactions for a specific account. It uses MongoDB’s `find` method to query transactions and sort them by timestamp.',
'docs_link': 'https://docs.mongodb.com/manual/reference/method/db.collection.find/' # Example link
},
'create_transaction': {
'title': 'Create Transaction Route',
'code': inspect.getsource(create_transaction),
'description': 'This route creates a new transaction and updates the account balance. It performs a deposit or withdrawal based on the request type and ensures atomicity using MongoDB’s ACID transaction capabilities.',
'docs_link': 'https://docs.mongodb.com/manual/core/transactions/' # Example link
},
'branch_locator': {
'title': 'Branch & ATM Locator Logic',
'code': inspect.getsource(get_branches), # assuming branch_locator is a defined function
'description': 'This code powers the branch and ATM locator functionality, retrieving nearby branches and ATMs based on user location.',
'docs_link': 'https://docs.mongodb.com/' # Replace with relevant documentation
},
'transfer': {
'title': 'Transfer Route',
'code': inspect.getsource(transfer),
'description': 'This route handles transferring funds between accounts. It ensures both the debit from the source account and the credit to the destination account are performed atomically using a MongoDB transaction.',
'docs_link': 'https://docs.mongodb.com/manual/core/transactions/' # Example link
},
'data_model': {
'title': 'Data Model',
'code': '''
# Customer Document
{
"_id": ObjectId("..."),
"username": "johndoe",
"password": "hashed_password",
"email": "[email protected]",
"created_at": ISODate("2023-08-28T12:00:00Z")
}
# Account Document
{
"_id": ObjectId("..."),
"customer_id": ObjectId("..."),
"account_type": "Checking",
"balance": 1000.00,
"created_at": ISODate("2023-08-28T12:00:00Z"),
"branch_id": ObjectId("...")
}
# Transaction Document
{
"_id": ObjectId("..."),
"account_id": ObjectId("..."),
"type": "deposit",
"amount": 500.00,
"timestamp": ISODate("2023-08-28T12:00:00Z"),
"from_account": ObjectId("..."), # Optional, for transfers
"to_account": ObjectId("..."), # Optional, for transfers
"fraud_flags": ["velocity", "location"] # Optional
}
# Branch Document
{
"_id": ObjectId("..."),
"name": "Downtown Branch",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "ST",
"zip_code": "12345",
"country": "USA"
},
"phone_number": "555-1234",
"email": "[email protected]",
"manager": "Jane Doe",
"services": ["Loans", "Deposits", "Wealth Management"],
"hours": {
"monday": {"open": "09:00", "close": "17:00"},
"tuesday": {"open": "09:00", "close": "17:00"},
# ... other days ...
},
"location": {
"type": "Point",
"coordinates": [-73.98, 40.73] # [longitude, latitude]
}
}
# ATM Document
{
"_id": ObjectId("..."),
"branch_id": ObjectId("..."),
"location": {
"type": "Point",
"coordinates": [-73.98, 40.73] # [longitude, latitude]
},
"address": {
"street": "456 Side St",
"city": "Anytown",
"state": "ST",
"zip_code": "12345",
"country": "USA"
},
"type": "Walk-up",
"features": ["Cash Withdrawal", "Deposit", "Check Cashing"],
"accessibility": true,
"status": "Operational"
}
# Alert Document
{
"_id": ObjectId("..."),
"customer_id": ObjectId("..."),
"account_id": ObjectId("..."),
"transaction_id": ObjectId("..."),
"type": "Potential Fraud",
"message": "Suspicious activity detected: velocity check triggered",
"timestamp": ISODate("2023-08-28T12:00:00Z"),
"resolved": false
}
''',
'description': 'This represents the comprehensive data model for the application, defining the structure of customer, account, transaction, branch, ATM, and alert documents.',
'docs_link': 'https://www.mongodb.com/docs/manual/data-modeling/'
},
'velocity_check': {
'title': 'Velocity Check Logic',
'code': '''
# Velocity Check Logic
velocity_count = db.transactions.count_documents({
'account_id': ObjectId(account_id),
'timestamp': {'$gte': timestamp - datetime.timedelta(hours=1)}
})
if velocity_count > 10: # Example threshold
fraud_flags.append('velocity')
''',
'description': 'This logic checks the number of transactions within the past hour. If the count exceeds a predefined threshold, the transaction is flagged as potentially fraudulent.',
'docs_link': 'https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/'
},
'location_check': {
'title': 'Location Check Logic',
'code': '''
# Location Check Logic
previous_transaction = db.transactions.find_one(
{'account_id': ObjectId(account_id)},
sort=[('timestamp', -1)]
)
if previous_transaction and location:
prev_location = previous_transaction.get('location')
if prev_location and calculate_distance(location, prev_location) > 1000: # Example threshold in km
fraud_flags.append('location')
''',
'description': 'This logic compares the current transaction location with the previous transaction location. If the distance exceeds a certain threshold, the transaction is flagged as potentially fraudulent.',
'docs_link': 'https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne/'
}
}
if endpoint in code_snippets:
return jsonify(code_snippets[endpoint])
else:
return jsonify({'title': 'Not Found', 'code': 'Code not available'}), 404
@app.route('/transfer', methods=['POST'])
def transfer():
source_account_id = request.json['source_account_id']
destination_account_id = request.json['destination_account_id']
amount = float(request.json['amount'])
simulate_failure = request.json.get('simulate_failure', False) # Get the simulate failure flag
logging.info(f"Starting transfer from {source_account_id} to {destination_account_id} amount: {amount}")
try:
with client.start_session() as session:
with session.start_transaction():
# Simulate a failure if the checkbox was checked
if simulate_failure:
raise Exception("Simulated failure for demonstration purposes")
# Step 1: Debit from source account
logging.info("Attempting to debit source account")
source_account = db.accounts.find_one_and_update(
{"_id": ObjectId(source_account_id), "balance": {"$gte": amount}},
{"$inc": {"balance": -amount}},
session=session,
return_document=True
)
if not source_account:
logging.error("Insufficient funds in source account")
raise errors.OperationFailure("Insufficient funds in source account")
# Step 2: Credit to destination account
logging.info("Attempting to credit destination account")
destination_account = db.accounts.find_one_and_update(
{"_id": ObjectId(destination_account_id)},
{"$inc": {"balance": amount}},
session=session,
return_document=True
)
if not destination_account:
logging.error("Destination account not found")
raise errors.OperationFailure("Destination account not found")
# Step 3: Record transaction in the source account
logging.info("Recording transaction in the source account")
source_transaction = {
"account_id": ObjectId(source_account_id),
"amount": -amount,
"type": "transfer_out",
"timestamp": datetime.now(timezone.utc).isoformat(),
"from_account": ObjectId(source_account_id),
"to_account": ObjectId(destination_account_id)
}
db.transactions.insert_one(source_transaction, session=session)
# Step 4: Record transaction in the destination account
logging.info("Recording transaction in the destination account")
destination_transaction = {
"account_id": ObjectId(destination_account_id),
"amount": amount,
"type": "transfer_in",
"timestamp": datetime.now(timezone.utc).isoformat(),
"from_account": ObjectId(source_account_id),
"to_account": ObjectId(destination_account_id)
}
db.transactions.insert_one(destination_transaction, session=session)
logging.info("Transfer successful")
return jsonify({"status": "Transfer successful"}), 200
except errors.OperationFailure as e:
logging.error(f"OperationFailure: {e}")
return jsonify({"error": str(e)}), 400
except Exception as e:
logging.error(f"General Exception: {e}")
return jsonify({"error": "An error occurred during the transaction"}), 500
def calculate_distance(location1, location2):
"""
Calculate the great-circle distance between two points
on the Earth's surface specified by their latitude and longitude.
Parameters:
location1 (dict): Dictionary containing 'latitude' and 'longitude' for the first location.
location2 (dict): Dictionary containing 'latitude' and 'longitude' for the second location.
Returns:
float: Distance between the two points in kilometers.
"""
# Convert latitude and longitude from degrees to radians
lat1, lon1 = math.radians(location1['latitude']), math.radians(location1['longitude'])
lat2, lon2 = math.radians(location2['latitude']), math.radians(location2['longitude'])
# Haversine formula
dlat = lat2 - lat1
dlon = lon2 - lon1
a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
# Radius of the Earth in kilometers (mean radius)
R = 6371.01
# Calculate the distance
distance = R * c
return distance
from bson import ObjectId
from bson.json_util import dumps
import json
from bson import ObjectId
from bson.json_util import dumps
import json
from datetime import datetime, timezone, timedelta
@app.route('/api/statement', methods=['GET'])
def generate_statement():
if 'user_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
account_id = request.args.get('account_id')
start_date = request.args.get('start_date')
end_date = request.args.get('end_date')
# Convert start and end dates to UTC timezone-aware datetimes
start_datetime = datetime.fromisoformat(f"{start_date}T00:00:00").replace(tzinfo=timezone.utc)
end_datetime = datetime.fromisoformat(f"{end_date}T23:59:59").replace(tzinfo=timezone.utc)
try:
account_object_id = ObjectId(account_id)
account = mongo.db.accounts.find_one({'_id': account_object_id, 'customer_id': ObjectId(session['user_id'])})
if not account:
logging.error(f"Account not found for account_id: {account_id}")
return jsonify({'error': 'Account not found'}), 404
logging.info(f"Fetching transactions for account_id: {account_id} from {start_datetime} to {end_datetime}")
# More flexible date query
query = {
'account_id': account_object_id,
'$or': [
{'timestamp': {'$gte': start_datetime, '$lte': end_datetime}},
{'timestamp': {'$gte': start_datetime.isoformat(), '$lte': end_datetime.isoformat()}},
]
}
transactions = list(mongo.db.transactions.find(query).sort('timestamp', pymongo.DESCENDING))
logging.info(f"Found {len(transactions)} transactions")
# Log a sample transaction if available
if transactions:
logging.info(f"Sample transaction: {transactions[0]}")
else:
logging.info("No transactions found. Checking for any transactions in the collection.")
sample_transaction = mongo.db.transactions.find_one()
if sample_transaction:
logging.info(f"Sample transaction from collection: {sample_transaction}")
else:
logging.info("No transactions found in the collection at all.")
# Prepare the statement data
statement = {
'account_type': account.get('account_type'),
'balance': account.get('balance'),
'transactions': transactions,
'start_date': start_date,
'end_date': end_date,
}
# Use json_util to handle MongoDB-specific types
json_statement = json.loads(dumps(statement))
# Further process the transactions if needed
for transaction in json_statement['transactions']:
if 'timestamp' in transaction:
if isinstance(transaction['timestamp'], dict) and '$date' in transaction['timestamp']:
transaction['timestamp'] = datetime.fromisoformat(transaction['timestamp']['$date']).isoformat()
elif isinstance(transaction['timestamp'], str):
# If it's already a string, we'll assume it's in ISO format
pass
else:
logging.warning(f"Unexpected timestamp format: {transaction['timestamp']}")
return jsonify(json_statement), 200
except Exception as e:
logging.error(f"Error generating statement: {e}")
return jsonify({'error': 'An error occurred while generating the statement'}), 500
@app.route('/api/generate_pdf_statement', methods=['GET'])
def generate_pdf_statement():
if 'user_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
account_id = request.args.get('account_id')
start_date = request.args.get('start_date')
end_date = request.args.get('end_date')
try:
account_object_id = ObjectId(account_id)
account = mongo.db.accounts.find_one({'_id': account_object_id, 'customer_id': ObjectId(session['user_id'])})
if not account:
return jsonify({'error': 'Account not found'}), 404
transactions = list(mongo.db.transactions.find({
'account_id': account_object_id,
'timestamp': {
'$gte': start_date,
'$lte': end_date
}
}).sort('timestamp', pymongo.DESCENDING))
# Create a PDF
buffer = BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=letter)
elements = []
# Add title
styles = getSampleStyleSheet()
elements.append(Paragraph(f"Account Statement", styles['Title']))
elements.append(Paragraph(f"Account Type: {account['account_type']}", styles['Normal']))
elements.append(Paragraph(f"Balance: ${account['balance']:.2f}", styles['Normal']))
elements.append(Paragraph(f"From: {start_date} To: {end_date}", styles['Normal']))
# Add transactions table
data = [['Date', 'Type', 'Amount']]
for transaction in transactions:
# Parse the timestamp string into a datetime object
timestamp = datetime.fromisoformat(transaction['timestamp'].replace('Z', '+00:00'))
data.append([
timestamp.strftime('%Y-%m-%d %H:%M:%S'),
transaction['type'],
f"${transaction['amount']:.2f}",
transaction.get('from_account_name', '-'),
transaction.get('to_account_name', '-')
])
table = Table(data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 14),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
('TEXTCOLOR', (0, 1), (-1, -1), colors.black),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
('FONTSIZE', (0, 1), (-1, -1), 12),
('TOPPADDING', (0, 1), (-1, -1), 6),
('BOTTOMPADDING', (0, 1), (-1, -1), 6),
('GRID', (0, 0), (-1, -1), 1, colors.black)
]))
elements.append(table)
# Generate PDF
doc.build(elements)
# Prepare response
pdf = buffer.getvalue()
buffer.close()
response = make_response(pdf)
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = f'attachment; filename=statement_{start_date}_to_{end_date}.pdf'
return response
except Exception as e:
app.logger.error(f"Error generating PDF statement: {str(e)}")
app.logger.error(traceback.format_exc()) # This will log the full stack trace
return jsonify({'error': 'An error occurred while generating the PDF statement'}), 500
@app.route('/api/review_transactions', methods=['GET'])
def get_review_transactions():
if 'user_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
transactions = list(mongo.db.transactions.find({
'fraud_flags': {'$exists': True, '$ne': []},
'reviewed': False
}))
for transaction in transactions:
transaction['_id'] = str(transaction['_id'])
transaction['account_id'] = str(transaction['account_id'])
transaction['timestamp'] = transaction['timestamp'].isoformat()
return jsonify(transactions), 200
@app.route('/api/review_transaction', methods=['POST'])
def review_transaction():
if 'user_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
data = request.json
transaction_id = data.get('transaction_id')
review_status = data.get('review_status') # "legitimate" or "fraudulent"
if not transaction_id or review_status not in ['legitimate', 'fraudulent']:
return jsonify({'error': 'Invalid input'}), 400
update_data = {
'reviewed': True,
'review_status': review_status
}
# If the transaction is reviewed as legitimate, clear the fraud flags
if review_status == 'legitimate':
update_data['fraud_flags'] = [] # Clear the fraud flags
mongo.db.transactions.update_one(
{'_id': ObjectId(transaction_id)},
{'$set': update_data}
)
return jsonify({'success': True}), 200
@app.route('/api/dashboard_metrics', methods=['GET'])
def get_dashboard_metrics():
try:
user_id = session.get('user_id')
if not user_id:
return jsonify({'error': 'Unauthorized'}), 401
# Fetch total balance
total_balance_cursor = db.accounts.aggregate([
{'$match': {'customer_id': ObjectId(user_id)}},
{'$group': {'_id': None, 'total_balance': {'$sum': '$balance'}}}
])
total_balance_result = list(total_balance_cursor)
total_balance = total_balance_result[0]["total_balance"] if total_balance_result else 0
# Calculate recent transactions
recent_transaction_count = db.transactions.count_documents({
"account_id": {'$in': [account['_id'] for account in db.accounts.find({'customer_id': ObjectId(user_id)})]},
"timestamp": {"$gte": datetime.now() - timedelta(days=7)}
})
# Calculate pending reviews
pending_review_count = db.transactions.count_documents({
"account_id": {'$in': [account['_id'] for account in db.accounts.find({'customer_id': ObjectId(user_id)})]},
"review_status": {"$exists": False},
"fraud_flags": {"$exists": True, "$ne": []}
})
# Calculate alerts
alert_count = db.alerts.count_documents({
"account_id": {'$in': [account['_id'] for account in db.accounts.find({'customer_id': ObjectId(user_id)})]}
})
return jsonify({
'total_balance': total_balance,
'recent_transaction_count': recent_transaction_count,
'pending_review_count': pending_review_count,
'alert_count': alert_count
}), 200
except Exception as e:
logging.error(f"Error fetching dashboard metrics: {e}")
return jsonify({'error': 'An error occurred'}), 500
def create_admin_user(username, password):
hashed_password = scrypt.hash(password)
admin_user = {
"username": username,
"password": hashed_password,
"is_admin": True
}
mongo.db.customers.insert_one(admin_user)
@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = mongo.db.customers.find_one({'username': username, 'is_admin': True})
if user and scrypt.verify(password, user['password']):
session['admin_id'] = str(user['_id'])
return redirect(url_for('admin_dashboard'))
return 'Invalid username or password', 401
return render_template('admin_login.html')
@app.route('/admin/logout')
def admin_logout():
session.pop('admin_id', None)
return redirect(url_for('admin_login'))
@app.route('/admin/dashboard')
def admin_dashboard():
if 'admin_id' not in session:
return redirect(url_for('admin_login'))
# Add admin dashboard logic here
return render_template('admin_dashboard.html')
def serialize_mongo_doc(doc):
"""Helper function to serialize MongoDB document"""
for key, value in doc.items():
if isinstance(value, ObjectId):
doc[key] = str(value)
elif isinstance(value, datetime):
doc[key] = value.isoformat()
return doc
@app.route('/admin/api/dashboard_metrics')
def admin_dashboard_metrics():
if 'admin_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
total_users = mongo.db.customers.count_documents({})
total_transactions = mongo.db.transactions.count_documents({})
total_accounts = mongo.db.accounts.count_documents({})
recent_transactions = list(mongo.db.transactions.find().sort('timestamp', -1).limit(5))
recent_transactions = [serialize_mongo_doc(transaction) for transaction in recent_transactions]
fraud_alerts = list(mongo.db.transactions.find({'fraud_flags': {'$exists': True, '$ne': []}}).sort('timestamp', -1).limit(5))
fraud_alerts = [serialize_mongo_doc(alert) for alert in fraud_alerts]
return jsonify({
'total_users': total_users,
'total_transactions': total_transactions,
'total_accounts': total_accounts,
'recent_transactions': recent_transactions,
'fraud_alerts': fraud_alerts
})
@app.route('/admin/api/transaction_volume')
def transaction_volume():
if 'admin_id' not in session:
return jsonify({'error': 'Unauthorized'}), 401
pipeline = [
{
'$addFields': {
'date': {
'$dateFromString': {
'dateString': '$timestamp',
'onError': '$timestamp' # If parsing fails, use the original value
}
}
}
},
{
'$group': {
'_id': {
'$dateToString': {
'format': '%Y-%m-%d',
'date': '$date'
}
},
'count': {'$sum': 1},
'total_amount': {'$sum': '$amount'}
}
},
{'$sort': {'_id': 1}},