sksameermujahid commited on
Commit
18315dc
·
verified ·
1 Parent(s): eae740d

Upload 17 files

Browse files
api_service_enhanced.py CHANGED
@@ -110,8 +110,8 @@ class EnhancedLeadQualificationAPI:
110
  # Frontend routes
111
  @self.app.route('/')
112
  def index():
113
- """Unified AI Customer Analysis & Email Automation Dashboard"""
114
- return render_template('unified_ai_dashboard.html', customer_id=None)
115
 
116
  @self.app.route('/old')
117
  def old_dashboard():
@@ -2378,13 +2378,34 @@ class EnhancedLeadQualificationAPI:
2378
  'error': 'Email address is required'
2379
  }), 400
2380
 
2381
- # Get customer analysis data
2382
- analysis_data = self._get_analysis_data_parallel(customer_id)
 
 
2383
  if not analysis_data:
2384
- return jsonify({
2385
- 'success': False,
2386
- 'error': 'No customer data found'
2387
- }), 404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2388
 
2389
  # Get AI engine for analysis
2390
  ai_engine = self.get_ai_engine()
 
110
  # Frontend routes
111
  @self.app.route('/')
112
  def index():
113
+ """Perfect AI Customer Analysis & Email Automation Dashboard"""
114
+ return render_template('perfect_ai_dashboard.html', customer_id=None)
115
 
116
  @self.app.route('/old')
117
  def old_dashboard():
 
2378
  'error': 'Email address is required'
2379
  }), 400
2380
 
2381
+ # Get customer analysis data (use the same method as the main analysis)
2382
+ cache_key = f'lead_analysis_{customer_id}'
2383
+ analysis_data = self.get_cached_data(cache_key)
2384
+
2385
  if not analysis_data:
2386
+ # Generate fresh analysis data
2387
+ logger.info(f"🌐 Fetching fresh data for email automation - customer {customer_id}")
2388
+ backend_response = self.make_api_request(f'/api/PropertyLeadQualification/customer/{customer_id}')
2389
+
2390
+ if not backend_response:
2391
+ return jsonify({
2392
+ 'success': False,
2393
+ 'error': 'No customer data found'
2394
+ }), 404
2395
+
2396
+ processed_data = self.process_lead_data(backend_response, customer_id)
2397
+ analytics = self.generate_analytics(backend_response, customer_id)
2398
+
2399
+ analysis_data = {
2400
+ 'success': True,
2401
+ 'customer_id': customer_id,
2402
+ 'data': {
2403
+ 'lead_qualification': analytics.get('lead_qualification', {}),
2404
+ 'analytics': analytics,
2405
+ 'properties': processed_data.get('properties', []),
2406
+ 'summary': processed_data.get('summary', {})
2407
+ }
2408
+ }
2409
 
2410
  # Get AI engine for analysis
2411
  ai_engine = self.get_ai_engine()
email_automation_service.py CHANGED
@@ -13,6 +13,9 @@ import threading
13
  import schedule
14
  from datetime import datetime, timedelta
15
  from flask import Flask, request, jsonify
 
 
 
16
  import smtplib
17
  from email.mime.text import MIMEText
18
  from email.mime.multipart import MIMEMultipart
@@ -44,9 +47,9 @@ app = Flask(__name__)
44
 
45
  class EmailAutomationService:
46
  def __init__(self):
47
- self.db_path = 'ai_lead_system.db'
48
  self.api_base_url = 'http://localhost:7860' # Updated for Hugging Face Spaces
49
- self.backend_url = 'https://hivepropapi.azurewebsites.net' # Updated backend URL
50
  self.email_queue = []
51
  self.is_running = False
52
 
 
13
  import schedule
14
  from datetime import datetime, timedelta
15
  from flask import Flask, request, jsonify
16
+
17
+ # Import centralized configuration
18
+ from config import get_backend_url, get_ngrok_headers, get_database_config
19
  import smtplib
20
  from email.mime.text import MIMEText
21
  from email.mime.multipart import MIMEMultipart
 
47
 
48
  class EmailAutomationService:
49
  def __init__(self):
50
+ self.db_path = get_database_config()['path']
51
  self.api_base_url = 'http://localhost:7860' # Updated for Hugging Face Spaces
52
+ self.backend_url = get_backend_url() # Centralized ngrok URL
53
  self.email_queue = []
54
  self.is_running = False
55
 
