Transaction View: LastMonth calculation fixed
[novacoin.git] / src / qt / transactionview.cpp
1 #include "transactionview.h"
2
3 #include "transactionfilterproxy.h"
4 #include "transactionrecord.h"
5 #include "walletmodel.h"
6 #include "addresstablemodel.h"
7 #include "transactiontablemodel.h"
8 #include "bitcoinunits.h"
9 #include "csvmodelwriter.h"
10 #include "transactiondescdialog.h"
11 #include "editaddressdialog.h"
12 #include "optionsmodel.h"
13 #include "guiutil.h"
14 #include "wallet.h"
15
16 #include <QScrollBar>
17 #include <QComboBox>
18 #include <QDoubleValidator>
19 #include <QHBoxLayout>
20 #include <QVBoxLayout>
21 #include <QLineEdit>
22 #include <QTableView>
23 #include <QHeaderView>
24 #include <QPushButton>
25 #include <QMessageBox>
26 #include <QPoint>
27 #include <QMenu>
28 #include <QApplication>
29 #include <QClipboard>
30 #include <QLabel>
31 #include <QDateTimeEdit>
32 #include <QDesktopServices>
33 #include <QSignalMapper>
34 #include <QUrl>
35 #include <QEventLoop>
36
37 TransactionView::TransactionView(QWidget *parent) :
38     QWidget(parent), model(0), transactionProxyModel(0),
39     transactionView(0)
40 {
41     // Build filter row
42     setContentsMargins(0,0,0,0);
43
44     QHBoxLayout *hlayout = new QHBoxLayout();
45     hlayout->setContentsMargins(0,0,0,0);
46 #ifdef Q_OS_MAC
47     hlayout->setSpacing(5);
48     hlayout->addSpacing(26);
49 #else
50     hlayout->setSpacing(0);
51     hlayout->addSpacing(23);
52 #endif
53
54     dateWidget = new QComboBox(this);
55 #ifdef Q_OS_MAC
56     dateWidget->setFixedWidth(121);
57 #else
58     dateWidget->setFixedWidth(120);
59 #endif
60     dateWidget->addItem(tr("All"), All);
61     dateWidget->addItem(tr("Today"), Today);
62     dateWidget->addItem(tr("This week"), ThisWeek);
63     dateWidget->addItem(tr("This month"), ThisMonth);
64     dateWidget->addItem(tr("Last month"), LastMonth);
65     dateWidget->addItem(tr("This year"), ThisYear);
66     dateWidget->addItem(tr("Range..."), Range);
67     hlayout->addWidget(dateWidget);
68
69     typeWidget = new QComboBox(this);
70 #ifdef Q_OS_MAC
71     typeWidget->setFixedWidth(121);
72 #else
73     typeWidget->setFixedWidth(120);
74 #endif
75
76     typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES);
77     typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |
78                                         TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));
79     typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |
80                                   TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));
81     typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));
82     typeWidget->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));
83     typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other));
84
85     hlayout->addWidget(typeWidget);
86
87     addressWidget = new QLineEdit(this);
88 #if QT_VERSION >= 0x040700
89     /* Do not move this to the XML file, Qt before 4.7 will choke on it */
90     addressWidget->setPlaceholderText(tr("Enter address or label to search"));
91 #endif
92     hlayout->addWidget(addressWidget);
93
94     amountWidget = new QLineEdit(this);
95 #if QT_VERSION >= 0x040700
96     /* Do not move this to the XML file, Qt before 4.7 will choke on it */
97     amountWidget->setPlaceholderText(tr("Min amount"));
98 #endif
99 #ifdef Q_OS_MAC
100     amountWidget->setFixedWidth(97);
101 #else
102     amountWidget->setFixedWidth(100);
103 #endif
104     amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));
105     hlayout->addWidget(amountWidget);
106
107     QVBoxLayout *vlayout = new QVBoxLayout(this);
108     vlayout->setContentsMargins(0,0,0,0);
109     vlayout->setSpacing(0);
110
111     QTableView *view = new QTableView(this);
112     vlayout->addLayout(hlayout);
113     vlayout->addWidget(createDateRangeWidget());
114     vlayout->addWidget(view);
115     vlayout->setSpacing(0);
116     int width = view->verticalScrollBar()->sizeHint().width();
117     // Cover scroll bar width with spacing
118 #ifdef Q_OS_MAC
119     hlayout->addSpacing(width+2);
120 #else
121     hlayout->addSpacing(width);
122 #endif
123     // Always show scroll bar
124     view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
125     view->setTabKeyNavigation(false);
126     view->setContextMenuPolicy(Qt::CustomContextMenu);
127
128     transactionView = view;
129
130     // Actions
131     QAction *copyAddressAction = new QAction(tr("Copy address"), this);
132     QAction *copyLabelAction = new QAction(tr("Copy label"), this);
133     QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
134     QAction *copyTxIDAction = new QAction(tr("Copy transaction ID"), this);
135     QAction *editLabelAction = new QAction(tr("Edit label"), this);
136     QAction *showDetailsAction = new QAction(tr("Show transaction details"), this);
137     QAction *clearOrphansAction = new QAction(tr("Clear orphans"), this);
138
139     contextMenu = new QMenu();
140     contextMenu->addAction(copyAddressAction);
141     contextMenu->addAction(copyLabelAction);
142     contextMenu->addAction(copyAmountAction);
143     contextMenu->addAction(copyTxIDAction);
144     contextMenu->addAction(editLabelAction);
145     contextMenu->addAction(showDetailsAction);
146     contextMenu->addSeparator();
147     contextMenu->addAction(clearOrphansAction);
148
149     mapperThirdPartyTxUrls = new QSignalMapper(this);
150
151     // Connect actions
152     connect(mapperThirdPartyTxUrls, SIGNAL(mapped(QString)), this, SLOT(openThirdPartyTxUrl(QString)));
153
154     connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));
155     connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));
156     connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));
157     connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));
158
159     connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));
160     connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
161
162     connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
163     connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
164     connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
165     connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID()));
166     connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));
167     connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));
168     connect(clearOrphansAction, SIGNAL(triggered()), this, SLOT(clearOrphans()));
169 }
170
171 void TransactionView::setModel(WalletModel *model, bool fShoudAddThirdPartyURL)
172 {
173     this->model = model;
174     if(model)
175     {
176         transactionProxyModel = new TransactionFilterProxy(this);
177         transactionProxyModel->setSourceModel(model->getTransactionTableModel());
178         transactionProxyModel->setDynamicSortFilter(true);
179         transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
180         transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
181
182         transactionProxyModel->setSortRole(Qt::EditRole);
183 //        transactionProxyModel->setSortRole(TransactionTableModel::DateRole);
184
185         transactionView->setModel(transactionProxyModel);
186         transactionView->setAlternatingRowColors(true);
187         transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);
188         transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);
189         transactionView->setSortingEnabled(true);
190         transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);
191         transactionView->verticalHeader()->hide();
192
193         transactionView->horizontalHeader()->resizeSection(
194                 TransactionTableModel::Status, 23);
195         transactionView->horizontalHeader()->resizeSection(
196                 TransactionTableModel::Date, 120);
197         transactionView->horizontalHeader()->resizeSection(
198                 TransactionTableModel::Type, 120);
199 #if QT_VERSION < 0x050000
200         transactionView->horizontalHeader()->setResizeMode(
201                 TransactionTableModel::ToAddress, QHeaderView::Stretch);
202 #else
203         transactionView->horizontalHeader()->setSectionResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);
204 #endif
205         transactionView->horizontalHeader()->resizeSection(
206                 TransactionTableModel::Amount, 130);
207
208         if (model->getOptionsModel() && fShoudAddThirdPartyURL)
209         {
210             // Add third party transaction URLs to context menu
211             QStringList listUrls = model->getOptionsModel()->getThirdPartyTxUrls().split("|", QString::SkipEmptyParts);
212             for (int i = 0; i < listUrls.size(); ++i)
213             {
214                 QString host = QUrl(listUrls[i].trimmed(), QUrl::StrictMode).host();
215                 if (!host.isEmpty())
216                 {
217                     QAction *thirdPartyTxUrlAction = new QAction(host, this); // use host as menu item label
218                     if (i == 0)
219                         contextMenu->addSeparator();
220                     contextMenu->addAction(thirdPartyTxUrlAction);
221                     connect(thirdPartyTxUrlAction, SIGNAL(triggered()), mapperThirdPartyTxUrls, SLOT(map()));
222                     mapperThirdPartyTxUrls->setMapping(thirdPartyTxUrlAction, listUrls[i].trimmed());
223                  }
224              }
225         }
226     }
227 }
228
229 void TransactionView::chooseDate(int idx)
230 {
231     if(!transactionProxyModel)
232         return;
233     QDate current = QDate::currentDate();
234     dateRangeWidget->setVisible(false);
235     switch(dateWidget->itemData(idx).toInt())
236     {
237     case All:
238         transactionProxyModel->setDateRange(
239                 TransactionFilterProxy::MIN_DATE,
240                 TransactionFilterProxy::MAX_DATE);
241         break;
242     case Today:
243         transactionProxyModel->setDateRange(
244                 QDateTime(current),
245                 TransactionFilterProxy::MAX_DATE);
246         break;
247     case ThisWeek: {
248         // Find last Monday
249         QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));
250         transactionProxyModel->setDateRange(
251                 QDateTime(startOfWeek),
252                 TransactionFilterProxy::MAX_DATE);
253
254         } break;
255     case ThisMonth:
256         transactionProxyModel->setDateRange(
257                 QDateTime(QDate(current.year(), current.month(), 1)),
258                 TransactionFilterProxy::MAX_DATE);
259         break;
260     case LastMonth:
261         transactionProxyModel->setDateRange(
262                 QDateTime(QDate(current.year(), current.month(), 1).addMonths(-1)),
263                 QDateTime(QDate(current.year(), current.month(), 1)));
264         break;
265     case ThisYear:
266         transactionProxyModel->setDateRange(
267                 QDateTime(QDate(current.year(), 1, 1)),
268                 TransactionFilterProxy::MAX_DATE);
269         break;
270     case Range:
271         dateRangeWidget->setVisible(true);
272         dateRangeChanged();
273         break;
274     }
275 }
276
277 void TransactionView::chooseType(int idx)
278 {
279     if(!transactionProxyModel)
280         return;
281     transactionProxyModel->setTypeFilter(
282         typeWidget->itemData(idx).toInt());
283 }
284
285 void TransactionView::changedPrefix(const QString &prefix)
286 {
287     if(!transactionProxyModel)
288         return;
289     transactionProxyModel->setAddressPrefix(prefix);
290 }
291
292 void TransactionView::changedAmount(const QString &amount)
293 {
294     if(!transactionProxyModel)
295         return;
296     qint64 amount_parsed = 0;
297     if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))
298     {
299         transactionProxyModel->setMinAmount(amount_parsed);
300     }
301     else
302     {
303         transactionProxyModel->setMinAmount(0);
304     }
305 }
306
307 void TransactionView::exportClicked()
308 {
309     // CSV is currently the only supported format
310     QString filename = GUIUtil::getSaveFileName(
311             this,
312             tr("Export Transaction Data"), QString(),
313             tr("Comma separated file (*.csv)"));
314
315     if (filename.isNull()) return;
316
317     CSVModelWriter writer(filename);
318
319     // name, column, role
320     writer.setModel(transactionProxyModel);
321     writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole);
322     writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole);
323     writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole);
324     writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole);
325     writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole);
326     writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole);
327     writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole);
328
329     if(!writer.write())
330     {
331         QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
332                               QMessageBox::Abort, QMessageBox::Abort);
333     }
334 }
335
336 void TransactionView::contextualMenu(const QPoint &point)
337 {
338     QModelIndex index = transactionView->indexAt(point);
339     if(index.isValid())
340     {
341         contextMenu->exec(QCursor::pos());
342     }
343 }
344
345 void TransactionView::copyAddress()
346 {
347     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);
348 }
349
350 void TransactionView::copyLabel()
351 {
352     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);
353 }
354
355 void TransactionView::copyAmount()
356 {
357     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);
358 }
359
360 void TransactionView::copyTxID()
361 {
362     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::TxIDRole);
363 }
364
365 void TransactionView::editLabel()
366 {
367     if(!transactionView->selectionModel() ||!model)
368         return;
369     QModelIndexList selection = transactionView->selectionModel()->selectedRows();
370     if(!selection.isEmpty())
371     {
372         AddressTableModel *addressBook = model->getAddressTableModel();
373         if(!addressBook)
374             return;
375         QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();
376         if(address.isEmpty())
377         {
378             // If this transaction has no associated address, exit
379             return;
380         }
381         // Is address in address book? Address book can miss address when a transaction is
382         // sent from outside the UI.
383         int idx = addressBook->lookupAddress(address);
384         if(idx != -1)
385         {
386             // Edit sending / receiving address
387             QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());
388             // Determine type of address, launch appropriate editor dialog type
389             QString type = modelIdx.data(AddressTableModel::TypeRole).toString();
390
391             EditAddressDialog dlg(type==AddressTableModel::Receive
392                                          ? EditAddressDialog::EditReceivingAddress
393                                          : EditAddressDialog::EditSendingAddress,
394                                   this);
395             dlg.setModel(addressBook);
396             dlg.loadRow(idx);
397             dlg.exec();
398         }
399         else
400         {
401             // Add sending address
402             EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,
403                                   this);
404             dlg.setModel(addressBook);
405             dlg.setAddress(address);
406             dlg.exec();
407         }
408     }
409 }
410
411 void TransactionView::showDetails()
412 {
413     if(!transactionView->selectionModel())
414         return;
415     QModelIndexList selection = transactionView->selectionModel()->selectedRows();
416     if(!selection.isEmpty())
417     {
418         TransactionDescDialog dlg(selection.at(0));
419         dlg.setWindowModality(Qt::ApplicationModal);
420         dlg.show();
421
422         // This loop will wait for the window is closed
423         QEventLoop loop;
424         connect(&dlg, SIGNAL(stopExec()), &loop, SLOT(quit()));
425         loop.exec();
426     }
427 }
428
429 void TransactionView::clearOrphans()
430 {
431     if(!model)
432         return;
433
434     model->clearOrphans();
435     model->getTransactionTableModel()->refresh();
436     delete transactionProxyModel;
437     setModel(model, false);
438     transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);
439     transactionView->sortByColumn(TransactionTableModel::Date, Qt::DescendingOrder);
440 }
441
442 void TransactionView::openThirdPartyTxUrl(QString url)
443 {
444     if(!transactionView->selectionModel())
445        return;
446     QModelIndexList selection = transactionView->selectionModel()->selectedRows(0);
447     if(!selection.isEmpty())
448         QDesktopServices::openUrl(QUrl::fromUserInput(url.replace("%s", selection.at(0).data(TransactionTableModel::TxHashRole).toString())));
449 }
450
451 QWidget *TransactionView::createDateRangeWidget()
452 {
453     dateRangeWidget = new QFrame();
454     dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
455     dateRangeWidget->setContentsMargins(1,1,1,1);
456     QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);
457     layout->setContentsMargins(0,0,0,0);
458     layout->addSpacing(23);
459     layout->addWidget(new QLabel(tr("Range:")));
460
461     dateFrom = new QDateTimeEdit(this);
462     dateFrom->setDisplayFormat("dd/MM/yy");
463     dateFrom->setCalendarPopup(true);
464     dateFrom->setMinimumWidth(100);
465     dateFrom->setDate(QDate::currentDate().addDays(-7));
466     layout->addWidget(dateFrom);
467     layout->addWidget(new QLabel(tr("to")));
468
469     dateTo = new QDateTimeEdit(this);
470     dateTo->setDisplayFormat("dd/MM/yy");
471     dateTo->setCalendarPopup(true);
472     dateTo->setMinimumWidth(100);
473     dateTo->setDate(QDate::currentDate());
474     layout->addWidget(dateTo);
475     layout->addStretch();
476
477     // Hide by default
478     dateRangeWidget->setVisible(false);
479
480     // Notify on change
481     connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
482     connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
483
484     return dateRangeWidget;
485 }
486
487 void TransactionView::dateRangeChanged()
488 {
489     if(!transactionProxyModel)
490         return;
491     transactionProxyModel->setDateRange(
492             QDateTime(dateFrom->date()),
493             QDateTime(dateTo->date()).addDays(1));
494 }
495
496 void TransactionView::focusTransaction(const QModelIndex &idx)
497 {
498     if(!transactionProxyModel)
499         return;
500     QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx);
501     transactionView->scrollTo(targetIdx);
502     transactionView->setCurrentIndex(targetIdx);
503     transactionView->setFocus();
504 }