khomeview_p.h 72.8 KB
Newer Older
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
/***************************************************************************
                          khomeview_p.h  -  description
                             -------------------
    begin                : Tue Jan 22 2002
    copyright            : (C) 2000-2002 by Michael Edwardes <mte@users.sourceforge.net>
                           Javier Campos Morales <javi_c@users.sourceforge.net>
                           Felix Rodriguez <frodriguez@users.sourceforge.net>
                           John C <thetacoturtle@users.sourceforge.net>
                           Thomas Baumgart <ipwizard@users.sourceforge.net>
                           Kevin Tambascio <ktambascio@users.sourceforge.net>
                           (C) 2017 by Łukasz Wojniłowicz <lukasz.wojnilowicz@gmail.com>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#ifndef KHOMEVIEW_P_H
#define KHOMEVIEW_P_H

#include "khomeview.h"

Heiko Becker's avatar
Heiko Becker committed
28
29
#include <config-kmymoney.h>

30
31
32
33
34
35
36
37
38
39
40
41
// ----------------------------------------------------------------------------
// QT Includes

#include <QList>
#include <QPixmap>
#include <QTimer>
#include <QBuffer>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QUrlQuery>
#include <QWheelEvent>
#include <QPrintDialog>
42
#include <QVBoxLayout>
43
44
45
46
47
#include <QPrinter>
#ifdef ENABLE_WEBENGINE
#include <QWebEngineView>
#else
#include <KWebView>
48
#include <QWebFrame>
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#endif

// ----------------------------------------------------------------------------
// KDE Includes

#include <KLocalizedString>
#include <KXmlGuiWindow>
#include <KActionCollection>
#include <KMessageBox>

// ----------------------------------------------------------------------------
// Project Includes

#include "kmymoneyviewbase_p.h"
#include "mymoneyutils.h"
#include "kmymoneyutils.h"
#include "kwelcomepage.h"
66
#include "kmymoneysettings.h"
67
68
69
#include "mymoneyfile.h"
#include "mymoneyaccount.h"
#include "mymoneyprice.h"
70
71
#include "mymoneyreport.h"
#include "mymoneymoney.h"
72
73
74
75
76
77
78
79
#include "mymoneyforecast.h"
#include "mymoneysplit.h"
#include "mymoneytransaction.h"
#include "icons.h"
#include "kmymoneywebpage.h"
#include "mymoneyschedule.h"
#include "mymoneysecurity.h"
#include "mymoneyexception.h"
80
#include "kmymoneyplugin.h"
81
82
#include "mymoneyenums.h"
#include "menuenums.h"
83
#include "plugins/views/reports/reportsviewenums.h"
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

#define VIEW_LEDGER         "ledger"
#define VIEW_SCHEDULE       "schedule"
#define VIEW_WELCOME        "welcome"
#define VIEW_HOME           "home"
#define VIEW_REPORTS        "reports"

using namespace Icons;
using namespace eMyMoney;

/**
 * @brief Converts a QPixmap to an data URI scheme
 *
 * According to RFC 2397
 *
 * @param pixmap Source to convert
 * @return full data URI
 */
QString QPixmapToDataUri(const QPixmap& pixmap)
{
  QImage image(pixmap.toImage());
  QByteArray byteArray;
  QBuffer buffer(&byteArray);
  buffer.open(QIODevice::WriteOnly);
  image.save(&buffer, "PNG"); // writes the image in PNG format inside the buffer
  return QLatin1String("data:image/png;base64,") + QString(byteArray.toBase64());
}

bool accountNameLess(const MyMoneyAccount &acc1, const MyMoneyAccount &acc2)
{
  return acc1.name().localeAwareCompare(acc2.name()) < 0;
}

class KHomeViewPrivate : public KMyMoneyViewBasePrivate
{
  Q_DECLARE_PUBLIC(KHomeView)

public:
  explicit KHomeViewPrivate(KHomeView *qq) :
    KMyMoneyViewBasePrivate(),
    q_ptr(qq),
125
    m_view(nullptr),
126
127
    m_showAllSchedules(false),
    m_needLoad(true),
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
128
    m_netWorthGraphLastValidSize(400, 300),
129
    m_scrollBarPos(0)
130
131
132
133
134
  {
  }

  ~KHomeViewPrivate() {
    // if user wants to remember the font size, store it here
135
136
137
    if (KMyMoneySettings::rememberZoomFactor() && m_view) {
        KMyMoneySettings::setZoomFactor(m_view->zoomFactor());
        KMyMoneySettings::self()->save();
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
      }
  }

  /**
    * Definition of bitmap used as argument for showAccounts().
    */
  enum paymentTypeE {
    Preferred = 1,          ///< show preferred accounts
    Payment = 2             ///< show payment accounts
  };

  void init()
  {
    Q_Q(KHomeView);
    m_needLoad = false;

    auto vbox = new QVBoxLayout(q);
    q->setLayout(vbox);
    vbox->setSpacing(6);
    vbox->setMargin(0);

  #ifdef ENABLE_WEBENGINE
    m_view = new QWebEngineView(q);
  #else
    m_view = new KWebView(q);
  #endif
    m_view->setPage(new MyQWebEnginePage(m_view));

    vbox->addWidget(m_view);

  #ifdef ENABLE_WEBENGINE
    q->connect(m_view->page(), &QWebEnginePage::urlChanged,
            q, &KHomeView::slotOpenUrl);
  #else
    m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    q->connect(m_view->page(), &KWebPage::linkClicked,
            q, &KHomeView::slotOpenUrl);
  #endif
176
177

    q->connect(MyMoneyFile::instance(), &MyMoneyFile::dataChanged, q, &KHomeView::refresh);
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
  }

  /**
    * Print an account and its balance and limit
    */
  void showAccountEntry(const MyMoneyAccount& acc, const MyMoneyMoney& value, const MyMoneyMoney& valueToMinBal, const bool showMinBal)
  {
    MyMoneyFile* file = MyMoneyFile::instance();
    QString tmp;
    MyMoneySecurity currency = file->currency(acc.currencyId());
    QString amount;
    QString amountToMinBal;

    //format amounts
    amount = MyMoneyUtils::formatMoney(value, acc, currency);
    amount.replace(QChar(' '), "&nbsp;");
    if (showMinBal) {
      amountToMinBal = MyMoneyUtils::formatMoney(valueToMinBal, acc, currency);
      amountToMinBal.replace(QChar(' '), "&nbsp;");
    }

199
    QString cellStatus, pathOK, pathTODO, pathNotOK;
200

201
    if (KMyMoneySettings::showBalanceStatusOfOnlineAccounts()) {
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
      //show account's online-status
      pathOK = QPixmapToDataUri(Icons::get(Icon::DialogOKApply).pixmap(QSize(16,16)));
      pathTODO = QPixmapToDataUri(Icons::get(Icon::MailReceive).pixmap(QSize(16,16)));
      pathNotOK = QPixmapToDataUri(Icons::get(Icon::DialogCancel).pixmap(QSize(16,16)));

      if (acc.value("lastImportedTransactionDate").isEmpty() || acc.value("lastStatementBalance").isEmpty())
        cellStatus = '-';
      else if (file->hasMatchingOnlineBalance(acc)) {
        if (file->hasNewerTransaction(acc.id(), QDate::fromString(acc.value("lastImportedTransactionDate"), Qt::ISODate)))
          cellStatus = QString("<img src=\"%1\" border=\"0\">").arg(pathTODO);
        else
          cellStatus = QString("<img src=\"%1\" border=\"0\">").arg(pathOK);
      } else
        cellStatus = QString("<img src=\"%1\" border=\"0\">").arg(pathNotOK);

      tmp = QString("<td class=\"center\">%1</td>").arg(cellStatus);
    }

220
221
222
223
224
225
226
227
228
    tmp += QString("<td>") + link(VIEW_LEDGER, QString("?id=%1").arg(acc.id()));
    if (acc.isClosed()) {
      tmp += QLatin1String("<strike>");
    }
    tmp +=  acc.name();
    if (acc.isClosed()) {
      tmp += QLatin1String("</strike>");
    }
    tmp += linkend() + "</td>";
229
230
231
232

    int countNotMarked = 0, countCleared = 0, countNotReconciled = 0;
    QString countStr;

233
    if (KMyMoneySettings::showCountOfUnmarkedTransactions() || KMyMoneySettings::showCountOfNotReconciledTransactions())
Thomas Baumgart's avatar
Thomas Baumgart committed
234
      countNotMarked = m_transactionStats[acc.id()][(int)Split::State::NotReconciled];
235

236
    if (KMyMoneySettings::showCountOfClearedTransactions() || KMyMoneySettings::showCountOfNotReconciledTransactions())
Thomas Baumgart's avatar
Thomas Baumgart committed
237
      countCleared = m_transactionStats[acc.id()][(int)Split::State::Cleared];
238

239
    if (KMyMoneySettings::showCountOfNotReconciledTransactions())
240
241
      countNotReconciled = countNotMarked + countCleared;

242
    if (KMyMoneySettings::showCountOfUnmarkedTransactions()) {
243
244
245
246
247
248
249
      if (countNotMarked)
        countStr = QString("%1").arg(countNotMarked);
      else
        countStr = '-';
      tmp += QString("<td class=\"center\">%1</td>").arg(countStr);
    }

250
    if (KMyMoneySettings::showCountOfClearedTransactions()) {
251
252
253
254
255
256
257
      if (countCleared)
        countStr = QString("%1").arg(countCleared);
      else
        countStr = '-';
      tmp += QString("<td class=\"center\">%1</td>").arg(countStr);
    }

258
    if (KMyMoneySettings::showCountOfNotReconciledTransactions()) {
259
260
261
262
263
264
265
      if (countNotReconciled)
        countStr = QString("%1").arg(countNotReconciled);
      else
        countStr = '-';
      tmp += QString("<td class=\"center\">%1</td>").arg(countStr);
    }

266
    if (KMyMoneySettings::showDateOfLastReconciliation()) {
267
      const auto lastReconciliationDate = acc.lastReconciliationDate().toString(Qt::SystemLocaleShortDate).replace(QChar(' '), "&nbsp;");
268
269
270
      tmp += QString("<td>%1</d>").arg(lastReconciliationDate);
    }

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
    //show account balance
    tmp += QString("<td class=\"right\">%1</td>").arg(showColoredAmount(amount, value.isNegative()));

    //show minimum balance column if requested
    if (showMinBal) {
      //if it is an investment, show minimum balance empty
      if (acc.accountType() == Account::Type::Investment) {
        tmp += QString("<td class=\"right\">&nbsp;</td>");
      } else {
        //show minimum balance entry
        tmp += QString("<td class=\"right\">%1</td>").arg(showColoredAmount(amountToMinBal, valueToMinBal.isNegative()));
      }
    }
    // qDebug("accountEntry = '%s'", tmp.toLatin1());
    m_html += tmp;
  }

