-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.cpp
More file actions
752 lines (646 loc) · 30.9 KB
/
Copy pathsettings.cpp
File metadata and controls
752 lines (646 loc) · 30.9 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
/**
* @file settings.cpp
* @brief Implementation of the Settings widget for user preferences, password management, and data export.
*
* This file handles:
* - UI setup for theme toggling and password change
* - PDF and CSV export of income, expenses, savings, stocks, and crypto
* - Integration with Income, Expenses, Savings, Stock, and Crypto modules
* - Theme state persistence and logout token deletion
*
* @author Shourya Nundy, Abdullah Ahmad
*/
#include "settings.h"
#include "income.h"
#include "expenses.h"
#include "Savings.h"
#include "stock.h"
#include "crypto.h"
#include <QFile>
#include <QMessageBox>
#include <QDebug>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QSettings>
#include <QLineEdit>
#include <QSqlQuery>
#include <QCryptographicHash>
#include <QPdfWriter>
#include <QPainter>
#include <QFileDialog>
#include <QTextStream>
#include <QPageSize>
#include <QImage>
/**
* @brief Constructs the Settings widget and sets up all controls and layout.
*
* Initializes labels, inputs, buttons, and layout containers.
* Connects signals for theme switch, password change, logout, and exports.
*
* @param parent Optional parent widget.
*/
Settings::Settings(QWidget *parent) : QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *title = new QLabel("Settings", this);
title->setStyleSheet("font-size: 24px; font-weight: bold; margin-bottom: 20px; margin-top: 15px; margin-left: 5px;");
layout->addWidget(title);
QLabel *appearanceLabel = new QLabel("Appearance", this);
appearanceLabel->setStyleSheet("font-size: 20px; font-weight: bold; margin-top: 10px; margin-left: 5px;");
layout->addWidget(appearanceLabel);
QHBoxLayout *themeRow = new QHBoxLayout();
QLabel *themeLabel = new QLabel(" Dark Mode", this);
themeLabel->setStyleSheet("font-size: 18px; margin-left: 5px;");
themeRow->addWidget(themeLabel);
themeRow->addStretch();
themeSwitch = new ToggleSwitch(this);
QSettings settings("BudgetX", "App");
bool darkMode = settings.value("darkMode", false).toBool();
themeSwitch->setChecked(darkMode);
themeRow->addWidget(themeSwitch);
layout->addLayout(themeRow);
connect(themeSwitch, &ToggleSwitch::toggled, this, &Settings::onThemeSwitchChanged);
QLabel *passwordLabel = new QLabel("Change Password", this);
passwordLabel->setStyleSheet("font-size: 20px; font-weight: bold; margin-top: 20px; margin-left: 5px;");
layout->addWidget(passwordLabel);
currentPasswordInput = new QLineEdit(this);
currentPasswordInput->setPlaceholderText("Current Password");
currentPasswordInput->setEchoMode(QLineEdit::Password);
currentPasswordInput->setFixedWidth(300);
currentPasswordInput->setStyleSheet("padding: 10px; border-radius: 8px; border: 1px solid #ccc; margin-left: 5px;");
layout->addWidget(currentPasswordInput);
newPasswordInput = new QLineEdit(this);
newPasswordInput->setPlaceholderText("New Password");
newPasswordInput->setEchoMode(QLineEdit::Password);
newPasswordInput->setFixedWidth(300);
newPasswordInput->setStyleSheet("padding: 10px; border-radius: 8px; border: 1px solid #ccc; margin-left: 5px;");
layout->addWidget(newPasswordInput);
confirmPasswordInput = new QLineEdit(this);
confirmPasswordInput->setPlaceholderText("Confirm New Password");
confirmPasswordInput->setEchoMode(QLineEdit::Password);
confirmPasswordInput->setFixedWidth(300);
confirmPasswordInput->setStyleSheet("padding: 10px; border-radius: 8px; border: 1px solid #ccc; margin-left: 5px;");
layout->addWidget(confirmPasswordInput);
changePasswordButton = new QPushButton("Change Password", this);
changePasswordButton->setFixedWidth(180);
changePasswordButton->setStyleSheet(R"(
QPushButton {
background-color: #3498db;
color: white;
padding: 10px;
border: none;
border-radius: 8px;
font-size: 16px;
margin-left: 5px;
}
QPushButton:hover {
background-color: #2980b9;
}
)");
layout->addWidget(changePasswordButton);
connect(changePasswordButton, &QPushButton::clicked, this, &Settings::handleChangePassword);
logoutButton = new QPushButton("Logout", this);
logoutButton->setFixedWidth(150);
logoutButton->setCursor(Qt::PointingHandCursor);
logoutButton->setStyleSheet(R"(
QPushButton {
background-color: #e74c3c;
color: white;
padding: 10px;
border: none;
border-radius: 8px;
font-size: 16px;
}
QPushButton:hover {
background-color: #c0392b;
}
)");
QWidget *spacer = new QWidget(this);
spacer->setFixedHeight(25);
layout->addWidget(spacer);
QHBoxLayout *logoutRow = new QHBoxLayout();
logoutRow->addStretch();
logoutRow->addWidget(logoutButton);
logoutRow->addStretch();
layout->addLayout(logoutRow);
connect(logoutButton, &QPushButton::clicked, this, &Settings::onLogoutClicked);
QLabel *exportLabel = new QLabel("Export Data", this);
exportLabel->setStyleSheet("font-size: 20px; font-weight: bold; margin-top: 20px; margin-left: 5px;");
layout->addWidget(exportLabel);
QHBoxLayout *exportButtonsLayout = new QHBoxLayout();
exportPdfButton = new QPushButton("Export PDF", this);
exportPdfButton->setStyleSheet("padding: 10px; border-radius: 8px;");
exportExcelButton = new QPushButton("Export Excel", this);
exportExcelButton->setStyleSheet("padding: 10px; border-radius: 8px;");
exportButtonsLayout->addWidget(exportPdfButton);
exportButtonsLayout->addWidget(exportExcelButton);
layout->addLayout(exportButtonsLayout);
connect(exportPdfButton, &QPushButton::clicked, this, &Settings::onExportPdfClicked);
connect(exportExcelButton, &QPushButton::clicked, this, &Settings::onExportExcelClicked);
// Initialize Income object as a regular member variable
m_income = new Income(this);
m_income->hide(); // Keep it hidden as we only need it for chart access
m_expenses = new Expenses(this);
m_expenses->hide(); // Keep it hidden as we only need it for chart access
m_savings = new Savings(this);
m_savings->hide(); // Keep it hidden as we only need it for chart access
m_stock = new Stock(this);
m_stock->hide(); // Keep it hidden as we only need it for chart access
layout->addStretch();
}
/**
* @brief Handles theme toggle event and updates persistent settings.
*
* Stores the theme mode in QSettings and emits `themeChanged()`.
*
* @param checked True for dark mode, false for light mode.
*/
void Settings::onThemeSwitchChanged(bool checked)
{
QSettings settings("BudgetX", "App");
settings.setValue("darkMode", checked);
emit themeChanged(checked);
}
/**
* @brief Clears session token and emits logout signal.
*
* Deletes the local session token file and emits `logoutRequested()` to return to login screen.
*/
void Settings::onLogoutClicked()
{
QFile file("session_token.txt");
if (file.exists()) {
if (!file.remove()) {
QMessageBox::warning(this, "Error", "Failed to remove session token.");
return;
}
}
emit logoutRequested();
}
/**
* @brief Validates and changes the user's password.
*
* Verifies current password, ensures new password is not empty,
* and calls the database manager to update credentials.
*/
void Settings::handleChangePassword()
{
QString current = currentPasswordInput->text();
QString newPass = newPasswordInput->text();
QString confirmPass = confirmPasswordInput->text();
if (current.isEmpty() || newPass.isEmpty() || confirmPass.isEmpty()) {
QMessageBox::warning(this, "Error", "Please fill in all fields.");
return;
}
if (newPass != confirmPass) {
QMessageBox::warning(this, "Error", "New passwords do not match.");
return;
}
QSqlQuery query;
query.prepare("SELECT password FROM users WHERE id = :id");
query.bindValue(":id", DatabaseManager::currentUserId);
if (!query.exec() || !query.next()) {
QMessageBox::warning(this, "Error", "User lookup failed.");
return;
}
QString storedHash = query.value(0).toString();
QString inputHash = QString(QCryptographicHash::hash(current.toUtf8(), QCryptographicHash::Sha256).toHex());
if (storedHash != inputHash) {
QMessageBox::warning(this, "Error", "Current password is incorrect.");
return;
}
QString newHash = QString(QCryptographicHash::hash(newPass.toUtf8(), QCryptographicHash::Sha256).toHex());
QSqlQuery updateQuery;
updateQuery.prepare("UPDATE users SET password = :pass WHERE id = :id");
updateQuery.bindValue(":pass", newHash);
updateQuery.bindValue(":id", DatabaseManager::currentUserId);
if (updateQuery.exec()) {
QMessageBox::information(this, "Success", "Password updated successfully.");
currentPasswordInput->clear();
newPasswordInput->clear();
confirmPasswordInput->clear();
} else {
QMessageBox::warning(this, "Error", "Failed to update password.");
}
}
/**
* @brief Checks if current PDF page has space for a new block and adds a page if needed.
*
* Prevents data from overflowing off the bottom of a page.
*
* @param writer PDF writer instance.
* @param painter Painter for drawing.
* @param yPos Current vertical position in the document.
* @param requiredHeight Space needed for the next content block.
*/
void Settings::checkPage(QPdfWriter &writer, QPainter &painter, int &yPos, int requiredHeight) {
QRect pageRect = writer.pageLayout().paintRectPixels(writer.resolution());
if (yPos + requiredHeight > pageRect.height() - 50) {
writer.newPage();
yPos = 50;
painter.resetTransform();
painter.scale(72.0 / writer.resolution(), 72.0 / writer.resolution());
}
}
/**
* @brief Handles export to PDF button click.
*
* Opens a save dialog, initializes a QPdfWriter, and calls export functions
* to write income, expenses, savings, stocks, and crypto data to the PDF.
*/
void Settings::onExportPdfClicked()
{
// Update all data and charts before exporting
m_income->loadIncomeData(); // Loads data and updates charts
m_expenses->loadExpenseData(); // Loads table data
m_expenses->updateExpenseChart(); // Updates bar chart
m_expenses->updateExpenseAreaChart(); // Updates area chart
m_savings->loadSavingsGoals(); // Loads data
m_savings->updatePieChart(); // Updates pie chart
m_stock->loadStockData(); // Loads data and triggers live price fetch
QString fileName = QFileDialog::getSaveFileName(this, "Export PDF", "", "*.pdf");
if (fileName.isEmpty())
return;
QPdfWriter writer(fileName);
writer.setPageSize(QPageSize(QPageSize::A4));
writer.setResolution(72);
QPainter painter(&writer);
qreal scaleFactor = 72.0 / writer.resolution();
painter.scale(scaleFactor, scaleFactor);
int yPos = 50;
const int lineHeight = 20;
painter.setFont(QFont("Arial", 16, QFont::Bold));
painter.drawText(50, yPos, "BudgetX Data Export");
yPos += 40;
painter.setFont(QFont("Arial", 10));
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(50, yPos, "Income Data:");
yPos += lineHeight;
exportIncomeData(painter, yPos, writer);
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(50, yPos, "Expenses Data:");
yPos += lineHeight;
exportExpensesData(painter, yPos, writer);
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(50, yPos, "Savings Goals Data:");
yPos += lineHeight;
exportSavingsData(painter, yPos, writer);
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(50, yPos, "Stocks Data:");
yPos += lineHeight;
exportStocksData(painter, yPos, writer);
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(50, yPos, "Cryptocurrencies Data:");
yPos += lineHeight;
exportCryptoData(painter, yPos, writer);
painter.end();
QMessageBox::information(this, "Export", "PDF export completed.");
}
/**
* @brief Draws the income table and pie/line charts into the PDF.
*
* Uses painter to render section title, table headers, and data rows,
* along with embedded chart images from the Income module.
*/
void Settings::exportIncomeData(QPainter &painter, int &yPos, QPdfWriter &writer)
{
const int lineHeight = 20;
int colWidthDate = 90;
int colWidthAmount = 70;
int colWidthSource = 100;
int colWidthDescription = 200;
int colWidthRecurring = 70;
int col1 = 50;
int col2 = col1 + colWidthDate;
int col3 = col2 + colWidthAmount;
int col4 = col3 + colWidthSource;
int col5 = col4 + colWidthDescription;
int col6 = col5 + colWidthRecurring;
painter.setFont(QFont("Arial", 10, QFont::Bold));
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft, "Date");
painter.drawText(QRect(col2, yPos, colWidthAmount, lineHeight), Qt::AlignLeft, "Amount");
painter.drawText(QRect(col3, yPos, colWidthSource, lineHeight), Qt::AlignLeft, "Source");
painter.drawText(QRect(col4, yPos, colWidthDescription, lineHeight), Qt::AlignLeft, "Description");
painter.drawText(QRect(col5, yPos, colWidthRecurring, lineHeight), Qt::AlignLeft, "Recurring");
painter.setFont(QFont("Arial", 10));
yPos += lineHeight;
painter.drawLine(col1 - 5, yPos, col6, yPos);
yPos += lineHeight;
QSqlQuery incomeQuery(QString("SELECT date, amount, source, description, recurring FROM income WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (incomeQuery.next()) {
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, incomeQuery.value(0).toString());
painter.drawText(QRect(col2, yPos, colWidthAmount, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(incomeQuery.value(1).toDouble()));
painter.drawText(QRect(col3, yPos, colWidthSource, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, incomeQuery.value(2).toString());
painter.drawText(QRect(col4, yPos, colWidthDescription, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, incomeQuery.value(3).toString());
QString recurringValue = incomeQuery.value(4).toString();
painter.drawText(QRect(col5, yPos, colWidthRecurring, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, recurringValue.isEmpty() ? "N/A" : recurringValue);
yPos += lineHeight;
}
yPos += 20;
// Add Income Charts
const int chartWidth = 300; // Width for each chart in PDF points
const int chartHeight = 200; // Height for each chart in PDF points
// Check space for Pie Chart
checkPage(writer, painter, yPos, chartHeight + 20);
painter.drawText(50, yPos, "Income by Source (Pie Chart):");
yPos += lineHeight;
QRectF pieChartRect(50, yPos, chartWidth, chartHeight);
m_income->getPieChartView()->render(&painter, pieChartRect, m_income->getPieChartView()->rect());
yPos += chartHeight + 20;
// Check space for Line Chart
checkPage(writer, painter, yPos, chartHeight + 20);
painter.drawText(50, yPos, "Income over Time (Line Chart):");
yPos += lineHeight;
QRectF lineChartRect(50, yPos, chartWidth, chartHeight);
m_income->getLineChartView()->render(&painter, lineChartRect, m_income->getLineChartView()->rect());
yPos += chartHeight + 20;
}
/**
* @brief Draws the expenses table and bar/area charts into the PDF.
*
* Lays out headers and data in rows, and embeds chart snapshots from Expenses module.
*/
void Settings::exportExpensesData(QPainter &painter, int &yPos, QPdfWriter &writer)
{
const int lineHeight = 20;
int colWidthDate = 90;
int colWidthAmount = 70;
int colWidthCategory = 100;
int colWidthDescription = 200;
int colWidthRecurring = 70;
int col1 = 50;
int col2 = col1 + colWidthDate;
int col3 = col2 + colWidthAmount;
int col4 = col3 + colWidthCategory;
int col5 = col4 + colWidthDescription;
int col6 = col5 + colWidthRecurring;
painter.setFont(QFont("Arial", 10, QFont::Bold));
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft, "Date");
painter.drawText(QRect(col2, yPos, colWidthAmount, lineHeight), Qt::AlignLeft, "Amount");
painter.drawText(QRect(col3, yPos, colWidthCategory, lineHeight), Qt::AlignLeft, "Category");
painter.drawText(QRect(col4, yPos, colWidthDescription, lineHeight), Qt::AlignLeft, "Description");
painter.drawText(QRect(col5, yPos, colWidthRecurring, lineHeight), Qt::AlignLeft, "Recurring");
painter.setFont(QFont("Arial", 10));
yPos += lineHeight;
painter.drawLine(col1 - 5, yPos, col6, yPos);
yPos += lineHeight;
QSqlQuery expensesQuery(QString("SELECT date, amount, category, description, recurring FROM expenses WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (expensesQuery.next()) {
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, expensesQuery.value(0).toString());
painter.drawText(QRect(col2, yPos, colWidthAmount, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(expensesQuery.value(1).toDouble()));
painter.drawText(QRect(col3, yPos, colWidthCategory, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, expensesQuery.value(2).toString());
painter.drawText(QRect(col4, yPos, colWidthDescription, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, expensesQuery.value(3).toString());
QString recurringValue = expensesQuery.value(4).toString();
painter.drawText(QRect(col5, yPos, colWidthRecurring, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, recurringValue.isEmpty() ? "N/A" : recurringValue);
yPos += lineHeight;
}
yPos += 20;
// Add Expenses Charts
const int chartWidth = 300; // Width for each chart in PDF points
const int chartHeight = 200; // Height for each chart in PDF points
// Check space for Bar Chart
checkPage(writer, painter, yPos, chartHeight + 20);
painter.drawText(50, yPos, "Expenses by Category (Bar Chart):");
yPos += lineHeight;
QRectF barChartRect(50, yPos, chartWidth, chartHeight);
m_expenses->getExpenseChartView()->render(&painter, barChartRect, m_expenses->getExpenseChartView()->rect());
yPos += chartHeight + 20;
// Check space for Area Chart
checkPage(writer, painter, yPos, chartHeight + 20);
painter.drawText(50, yPos, "Cumulative Expenses Over Time (Area Chart):");
yPos += lineHeight;
QRectF areaChartRect(50, yPos, chartWidth, chartHeight);
m_expenses->getExpenseAreaChartView()->render(&painter, areaChartRect, m_expenses->getExpenseAreaChartView()->rect());
yPos += chartHeight + 20;
}
/**
* @brief Draws savings goals and pie chart into the PDF.
*
* Displays name, target, current, priority per row, and visualizes distribution using a pie chart.
*/
void Settings::exportSavingsData(QPainter &painter, int &yPos, QPdfWriter &writer)
{
const int lineHeight = 20;
int colWidthGoalName = 200;
int colWidthTargetAmount = 120;
int colWidthCurrentAmount = 120;
int colWidthPriority = 80;
int col1 = 50;
int col2 = col1 + colWidthGoalName;
int col3 = col2 + colWidthTargetAmount;
int col4 = col3 + colWidthCurrentAmount;
painter.setFont(QFont("Arial", 10, QFont::Bold));
painter.drawText(QRect(col1, yPos, colWidthGoalName, lineHeight), Qt::AlignLeft, "Goal Name");
painter.drawText(QRect(col2, yPos, colWidthTargetAmount, lineHeight), Qt::AlignLeft, "Target Amount");
painter.drawText(QRect(col3, yPos, colWidthCurrentAmount, lineHeight), Qt::AlignLeft, "Current Amount");
painter.drawText(QRect(col4, yPos, colWidthPriority, lineHeight), Qt::AlignLeft, "Priority");
painter.setFont(QFont("Arial", 10));
yPos += lineHeight;
painter.drawLine(col1 - 5, yPos, col4 + colWidthPriority, yPos);
yPos += lineHeight;
QSqlQuery savingsQuery(QString("SELECT goalName, targetAmount, currentAmount, priority FROM saving_goals WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (savingsQuery.next()) {
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(QRect(col1, yPos, colWidthGoalName, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, savingsQuery.value(0).toString());
painter.drawText(QRect(col2, yPos, colWidthTargetAmount, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(savingsQuery.value(1).toDouble()));
painter.drawText(QRect(col3, yPos, colWidthCurrentAmount, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(savingsQuery.value(2).toDouble()));
painter.drawText(QRect(col4, yPos, colWidthPriority, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(savingsQuery.value(3).toInt()));
yPos += lineHeight;
}
yPos += 20;
// Add Savings Chart
const int chartWidth = 300; // Width for the chart in PDF points
const int chartHeight = 200; // Height for the chart in PDF points
// Check space for Pie Chart
checkPage(writer, painter, yPos, chartHeight + 20);
painter.drawText(50, yPos, "Savings Allocation (Pie Chart):");
yPos += lineHeight;
QRectF pieChartRect(50, yPos, chartWidth, chartHeight);
m_savings->getPieChartView()->render(&painter, pieChartRect, m_savings->getPieChartView()->rect());
yPos += chartHeight + 20;
}
/**
* @brief Exports stocks table and calculates profit/loss for PDF rendering.
*
* Includes ticker, price, quantity, and P/L. Top performer is highlighted.
*/
void Settings::exportStocksData(QPainter &painter, int &yPos, QPdfWriter &writer)
{
const int lineHeight = 20;
int colWidthDate = 100;
int colWidthStockName = 120;
int colWidthPurchasePrice = 120;
int colWidthQuantity = 80;
int colWidthProfitLoss = 100;
int col1 = 50;
int col2 = col1 + colWidthDate;
int col3 = col2 + colWidthStockName;
int col4 = col3 + colWidthPurchasePrice;
int col5 = col4 + colWidthQuantity;
painter.setFont(QFont("Arial", 10, QFont::Bold));
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft, "Date");
painter.drawText(QRect(col2, yPos, colWidthStockName, lineHeight), Qt::AlignLeft, "Stock Name");
painter.drawText(QRect(col3, yPos, colWidthPurchasePrice, lineHeight), Qt::AlignLeft, "Purchase Price");
painter.drawText(QRect(col4, yPos, colWidthQuantity, lineHeight), Qt::AlignLeft, "Quantity");
painter.drawText(QRect(col5, yPos, colWidthProfitLoss, lineHeight), Qt::AlignLeft, "Profit/Loss");
painter.setFont(QFont("Arial", 10));
yPos += lineHeight;
painter.drawLine(col1 - 5, yPos, col5 + colWidthProfitLoss, yPos);
yPos += lineHeight;
QSqlQuery stocksQuery(QString("SELECT date, stock_name, purchase_price, quantity FROM stocks WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (stocksQuery.next()) {
checkPage(writer, painter, yPos, lineHeight);
QString date = stocksQuery.value(0).toString();
QString ticker = stocksQuery.value(1).toString();
double purchasePrice = stocksQuery.value(2).toDouble();
int quantity = stocksQuery.value(3).toInt();
double livePrice = m_stock->getLivePrice(ticker); // Fallback to purchase price if no live data
double profitLoss = (livePrice - purchasePrice) * quantity;
QString plText = (profitLoss >= 0 ? "+" : "") + QString::number(profitLoss, 'f', 2);
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, date);
painter.drawText(QRect(col2, yPos, colWidthStockName, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, ticker);
painter.drawText(QRect(col3, yPos, colWidthPurchasePrice, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(purchasePrice));
painter.drawText(QRect(col4, yPos, colWidthQuantity, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(quantity));
painter.drawText(QRect(col5, yPos, colWidthProfitLoss, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, plText);
yPos += lineHeight;
}
yPos += 20;
}
/**
* @brief Draws crypto investments and their stats to the PDF.
*
* Displays name, date, purchase price, quantity, and ID.
*/
void Settings::exportCryptoData(QPainter &painter, int &yPos, QPdfWriter &writer)
{
const int lineHeight = 20;
int colWidthDate = 100;
int colWidthCryptoName = 120;
int colWidthPurchasePrice = 120;
int colWidthQuantity = 80;
int col1 = 50;
int col2 = col1 + colWidthDate;
int col3 = col2 + colWidthCryptoName;
int col4 = col3 + colWidthPurchasePrice;
painter.setFont(QFont("Arial", 10, QFont::Bold));
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft, "Date");
painter.drawText(QRect(col2, yPos, colWidthCryptoName, lineHeight), Qt::AlignLeft, "Crypto Name");
painter.drawText(QRect(col3, yPos, colWidthPurchasePrice, lineHeight), Qt::AlignLeft, "Purchase Price");
painter.drawText(QRect(col4, yPos, colWidthQuantity, lineHeight), Qt::AlignLeft, "Quantity");
painter.setFont(QFont("Arial", 10));
yPos += lineHeight;
painter.drawLine(col1 - 5, yPos, col4 + colWidthQuantity, yPos);
yPos += lineHeight;
QSqlQuery cryptoQuery(QString("SELECT date, crypto_name, purchase_price, quantity FROM cryptocurrencies WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (cryptoQuery.next()) {
checkPage(writer, painter, yPos, lineHeight);
painter.drawText(QRect(col1, yPos, colWidthDate, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, cryptoQuery.value(0).toString());
painter.drawText(QRect(col2, yPos, colWidthCryptoName, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, cryptoQuery.value(1).toString());
painter.drawText(QRect(col3, yPos, colWidthPurchasePrice, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(cryptoQuery.value(2).toDouble()));
painter.drawText(QRect(col4, yPos, colWidthQuantity, lineHeight), Qt::AlignLeft | Qt::TextWordWrap, QString::number(cryptoQuery.value(3).toDouble()));
yPos += lineHeight;
}
yPos += 20;
}
/**
* @brief Handles export to Excel (CSV) button click.
*
* Opens a save dialog and writes all financial data to a CSV file in tabular format.
*/
void Settings::onExportExcelClicked()
{
// Update all data before exporting, mirroring the PDF export
m_income->loadIncomeData(); // Loads data and updates charts
m_expenses->loadExpenseData(); // Loads table data
m_expenses->updateExpenseChart(); // Updates bar chart
m_expenses->updateExpenseAreaChart(); // Updates area chart
m_savings->loadSavingsGoals(); // Loads data
m_savings->updatePieChart(); // Updates pie chart
m_stock->loadStockData(); // Loads data and triggers live price fetch
QString fileName = QFileDialog::getSaveFileName(this, "Export Excel", "", "*.csv");
if (fileName.isEmpty())
return;
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "Export", "Unable to open file for writing.");
return;
}
QTextStream out(&file);
// Income Data
out << "Income Data:\nDate,Amount,Source,Description,Recurring\n";
QSqlQuery incomeQuery(QString("SELECT date, amount, source, description, recurring FROM income WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (incomeQuery.next()) {
out << incomeQuery.value(0).toString() << ","
<< incomeQuery.value(1).toDouble() << ","
<< incomeQuery.value(2).toString() << ","
<< incomeQuery.value(3).toString() << ","
<< incomeQuery.value(4).toString() << "\n";
}
out << "\n";
// Expenses Data
out << "Expenses Data:\nDate,Amount,Category,Description,Recurring\n";
QSqlQuery expensesQuery(QString("SELECT date, amount, category, description, recurring FROM expenses WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (expensesQuery.next()) {
out << expensesQuery.value(0).toString() << ","
<< expensesQuery.value(1).toDouble() << ","
<< expensesQuery.value(2).toString() << ","
<< expensesQuery.value(3).toString() << ","
<< expensesQuery.value(4).toString() << "\n";
}
out << "\n";
// Savings Goals Data
out << "Savings Goals Data:\nGoal Name,Target Amount,Current Amount,Priority\n";
QSqlQuery savingsQuery(QString("SELECT goalName, targetAmount, currentAmount, priority FROM saving_goals WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (savingsQuery.next()) {
out << savingsQuery.value(0).toString() << ","
<< savingsQuery.value(1).toDouble() << ","
<< savingsQuery.value(2).toDouble() << ","
<< savingsQuery.value(3).toInt() << "\n";
}
out << "\n";
// Stocks Data with Profit/Loss
out << "Stocks Data:\nDate,Stock Name,Purchase Price,Quantity,Profit/Loss\n";
QSqlQuery stocksQuery(QString("SELECT date, stock_name, purchase_price, quantity FROM stocks WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (stocksQuery.next()) {
QString date = stocksQuery.value(0).toString();
QString ticker = stocksQuery.value(1).toString();
double purchasePrice = stocksQuery.value(2).toDouble();
int quantity = stocksQuery.value(3).toInt();
// Calculate Profit/Loss using live price, as in exportStocksData
double livePrice = m_stock->getLivePrice(ticker); // Fallback to purchase price if no live data
double profitLoss = (livePrice - purchasePrice) * quantity;
QString plText = (profitLoss >= 0 ? "+" : "") + QString::number(profitLoss, 'f', 2);
out << date << ","
<< ticker << ","
<< purchasePrice << ","
<< quantity << ","
<< plText << "\n";
}
out << "\n";
// Cryptocurrencies Data
out << "Cryptocurrencies Data:\nDate,Crypto Name,Purchase Price,Quantity\n";
QSqlQuery cryptoQuery(QString("SELECT date, crypto_name, purchase_price, quantity FROM cryptocurrencies WHERE user_id = %1")
.arg(DatabaseManager::currentUserId));
while (cryptoQuery.next()) {
out << cryptoQuery.value(0).toString() << ","
<< cryptoQuery.value(1).toString() << ","
<< cryptoQuery.value(2).toDouble() << ","
<< cryptoQuery.value(3).toDouble() << "\n";
}
out << "\n";
out << "Charts: Please refer to the PDF export for chart images.\n";
file.close();
QMessageBox::information(this, "Export", "Excel (CSV) export completed.");
}