-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3916 lines (3281 loc) · 158 KB
/
app.py
File metadata and controls
3916 lines (3281 loc) · 158 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 logging
import stripe
from datetime import datetime, timedelta
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, session, g
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from flask_wtf.csrf import CSRFProtect, generate_csrf, validate_csrf
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Optional
# Create the app
app = Flask(__name__)
app.secret_key = os.environ.get("SESSION_SECRET") or "development_key"
# Configure logging
logging.basicConfig(level=logging.DEBUG)
# Get database URL from environment or use SQLite as fallback
database_url = os.environ.get("DATABASE_URL")
if database_url and database_url.startswith("postgresql://"):
# For PostgreSQL
app.config['SQLALCHEMY_DATABASE_URI'] = database_url
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
"pool_pre_ping": True,
"pool_recycle": 300,
"pool_timeout": 900,
"pool_size": 10,
"max_overflow": 5,
}
app.logger.info("Using PostgreSQL database")
else:
# Fallback to SQLite
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///tradeline.db"
app.logger.info("Using SQLite database")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['WTF_CSRF_ENABLED'] = True
# Add min() function to Jinja environment
app.jinja_env.globals.update(min=min)
# Initialize Stripe with the secret key
stripe.api_key = os.environ.get('STRIPE_SECRET_KEY')
# Import database object
from db import db
# Configure SQLAlchemy
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
"pool_recycle": 300,
"pool_pre_ping": True,
}
# Initialize the db with the app
db.init_app(app)
# Import models from models_copy.py (avoiding module import issues)
from models_copy import User, CreditProfile, Tradeline, TradelinePurchase, AIAgent, TradelinePerformance
from models_copy import AIAgentAllocation, Transaction, Repayment, PromoCode, DefiLoan, DefiRepayment
# Import API models separately
try:
import models.api
except ImportError as e:
app.logger.warning(f"Could not import API models: {e}")
# Import e-commerce models - will be created when we run create_test_ecommerce.py
try:
from create_test_ecommerce import ProductCategory, Product, ProductPurchase
except ImportError:
# Models will be available after running create_test_ecommerce.py
pass
# Import existing modules
from modules.transaction_manager import TransactionManager
from modules.credit_analyzer import CreditAnalyzer
from modules.repayment_scheduler import RepaymentScheduler
from modules.ml_analytics import MLAnalytics
from modules.fraud_detection import FraudDetection
from modules.accessibility import get_user_accessibility_preferences, apply_accessibility_preferences_from_form
from modules.crypto_wallet import CryptoWalletManager
# Initialize CSRF protection
csrf = CSRFProtect(app)
# Make CSRF token and accessibility settings available to all templates
@app.context_processor
def inject_template_vars():
# Add CSRF token for all templates
context = dict(csrf_token=generate_csrf())
# Add accessibility preferences if user is logged in
if current_user.is_authenticated:
preferences = get_user_accessibility_preferences(current_user)
context['accessibility'] = preferences
else:
# Default empty preferences for non-logged in users
context['accessibility'] = None
return context
# Initialize Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# Initialize modules
transaction_manager = TransactionManager()
credit_analyzer = CreditAnalyzer()
repayment_scheduler = RepaymentScheduler()
ml_analytics = MLAnalytics()
fraud_detection = FraudDetection()
# Import and register the Google OAuth blueprint
try:
from modules.google_auth import google_auth
app.register_blueprint(google_auth)
app.logger.info("Google OAuth blueprint registered")
except ImportError as e:
app.logger.warning(f"Could not import Google OAuth module: {e}")
except Exception as e:
app.logger.error(f"Error registering Google OAuth blueprint: {e}")
# Import and register the Promo Codes blueprint
try:
from modules.promo_codes import promo_codes
app.register_blueprint(promo_codes)
app.logger.info("Promo Codes blueprint registered")
except ImportError as e:
app.logger.warning(f"Could not import Promo Codes module: {e}")
except Exception as e:
app.logger.error(f"Error registering Promo Codes blueprint: {e}")
# Add direct routes for tradeline performance
@app.route('/tradeline-performance')
@login_required
def tradeline_performance_dashboard():
"""Tradeline performance dashboard"""
# Get user's tradelines
tradelines = Tradeline.query.filter_by(owner_id=current_user.id).all()
# Get tradeline performance data
tradeline_data = []
for tradeline in tradelines:
# Get performance records
performance_records = TradelinePerformance.query.filter_by(tradeline_id=tradeline.id).all()
# Calculate performance metrics
utilization_history = []
payment_history = []
for record in performance_records:
# Calculate utilization for this record
utilization = (record.balance / tradeline.credit_limit) * 100 if tradeline.credit_limit > 0 else 0
utilization_history.append({
'date': record.report_date.strftime('%Y-%m-%d'),
'utilization': round(utilization, 2)
})
# Payment history
payment_history.append({
'date': record.report_date.strftime('%Y-%m-%d'),
'status': record.payment_status,
'amount': record.payment_amount
})
# Add tradeline data
tradeline_data.append({
'id': tradeline.id,
'name': tradeline.name,
'utilization_history': utilization_history,
'payment_history': payment_history,
'current_utilization': (tradeline.credit_limit - tradeline.available_limit) / tradeline.credit_limit * 100 if tradeline.credit_limit > 0 else 0
})
return render_template('tradeline_performance/index.html',
tradelines=tradelines,
tradeline_data=tradeline_data,
active_page='tradeline_performance')
@app.route('/tradeline-performance/<int:tradeline_id>')
@login_required
def tradeline_performance_detail(tradeline_id):
"""Tradeline performance detail view"""
# Get the tradeline
tradeline = Tradeline.query.get_or_404(tradeline_id)
# Check if the user owns this tradeline
if tradeline.owner_id != current_user.id:
flash('You do not have permission to view this tradeline', 'danger')
return redirect(url_for('tradeline_performance_dashboard'))
# Get performance records
performance_records = TradelinePerformance.query.filter_by(tradeline_id=tradeline.id).all()
# Calculate performance metrics
utilization_history = []
payment_history = []
for record in performance_records:
# Calculate utilization for this record
utilization = (record.balance / tradeline.credit_limit) * 100 if tradeline.credit_limit > 0 else 0
utilization_history.append({
'date': record.report_date.strftime('%Y-%m-%d'),
'utilization': round(utilization, 2)
})
# Payment history
payment_history.append({
'date': record.report_date.strftime('%Y-%m-%d'),
'status': record.payment_status,
'amount': record.payment_amount
})
return render_template('tradeline_performance/detail.html',
tradeline=tradeline,
utilization_history=utilization_history,
payment_history=payment_history,
performance_records=performance_records,
active_page='tradeline_performance')
# Add direct route for Google login
@app.route('/google_login')
def google_login():
"""Redirect to Google OAuth login"""
# This is a simplified fallback since we don't have the real Google OAuth setup
flash('Google login is not available in this environment', 'warning')
return redirect(url_for('login'))
# Add direct route for promo codes admin
@app.route('/admin/promo-codes')
@login_required
def admin_promo_codes():
"""Admin page for managing promo codes"""
# Get all promo codes
promo_codes = PromoCode.query.all()
return render_template('admin/promo_codes.html',
promo_codes=promo_codes,
active_page='admin')
# Register API Gateway module for external tradeline access
try:
from modules.api_gateway import api_gateway
app.register_blueprint(api_gateway, url_prefix='/api')
app.logger.info("API Gateway blueprint registered")
# Register the /api-dashboard route as a redirect to api_gateway.api_dashboard
@app.route('/api-dashboard')
@login_required
def api_dashboard():
"""View and manage API access for external platforms"""
return redirect(url_for('api_gateway.api_dashboard'))
# Register the /api-docs route as a redirect to api_gateway.api_docs
@app.route('/api-docs')
@login_required
def api_docs_blueprint():
"""View API documentation"""
return redirect(url_for('api_gateway.api_docs'))
except ImportError as e:
app.logger.warning(f"Could not import API Gateway module: {e}")
# Register A2A Protocol Integration
try:
from modules.a2a_integration import a2a_blueprint, a2a_messages
app.register_blueprint(a2a_blueprint)
app.register_blueprint(a2a_messages)
app.logger.info("A2A Protocol Integration registered")
except ImportError as e:
app.logger.warning(f"Could not import A2A Protocol Integration module: {e}")
except Exception as e:
app.logger.error(f"Error registering A2A Protocol Integration: {e}")
# Register Coinbase Developer Platform (CDP) Integration
try:
from modules.cdp_integration import register_cdp_routes
register_cdp_routes(app)
app.logger.info("CDP Integration registered")
except ImportError as e:
app.logger.warning(f"Could not import CDP Integration module: {e}")
except Exception as e:
app.logger.error(f"Error registering CDP Integration: {e}")
# Add well-known Agent Card endpoint for agent discovery
@app.route('/.well-known/agent.json')
def agent_card():
"""Return the Agent Card for the requested agent"""
import json
from models import get_ai_agent_model
# Get AI Agent model
AIAgent = get_ai_agent_model()
# Get the agent identifier from the request, could be BNS or agent ID
agent_id = request.args.get('agent_id')
bns_id = request.args.get('bns_id')
if not agent_id and not bns_id:
return jsonify({"error": "Missing agent_id or bns_id parameter"}), 400
# Get the agent by ID or BNS identifier
if agent_id:
agent = AIAgent.query.get(agent_id)
else:
agent = AIAgent.query.filter_by(bns_identifier=bns_id).first()
if not agent:
return jsonify({"error": "Agent not found"}), 404
# Ensure the agent has A2A enabled
if not agent.a2a_enabled:
return jsonify({"error": "Agent does not support A2A protocol"}), 403
# Build the Agent Card
agent_card = {
"name": agent.name,
"description": agent.description,
"purpose": agent.purpose,
"version": "1.0",
"protocol": "a2a",
"capabilities": ["financial_transactions", "credit_utilization"],
"identity": {
"bns": agent.bns_identifier,
"wallet": agent.wallet_address,
"network": agent.wallet_network
},
"financial": {
"purpose_code": agent.purpose_code,
"entity_code": agent.entity_code,
"credit_score": agent.credit_score,
"risk_profile": agent.risk_profile
},
"endpoints": {
"messages": f"/a2a/messages/{agent.bns_identifier}",
"status": f"/a2a/status/{agent.bns_identifier}"
},
"authentication": {
"type": "blockchain_signature",
"required": True
}
}
# Add custom metadata if available
if agent.a2a_metadata:
try:
custom_metadata = json.loads(agent.a2a_metadata)
if isinstance(custom_metadata, dict):
# Add custom fields to agent card
for key, value in custom_metadata.items():
if key not in agent_card:
agent_card[key] = value
except:
# If metadata is invalid JSON, ignore it
pass
# Set proper content type for JSON and CORS headers
response = jsonify(agent_card)
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
return response
@app.route('/a2a_dashboard')
@login_required
def a2a_dashboard():
"""View and manage A2A protocol integration"""
# Import here to avoid circular imports
from models import get_ai_agent_model
from datetime import datetime, timedelta
# Get AI Agent model
AIAgent = get_ai_agent_model()
# Get A2A-enabled agents
a2a_agents = AIAgent.query.filter_by(a2a_enabled=True).all()
# Placeholder for recent A2A interactions (in a real app, this would come from a database)
recent_interactions = []
# Return the template with data
return render_template('a2a_dashboard/index.html',
a2a_agents=a2a_agents,
recent_interactions=recent_interactions,
active_page='a2a_dashboard')
except ImportError as e:
app.logger.warning(f"Could not import A2A Integration module: {e}")
# Add fallback routes if API Gateway is not available
@app.route('/api-dashboard')
@login_required
def api_dashboard():
"""Fallback API dashboard view"""
app.logger.warning("Using fallback API dashboard view as API Gateway module is not available")
# Generate CSRF token for the template forms
from flask_wtf.csrf import generate_csrf
csrf_token = generate_csrf()
# Provide empty mock data for template variables to avoid undefined errors
from datetime import datetime, timedelta
today = datetime.utcnow()
# Create empty date arrays for charts
usage_dates = [(today - timedelta(days=i)).strftime('%Y-%m-%d') for i in range(30, 0, -1)]
usage_counts = [0] * 30
success_rates = [100] * 30
# Create empty stats dictionaries
usage_stats = {}
daily_usage = []
return render_template('api_dashboard/index.html',
api_keys=[],
subscriptions=[],
usage=[],
usage_stats=usage_stats,
usage_dates=usage_dates,
usage_counts=usage_counts,
success_rates=success_rates,
daily_usage=daily_usage,
csrf_token=csrf_token,
active_page='api_dashboard')
@app.route('/api-docs')
@login_required
def api_docs():
"""Fallback API docs view"""
# Generate CSRF token for the template forms
from flask_wtf.csrf import generate_csrf
csrf_token = generate_csrf()
return render_template('api_dashboard/documentation.html',
csrf_token=csrf_token,
active_page='api_dashboard')
except Exception as e:
app.logger.error(f"Error registering API Gateway blueprint: {e}")
# Create database tables
with app.app_context():
# Create all tables
db.create_all()
# Log the creation
app.logger.info("Database tables created successfully")
# Create a default user if none exists
from datetime import datetime
user_count = User.query.count()
if user_count == 0:
app.logger.info("Creating default admin user...")
# Create a new admin user
default_user = User(
username="admin",
email="admin@example.com",
first_name="Admin",
last_name="User",
date_joined=datetime.utcnow(),
is_active=True
)
# Set password
default_user.set_password("admin")
# Add user to database
db.session.add(default_user)
db.session.flush() # Flush to get the user ID
# Create a credit profile for the user
credit_profile = CreditProfile(
user_id=default_user.id,
credit_score=750,
verified=True,
verification_date=datetime.utcnow(),
identity_number="123-45-6789",
available_credit=10000.0,
total_credit_limit=15000.0
)
# Add credit profile to database
db.session.add(credit_profile)
# Commit changes
db.session.commit()
app.logger.info("Default user created successfully with username 'admin' and password 'admin'")
@app.route('/whitepaper')
def whitepaper():
"""Display the platform whitepaper"""
try:
with open('whitepaper.md', 'r') as f:
whitepaper_content = f.read()
return render_template('whitepaper.html',
whitepaper_content=whitepaper_content,
active_page='whitepaper')
except FileNotFoundError:
flash('Whitepaper not found', 'danger')
return redirect(url_for('dashboard'))
@app.route('/pitch-deck')
@login_required
def pitch_deck():
"""Display the investor pitch deck"""
return render_template('pitch_deck.html', active_page='pitch_deck')
@app.route('/download-pitch-deck-pdf')
@login_required
def download_pitch_deck_pdf():
"""Generate and download the pitch deck as a PDF"""
from reportlab.lib.pagesizes import letter, landscape
from reportlab.platypus import SimpleDocTemplate, Spacer, PageBreak
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF
from io import BytesIO
import os
# Create a BytesIO buffer to store the PDF
buffer = BytesIO()
# Get landscape letter dimensions
page_width, page_height = landscape(letter)
# Create PDF canvas
c = canvas.Canvas(buffer, pagesize=landscape(letter))
# Define safe margins
margin = 36 # 0.5 inch margins
# Calculate available drawing area
available_width = page_width - 2 * margin
available_height = page_height - 2 * margin
# Process each slide
for i in range(1, 14): # 13 slides
svg_path = os.path.join(app.root_path, 'static', 'images', 'pitch_deck', f'slide{i}.svg')
try:
# Convert SVG to ReportLab drawing
drawing = svg2rlg(svg_path)
# Calculate scale to fit within available area while maintaining aspect ratio
width_scale = available_width / drawing.width
height_scale = available_height / drawing.height
scale = min(width_scale, height_scale) * 0.95 # Add a little extra margin for safety
# Calculate centering position
x_pos = margin + (available_width - drawing.width * scale) / 2
y_pos = margin + (available_height - drawing.height * scale) / 2
# Draw the SVG on the page
c.translate(x_pos, y_pos)
c.scale(scale, scale)
renderPDF.draw(drawing, c, 0, 0)
# Reset transform matrix for next slide
c.resetTransforms()
# Add a new page if this isn't the last slide
if i < 13:
c.showPage()
except Exception as e:
app.logger.error(f"Error processing slide {i}: {e}")
# Save the PDF
c.save()
# Get the PDF from the buffer
pdf_data = buffer.getvalue()
buffer.close()
# Create a response with the PDF data
from flask import make_response
response = make_response(pdf_data)
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = 'attachment; filename=TradeLine_AI_Pitch_Deck.pdf'
return response
@app.route('/')
@login_required
def dashboard():
"""Main dashboard view with credit utilization metrics"""
# Get credit utilization data with error handling
try:
credit_data = credit_analyzer.get_dashboard_data()
except Exception as e:
app.logger.error(f"Error getting credit data: {str(e)}")
# Provide default data if there's an error
credit_data = {
'credit_limit': 0,
'available_credit': 0,
'current_balance': 0,
'utilization': 0,
'utilization_percentage': 0,
'predicted_utilization': 0,
'utilization_trend': 'stable',
'transactions_count': 0,
'forecasts': [],
'payment_due_date': (datetime.utcnow() + timedelta(days=15)).strftime("%b %d, %Y"),
'days_until_due': 15
}
# Get user's credit profile
credit_profile = CreditProfile.query.filter_by(user_id=current_user.id).first()
# Get user's AI agents with their credit scores
agent_data = []
try:
agents = AIAgent.query.filter_by(owner_id=current_user.id).all()
for agent in agents:
# Get tradeline allocations
allocations = AIAgentAllocation.query.filter_by(
agent_id=agent.id,
is_active=True
).all()
# Calculate total limit
total_limit = sum(allocation.credit_limit for allocation in allocations)
agent_data.append({
'id': agent.id,
'name': agent.name,
'credit_score': agent.credit_score,
'allocations': allocations,
'total_limit': total_limit
})
except Exception as e:
app.logger.error(f"Error fetching agent data: {str(e)}")
return render_template('dashboard.html',
credit_data=credit_data,
credit_profile=credit_profile,
agent_data=agent_data,
active_page='dashboard',
error=None)
@app.route('/transactions')
@login_required
def transactions():
"""Transaction history page"""
transactions = transaction_manager.get_transactions()
return render_template('transactions.html',
transactions=transactions,
active_page='transactions')
@app.route('/transaction', methods=['POST'])
@login_required
def process_transaction():
"""API endpoint to process a new transaction"""
transaction_data = request.json
result = transaction_manager.process_transaction(transaction_data)
return jsonify(result)
@app.route('/repayments')
@login_required
def repayments():
"""Repayment management page"""
repayment_data = repayment_scheduler.get_all_repayments()
return render_template('repayments.html',
repayments=repayment_data,
active_page='repayments')
@app.route('/repay', methods=['POST'])
@login_required
def repay():
"""API endpoint to schedule a repayment"""
repayment_data = request.json
result = repayment_scheduler.schedule_repayment(repayment_data)
return jsonify(result)
@app.route('/analytics')
@login_required
def analytics():
"""Analytics page with ML insights"""
# Prepare analytics data for the dashboard
cash_flow_data = ml_analytics.get_cash_flow_trends()
fraud_stats = fraud_detection.get_fraud_statistics()
credit_forecasts = credit_analyzer.get_credit_forecasts()
return render_template('analytics.html',
cash_flow_data=cash_flow_data,
fraud_stats=fraud_stats,
credit_forecasts=credit_forecasts,
active_page='analytics')
@app.route('/reports')
@login_required
def reports():
"""Detailed reporting dashboard with comprehensive financial analytics"""
# Get user's tradelines
user_tradelines = Tradeline.query.filter_by(owner_id=current_user.id).all()
# Get purchased tradelines
purchased_tradelines = TradelinePurchase.query.filter_by(purchaser_id=current_user.id).all()
# Get AI agents
user_agents = AIAgent.query.filter_by(owner_id=current_user.id).all()
# Get agent allocations
agent_allocations = AIAgentAllocation.query.filter(
AIAgentAllocation.agent_id.in_([a.id for a in user_agents])
).all() if user_agents else []
# Get agent transactions
agent_transactions = Transaction.query.filter(
Transaction.agent_id.in_([a.id for a in user_agents])
).all() if user_agents else []
# Get cash flow data for charts
cash_flow_data = ml_analytics.get_cash_flow_trends()
# Get tradeline performance data
tradeline_performance = {
'utilization_rates': [],
'risk_scores': [],
'transaction_volumes': []
}
for tradeline in user_tradelines:
# Calculate utilization rate
utilization = round((tradeline.credit_limit - tradeline.available_limit) / tradeline.credit_limit * 100, 2)
tradeline_performance['utilization_rates'].append({
'name': tradeline.name,
'utilization': utilization
})
# Get risk assessment
risk_data = ml_analytics.predict_tradeline_risk({
'credit_limit': tradeline.credit_limit,
'available_limit': tradeline.available_limit,
'interest_rate': tradeline.interest_rate,
'account_type': tradeline.account_type
})
tradeline_performance['risk_scores'].append({
'name': tradeline.name,
'risk_score': risk_data.get('risk_score', 50),
'risk_category': risk_data.get('risk_category', 'Medium')
})
# Agent performance metrics
agent_performance = []
for agent in user_agents:
# Get agent transactions
agent_txns = [t for t in agent_transactions if t.agent_id == agent.id]
# Calculate transaction volume
total_volume = sum(t.amount for t in agent_txns) if agent_txns else 0
# Get allocated tradelines
allocations = [a for a in agent_allocations if a.agent_id == agent.id]
allocated_credit = sum(a.credit_limit for a in allocations) if allocations else 0
agent_performance.append({
'name': agent.name,
'purpose': agent.purpose,
'risk_profile': agent.risk_profile,
'transaction_volume': total_volume,
'allocated_credit': allocated_credit,
'transaction_count': len(agent_txns),
'efficiency': round((total_volume / allocated_credit * 100) if allocated_credit > 0 else 0, 2)
})
return render_template('reports.html',
user_tradelines=user_tradelines,
purchased_tradelines=purchased_tradelines,
agent_performance=agent_performance,
tradeline_performance=tradeline_performance,
cash_flow_data=cash_flow_data,
active_page='reports')
@app.route('/api/predict-cash-flow', methods=['POST'])
@login_required
@csrf.exempt
def predict_cash_flow():
"""API endpoint for cash flow prediction"""
# Validate CSRF token from header
token = request.headers.get('X-CSRFToken')
if not token or not validate_csrf(token):
return jsonify({'error': 'Invalid CSRF token', 'accessible_message': 'Security token validation failed. Please refresh the page.'}), 403
data = request.json
prediction = ml_analytics.predict_cash_flow(data)
return jsonify({"cash_flow_prediction": prediction})
@app.route('/api/detect-fraud', methods=['POST'])
@login_required
@csrf.exempt
def detect_fraud():
"""API endpoint for fraud detection"""
# Validate CSRF token from header
token = request.headers.get('X-CSRFToken')
if not token or not validate_csrf(token):
return jsonify({'error': 'Invalid CSRF token', 'accessible_message': 'Security token validation failed. Please refresh the page.'}), 403
transaction_data = request.json
result = fraud_detection.detect_fraud(transaction_data)
return jsonify({"fraud_result": result})
@app.route('/api/predict-tradeline-risk', methods=['POST'])
@login_required
@csrf.exempt
def predict_tradeline_risk():
"""API endpoint for tradeline risk assessment"""
# Validate CSRF token from header
token = request.headers.get('X-CSRFToken')
if not token or not validate_csrf(token):
return jsonify({'error': 'Invalid CSRF token', 'accessible_message': 'Security token validation failed. Please refresh the page.'}), 403
tradeline_data = request.json
result = ml_analytics.predict_tradeline_risk(tradeline_data)
return jsonify({"risk_assessment": result})
@app.route('/api/predict-credit-usage', methods=['POST'])
@login_required
@csrf.exempt
def predict_credit_usage():
"""API endpoint for credit usage prediction"""
# Validate CSRF token from header
token = request.headers.get('X-CSRFToken')
if not token or not validate_csrf(token):
return jsonify({'error': 'Invalid CSRF token', 'accessible_message': 'Security token validation failed. Please refresh the page.'}), 403
credit_data = request.json
result = ml_analytics.predict_credit_usage(credit_data)
return jsonify({"credit_usage_prediction": result})
@app.route('/api/generate-report', methods=['POST'])
@login_required
@csrf.exempt # Exempting this specific endpoint from CSRF protection as we validate tokens in the header
def generate_report():
"""API endpoint for generating custom reports with accessibility annotations"""
report_data = request.json
report_type = report_data.get('report_type', 'summary')
timeframe = report_data.get('timeframe', '30d')
# Validate CSRF token from the header
token = request.headers.get('X-CSRFToken')
if not token or not validate_csrf(token):
return jsonify({
'error': 'Invalid or missing CSRF token',
'message': 'Please refresh the page and try again',
'accessible_message': 'Your security token has expired. Please refresh the page and try again.'
}), 403
# Get user's tradelines
user_tradelines = Tradeline.query.filter_by(owner_id=current_user.id).all()
# Get purchased tradelines
purchased_tradelines = TradelinePurchase.query.filter_by(purchaser_id=current_user.id).all()
# Get AI agents
user_agents = AIAgent.query.filter_by(owner_id=current_user.id).all()
# Initialize response object
response = {
'report_type': report_type,
'timeframe': timeframe,
'generated_at': datetime.utcnow().isoformat(),
'user_id': current_user.id,
'data': {}
}
# Process different report types
if report_type == 'tradeline_performance':
# Calculate tradeline performance metrics
tradeline_metrics = []
for tradeline in user_tradelines:
# Calculate utilization rate
utilization = round((tradeline.credit_limit - tradeline.available_limit) / tradeline.credit_limit * 100, 2)
# Get risk assessment
risk_data = ml_analytics.predict_tradeline_risk({
'credit_limit': tradeline.credit_limit,
'available_limit': tradeline.available_limit,
'interest_rate': tradeline.interest_rate,
'account_type': tradeline.account_type
})
tradeline_metrics.append({
'id': tradeline.id,
'name': tradeline.name,
'credit_limit': float(tradeline.credit_limit),
'available_limit': float(tradeline.available_limit),
'utilization': utilization,
'risk_score': risk_data.get('risk_score', 50),
'risk_category': risk_data.get('risk_category', 'Medium'),
'recommendations': risk_data.get('recommendations', []),
'is_for_sale': tradeline.is_for_sale,
'is_for_rent': tradeline.is_for_rent
})
response['data']['tradeline_metrics'] = tradeline_metrics
elif report_type == 'agent_performance':
# Get agent allocations
agent_allocations = AIAgentAllocation.query.filter(
AIAgentAllocation.agent_id.in_([a.id for a in user_agents])
).all() if user_agents else []
# Get agent transactions
agent_transactions = Transaction.query.filter(
Transaction.agent_id.in_([a.id for a in user_agents])
).all() if user_agents else []
# Calculate agent performance metrics
agent_metrics = []
for agent in user_agents:
# Get agent transactions
agent_txns = [t for t in agent_transactions if t.agent_id == agent.id]
# Calculate transaction volume
total_volume = sum(t.amount for t in agent_txns) if agent_txns else 0
# Get allocated tradelines
allocations = [a for a in agent_allocations if a.agent_id == agent.id]
allocated_credit = sum(a.credit_limit for a in allocations) if allocations else 0
agent_metrics.append({
'id': agent.id,
'name': agent.name,
'purpose': agent.purpose,
'risk_profile': agent.risk_profile,
'transaction_volume': float(total_volume),
'allocated_credit': float(allocated_credit),
'transaction_count': len(agent_txns),
'efficiency': round((total_volume / allocated_credit * 100) if allocated_credit > 0 else 0, 2),
'is_active': agent.is_active
})
response['data']['agent_metrics'] = agent_metrics
elif report_type == 'marketplace_activity':
# Get marketplace activity metrics
sale_purchases = [p for p in purchased_tradelines if not p.is_rental]
rental_purchases = [p for p in purchased_tradelines if p.is_rental]
# Calculate metrics
total_investment = sum(p.price_paid for p in purchased_tradelines) if purchased_tradelines else 0
acquired_credit = sum(p.allocated_limit for p in purchased_tradelines) if purchased_tradelines else 0
roi_percentage = round((acquired_credit / total_investment * 100) if total_investment > 0 else 0, 2)
marketplace_metrics = {
'total_purchases': len(sale_purchases),
'total_rentals': len(rental_purchases),
'total_investment': float(total_investment),
'acquired_credit': float(acquired_credit),
'roi_percentage': roi_percentage,
'active_purchases': len([p for p in purchased_tradelines if p.is_active])
}
response['data']['marketplace_metrics'] = marketplace_metrics
else:
# Summary report type - include all data
# Get cash flow data for charts
cash_flow_data = ml_analytics.get_cash_flow_trends()
# Calculate summary metrics
total_credit_limit = sum(t.credit_limit for t in user_tradelines) if user_tradelines else 0
total_available_credit = sum(t.available_limit for t in user_tradelines) if user_tradelines else 0
acquired_credit = sum(p.allocated_limit for p in purchased_tradelines) if purchased_tradelines else 0
# Get active agents
active_agents = [a for a in user_agents if a.is_active]
# Calculate average risk score across tradelines
avg_risk_score = 0
if user_tradelines:
risk_scores = []
for tradeline in user_tradelines:
risk_data = ml_analytics.predict_tradeline_risk({
'credit_limit': tradeline.credit_limit,
'available_limit': tradeline.available_limit,
'interest_rate': tradeline.interest_rate,
'account_type': tradeline.account_type
})
risk_scores.append(risk_data.get('risk_score', 50))
avg_risk_score = sum(risk_scores) / len(risk_scores) if risk_scores else 50