  void showAccountEntry(const MyMoneyAccount& acc)
  {
290
    const auto file = MyMoneyFile::instance();
291
292
    MyMoneyMoney value;

293
    bool showLimit = KMyMoneySettings::showLimitInfo();
294
295
296
297
298
299
300
301
302
303
304

    if (acc.accountType() == Account::Type::Investment) {
      //investment accounts show the balances of all its subaccounts
      value = investmentBalance(acc);

      //investment accounts have no minimum balance
      showAccountEntry(acc, value, MyMoneyMoney(), showLimit);
    } else {
      //get balance for normal accounts
      value = file->balance(acc.id(), QDate::currentDate());
      if (acc.currencyId() != file->baseCurrency().id()) {
305
306
307
        const auto curPrice = file->price(acc.tradingCurrencyId(), file->baseCurrency().id(), QDate::currentDate());
        const auto curRate = curPrice.rate(file->baseCurrency().id());
        auto baseValue = value * curRate;
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
        baseValue = baseValue.convert(file->baseCurrency().smallestAccountFraction());
        m_total += baseValue;
      } else {
        m_total += value;
      }
      //if credit card or checkings account, show maximum credit
      if (acc.accountType() == Account::Type::CreditCard ||
          acc.accountType() == Account::Type::Checkings) {
        QString maximumCredit = acc.value("maxCreditAbsolute");
        if (maximumCredit.isEmpty()) {
          maximumCredit = acc.value("minBalanceAbsolute");
        }
        MyMoneyMoney maxCredit = MyMoneyMoney(maximumCredit);
        showAccountEntry(acc, value, value - maxCredit, showLimit);
      } else {
        //otherwise use minimum balance
        QString minimumBalance = acc.value("minBalanceAbsolute");
        MyMoneyMoney minBalance = MyMoneyMoney(minimumBalance);
        showAccountEntry(acc, value, value - minBalance, showLimit);
      }
    }
  }

  /**
    * @param acc the investment account
    * @return the balance in the currency of the investment account
    */
  MyMoneyMoney investmentBalance(const MyMoneyAccount& acc)
  {
    auto file = MyMoneyFile::instance();
    auto value = file->balance(acc.id(), QDate::currentDate());
    foreach (const auto accountID, acc.accountList()) {
      auto stock = file->account(accountID);
      if (!stock.isClosed()) {
        try {
          MyMoneyMoney val;
          MyMoneyMoney balance = file->balance(stock.id(), QDate::currentDate());
          MyMoneySecurity security = file->security(stock.currencyId());
          const MyMoneyPrice &price = file->price(stock.currencyId(), security.tradingCurrency());
          val = (balance * price.rate(security.tradingCurrency())).convertPrecision(security.pricePrecision());
          // adjust value of security to the currency of the account
          MyMoneySecurity accountCurrency = file->currency(acc.currencyId());
          val = val * file->price(security.tradingCurrency(), accountCurrency.id()).rate(accountCurrency.id());
          val = val.convert(acc.fraction());
          value += val;
        } catch (const MyMoneyException &e) {
          qWarning("%s", qPrintable(QString("cannot convert stock balance of %1 to base currency: %2").arg(stock.name(), e.what())));
        }
      }
    }
    return value;
  }

  /**
   * Print text in the color set for negative numbers, if @p amount is negative
   * abd @p isNegative is true
   */
  QString showColoredAmount(const QString& amount, bool isNegative)
  {
    if (isNegative) {
      //if negative, get the settings for negative numbers
369
      return QString("<font color=\"%1\">%2</font>").arg(KMyMoneySettings::schemeColor(SchemeColor::Negative).name(), amount);
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    }

    //if positive, return the same string
    return amount;
  }

  /**
   * Run the forecast
   */
  void doForecast()
  {
    //clear m_accountList because forecast is about to changed
    m_accountList.clear();

    //reinitialize the object
385
    m_forecast = KMyMoneyUtils::forecast();
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

    //If forecastDays lower than accountsCycle, adjust to the first cycle
    if (m_forecast.accountsCycle() > m_forecast.forecastDays())
      m_forecast.setForecastDays(m_forecast.accountsCycle());

    //Get all accounts of the right type to calculate forecast
    m_forecast.doForecast();
  }

  /**
   * Calculate the forecast balance after a payment has been made
   */
  MyMoneyMoney forecastPaymentBalance(const MyMoneyAccount& acc, const MyMoneyMoney& payment, QDate& paymentDate)
  {
    //if paymentDate before or equal to currentDate set it to current date plus 1
    //so we get to accumulate forecast balance correctly
    if (paymentDate <= QDate::currentDate())
      paymentDate = QDate::currentDate().addDays(1);

    //check if the account is already there
    if (m_accountList.find(acc.id()) == m_accountList.end()
        || m_accountList[acc.id()].find(paymentDate) == m_accountList[acc.id()].end()) {
      if (paymentDate == QDate::currentDate()) {
        m_accountList[acc.id()][paymentDate] = m_forecast.forecastBalance(acc, paymentDate);
      } else {
        m_accountList[acc.id()][paymentDate] = m_forecast.forecastBalance(acc, paymentDate.addDays(-1));
      }
    }
    m_accountList[acc.id()][paymentDate] = m_accountList[acc.id()][paymentDate] + payment;
    return m_accountList[acc.id()][paymentDate];
  }

  void loadView()
  {
420
    Q_Q(KHomeView);
421
    m_view->setZoomFactor(KMyMoneySettings::zoomFactor());
422
423

    QList<MyMoneyAccount> list;
Thomas Baumgart's avatar
Thomas Baumgart committed
424
    if (MyMoneyFile::instance()->storage()) {
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
425
      MyMoneyFile::instance()->accountList(list);
Thomas Baumgart's avatar
Thomas Baumgart committed
426
    }
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
427
    if (list.isEmpty()) {
428
429
      m_view->setHtml(KWelcomePage::welcomePage(), QUrl("file://"));
    } else {
Thomas Baumgart's avatar
Thomas Baumgart committed
430
431
432
      // preload transaction statistics
      m_transactionStats = MyMoneyFile::instance()->countTransactionsWithSpecificReconciliationState();

433
      // keep current location on page
434
435
436
      m_scrollBarPos = 0;
#ifndef ENABLE_WEBENGINE
      m_scrollBarPos = m_view->page()->mainFrame()->scrollBarValue(Qt::Vertical);
437
438
#endif

439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
      //clear the forecast flag so it will be reloaded
      m_forecast.setForecastDone(false);

      const QString filename = QStandardPaths::locate(QStandardPaths::AppConfigLocation, "html/kmymoney.css");
      QString header = QString("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\">\n<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"%1\">\n").arg(QUrl::fromLocalFile(filename).url());

      header += KMyMoneyUtils::variableCSS();

      header += "</head><body id=\"summaryview\">\n";

      QString footer = "</body></html>\n";

      m_html.clear();
      m_html += header;

      m_html += QString("<div id=\"summarytitle\">%1</div>").arg(i18n("Your Financial Summary"));

456
      QStringList settings = KMyMoneySettings::listOfItems();
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

      QStringList::ConstIterator it;

      for (it = settings.constBegin(); it != settings.constEnd(); ++it) {
        int option = (*it).toInt();
        if (option > 0) {
          switch (option) {
            case 1:         // payments
              showPayments();
              break;

            case 2:         // preferred accounts
              showAccounts(Preferred, i18n("Preferred Accounts"));
              break;

            case 3:         // payment accounts
              // Check if preferred accounts are shown separately
              if (settings.contains("2")) {
                showAccounts(static_cast<paymentTypeE>(Payment | Preferred),
                             i18n("Payment Accounts"));
              } else {
                showAccounts(Payment, i18n("Payment Accounts"));
              }
              break;
            case 4:         // favorite reports
              showFavoriteReports();
              break;
            case 5:         // forecast
              showForecast();
              break;
            case 6:         // net worth graph over all accounts
              showNetWorthGraph();
              break;
490
491
            case 7:         // forecast (history) - currently unused
              break;
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
            case 8:         // assets and liabilities
              showAssetsLiabilities();
              break;
            case 9:         // budget
              showBudget();
              break;
            case 10:         // cash flow summary
              showCashFlowSummary();
              break;
          }
          m_html += "<div class=\"gap\">&nbsp;</div>\n";
        }
      }

      m_html += "<div id=\"returnlink\">";
      m_html += link(VIEW_WELCOME, QString()) + i18n("Show KMyMoney welcome page") + linkend();
      m_html += "</div>";
      m_html += "<div id=\"vieweffect\"></div>";
      m_html += footer;

      m_view->setHtml(m_html, QUrl("file://"));
513

514
515
516
#ifndef ENABLE_WEBENGINE
      if (m_scrollBarPos) {
        QMetaObject::invokeMethod(q, "slotAdjustScrollPos", Qt::QueuedConnection);
517
      }
518
#endif
519
520
521
522
523
524
525
526
527
528
    }
  }

