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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
|
#include "cashflow.h"
#include "ui_cashflow.h"
#include "settingsdialog.h"
#include <QMessageBox>
#include <QDir>
#include <QStandardPaths>
#include <QFontDialog>
#include <QLocale>
#include <QFileDialog>
#include <QApplication>
CashFlow::CashFlow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::CashFlow)
, currentTransactionId(-1)
, currentRecurringId(-1)
, startingBalance(0.0)
, currentAmountFont("Courier New", 10)
, weekStartDay(1) // Default to Monday
{
ui->setupUi(this);
// Initialize database
database = new Database();
// Try to open default database
QString defaultDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QDir().mkpath(defaultDir);
QString defaultPath = defaultDir + "/default.cashflo.sqlite";
setupConnections();
if (!openDatabase(defaultPath)) {
QMessageBox::critical(this, "Database Error", "Failed to open default database: " + database->lastError());
return;
}
}
CashFlow::~CashFlow()
{
delete database;
delete ui;
}
void CashFlow::setupConnections() {
// File menu
connect(ui->actionNew, &QAction::triggered, this, &CashFlow::onNewFile);
connect(ui->actionOpen, &QAction::triggered, this, &CashFlow::onOpenFile);
connect(ui->actionQuit, &QAction::triggered, this, &CashFlow::onQuit);
// Settings menu
connect(ui->actionPreferences, &QAction::triggered, this, &CashFlow::onPreferences);
// Transaction tab
connect(ui->dateFromEdit, &QDateEdit::dateChanged, this, &CashFlow::onDateRangeChanged);
connect(ui->dateToEdit, &QDateEdit::dateChanged, this, &CashFlow::onDateRangeChanged);
connect(ui->periodCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CashFlow::onPeriodChanged);
connect(ui->accountFilterCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CashFlow::onDateRangeChanged);
connect(ui->showAccountBalancesCheck, &QCheckBox::stateChanged, this, &CashFlow::onDateRangeChanged);
// Auto-save period and show balances settings
connect(ui->periodCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this]() {
database->setSetting("default_period", QString::number(ui->periodCombo->currentIndex()));
});
connect(ui->showAccountBalancesCheck, &QCheckBox::stateChanged, this, [this]() {
database->setSetting("show_account_balances", QString::number(ui->showAccountBalancesCheck->isChecked() ? 1 : 0));
});
connect(ui->transactionTable, &QTableWidget::itemSelectionChanged, this, &CashFlow::onTransactionSelected);
connect(ui->saveBtn, &QPushButton::clicked, this, &CashFlow::onSaveTransaction);
connect(ui->newBtn, &QPushButton::clicked, this, &CashFlow::onNewTransaction);
connect(ui->deleteBtn, &QPushButton::clicked, this, &CashFlow::onDeleteTransaction);
// Transaction entry recurring rule linking
connect(ui->entryRecurringCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CashFlow::onRecurringRuleChanged);
connect(ui->entryDateEdit, &QDateEdit::dateChanged, this, &CashFlow::onTransactionDateChanged);
// Set up Delete key shortcut for transaction table
ui->deleteBtn->setShortcut(Qt::Key_Delete);
// Color-code amount inputs
connect(ui->entryAmountSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &CashFlow::updateAmountColors);
connect(ui->recurringAmountSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &CashFlow::updateAmountColors);
// Recurring tab
connect(ui->recurringTable, &QTableWidget::itemSelectionChanged, this, &CashFlow::onRecurringSelected);
connect(ui->saveRecurringBtn, &QPushButton::clicked, this, &CashFlow::onSaveRecurring);
connect(ui->newRecurringBtn, &QPushButton::clicked, this, &CashFlow::onNewRecurring);
connect(ui->deleteRecurringBtn, &QPushButton::clicked, this, &CashFlow::onDeleteRecurring);
// Set up Delete key shortcut for recurring table
ui->deleteRecurringBtn->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Delete));
}
void CashFlow::refreshView() {
// Populate account filter dropdown with unique accounts
// Block signals to prevent recursive refresh
ui->accountFilterCombo->blockSignals(true);
QString currentFilter = ui->accountFilterCombo->currentText();
ui->accountFilterCombo->clear();
ui->accountFilterCombo->addItem("All Accounts");
// Get unique account names and categories
QSet<QString> accounts;
QSet<QString> categories;
for (const Transaction &t : database->getAllTransactions()) {
if (!t.account.isEmpty()) accounts.insert(t.account);
if (!t.category.isEmpty()) categories.insert(t.category);
}
for (const RecurringRule &r : database->getAllRecurringRules()) {
if (!r.account.isEmpty()) accounts.insert(r.account);
if (!r.category.isEmpty()) categories.insert(r.category);
}
QStringList sortedAccounts = accounts.values();
sortedAccounts.sort();
ui->accountFilterCombo->addItems(sortedAccounts);
// Populate entry form account combo
ui->entryAccountCombo->blockSignals(true);
QString currentAccount = ui->entryAccountCombo->currentText();
ui->entryAccountCombo->clear();
ui->entryAccountCombo->addItems(sortedAccounts);
ui->entryAccountCombo->setCurrentText(currentAccount);
ui->entryAccountCombo->blockSignals(false);
// Populate entry form category combo
ui->entryCategoryCombo->blockSignals(true);
QString currentCategory = ui->entryCategoryCombo->currentText();
ui->entryCategoryCombo->clear();
QStringList sortedCategories = categories.values();
sortedCategories.sort();
ui->entryCategoryCombo->addItems(sortedCategories);
ui->entryCategoryCombo->setCurrentText(currentCategory);
ui->entryCategoryCombo->blockSignals(false);
// Populate recurring rules combo
populateRecurringRulesCombo();
// Populate recurring rule account and category combos
ui->recurringAccountCombo->blockSignals(true);
ui->recurringAccountCombo->clear();
ui->recurringAccountCombo->addItems(sortedAccounts);
ui->recurringAccountCombo->blockSignals(false);
ui->recurringCategoryCombo->blockSignals(true);
ui->recurringCategoryCombo->clear();
ui->recurringCategoryCombo->addItems(sortedCategories);
ui->recurringCategoryCombo->blockSignals(false);
// Restore previous selection if possible
int index = ui->accountFilterCombo->findText(currentFilter);
if (index >= 0) {
ui->accountFilterCombo->setCurrentIndex(index);
}
ui->accountFilterCombo->blockSignals(false);
refreshTransactionTable();
refreshRecurringTable();
calculateAndDisplayBalance();
}
void CashFlow::refreshTransactionTable() {
QList<Transaction> allTransactions = getAllTransactionsInRange();
ui->transactionTable->setRowCount(0);
ui->transactionTable->setColumnCount(7);
ui->transactionTable->setHorizontalHeaderLabels({"Date", "Amount", "Balance", "Account", "Category", "Description", "Type"});
double runningBalance = startingBalance;
QMap<QString, double> accountBalances; // Track per-account balances
QDate currentPeriodEnd;
QString periodLabel;
int periodCount = 1;
// Determine period type
PeriodType periodType = static_cast<PeriodType>(ui->periodCombo->currentIndex());
// Get first period end date
if (!allTransactions.isEmpty()) {
currentPeriodEnd = getPeriodEnd(allTransactions.first().date, periodType);
periodLabel = getPeriodLabel(allTransactions.first().date, periodType, periodCount);
}
for (const Transaction &t : allTransactions) {
// Check if we've crossed into a new period
if (t.date > currentPeriodEnd) {
// Insert period end row
insertPeriodEndRow(periodLabel, runningBalance, accountBalances);
// Move to next period
periodCount++;
currentPeriodEnd = getPeriodEnd(t.date, periodType);
periodLabel = getPeriodLabel(t.date, periodType, periodCount);
}
// Update balances
runningBalance += t.amount;
accountBalances[t.account] += t.amount;
// Insert transaction row
int row = ui->transactionTable->rowCount();
ui->transactionTable->insertRow(row);
// Store ID in first column's data for retrieval later
QTableWidgetItem *dateItem = new QTableWidgetItem(t.date.toString("MM/dd/yy"));
dateItem->setData(Qt::UserRole, t.id);
// Store full transaction for projected items (id == -1)
if (t.id == -1) {
dateItem->setData(Qt::UserRole + 1, QVariant::fromValue(t));
}
dateItem->setFlags(dateItem->flags() & ~Qt::ItemIsEditable);
ui->transactionTable->setItem(row, 0, dateItem);
// Format amount with color, right-align, monospace
QTableWidgetItem *amountItem = new QTableWidgetItem(QString("$%1").arg(formatCurrency(t.amount)));
amountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
amountItem->setFont(currentAmountFont);
amountItem->setFlags(amountItem->flags() & ~Qt::ItemIsEditable);
if (t.amount < 0) {
amountItem->setForeground(QColor(200, 0, 0));
} else {
amountItem->setForeground(QColor(0, 150, 0));
}
ui->transactionTable->setItem(row, 1, amountItem);
// Format balance with right-align, monospace
QTableWidgetItem *balanceItem = new QTableWidgetItem(QString("$%1").arg(formatCurrency(runningBalance)));
balanceItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
balanceItem->setFont(currentAmountFont);
balanceItem->setFlags(balanceItem->flags() & ~Qt::ItemIsEditable);
if (runningBalance < 0) {
balanceItem->setForeground(QColor(200, 0, 0));
}
ui->transactionTable->setItem(row, 2, balanceItem);
QTableWidgetItem *accountItem = new QTableWidgetItem(t.account);
accountItem->setFlags(accountItem->flags() & ~Qt::ItemIsEditable);
ui->transactionTable->setItem(row, 3, accountItem);
QTableWidgetItem *categoryItem = new QTableWidgetItem(t.category);
categoryItem->setFlags(categoryItem->flags() & ~Qt::ItemIsEditable);
ui->transactionTable->setItem(row, 4, categoryItem);
QTableWidgetItem *descItem = new QTableWidgetItem(t.description);
descItem->setFlags(descItem->flags() & ~Qt::ItemIsEditable);
ui->transactionTable->setItem(row, 5, descItem);
QTableWidgetItem *typeItem = new QTableWidgetItem(
t.type == TransactionType::Actual ? "Actual" : "Estimated");
typeItem->setFlags(typeItem->flags() & ~Qt::ItemIsEditable);
ui->transactionTable->setItem(row, 6, typeItem);
// Color code estimated vs actual
QColor rowColor = t.type == TransactionType::Actual ?
QColor(200, 255, 200) : QColor(255, 255, 200);
for (int col = 0; col < 7; col++) {
if (ui->transactionTable->item(row, col)) {
ui->transactionTable->item(row, col)->setBackground(rowColor);
}
}
}
// Insert final period end row
if (!allTransactions.isEmpty()) {
insertPeriodEndRow(periodLabel, runningBalance, accountBalances);
}
ui->transactionTable->resizeColumnsToContents();
// Set minimum and optimal widths for specific columns
ui->transactionTable->setColumnWidth(0, 100); // Date
ui->transactionTable->setColumnWidth(1, 100); // Amount
ui->transactionTable->setColumnWidth(2, 100); // Balance
ui->transactionTable->setColumnWidth(3, 120); // Account
ui->transactionTable->setColumnWidth(4, 120); // Category
ui->transactionTable->horizontalHeader()->setStretchLastSection(false);
ui->transactionTable->setColumnWidth(5, 250); // Description
ui->transactionTable->setColumnWidth(6, 80); // Type
}
QDate CashFlow::getPeriodEnd(const QDate &date, PeriodType periodType) {
switch (periodType) {
case Daily:
return date;
case Weekly: {
// End on day before week start day
int weekEndDay = (weekStartDay == 1) ? 7 : weekStartDay - 1;
int currentDay = date.dayOfWeek();
int daysUntilWeekEnd = (weekEndDay - currentDay + 7) % 7;
if (daysUntilWeekEnd == 0 && currentDay != weekEndDay) {
daysUntilWeekEnd = 7; // If we're past the end, go to next week's end
}
return date.addDays(daysUntilWeekEnd);
}
case Monthly:
return QDate(date.year(), date.month(), date.daysInMonth());
case Quarterly: {
int quarter = (date.month() - 1) / 3;
int lastMonthOfQuarter = (quarter + 1) * 3;
QDate lastDayOfQuarter(date.year(), lastMonthOfQuarter, 1);
return QDate(date.year(), lastMonthOfQuarter, lastDayOfQuarter.daysInMonth());
}
}
return date;
}
QString CashFlow::getPeriodLabel(const QDate &date, PeriodType periodType, int count) {
QDate periodStart = getPeriodStart(date, periodType);
QDate periodEnd = getPeriodEnd(date, periodType);
QString dateRange = QString("%1 - %2").arg(periodStart.toString("MM/dd/yy")).arg(periodEnd.toString("MM/dd/yy"));
switch (periodType) {
case Daily:
return QString("DAY %1 (%2) END").arg(count).arg(date.toString("MM/dd/yy"));
case Weekly:
return QString("WEEK %1 END (%2)").arg(count).arg(dateRange);
case Monthly:
return QString("%1 END (%2)").arg(date.toString("MMMM yyyy").toUpper()).arg(dateRange);
case Quarterly:
return QString("Q%1 %2 END (%3)").arg((date.month() - 1) / 3 + 1).arg(date.year()).arg(dateRange);
}
return "";
}
QDate CashFlow::getPeriodStart(const QDate &date, PeriodType periodType) {
switch (periodType) {
case Daily:
return date;
case Weekly: {
// Start on configured week start day (1=Monday, 7=Sunday)
int currentDay = date.dayOfWeek(); // 1=Monday, 7=Sunday
int daysFromWeekStart = (currentDay - weekStartDay + 7) % 7;
return date.addDays(-daysFromWeekStart);
}
case Monthly:
return QDate(date.year(), date.month(), 1);
case Quarterly: {
int quarter = (date.month() - 1) / 3;
int firstMonthOfQuarter = quarter * 3 + 1;
return QDate(date.year(), firstMonthOfQuarter, 1);
}
}
return date;
}
void CashFlow::insertPeriodEndRow(const QString &label, double balance, const QMap<QString, double> &accountBalances) {
int row = ui->transactionTable->rowCount();
ui->transactionTable->insertRow(row);
// Build display text with optional account balances
QString displayText = QString("%1 Balance: $%2").arg(label).arg(formatCurrency(balance));
if (ui->showAccountBalancesCheck->isChecked() && !accountBalances.isEmpty()) {
QStringList accountTexts;
QMapIterator<QString, double> it(accountBalances);
while (it.hasNext()) {
it.next();
accountTexts.append(QString("%1: $%2").arg(it.key()).arg(formatCurrency(it.value())));
}
displayText += " " + accountTexts.join(" ");
}
QTableWidgetItem *spanItem = new QTableWidgetItem(displayText);
spanItem->setFont(QFont("Arial", 11, QFont::Bold));
spanItem->setBackground(QColor(180, 180, 180));
spanItem->setForeground(balance < 0 ? QColor(200, 0, 0) : QColor(0, 100, 0));
spanItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
spanItem->setFlags(spanItem->flags() & ~Qt::ItemIsSelectable); // Make non-selectable
ui->transactionTable->setItem(row, 0, spanItem);
// Span across all columns
ui->transactionTable->setSpan(row, 0, 1, 7);
// Make the row taller
ui->transactionTable->setRowHeight(row, 30);
}
void CashFlow::refreshRecurringTable() {
QList<RecurringRule> rules = database->getAllRecurringRules();
ui->recurringTable->setRowCount(0);
ui->recurringTable->setColumnCount(7);
ui->recurringTable->setHorizontalHeaderLabels({"ID", "Name", "Frequency", "Amount", "Account", "Category", "Start Date"});
ui->recurringTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
for (const RecurringRule &r : rules) {
int row = ui->recurringTable->rowCount();
ui->recurringTable->insertRow(row);
ui->recurringTable->setItem(row, 0, new QTableWidgetItem(QString::number(r.id)));
ui->recurringTable->setItem(row, 1, new QTableWidgetItem(r.name));
QString freqStr;
switch (r.frequency) {
case RecurrenceFrequency::Daily: freqStr = "Daily"; break;
case RecurrenceFrequency::Weekly: freqStr = "Weekly"; break;
case RecurrenceFrequency::BiWeekly: freqStr = "Bi-Weekly"; break;
case RecurrenceFrequency::Monthly: freqStr = "Monthly"; break;
case RecurrenceFrequency::Yearly: freqStr = "Yearly"; break;
default: freqStr = "None"; break;
}
ui->recurringTable->setItem(row, 2, new QTableWidgetItem(freqStr));
// Amount with color coding, right-align, monospace
QTableWidgetItem *amountItem = new QTableWidgetItem(QString("$%1").arg(formatCurrency(r.amount)));
amountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
amountItem->setFont(currentAmountFont);
if (r.amount < 0) {
amountItem->setForeground(QColor(200, 0, 0)); // Red for debits
} else {
amountItem->setForeground(QColor(0, 150, 0)); // Green for credits
}
ui->recurringTable->setItem(row, 3, amountItem);
ui->recurringTable->setItem(row, 4, new QTableWidgetItem(r.account));
ui->recurringTable->setItem(row, 5, new QTableWidgetItem(r.category));
ui->recurringTable->setItem(row, 6, new QTableWidgetItem(r.startDate.toString("yyyy-MM-dd")));
}
ui->recurringTable->resizeColumnsToContents();
}
void CashFlow::calculateAndDisplayBalance() {
QList<Transaction> allTransactions = getAllTransactionsInRange();
double endBalance = startingBalance;
for (const Transaction &t : allTransactions) {
endBalance += t.amount;
}
ui->startBalanceLabel->setText(QString("Starting Balance: $%1").arg(formatCurrency(startingBalance)));
ui->endBalanceLabel->setText(QString("Ending Balance: $%1").arg(formatCurrency(endBalance)));
// Color code the ending balance
if (endBalance < 0) {
ui->endBalanceLabel->setStyleSheet("font-weight: bold; font-size: 12pt; color: red;");
} else if (endBalance < 1000) {
ui->endBalanceLabel->setStyleSheet("font-weight: bold; font-size: 12pt; color: orange;");
} else {
ui->endBalanceLabel->setStyleSheet("font-weight: bold; font-size: 12pt; color: green;");
}
}
QList<Transaction> CashFlow::getAllTransactionsInRange() {
QDate startDate = ui->dateFromEdit->date();
QDate endDate = ui->dateToEdit->date();
QString accountFilter = ui->accountFilterCombo->currentText();
// Safety check
if (accountFilter.isEmpty()) {
accountFilter = "All Accounts";
}
// Get actual transactions from database
QList<Transaction> actualTransactions = database->getTransactions(startDate, endDate);
// Generate projected transactions from recurring rules
QList<Transaction> projectedTransactions = generateProjectedTransactions();
// Combine
QList<Transaction> allTransactions = actualTransactions + projectedTransactions;
// Filter by account if not "All Accounts"
if (accountFilter != "All Accounts") {
QList<Transaction> filtered;
for (const Transaction &t : allTransactions) {
if (t.account == accountFilter) {
filtered.append(t);
}
}
allTransactions = filtered;
}
// Sort by date, then by sort_order, then credits before debits
std::sort(allTransactions.begin(), allTransactions.end(),
[](const Transaction &a, const Transaction &b) {
if (a.date != b.date) return a.date < b.date;
if (a.sortOrder != b.sortOrder) return a.sortOrder < b.sortOrder;
// Credits (positive amounts) before debits (negative amounts)
return a.amount > b.amount;
});
return allTransactions;
}
QList<Transaction> CashFlow::generateProjectedTransactions() {
QList<Transaction> projections;
QList<RecurringRule> rules = database->getAllRecurringRules();
QDate startDate = ui->dateFromEdit->date();
QDate endDate = ui->dateToEdit->date();
// Load all actual transactions with recurring_id (converted projections)
QList<Transaction> actualTransactions = database->getAllTransactions();
QSet<QString> existingOccurrences; // recurring_id:occurrence_key pairs
for (const Transaction &t : actualTransactions) {
if (t.recurringId != -1 && !t.occurrenceKey.isEmpty()) {
existingOccurrences.insert(QString("%1:%2").arg(t.recurringId).arg(t.occurrenceKey));
}
}
for (const RecurringRule &rule : rules) {
QDate currentDate = rule.startDate > startDate ? rule.startDate : startDate;
// Align to proper day based on frequency
if (rule.frequency == RecurrenceFrequency::Weekly || rule.frequency == RecurrenceFrequency::BiWeekly) {
// Find next occurrence of the specified day of week
while (currentDate <= endDate && currentDate.dayOfWeek() != rule.dayOfWeek) {
currentDate = currentDate.addDays(1);
}
} else if (rule.frequency == RecurrenceFrequency::Monthly) {
// Set to the specified day of month
int targetDay = qMin(rule.dayOfMonth, currentDate.daysInMonth());
currentDate = QDate(currentDate.year(), currentDate.month(), targetDay);
if (currentDate < startDate) {
currentDate = currentDate.addMonths(1);
targetDay = qMin(rule.dayOfMonth, currentDate.daysInMonth());
currentDate = QDate(currentDate.year(), currentDate.month(), targetDay);
}
}
int count = 0;
while (currentDate <= endDate) {
if (rule.occurrences != -1 && count >= rule.occurrences) {
break;
}
if (rule.endDate.isValid() && currentDate > rule.endDate) {
break;
}
// Generate occurrence key based on frequency
QString occurrenceKey;
if (rule.frequency == RecurrenceFrequency::Daily) {
occurrenceKey = currentDate.toString("yyyy-MM-dd");
} else if (rule.frequency == RecurrenceFrequency::Weekly || rule.frequency == RecurrenceFrequency::BiWeekly) {
occurrenceKey = QString("%1-W%2").arg(currentDate.year()).arg(currentDate.weekNumber(), 2, 10, QChar('0'));
} else if (rule.frequency == RecurrenceFrequency::Monthly) {
occurrenceKey = currentDate.toString("yyyy-MM");
} else if (rule.frequency == RecurrenceFrequency::Yearly) {
occurrenceKey = QString::number(currentDate.year());
}
// Skip if actual already exists for this occurrence
QString occurrenceCheck = QString("%1:%2").arg(rule.id).arg(occurrenceKey);
if (existingOccurrences.contains(occurrenceCheck)) {
// Actual exists, skip this projection
} else {
Transaction t;
t.id = -1; // Projected transactions have no ID
t.date = currentDate;
t.amount = rule.amount;
t.account = rule.account;
t.category = rule.category;
t.description = rule.description + " (projected)";
t.type = TransactionType::Estimated;
t.recurringId = rule.id;
t.occurrenceKey = occurrenceKey;
t.reconciled = false;
projections.append(t);
}
count++;
// Calculate next occurrence
switch (rule.frequency) {
case RecurrenceFrequency::Daily:
currentDate = currentDate.addDays(1);
break;
case RecurrenceFrequency::Weekly:
currentDate = currentDate.addDays(7);
break;
case RecurrenceFrequency::BiWeekly:
currentDate = currentDate.addDays(14);
break;
case RecurrenceFrequency::Monthly: {
currentDate = currentDate.addMonths(1);
int targetDay = qMin(rule.dayOfMonth, currentDate.daysInMonth());
currentDate = QDate(currentDate.year(), currentDate.month(), targetDay);
break;
}
case RecurrenceFrequency::Yearly:
currentDate = currentDate.addYears(1);
break;
default:
currentDate = endDate.addDays(1); // Exit loop
break;
}
}
}
return projections;
}
void CashFlow::onDateRangeChanged() {
refreshView();
}
void CashFlow::onPeriodChanged() {
refreshView();
}
void CashFlow::onTransactionSelected() {
QList<QTableWidgetItem*> selected = ui->transactionTable->selectedItems();
if (selected.isEmpty()) {
return;
}
int row = selected[0]->row();
int id = ui->transactionTable->item(row, 0)->data(Qt::UserRole).toInt();
// If it's a projected transaction (id = -1), load it for editing
if (id == -1) {
QVariant projectedData = ui->transactionTable->item(row, 0)->data(Qt::UserRole + 1);
if (projectedData.canConvert<Transaction>()) {
Transaction t = projectedData.value<Transaction>();
currentTransactionId = -1; // Will create new actual when saved
currentProjectedTransaction = t; // Store for conversion
loadTransactionToEntry(t);
ui->entryStatusLabel->setText("(Converting Projection to Actual)");
}
return;
}
// Load from database
QList<Transaction> allTrans = database->getAllTransactions();
for (const Transaction &t : allTrans) {
if (t.id == id) {
currentTransactionId = id;
loadTransactionToEntry(t);
ui->entryStatusLabel->setText(QString("Editing ID: %1").arg(id));
return;
}
}
}
void CashFlow::onSaveTransaction() {
// Skip validation if this is a new empty transaction being auto-saved
bool isEmptyNew = (currentTransactionId == -1 &&
ui->entryAccountCombo->currentText().isEmpty() &&
ui->entryAmountSpin->value() == 0.0);
if (!isEmptyNew) {
// Validate required fields
if (ui->entryAccountCombo->currentText().isEmpty()) {
QMessageBox::warning(this, "Required Field", "Account is required.");
return;
}
if (ui->entryAmountSpin->value() == 0.0) {
QMessageBox::warning(this, "Required Field", "Amount cannot be zero.");
return;
}
}
Transaction t;
t.id = currentTransactionId;
t.date = ui->entryDateEdit->date();
t.amount = ui->entryAmountSpin->value();
t.account = ui->entryAccountCombo->currentText();
t.category = ui->entryCategoryCombo->currentText();
t.description = ui->entryDescriptionEdit->text();
t.type = ui->entryTypeCombo->currentText() == "Actual" ? TransactionType::Actual : TransactionType::Estimated;
// Check if user manually linked to a recurring rule
int manualRuleId = ui->entryRecurringCombo->currentData().toInt();
QString manualOccurrenceKey = ui->entryOccurrenceEdit->text().trimmed();
// Check if we're converting a projection to actual
if (currentTransactionId == -1 && currentProjectedTransaction.recurringId != -1) {
// Converting projection - keep recurring link and store expected values
t.recurringId = currentProjectedTransaction.recurringId;
t.occurrenceKey = currentProjectedTransaction.occurrenceKey;
t.expectedAmount = currentProjectedTransaction.amount;
t.expectedDate = currentProjectedTransaction.date;
t.reconciled = true;
t.type = TransactionType::Actual; // Force to actual when converting
} else if (manualRuleId != -1 && !manualOccurrenceKey.isEmpty()) {
// User manually linked to recurring rule
t.recurringId = manualRuleId;
t.occurrenceKey = manualOccurrenceKey;
t.reconciled = true;
// Try to get expected amount from the rule
QList<RecurringRule> rules = database->getAllRecurringRules();
for (const RecurringRule &rule : rules) {
if (rule.id == manualRuleId) {
t.expectedAmount = rule.amount;
break;
}
}
} else if (currentTransactionId != -1) {
// Editing existing transaction - load from database to preserve reconciliation fields
QList<Transaction> allTrans = database->getAllTransactions();
for (const Transaction &existing : allTrans) {
if (existing.id == currentTransactionId) {
t.recurringId = existing.recurringId;
t.occurrenceKey = existing.occurrenceKey;
t.expectedAmount = existing.expectedAmount;
t.expectedDate = existing.expectedDate;
t.reconciled = existing.reconciled;
break;
}
}
} else {
// New manual transaction with no recurring link
t.recurringId = -1;
t.reconciled = false;
}
bool success;
if (currentTransactionId == -1) {
// New transaction
success = database->addTransaction(t);
if (success) {
// Get the new ID and update currentTransactionId
QList<Transaction> allTrans = database->getAllTransactions();
if (!allTrans.isEmpty()) {
currentTransactionId = allTrans.last().id;
}
}
} else {
// Update existing
success = database->updateTransaction(t);
}
if (success) {
ui->entryStatusLabel->setText("Saved!");
refreshView();
} else {
QMessageBox::critical(this, "Error", "Failed to save: " + database->lastError());
}
}
void CashFlow::onNewTransaction() {
clearTransactionEntry();
currentProjectedTransaction = Transaction(); // Reset projected transaction
ui->entryDateEdit->setDate(QDate::currentDate());
ui->entryDateEdit->setFocus();
}
void CashFlow::onDeleteTransaction() {
if (currentTransactionId == -1) {
QMessageBox::warning(this, "No Selection", "Please select a transaction to delete.");
return;
}
if (QMessageBox::question(this, "Confirm Delete",
QString("Delete transaction ID %1?").arg(currentTransactionId)) == QMessageBox::Yes) {
if (database->deleteTransaction(currentTransactionId)) {
clearTransactionEntry();
refreshView();
} else {
QMessageBox::critical(this, "Error", "Failed to delete: " + database->lastError());
}
}
}
void CashFlow::onRecurringSelected() {
QList<QTableWidgetItem*> selected = ui->recurringTable->selectedItems();
if (selected.isEmpty()) {
return;
}
int row = selected[0]->row();
int id = ui->recurringTable->item(row, 0)->text().toInt();
QList<RecurringRule> rules = database->getAllRecurringRules();
for (const RecurringRule &r : rules) {
if (r.id == id) {
loadRecurringToEntry(r);
currentRecurringId = id;
return;
}
}
}
void CashFlow::onSaveRecurring() {
RecurringRule r;
r.id = currentRecurringId;
r.name = ui->recurringNameEdit->text();
r.startDate = ui->recurringStartDateEdit->date();
r.amount = ui->recurringAmountSpin->value();
r.account = ui->recurringAccountCombo->currentText();
r.category = ui->recurringCategoryCombo->currentText();
r.description = ui->recurringDescriptionEdit->text();
r.occurrences = -1; // Default to infinite
QString freqStr = ui->recurringFrequencyCombo->currentText();
if (freqStr == "Daily") {
r.frequency = RecurrenceFrequency::Daily;
r.dayOfWeek = -1;
r.dayOfMonth = -1;
}
else if (freqStr == "Weekly") {
r.frequency = RecurrenceFrequency::Weekly;
r.dayOfWeek = r.startDate.dayOfWeek(); // Use the day of week from start date
r.dayOfMonth = -1;
}
else if (freqStr == "Bi-Weekly") {
r.frequency = RecurrenceFrequency::BiWeekly;
r.dayOfWeek = r.startDate.dayOfWeek(); // Use the day of week from start date
r.dayOfMonth = -1;
}
else if (freqStr == "Monthly") {
r.frequency = RecurrenceFrequency::Monthly;
r.dayOfWeek = -1;
r.dayOfMonth = r.startDate.day(); // Use the day of month from start date
}
else if (freqStr == "Yearly") {
r.frequency = RecurrenceFrequency::Yearly;
r.dayOfWeek = -1;
r.dayOfMonth = r.startDate.day();
}
bool success;
if (currentRecurringId == -1) {
success = database->addRecurringRule(r);
} else {
success = database->updateRecurringRule(r);
}
if (success) {
refreshView();
QMessageBox::information(this, "Success", "Recurring rule saved. Projections updated automatically.");
} else {
QMessageBox::critical(this, "Error", "Failed to save: " + database->lastError());
}
}
void CashFlow::onNewRecurring() {
clearRecurringEntry();
ui->recurringStartDateEdit->setDate(QDate::currentDate());
ui->recurringNameEdit->setFocus();
}
void CashFlow::onDeleteRecurring() {
if (currentRecurringId == -1) {
QMessageBox::warning(this, "No Selection", "Please select a recurring rule to delete.");
return;
}
if (QMessageBox::question(this, "Confirm Delete",
"Delete this recurring rule?") == QMessageBox::Yes) {
if (database->deleteRecurringRule(currentRecurringId)) {
clearRecurringEntry();
refreshView();
} else {
QMessageBox::critical(this, "Error", "Failed to delete: " + database->lastError());
}
}
}
void CashFlow::clearTransactionEntry() {
currentTransactionId = -1;
ui->entryDateEdit->setDate(QDate::currentDate());
ui->entryAmountSpin->setValue(0.0);
ui->entryAccountCombo->setCurrentText("");
ui->entryCategoryCombo->setCurrentText("");
ui->entryDescriptionEdit->clear();
ui->entryTypeCombo->setCurrentIndex(0);
ui->entryRecurringCombo->setCurrentIndex(0); // (None)
ui->entryOccurrenceEdit->clear();
ui->entryOccurrenceEdit->setEnabled(false);
ui->entryStatusLabel->setText("(New transaction)");
updateAmountColors();
}
void CashFlow::loadTransactionToEntry(const Transaction &t) {
// Block signals to prevent auto-save while loading
ui->entryDateEdit->blockSignals(true);
ui->entryAmountSpin->blockSignals(true);
ui->entryAccountCombo->blockSignals(true);
ui->entryCategoryCombo->blockSignals(true);
ui->entryDescriptionEdit->blockSignals(true);
ui->entryTypeCombo->blockSignals(true);
ui->entryRecurringCombo->blockSignals(true);
ui->entryOccurrenceEdit->blockSignals(true);
ui->entryDateEdit->setDate(t.date);
ui->entryAmountSpin->setValue(t.amount);
ui->entryAccountCombo->setCurrentText(t.account);
ui->entryCategoryCombo->setCurrentText(t.category);
ui->entryDescriptionEdit->setText(t.description);
ui->entryTypeCombo->setCurrentIndex(t.type == TransactionType::Actual ? 1 : 0);
// Set recurring rule link if present
if (t.recurringId != -1) {
// Find and select the rule in combo
for (int i = 0; i < ui->entryRecurringCombo->count(); i++) {
if (ui->entryRecurringCombo->itemData(i).toInt() == t.recurringId) {
ui->entryRecurringCombo->setCurrentIndex(i);
break;
}
}
ui->entryOccurrenceEdit->setText(t.occurrenceKey);
ui->entryOccurrenceEdit->setEnabled(true);
} else {
ui->entryRecurringCombo->setCurrentIndex(0); // (None)
ui->entryOccurrenceEdit->clear();
ui->entryOccurrenceEdit->setEnabled(false);
}
ui->entryDateEdit->blockSignals(false);
ui->entryAmountSpin->blockSignals(false);
ui->entryAccountCombo->blockSignals(false);
ui->entryCategoryCombo->blockSignals(false);
ui->entryDescriptionEdit->blockSignals(false);
ui->entryTypeCombo->blockSignals(false);
ui->entryRecurringCombo->blockSignals(false);
ui->entryOccurrenceEdit->blockSignals(false);
updateAmountColors();
}
void CashFlow::clearRecurringEntry() {
currentRecurringId = -1;
ui->recurringNameEdit->clear();
ui->recurringStartDateEdit->setDate(QDate::currentDate());
ui->recurringAmountSpin->setValue(0.0);
ui->recurringAccountCombo->setCurrentText("");
ui->recurringCategoryCombo->setCurrentText("");
ui->recurringDescriptionEdit->clear();
ui->recurringFrequencyCombo->setCurrentIndex(3); // Default to Monthly
updateAmountColors();
}
void CashFlow::loadRecurringToEntry(const RecurringRule &r) {
ui->recurringNameEdit->setText(r.name);
ui->recurringStartDateEdit->setDate(r.startDate);
ui->recurringAmountSpin->setValue(r.amount);
ui->recurringAccountCombo->setCurrentText(r.account);
ui->recurringCategoryCombo->setCurrentText(r.category);
ui->recurringDescriptionEdit->setText(r.description);
int freqIndex = 3; // Default monthly
switch (r.frequency) {
case RecurrenceFrequency::Daily: freqIndex = 0; break;
case RecurrenceFrequency::Weekly: freqIndex = 1; break;
case RecurrenceFrequency::BiWeekly: freqIndex = 2; break;
case RecurrenceFrequency::Monthly: freqIndex = 3; break;
case RecurrenceFrequency::Yearly: freqIndex = 4; break;
default: break;
}
ui->recurringFrequencyCombo->setCurrentIndex(freqIndex);
updateAmountColors();
}
void CashFlow::updateAmountColors() {
// Color code transaction amount
if (ui->entryAmountSpin->value() < 0) {
ui->entryAmountSpin->setStyleSheet("QDoubleSpinBox { color: rgb(200, 0, 0); font-weight: bold; }");
} else if (ui->entryAmountSpin->value() > 0) {
ui->entryAmountSpin->setStyleSheet("QDoubleSpinBox { color: rgb(0, 150, 0); font-weight: bold; }");
} else {
ui->entryAmountSpin->setStyleSheet("");
}
// Color code recurring amount
if (ui->recurringAmountSpin->value() < 0) {
ui->recurringAmountSpin->setStyleSheet("QDoubleSpinBox { color: rgb(200, 0, 0); font-weight: bold; }");
} else if (ui->recurringAmountSpin->value() > 0) {
ui->recurringAmountSpin->setStyleSheet("QDoubleSpinBox { color: rgb(0, 150, 0); font-weight: bold; }");
} else {
ui->recurringAmountSpin->setStyleSheet("");
}
}
void CashFlow::loadSettings() {
// Load settings from database
QString fontFamily = database->getSetting("amount_font", "Courier New");
int fontSize = database->getSetting("amount_font_size", "10").toInt();
int defaultPeriod = database->getSetting("default_period", "2").toInt();
bool showAccountBalances = database->getSetting("show_account_balances", "0").toInt();
weekStartDay = database->getSetting("week_start_day", "1").toInt();
// Apply to member variables and main UI
currentAmountFont = QFont(fontFamily, fontSize);
ui->periodCombo->setCurrentIndex(defaultPeriod);
ui->showAccountBalancesCheck->setChecked(showAccountBalances);
}
QString CashFlow::formatCurrency(double amount) const {
QLocale locale;
return locale.toString(amount, 'f', 2);
}
bool CashFlow::openDatabase(const QString &filePath) {
if (database->open(filePath)) {
currentFilePath = filePath;
QFileInfo fileInfo(filePath);
setWindowTitle(QString("CashFlo - %1").arg(fileInfo.fileName()));
loadSettings();
// Set default date range (current month to 3 months out)
QDate today = QDate::currentDate();
ui->dateFromEdit->setDate(QDate(today.year(), today.month(), 1));
ui->dateToEdit->setDate(today.addMonths(3));
clearTransactionEntry();
clearRecurringEntry();
refreshView();
return true;
}
return false;
}
void CashFlow::onNewFile() {
QString defaultDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QDir().mkpath(defaultDir);
QString fileName = QFileDialog::getSaveFileName(
this,
"New CashFlo File",
defaultDir,
"CashFlo Files (*.cashflo.sqlite);;All Files (*)"
);
if (fileName.isEmpty()) {
return;
}
// Ensure .cashflo.sqlite extension
if (!fileName.endsWith(".cashflo.sqlite", Qt::CaseInsensitive)) {
fileName += ".cashflo.sqlite";
}
// Remove file if it exists
if (QFile::exists(fileName)) {
QFile::remove(fileName);
}
// Close current database
delete database;
database = new Database();
if (!openDatabase(fileName)) {
QMessageBox::critical(this, "Error", "Failed to create new file: " + database->lastError());
}
}
void CashFlow::onOpenFile() {
QString defaultDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QString fileName = QFileDialog::getOpenFileName(
this,
"Open CashFlo File",
defaultDir,
"CashFlo Files (*.cashflo.sqlite);;All Files (*)"
);
if (fileName.isEmpty()) {
return;
}
// Close current database
delete database;
database = new Database();
if (!openDatabase(fileName)) {
QMessageBox::critical(this, "Error", "Failed to open file: " + database->lastError());
}
}
void CashFlow::onQuit() {
QApplication::quit();
}
void CashFlow::onPreferences() {
SettingsDialog dialog(database, this);
if (dialog.exec() == QDialog::Accepted) {
// Reload settings
currentAmountFont = dialog.getCurrentAmountFont();
weekStartDay = dialog.getWeekStartDay();
loadSettings();
refreshView();
}
}
void CashFlow::populateRecurringRulesCombo() {
ui->entryRecurringCombo->clear();
ui->entryRecurringCombo->addItem("(None)", -1);
QList<RecurringRule> rules = database->getAllRecurringRules();
for (const RecurringRule &rule : rules) {
QString label = QString("%1 (%2)").arg(rule.name).arg(
rule.frequency == RecurrenceFrequency::Daily ? "Daily" :
rule.frequency == RecurrenceFrequency::Weekly ? "Weekly" :
rule.frequency == RecurrenceFrequency::BiWeekly ? "Bi-weekly" :
rule.frequency == RecurrenceFrequency::Monthly ? "Monthly" :
rule.frequency == RecurrenceFrequency::Yearly ? "Yearly" : "Unknown"
);
ui->entryRecurringCombo->addItem(label, rule.id);
}
}
QString CashFlow::generateOccurrenceKey(const QDate &date, RecurrenceFrequency frequency) const {
if (frequency == RecurrenceFrequency::Daily) {
return date.toString("yyyy-MM-dd");
} else if (frequency == RecurrenceFrequency::Weekly || frequency == RecurrenceFrequency::BiWeekly) {
return QString("%1-W%2").arg(date.year()).arg(date.weekNumber(), 2, 10, QChar('0'));
} else if (frequency == RecurrenceFrequency::Monthly) {
return date.toString("yyyy-MM");
} else if (frequency == RecurrenceFrequency::Yearly) {
return QString::number(date.year());
}
return QString();
}
void CashFlow::updateOccurrenceKey() {
int ruleId = ui->entryRecurringCombo->currentData().toInt();
if (ruleId == -1) {
ui->entryOccurrenceEdit->clear();
ui->entryOccurrenceEdit->setEnabled(false);
return;
}
ui->entryOccurrenceEdit->setEnabled(true);
// Find the rule to get its frequency
QList<RecurringRule> rules = database->getAllRecurringRules();
for (const RecurringRule &rule : rules) {
if (rule.id == ruleId) {
QString occurrenceKey = generateOccurrenceKey(ui->entryDateEdit->date(), rule.frequency);
ui->entryOccurrenceEdit->setText(occurrenceKey);
break;
}
}
}
void CashFlow::onRecurringRuleChanged() {
updateOccurrenceKey();
}
void CashFlow::onTransactionDateChanged() {
// Update occurrence key if a recurring rule is selected
if (ui->entryRecurringCombo->currentData().toInt() != -1) {
updateOccurrenceKey();
}
}
|