-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2349 lines (1969 loc) · 82.5 KB
/
Copy pathscript.js
File metadata and controls
2349 lines (1969 loc) · 82.5 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
// // QuanTara Finance Dashboard JavaScript
// // Configuration
// const API_BASE = 'http://127.0.0.1:5000';
// // Global variables
// let revenueChart = null;
// let stockChart = null;
// let corpSelectedFile = null;
// // DOM utility functions
// const $ = (id) => document.getElementById(id);
// const show = (el) => el.classList.remove('hidden');
// const hide = (el) => el.classList.add('hidden');
// const addClass = (el, className) => el.classList.add(className);
// const removeClass = (el, className) => el.classList.remove(className);
// // Loading spinner utilities
// const showSpinner = () => show($('loadingSpinner'));
// const hideSpinner = () => hide($('loadingSpinner'));
// // Value formatting utilities
// const formatCurrency = (value, currency = '$') => {
// if (value == null || value === '—') return '—';
// if (typeof value === 'string') return value;
// return `${currency}${Number(value).toLocaleString()}`;
// };
// const formatPercentage = (value) => {
// if (value == null || value === '—') return '—';
// if (typeof value === 'string') return value;
// return `${Number(value).toFixed(2)}%`;
// };
// const valOrDash = (val) => val != null ? val : '—';
// // File utilities
// const fileIsCSV = (file) => file && /\.csv$/i.test(file.name);
// const getCurrency = (ticker) => {
// const t = (ticker || '').toUpperCase();
// if (t.endsWith('.NS') || t.endsWith('.BO')) return '₹';
// if (t.endsWith('.L')) return '£';
// if (t.endsWith('.TO')) return 'C$';
// return '$';
// };
// // Animation utilities
// const fadeIn = (element) => {
// element.classList.add('fade-in');
// setTimeout(() => element.classList.remove('fade-in'), 500);
// };
// const addGlowEffect = (element) => {
// element.classList.add('glow-effect');
// setTimeout(() => element.classList.remove('glow-effect'), 300);
// };
// // Tab Management System
// class TabManager {
// constructor() {
// this.activeTab = 'corporate';
// this.init();
// }
// init() {
// // Get all tab buttons and panels
// this.tabButtons = document.querySelectorAll('.tab');
// this.panels = {
// corporate: $('panel-corporate'),
// news: $('panel-news'),
// stock: $('panel-stock'),
// industry: $('panel-industry'),
// summarization: $('panel-summarization'),
// whatif: $('panel-whatif'),
// market: $('panel-market')
// };
// // Add event listeners to tab buttons
// this.tabButtons.forEach(button => {
// button.addEventListener('click', () => {
// const tabName = button.dataset.tab;
// this.switchTab(tabName);
// addGlowEffect(button);
// });
// });
// }
// switchTab(tabName) {
// if (!this.panels[tabName]) return;
// // Hide all panels
// Object.values(this.panels).forEach(panel => {
// panel.classList.remove('panel-active');
// panel.classList.add('hidden');
// });
// // Remove active class from all tabs
// this.tabButtons.forEach(button => {
// button.classList.remove('tab-active');
// });
// // Show selected panel and activate tab
// const selectedPanel = this.panels[tabName];
// const selectedTab = document.querySelector(`[data-tab="${tabName}"]`);
// selectedPanel.classList.remove('hidden');
// selectedPanel.classList.add('panel-active');
// selectedTab.classList.add('tab-active');
// this.activeTab = tabName;
// fadeIn(selectedPanel);
// // Smooth scroll to top
// window.scrollTo({ top: 0, behavior: 'smooth' });
// }
// }
// // API Status Manager
// class ApiStatusManager {
// constructor() {
// this.badge = $('apiStatusBadge');
// this.checkStatus();
// this.startPeriodicCheck();
// }
// async checkStatus() {
// try {
// const response = await fetch(`${API_BASE}/api-status`, {
// method: 'GET',
// timeout: 5000
// });
// if (response.ok) {
// const data = await response.json();
// this.updateStatus(data.status === 'connected' ? 'connected' : 'degraded');
// } else {
// this.updateStatus('degraded');
// }
// } catch (error) {
// this.updateStatus('offline');
// }
// }
// updateStatus(status) {
// this.badge.className = 'status-badge ' + status;
// switch (status) {
// case 'connected':
// this.badge.textContent = 'API: Connected';
// break;
// case 'degraded':
// this.badge.textContent = 'API: Degraded';
// break;
// case 'offline':
// this.badge.textContent = 'API: Offline';
// break;
// }
// }
// startPeriodicCheck() {
// setInterval(() => this.checkStatus(), 30000); // Check every 30 seconds
// }
// }
// // Corporate Analyzer Manager
// class CorporateAnalyzer {
// constructor() {
// this.init();
// }
// init() {
// $('corpFile').addEventListener('change', this.handleFileChange.bind(this));
// $('btnParseCompanies').addEventListener('click', this.parseCompanies.bind(this));
// $('btnAnalyzeCorporate').addEventListener('click', this.analyzeCorporate.bind(this));
// }
// handleFileChange(event) {
// corpSelectedFile = event.target.files[0] || null;
// const parseBtn = $('btnParseCompanies');
// if (fileIsCSV(corpSelectedFile)) {
// parseBtn.disabled = false;
// parseBtn.style.opacity = '1';
// } else {
// parseBtn.disabled = true;
// parseBtn.style.opacity = '0.5';
// $('corpCompany').innerHTML = '<option value="">Select Company (CSV only)</option>';
// }
// }
// async parseCompanies() {
// if (!corpSelectedFile || !fileIsCSV(corpSelectedFile)) {
// alert('Please select a CSV file first.');
// return;
// }
// const btn = $('btnParseCompanies');
// const originalText = btn.textContent;
// btn.textContent = 'Loading...';
// btn.disabled = true;
// try {
// const formData = new FormData();
// formData.append('file', corpSelectedFile);
// const response = await fetch(`${API_BASE}/parse-csv-companies`, {
// method: 'POST',
// body: formData
// });
// const data = await response.json();
// if (!response.ok) {
// throw new Error(data.error || 'Failed to parse companies');
// }
// // Populate company dropdown
// const select = $('corpCompany');
// const options = ['<option value="">Select Company</option>'];
// (data.companies || []).forEach(company => {
// options.push(`<option value="${company}">${company}</option>`);
// });
// select.innerHTML = options.join('');
// } catch (error) {
// alert(`Error: ${error.message}`);
// } finally {
// btn.textContent = originalText;
// btn.disabled = false;
// }
// }
// async analyzeCorporate() {
// if (!corpSelectedFile) {
// alert('Please select a file to analyze.');
// return;
// }
// const btn = $('btnAnalyzeCorporate');
// const originalText = btn.textContent;
// btn.textContent = 'Analyzing...';
// btn.disabled = true;
// showSpinner();
// try {
// const formData = new FormData();
// formData.append('file', corpSelectedFile);
// const selectedCompany = $('corpCompany').value;
// if (selectedCompany) {
// formData.append('company', selectedCompany);
// }
// const response = await fetch(`${API_BASE}/analyze-corporate`, {
// method: 'POST',
// body: formData
// });
// const data = await response.json();
// if (!response.ok) {
// throw new Error(data.error || 'Analysis failed');
// }
// this.displayResults(data);
// } catch (error) {
// alert(`Error: ${error.message}`);
// } finally {
// btn.textContent = originalText;
// btn.disabled = false;
// hideSpinner();
// }
// }
// displayResults(data) {
// // Update summary
// $('corpSummary').textContent = data.summary || 'Analysis completed successfully.';
// // Update KPIs
// const kpis = data.kpis || {};
// $('kpiRevenue').textContent = formatCurrency(kpis["Total Revenue"]);
// $('kpiIncome').textContent = formatCurrency(kpis["Net Income"]);
// $('kpiEPS').textContent = valOrDash(kpis["EPS"]);
// $('kpiOM').textContent = formatPercentage(kpis["Operating Margin"]);
// // Update chart
// this.updateRevenueChart(data.chartData);
// // Update risks and opportunities
// this.updateInsightLists(data.risks, data.opportunities);
// // Update insight card
// const insightCard = data.insightCard || {};
// $('corpInsightTitle').textContent = insightCard.title || '';
// $('corpInsightExp').textContent = insightCard.explanation || '';
// // Show results with animation
// const resultContainer = $('corpResult');
// show(resultContainer);
// fadeIn(resultContainer);
// }
// updateRevenueChart(chartData) {
// const chart = chartData || {};
// const labels = chart.labels || [];
// const revenueData = chart.revenueData || [];
// const ctx = $('revenueChart').getContext('2d');
// // Destroy existing chart
// if (revenueChart) {
// revenueChart.destroy();
// }
// revenueChart = new Chart(ctx, {
// type: 'line',
// data: {
// labels,
// datasets: [{
// label: 'Revenue',
// data: revenueData,
// borderColor: '#8B7EC8',
// backgroundColor: 'rgba(139, 126, 200, 0.1)',
// fill: true,
// tension: 0.4,
// pointBackgroundColor: '#A594D1',
// pointBorderColor: '#8B7EC8',
// pointHoverBackgroundColor: '#A594D1',
// pointHoverBorderColor: '#ffffff'
// }]
// },
// options: {
// responsive: true,
// maintainAspectRatio: false,
// plugins: {
// legend: {
// labels: {
// color: '#b4b4b4'
// }
// },
// tooltip: {
// mode: 'index',
// intersect: false,
// backgroundColor: 'rgba(26, 26, 26, 0.95)',
// titleColor: '#ffffff',
// bodyColor: '#b4b4b4',
// borderColor: '#8B7EC8',
// borderWidth: 1
// }
// },
// scales: {
// x: {
// ticks: { color: '#666666' },
// grid: { color: 'rgba(139, 126, 200, 0.1)' }
// },
// y: {
// ticks: { color: '#666666' },
// grid: { color: 'rgba(139, 126, 200, 0.1)' }
// }
// }
// }
// });
// }
// updateInsightLists(risks, opportunities) {
// const risksList = $('corpRisks');
// const oppsList = $('corpOpps');
// // Convert markdown lists to HTML
// const convertToHTML = (mdText = '') => {
// return mdText.split('\n')
// .filter(line => line.trim().startsWith('-'))
// .map(line => `<li>${line.replace(/^-\s*/, '')}</li>`)
// .join('');
// };
// risksList.innerHTML = convertToHTML(risks);
// oppsList.innerHTML = convertToHTML(opportunities);
// }
// }
// // News Analyzer Manager
// class NewsAnalyzer {
// constructor() {
// this.init();
// }
// init() {
// $('btnFetchNews').addEventListener('click', this.fetchNews.bind(this));
// }
// async fetchNews() {
// const company = $('newsCompany').value.trim();
// if (!company) {
// alert('Please enter a company name.');
// return;
// }
// const resultContainer = $('newsResult');
// resultContainer.innerHTML = '<div class="loading-text">Fetching news...</div>';
// try {
// const response = await fetch(`${API_BASE}/live-news`, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ company })
// });
// const data = await response.json();
// if (!response.ok) {
// throw new Error(data.error || 'Failed to fetch news');
// }
// this.displayNewsResults(data);
// } catch (error) {
// resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// }
// }
// displayNewsResults(data) {
// const sentiment = data.sentiment || 'Neutral';
// const sentimentClass = sentiment === 'Positive' ? 'success' :
// sentiment === 'Negative' ? 'error' : 'info';
// const articles = (data.articles || []).map(article => `
// <div class="news-article">
// <a href="${article.url}" target="_blank" class="article-link">
// ${article.title || 'Untitled'}
// </a>
// <div class="article-meta">
// <span class="article-source">${article.source || 'Unknown'}</span>
// <span class="article-date">${new Date(article.publishedAt).toLocaleDateString()}</span>
// </div>
// </div>
// `).join('');
// const resultContainer = $('newsResult');
// resultContainer.innerHTML = `
// <div class="sentiment-analysis">
// <div class="sentiment-badge ${sentimentClass}">${sentiment}</div>
// <div class="sentiment-summary">${data.summary || ''}</div>
// </div>
// <div class="articles-section">
// <h3 class="section-title">Recent Articles</h3>
// <div class="articles-list">${articles}</div>
// </div>
// `;
// fadeIn(resultContainer);
// }
// }
// // Stock Analyzer Manager
// class StockAnalyzer {
// constructor() {
// this.init();
// }
// init() {
// $('btnStockAnalyze').addEventListener('click', this.analyzeStock.bind(this));
// }
// async analyzeStock() {
// const ticker = $('stockTicker').value.trim();
// const period = $('stockPeriod').value;
// const interval = $('stockInterval').value;
// const question = $('stockQuestion').value.trim();
// if (!ticker) {
// alert('Please enter a stock ticker.');
// return;
// }
// const resultContainer = $('stockResult');
// resultContainer.innerHTML = '<div class="loading-text">Analyzing stock data...</div>';
// show(resultContainer);
// try {
// const response = await fetch(`${API_BASE}/stock-analysis`, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ ticker, period, interval, question })
// });
// const data = await response.json();
// if (!response.ok) {
// throw new Error(data.error || 'Analysis failed');
// }
// this.displayStockResults(data);
// } catch (error) {
// resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// }
// }
// displayStockResults(data) {
// const metrics = data.metrics || {};
// const forecast = data.forecast || [];
// const currency = getCurrency(data.ticker);
// // Generate forecast table
// const forecastTable = forecast.map(item => `
// <tr>
// <td>${item.day}</td>
// <td class="text-right">${currency}${item.price}</td>
// <td class="text-right">${currency}${item.lower}</td>
// <td class="text-right">${currency}${item.upper}</td>
// </tr>
// `).join('');
// const resultContainer = $('stockResult');
// resultContainer.innerHTML = `
// ${data.qa ? `
// <div class="qa-section">
// <h3 class="section-title">Analysis Response</h3>
// <div class="qa-response">${data.qa}</div>
// </div>
// ` : ''}
// <div class="stock-metrics-grid">
// <div class="metric-card">
// <div class="metric-label">Current Price</div>
// <div class="metric-value">${currency}${valOrDash(metrics.price)}</div>
// <div class="metric-change ${(metrics.changePct || 0) >= 0 ? 'positive' : 'negative'}">
// ${formatPercentage(metrics.changePct)}
// </div>
// </div>
// <div class="metric-card">
// <div class="metric-label">RSI (14)</div>
// <div class="metric-value">${valOrDash(metrics.RSI14)}</div>
// <div class="rsi-indicator ${this.getRSIClass(metrics.RSI14)}">${this.getRSIStatus(metrics.RSI14)}</div>
// </div>
// <div class="metric-card">
// <div class="metric-label">SMA 20</div>
// <div class="metric-value">${currency}${valOrDash(metrics.SMA20)}</div>
// </div>
// <div class="metric-card">
// <div class="metric-label">SMA 50</div>
// <div class="metric-value">${currency}${valOrDash(metrics.SMA50)}</div>
// </div>
// </div>
// <div class="chart-container">
// <h3 class="section-title">Price History</h3>
// <canvas id="stockChart"></canvas>
// </div>
// <div class="forecast-section">
// <h3 class="section-title">Price Forecast (Next 5 Sessions)</h3>
// <table class="forecast-table">
// <thead>
// <tr>
// <th>Day</th>
// <th>Price</th>
// <th>Lower Bound</th>
// <th>Upper Bound</th>
// </tr>
// </thead>
// <tbody>${forecastTable}</tbody>
// </table>
// </div>
// `;
// // Update stock chart
// this.updateStockChart(data.history);
// fadeIn(resultContainer);
// }
// getRSIClass(rsi) {
// if (rsi >= 70) return 'overbought';
// if (rsi <= 30) return 'oversold';
// return 'neutral';
// }
// getRSIStatus(rsi) {
// if (rsi >= 70) return 'Overbought';
// if (rsi <= 30) return 'Oversold';
// return 'Neutral';
// }
// updateStockChart(historyData) {
// const history = historyData || {};
// const labels = history.labels || [];
// const closeData = history.close || [];
// const ctx = $('stockChart').getContext('2d');
// if (stockChart) {
// stockChart.destroy();
// }
// stockChart = new Chart(ctx, {
// type: 'line',
// data: {
// labels,
// datasets: [{
// label: 'Close Price',
// data: closeData,
// borderColor: '#8B7EC8',
// backgroundColor: 'rgba(139, 126, 200, 0.1)',
// fill: true,
// tension: 0.2,
// pointRadius: 1,
// pointHoverRadius: 4
// }]
// },
// options: {
// responsive: true,
// maintainAspectRatio: false,
// plugins: {
// legend: { display: false },
// tooltip: {
// backgroundColor: 'rgba(26, 26, 26, 0.95)',
// titleColor: '#ffffff',
// bodyColor: '#b4b4b4',
// borderColor: '#8B7EC8',
// borderWidth: 1
// }
// },
// scales: {
// x: {
// ticks: { color: '#666666' },
// grid: { color: 'rgba(139, 126, 200, 0.1)' }
// },
// y: {
// ticks: { color: '#666666' },
// grid: { color: 'rgba(139, 126, 200, 0.1)' }
// }
// }
// }
// });
// }
// }
// // Industry Analyzer Manager
// class IndustryAnalyzer {
// constructor() {
// this.init();
// }
// init() {
// $('btnIndustryAnalyze').addEventListener('click', this.analyzeIndustry.bind(this));
// }
// async analyzeIndustry() {
// const industry = $('industryName').value.trim();
// const inputs = $('industryInputs').value.trim();
// if (!industry) {
// alert('Please enter an industry name.');
// return;
// }
// const resultContainer = $('industryResult');
// resultContainer.innerHTML = '<div class="loading-text">Analyzing industry...</div>';
// try {
// const response = await fetch(`${API_BASE}/industry-analyze`, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ industry, inputs })
// });
// const data = await response.json();
// if (!response.ok) {
// throw new Error(data.error || 'Analysis failed');
// }
// this.displayIndustryResults(data);
// } catch (error) {
// resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// }
// }
// displayIndustryResults(data) {
// const resultContainer = $('industryResult');
// const createList = (items = []) => {
// return items.map(item => `<li>${item}</li>`).join('');
// };
// resultContainer.innerHTML = `
// <div class="industry-analysis">
// <div class="analysis-section">
// <h3 class="section-title">Overview</h3>
// <p class="analysis-text">${data.overview || 'No overview available.'}</p>
// </div>
// <div class="analysis-section">
// <h3 class="section-title">Key Drivers</h3>
// <ul class="analysis-list">${createList(data.drivers)}</ul>
// </div>
// <div class="analysis-section">
// <h3 class="section-title">Risk Factors</h3>
// <ul class="analysis-list risks">${createList(data.risks)}</ul>
// </div>
// <div class="analysis-section">
// <h3 class="section-title">Outlook</h3>
// <p class="analysis-text">${data.outlook || 'No outlook available.'}</p>
// </div>
// <div class="analysis-section">
// <h3 class="section-title">Companies to Watch</h3>
// <ul class="analysis-list watchlist">${createList(data.watchlist)}</ul>
// </div>
// </div>
// `;
// fadeIn(resultContainer);
// }
// }
// // Summarization Manager
// // class SummarizationManager {
// // constructor() {
// // this.init();
// // }
// // init() {
// // $('btnSummarizeFile').addEventListener('click', this.summarizeFile.bind(this));
// // $('btnSummarizeText').addEventListener('click', this.summarizeText.bind(this));
// // }
// // async summarizeFile() {
// // const file = $('sumFile').files[0];
// // const style = $('sumStyle').value;
// // if (!file) {
// // alert('Please select a file to summarize.');
// // return;
// // }
// // const resultContainer = $('sumResult');
// // resultContainer.innerHTML = '<div class="loading-text">Summarizing file...</div>';
// // try {
// // const formData = new FormData();
// // formData.append('file', file);
// // formData.append('style', style);
// // const response = await fetch(`${API_BASE}/summarize`, {
// // method: 'POST',
// // body: formData
// // });
// // const data = await response.json();
// // if (!response.ok) {
// // throw new Error(data.error || 'Summarization failed');
// // }
// // resultContainer.innerHTML = `
// // <div class="summary-result">
// // <h3 class="section-title">Summary</h3>
// // <div class="summary-content">${data.summary}</div>
// // </div>
// // `;
// // fadeIn(resultContainer);
// // } catch (error) {
// // resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// // }
// // }
// // async summarizeText() {
// // const text = $('sumText').value.trim();
// // const style = $('sumStyle').value;
// // if (!text) {
// // alert('Please enter text to summarize.');
// // return;
// // }
// // const resultContainer = $('sumResult');
// // resultContainer.innerHTML = '<div class="loading-text">Summarizing text...</div>';
// // try {
// // const response = await fetch(`${API_BASE}/summarize`, {
// // method: 'POST',
// // headers: { 'Content-Type': 'application/json' },
// // body: JSON.stringify({ text, style })
// // });
// // const data = await response.json();
// // if (!response.ok) {
// // throw new Error(data.error || 'Summarization failed');
// // }
// // resultContainer.innerHTML = `
// // <div class="summary-result">
// // <h3 class="section-title">Summary</h3>
// // <div class="summary-content">${data.summary}</div>
// // </div>
// // `;
// // fadeIn(resultContainer);
// // } catch (error) {
// // resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// // }
// // }
// // }
// class SummarizationManager {
// constructor() {
// this.init();
// }
// init() {
// $('btnSummarizeFile').addEventListener('click', this.summarizeFile.bind(this));
// $('btnSummarizeText').addEventListener('click', this.summarizeText.bind(this));
// }
// /**
// * This function takes the raw text from the server and formats it into pretty HTML.
// * @param {string} summaryText The raw text string from the API response.
// * @returns {string} An HTML string formatted as a list with bold headings.
// */
// formatSummary(summaryText) {
// // Splits the text into points based on the "* **" pattern
// const points = summaryText.split('* **').filter(point => point.trim() !== '');
// if (points.length === 0 && summaryText.length > 0) {
// return `<p>${summaryText}</p>`; // Fallback for plain paragraph text
// }
// const listItems = points.map(point => {
// const titleEndIndex = point.indexOf('**');
// if (titleEndIndex !== -1) {
// // Extracts the heading and the description text
// const title = point.substring(0, titleEndIndex).trim();
// const description = point.substring(titleEndIndex + 2).replace(/^:\s*/, '').trim();
// // Creates a list item with a bolded heading
// return `<li><strong>${title}:</strong> ${description}</li>`;
// }
// return `<li>${point.trim()}</li>`; // Fallback for items without a heading
// }).join('');
// return `<ul>${listItems}</ul>`;
// }
// async summarizeFile() {
// const file = $('sumFile').files[0];
// const style = $('sumStyle').value;
// if (!file) {
// alert('Please select a file to summarize.');
// return;
// }
// const resultContainer = $('sumResult');
// resultContainer.innerHTML = '<div class="loading-text">Summarizing file...</div>';
// try {
// const formData = new FormData();
// formData.append('file', file);
// formData.append('style', style);
// const response = await fetch(`${API_BASE}/summarize`, {
// method: 'POST',
// body: formData
// });
// if (!response.ok) {
// const errorText = await response.text();
// throw new Error(errorText || `Request failed with status ${response.status}`);
// }
// const summaryText = await response.text();
// // ✨ Use the new function here to format the text before displaying it
// const formattedSummary = this.formatSummary(summaryText);
// resultContainer.innerHTML = `
// <div class="summary-result">
// <h3 class="section-title">Summary</h3>
// <div class="summary-content">${formattedSummary}</div>
// </div>
// `;
// // fadeIn(resultContainer); // Uncomment if you have this function
// } catch (error) {
// resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// }
// }
// async summarizeText() {
// const text = $('sumText').value.trim();
// const style = $('sumStyle').value;
// if (!text) {
// alert('Please enter text to summarize.');
// return;
// }
// const resultContainer = $('sumResult');
// resultContainer.innerHTML = '<div class="loading-text">Summarizing text...</div>';
// try {
// const response = await fetch(`${API_BASE}/summarize`, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ text, style })
// });
// if (!response.ok) {
// const errorText = await response.text();
// throw new Error(errorText || `Request failed with status ${response.status}`);
// }
// const summaryText = await response.text();
// // ✨ Use the new function here to format the text before displaying it
// const formattedSummary = this.formatSummary(summaryText);
// resultContainer.innerHTML = `
// <div class="summary-result">
// <h3 class="section-title">Summary</h3>
// <div class="summary-content">${formattedSummary}</div>
// </div>
// `;
// // fadeIn(resultContainer); // Uncomment if you have this function
// } catch (error) {
// resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// }
// }
// }
// // Add this at the end of your script to ensure it runs after the page loads
// document.addEventListener('DOMContentLoaded', () => {
// new SummarizationManager();
// });
// // What-If Analyzer Manager
// class WhatIfAnalyzer {
// constructor() {
// this.init();
// }
// init() {
// $('btnWhatIf').addEventListener('click', this.runScenario.bind(this));
// }
// async runScenario() {
// const query = $('whatIfQuery').value.trim();
// if (!query) {
// alert('Please enter a what-if scenario.');
// return;
// }
// const resultContainer = $('whatIfResult');
// resultContainer.innerHTML = '<div class="loading-text">Running scenario analysis...</div>';
// try {
// const response = await fetch(`${API_BASE}/what-if-sandbox`, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ query })
// });
// const data = await response.json();
// if (!response.ok) {
// throw new Error(data.error || 'Scenario analysis failed');
// }
// resultContainer.innerHTML = `
// <div class="whatif-result">
// <h3 class="section-title">Scenario Analysis</h3>
// <div class="scenario-content">${data.answer}</div>
// </div>
// `;
// fadeIn(resultContainer);
// } catch (error) {
// resultContainer.innerHTML = `<div class="error-message">Error: ${error.message}</div>`;
// }
// }
// }
// // Market Intelligence Manager