  void showNetWorthGraph()
  {
    Q_Q(KHomeView);

    // Adjust the size
    QSize netWorthGraphSize = q->size();
    netWorthGraphSize -= QSize(80, 30);
529
    m_netWorthGraphLastValidSize = netWorthGraphSize;
530

531
    m_html += QString("<div class=\"shadow\"><div class=\"displayblock\"><div class=\"summaryheader\">%1</div>\n<div class=\"gap\">&nbsp;</div>\n").arg(i18n("Net Worth Forecast"));
532
533
    m_html += QString("<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >");
    m_html += QString("<tr>");
534
535
536
537
538
539
540
541
542
543
544
545
546

    if (const auto reportsPlugin = pPlugins.data.value(QStringLiteral("reportsview"), nullptr)) {
      const auto variantReport = reportsPlugin->requestData(QString(), eWidgetPlugin::WidgetType::NetWorthForecast);
      if (!variantReport.isNull()) {
        auto report = variantReport.value<QWidget *>();
        report->resize(m_netWorthGraphLastValidSize);
        m_html += QString("<td><center><img src=\"%1\" ALT=\"Networth\" width=\"100%\" ></center></td>").arg(QPixmapToDataUri(report->grab()));
        delete report;
      }
    } else {
      m_html += QString("<td><center>%1</center></td>").arg(i18n("Enable reports plugin to see this chart."));
    }

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
    m_html += QString("</tr>");
    m_html += QString("</table></div></div>");
  }

  void showPayments()
  {
    MyMoneyFile* file = MyMoneyFile::instance();
    QList<MyMoneySchedule> overdues;
    QList<MyMoneySchedule> schedule;
    int i = 0;

    //if forecast has not been executed yet, do it.
    if (!m_forecast.isForecastDone())
      doForecast();

    schedule = file->scheduleList(QString(), Schedule::Type::Any,
                                  Schedule::Occurrence::Any,
                                  Schedule::PaymentType::Any,
                                  QDate::currentDate(),
                                  QDate::currentDate().addMonths(1), false);
    overdues = file->scheduleList(QString(), Schedule::Type::Any,
                                  Schedule::Occurrence::Any,
                                  Schedule::PaymentType::Any,
                                  QDate(), QDate(), true);

    if (schedule.empty() && overdues.empty())
      return;

    // HACK
    // Remove the finished schedules
    QList<MyMoneySchedule>::Iterator d_it;
    //regular schedules
    d_it = schedule.begin();
    while (d_it != schedule.end()) {
      if ((*d_it).isFinished()) {
        d_it = schedule.erase(d_it);
        continue;
      }
      ++d_it;
    }
    //overdue schedules
    d_it = overdues.begin();
    while (d_it != overdues.end()) {
      if ((*d_it).isFinished()) {
        d_it = overdues.erase(d_it);
        continue;
      }
      ++d_it;
    }

    m_html += "<div class=\"shadow\"><div class=\"displayblock\">";
    m_html += QString("<div class=\"summaryheader\">%1</div>\n").arg(i18n("Payments"));

    if (!overdues.isEmpty()) {
      m_html += "<div class=\"gap\">&nbsp;</div>\n";

      qSort(overdues);
      QList<MyMoneySchedule>::Iterator it;
      QList<MyMoneySchedule>::Iterator it_f;

      m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
      m_html += QString("<tr class=\"itemtitle warningtitle\" ><td colspan=\"5\">%1</td></tr>\n").arg(showColoredAmount(i18n("Overdue payments"), true));
      m_html += "<tr class=\"item warning\">";
      m_html += "<td class=\"left\" width=\"10%\">";
      m_html += i18n("Date");
      m_html += "</td>";
      m_html += "<td class=\"left\" width=\"40%\">";
      m_html += i18n("Schedule");
      m_html += "</td>";
      m_html += "<td class=\"left\" width=\"20%\">";
      m_html += i18n("Account");
      m_html += "</td>";
      m_html += "<td class=\"right\" width=\"15%\">";
      m_html += i18n("Amount");
      m_html += "</td>";
      m_html += "<td class=\"right\" width=\"15%\">";
      m_html += i18n("Balance after");
      m_html += "</td>";
      m_html += "</tr>";

      for (it = overdues.begin(); it != overdues.end(); ++it) {
        // determine number of overdue payments
        int cnt =
          (*it).transactionsRemainingUntil(QDate::currentDate().addDays(-1));

        m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
        showPaymentEntry(*it, cnt);
        m_html += "</tr>";
      }
      m_html += "</table>";
    }

    if (!schedule.isEmpty()) {
      qSort(schedule);

      // Extract todays payments if any
      QList<MyMoneySchedule> todays;
      QList<MyMoneySchedule>::Iterator t_it;
      for (t_it = schedule.begin(); t_it != schedule.end();) {
        if ((*t_it).adjustedNextDueDate() == QDate::currentDate()) {
          todays.append(*t_it);
          (*t_it).setNextDueDate((*t_it).nextPayment(QDate::currentDate()));

          // if adjustedNextDueDate is still currentDate then remove it from
          // scheduled payments
          if ((*t_it).adjustedNextDueDate() == QDate::currentDate()) {
            t_it = schedule.erase(t_it);
            continue;
          }
        }
        ++t_it;
      }

      if (todays.count() > 0) {
        m_html += "<div class=\"gap\">&nbsp;</div>\n";
        m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
        m_html += QString("<tr class=\"itemtitle\"><td class=\"left\" colspan=\"5\">%1</td></tr>\n").arg(i18n("Today's due payments"));
        m_html += "<tr class=\"item\">";
        m_html += "<td class=\"left\" width=\"10%\">";
        m_html += i18n("Date");
        m_html += "</td>";
        m_html += "<td class=\"left\" width=\"40%\">";
        m_html += i18n("Schedule");
        m_html += "</td>";
        m_html += "<td class=\"left\" width=\"20%\">";
        m_html += i18n("Account");
        m_html += "</td>";
        m_html += "<td class=\"right\" width=\"15%\">";
        m_html += i18n("Amount");
        m_html += "</td>";
        m_html += "<td class=\"right\" width=\"15%\">";
        m_html += i18n("Balance after");
        m_html += "</td>";
        m_html += "</tr>";

        for (t_it = todays.begin(); t_it != todays.end(); ++t_it) {
          m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
          showPaymentEntry(*t_it);
          m_html += "</tr>";
        }
        m_html += "</table>";
      }

      if (!schedule.isEmpty()) {
        m_html += "<div class=\"gap\">&nbsp;</div>\n";

        QList<MyMoneySchedule>::Iterator it;

        m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
        m_html += QString("<tr class=\"itemtitle\"><td class=\"left\" colspan=\"5\">%1</td></tr>\n").arg(i18n("Future payments"));
        m_html += "<tr class=\"item\">";
        m_html += "<td class=\"left\" width=\"10%\">";
        m_html += i18n("Date");
        m_html += "</td>";
        m_html += "<td class=\"left\" width=\"40%\">";
        m_html += i18n("Schedule");
        m_html += "</td>";
        m_html += "<td class=\"left\" width=\"20%\">";
        m_html += i18n("Account");
        m_html += "</td>";
        m_html += "<td class=\"right\" width=\"15%\">";
        m_html += i18n("Amount");
        m_html += "</td>";
        m_html += "<td class=\"right\" width=\"15%\">";
        m_html += i18n("Balance after");
        m_html += "</td>";
        m_html += "</tr>";

        // show all or the first 6 entries
        int cnt;
        cnt = (m_showAllSchedules) ? -1 : 6;
        bool needMoreLess = m_showAllSchedules;

        QDate lastDate = QDate::currentDate().addMonths(1);
        qSort(schedule);
        do {
          it = schedule.begin();
          if (it == schedule.end())
            break;

          // if the next due date is invalid (schedule is finished)
          // we remove it from the list
          QDate nextDate = (*it).nextDueDate();
          if (!nextDate.isValid()) {
            schedule.erase(it);
            continue;
          }

          if (nextDate > lastDate)
            break;

          if (cnt == 0) {
            needMoreLess = true;
            break;
          }

          // in case we've shown the current recurrence as overdue,
          // we don't show it here again, but keep the schedule
          // as it might show up later in the list again
          if (!(*it).isOverdue()) {
            if (cnt > 0)
              --cnt;

            m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
            showPaymentEntry(*it);
            m_html += "</tr>";

            // for single occurrence we have reported everything so we
            // better get out of here.
            if ((*it).occurrence() == Schedule::Occurrence::Once) {
              schedule.erase(it);
              continue;
            }
          }

          // if nextPayment returns an invalid date, setNextDueDate will
          // just skip it, resulting in a loop
          // we check the resulting date and erase the schedule if invalid
          if (!((*it).nextPayment((*it).nextDueDate())).isValid()) {
            schedule.erase(it);
            continue;
          }

          (*it).setNextDueDate((*it).nextPayment((*it).nextDueDate()));
          qSort(schedule);
        } while (1);

        if (needMoreLess) {
          m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
          m_html += "<td colspan=\"5\">";
          if (m_showAllSchedules) {
            m_html += link(VIEW_SCHEDULE,  QString("?mode=%1").arg("reduced")) + i18nc("Less...", "Show fewer schedules on the list") + linkend();
          } else {
            m_html += link(VIEW_SCHEDULE,  QString("?mode=%1").arg("full")) + i18nc("More...", "Show more schedules on the list") + linkend();
          }
          m_html += "</td>";
          m_html += "</tr>";
        }
        m_html += "</table>";
      }
    }
    m_html += "</div></div>";
  }

