summaryrefslogtreecommitdiff
path: root/geld.cpp
blob: 1482a5ae97a49b7da3f178d5956ff9bdea688d1b (plain)
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
#include "geld.h"
#include "ui_geld.h"
#include <QDir>
#include <QFile>
#include <QtGlobal>
#include <QSqlQueryModel>
#include <QMessageBox>
#include "contraaccount.h"
#include "transactionmodel.h"
#include "transaction.h"


Geld::Geld(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::Geld)
{
    QString f = QDir::home().filePath(".geld.db");
    if(!QFile::exists(f))
        QMessageBox::information(this, "First run",
            "This appears to be your first time running this program, let me use this opportunity to tell you a few things:\n\n"
            "- This program is just a little experiment, don't assume things to work.\n"
            "- All data is saved in a user-global database file which cannot be changed at the moment, so if someone opens this program on your PC, the first thing he/she will see is your financial data.\n"
            "- All data is saved unencrypted, anyone who has access to the database file has access to it's contents.\n"
            "- This program is still in development, older database files may not be compatible with newer versions of the software.\n"
            "- A simple excel sheet may very well be more useful than this program.\n"
            "- This program is written by an engineer who knows nothing about finance");
    ui->setupUi(this);
    initDB(f);

    TransactionModel *transmod = new TransactionModel(ui->tableTransactions);
    ui->tableTransactions->setModel(transmod);
    ui->tableTransactions->setColumnHidden(0, true);

    QSqlQueryModel *contramod = new QSqlQueryModel(ui->tableContra);
    ui->tableContra->setModel(contramod);
    ui->tableTransactions->setColumnHidden(0, true);
    refreshLists();

    // the Qt Designer interface lacks functionality for connecting actions to widgets
    ui->tableTransactions->addAction(ui->actionTransAdd);
    ui->tableTransactions->addAction(ui->actionTransEdit);
    ui->tableTransactions->addAction(ui->actionTransDelete);

    ui->tableContra->addAction(ui->actionContraAdd);
    ui->tableContra->addAction(ui->actionContraEdit);
    ui->tableContra->addAction(ui->actionContraDelete);

    // the Qt Designer interface also lacks some functionality when it comes to connecting signals to functions
    connect(ui->btnAddTransaction,  SIGNAL(clicked()),                  this, SLOT(addTransaction()));
    connect(ui->actionTransAdd,     SIGNAL(triggered()),                this, SLOT(addTransaction()));
    connect(ui->btnEditTransaction, SIGNAL(clicked()),                  this, SLOT(editTransaction()));
    connect(ui->actionTransEdit,    SIGNAL(triggered()),                this, SLOT(editTransaction()));
    connect(ui->tableTransactions,  SIGNAL(doubleClicked(QModelIndex)), this, SLOT(editTransaction()));
    connect(ui->actionTransDelete,  SIGNAL(triggered()),                this, SLOT(deleteTransaction()));

    connect(ui->btnAddContra,       SIGNAL(clicked()),                  this, SLOT(addContra()));
    connect(ui->actionContraAdd,    SIGNAL(triggered()),                this, SLOT(addContra()));
    connect(ui->btnEditContra,      SIGNAL(clicked()),                  this, SLOT(editContra()));
    connect(ui->actionContraEdit,   SIGNAL(triggered()),                this, SLOT(editContra()));
    connect(ui->tableContra,        SIGNAL(doubleClicked(QModelIndex)), this, SLOT(editContra()));
    connect(ui->actionContraDelete, SIGNAL(triggered()),                this, SLOT(deleteContra()));

    ui->statusBar->showMessage(QString("Opened database file %1").arg(f), 0);
}


Geld::~Geld()
{
    closeDB();
    delete ui;
}


void Geld::initDB(QString file)
{
    // open or create database file
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(file);
    Q_ASSERT(db.open()); // assuming this doesn't fail to keep the code simple

    // create tables
    QSqlQuery q;
    q.exec("CREATE TABLE IF NOT EXISTS contra_accounts ("
       "id INTEGER PRIMARY KEY,"
       "account TEXT,"   // account number
       "name TEXT,"
       "address TEXT"
       ")"
    );
    q.exec("CREATE TABLE IF NOT EXISTS transactions ("
       "id INTEGER PRIMARY KEY,"
       "amount INTEGER,"            // amount in cents
       "date TEXT,"                 // yyyy-mm-dd
       "contra INTEGER REFERENCES contra_accounts (id)," // contra account
       "description TEXT"
       ")"
    );
}


void Geld::closeDB()
{
    QString conn;
    {
        QSqlDatabase db = QSqlDatabase::database();
        conn = db.connectionName();
        db.close();
    }
    QSqlDatabase::removeDatabase(conn);
}

