summaryrefslogtreecommitdiffstats
path: root/kmymoney2/dialogs/kcurrencycalculator.cpp
blob: 2306816309e8566ad7df2db44e080c49229566e9 (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
/***************************************************************************
                          kcurrencycalculator.cpp  -  description
                             -------------------
    begin                : Thu Apr 8 2004
    copyright            : (C) 2000-2004 by Michael Edwardes
    email                : 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>
 ***************************************************************************/

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

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

#include <tqlabel.h>
#include <tqradiobutton.h>
#include <tqcheckbox.h>
#include <tqwidgetstack.h>
#include <tqgroupbox.h>

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

#include <klocale.h>
#include <kpushbutton.h>
#include <kcombobox.h>
#include <kstdguiitem.h>

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

#include "kcurrencycalculator.h"

#include <kmymoney/kmymoneyedit.h>
#include <kmymoney/kmymoneydateinput.h>
#include <kmymoney/kmymoneycurrencyselector.h>
#include <kmymoney/mymoneyprice.h>
#include <kmymoney/mymoneytransaction.h>
#include <kmymoney/kmymoneyglobalsettings.h>

#include "../kmymoneyutils.h"

bool KCurrencyCalculator::setupSplitPrice(MyMoneyMoney& shares, const MyMoneyTransaction& t, const MyMoneySplit& s, const TQMap<TQString, MyMoneyMoney>& priceInfo, TQWidget* parentWidget)
{
  bool rc = true;
  MyMoneyFile* file = MyMoneyFile::instance();

  if(!s.value().isZero()) {
    MyMoneyAccount cat = file->account(s.accountId());
    MyMoneySecurity toCurrency;
    toCurrency = file->security(cat.currencyId());
    // determine the fraction required for this category/account
    int fract = cat.fraction(toCurrency);

    if(cat.currencyId() != t.commodity()) {

      MyMoneySecurity fromCurrency;
      MyMoneyMoney fromValue, toValue;
      fromCurrency = file->security(t.commodity());
      // display only positive values to the user
      fromValue = s.value().abs();

      // if we had a price info in the beginning, we use it here
      if(priceInfo.find(cat.currencyId()) != priceInfo.end()) {
        toValue = (fromValue * priceInfo[cat.currencyId()]).convert(fract);
      }

      // if the shares are still 0, we need to change that
      if(toValue.isZero()) {
        MyMoneyPrice price = file->price(fromCurrency.id(), toCurrency.id());
        // if the price is valid calculate the shares. If it is invalid
        // assume a conversion rate of 1.0
        if(price.isValid()) {
          toValue = (price.rate(toCurrency.id()) * fromValue).convert(fract);
        } else {
          toValue = fromValue;
        }
      }

      // now present all that to the user
      KCurrencyCalculator calc(fromCurrency,
                              toCurrency,
                              fromValue,
                              toValue,
                              t.postDate(),
                              fract,
                              parentWidget, "currencyCalculator");

      if(calc.exec() == TQDialog::Rejected) {
        rc = false;
      } else
        shares = (s.value() * calc.price()).convert(fract);

    } else {
      shares = s.value().convert(fract);
    }
  } else
    shares = s.value();

  return rc;
}

KCurrencyCalculator::KCurrencyCalculator(const MyMoneySecurity& from, const MyMoneySecurity& to, const MyMoneyMoney& value, const MyMoneyMoney& shares, const TQDate& date, const signed64 resultFraction, TQWidget *parent, const char *name ) :
  KCurrencyCalculatorDecl(parent, name),
  m_fromCurrency(from),
  m_toCurrency(to),
  m_result(shares.abs()),
  m_value(value.abs()),
  m_resultFraction(resultFraction)
{
  MyMoneyFile* file = MyMoneyFile::instance();

  m_dateFrame->hide();
  if(date.isValid())
    m_dateEdit->setDate(date);
  else
    m_dateEdit->setDate(TQDate::tqcurrentDate());

  m_fromCurrencyText->setText(m_fromCurrency.isCurrency() ? m_fromCurrency.id() : m_fromCurrency.tradingSymbol());
  m_toCurrencyText->setText(m_toCurrency.isCurrency() ? m_toCurrency.id() : m_toCurrency.tradingSymbol());

  m_fromAmount->setText(m_value.formatMoney("", MyMoneyMoney::denomToPrec(m_fromCurrency.smallestAccountFraction())));

  m_dateText->setText(KGlobal::locale()->formatDate(date, true));

  m_fromType->setText(KMyMoneyUtils::securityTypeToString(m_fromCurrency.securityType()));
  m_toType->setText(KMyMoneyUtils::securityTypeToString(m_toCurrency.securityType()));

  // load button icons
  m_cancelButton->setGuiItem(KStdGuiItem::cancel());
  m_okButton->setGuiItem(KStdGuiItem::ok());

  m_updateButton->setChecked(KMyMoneyGlobalSettings::priceHistoryUpdate());

  // setup initial result
  if(m_result == MyMoneyMoney() && !m_value.isZero()) {
    MyMoneyPrice pr = file->price(m_fromCurrency.id(), m_toCurrency.id(), date);
    if(pr.isValid()) {
      m_result = m_value * pr.rate(m_fromCurrency.id());
    }
  }

  // fill in initial values
  m_toAmount->loadText(m_result.formatMoney("", MyMoneyMoney::denomToPrec(m_resultFraction)));
  m_toAmount->setPrecision(MyMoneyMoney::denomToPrec(m_resultFraction));

  m_conversionRate->setPrecision(KMyMoneyGlobalSettings::pricePrecision());

  connect(m_amountButton, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotSetToAmount()));
  connect(m_rateButton, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotSetExchangeRate()));

  connect(m_toAmount, TQT_SIGNAL(valueChanged(const TQString&)), this, TQT_SLOT(slotUpdateResult(const TQString&)));
  connect(m_conversionRate, TQT_SIGNAL(valueChanged(const TQString&)), this, TQT_SLOT(slotUpdateRate(const TQString&)));
  connect(m_cancelButton, TQT_SIGNAL(clicked()), this, TQT_SLOT(reject()));
  connect(m_okButton, TQT_SIGNAL(clicked()), this, TQT_SLOT(accept()));

  // use this as the default
  m_amountButton->animateClick();
  slotUpdateResult(m_toAmount->text());

  // If the from security is not a currency, we only allow entering a price
  if(!m_fromCurrency.isCurrency()) {
    m_rateButton->animateClick();
    m_amountButton->hide();
    m_toAmount->hide();
  }
  m_okButton->setFocus();
}