  void showPaymentEntry(const MyMoneySchedule& sched, int cnt = 1)
  {
    QString tmp;
    MyMoneyFile* file = MyMoneyFile::instance();

    try {
      MyMoneyAccount acc = sched.account();
      if (!acc.id().isEmpty()) {
        MyMoneyTransaction t = sched.transaction();
        // only show the entry, if it is still active
        if (!sched.isFinished()) {
          MyMoneySplit sp = t.splitByAccount(acc.id(), true);

          QString pathEnter = QPixmapToDataUri(Icons::get(Icon::KeyEnter).pixmap(QSize(16,16)));
Dawid Wróbel's avatar
Dawid Wróbel committed
805
          QString pathSkip = QPixmapToDataUri(Icons::get(Icon::SkipForward).pixmap(QSize(16, 16)));
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

          //show payment date
          tmp = QString("<td>") +
                QLocale().toString(sched.adjustedNextDueDate(), QLocale::ShortFormat) +
                "</td><td>";
          if (!pathEnter.isEmpty())
            tmp += link(VIEW_SCHEDULE, QString("?id=%1&amp;mode=enter").arg(sched.id()), i18n("Enter schedule")) + QString("<img src=\"%1\" border=\"0\"></a>").arg(pathEnter) + linkend();
          if (!pathSkip.isEmpty())
            tmp += "&nbsp;" + link(VIEW_SCHEDULE, QString("?id=%1&amp;mode=skip").arg(sched.id()), i18n("Skip schedule")) + QString("<img src=\"%1\" border=\"0\"></a>").arg(pathSkip) + linkend();

          tmp += QString("&nbsp;");
          tmp += link(VIEW_SCHEDULE, QString("?id=%1&amp;mode=edit").arg(sched.id()), i18n("Edit schedule")) + sched.name() + linkend();

          //show quantity of payments overdue if any
          if (cnt > 1)
            tmp += i18np(" (%1 payment)", " (%1 payments)", cnt);

          //show account of the main split
          tmp += "</td><td>";
          tmp += QString(file->account(acc.id()).name());

          //show amount of the schedule
          tmp += "</td><td align=\"right\">";

          const MyMoneySecurity& currency = MyMoneyFile::instance()->currency(acc.currencyId());
          MyMoneyMoney payment = MyMoneyMoney(sp.value(t.commodity(), acc.currencyId()) * cnt);
          QString amount = MyMoneyUtils::formatMoney(payment, acc, currency);
          amount.replace(QChar(' '), "&nbsp;");
          tmp += showColoredAmount(amount, payment.isNegative());
          tmp += "</td>";
          //show balance after payments
          tmp += "<td align=\"right\">";
          QDate paymentDate = QDate(sched.adjustedNextDueDate());
          MyMoneyMoney balanceAfter = forecastPaymentBalance(acc, payment, paymentDate);
          QString balance = MyMoneyUtils::formatMoney(balanceAfter, acc, currency);
          balance.replace(QChar(' '), "&nbsp;");
          tmp += showColoredAmount(balance, balanceAfter.isNegative());
          tmp += "</td>";

          // qDebug("paymentEntry = '%s'", tmp.toLatin1());
          m_html += tmp;
        }
      }
    } catch (const MyMoneyException &e) {
850
      qDebug("Unable to display schedule entry: %s", e.what());
851
852
853
854
855
856
857
858
859
    }
  }

  void showAccounts(paymentTypeE type, const QString& header)
  {
    MyMoneyFile* file = MyMoneyFile::instance();
    int prec = MyMoneyMoney::denomToPrec(file->baseCurrency().smallestAccountFraction());
    QList<MyMoneyAccount> accounts;

860
    const auto showClosedAccounts = !KMyMoneySettings::hideClosedAccounts() || KMyMoneySettings::showAllAccounts();
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

    // get list of all accounts
    file->accountList(accounts);
    for (QList<MyMoneyAccount>::Iterator it = accounts.begin(); it != accounts.end();) {
      bool removeAccount = false;
      if (!(*it).isClosed() || showClosedAccounts) {
        switch ((*it).accountType()) {
          case Account::Type::Expense:
          case Account::Type::Income:
            // never show a category account
            // Note: This might be different in a future version when
            //       the homepage also shows category based information
            removeAccount = true;
            break;

            // Asset and Liability accounts are only shown if they
            // have the preferred flag set
          case Account::Type::Asset:
          case Account::Type::Liability:
          case Account::Type::Investment:
            // if preferred accounts are requested, then keep in list
            if ((*it).value("PreferredAccount") != "Yes"
                || (type & Preferred) == 0) {
              removeAccount = true;
            }
            break;

            // Check payment accounts. If payment and preferred is selected,
            // then always show them. If only payment is selected, then
            // show only if preferred flag is not set.
          case Account::Type::Checkings:
          case Account::Type::Savings:
          case Account::Type::Cash:
          case Account::Type::CreditCard:
            switch (type & (Payment | Preferred)) {
              case Payment:
                if ((*it).value("PreferredAccount") == "Yes")
                  removeAccount = true;
                break;

              case Preferred:
                if ((*it).value("PreferredAccount") != "Yes")
                  removeAccount = true;
                break;

              case Payment | Preferred:
                break;

              default:
                removeAccount = true;
                break;
            }
            break;

            // filter all accounts that are not used on homepage views
          default:
            removeAccount = true;
            break;
        }

      } else if ((*it).isClosed() || (*it).isInvest()) {
        // don't show if closed or a stock account
        removeAccount = true;
      }

      if (removeAccount)
        it = accounts.erase(it);
      else
        ++it;
    }

    if (!accounts.isEmpty()) {
      // sort the accounts by name
      qStableSort(accounts.begin(), accounts.end(), accountNameLess);
      QString tmp;
      int i = 0;
      tmp = "<div class=\"shadow\"><div class=\"displayblock\"><div class=\"summaryheader\">" + header + "</div>\n<div class=\"gap\">&nbsp;</div>\n";
      m_html += tmp;
      m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
      m_html += "<tr class=\"item\">";

942
      if (KMyMoneySettings::showBalanceStatusOfOnlineAccounts()) {
943
944
945
946
947
948
949
950
        QString pathStatusHeader = QPixmapToDataUri(Icons::get(Icon::Download).pixmap(QSize(16,16)));
        m_html += QString("<td class=\"center\"><img src=\"%1\" border=\"0\"></td>").arg(pathStatusHeader);
      }

      m_html += "<td class=\"left\" width=\"35%\">";
      m_html += i18n("Account");
      m_html += "</td>";

951
      if (KMyMoneySettings::showCountOfUnmarkedTransactions())
Thomas Baumgart's avatar
Thomas Baumgart committed
952
        m_html += QString("<td class=\"center\">%1</td>").arg(i18nc("Header not marked", "!M"));
953

954
      if (KMyMoneySettings::showCountOfClearedTransactions())
Thomas Baumgart's avatar
Thomas Baumgart committed
955
        m_html += QString("<td class=\"center\">%1</td>").arg(i18nc("Header cleared", "C"));
956

957
      if (KMyMoneySettings::showCountOfNotReconciledTransactions())
Thomas Baumgart's avatar
Thomas Baumgart committed
958
        m_html += QString("<td class=\"center\">%1</td>").arg(i18nc("Header not reconciled", "!R"));
959

960
961
962
      if (KMyMoneySettings::showDateOfLastReconciliation())
        m_html += QString("<td>%1</td>").arg(i18n("Last Reconciled"));

963
964
965
966
967
      m_html += "<td width=\"25%\" class=\"right\">";
      m_html += i18n("Current Balance");
      m_html += "</td>";

      //only show limit info if user chose to do so
968
      if (KMyMoneySettings::showLimitInfo()) {
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
        m_html += "<td width=\"40%\" class=\"right\">";
        m_html += i18n("To Minimum Balance / Maximum Credit");
        m_html += "</td>";
      }
      m_html += "</tr>";

      m_total = 0;
      QList<MyMoneyAccount>::const_iterator it_m;
      for (it_m = accounts.constBegin(); it_m != accounts.constEnd(); ++it_m) {
        m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
        showAccountEntry(*it_m);
        m_html += "</tr>";
      }
      m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
      QString amount = m_total.formatMoney(file->baseCurrency().tradingSymbol(), prec);
984
      if (KMyMoneySettings::showBalanceStatusOfOnlineAccounts()) m_html += "<td></td>";
985
      m_html += QString("<td class=\"right\"><b>%1</b></td>").arg(i18n("Total"));
986
987
988
      if (KMyMoneySettings::showCountOfUnmarkedTransactions()) m_html += "<td></td>";
      if (KMyMoneySettings::showCountOfClearedTransactions()) m_html += "<td></td>";
      if (KMyMoneySettings::showCountOfNotReconciledTransactions()) m_html += "<td></td>";
989
      if (KMyMoneySettings::showDateOfLastReconciliation()) m_html += "<td></td>";
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
      m_html += QString("<td class=\"right\"><b>%1</b></td></tr>").arg(showColoredAmount(amount, m_total.isNegative()));
      m_html += "</table></div></div>";
    }
  }