templates/perfect_ai_dashboard.html ADDED
@@ -0,0 +1,1015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>🤖 Perfect AI Customer Analysis & Email Automation Dashboard</title>
7
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
8
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
9
+ <style>
10
+ :root {
11
+ --primary-color: #2563eb;
12
+ --secondary-color: #7c3aed;
13
+ --accent-color: #059669;
14
+ --success-color: #10b981;
15
+ --warning-color: #f59e0b;
16
+ --danger-color: #ef4444;
17
+ --light-color: #f8fafc;
18
+ --dark-color: #1e293b;
19
+ --info-color: #0ea5e9;
20
+ }
21
+
22
+ * {
23
+ margin: 0;
24
+ padding: 0;
25
+ box-sizing: border-box;
26
+ }
27
+
28
+ body {
29
+ font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
30
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
31
+ color: var(--dark-color);
32
+ line-height: 1.6;
33
+ min-height: 100vh;
34
+ }
35
+
36
+ .main-container {
37
+ max-width: 1600px;
38
+ margin: 0 auto;
39
+ padding: 20px;
40
+ }
41
+
42
+ /* Header Styles */
43
+ .hero-header {
44
+ background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
45
+ color: white;
46
+ border-radius: 20px;
47
+ padding: 40px;
48
+ margin-bottom: 30px;
49
+ text-align: center;
50
+ box-shadow: 0 20px 40px rgba(37, 99, 235, 0.3);
51
+ }
52
+
53
+ .hero-header h1 {
54
+ font-size: 3.5rem;
55
+ font-weight: 700;
56
+ margin-bottom: 15px;
57
+ text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
58
+ }
59
+
60
+ .hero-header p {
61
+ font-size: 1.4rem;
62
+ margin-bottom: 25px;
63
+ opacity: 0.95;
64
+ }
65
+
66
+ /* Card Styles */
67
+ .card {
68
+ background: white;
69
+ border-radius: 16px;
70
+ padding: 30px;
71
+ margin-bottom: 25px;
72
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
73
+ border: 1px solid rgba(255, 255, 255, 0.2);
74
+ backdrop-filter: blur(10px);
75
+ transition: all 0.3s ease;
76
+ }
77
+
78
+ .card:hover {
79
+ transform: translateY(-5px);
80
+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
81
+ }
82
+
83
+ .card h3 {
84
+ color: var(--dark-color);
85
+ font-weight: 600;
86
+ margin-bottom: 20px;
87
+ font-size: 1.6rem;
88
+ display: flex;
89
+ align-items: center;
90
+ gap: 10px;
91
+ }
92
+
93
+ /* Analysis Section */
94
+ .analysis-grid {
95
+ display: grid;
96
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
97
+ gap: 20px;
98
+ margin-bottom: 30px;
99
+ }
100
+
101
+ .analysis-card {
102
+ background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
103
+ border-radius: 12px;
104
+ padding: 20px;
105
+ border-left: 4px solid var(--primary-color);
106
+ }
107
+
108
+ .analysis-card h5 {
109
+ color: var(--primary-color);
110
+ margin-bottom: 15px;
111
+ font-weight: 600;
112
+ }
113
+
114
+ .metric-value {
115
+ font-size: 2.5rem;
116
+ font-weight: 700;
117
+ color: var(--primary-color);
118
+ margin-bottom: 5px;
119
+ }
120
+
121
+ .metric-label {
122
+ color: #64748b;
123
+ font-size: 0.9rem;
124
+ font-weight: 500;
125
+ }
126
+
127
+ /* Customer Input Section */
128
+ .customer-input-section {
129
+ background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
130
+ border-radius: 16px;
131
+ padding: 30px;
132
+ margin-bottom: 30px;
133
+ border: 2px solid var(--primary-color);
134
+ }
135
+
136
+ .form-control {
137
+ border-radius: 10px;
138
+ border: 2px solid #e2e8f0;
139
+ padding: 12px 16px;
140
+ font-size: 1.1rem;
141
+ transition: all 0.3s ease;
142
+ }
143
+
144
+ .form-control:focus {
145
+ border-color: var(--primary-color);
146
+ box-shadow: 0 0 0 0.2rem rgba(37, 99, 235, 0.25);
147
+ }
148
+
149
+ .btn {
150
+ border-radius: 10px;
151
+ padding: 12px 24px;
152
+ font-weight: 600;
153
+ font-size: 1.1rem;
154
+ transition: all 0.3s ease;
155
+ border: none;
156
+ }
157
+
158
+ .btn-primary {
159
+ background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
160
+ color: white;
161
+ }
162
+
163
+ .btn-primary:hover {
164
+ transform: translateY(-2px);
165
+ box-shadow: 0 8px 25px rgba(37, 99, 235, 0.3);
166
+ }
167
+
168
+ /* Email Preview Section */
169
+ .email-preview-section {
170
+ background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
171
+ border-radius: 16px;
172
+ padding: 30px;
173
+ margin-bottom: 30px;
174
+ border: 2px solid var(--warning-color);
175
+ }
176
+
177
+ .email-preview-container {
178
+ background: white;
179
+ border-radius: 12px;
180
+ padding: 20px;
181
+ min-height: 300px;
182
+ border: 1px solid #e5e7eb;
183
+ }
184
+
185
+ .email-type-btn {
186
+ margin: 5px;
187
+ border-radius: 8px;
188
+ padding: 10px 20px;
189
+ font-weight: 600;
190
+ transition: all 0.3s ease;
191
+ }
192
+
193
+ .email-type-btn:hover {
194
+ transform: translateY(-2px);
195
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
196
+ }
197
+
198
+ /* Loading Animation */
199
+ .loading-spinner {
200
+ display: inline-block;
201
+ width: 20px;
202
+ height: 20px;
203
+ border: 3px solid #f3f3f3;
204
+ border-top: 3px solid var(--primary-color);
205
+ border-radius: 50%;
206
+ animation: spin 1s linear infinite;
207
+ }
208
+
209
+ @keyframes spin {
210
+ 0% { transform: rotate(0deg); }
211
+ 100% { transform: rotate(360deg); }
212
+ }
213
+
214
+ /* Status Badges */
215
+ .status-badge {
216
+ padding: 8px 16px;
217
+ border-radius: 20px;
218
+ font-weight: 600;
219
+ font-size: 0.9rem;
220
+ text-transform: uppercase;
221
+ letter-spacing: 0.5px;
222
+ }
223
+
224
+ .status-hot { background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; }
225
+ .status-warm { background: #fffbeb; color: #d97706; border: 1px solid #fed7aa; }
226
+ .status-cold { background: #f0f9ff; color: #0284c7; border: 1px solid #bae6fd; }
227
+ .status-lukewarm { background: #f3f4f6; color: #6b7280; border: 1px solid #d1d5db; }
228
+
229
+ /* Alert Styles */
230
+ .alert {
231
+ border-radius: 12px;
232
+ border: none;
233
+ padding: 20px;
234
+ margin-bottom: 20px;
235
+ }
236
+
237
+ .alert-success {
238
+ background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
239
+ color: #065f46;
240
+ }
241
+
242
+ .alert-danger {
243
+ background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
244
+ color: #991b1b;
245
+ }
246
+
247
+ .alert-info {
248
+ background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
249
+ color: #1e40af;
250
+ }
251
+
252
+ /* Hidden class */
253
+ .hidden {
254
+ display: none !important;
255
+ }
256
+
257
+ /* Responsive Design */
258
+ @media (max-width: 768px) {
259
+ .hero-header h1 {
260
+ font-size: 2.5rem;
261
+ }
262
+
263
+ .analysis-grid {
264
+ grid-template-columns: 1fr;
265
+ }
266
+
267
+ .main-container {
268
+ padding: 10px;
269
+ }
270
+ }
271
+ </style>
272
+ </head>
273
+ <body>
274
+ <div class="main-container">
275
+ <!-- Hero Header -->
276
+ <div class="hero-header">
277
+ <h1>🤖 Perfect AI Customer Analysis & Email Automation</h1>
278
+ <p>Complete Customer Intelligence & Automated Email System</p>
279
+ <div class="d-flex justify-content-center gap-3 flex-wrap">
280
+ <span class="badge bg-light text-dark px-3 py-2">Real Data Analysis</span>
281
+ <span class="badge bg-light text-dark px-3 py-2">AI Insights</span>
282
+ <span class="badge bg-light text-dark px-3 py-2">Email Automation</span>
283
+ <span class="badge bg-light text-dark px-3 py-2">Behavior Tracking</span>
284
+ </div>
285
+ </div>
286
+
287
+ <!-- Customer Input Section -->
288
+ <div class="customer-input-section">
289
+ <div class="row align-items-center">
290
+ <div class="col-md-4">
291
+ <label for="customerId" class="form-label fw-bold">Customer ID:</label>
292
+ <input type="number" id="customerId" class="form-control" value="144" min="1" placeholder="Enter Customer ID">
293
+ </div>
294
+ <div class="col-md-4">
295
+ <label for="testEmail" class="form-label fw-bold">Test Email:</label>
296
+ <input type="email" id="testEmail" class="form-control" value="[email protected]" placeholder="Enter test email">
297
+ </div>
298
+ <div class="col-md-4">
299
+ <button type="button" class="btn btn-primary btn-lg w-100" onclick="analyzeCustomer()">
300
+ <i class="fas fa-chart-line"></i> Analyze Customer & Generate AI Insights
301
+ </button>
302
+ </div>
303
+ </div>
304
+ </div>
305
+
306
+ <!-- Loading Section -->
307
+ <div id="loadingSection" class="card text-center hidden">
308
+ <div class="loading-spinner mx-auto mb-3"></div>
309
+ <h4>Analyzing Customer Data & Generating AI Insights...</h4>
310
+ <p class="text-muted">This may take a few moments</p>
311
+ </div>
312
+
313
+ <!-- Analysis Results -->
314
+ <div id="analysisResults" class="hidden">
315
+ <!-- Customer Analysis Grid -->
316
+ <div class="analysis-grid">
317
+ <div class="analysis-card">
318
+ <h5><i class="fas fa-user"></i> Lead Status</h5>
319
+ <div id="leadStatus"></div>
320
+ </div>
321
+ <div class="analysis-card">
322
+ <h5><i class="fas fa-chart-line"></i> Engagement Score</h5>
323
+ <div class="metric-value" id="engagementScore">0</div>
324
+ <div class="metric-label">Overall Engagement</div>
325
+ </div>
326
+ <div class="analysis-card">
327
+ <h5><i class="fas fa-eye"></i> Total Views</h5>
328
+ <div class="metric-value" id="totalViews">0</div>
329
+ <div class="metric-label">Property Views</div>
330
+ </div>
331
+ <div class="analysis-card">
332
+ <h5><i class="fas fa-clock"></i> Total Duration</h5>
333
+ <div class="metric-value" id="totalDuration">0</div>
334
+ <div class="metric-label">Time Spent</div>
335
+ </div>
336
+ <div class="analysis-card">
337
+ <h5><i class="fas fa-percentage"></i> Conversion Probability</h5>
338
+ <div class="metric-value" id="conversionProbability">0%</div>
339
+ <div class="metric-label">Likelihood to Convert</div>
340
+ </div>
341
+ <div class="analysis-card">
342
+ <h5><i class="fas fa-home"></i> Preferred Properties</h5>
343
+ <div id="propertyPreferences"></div>
344
+ </div>
345
+ </div>
346
+
347
+ <!-- Detailed Customer Behavior Analysis -->
348
+ <div class="card">
349
+ <h3><i class="fas fa-brain"></i> Detailed Customer Behavior Analysis</h3>
350
+ <div class="row">
351
+ <div class="col-md-4">
352
+ <h5><i class="fas fa-clock"></i> Viewing Patterns</h5>
353
+ <div id="viewingPatterns"></div>
354
+ </div>
355
+ <div class="col-md-4">
356
+ <h5><i class="fas fa-chart-line"></i> Activity Timeline</h5>
357
+ <div id="activityTimeline"></div>
358
+ </div>
359
+ <div class="col-md-4">
360
+ <h5><i class="fas fa-dollar-sign"></i> Price Analysis</h5>
361
+ <div id="priceAnalysis"></div>
362
+ </div>
363
+ </div>
364
+ </div>
365
+
366
+ <!-- AI Insights & Recommendations -->
367
+ <div class="card">
368
+ <h3><i class="fas fa-robot"></i> AI Insights & Recommendations</h3>
369
+ <div class="row">
370
+ <div class="col-md-6">
371
+ <h5><i class="fas fa-lightbulb"></i> AI Analysis</h5>
372
+ <div id="aiRecommendations"></div>
373
+ </div>
374
+ <div class="col-md-6">
375
+ <h5><i class="fas fa-star"></i> Property Recommendations</h5>
376
+ <div id="propertyRecommendations"></div>
377
+ </div>
378
+ </div>
379
+ </div>
380
+
381
+ <!-- Email Preview & Testing Section -->
382
+ <div class="email-preview-section">
383
+ <h3><i class="fas fa-envelope-open"></i> Email Preview & Testing Center</h3>
384
+ <p class="mb-4">Preview and test all 5 types of automated emails based on customer analysis</p>
385
+
386
+ <div class="d-flex gap-2 flex-wrap mb-4">
387
+ <button type="button" class="btn btn-primary email-type-btn" onclick="previewAllEmails()">
388
+ <i class="fas fa-eye"></i> Preview All 5 Emails
389
+ </button>
390
+ <button type="button" class="btn btn-success email-type-btn" onclick="previewNewPropertiesEmail()">
391
+ <i class="fas fa-home"></i> New Properties
392
+ </button>
393
+ <button type="button" class="btn btn-info email-type-btn" onclick="previewRecommendationsEmail()">
394
+ <i class="fas fa-lightbulb"></i> AI Recommendations
395
+ </button>
396
+ <button type="button" class="btn btn-warning email-type-btn" onclick="previewPeakTimeEmail()">
397
+ <i class="fas fa-clock"></i> Peak Time
398
+ </button>
399
+ <button type="button" class="btn btn-secondary email-type-btn" onclick="previewBehavioralEmail()">
400
+ <i class="fas fa-user-cog"></i> Behavioral
401
+ </button>
402
+ </div>
403
+
404
+ <div class="d-flex gap-2 flex-wrap mb-4">
405
+ <button type="button" class="btn btn-danger email-type-btn" onclick="testAllEmails()">
406
+ <i class="fas fa-paper-plane"></i> Test All Emails
407
+ </button>
408
+ <button type="button" class="btn btn-success email-type-btn" onclick="sendAllEmails()">
409
+ <i class="fas fa-rocket"></i> Send All Emails
410
+ </button>
411
+ <button type="button" class="btn btn-info email-type-btn" onclick="getEmailStatus()">
412
+ <i class="fas fa-chart-bar"></i> Email Status
413
+ </button>
414
+ </div>
415
+
416
+ <div class="email-preview-container" id="emailPreviewContainer">
417
+ <div class="text-center text-muted">
418
+ <i class="fas fa-envelope fa-3x mb-3"></i>
419
+ <h5>Select an email type above to preview</h5>
420
+ <p>All emails are personalized based on customer analysis and AI insights</p>
421
+ </div>
422
+ </div>
423
+ </div>
424
+
425
+ <!-- Email Logs -->
426
+ <div class="card">
427
+ <h3><i class="fas fa-list"></i> Email Activity Logs</h3>
428
+ <div id="emailLogs"></div>
429
+ </div>
430
+ </div>
431
+ </div>
432
+
433
+ <script>
434
+ let currentCustomerId = 144;
435
+ let analysisData = null;
436
+
437
+ async function analyzeCustomer() {
438
+ const customerId = document.getElementById('customerId').value;
439
+ if (!customerId) {
440
+ showError('Please enter a Customer ID');
441
+ return;
442
+ }
443
+
444
+ currentCustomerId = customerId;
445
+
446
+ // Show loading
447
+ document.getElementById('loadingSection').classList.remove('hidden');
448
+ document.getElementById('analysisResults').classList.add('hidden');
449
+
450
+ try {
451
+ const response = await fetch(`/api/lead-analysis/${customerId}`);
452
+ const data = await response.json();
453
+
454
+ if (data.success) {
455
+ analysisData = data;
456
+ displayAnalysis(data);
457
+ loadEmailLogs();
458
+ showSuccess('Customer analysis completed successfully!');
459
+ } else {
460
+ showError('Analysis failed: ' + (data.error || 'Unknown error'));
461
+ }
462
+ } catch (error) {
463
+ showError('Error analyzing customer: ' + error.message);
464
+ } finally {
465
+ document.getElementById('loadingSection').classList.add('hidden');
466
+ document.getElementById('analysisResults').classList.remove('hidden');
467
+ }
468
+ }
469
+
470
+ function displayAnalysis(responseData) {
471
+ // Handle the actual API response structure
472
+ const data = responseData.data;
473
+ const analytics = data.analytics;
474
+ const leadQual = data.lead_qualification;
475
+ const summary = data.summary;
476
+
477
+ // Lead Status
478
+ document.getElementById('leadStatus').innerHTML = `
479
+ <div class="status-badge status-${leadQual.lead_status.toLowerCase()}">
480
+ ${leadQual.lead_status}
481
+ </div>
482
+ <p class="mt-3">${leadQual.status_description}</p>
483
+ <div class="progress mt-3">
484
+ <div class="progress-bar" style="width: ${leadQual.lead_score}%"></div>
485
+ </div>
486
+ <small class="text-muted mt-2">${leadQual.lead_score}/${leadQual.max_possible_score} points</small>
487
+ `;
488
+
489
+ // Key Metrics
490
+ document.getElementById('totalViews').textContent = summary.total_views;
491
+ document.getElementById('totalDuration').textContent = formatDuration(summary.total_duration);
492
+ document.getElementById('engagementScore').textContent = Math.round(summary.engagement_score);
493
+
494
+ const conversionProb = analytics.conversion_probability;
495
+ document.getElementById('conversionProbability').textContent = Math.round(conversionProb.final_probability) + '%';
496
+
497
+ // Property Preferences
498
+ document.getElementById('propertyPreferences').innerHTML = `
499
+ <ul class="list-unstyled">
500
+ ${analytics.preferred_property_types.map(type => `<li><i class="fas fa-check-circle text-success"></i> ${type}</li>`).join('')}
501
+ </ul>
502
+ `;
503
+
504
+ // Display other sections
505
+ displayViewingPatterns(analytics.viewing_patterns);
506
+ displayActivityTimeline(analytics.lead_timeline);
507
+ displayPriceAnalysis(analytics.price_preferences);
508
+ displayPropertiesViewed(data.properties);
509
+ displayAIRecommendations(analytics);
510
+ }
511
+
512
+ function displayViewingPatterns(patterns) {
513
+ const patternsHtml = `
514
+ <div class="d-flex flex-column gap-2">
515
+ <div><strong>Peak Time:</strong> ${patterns.peak_viewing_time}</div>
516
+ <div><strong>Morning Views:</strong> ${patterns.morning_views}</div>
517
+ <div><strong>Afternoon Views:</strong> ${patterns.afternoon_views}</div>
518
+ <div><strong>Evening Views:</strong> ${patterns.evening_views}</div>
519
+ </div>
520
+ `;
521
+ document.getElementById('viewingPatterns').innerHTML = patternsHtml;
522
+ }
523
+
524
+ function displayActivityTimeline(timeline) {
525
+ const timelineHtml = timeline.slice(0, 5).map(item => `
526
+ <div class="border rounded p-2 mb-2">
527
+ <div><strong>${item.property_name}</strong></div>
528
+ <small class="text-muted">${item.views} views • ${new Date(item.date).toLocaleDateString()}</small>
529
+ </div>
530
+ `).join('');
531
+ document.getElementById('activityTimeline').innerHTML = timelineHtml;
532
+ }
533
+
534
+ function displayPriceAnalysis(pricePrefs) {
535
+ const priceHtml = `
536
+ <div class="row">
537
+ <div class="col-md-6">
538
+ <div class="text-center">
539
+ <div class="h4 text-primary">$${formatPrice(pricePrefs.avg_price)}</div>
540
+ <small>Average Price</small>
541
+ </div>
542
+ </div>
543
+ <div class="col-md-6">
544
+ <div class="text-center">
545
+ <div class="h4 text-success">$${formatPrice(pricePrefs.min_price)}</div>
546
+ <small>Min Price</small>
547
+ </div>
548
+ </div>
549
+ </div>
550
+ `;
551
+ document.getElementById('priceAnalysis').innerHTML = priceHtml;
552
+ }
553
+
554
+ function displayPropertiesViewed(properties) {
555
+ const propertiesHtml = properties.slice(0, 3).map(prop => `
556
+ <div class="card mb-2">
557
+ <div class="card-body p-3">
558
+ <h6 class="card-title">${prop.propertyName}</h6>
559
+ <p class="card-text small text-muted">
560
+ <i class="fas fa-map-marker-alt"></i> ${prop.propertyTypeName}<br>
561
+ <i class="fas fa-dollar-sign"></i> $${formatPrice(prop.price)}<br>
562
+ <i class="fas fa-eye"></i> ${prop.viewCount} views
563
+ </p>
564
+ </div>
565
+ </div>
566
+ `).join('');
567
+ document.getElementById('propertyRecommendations').innerHTML = propertiesHtml;
568
+ }
569
+
570
+ function displayAIRecommendations(analytics) {
571
+ const recommendationsHtml = `
572
+ <div class="alert alert-info">
573
+ <h6><i class="fas fa-lightbulb"></i> AI Insights</h6>
574
+ <ul class="list-unstyled mb-0">
575
+ <li><i class="fas fa-check text-success"></i> Customer shows high engagement during ${analytics.viewing_patterns.peak_viewing_time}</li>
576
+ <li><i class="fas fa-check text-success"></i> Prefers ${analytics.preferred_property_types.join(' and ')} properties</li>
577
+ <li><i class="fas fa-check text-success"></i> Price range: $${formatPrice(analytics.price_preferences.min_price)} - $${formatPrice(analytics.price_preferences.max_price)}</li>
578
+ <li><i class="fas fa-check text-success"></i> Conversion probability: ${Math.round(analytics.conversion_probability.final_probability)}%</li>
579
+ </ul>
580
+ </div>
581
+ `;
582
+ document.getElementById('aiRecommendations').innerHTML = recommendationsHtml;
583
+ }
584
+
585
+ // Email Preview Functions
586
+ async function previewAllEmails() {
587
+ if (!analysisData) {
588
+ showError('Please analyze a customer first to preview emails');
589
+ return;
590
+ }
591
+
592
+ document.getElementById('emailPreviewContainer').innerHTML = '<div class="text-center"><div class="loading-spinner mx-auto mb-3"></div>Loading all email previews...</div>';
593
+
594
+ try {
595
+ const response = await fetch(`/api/email-automation/${currentCustomerId}`, {
596
+ method: 'POST',
597
+ headers: {
598
+ 'Content-Type': 'application/json'
599
+ },
600
+ body: JSON.stringify({
601
+ email: document.getElementById('testEmail').value || '[email protected]',
602
+ email_type: 'all'
603
+ })
604
+ });
605
+
606
+ const data = await response.json();
607
+
608
+ if (data.success) {
609
+ displayEmailPreviews(data.results, 'All 5 Email Types');
610
+ } else {
611
+ showError('Failed to preview emails: ' + (data.error || 'Unknown error'));
612
+ }
613
+ } catch (error) {
614
+ showError('Error previewing emails: ' + error.message);
615
+ }
616
+ }
617
+
618
+ async function previewNewPropertiesEmail() {
619
+ if (!analysisData) {
620
+ showError('Please analyze a customer first to preview emails');
621
+ return;
622
+ }
623
+
624
+ document.getElementById('emailPreviewContainer').innerHTML = '<div class="text-center"><div class="loading-spinner mx-auto mb-3"></div>Loading new properties email preview...</div>';
625
+
626
+ try {
627
+ const response = await fetch(`/api/email-automation/${currentCustomerId}`, {
628
+ method: 'POST',
629
+ headers: {
630
+ 'Content-Type': 'application/json'
631
+ },
632
+ body: JSON.stringify({
633
+ email: document.getElementById('testEmail').value || '[email protected]',
634
+ email_type: 'new_properties'
635
+ })
636
+ });
637
+
638
+ const data = await response.json();
639
+
640
+ if (data.success) {
641
+ displayEmailPreviews(data.results, 'New Properties Email');
642
+ } else {
643
+ showError('Failed to preview new properties email: ' + (data.error || 'Unknown error'));
644
+ }
645
+ } catch (error) {
646
+ showError('Error previewing new properties email: ' + error.message);
647
+ }
648
+ }
649
+
650
+ async function previewRecommendationsEmail() {
651
+ if (!analysisData) {
652
+ showError('Please analyze a customer first to preview emails');
653
+ return;
654
+ }
655
+
656
+ document.getElementById('emailPreviewContainer').innerHTML = '<div class="text-center"><div class="loading-spinner mx-auto mb-3"></div>Loading recommendations email preview...</div>';
657
+
658
+ try {
659
+ const response = await fetch(`/api/email-automation/${currentCustomerId}`, {
660
+ method: 'POST',
661
+ headers: {
662
+ 'Content-Type': 'application/json'
663
+ },
664
+ body: JSON.stringify({
665
+ email: document.getElementById('testEmail').value || '[email protected]',
666
+ email_type: 'recommendations'
667
+ })
668
+ });
669
+
670
+ const data = await response.json();
671
+
672
+ if (data.success) {
673
+ displayEmailPreviews(data.results, 'AI Recommendations Email');
674
+ } else {
675
+ showError('Failed to preview recommendations email: ' + (data.error || 'Unknown error'));
676
+ }
677
+ } catch (error) {
678
+ showError('Error previewing recommendations email: ' + error.message);
679
+ }
680
+ }
681
+
682
+ async function previewPeakTimeEmail() {
683
+ if (!analysisData) {
684
+ showError('Please analyze a customer first to preview emails');
685
+ return;
686
+ }
687
+
688
+ document.getElementById('emailPreviewContainer').innerHTML = '<div class="text-center"><div class="loading-spinner mx-auto mb-3"></div>Loading peak time email preview...</div>';
689
+
690
+ try {
691
+ const response = await fetch(`/api/email-automation/${currentCustomerId}`, {
692
+ method: 'POST',
693
+ headers: {
694
+ 'Content-Type': 'application/json'
695
+ },
696
+ body: JSON.stringify({
697
+ email: document.getElementById('testEmail').value || '[email protected]',
698
+ email_type: 'peak_time'
699
+ })
700
+ });
701
+
702
+ const data = await response.json();
703
+
704
+ if (data.success) {
705
+ displayEmailPreviews(data.results, 'Peak Time Engagement Email');
706
+ } else {
707
+ showError('Failed to preview peak time email: ' + (data.error || 'Unknown error'));
708
+ }
709
+ } catch (error) {
710
+ showError('Error previewing peak time email: ' + error.message);
711
+ }
712
+ }
713
+
714
+ async function previewBehavioralEmail() {
715
+ if (!analysisData) {
716
+ showError('Please analyze a customer first to preview emails');
717
+ return;
718
+ }
719
+
720
+ document.getElementById('emailPreviewContainer').innerHTML = '<div class="text-center"><div class="loading-spinner mx-auto mb-3"></div>Loading behavioral email preview...</div>';
721
+
722
+ try {
723
+ const response = await fetch(`/api/test-automated-emails/${currentCustomerId}`, {
724
+ method: 'POST',
725
+ headers: {
726
+ 'Content-Type': 'application/json'
727
+ }
728
+ });
729
+
730
+ const data = await response.json();
731
+
732
+ if (data.success) {
733
+ displayBehavioralEmailPreview(data, 'Behavioral Trigger Email');
734
+ } else {
735
+ showError('Failed to preview behavioral email: ' + (data.error || 'Unknown error'));
736
+ }
737
+ } catch (error) {
738
+ showError('Error previewing behavioral email: ' + error.message);
739
+ }
740
+ }
741
+
742
+ function displayEmailPreviews(results, title) {
743
+ let html = `<h5><i class="fas fa-envelope"></i> ${title} Preview</h5>`;
744
+
745
+ if (results && results.length > 0) {
746
+ results.forEach((result, index) => {
747
+ html += `
748
+ <div class="card mb-3">
749
+ <div class="card-header d-flex justify-content-between align-items-center">
750
+ <h6 class="mb-0">
751
+ <i class="fas fa-envelope"></i> ${result.type ? result.type.replace('_', ' ').toUpperCase() : 'Email'} ${index + 1}
752
+ </h6>
753
+ <span class="badge ${result.success ? 'bg-success' : 'bg-danger'}">
754
+ ${result.success ? 'SUCCESS' : 'FAILED'}
755
+ </span>
756
+ </div>
757
+ <div class="card-body">
758
+ ${result.success ? `
759
+ <div class="row">
760
+ <div class="col-md-6">
761
+ <h6>Email Details:</h6>
762
+ <ul class="list-unstyled">
763
+ <li><strong>Type:</strong> ${result.type || 'N/A'}</li>
764
+ <li><strong>Properties Count:</strong> ${result.properties_count || 0}</li>
765
+ <li><strong>Recommendations Count:</strong> ${result.recommendations_count || 0}</li>
766
+ <li><strong>Peak Time:</strong> ${result.peak_time || 'N/A'}</li>
767
+ <li><strong>Engagement Level:</strong> ${result.engagement_level || 'N/A'}</li>
768
+ </ul>
769
+ </div>
770
+ <div class="col-md-6">
771
+ <h6>AI Insights:</h6>
772
+ <ul class="list-unstyled">
773
+ <li><strong>Personality Type:</strong> ${result.ai_insights?.personality_type || 'N/A'}</li>
774
+ <li><strong>Decision Style:</strong> ${result.ai_insights?.decision_making_style || 'N/A'}</li>
775
+ <li><strong>Urgency Level:</strong> ${result.ai_insights?.urgency_level || 'N/A'}</li>
776
+ <li><strong>Peak Activity:</strong> ${result.ai_insights?.peak_time || 'N/A'}</li>
777
+ </ul>
778
+ </div>
779
+ </div>
780
+ <div class="mt-3">
781
+ <h6>Email Content Preview:</h6>
782
+ <div class="alert alert-light">
783
+ <small>This email would be sent to the customer based on their tracking data and AI analysis. The content is personalized based on their viewing behavior, preferences, and engagement patterns.</small>
784
+ </div>
785
+ </div>
786
+ ` : `
787
+ <div class="alert alert-danger">
788
+ <strong>Error:</strong> ${result.error || 'Unknown error occurred'}
789
+ </div>
790
+ `}
791
+ </div>
792
+ </div>
793
+ `;
794
+ });
795
+ } else {
796
+ html += '<div class="alert alert-warning">No email previews available</div>';
797
+ }
798
+
799
+ document.getElementById('emailPreviewContainer').innerHTML = html;
800
+ }
801
+
802
+ function displayBehavioralEmailPreview(data, title) {
803
+ let html = `<h5><i class="fas fa-envelope"></i> ${title} Preview</h5>`;
804
+
805
+ html += `
806
+ <div class="card">
807
+ <div class="card-header">
808
+ <h6 class="mb-0">
809
+ <i class="fas fa-user-cog"></i> Behavioral Trigger Email
810
+ </h6>
811
+ </div>
812
+ <div class="card-body">
813
+ <div class="row">
814
+ <div class="col-md-6">
815
+ <h6>Trigger Details:</h6>
816
+ <ul class="list-unstyled">
817
+ <li><strong>Trigger Type:</strong> ${data.trigger_type || 'Behavioral'}</li>
818
+ <li><strong>Customer ID:</strong> ${data.customer_id || currentCustomerId}</li>
819
+ <li><strong>Status:</strong> ${data.success ? 'SUCCESS' : 'FAILED'}</li>
820
+ </ul>
821
+ </div>
822
+ <div class="col-md-6">
823
+ <h6>Analysis Basis:</h6>
824
+ <ul class="list-unstyled">
825
+ <li><strong>Viewing Behavior:</strong> Based on customer's property viewing patterns</li>
826
+ <li><strong>Engagement Level:</strong> ${analysisData?.data?.summary?.engagement_score || 'N/A'}%</li>
827
+ <li><strong>Peak Time:</strong> ${analysisData?.data?.analytics?.viewing_patterns?.peak_viewing_time || 'N/A'}</li>
828
+ </ul>
829
+ </div>
830
+ </div>
831
+ <div class="mt-3">
832
+ <h6>Email Content Preview:</h6>
833
+ <div class="alert alert-light">
834
+ <small>This behavioral email is triggered based on the customer's activity patterns and engagement level. It provides personalized recommendations and follow-up actions based on their browsing behavior.</small>
835
+ </div>
836
+ </div>
837
+ </div>
838
+ </div>
839
+ `;
840
+
841
+ document.getElementById('emailPreviewContainer').innerHTML = html;
842
+ }
843
+
844
+ // Email Testing Functions
845
+ async function testAllEmails() {
846
+ if (!analysisData) {
847
+ showError('Please analyze a customer first to test emails');
848
+ return;
849
+ }
850
+
851
+ showSuccess('Testing all email types...');
852
+
853
+ try {
854
+ const response = await fetch(`/api/email-automation/${currentCustomerId}`, {
855
+ method: 'POST',
856
+ headers: {
857
+ 'Content-Type': 'application/json'
858
+ },
859
+ body: JSON.stringify({
860
+ email: document.getElementById('testEmail').value || '[email protected]',
861
+ email_type: 'all'
862
+ })
863
+ });
864
+
865
+ const data = await response.json();
866
+
867
+ if (data.success) {
868
+ showSuccess('All email tests completed successfully!');
869
+ loadEmailLogs();
870
+ } else {
871
+ showError('Email tests failed: ' + (data.error || 'Unknown error'));
872
+ }
873
+ } catch (error) {
874
+ showError('Error testing emails: ' + error.message);
875
+ }
876
+ }
877
+
878
+ async function sendAllEmails() {
879
+ if (!analysisData) {
880
+ showError('Please analyze a customer first to send emails');
881
+ return;
882
+ }
883
+
884
+ if (confirm('Are you sure you want to send all emails to the customer?')) {
885
+ showSuccess('Sending all emails...');
886
+
887
+ try {
888
+ const response = await fetch(`/api/email-automation/${currentCustomerId}`, {
889
+ method: 'POST',
890
+ headers: {
891
+ 'Content-Type': 'application/json'
892
+ },
893
+ body: JSON.stringify({
894
+ email: document.getElementById('testEmail').value || '[email protected]',
895
+ email_type: 'all'
896
+ })
897
+ });
898
+
899
+ const data = await response.json();
900
+
901
+ if (data.success) {
902
+ showSuccess('All emails sent successfully!');
903
+ loadEmailLogs();
904
+ } else {
905
+ showError('Failed to send emails: ' + (data.error || 'Unknown error'));
906
+ }
907
+ } catch (error) {
908
+ showError('Error sending emails: ' + error.message);
909
+ }
910
+ }
911
+ }
912
+
913
+ async function getEmailStatus() {
914
+ try {
915
+ const response = await fetch('/api/list-emails');
916
+ const data = await response.json();
917
+
918
+ if (data.success) {
919
+ const emails = data.emails || [];
920
+ showSuccess(`Email Status: ${emails.length} total emails, ${emails.filter(e => e.success !== false).length} successful, ${emails.filter(e => e.success === false).length} failed`);
921
+ loadEmailLogs();
922
+ } else {
923
+ showError('Failed to get email status');
924
+ }
925
+ } catch (error) {
926
+ showError('Error getting email status: ' + error.message);
927
+ }
928
+ }
929
+
930
+ async function loadEmailLogs() {
931
+ try {
932
+ const response = await fetch('/api/list-emails');
933
+ const data = await response.json();
934
+
935
+ if (data.success) {
936
+ const emails = data.emails || [];
937
+
938
+ document.getElementById('emailLogs').innerHTML = `
939
+ ${emails.slice(0, 10).map(email => `
940
+ <div class="alert ${email.success !== false ? 'alert-success' : 'alert-danger'}">
941
+ <div class="d-flex justify-content-between">
942
+ <strong>${email.filename || 'Email Log'}</strong>
943
+ <small>${new Date(email.created || Date.now()).toLocaleString()}</small>
944
+ </div>
945
+ <div class="mt-2">
946
+ <small><strong>Type:</strong> ${email.email_type || 'Unknown'}</small><br>
947
+ <small><strong>Recipient:</strong> ${email.recipient || 'N/A'}</small><br>
948
+ <small><strong>Subject:</strong> ${email.subject || 'N/A'}</small>
949
+ </div>
950
+ </div>
951
+ `).join('')}
952
+ `;
953
+ } else {
954
+ document.getElementById('emailLogs').innerHTML = '<div class="alert alert-warning">No email logs found</div>';
955
+ }
956
+ } catch (error) {
957
+ console.error('Error loading email logs:', error);
958
+ document.getElementById('emailLogs').innerHTML = '<div class="alert alert-danger">Error loading email logs</div>';
959
+ }
960
+ }
961
+
962
+ // Utility Functions
963
+ function formatDuration(seconds) {
964
+ const hours = Math.floor(seconds / 3600);
965
+ const minutes = Math.floor((seconds % 3600) / 60);
966
+ return `${hours}h ${minutes}m`;
967
+ }
968
+
969
+ function formatPrice(price) {
970
+ return new Intl.NumberFormat('en-US').format(price);
971
+ }
972
+
973
+ function showSuccess(message) {
974
+ const alert = document.createElement('div');
975
+ alert.className = 'alert alert-success alert-dismissible fade show position-fixed';
976
+ alert.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 400px;';
977
+ alert.innerHTML = `
978
+ <i class="fas fa-check-circle"></i>
979
+ ${message}
980
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
981
+ `;
982
+ document.body.appendChild(alert);
983
+
984
+ setTimeout(() => {
985
+ if (alert.parentNode) {
986
+ alert.remove();
987
+ }
988
+ }, 5000);
989
+ }
990
+
991
+ function showError(message) {
992
+ const alert = document.createElement('div');
993
+ alert.className = 'alert alert-danger alert-dismissible fade show position-fixed';
994
+ alert.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 400px;';
995
+ alert.innerHTML = `
996
+ <i class="fas fa-exclamation-circle"></i>
997
+ ${message}
998
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
999
+ `;
1000
+ document.body.appendChild(alert);
1001
+
1002
+ setTimeout(() => {
1003
+ if (alert.parentNode) {
1004
+ alert.remove();
1005
+ }
1006
+ }, 5000);
1007
+ }
1008
+
1009
+ // Initialize
1010
+ document.addEventListener('DOMContentLoaded', function() {
1011
+ console.log('Perfect AI Customer Analysis & Email Automation Dashboard loaded');
1012
+ });
1013
+ </script>
1014
+ </body>
1015
+ </html>
templates/unified_ai_dashboard.html CHANGED
@@ -466,9 +466,14 @@
466
  }
467
  }
468
 
469
- function displayAnalysis(data) {
470
- // Lead Status
 
 
471
  const leadQual = data.lead_qualification;
 
 
 
472
  document.getElementById('leadStatus').innerHTML = `
473
  <div class="status-badge status-${leadQual.lead_status.toLowerCase()}">
474
  ${leadQual.lead_status}
@@ -481,16 +486,14 @@
481
  `;
482
 
483
  // Key Metrics
484
- const summary = data.summary;
485
  document.getElementById('totalViews').textContent = summary.total_views;
486
  document.getElementById('totalDuration').textContent = formatDuration(summary.total_duration);
487
  document.getElementById('engagementScore').textContent = Math.round(summary.engagement_score);
488
 
489
- const conversionProb = data.analytics.conversion_probability;
490
  document.getElementById('conversionProbability').textContent = Math.round(conversionProb.final_probability) + '%';
491
 
492
  // Property Preferences
493
- const analytics = data.analytics;
494
  document.getElementById('propertyPreferences').innerHTML = `
495
  <ul class="list-unstyled">
496
  ${analytics.preferred_property_types.map(type => `<li><i class="fas fa-check-circle text-success"></i> ${type}</li>`).join('')}
 
466
  }
467
  }
468
 
469
+ function displayAnalysis(responseData) {
470
+ // Handle the actual API response structure
471
+ const data = responseData.data;
472
+ const analytics = data.analytics;
473
  const leadQual = data.lead_qualification;
474
+ const summary = data.summary;
475
+
476
+ // Lead Status
477
  document.getElementById('leadStatus').innerHTML = `
478
  <div class="status-badge status-${leadQual.lead_status.toLowerCase()}">
479
  ${leadQual.lead_status}
 
486
  `;
487
 
488
  // Key Metrics
 
489
  document.getElementById('totalViews').textContent = summary.total_views;
490
  document.getElementById('totalDuration').textContent = formatDuration(summary.total_duration);
491
  document.getElementById('engagementScore').textContent = Math.round(summary.engagement_score);
492
 
493
+ const conversionProb = analytics.conversion_probability;
494
  document.getElementById('conversionProbability').textContent = Math.round(conversionProb.final_probability) + '%';
495
 
496
  // Property Preferences
 
497
  document.getElementById('propertyPreferences').innerHTML = `
498
  <ul class="list-unstyled">
499
  ${analytics.preferred_property_types.map(type => `<li><i class="fas fa-check-circle text-success"></i> ${type}</li>`).join('')}