-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainwindow.cpp
525 lines (455 loc) · 16.5 KB
/
mainwindow.cpp
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
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QMessageBox"
#include "QtDebug"
#include "definitions.h"
#include <QLocale>
//#define pathDB "/shared/coin/coin.db"
#define pathDB "/home/spencer/dev/coin/coin/coin.db"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
//set the ui
ui->setupUi(this);
ui->dateEdit->setDate(QDate::currentDate()); //set the date to today
ui->lineEditAmount->setValidator(new QDoubleValidator(-INFINITY,INFINITY,2)); //force 2-decimal number in amount field
ui->comboAccounts->hide(); //hide the transfer to account combobox
ui->lblFilterTotal->hide(); //hide the filter total
//set the db and open
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(pathDB);
QFileInfo checkFile(pathDB);
if(!checkFile.isFile() or !db.open())
{
QMessageBox::critical(0, qApp->tr("Cannot open database"),
qApp->tr("Unable to establish a database connection.\n"
"Click Cancel to exit."), QMessageBox::Cancel);
QApplication::quit();
}
//establish accounts and select first account
refreshAccountTree();
ui->treeAccounts->expandAll();
//set up transactions table
transactions = new TransactionsModel(this);
transactions->refresh();
//set up the filters
accountFilter = new QSortFilterProxyModel(this);
reconcileFilter = new QSortFilterProxyModel(this);
commentFilter = new QSortFilterProxyModel(this);
accountFilter->setFilterKeyColumn(col_id_account);
reconcileFilter->setFilterKeyColumn(col_reconciled);
commentFilter->setFilterKeyColumn(col_comment);
accountFilter->setDynamicSortFilter(true);
reconcileFilter->setDynamicSortFilter(true);
commentFilter->setDynamicSortFilter(true);
accountFilter->setSourceModel(transactions);
reconcileFilter->setSourceModel(accountFilter);
commentFilter->setSourceModel(reconcileFilter);
if (ui->treeAccounts->selectedItems().count() == 1) //filter the table based on the selection in the accounts tree
{
accountFilter->setFilterFixedString(QString::number(getAccountId()));
}
ui->tableTransactions->setModel(commentFilter); //filter the table for tag searches in the box
//hide the pk_uid, id_account, and related account columns
//and size the remaining columns appropriately
ui->tableTransactions->hideColumn(col_pk_uid);
ui->tableTransactions->hideColumn(col_id_account);
ui->tableTransactions->hideColumn(col_relate_account);
ui->tableTransactions->hideColumn(col_reconciled);
QHeaderView *h = ui->tableTransactions->horizontalHeader();
h->setStretchLastSection(false);
h->setSectionResizeMode(col_date,QHeaderView::Fixed);
h->setSectionResizeMode(col_comment,QHeaderView::Stretch); //make the comments column stretch to fill leftover space
h->setSectionResizeMode(col_amount,QHeaderView::Fixed);
h->setSectionResizeMode(col_total,QHeaderView::Fixed);
h->resizeSection(col_date,100);
h->resizeSection(col_amount,100);
h->resizeSection(col_total,120);
//select the first account (so that there is a selection active)
ui->treeAccounts->setCurrentItem(ui->treeAccounts->itemAt(0,0));
}
MainWindow::~MainWindow()
{
delete ui;
db.close();
}
void MainWindow::refreshAccountTree()
{
// int previousSelectionId = getAccountId(); //save the currently-selected pk_uid. if no selection, returns -1
ui->treeAccounts->clear();
QSqlQuery *parentAccounts;
QSqlQuery *childAccounts;
//get the parent accounts
parentAccounts = new QSqlQuery();
parentAccounts->exec("SELECT pk_uid, account_name FROM account WHERE id_parent IS NULL ORDER BY account_name");
while(parentAccounts->next())
{
QTreeWidgetItem *itmParent;
itmParent = new QTreeWidgetItem();
itmParent->setText(0,parentAccounts->value(1).toString());
itmParent->setData(0,Qt::UserRole,parentAccounts->value(0).toInt());
//add the parent entry
ui->treeAccounts->addTopLevelItem(itmParent);
//get the child accounts
childAccounts = new QSqlQuery();
childAccounts->prepare("SELECT pk_uid, account_name FROM account WHERE id_parent=? ORDER BY account_name");
childAccounts->addBindValue(parentAccounts->value(0));
childAccounts->exec();
while(childAccounts->next())
{
QTreeWidgetItem *itmChild;
itmChild = new QTreeWidgetItem();
itmChild->setText(0,childAccounts->value(1).toString());
itmChild->setData(0,Qt::UserRole,childAccounts->value(0).toInt());
itmParent->addChild(itmChild);
}
}
}
void MainWindow::on_btnAccept_clicked()
{
double transactionAmount, transferAmount;
int accountId, transferAccountId, firstTransactionId, secondTransactionId;
QString transactionComment, transactionDate;
//get the account id and the information from the fields
accountId = getAccountId();
transferAccountId = ui->comboAccounts->itemData(ui->comboAccounts->currentIndex()).toInt();
transactionAmount = ui->lineEditAmount->text().toDouble();
transferAmount = transactionAmount*-1;
transactionComment = ui->lineEditTransactionInfo->text();
transactionDate = ui->dateEdit->date().toString("yyyy-MM-dd");
//check to see if this is a transfer
if (ui->transferCheckBox->isChecked()) //this is a transfer
{
QSqlQuery q;
//perform the first part of the transfer. if it fails, kick out an error message and exit routine
if(!transactions->addTransaction(accountId,transactionDate,transactionComment,transactionAmount))
{
transactionFailedError(qApp->tr("Could not add transaction."));
return;
}
//get the id of the first part of the transfer
q.exec("SELECT last_insert_rowid()");
q.first();
firstTransactionId = q.value(0).toInt();
//perform the second part of the transfer. if it fails, kick out an error message and exit routine
if(!transactions->addTransaction(transferAccountId,transactionDate,transactionComment,transferAmount))
{
transactionFailedError(qApp->tr("Could not add transaction."));
return;
}
//get the id of the second part of the transfer
q.clear();
q.exec("SELECT last_insert_rowid()");
q.first();
q.value(0);
secondTransactionId = q.value(0).toInt();
if(!transactions->addTransactionRelation(firstTransactionId,secondTransactionId))
{
transactionFailedError(qApp->tr("Could not add transaction."));
return;
}
if(!transactions->addTransactionRelation(secondTransactionId,firstTransactionId))
{
transactionFailedError(qApp->tr("Could not add transaction."));
return;
}
}
else //this is not a transfer
{
//perform the transaction. if it fails, kick out an error message
if(!transactions->addTransaction(accountId,transactionDate,transactionComment,transactionAmount))
{
transactionFailedError(qApp->tr("Could not add transaction."));
return;
}
}
//clear the amount and comment lines
ui->lineEditAmount->clear();
ui->lineEditTransactionInfo->clear();
//clear the transfer checkbox and hide the combobox
ui->transferCheckBox->setChecked(false);
ui->comboAccounts->clear();
ui->comboAccounts->hide();
//refresh the table
transactions->refresh();
//scroll to the bottom
ui->tableTransactions->scrollToBottom();
}
void MainWindow::on_treeAccounts_itemSelectionChanged()
{
transactions->refresh();
accountFilter->setFilterFixedString(QString::number(getAccountId()));
//if the transfer combobox is showing, update the accounts to reflect the change
if (ui->transferCheckBox->checkState() == Qt::Checked)
{
ui->comboAccounts->clear();
fillAccountCombo();
}
//scroll to the bottom of the transactions
ui->tableTransactions->scrollToBottom();
//reset filtered amount label if visible
if ( ! ui->lblFilterTotal->isHidden() )
{
setFilterAmount();
}
}
/*
* returns the pk_uid of the account selected in the account tree view
*/
int MainWindow::getAccountId()
{
if (ui->treeAccounts->selectedItems().count() == 0)
{
return -1;
}
else
{
return ui->treeAccounts->selectedItems().first()->data(0,Qt::UserRole).toInt();
}
}
QString MainWindow::getAccountName()
{
return ui->treeAccounts->selectedItems().first()->data(0,Qt::DisplayRole).toString();
}
/*
* returns the pk_uid of the transaction selected in the transactions table
*/
int MainWindow::getTransactionId()
{
int rowId;
rowId = ui->tableTransactions->selectionModel()->currentIndex().row();
return getTransactionId(rowId);
}
/*
* returns the pk_uid of the transaction at the given row position in the transactions table
*/
int MainWindow::getTransactionId(int rowNum)
{
int transactionId;
transactionId = ui->tableTransactions->model()->data(ui->tableTransactions->model()->index(rowNum,col_pk_uid)).toInt();
return transactionId;
}
/*
* right click menu for transactions
*/
void MainWindow::on_tableTransactions_customContextMenuRequested(const QPoint &pos)
{
//test for a click in empty table space, or for no selection
if (ui->tableTransactions->selectionModel()->selectedRows().count() < 1 || !ui->tableTransactions->indexAt(pos).isValid())
{
return;
}
QMenu *transactionsMenu;
QPoint globalPos = ui->tableTransactions->mapToGlobal(pos);
QMenu *accountsMenu;
QSqlQuery q;
QString moveText;
QString deleteText;
QString reconcileText;
//set the menu item text based on the number of selected transactions
if (ui->tableTransactions->selectionModel()->selectedRows().count() == 1)
{
moveText = "Move transaction";
deleteText = "Delete this transaction";
}
else
{
moveText = "Move transactions";
deleteText = "Delete these transactions";
}
reconcileText = "Mark as reconciled"; //not dependent on number of transactions selected
//create the menus
transactionsMenu = new QMenu(this);
accountsMenu = new QMenu(moveText,transactionsMenu);
transactionsMenu->addMenu(accountsMenu);
//add the delete transaction action
QAction *deleteAction;
deleteAction = new QAction(deleteText,transactionsMenu);
deleteAction->setData("delete");
transactionsMenu->addAction(deleteAction);
//add the reconcile action
QAction *reconcileAction;
reconcileAction = new QAction(reconcileText,transactionsMenu);
reconcileAction->setData("reconcile");
transactionsMenu->addAction(reconcileAction);
//query the accounts
q.prepare("SELECT pk_uid, account_name FROM account WHERE pk_uid <> ? ORDER BY account_name");
q.addBindValue(QString::number(getAccountId()));
q.exec();
//iterate through the accounts selected in the sql query, create an action for each, and populate the submenu
while (q.next())
{
QAction *a;
a = new QAction(q.value(1).toString(),accountsMenu);
a->setData(q.value(0).toInt()); //need to store the pk_uid for each account with the menu item
accountsMenu->addAction(a);
}
//show the menu and get the selected menu item
QAction *selectedMenuItem = transactionsMenu->exec(globalPos);
if (selectedMenuItem)
{
QItemSelectionModel *rowsSelectionModel;
QModelIndexList rowsList;
//set up the selection model and get the pk_uid column of the selected rows
rowsSelectionModel = ui->tableTransactions->selectionModel();
rowsList = rowsSelectionModel->selectedRows(col_pk_uid);
//iterate through the selection and perform the selected task on each
//selected transaction
QList<QModelIndex>::Iterator i;
for (i = rowsList.begin(); i != rowsList.end(); ++i)
{
int transactionId;
transactionId = i->data().toInt();
if(selectedMenuItem->data() == "delete") //if the user clicked on "delete this transaction"
{
if(!transactions->deleteTransaction(transactionId))
{
transactionFailedError(qApp->tr("Could not delete transaction."));
return;
}
}
else if(selectedMenuItem->data() == "reconcile")
{
if(!transactions->setReconcile(transactionId,true))
{
transactionFailedError(qApp->tr("Could not set as reconciled."));
return;
}
}
else //the user selected an account to move the transaction to
{
int accountId = selectedMenuItem->data().toInt();
if (!transactions->moveTransaction(accountId, transactionId))
{
transactionFailedError(qApp->tr("Could not move transaction."));
return;
}
}
}
transactions->refresh();
ui->tableTransactions->scrollToBottom();
}
}
/*
* toggle checkbox for a transfer
*/
void MainWindow::on_transferCheckBox_stateChanged(int arg1)
{
if (arg1 == 0) //if the user unchecked the transfer
{
ui->comboAccounts->clear();
ui->comboAccounts->hide();
}
else //if the user checked for a transfer
{
fillAccountCombo();
ui->comboAccounts->show();
}
}
/*
* fills the account combobox with accounts for a transfer transaction
*/
void MainWindow::fillAccountCombo()
{
//query the accounts
QSqlQuery q;
q.prepare("SELECT pk_uid, account_name FROM account WHERE pk_uid <> ? ORDER BY account_name");
q.addBindValue(QString::number(getAccountId()));
q.exec();
//add accounts to the combobox
while(q.next())
{
ui->comboAccounts->addItem(q.value(1).toString(),q.value(0));
}
}
/*
* sets a word filter on transactions
*/
void MainWindow::on_lineEditFilter_textChanged(const QString &arg1)
{
commentFilter->setFilterRegExp(arg1);
if (0 < arg1.length())
{
ui->lblFilterTotal->show();
setFilterAmount();
}
else
{
ui->lblFilterTotal->hide();
}
}
void MainWindow::transactionFailedError(QString errMessage)
{
QMessageBox::critical(0, qApp->tr("Transaction Error"),
errMessage, QMessageBox::Cancel);
return;
}
void MainWindow::on_btnAddAccount_clicked()
{
}
void MainWindow::on_btnDeleteAccount_clicked()
{
QString selectedAccountName = getAccountName();
QString warningMessage = qApp->tr("This will delete account ");
warningMessage.append(selectedAccountName);
if (QMessageBox::warning(0,qApp->tr("Delete Account"),
warningMessage,
QMessageBox::Ok | QMessageBox::Cancel)
== QMessageBox::Ok)
{
int accountId = getAccountId();
//remove any transactions associated with this account
QSqlQuery q;
q.prepare("DELETE FROM trans WHERE id_account = ?");
q.addBindValue(accountId);
if(!q.exec())
{
transactionFailedError(qApp->tr("Could not delete account"));
}
//remove the account
q.clear();
q.prepare("DELETE FROM account WHERE pk_uid = ?");
q.addBindValue(accountId);
if(!q.exec())
{
transactionFailedError(qApp->tr("Could not delete account"));
}
}
refreshAccountTree();
}
void MainWindow::on_actionReconciled_triggered(bool checked)
{
if (checked)
{
reconcileFilter->setFilterFixedString(QString::number(0)); //filter the table for unreconciled transactions only
}
else
{
reconcileFilter->setFilterFixedString(QString());
}
return;
}
float MainWindow::sumColumn(int column)
{
float sum = 0;
//iterate rows
for(int i = 0; i < commentFilter->rowCount(); ++i)
{
float f;
QString t;
QModelIndex idx;
idx = commentFilter->index(i,column,QModelIndex());
f = ui->tableTransactions->model()->data(idx,Qt::EditRole).toFloat(); // <--- the problem is with the userrole
sum = sum + f;
}
return sum;
}
void MainWindow::setFilterAmount()
{
QString amt;
QLocale us(QLocale::English,QLocale::UnitedStates);
amt = "Filter total: ";
amt.append(us.toCurrencyString(sumColumn(col_amount),us.currencySymbol()));
ui->lblFilterTotal->setText(amt);
}