-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbudgetManager.cpp
More file actions
489 lines (416 loc) · 17.8 KB
/
Copy pathbudgetManager.cpp
File metadata and controls
489 lines (416 loc) · 17.8 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
/**
* @file budgetManager.cpp
* @brief Implementation of the BudgetManager widget.
*
* Provides UI and logic to set monthly budgets, allocate funds per category,
* and visualize budget usage and progress. Integrates with the database layer
* to persist and retrieve budget data.
*
* @author Armaan Sharma
*/
#include "budgetManager.h"
#include "database.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QDate>
#include <QHeaderView>
#include <QScrollArea>
/**
* @brief Constructor for BudgetManager.
*
* Sets up UI layout, initializes widgets, connects signals to slots,
* and populates data from the database.
*
*/
BudgetManager::BudgetManager(QWidget *parent) : QWidget(parent)
{
mainLayout = new QVBoxLayout(); ///< Main vertical layout.
// Title label setup
QLabel *title = new QLabel("Budget Manager", this);
title->setStyleSheet("font-size: 24px; font-weight: bold;");
mainLayout->addWidget(title);
// Top form layout: month dropdown + total budget input + save button
QHBoxLayout *topFormLayout = new QHBoxLayout();
// Month selection dropdown
monthDropdown = new QComboBox();
int currentYear = QDate::currentDate().year();
QStringList monthNames = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
// Populate dropdown with months and corresponding values
for (int m = 1; m <= 12; ++m) {
QString internalValue = QString("%1-%2").arg(currentYear).arg(m, 2, 10, QLatin1Char('0'));
QString displayText = QString("%1 %2").arg(monthNames[m - 1]).arg(currentYear);
monthDropdown->addItem(displayText, internalValue);
}
// Connect month change to UI refresh
connect(monthDropdown, &QComboBox::currentTextChanged, this, &BudgetManager::refreshUI);
monthDropdown->setStyleSheet("padding: 8px;");
// Monthly total budget input field
totalBudgetInput = new QLineEdit();
totalBudgetInput->setPlaceholderText("Monthly Budget ($)");
totalBudgetInput->setStyleSheet("padding: 8px; border-radius: 5px; border: 1px solid #ccc;");
// Save button to store monthly budget
saveMonthlyButton = new QPushButton("Save Monthly Budget");
saveMonthlyButton->setStyleSheet("background-color: #3498db; color: white; padding: 10px; border-radius: 5px;");
connect(saveMonthlyButton, &QPushButton::clicked, this, &BudgetManager::saveMonthlyBudget);
// Add form elements to layout
topFormLayout->addWidget(monthDropdown);
topFormLayout->addWidget(totalBudgetInput);
topFormLayout->addWidget(saveMonthlyButton);
mainLayout->addLayout(topFormLayout);
// Section header for allocations
QLabel *allocationHeader = new QLabel("Category Allocations", this);
allocationHeader->setStyleSheet("font-size: 18px; font-weight: bold; margin-top: 15px;");
mainLayout->addWidget(allocationHeader);
// Layout for category input form
QHBoxLayout *categoryFormLayout = new QHBoxLayout();
// Category selection dropdown
categoryDropdown = new QComboBox();
categoryDropdown->addItems({"Food", "Shopping", "Bills", "Entertainment", "Other"});
categoryDropdown->setStyleSheet("padding: 8px;");
// Input field for allocation amount
categoryAmountInput = new QLineEdit();
categoryAmountInput->setPlaceholderText("Amount ($)");
categoryAmountInput->setStyleSheet("padding: 8px; border-radius: 5px; border: 1px solid #ccc;");
// Button to add category budget
addCategoryButton = new QPushButton("Add Category Budget");
addCategoryButton->setStyleSheet("background-color: #2ecc71; color: white; padding: 10px; border-radius: 5px;");
connect(addCategoryButton, &QPushButton::clicked, this, &BudgetManager::addCategoryBudget);
// Assemble category form
categoryFormLayout->addWidget(categoryDropdown);
categoryFormLayout->addWidget(categoryAmountInput);
categoryFormLayout->addWidget(addCategoryButton);
mainLayout->addLayout(categoryFormLayout);
// Label showing total allocated
totalAllocatedLabel = new QLabel(this);
totalAllocatedLabel->setStyleSheet("font-weight: bold; padding: 6px;");
totalAllocatedLabel->setAlignment(Qt::AlignCenter);
mainLayout->addWidget(totalAllocatedLabel);
// Label for budget over-allocation alerts
mainBudgetAlertLabel = new QLabel(this);
mainBudgetAlertLabel->setStyleSheet("color: red; font-weight: bold;");
mainBudgetAlertLabel->hide();
mainLayout->addWidget(mainBudgetAlertLabel);
// Main progress bar showing overall spending
monthlyProgressBar = new QProgressBar(this);
monthlyProgressBar->setTextVisible(true);
monthlyProgressBar->setMinimumHeight(25);
mainLayout->addWidget(monthlyProgressBar);
// Table displaying per-category budget details
categoryTable = new QTableWidget(this);
categoryTable->setColumnCount(6);
categoryTable->setHorizontalHeaderLabels({"Category", "Allocated", "Spent", "Progress", "Alert", "Delete"});
categoryTable->horizontalHeader()->setStretchLastSection(true);
categoryTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
categoryTable->setMinimumHeight(300);
mainLayout->addWidget(categoryTable);
// Final alert label at the bottom
alertLabel = new QLabel(this);
alertLabel->setStyleSheet("color: red; font-weight: bold;");
mainLayout->addWidget(alertLabel);
// Wrap everything inside a scroll area for responsiveness
QScrollArea *scrollArea = new QScrollArea(this);
scrollArea->setWidgetResizable(true);
QWidget *container = new QWidget;
container->setLayout(mainLayout);
scrollArea->setWidget(container);
QVBoxLayout *outerLayout = new QVBoxLayout(this);
outerLayout->addWidget(scrollArea);
setLayout(outerLayout);
refreshUI(); ///< Populate UI on load.
}
/**
* @brief Saves the selected monthly budget to the database.
*/
void BudgetManager::saveMonthlyBudget()
{
QString month = monthDropdown->currentData().toString();
double total = totalBudgetInput->text().toDouble();
if (total <= 0) return;
QSqlQuery q(DatabaseManager::getDatabase());
q.prepare("REPLACE INTO monthly_budgets (user_id, month, total_amount) VALUES (:uid, :month, :amount)");
q.bindValue(":uid", DatabaseManager::currentUserId);
q.bindValue(":month", month);
q.bindValue(":amount", total);
q.exec();
refreshUI();
}
/**
* @brief Calculates the sum of all allocated category budgets for the selected month.
*
* @return double Total allocated amount.
*/
double BudgetManager::calculateTotalAllocated()
{
QString month = monthDropdown->currentData().toString();
double total = 0.0;
QSqlQuery query(DatabaseManager::getDatabase());
query.prepare("SELECT SUM(amount) FROM category_budgets WHERE user_id = :uid AND month = :month");
query.bindValue(":uid", DatabaseManager::currentUserId);
query.bindValue(":month", month);
if (query.exec() && query.next()) {
total = query.value(0).toDouble();
}
return total;
}
/**
* @brief Adds a category budget allocation for the selected month.
*
* Validates against the total budget and updates the database.
*/
void BudgetManager::addCategoryBudget()
{
QString month = monthDropdown->currentData().toString();
QString cat = categoryDropdown->currentText();
double amt = categoryAmountInput->text().toDouble();
if (amt <= 0) return;
double totalAllocatedLabel = calculateTotalAllocated();
if (totalAllocatedLabel + amt > currentMonthlyBudget) {
QMessageBox::warning(this, "Allocation Error", "Exceeds total monthly budget.");
return;
}
QSqlQuery q(DatabaseManager::getDatabase());
q.prepare("REPLACE INTO category_budgets (user_id, month, category, amount) VALUES (:uid, :month, :cat, :amt)");
q.bindValue(":uid", DatabaseManager::currentUserId);
q.bindValue(":month", month);
q.bindValue(":cat", cat);
q.bindValue(":amt", amt);
q.exec();
categoryAmountInput->clear();
refreshUI();
}
/**
*
* Pulls data from the database to update UI components including:
* - Monthly total budget
* - Per-category allocations
* - Expenses
* - Progress bars and warnings
*/
void BudgetManager::refreshUI()
{
QString month = monthDropdown->currentData().toString();
categoryTable->setRowCount(0);
alertLabel->clear();
currentMonthlyBudget = 0.0;
// Step 1: Get Monthly Budget Total
QSqlQuery monthlyQuery(DatabaseManager::getDatabase());
monthlyQuery.prepare("SELECT total_amount FROM monthly_budgets WHERE user_id = :uid AND month = :month");
monthlyQuery.bindValue(":uid", DatabaseManager::currentUserId);
monthlyQuery.bindValue(":month", month);
if (monthlyQuery.exec() && monthlyQuery.next()) {
currentMonthlyBudget = monthlyQuery.value(0).toDouble();
totalBudgetInput->setText(QString::number(currentMonthlyBudget, 'f', 2));
mainBudgetAlertLabel->hide();
monthlyProgressBar->show();
} else {
totalBudgetInput->clear();
mainBudgetAlertLabel->setText(" No monthly budget set for this month.");
mainBudgetAlertLabel->show();
monthlyProgressBar->hide();
return;
}
// Step 2: Get Category Budgets for this month
QSqlQuery categoryQuery(DatabaseManager::getDatabase());
categoryQuery.prepare("SELECT category, amount FROM category_budgets WHERE user_id = :uid AND month = :month");
categoryQuery.bindValue(":uid", DatabaseManager::currentUserId);
categoryQuery.bindValue(":month", month);
double totalAllocated = 0.0;
if (!categoryQuery.exec()) return;
while (categoryQuery.next()) {
QString category = categoryQuery.value(0).toString();
double allocated = categoryQuery.value(1).toDouble();
totalAllocated += allocated;
// Step 3: Get total spent in this category this month
QSqlQuery spentQuery(DatabaseManager::getDatabase());
QString queryStr;
if (category == "Other") {
// Any category not in main predefined list = "Other"
queryStr =
"SELECT SUM(amount) FROM expenses "
"WHERE user_id = :uid AND strftime('%Y-%m', date) = :month "
"AND (category NOT IN ('Food', 'Shopping', 'Bills', 'Entertainment'))";
} else {
queryStr =
"SELECT SUM(amount) FROM expenses "
"WHERE user_id = :uid AND category = :cat AND strftime('%Y-%m', date) = :month";
}
spentQuery.prepare(queryStr);
spentQuery.bindValue(":uid", DatabaseManager::currentUserId);
spentQuery.bindValue(":month", month);
if (category != "Other") {
spentQuery.bindValue(":cat", category);
}
spentQuery.bindValue(":month", month);
double spent = 0.0;
if (spentQuery.exec() && spentQuery.next())
spent = spentQuery.value(0).toDouble();
int row = categoryTable->rowCount();
categoryTable->insertRow(row);
categoryTable->setItem(row, 0, new QTableWidgetItem(category));
categoryTable->setItem(row, 1, new QTableWidgetItem("$" + QString::number(allocated, 'f', 2)));
categoryTable->setItem(row, 2, new QTableWidgetItem("$" + QString::number(spent, 'f', 2)));
// Step 4: Progress Bar
QString alertText;
QProgressBar *bar = new QProgressBar();
// Set value and max such that overspending doesn't break the bar
int barValue = static_cast<int>(spent);
int barMax = static_cast<int>(qMax(spent, allocated));
bar->setRange(0, barMax);
bar->setValue(barValue);
bar->setTextVisible(true); // Optional: turn off if you want a clean look
// Set color based on condition
if (spent >= allocated) {
bar->setStyleSheet(
"QProgressBar {"
" border: none;"
" background-color: transparent;"
" text-align: center;"
"}"
"QProgressBar::chunk {"
" background-color: red;"
" border-radius: 5px;"
"}"
);
alertText = "❗ Overspent by $" + QString::number(spent - allocated, 'f', 2);
}
else if ((allocated - spent) <= 50.0) {
bar->setStyleSheet(
"QProgressBar {"
" border: none;"
" background-color: transparent;"
" text-align: center;"
"}"
"QProgressBar::chunk {"
" background-color: orange;"
" border-radius: 5px;"
"}"
);
alertText = "⚠ Close to limit";
}
else {
bar->setStyleSheet(
"QProgressBar {"
" border: none;"
" background-color: transparent;"
" text-align: center;"
"}"
"QProgressBar::chunk {"
" background-color: #3498db;"
" border-radius: 5px;"
"}"
);
}
categoryTable->setCellWidget(row, 3, bar);
categoryTable->setItem(row, 4, new QTableWidgetItem(alertText));
QPushButton *deleteBtn = new QPushButton("✖");
deleteBtn->setStyleSheet(
"QPushButton {"
" background-color: #e74c3c;"
" color: white;"
" font-weight: bold;"
" border: none;"
" padding: 4px 8px;"
" border-radius: 4px;"
"}"
"QPushButton:hover {"
" background-color: #c0392b;"
"}"
);
deleteBtn->setToolTip("Delete this category");
categoryTable->setCellWidget(row, 5, deleteBtn);
// Connect the delete button with category + month context
connect(deleteBtn, &QPushButton::clicked, this, [=]() {
auto confirm = QMessageBox::question(this, "Delete Category",
"Are you sure you want to delete the budget for \"" + category + "\"?");
if (confirm == QMessageBox::Yes) {
QSqlQuery del(DatabaseManager::getDatabase());
del.prepare("DELETE FROM category_budgets WHERE user_id = :uid AND month = :month AND category = :cat");
del.bindValue(":uid", DatabaseManager::currentUserId);
del.bindValue(":month", month);
del.bindValue(":cat", category);
del.exec();
refreshUI();
}
});
}
// Step 5: Update allocation summary
totalAllocatedLabel->setText("💰 <b>Allocated:</b> <span style='color:#2c3e50;'>$" +
QString::number(totalAllocated, 'f', 2) + "</span>");
if (totalAllocated > currentMonthlyBudget) {
alertLabel->setText("⚠ Total category allocations exceed monthly budget!");
}
// Step 6: Total Monthly Spending
QSqlQuery spentQuery(DatabaseManager::getDatabase());
spentQuery.prepare("SELECT SUM(amount) FROM expenses "
"WHERE user_id = :uid AND strftime('%Y-%m', date) = :month");
spentQuery.bindValue(":uid", DatabaseManager::currentUserId);
spentQuery.bindValue(":month", month);
double totalSpent = 0.0;
if (spentQuery.exec() && spentQuery.next())
totalSpent = spentQuery.value(0).toDouble();
// Step 7: Update Master Progress Bar
int overallPercent = (currentMonthlyBudget > 0) ? static_cast<int>((totalSpent / currentMonthlyBudget) * 100.0) : 0;
monthlyProgressBar->setValue(overallPercent);
monthlyProgressBar->setFormat(QString("$%1 / $%2")
.arg(QString::number(totalSpent, 'f', 2))
.arg(QString::number(currentMonthlyBudget, 'f', 2)));
QFont boldFont;
boldFont.setBold(true);
boldFont.setPointSize(11); // ⬅️ Increase this value as needed
monthlyProgressBar->setFont(boldFont);
// Ensure bar doesn't cap at 100%
int masterValue = static_cast<int>(totalSpent);
int masterMax = static_cast<int>(qMax(totalSpent, currentMonthlyBudget));
monthlyProgressBar->setRange(0, masterMax);
monthlyProgressBar->setValue(masterValue);
// Style based on distance to limit
if (totalSpent >= currentMonthlyBudget) {
monthlyProgressBar->setStyleSheet(
"QProgressBar {"
" border: none;"
" background-color: transparent;"
" text-align: center;"
"}"
"QProgressBar::chunk {"
" background-color: red;"
" border-radius: 5px;"
"}"
);
// Optional: show alert label
mainBudgetAlertLabel->setText("❗ You have reached your budget!");
mainBudgetAlertLabel->setStyleSheet("color: red; font-size: 16px; font-weight: bold;");
mainBudgetAlertLabel->show();
}
else if (totalSpent >= currentMonthlyBudget - 100.0) {
monthlyProgressBar->setStyleSheet(
"QProgressBar {"
" border: none;"
" background-color: transparent;"
" text-align: center;"
"}"
"QProgressBar::chunk {"
" background-color: orange;"
" border-radius: 5px;"
"}"
);
mainBudgetAlertLabel->hide();
}
else {
monthlyProgressBar->setStyleSheet(
"QProgressBar {"
" border: none;"
" background-color: transparent;"
" text-align: center;"
"}"
"QProgressBar::chunk {"
" background-color: #3498db;"
" border-radius: 5px;"
"}"
);
mainBudgetAlertLabel->hide();
}
mainBudgetAlertLabel->hide(); // reset first
}