  void showFavoriteReports()
  {
    QList<MyMoneyReport> reports = MyMoneyFile::instance()->reportList();

    if (!reports.isEmpty()) {
      bool firstTime = 1;
      int row = 0;
      QList<MyMoneyReport>::const_iterator it_report = reports.constBegin();
      while (it_report != reports.constEnd()) {
        if ((*it_report).isFavorite()) {
          if (firstTime) {
            m_html += QString("<div class=\"shadow\"><div class=\"displayblock\"><div class=\"summaryheader\">%1</div>\n<div class=\"gap\">&nbsp;</div>\n").arg(i18n("Favorite Reports"));
            m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
            m_html += "<tr class=\"item\"><td class=\"left\" width=\"40%\">";
            m_html += i18n("Report");
            m_html += "</td><td width=\"60%\" class=\"left\">";
            m_html += i18n("Comment");
            m_html += "</td></tr>";
            firstTime = false;
          }

          m_html += QString("<tr class=\"row-%1\"><td>%2%3%4</td><td align=\"left\">%5</td></tr>")
                       .arg(row++ & 0x01 ? "even" : "odd")
                       .arg(link(VIEW_REPORTS, QString("?id=%1").arg((*it_report).id())))
                       .arg((*it_report).name())
                       .arg(linkend())
                       .arg((*it_report).comment());
        }

        ++it_report;
      }
      if (!firstTime)
        m_html += "</table></div></div>";
    }
  }

  void showForecast()
  {
    MyMoneyFile* file = MyMoneyFile::instance();
    QList<MyMoneyAccount> accList;

    //if forecast has not been executed yet, do it.
    if (!m_forecast.isForecastDone())
      doForecast();

    accList = m_forecast.accountList();

    if (accList.count() > 0) {
      // sort the accounts by name
      qStableSort(accList.begin(), accList.end(), accountNameLess);
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
1045
      auto i = 0;
1046

Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
1047
      auto colspan = 1;
1048
      //get begin day
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
1049
      auto beginDay = QDate::currentDate().daysTo(m_forecast.beginForecastDate());
1050
1051
1052
1053
1054
      //if begin day is today skip to next cycle
      if (beginDay == 0)
        beginDay = m_forecast.accountsCycle();

      // Now output header
1055
      m_html += QString("<div class=\"shadow\"><div class=\"displayblock\"><div class=\"summaryheader\">%1</div>\n<div class=\"gap\">&nbsp;</div>\n").arg(i18ncp("Forecast days", "%1 Day Forecast", "%1 Day Forecast", m_forecast.forecastDays()));
1056
1057
1058
1059
      m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
      m_html += "<tr class=\"item\"><td class=\"left\" width=\"40%\">";
      m_html += i18n("Account");
      m_html += "</td>";
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
1060
      auto colWidth = 55 / (m_forecast.forecastDays() / m_forecast.accountsCycle());
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
      for (i = 0; (i*m_forecast.accountsCycle() + beginDay) <= m_forecast.forecastDays(); ++i) {
        m_html += QString("<td width=\"%1%\" class=\"right\">").arg(colWidth);

        m_html += i18ncp("Forecast days", "%1 day", "%1 days", i * m_forecast.accountsCycle() + beginDay);
        m_html += "</td>";
        colspan++;
      }
      m_html += "</tr>";

      // Now output entries
      i = 0;

      QList<MyMoneyAccount>::ConstIterator it_account;
      for (it_account = accList.constBegin(); it_account != accList.constEnd(); ++it_account) {
        //MyMoneyAccount acc = (*it_n);

        m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
        m_html += QString("<td width=\"40%\">") +
                     link(VIEW_LEDGER, QString("?id=%1").arg((*it_account).id())) + (*it_account).name() + linkend() + "</td>";

1081
1082
        qint64 dropZero = -1; //account dropped below zero
        qint64 dropMinimum = -1; //account dropped below minimum balance
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
        QString minimumBalance = (*it_account).value("minimumBalance");
        MyMoneyMoney minBalance = MyMoneyMoney(minimumBalance);
        MyMoneySecurity currency;
        MyMoneyMoney forecastBalance;

        //change account to deep currency if account is an investment
        if ((*it_account).isInvest()) {
          MyMoneySecurity underSecurity = file->security((*it_account).currencyId());
          currency = file->security(underSecurity.tradingCurrency());
        } else {
          currency = file->security((*it_account).currencyId());
        }

Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
1096
        for (auto f = beginDay; f <= m_forecast.forecastDays(); f += m_forecast.accountsCycle()) {
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
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
          forecastBalance = m_forecast.forecastBalance(*it_account, QDate::currentDate().addDays(f));
          QString amount;
          amount = MyMoneyUtils::formatMoney(forecastBalance, *it_account, currency);
          amount.replace(QChar(' '), "&nbsp;");
          m_html += QString("<td width=\"%1%\" align=\"right\">").arg(colWidth);
          m_html += QString("%1</td>").arg(showColoredAmount(amount, forecastBalance.isNegative()));
        }

        m_html += "</tr>";

        //Check if the account is going to be below zero or below the minimal balance in the forecast period

        //Check if the account is going to be below minimal balance
        dropMinimum = m_forecast.daysToMinimumBalance(*it_account);

        //Check if the account is going to be below zero in the future
        dropZero = m_forecast.daysToZeroBalance(*it_account);


        // spit out possible warnings
        QString msg;

        // if a minimum balance has been specified, an appropriate warning will
        // only be shown, if the drop below 0 is on a different day or not present

        if (dropMinimum != -1
            && !minBalance.isZero()
            && (dropMinimum < dropZero
                || dropZero == -1)) {
          switch (dropMinimum) {
            case 0:
              msg = i18n("The balance of %1 is below the minimum balance %2 today.", (*it_account).name(), MyMoneyUtils::formatMoney(minBalance, *it_account, currency));
              msg = showColoredAmount(msg, true);
              break;
            default:
              msg = i18np("The balance of %2 will drop below the minimum balance %3 in %1 day.",
                          "The balance of %2 will drop below the minimum balance %3 in %1 days.",
                          dropMinimum - 1, (*it_account).name(), MyMoneyUtils::formatMoney(minBalance, *it_account, currency));
              msg = showColoredAmount(msg, true);
              break;
          }

          if (!msg.isEmpty()) {
            m_html += QString("<tr class=\"warning\" style=\"font-weight: normal;\" ><td colspan=%2 align=\"center\" >%1</td></tr>").arg(msg).arg(colspan);
          }
        }
        // a drop below zero is always shown
        msg.clear();
        switch (dropZero) {
          case -1:
            break;
          case 0:
            if ((*it_account).accountGroup() == Account::Type::Asset) {
              msg = i18n("The balance of %1 is below %2 today.", (*it_account).name(), MyMoneyUtils::formatMoney(MyMoneyMoney(), *it_account, currency));
              msg = showColoredAmount(msg, true);
              break;
            }
            if ((*it_account).accountGroup() == Account::Type::Liability) {
              msg = i18n("The balance of %1 is above %2 today.", (*it_account).name(), MyMoneyUtils::formatMoney(MyMoneyMoney(), *it_account, currency));
              break;
            }
            break;
          default:
            if ((*it_account).accountGroup() == Account::Type::Asset) {
              msg = i18np("The balance of %2 will drop below %3 in %1 day.",
                          "The balance of %2 will drop below %3 in %1 days.",
                          dropZero, (*it_account).name(), MyMoneyUtils::formatMoney(MyMoneyMoney(), *it_account, currency));
              msg = showColoredAmount(msg, true);
              break;
            }
            if ((*it_account).accountGroup() == Account::Type::Liability) {
              msg = i18np("The balance of %2 will raise above %3 in %1 day.",
                          "The balance of %2 will raise above %3 in %1 days.",
                          dropZero, (*it_account).name(), MyMoneyUtils::formatMoney(MyMoneyMoney(), *it_account, currency));
              break;
            }
        }
        if (!msg.isEmpty()) {
          m_html += QString("<tr class=\"warning\"><td colspan=%2 align=\"center\" ><b>%1</b></td></tr>").arg(msg).arg(colspan);
        }
      }
      m_html += "</table></div></div>";

    }
  }