KCurrencyCalculator::~KCurrencyCalculator()
{
}

void KCurrencyCalculator::setupPriceEditor(void)
{
  m_dateFrame->show();
  m_amountDateFrame->hide();
  m_updateButton->setChecked(true);
  m_updateButton->hide();
}

void KCurrencyCalculator::slotSetToAmount(void)
{
  m_rateButton->setChecked(false);
  m_toAmount->setEnabled(true);
  m_conversionRate->setEnabled(false);
}

void KCurrencyCalculator::slotSetExchangeRate(void)
{
  m_amountButton->setChecked(false);
  m_toAmount->setEnabled(false);
  m_conversionRate->setEnabled(true);
}

void KCurrencyCalculator::slotUpdateResult(const TQString& /*txt*/)
{
  MyMoneyMoney result = m_toAmount->value();
  MyMoneyMoney price(0, 1);

  if(result.isNegative()) {
    m_toAmount->setValue(-result);
    slotUpdateResult(TQString());
    return;
  }

  if(!result.isZero()) {
    price = result / m_value;

    m_conversionRate->loadText(price.formatMoney("", KMyMoneyGlobalSettings::pricePrecision()));
    m_result = (m_value * price).convert(m_resultFraction);
    m_toAmount->loadText(m_result.formatMoney("", MyMoneyMoney::denomToPrec(m_resultFraction)));
  }
  updateExample(price);
}