void Geld::refreshLists() {
    ui->tableTransactions->horizontalHeader()->setStretchLastSection(false);
    ((TransactionModel *) ui->tableTransactions->model())->refresh();
    ui->tableTransactions->resizeColumnsToContents();
    ui->tableTransactions->horizontalHeader()->setStretchLastSection(true);

    QSqlQuery q;
    q.exec("SELECT SUM(amount) FROM transactions");
    q.next();
    ui->lblTransactionBalance->setText(QString("Balance: <span style=\"color: %1\">%2</span>")
        .arg(q.value(0).toInt() < 0 ? "red" : "green").arg(q.value(0).toDouble()/100, 4, 'f', 2));

    ui->tableContra->horizontalHeader()->setStretchLastSection(false);
    QSqlQueryModel *m = (QSqlQueryModel *)ui->tableContra->model();
    m->setQuery(
         "SELECT c.id, c.account, c.name, COUNT(t.id), c.address "
           "FROM contra_accounts c "
      "LEFT JOIN transactions t ON t.contra = c.id "
       "GROUP BY c.id "
       "ORDER BY name"
    );
    m->setHeaderData(0, Qt::Horizontal, "ID");
    m->setHeaderData(1, Qt::Horizontal, "Account");
    m->setHeaderData(2, Qt::Horizontal, "Name");
    m->setHeaderData(3, Qt::Horizontal, "Transactions");
    m->setHeaderData(4, Qt::Horizontal, "Address");
    ui->tableContra->setColumnHidden(0, true);
    ui->tableContra->resizeColumnsToContents();
    ui->tableContra->horizontalHeader()->setStretchLastSection(true);
}

int Geld::selectedTransaction()
{
    // this. is. soooooooo. ugly.
    TransactionModel *mod = (TransactionModel *) ui->tableTransactions->model();
    QModelIndexList indexes = ui->tableTransactions->selectionModel()->selection().indexes();
    if(indexes.count() != mod->columnCount()) {
        ui->statusBar->showMessage("Nothing selected.", 3000);
        return 0;
    }
    return mod->data(mod->index(indexes.at(0).row(), 0), Qt::DisplayRole).toInt();
}

void Geld::editTransaction()
{
    int id = selectedTransaction();
    if(!id)
        return;
    Transaction t(this);
    t.load(id);
    if(t.exec() == QDialog::Accepted) {
        t.save(id);
        refreshLists();
    }
}

void Geld::addTransaction()
{
    Transaction t(this);
    if(t.exec() == QDialog::Accepted) {
        t.save();
        refreshLists();
    }
}

void Geld::deleteTransaction()
{
    int id = selectedTransaction();
    if(!id)
        return;
    if(QMessageBox::question(this, "You sure?", "Are you sure you want to remove the selected transaction?", QMessageBox::No|QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) {
        QSqlQuery q;
        q.prepare("DELETE FROM transactions WHERE id = ?");
        q.addBindValue(id);
        q.exec();
        refreshLists();
    }
}

int Geld::selectedContra()
{
    // this. is. soooooooo. ugly.
    QAbstractItemModel *mod = ui->tableContra->model();
    QModelIndexList indexes = ui->tableContra->selectionModel()->selection().indexes();
    if(indexes.count() != mod->columnCount()) {
        ui->statusBar->showMessage("Nothing selected.", 3000);
        return 0;
    }
    return mod->data(mod->index(indexes.at(0).row(), 0), Qt::DisplayRole).toInt();
}

void Geld::addContra()
{
    ContraAccount c(this);
    if(c.exec() == QDialog::Accepted) {
        c.save();
        refreshLists();
    }
}

void Geld::editContra()
{
    int id = selectedContra();
    if(!id)
        return;
    ContraAccount c(this);
    c.load(id);
    if(c.exec() == QDialog::Accepted) {
        c.save(id);
        refreshLists();
    }
}

void Geld::deleteContra()
{
    int id = selectedContra();
    if(!id)
        return;
    QSqlQuery q;
    q.prepare("SELECT 1 FROM transactions WHERE contra = ? LIMIT 1");
    q.addBindValue(id);
    q.exec();
    if(q.next()) {
        QMessageBox::critical(this, "Can't delete contra account",
            "This contra account appears to be refered to from a transaction. "
            "Please make sure there are no transactions with this contra account in the database and try again."
        );
        return;
    }
    if(QMessageBox::question(this, "You sure?", "Are you sure you want to remove the selected contra account?", QMessageBox::No|QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) {
        QSqlQuery q;
        q.prepare("DELETE FROM contra_accounts WHERE id = ?");
        q.addBindValue(id);
        q.exec();
        refreshLists();
    }
}