  QString link(const QString& view, const QString& query, const QString& _title = QString()) const
  {
    QString titlePart;
    QString title(_title);
    if (!title.isEmpty())
      titlePart = QString(" title=\"%1\"").arg(title.replace(QLatin1Char(' '), "&nbsp;"));

    return QString("<a href=\"/%1%2\"%3>").arg(view, query, titlePart);
  }

  QString linkend() const
  {
    return QStringLiteral("</a>");
  }

  void showAssetsLiabilities()
  {
    QList<MyMoneyAccount> accounts;
    QList<MyMoneyAccount>::ConstIterator it;
    QList<MyMoneyAccount> assets;
    QList<MyMoneyAccount> liabilities;
    MyMoneyMoney netAssets;
    MyMoneyMoney netLiabilities;

    MyMoneyFile* file = MyMoneyFile::instance();
    int prec = MyMoneyMoney::denomToPrec(file->baseCurrency().smallestAccountFraction());
    int i = 0;

    // get list of all accounts
    file->accountList(accounts);

1214
1215
    const auto showClosedAccounts = !KMyMoneySettings::hideClosedAccounts() || KMyMoneySettings::showAllAccounts();

1216
    for (it = accounts.constBegin(); it != accounts.constEnd();) {
1217
      if (!(*it).isClosed() || showClosedAccounts) {
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
        switch ((*it).accountType()) {
            // group all assets into one list but make sure that investment accounts always show up
          case Account::Type::Investment:
            assets << *it;
            break;

          case Account::Type::Checkings:
          case Account::Type::Savings:
          case Account::Type::Cash:
          case Account::Type::Asset:
          case Account::Type::AssetLoan:
            // list account if it's the last in the hierarchy or has transactions in it
            if ((*it).accountList().isEmpty() || (file->transactionCount((*it).id()) > 0)) {
              assets << *it;
            }
            break;

            // group the liabilities into the other
          case Account::Type::CreditCard:
          case Account::Type::Liability:
          case Account::Type::Loan:
            // list account if it's the last in the hierarchy or has transactions in it
            if ((*it).accountList().isEmpty() || (file->transactionCount((*it).id()) > 0)) {
1241
	      // Add it if we are not hiding zero balance liabilities, or the balance is not zero
Thomas Baumgart's avatar
Thomas Baumgart committed
1242
              const auto value =
1243
1244
1245
1246
		      MyMoneyFile::instance()->balance((*it).id(), QDate::currentDate());
	      if (!(KMyMoneySettings::hideZeroBalanceLiabilities() && value.isZero())) {
                liabilities << *it;
              }
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
            }
            break;

          default:
            break;
        }
      }
      ++it;
    }

    //only do it if we have assets or liabilities account
    if (assets.count() > 0 || liabilities.count() > 0) {
      // sort the accounts by name
      qStableSort(assets.begin(), assets.end(), accountNameLess);
      qStableSort(liabilities.begin(), liabilities.end(), accountNameLess);
      QString statusHeader;
1263
      if (KMyMoneySettings::showBalanceStatusOfOnlineAccounts()) {
1264
        QString pathStatusHeader;
1265
        pathStatusHeader = QPixmapToDataUri(Icons::get(Icon::OnlineJobOutbox).pixmap(QSize(16, 16)));
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
        statusHeader = QString("<img src=\"%1\" border=\"0\">").arg(pathStatusHeader);
      }

      //print header
      m_html += "<div class=\"shadow\"><div class=\"displayblock\"><div class=\"summaryheader\">" + i18n("Assets and Liabilities Summary") + "</div>\n<div class=\"gap\">&nbsp;</div>\n";
      m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";

      //column titles

      m_html += "<tr class=\"item\">";

1277
      if (KMyMoneySettings::showBalanceStatusOfOnlineAccounts()) {
1278
1279
1280
1281
1282
1283
1284
1285
1286
        m_html += "<td class=\"setcolor\">";
        m_html += statusHeader;
        m_html += "</td>";
      }

      m_html += "<td class=\"left\" width=\"30%\">";
      m_html += i18n("Asset Accounts");
      m_html += "</td>";

1287
      if (KMyMoneySettings::showCountOfUnmarkedTransactions())
1288
1289
        m_html += "<td class=\"setcolor\">!M</td>";

1290
      if (KMyMoneySettings::showCountOfClearedTransactions())
1291
1292
        m_html += "<td class=\"setcolor\">C</td>";

1293
      if (KMyMoneySettings::showCountOfNotReconciledTransactions())
1294
1295
        m_html += "<td class=\"setcolor\">!R</td>";

1296
1297
1298
      if (KMyMoneySettings::showDateOfLastReconciliation())
        m_html += "<td class=\"setcolor\">" + i18n("Last Reconciled") + "</td>";

1299
1300
1301
1302
1303
1304
1305
      m_html += "<td width=\"15%\" class=\"right\">";
      m_html += i18n("Current Balance");
      m_html += "</td>";

      //intermediate row to separate both columns
      m_html += "<td width=\"10%\" class=\"setcolor\"></td>";

1306
      if (KMyMoneySettings::showBalanceStatusOfOnlineAccounts()) {
1307
1308
1309
1310
1311
1312
1313
1314
1315
        m_html += "<td class=\"setcolor\">";
        m_html += statusHeader;
        m_html += "</td>";
      }

      m_html += "<td class=\"left\" width=\"30%\">";
      m_html += i18n("Liability Accounts");
      m_html += "</td>";

1316
      if (KMyMoneySettings::showCountOfUnmarkedTransactions())
1317
1318
        m_html += "<td class=\"setcolor\">!M</td>";

1319
      if (KMyMoneySettings::showCountOfClearedTransactions())
1320
1321
        m_html += "<td class=\"setcolor\">C</td>";

1322
      if (KMyMoneySettings::showCountOfNotReconciledTransactions())
1323
1324
        m_html += "<td class=\"setcolor\">!R</td>";

1325
1326
1327
      if (KMyMoneySettings::showDateOfLastReconciliation())
        m_html += "<td class=\"setcolor\">" + i18n("Last Reconciled") + "</td>";

1328
1329
1330
1331
1332
      m_html += "<td width=\"15%\" class=\"right\">";
      m_html += i18n("Current Balance");
      m_html += "</td></tr>";

      QString placeHolder_Status, placeHolder_Counts;
1333
1334
1335
1336
      if (KMyMoneySettings::showBalanceStatusOfOnlineAccounts()) placeHolder_Status = "<td></td>";
      if (KMyMoneySettings::showCountOfUnmarkedTransactions()) placeHolder_Counts = "<td></td>";
      if (KMyMoneySettings::showCountOfClearedTransactions()) placeHolder_Counts += "<td></td>";
      if (KMyMoneySettings::showCountOfNotReconciledTransactions()) placeHolder_Counts += "<td></td>";
1337
      if (KMyMoneySettings::showDateOfLastReconciliation()) placeHolder_Counts += "<td></td>";
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355

      //get asset and liability accounts
      QList<MyMoneyAccount>::const_iterator asset_it = assets.constBegin();
      QList<MyMoneyAccount>::const_iterator liabilities_it = liabilities.constBegin();
      for (; asset_it != assets.constEnd() || liabilities_it != liabilities.constEnd();) {
        m_html += QString("<tr class=\"row-%1\">").arg(i++ & 0x01 ? "even" : "odd");
        //write an asset account if we still have any
        if (asset_it != assets.constEnd()) {
          MyMoneyMoney value;
          //investment accounts consolidate the balance of its subaccounts
          if ((*asset_it).accountType() == Account::Type::Investment) {
            value = investmentBalance(*asset_it);
          } else {
            value = MyMoneyFile::instance()->balance((*asset_it).id(), QDate::currentDate());
          }

          //calculate balance for foreign currency accounts
          if ((*asset_it).currencyId() != file->baseCurrency().id()) {
1356
1357
1358
            const auto curPrice = file->price((*asset_it).tradingCurrencyId(), file->baseCurrency().id(), QDate::currentDate());
            const auto curRate = curPrice.rate(file->baseCurrency().id());
            auto baseValue = value * curRate;
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
            baseValue = baseValue.convert(10000);
            netAssets += baseValue;
          } else {
            netAssets += value;
          }
          //show the account without minimum balance
          showAccountEntry(*asset_it, value, MyMoneyMoney(), false);
          ++asset_it;
        } else {
          //write a white space if we don't
          m_html += QString("%1<td></td>%2<td></td>").arg(placeHolder_Status).arg(placeHolder_Counts);
        }

        //leave the intermediate column empty
        m_html += "<td class=\"setcolor\"></td>";

        //write a liability account
        if (liabilities_it != liabilities.constEnd()) {
          MyMoneyMoney value;
          value = MyMoneyFile::instance()->balance((*liabilities_it).id(), QDate::currentDate());
          //calculate balance if foreign currency
          if ((*liabilities_it).currencyId() != file->baseCurrency().id()) {
1381
1382
1383
            const auto curPrice = file->price((*liabilities_it).tradingCurrencyId(), file->baseCurrency().id(), QDate::currentDate());
            const auto curRate = curPrice.rate(file->baseCurrency().id());
            auto baseValue = value * curRate;
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
            baseValue = baseValue.convert(10000);
            netLiabilities += baseValue;
          } else {
            netLiabilities += value;
          }
          //show the account without minimum balance
          showAccountEntry(*liabilities_it, value, MyMoneyMoney(), false);
          ++liabilities_it;
        } else {
          //leave the space empty if we run out of liabilities
          m_html += QString("%1<td></td>%2<td></td>").arg(placeHolder_Status).arg(placeHolder_Counts);
        }
        m_html += "</tr>";
      }

      //calculate net worth
      MyMoneyMoney netWorth = netAssets + netLiabilities;

      //format assets, liabilities and net worth
      QString amountAssets = netAssets.formatMoney(file->baseCurrency().tradingSymbol(), prec);
      QString amountLiabilities = netLiabilities.formatMoney(file->baseCurrency().tradingSymbol(), prec);
      QString amountNetWorth = netWorth.formatMoney(file->baseCurrency().tradingSymbol(), prec);
      amountAssets.replace(QChar(' '), "&nbsp;");
      amountLiabilities.replace(QChar(' '), "&nbsp;");
      amountNetWorth.replace(QChar(' '), "&nbsp;");

      m_html += QString("<tr class=\"row-%1\" style=\"font-weight:bold;\">").arg(i++ & 0x01 ? "even" : "odd");

      //print total for assets
      m_html += QString("%1<td class=\"left\">%2</td>%3<td align=\"right\">%4</td>").arg(placeHolder_Status).arg(i18n("Total Assets")).arg(placeHolder_Counts).arg(showColoredAmount(amountAssets, netAssets.isNegative()));

      //leave the intermediate column empty
      m_html += "<td class=\"setcolor\"></td>";

      //print total liabilities
      m_html += QString("%1<td class=\"left\">%2</td>%3<td align=\"right\">%4</td>").arg(placeHolder_Status).arg(i18n("Total Liabilities")).arg(placeHolder_Counts).arg(showColoredAmount(amountLiabilities, netLiabilities.isNegative()));
      m_html += "</tr>";

      //print net worth
      m_html += QString("<tr class=\"row-%1\" style=\"font-weight:bold;\">").arg(i++ & 0x01 ? "even" : "odd");

      m_html += QString("%1<td></td><td></td>%2<td class=\"setcolor\"></td>").arg(placeHolder_Status).arg(placeHolder_Counts);
      m_html += QString("%1<td class=\"left\">%2</td>%3<td align=\"right\">%4</td>").arg(placeHolder_Status).arg(i18n("Net Worth")).arg(placeHolder_Counts).arg(showColoredAmount(amountNetWorth, netWorth.isNegative()));

      m_html += "</tr>";
      m_html += "</table>";
      m_html += "</div></div>";
    }
  }

