summaryrefslogtreecommitdiffstats
path: root/kmymoney2/views/kinstitutionsview.cpp
blob: b976fe59c3cd7446c28da94fcc8cdc022cf3836c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/***************************************************************************
                          kinstitutionsview.cpp
                             -------------------
    copyright            : (C) 2005 by Thomas Baumgart
    email                : ipwizard@users.sourceforge.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

// ----------------------------------------------------------------------------
// QT Includes

#include <tqheader.h>
#include <tqlabel.h>
#include <tqtabwidget.h>

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

#include <kdebug.h>
#include <tdelocale.h>
#include <kstandarddirs.h>

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

#include <kmymoney/mymoneyfile.h>
#include "kinstitutionsview.h"
#include "../kmymoneyglobalsettings.h"
#include "../kmymoney2.h"

KInstitutionsView::KInstitutionsView(TQWidget *parent, const char *name) :
  KInstitutionsViewDecl(parent,name),
  m_needReload(false)
{
  m_accountTree->header()->setLabel(0, i18n("Institution/Account"));

  connect(m_accountTree, TQ_SIGNAL(selectObject(const MyMoneyObject&)), this, TQ_SIGNAL(selectObject(const MyMoneyObject&)));
  connect(m_accountTree, TQ_SIGNAL(openContextMenu(const MyMoneyObject&)), this, TQ_SIGNAL(openContextMenu(const MyMoneyObject&)));
  connect(m_accountTree, TQ_SIGNAL(valueChanged(void)), this, TQ_SLOT(slotUpdateNetWorth(void)));
  connect(m_accountTree, TQ_SIGNAL(openObject(const MyMoneyObject&)), this, TQ_SIGNAL(openObject(const MyMoneyObject&)));
  connect(m_accountTree, TQ_SIGNAL(reparent(const MyMoneyAccount&, const MyMoneyInstitution&)), this, TQ_SIGNAL(reparent(const MyMoneyAccount&, const MyMoneyInstitution&)));

  connect(MyMoneyFile::instance(), TQ_SIGNAL(dataChanged()), this, TQ_SLOT(slotLoadAccounts()));
}

KInstitutionsView::~KInstitutionsView()
{
}

void KInstitutionsView::show(void)
{
  if(m_needReload) {
    loadAccounts();
    m_needReload = false;
  }

  // don't forget base class implementation
  KInstitutionsViewDecl::show();

  // if we have a selected account, let the application know about it
  KMyMoneyAccountTreeBaseItem *item = m_accountTree->selectedItem();
  if(item) {
    emit selectObject(item->itemObject());
  }
}

void KInstitutionsView::polish(void)
{
  KInstitutionsViewDecl::polish();
  m_accountTree->setResizeMode(TQListView::LastColumn);
  m_accountTree->restoreLayout("Institution View Settings");
}

void KInstitutionsView::slotLoadAccounts(void)
{
  if(isVisible()) {
    loadAccounts();
  } else {
    m_needReload = true;
  }
}

void KInstitutionsView::loadAccounts(void)
{
  TQMap<TQString, bool> isOpen;

  ::timetrace("start load institutions view");
  // remember the id of the current selected item
  KMyMoneyAccountTreeBaseItem *item = m_accountTree->selectedItem();
  TQString selectedItemId = (item) ? item->id() : TQString();

  // keep a map of all 'expanded' accounts
  TQListViewItemIterator it_lvi(m_accountTree);
  while(it_lvi.current()) {
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
    if(item && item->isOpen()) {
      isOpen[item->id()] = true;
    }
    ++it_lvi;
  }

  // remember the upper left corner of the viewport
  TQPoint startPoint = m_accountTree->viewportToContents(TQPoint(0, 0));

  // turn off updates to avoid flickering during reload
  m_accountTree->setUpdatesEnabled(false);

  // clear the current contents and recreate it
  m_accountTree->clear();
  m_accountMap.clear();
  m_securityMap.clear();
  m_transactionCountMap.clear();

  MyMoneyFile* file = MyMoneyFile::instance();

  TQValueList<MyMoneyAccount> alist;
  file->accountList(alist);
  TQValueList<MyMoneyAccount>::const_iterator it_a;
  for(it_a = alist.begin(); it_a != alist.end(); ++it_a) {
    m_accountMap[(*it_a).id()] = *it_a;
  }

  // we need to make sure we show stock accounts
  // under the right institution (the one of the parent account)
  TQMap<TQString, MyMoneyAccount>::iterator it_am;
  for(it_am = m_accountMap.begin(); it_am != m_accountMap.end(); ++it_am) {
    if((*it_am).isInvest()) {
      (*it_am).setInstitutionId(m_accountMap[(*it_am).parentAccountId()].institutionId());
    }
  }

  TQValueList<MyMoneySecurity> slist = file->currencyList();
  slist += file->securityList();
  TQValueList<MyMoneySecurity>::const_iterator it_s;
  for(it_s = slist.begin(); it_s != slist.end(); ++it_s) {
    m_securityMap[(*it_s).id()] = *it_s;
  }

  m_transactionCountMap = file->transactionCountMap();

  m_accountTree->setBaseCurrency(file->baseCurrency());

  // create the items
  try {
    const MyMoneySecurity& security = file->baseCurrency();
    m_accountTree->setBaseCurrency(security);

    MyMoneyInstitution none;
    none.setName(i18n("Accounts with no institution assigned"));
    KMyMoneyAccountTreeItem* noInstitutionItem = new KMyMoneyAccountTreeItem(m_accountTree, none);
    noInstitutionItem->setPixmap(0,none.pixmap());
    loadSubAccounts(noInstitutionItem, TQString());

    // hide it, if unused
    noInstitutionItem->setVisible(noInstitutionItem->childCount() != 0);
    
    bool showClosedAccounts = kmymoney2->toggleAction("view_show_all_accounts")->isChecked()
      || !KMyMoneyGlobalSettings::hideClosedAccounts();

    TQValueList<MyMoneyInstitution> list = file->institutionList();
    TQValueList<MyMoneyInstitution>::const_iterator it_i;
    for(it_i = list.begin(); it_i != list.end(); ++it_i) {
      KMyMoneyAccountTreeItem* item = new KMyMoneyAccountTreeItem(m_accountTree, *it_i);
      item->setPixmap(0, none.pixmap());
      loadSubAccounts(item, (*it_i).id());
      if(!showClosedAccounts)
        item->setVisible(item->childCount() != 0);
    }

  } catch(MyMoneyException *e) {
    kdDebug(2) << "Problem in institutions view: " << e->what();
    delete e;
  }

  // scan through the list of accounts and re-expand those that were
  // expanded and re-select the one that was probably selected before
  it_lvi = TQListViewItemIterator(m_accountTree);
  while(it_lvi.current()) {
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
    if(item) {
      if(item->id() == selectedItemId)
        m_accountTree->setSelected(item, true);
      if(isOpen.find(item->id()) != isOpen.end())
        item->setOpen(true);
    }
    ++it_lvi;
  }

  // reposition viewport
  m_accountTree->setContentsPos(startPoint.x(), startPoint.y());

  // turn updates back on
  m_accountTree->setUpdatesEnabled(true);
  m_accountTree->repaintContents();

  ::timetrace("done load institutions view");
}

void KInstitutionsView::loadSubAccounts(KMyMoneyAccountTreeItem* parent)
{
  bool showClosedAccounts = kmymoney2->toggleAction("view_show_all_accounts")->isChecked()
      || !KMyMoneyGlobalSettings::hideClosedAccounts();
  const MyMoneyAccount& account = dynamic_cast<const MyMoneyAccount&>(parent->itemObject());
  TQValueList<TQString>::const_iterator it_a;
  MyMoneyFile* file = MyMoneyFile::instance();
  for(it_a = account.accountList().begin(); it_a != account.accountList().end(); ++it_a) {
    MyMoneyAccount acc = m_accountMap[(*it_a)];
    if(!acc.isInvest())
      continue;
    if(acc.isClosed() && !showClosedAccounts)
      continue;
    const MyMoneySecurity& security = m_securityMap[acc.currencyId()];
    TQValueList<MyMoneyPrice> prices;
    prices += file->price(acc.currencyId(), security.tradingCurrency());
    if(security.tradingCurrency() != file->baseCurrency().id()) {
      MyMoneySecurity sec = m_securityMap[security.tradingCurrency()];
      prices += file->price(sec.id(), file->baseCurrency().id());
    }
    KMyMoneyAccountTreeItem* item = new KMyMoneyAccountTreeItem(parent, acc, prices, security);
    if(acc.id() == m_reconciliationAccount.id())
      item->setReconciliation(true);
  }
}

void KInstitutionsView::loadSubAccounts(KMyMoneyAccountTreeItem* parent, const TQString& institutionId)
{
  MyMoneyFile* file = MyMoneyFile::instance();

  TQMap<TQString, MyMoneyAccount>::const_iterator it_a;
  MyMoneyMoney  value;
  bool showClosedAccounts = kmymoney2->toggleAction("view_show_all_accounts")->isChecked()
      || !KMyMoneyGlobalSettings::hideClosedAccounts();

  for(it_a = m_accountMap.begin(); it_a != m_accountMap.end(); ++it_a) {
    const MyMoneyAccount& acc = *it_a;
    MyMoneyMoney factor(1,1);
    switch(acc.accountGroup()) {
      case MyMoneyAccount::Liability:
        factor = MyMoneyMoney(-1,1);
        // tricky fall through here

      case MyMoneyAccount::Asset:
        if(acc.institutionId() == institutionId
        && !acc.isInvest()
        && (!acc.isClosed() || showClosedAccounts)) {
          TQValueList<MyMoneyPrice> prices;
          MyMoneySecurity security = file->baseCurrency();
          try {
            if(acc.currencyId() != file->baseCurrency().id()) {
              security = m_securityMap[acc.currencyId()];
              prices += file->price(acc.currencyId(), file->baseCurrency().id());
            }

          } catch(MyMoneyException *e) {
            kdDebug(2) << __PRETTY_FUNCTION__ << " caught exception while adding " << acc.name() << "[" << acc.id() << "]: " << e->what();
            delete e;
          }

          KMyMoneyAccountTreeItem* item = new KMyMoneyAccountTreeItem(parent, acc, prices, security);
          if(acc.id() == m_reconciliationAccount.id())
            item->setReconciliation(true);

          if(acc.accountType() == MyMoneyAccount::Investment)
            loadSubAccounts(item);
          value += (item->totalValue() * factor);
        }
        break;

      default:
        break;
    }
  }

  // the calulated value for the institution is not correct as
  // it does not take the negative sign for liability accounts
  // into account. So we correct this here with the value we
  // have calculated while filling the list
  parent->adjustTotalValue(-parent->totalValue());  // load a 0
  parent->adjustTotalValue(value);                  // now store the new value

  // we need to call slotUpdateNetWorth() here manually, because
  // KMyMoneyAccountTreeItem::adjustTotalValue() does not send out
  // the valueChanged() signal
  slotUpdateNetWorth();
}

void KInstitutionsView::slotUpdateNetWorth(void)
{
  MyMoneyMoney netWorth;

  // calculate by going through the account trees top items
  // and summing up the total value shown there
  KMyMoneyAccountTreeItem* item = dynamic_cast<KMyMoneyAccountTreeItem*>(m_accountTree->firstChild());
  while(item) {
    netWorth += item->totalValue();
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(item->nextSibling());
  }

  TQString s(i18n("Net Worth: "));

  // FIXME figure out how to deal with the approximate
  // if(!(file->totalValueValid(assetAccount.id()) & file->totalValueValid(liabilityAccount.id())))
  //  s += "~ ";

  s.replace(TQString(" "), TQString("&nbsp;"));
  if(netWorth.isNegative()) {
    s += "<b><font color=\"red\">";
  }
  const MyMoneySecurity& sec = MyMoneyFile::instance()->baseCurrency();
  TQString v(netWorth.formatMoney(sec));
  s += v.replace(TQString(" "), TQString("&nbsp;"));
  if(netWorth.isNegative()) {
    s += "</font></b>";
  }

  m_totalProfitsLabel->setFont(KMyMoneyGlobalSettings::listCellFont());
  m_totalProfitsLabel->setText(s);
}

void KInstitutionsView::slotReconcileAccount(const MyMoneyAccount& acc, const TQDate& reconciliationDate, const MyMoneyMoney& endingBalance)
{
  Q_UNUSED(reconciliationDate);
  Q_UNUSED(endingBalance);

  // scan through the list of accounts and mark all non
  // expanded and re-select the one that was probably selected before
  TQListViewItemIterator it_lvi(m_accountTree);
  KMyMoneyAccountTreeItem* item;
  while(it_lvi.current()) {
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
    if(item) {
      item->setReconciliation(false);
    }
    ++it_lvi;
  }

  m_reconciliationAccount = acc;
  if(!acc.id().isEmpty()) {
    it_lvi = TQListViewItemIterator(m_accountTree);
    while(it_lvi.current()) {
      item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
      if(item && item->itemObject().id() == acc.id()) {
        item->setReconciliation(true);
        break;
      }
      ++it_lvi;
    }
  }
}


#include "kinstitutionsview.moc"