void KCurrencyCalculator::slotUpdateRate(const TQString& /*txt*/)
{
  MyMoneyMoney price = m_conversionRate->value();

  if(price.isNegative()) {
    m_conversionRate->setValue(-price);
    slotUpdateRate(TQString());
    return;
  }

  if(!price.isZero()) {
    m_conversionRate->loadText(price.formatMoney("", KMyMoneyGlobalSettings::pricePrecision()));
    m_result = (m_value * price).convert(m_resultFraction);
    m_toAmount->loadText(m_result.formatMoney("", MyMoneyMoney::denomToPrec(m_resultFraction)));
  }
  updateExample(price);
}

void KCurrencyCalculator::updateExample(const MyMoneyMoney& price)
{
  TQString msg;
  if(price.isZero()) {
    msg = TQString("1 %1 = ? %2").tqarg(m_fromCurrency.tradingSymbol())
                                .tqarg(m_toCurrency.tradingSymbol());
    if(m_fromCurrency.isCurrency()) {
      msg += TQString("\n");
      msg += TQString("1 %1 = ? %2").tqarg(m_toCurrency.tradingSymbol())
                                     .tqarg(m_fromCurrency.tradingSymbol());
    }
  } else {
    msg = TQString("1 %1 = %2 %3").tqarg(m_fromCurrency.tradingSymbol())
                                 .tqarg(price.formatMoney("", KMyMoneyGlobalSettings::pricePrecision()))
                                 .tqarg(m_toCurrency.tradingSymbol());
    if(m_fromCurrency.isCurrency()) {
      msg += TQString("\n");
      msg += TQString("1 %1 = %2 %3").tqarg(m_toCurrency.tradingSymbol())
                                    .tqarg((MyMoneyMoney(1,1)/price).formatMoney("", KMyMoneyGlobalSettings::pricePrecision()))
                                    .tqarg(m_fromCurrency.tradingSymbol());
    }
  }
  m_conversionExample->setText(msg);
  m_okButton->setEnabled(!price.isZero());
}

void KCurrencyCalculator::accept(void)
{
  if(m_conversionRate->isEnabled())
    slotUpdateRate(TQString());
  else
    slotUpdateResult(TQString());

  if(m_updateButton->isChecked()) {
    MyMoneyPrice pr = MyMoneyFile::instance()->price(m_fromCurrency.id(), m_toCurrency.id(), m_dateEdit->date());
    if(!pr.isValid()
    || pr.date() != m_dateEdit->date()
    || (pr.date() == m_dateEdit->date() && pr.rate(m_fromCurrency.id()) != price())) {
      pr = MyMoneyPrice(m_fromCurrency.id(), m_toCurrency.id(), m_dateEdit->date(), price(), i18n("User"));
      MyMoneyFileTransaction ft;
      try {
        MyMoneyFile::instance()->addPrice(pr);
        ft.commit();
      } catch(MyMoneyException *e) {
        qDebug("Cannot add price");
        delete e;
      }
    }
  }

  // remember setting for next round
  KMyMoneyGlobalSettings::setPriceHistoryUpdate(m_updateButton->isChecked());

  KCurrencyCalculatorDecl::accept();
}

const MyMoneyMoney KCurrencyCalculator::price(void) const
{
  // This should fix https://bugs.kde.org/show_bug.cgi?id=205254 but
  // I am not sure about any side effects when dealing with multi-
  // currency transactions.
  //
  // The following line is the original version of this code
  // which causes some rounding issues (see the above bug entry)
  // return m_result / m_value;
  return m_conversionRate->value();
}


#include "kcurrencycalculator.moc"