  void showBudget()
  {
1436
    QVariant variantReport;
1437

1438
    if (const auto reportsPlugin = pPlugins.data.value(QStringLiteral("reportsview"), nullptr)) {
1439
1440
1441
1442
1443
      variantReport = reportsPlugin->requestData(QString(), eWidgetPlugin::WidgetType::Budget);
    }

    if (!variantReport.isNull()) {
      m_html.append(variantReport.toString());
1444
    } else {
1445
1446
      m_html += "<div class=\"shadow\"><div class=\"displayblock\"><div class=\"summaryheader\">" + i18n("Budget") + "</div>\n<div class=\"gap\">&nbsp;</div>\n";
      m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
1447
1448
1449
      m_html += QString("<tr>");
      m_html += QString("<td><center>%1</center></td>").arg(i18n("Enable reports plugin to see this chart."));
      m_html += QString("</tr>");
1450
      m_html += QString("</table></div></div>");
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
    }
  }

  void showCashFlowSummary()
  {
    MyMoneyTransactionFilter filter;
    MyMoneyMoney incomeValue;
    MyMoneyMoney expenseValue;

    MyMoneyFile* file = MyMoneyFile::instance();
    int prec = MyMoneyMoney::denomToPrec(file->baseCurrency().smallestAccountFraction());

    //set start and end of month dates
    QDate startOfMonth = QDate(QDate::currentDate().year(), QDate::currentDate().month(), 1);
    QDate endOfMonth = QDate(QDate::currentDate().year(), QDate::currentDate().month(), QDate::currentDate().daysInMonth());

    //Add total income and expenses for this month
    //get transactions for current month
    filter.setDateFilter(startOfMonth, endOfMonth);
    filter.setReportAllSplits(false);

    QList<MyMoneyTransaction> transactions = file->transactionList(filter);
    //if no transaction then skip and print total in zero
    if (transactions.size() > 0) {

      //get all transactions for this month
      foreach (const auto transaction, transactions) {
        //get the splits for each transaction
        foreach (const auto split, transaction.splits()) {
          if (!split.shares().isZero()) {
1481
            auto repSplitAcc = file->account(split.accountId());
1482
1483
1484
1485
1486
1487
1488

            //only add if it is an income or expense
            if (repSplitAcc.isIncomeExpense()) {
              MyMoneyMoney value;

              //convert to base currency if necessary
              if (repSplitAcc.currencyId() != file->baseCurrency().id()) {
1489
1490
1491
                const auto curPrice = file->price(repSplitAcc.tradingCurrencyId(), file->baseCurrency().id(), QDate::currentDate());
                const auto curRate = curPrice.rate(file->baseCurrency().id());
                value = (split.shares() * MyMoneyMoney::MINUS_ONE) * curRate;
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
                value = value.convert(10000);
              } else {
                value = (split.shares() * MyMoneyMoney::MINUS_ONE);
              }

              //store depending on account type
              if (repSplitAcc.accountType() == Account::Type::Income) {
                incomeValue += value;
              } else {
                expenseValue += value;
              }
            }
          }
        }
      }
    }

    //format income and expenses
    QString amountIncome = incomeValue.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    QString amountExpense = expenseValue.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    amountIncome.replace(QChar(' '), "&nbsp;");
    amountExpense.replace(QChar(' '), "&nbsp;");

    //calculate schedules

    //Add all schedules for this month
    MyMoneyMoney scheduledIncome;
    MyMoneyMoney scheduledExpense;
    MyMoneyMoney scheduledLiquidTransfer;
    MyMoneyMoney scheduledOtherTransfer;

    //get overdues and schedules until the end of this month
    QList<MyMoneySchedule> schedule = file->scheduleList(QString(), Schedule::Type::Any,
                                      Schedule::Occurrence::Any,
                                      Schedule::PaymentType::Any,
                                      QDate(),
                                      endOfMonth, false);

    //Remove the finished schedules
    QList<MyMoneySchedule>::Iterator finished_it;
    for (finished_it = schedule.begin(); finished_it != schedule.end();) {
      if ((*finished_it).isFinished()) {
        finished_it = schedule.erase(finished_it);
        continue;
      }
      ++finished_it;
    }

    //add income and expenses
    QList<MyMoneySchedule>::Iterator sched_it;
    for (sched_it = schedule.begin(); sched_it != schedule.end();) {
      QDate nextDate = (*sched_it).nextDueDate();
      int cnt = 0;

      while (nextDate.isValid() && nextDate <= endOfMonth) {
        ++cnt;
        nextDate = (*sched_it).nextPayment(nextDate);
        // for single occurrence nextDate will not change, so we
        // better get out of here.
        if ((*sched_it).occurrence() == Schedule::Occurrence::Once)
          break;
      }

      MyMoneyAccount acc = (*sched_it).account();
      if (!acc.id().isEmpty()) {
        MyMoneyTransaction transaction = (*sched_it).transaction();
        // only show the entry, if it is still active

        MyMoneySplit sp = transaction.splitByAccount(acc.id(), true);

        // take care of the autoCalc stuff
        if ((*sched_it).type() == Schedule::Type::LoanPayment) {
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
1564
          nextDate = (*sched_it).nextPayment((*sched_it).lastPayment());
1565
1566
1567
1568
1569

          //make sure we have all 'starting balances' so that the autocalc works
          QMap<QString, MyMoneyMoney> balanceMap;

          foreach (const auto split, transaction.splits()) {
Łukasz Wojniłowicz's avatar
Łukasz Wojniłowicz committed
1570
            acc = file->account(split.accountId());
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
            // collect all overdues on the first day
            QDate schedDate = nextDate;
            if (QDate::currentDate() >= nextDate)
              schedDate = QDate::currentDate().addDays(1);

            balanceMap[acc.id()] += file->balance(acc.id(), QDate::currentDate());
          }
          KMyMoneyUtils::calculateAutoLoan(*sched_it, transaction, balanceMap);
        }

        //go through the splits and assign to liquid or other transfers
        const QList<MyMoneySplit> splits = transaction.splits();
        QList<MyMoneySplit>::const_iterator split_it;
        for (split_it = splits.constBegin(); split_it != splits.constEnd(); ++split_it) {
          if ((*split_it).accountId() != acc.id()) {
1586
            auto repSplitAcc = file->account((*split_it).accountId());
1587
1588
1589
1590
1591
1592

            //get the shares and multiply by the quantity of occurrences in the period
            MyMoneyMoney value = (*split_it).shares() * cnt;

            //convert to foreign currency if needed
            if (repSplitAcc.currencyId() != file->baseCurrency().id()) {
1593
1594
1595
              const auto curPrice = file->price(repSplitAcc.tradingCurrencyId(), file->baseCurrency().id(), QDate::currentDate());
              const auto curRate = curPrice.rate(file->baseCurrency().id());
              value = value * curRate;
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
              value = value.convert(10000);
            }

            if ((repSplitAcc.isLiquidLiability()
                 || repSplitAcc.isLiquidAsset())
                && acc.accountGroup() != repSplitAcc.accountGroup()) {
              scheduledLiquidTransfer += value;
            } else if (repSplitAcc.isAssetLiability()
                       && !repSplitAcc.isLiquidLiability()
                       && !repSplitAcc.isLiquidAsset()) {
              scheduledOtherTransfer += value;
            } else if (repSplitAcc.isIncomeExpense()) {
              //income and expenses are stored as negative values
              if (repSplitAcc.accountType() == Account::Type::Income)
                scheduledIncome -= value;
              if (repSplitAcc.accountType() == Account::Type::Expense)
                scheduledExpense -= value;
            }
          }
        }
      }
      ++sched_it;
    }

    //format the currency strings
    QString amountScheduledIncome = scheduledIncome.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    QString amountScheduledExpense = scheduledExpense.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    QString amountScheduledLiquidTransfer = scheduledLiquidTransfer.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    QString amountScheduledOtherTransfer = scheduledOtherTransfer.formatMoney(file->baseCurrency().tradingSymbol(), prec);

    amountScheduledIncome.replace(QChar(' '), "&nbsp;");
    amountScheduledExpense.replace(QChar(' '), "&nbsp;");
    amountScheduledLiquidTransfer.replace(QChar(' '), "&nbsp;");
    amountScheduledOtherTransfer.replace(QChar(' '), "&nbsp;");

    //get liquid assets and liabilities
    QList<MyMoneyAccount> accounts;
    QList<MyMoneyAccount>::const_iterator account_it;
    MyMoneyMoney liquidAssets;
    MyMoneyMoney liquidLiabilities;

    // get list of all accounts
    file->accountList(accounts);
    for (account_it = accounts.constBegin(); account_it != accounts.constEnd();) {
      if (!(*account_it).isClosed()) {
        switch ((*account_it).accountType()) {
            //group all assets into one list
          case Account::Type::Checkings:
          case Account::Type::Savings:
          case Account::Type::Cash: {
              MyMoneyMoney value = MyMoneyFile::instance()->balance((*account_it).id(), QDate::currentDate());
              //calculate balance for foreign currency accounts
              if ((*account_it).currencyId() != file->baseCurrency().id()) {
1649
1650
1651
                const auto curPrice = file->price((*account_it).tradingCurrencyId(), file->baseCurrency().id(), QDate::currentDate());
                const auto curRate = curPrice.rate(file->baseCurrency().id());
                auto baseValue = value * curRate;
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
                liquidAssets += baseValue;
                liquidAssets = liquidAssets.convert(10000);
              } else {
                liquidAssets += value;
              }
              break;
            }
            //group the liabilities into the other
          case Account::Type::CreditCard: {
              MyMoneyMoney value;
              value = MyMoneyFile::instance()->balance((*account_it).id(), QDate::currentDate());
              //calculate balance if foreign currency
              if ((*account_it).currencyId() != file->baseCurrency().id()) {
1665
1666
1667
                const auto curPrice = file->price((*account_it).tradingCurrencyId(), file->baseCurrency().id(), QDate::currentDate());
                const auto curRate = curPrice.rate(file->baseCurrency().id());
                auto baseValue = value * curRate;
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
                liquidLiabilities += baseValue;
                liquidLiabilities = liquidLiabilities.convert(10000);
              } else {
                liquidLiabilities += value;
              }
              break;
            }
          default:
            break;
        }
      }
      ++account_it;
    }
    //calculate net worth
    MyMoneyMoney liquidWorth = liquidAssets + liquidLiabilities;

    //format assets, liabilities and net worth
    QString amountLiquidAssets = liquidAssets.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    QString amountLiquidLiabilities = liquidLiabilities.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    QString amountLiquidWorth = liquidWorth.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    amountLiquidAssets.replace(QChar(' '), "&nbsp;");
    amountLiquidLiabilities.replace(QChar(' '), "&nbsp;");
    amountLiquidWorth.replace(QChar(' '), "&nbsp;");

    //show the summary
    m_html += "<div class=\"shadow\"><div class=\"displayblock\"><div class=\"summaryheader\">" + i18n("Cash Flow Summary") + "</div>\n<div class=\"gap\">&nbsp;</div>\n";

    //print header
    m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
    //income and expense title
    m_html += "<tr class=\"itemtitle\">";
    m_html += "<td class=\"left\" colspan=\"4\">";
    m_html += i18n("Income and Expenses of Current Month");
    m_html += "</td></tr>";
    //column titles
    m_html += "<tr class=\"item\">";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Income");
    m_html += "</td>";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Scheduled Income");
    m_html += "</td>";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Expenses");
    m_html += "</td>";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Scheduled Expenses");
    m_html += "</td>";
    m_html += "</tr>";

    //add row with banding
    m_html += QString("<tr class=\"row-even\" style=\"font-weight:bold;\">");

    //print current income
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountIncome, incomeValue.isNegative()));

    //print the scheduled income
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountScheduledIncome, scheduledIncome.isNegative()));

    //print current expenses
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountExpense,  expenseValue.isNegative()));

    //print the scheduled expenses
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountScheduledExpense,  scheduledExpense.isNegative()));
    m_html += "</tr>";

    m_html += "</table>";

    //print header of assets and liabilities
    m_html += "<div class=\"gap\">&nbsp;</div>\n";
    m_html += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"summarytable\" >";
    //assets and liabilities title
    m_html += "<tr class=\"itemtitle\">";
    m_html += "<td class=\"left\" colspan=\"4\">";
    m_html += i18n("Liquid Assets and Liabilities");
    m_html += "</td></tr>";
    //column titles
    m_html += "<tr class=\"item\">";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Liquid Assets");
    m_html += "</td>";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Transfers to Liquid Liabilities");
    m_html += "</td>";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Liquid Liabilities");
    m_html += "</td>";
    m_html += "<td width=\"25%\" class=\"center\">";
    m_html += i18n("Other Transfers");
    m_html += "</td>";
    m_html += "</tr>";

    //add row with banding
    m_html += QString("<tr class=\"row-even\" style=\"font-weight:bold;\">");

    //print current liquid assets
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountLiquidAssets, liquidAssets.isNegative()));

    //print the scheduled transfers
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountScheduledLiquidTransfer, scheduledLiquidTransfer.isNegative()));

    //print current liabilities
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountLiquidLiabilities,  liquidLiabilities.isNegative()));

    //print the scheduled transfers
    m_html += QString("<td align=\"right\">%2</td>").arg(showColoredAmount(amountScheduledOtherTransfer, scheduledOtherTransfer.isNegative()));


    m_html += "</tr>";

    m_html += "</table>";

    //final conclusion
    MyMoneyMoney profitValue = incomeValue + expenseValue + scheduledIncome + scheduledExpense;
    MyMoneyMoney expectedAsset = liquidAssets + scheduledIncome + scheduledExpense + scheduledLiquidTransfer + scheduledOtherTransfer;
    MyMoneyMoney expectedLiabilities = liquidLiabilities + scheduledLiquidTransfer;

    QString amountExpectedAsset = expectedAsset.formatMoney(file->baseCurrency().tradingSymbol(), prec);
    QString amountExpectedLiabilities = expectedLiabilities.formatMoney(