Пример #1
0
void KInstitutionsView::slotReconcileAccount(const MyMoneyAccount& acc, const QDate& 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
  QListViewItemIterator 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 = QListViewItemIterator(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;
    }
  }
}
Пример #2
0
void KMyMoneyUtils::updateLastNumberUsed(const MyMoneyAccount& acc, const QString& number)
{
  MyMoneyAccount accnt = acc;
  QString num = number;
  // now check if this number has been used already
  MyMoneyFile* file = MyMoneyFile::instance();
  if (file->checkNoUsed(accnt.id(), num)) {
    // if a number has been entered which is immediately prior to
    // an existing number, the next new number produced would clash
    // so need to look ahead for free next number
    bool free = false;
    for (int i = 0; i < 10; i++) {
      // find next unused number - 10 tries (arbitrary)
      if (file->checkNoUsed(accnt.id(), num)) {
        //  increment and try again
        num = getAdjacentNumber(num);
      } else {
        //  found a free number
        free = true;
        break;
      }
    }
    if (!free) {
      qDebug() << "No free number found - set to '1'";
      num = '1';
    }
    setLastNumberUsed(getAdjacentNumber(num, - 1));
  }
}
Пример #3
0
void KForecastView::loadAccounts(MyMoneyForecast& forecast, const MyMoneyAccount& account, QTreeWidgetItem* parentItem, int forecastType)
{
  QMap<QString, QString> nameIdx;
  QStringList accList;
  MyMoneyFile* file = MyMoneyFile::instance();
  QTreeWidgetItem *forecastItem = 0;

  //Get all accounts of the right type to calculate forecast
  accList = account.accountList();

  if (accList.size() == 0)
    return;

  QStringList::ConstIterator accList_t;
  for (accList_t = accList.constBegin(); accList_t != accList.constEnd(); ++accList_t) {
    MyMoneyAccount subAccount = file->account(*accList_t);
    //only add the account if it is a forecast account or the parent of a forecast account
    if (includeAccount(forecast, subAccount)) {
      nameIdx[subAccount.id()] = subAccount.id();
    }
  }

  QMap<QString, QString>::ConstIterator it_nc;
  for (it_nc = nameIdx.constBegin(); it_nc != nameIdx.constEnd(); ++it_nc) {

    const MyMoneyAccount subAccount = file->account(*it_nc);
    MyMoneySecurity currency;
    if (subAccount.isInvest()) {
      MyMoneySecurity underSecurity = file->security(subAccount.currencyId());
      currency = file->security(underSecurity.tradingCurrency());
    } else {
      currency = file->security(subAccount.currencyId());
    }

    forecastItem = new QTreeWidgetItem(parentItem);
    forecastItem->setText(0, subAccount.name());
    forecastItem->setIcon(0, subAccount.accountPixmap());
    forecastItem->setData(0, ForecastRole, QVariant::fromValue(forecast));
    forecastItem->setData(0, AccountRole, QVariant::fromValue(subAccount));
    forecastItem->setExpanded(true);

    switch (forecastType) {
      case eSummary:
        updateSummary(forecastItem);
        break;
      case eDetailed:
        updateDetailed(forecastItem);
        break;
      case eBudget:
        updateBudget(forecastItem);
        break;
      default:
        break;
    }

    loadAccounts(forecast, subAccount, forecastItem, forecastType);
  }
}
Пример #4
0
MyMoneyMoney MyMoneyForecast::calculateAccountTrend(const MyMoneyAccount& acc, int trendDays)
{
  MyMoneyFile* file = MyMoneyFile::instance();
  MyMoneyTransactionFilter filter;
  MyMoneyMoney netIncome;
  QDate startDate;
  QDate openingDate = acc.openingDate();

  //validate arguments
  if(trendDays < 1)
  {
    throw new MYMONEYEXCEPTION("Illegal arguments when calling calculateAccountTrend. trendDays must be higher than 0");
  }

  //If it is a new account, we don't take into account the first day
  //because it is usually a weird one and it would mess up the trend
  if(openingDate.daysTo(QDate::currentDate())<trendDays){
    startDate = (acc.openingDate()).addDays(1);
  }
  else {
    startDate = QDate::currentDate().addDays(-trendDays);
  }
  //get all transactions for the period
  filter.setDateFilter(startDate, QDate::currentDate());
  if(acc.accountGroup() == MyMoneyAccount::Income
     || acc.accountGroup() == MyMoneyAccount::Expense) {
    filter.addCategory(acc.id());
     } else {
       filter.addAccount(acc.id());
     }

  filter.setReportAllSplits(false);
  QValueList<MyMoneyTransaction> transactions = file->transactionList(filter);
  QValueList<MyMoneyTransaction>::const_iterator it_t = transactions.begin();

  //add all transactions for that account
  for(; it_t != transactions.end(); ++it_t ) {
    const QValueList<MyMoneySplit>& splits = (*it_t).splits();
    QValueList<MyMoneySplit>::const_iterator it_s = splits.begin();
    for(; it_s != splits.end(); ++it_s ) {
      if(!(*it_s).shares().isZero()) {
        if(acc.id()==(*it_s).accountId()) netIncome += (*it_s).value();
      }
    }
  }

  //calculate trend of the account in the past period
  MyMoneyMoney accTrend;

  //don't take into account the first day of the account
  if(openingDate.daysTo(QDate::currentDate())<trendDays) {
    accTrend = netIncome/MyMoneyMoney(openingDate.daysTo(QDate::currentDate())-1,1);
  } else {
    accTrend = netIncome/MyMoneyMoney(trendDays,1);
  }
  return accTrend;
}
Пример #5
0
void MyMoneyForecast::addFutureTransactions(void)
{
  MyMoneyTransactionFilter filter;
  MyMoneyFile* file = MyMoneyFile::instance();

  // collect and process all transactions that have already been entered but
  // are located in the future.
  filter.setDateFilter(forecastStartDate(), forecastEndDate());
  filter.setReportAllSplits(false);

  QValueList<MyMoneyTransaction> transactions = file->transactionList(filter);
  QValueList<MyMoneyTransaction>::const_iterator it_t = transactions.begin();

  for(; it_t != transactions.end(); ++it_t ) {
    const QValueList<MyMoneySplit>& splits = (*it_t).splits();
    QValueList<MyMoneySplit>::const_iterator it_s = splits.begin();
    for(; it_s != splits.end(); ++it_s ) {
      if(!(*it_s).shares().isZero()) {
        MyMoneyAccount acc = file->account((*it_s).accountId());
        if(isForecastAccount(acc)) {
          dailyBalances balance;
          balance = m_accountList[acc.id()];
          //if it is income, the balance is stored as negative number
          if(acc.accountType() == MyMoneyAccount::Income) {
            balance[(*it_t).postDate()] += ((*it_s).shares() * MyMoneyMoney(-1, 1));
          } else {
            balance[(*it_t).postDate()] += (*it_s).shares();
          }
          m_accountList[acc.id()] = balance;
        }
      }
    }
  }

#if 0
  QFile trcFile("forecast.csv");
    trcFile.open(IO_WriteOnly);
    QTextStream s(&trcFile);

    {
      s << "Already present transactions\n";
      QMap<QString, dailyBalances>::Iterator it_a;
      QMap<QString, QString>::ConstIterator it_n;
      for(it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n) {
      MyMoneyAccount acc = file->account(*it_n);
      it_a = m_accountList.find(*it_n);
      s << "\"" << acc.name() << "\",";
      for(int i = 0; i < 90; ++i) {
      s << "\"" << (*it_a)[i].formatMoney("") << "\",";
    }
    s << "\n";
  }
}
#endif

}
Пример #6
0
MyMoneyMoney MyMoneyForecast::accountWeightedMovingAverage(const MyMoneyAccount &acc, const int trendDay, const int totalWeight)
{
  MyMoneyMoney balanceVariation;

  for(int it_terms = 0, weight = 1; (trendDay+(accountsCycle()*it_terms)) <= historyDays(); ++it_terms, ++weight) //sum for each term multiplied by weight
  {
    MyMoneyMoney balanceBefore = m_accountListPast[acc.id()][historyStartDate().addDays(trendDay+(accountsCycle()*it_terms)-2)]; //get balance for the day before
    MyMoneyMoney balanceAfter = m_accountListPast[acc.id()][historyStartDate().addDays(trendDay+(accountsCycle()*it_terms)-1)];
    balanceVariation += ( (balanceAfter - balanceBefore) * MyMoneyMoney(weight, 1) ); //add the balance variation between days multiplied by its weight
  }
  //calculate average of the variations
  return (balanceVariation / MyMoneyMoney(totalWeight, 1)).convert(10000);
}
Пример #7
0
void MyMoneyForecast::setBudgetAccountList(void)
{
  //get budget accounts
  QValueList<MyMoneyAccount> accList;
  accList = budgetAccountList();

  QValueList<MyMoneyAccount>::const_iterator accList_t = accList.begin();
  for(; accList_t != accList.end(); ++accList_t ) {
    MyMoneyAccount acc = *accList_t;
      // check if this is a new account for us
    if(m_nameIdx[acc.id()] != acc.id()) {
      m_nameIdx[acc.id()] = acc.id();
    }
  }
}
Пример #8
0
ReportAccount::ReportAccount(const MyMoneyAccount& account):
    MyMoneyAccount(account)
{
  DEBUG_ENTER(Q_FUNC_INFO);
  DEBUG_OUTPUT(QString("Account %1").arg(account.id()));
  calculateAccountHierarchy();
}
Пример #9
0
QString makeAccount( const QString& _name, MyMoneyAccount::accountTypeE _type, MyMoneyMoney _balance, const QDate& _open, const QString& _parent, QString _currency, bool _taxReport )
{
  MyMoneyAccount info;
  MyMoneyFileTransaction ft;

  info.setName(_name);
  info.setAccountType(_type);
  info.setOpeningDate(_open);
  if ( _currency != "" )
    info.setCurrencyId(_currency);
  else
    info.setCurrencyId(MyMoneyFile::instance()->baseCurrency().id());

  if(_taxReport)
    info.setValue("Tax", "Yes");

  MyMoneyAccount parent = MyMoneyFile::instance()->account(_parent);
  MyMoneyFile::instance()->addAccount( info, parent );
  // create the opening balance transaction if any
  if(!_balance.isZero()) {
    MyMoneySecurity sec = MyMoneyFile::instance()->currency(info.currencyId());
    MyMoneyFile::instance()->openingBalanceAccount(sec);
    MyMoneyFile::instance()->createOpeningBalanceTransaction(info, _balance);
  }
  ft.commit();

  return info.id();
}
Пример #10
0
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());
  QValueList<QString>::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()];
    QValueList<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);
  }
}
Пример #11
0
int MyMoneyForecast::daysToZeroBalance(const MyMoneyAccount& acc)
{
  dailyBalances balance;

  //Check if acc is not a forecast account, return -1
  if(!isForecastAccount(acc)) {
    return -2;
  }

  balance = m_accountList[acc.id()];

  if (acc.accountGroup() == MyMoneyAccount::Asset) {
    for (QDate it_day = QDate::currentDate() ; it_day <= forecastEndDate(); )
    {
      if ( balance[it_day] < MyMoneyMoney ( 0, 1 ) )
      {
        return QDate::currentDate().daysTo(it_day);
      }
      it_day = it_day.addDays(1);
    }
  } else if (acc.accountGroup() == MyMoneyAccount::Liability) {
    for (QDate it_day = QDate::currentDate() ; it_day <= forecastEndDate(); )
    {
      if ( balance[it_day] > MyMoneyMoney ( 0, 1 ) )
      {
        return QDate::currentDate().daysTo(it_day);
      }
      it_day = it_day.addDays(1);
    }
  }
  return -1;
}
Пример #12
0
MyMoneyMoney MyMoneyForecast::accountMovingAverage(const MyMoneyAccount &acc, const int trendDay, const int forecastTerms)
{
  //Calculate a daily trend for the account based on the accounts of a given number of terms
  //With a term of 1 month and 3 terms, it calculates the trend taking the transactions occurred at that day and the day before,
  //for the last 3 months
  MyMoneyMoney balanceVariation;

  for(int it_terms = 0; (trendDay+(accountsCycle()*it_terms)) <= historyDays(); ++it_terms) //sum for each term
  {
    MyMoneyMoney balanceBefore = m_accountListPast[acc.id()][historyStartDate().addDays(trendDay+(accountsCycle()*it_terms)-2)]; //get balance for the day before
    MyMoneyMoney balanceAfter = m_accountListPast[acc.id()][historyStartDate().addDays(trendDay+(accountsCycle()*it_terms)-1)];
    balanceVariation += (balanceAfter - balanceBefore); //add the balance variation between days
  }
  //calculate average of the variations
  return (balanceVariation / MyMoneyMoney(forecastTerms,1)).convert(10000);
}
Пример #13
0
void MyMoneyForecast::doFutureScheduledForecast(void)
{
  MyMoneyFile* file = MyMoneyFile::instance();

  if(isIncludingFutureTransactions())
    addFutureTransactions();

  if(isIncludingScheduledTransactions())
    addScheduledTransactions();

  //do not show accounts with no transactions
  if(!isIncludingUnusedAccounts())
    purgeForecastAccountsList(m_accountList);

  //adjust value of investments to deep currency
  QMap<QString, QString>::ConstIterator it_n;
  for ( it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n ) {
    MyMoneyAccount acc = file->account ( *it_n );

    if ( acc.isInvest() ) {
      //get the id of the security for that account
      MyMoneySecurity undersecurity = file->security ( acc.currencyId() );

      //only do it if the security is not an actual currency
      if ( ! undersecurity.isCurrency() )
      {
        //set the default value
        MyMoneyMoney rate = MyMoneyMoney ( 1, 1 );
        MyMoneyPrice price;

        for (QDate it_day = QDate::currentDate(); it_day <= forecastEndDate(); ) {
          //get the price for the tradingCurrency that day
          price = file->price ( undersecurity.id(), undersecurity.tradingCurrency(), it_day );
          if ( price.isValid() )
          {
            rate = price.rate ( undersecurity.tradingCurrency() );
          }
          //value is the amount of shares multiplied by the rate of the deep currency
          m_accountList[acc.id() ][it_day] = m_accountList[acc.id() ][it_day] * rate;
          it_day = it_day.addDays(1);
        }
      }
    }
  }
}
Пример #14
0
bool MyMoneyReport::includes( const MyMoneyAccount& acc ) const
{
  bool result = false;

  if ( includesAccountGroup ( acc.accountGroup() ) )
  {
    switch ( acc.accountGroup() )
    {
      case MyMoneyAccount::Income:
      case MyMoneyAccount::Expense:
        if ( isTax() )
          result = ( acc.value ( "Tax" ) == "Yes" ) && includesCategory ( acc.id() );
        else
          result = includesCategory ( acc.id() );
        break;
      case MyMoneyAccount::Asset:
      case MyMoneyAccount::Liability:
        if ( isLoansOnly() )
          result = acc.isLoan() && includesAccount ( acc.id() );
        else if ( isInvestmentsOnly() )
          result = acc.isInvest() && includesAccount ( acc.id() );
        else if ( isIncludingTransfers() && m_rowType == MyMoneyReport::eExpenseIncome )
          // If transfers are included, ONLY include this account if it is NOT
          // included in the report itself!!
          result = ! includesAccount ( acc.id() );
        else
          result = includesAccount ( acc.id() );
        break;
      default:
        result = includesAccount ( acc.id() );
    }
  }
  return result;
}
Пример #15
0
void KEndingBalanceDlg::createCategory(const QString& txt, QString& id, const MyMoneyAccount& parent)
{
  MyMoneyAccount acc;
  acc.setName(txt);

  emit createCategory(acc, parent);

  id = acc.id();
}
Пример #16
0
MyMoneyMoney MyMoneyForecast::forecastBalance(const MyMoneyAccount& acc, QDate forecastDate)
{

  dailyBalances balance;
  MyMoneyMoney MM_amount = MyMoneyMoney(0,1);

  //Check if acc is not a forecast account, return 0
  if ( !isForecastAccount ( acc ) )
  {
    return MM_amount;
  }

  balance = m_accountList[acc.id() ];
  if ( balance.contains ( forecastDate ) )
  { //if the date is not in the forecast, it returns 0
    MM_amount = m_accountList[acc.id() ][forecastDate];
  }
  return MM_amount;
}
Пример #17
0
void MyMoneyForecast::calculateHistoricDailyBalances()
{
  MyMoneyFile* file = MyMoneyFile::instance();

  calculateAccountTrendList();

  //Calculate account daily balances
  QMap<QString, QString>::ConstIterator it_n;
  for(it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n) {
    MyMoneyAccount acc = file->account(*it_n);

    //set the starting balance of the account
    setStartingBalance(acc);

    switch(historyMethod()) {
      case 0:
      case 1:
      {
        for(QDate f_day = forecastStartDate(); f_day <= forecastEndDate(); ) {
          for(int t_day = 1; t_day <= accountsCycle(); ++t_day) {
            MyMoneyMoney balanceDayBefore = m_accountList[acc.id()][(f_day.addDays(-1))];//balance of the day before
            MyMoneyMoney accountDailyTrend = m_accountTrendList[acc.id()][t_day]; //trend for that day
            //balance of the day is the balance of the day before multiplied by the trend for the day
            m_accountList[acc.id()][f_day] = balanceDayBefore;
            m_accountList[acc.id()][f_day] += accountDailyTrend; //movement trend for that particular day
            m_accountList[acc.id()][f_day] = m_accountList[acc.id()][f_day].convert(acc.fraction());
            //m_accountList[acc.id()][f_day] += m_accountListPast[acc.id()][f_day.addDays(-historyDays())];
            f_day = f_day.addDays(1);
          }
        }
      }
      break;
      case 2:
      {
        QDate baseDate = QDate::currentDate().addDays(-accountsCycle());
        for(int t_day = 1; t_day <= accountsCycle(); ++t_day) {
          int f_day = 1;
          QDate fDate = baseDate.addDays(accountsCycle()+1);
          while (fDate <= forecastEndDate()) {

            //the calculation is based on the balance for the last month, that is then multiplied by the trend
            m_accountList[acc.id()][fDate] = m_accountListPast[acc.id()][baseDate] + (m_accountTrendList[acc.id()][t_day] * MyMoneyMoney(f_day,1));
            m_accountList[acc.id()][fDate] = m_accountList[acc.id()][fDate].convert(acc.fraction());
            ++f_day;
            fDate = baseDate.addDays(accountsCycle() * f_day);
          }
          baseDate = baseDate.addDays(1);
        }
      }
    }
  }
}
Пример #18
0
void MyMoneyForecast::calculateScheduledMonthlyBalances()
{
  MyMoneyFile* file = MyMoneyFile::instance();

//Calculate account monthly balances
  QMap<QString, QString>::ConstIterator it_n;
  for(it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n) {
    MyMoneyAccount acc = file->account(*it_n);

    for( QDate f_date = forecastStartDate(); f_date <= forecastEndDate(); f_date = f_date.addDays(1) ) {
      //get the trend for the day
      MyMoneyMoney accountDailyBalance = m_accountList[acc.id()][f_date];

      //do not add if it is the beginning of the month
      //otherwise we end up with duplicated values as reported by Marko Käning
      if(f_date != QDate(f_date.year(), f_date.month(), 1) )
        m_accountList[acc.id()][QDate(f_date.year(), f_date.month(), 1)] += accountDailyBalance;
    }
  }
}
Пример #19
0
void MyMoneyForecast::calculateScheduledDailyBalances (void)
{
  MyMoneyFile* file = MyMoneyFile::instance();

  //Calculate account daily balances
  QMap<QString, QString>::ConstIterator it_n;
  for(it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n) {
    MyMoneyAccount acc = file->account(*it_n);

    //set the starting balance of the account
    setStartingBalance(acc);

    for(QDate f_day = forecastStartDate(); f_day <= forecastEndDate(); ) {
      MyMoneyMoney balanceDayBefore = m_accountList[acc.id()][(f_day.addDays(-1))];//balance of the day before
      m_accountList[acc.id()][f_day] += balanceDayBefore; //running sum
      f_day = f_day.addDays(1);
    }
  }


}
Пример #20
0
void CsvUtil::scanCategories(QString& id, const MyMoneyAccount& invAcc, const MyMoneyAccount& parentAccount, const QString& defaultName)
{
  if (!m_scannedCategories) {
    previouslyUsedCategories(invAcc.id(), m_feeId, m_interestId);
    m_scannedCategories = true;
  }

  if (id.isEmpty()) {
    MyMoneyFile* file = MyMoneyFile::instance();
    MyMoneyAccount acc = file->accountByName(defaultName);
    // if it does not exist, we have to create it
    if (acc.id().isEmpty()) {
      MyMoneyAccount parent = parentAccount;
      acc.setName(defaultName);
      acc.setAccountType(parent.accountType());
      acc.setCurrencyId(parent.currencyId());
      file->addAccount(acc, parent);
    }
    id = acc.id();
  }
}
Пример #21
0
void MyMoneyForecast::calculateHistoricMonthlyBalances()
{
  MyMoneyFile* file = MyMoneyFile::instance();

  //Calculate account monthly balances
  QMap<QString, QString>::ConstIterator it_n;
  for(it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n) {
    MyMoneyAccount acc = file->account(*it_n);

    for( QDate f_date = forecastStartDate(); f_date <= forecastEndDate(); ) {
      for(int f_day = 1; f_day <= accountsCycle() && f_date <= forecastEndDate(); ++f_day) {
        MyMoneyMoney accountDailyTrend = m_accountTrendList[acc.id()][f_day]; //trend for that day
        //check for leap year
        if(f_date.month() == 2 && f_date.day() == 29)
          f_date = f_date.addDays(1); //skip 1 day
        m_accountList[acc.id()][QDate(f_date.year(), f_date.month(), 1)] += accountDailyTrend; //movement trend for that particular day
        f_date = f_date.addDays(1);
      }
    }
  }
}
Пример #22
0
MyMoneyMoney MyMoneyForecast::accountLinearRegression(const MyMoneyAccount &acc, const int trendDay, const int actualTerms, const MyMoneyMoney meanTerms)
{
  MyMoneyMoney meanBalance, totalBalance, totalTerms;
  totalTerms = MyMoneyMoney(actualTerms, 1);

  //calculate mean balance
  for(int it_terms = forecastCycles() - actualTerms; (trendDay+(accountsCycle()*it_terms)) <= historyDays(); ++it_terms) //sum for each term
  {
    totalBalance += m_accountListPast[acc.id()][historyStartDate().addDays(trendDay+(accountsCycle()*it_terms)-1)];
  }
  meanBalance = totalBalance / MyMoneyMoney(actualTerms,1);
  meanBalance = meanBalance.convert(10000);

  //calculate b1

  //first calculate x - mean x multiplied by y - mean y
  MyMoneyMoney totalXY, totalSqX;
  for(int it_terms = forecastCycles() - actualTerms, term = 1; (trendDay+(accountsCycle()*it_terms)) <= historyDays(); ++it_terms, ++term) //sum for each term
  {
    MyMoneyMoney balance = m_accountListPast[acc.id()][historyStartDate().addDays(trendDay+(accountsCycle()*it_terms)-1)];

    MyMoneyMoney balMeanBal = balance - meanBalance;
    MyMoneyMoney termMeanTerm = (MyMoneyMoney(term, 1) - meanTerms);

    totalXY += (balMeanBal * termMeanTerm).convert(10000);

    totalSqX += (termMeanTerm * termMeanTerm).convert(10000);
  }
  totalXY = (totalXY / MyMoneyMoney(actualTerms,1)).convert(10000);
  totalSqX = (totalSqX / MyMoneyMoney(actualTerms,1)).convert(10000);

  //check zero
  if(totalSqX.isZero())
    return MyMoneyMoney(0,1);

  MyMoneyMoney linReg = (totalXY/totalSqX).convert(10000);

  return linReg;
}
Пример #23
0
void MyMoneyAccountTest::testEmptyConstructor()
{
  MyMoneyAccount a;

  QVERIFY(a.id().isEmpty());
  QVERIFY(a.name().isEmpty());
  QVERIFY(a.accountType() == MyMoneyAccount::UnknownAccountType);
  QVERIFY(a.openingDate() == QDate());
  QVERIFY(a.lastModified() == QDate());
  QVERIFY(a.lastReconciliationDate() == QDate());
  QVERIFY(a.accountList().count() == 0);
  QVERIFY(a.balance().isZero());
}
Пример #24
0
MyMoneyMoney MyMoneyForecast::accountCycleVariation(const MyMoneyAccount& acc)
{
  MyMoneyMoney cycleVariation;

  if (forecastMethod() == eHistoric) {
    switch(historyMethod()) {
      case 0:
      case 1:
        {
          for(int t_day = 1; t_day <= accountsCycle() ; ++t_day) {
            cycleVariation += m_accountTrendList[acc.id()][t_day];
          }
        }
        break;

      case 2:
        {
          cycleVariation = m_accountList[acc.id()][QDate::currentDate().addDays(accountsCycle())] - m_accountList[acc.id()][QDate::currentDate()];
        }
        break;
    }
  }
  return cycleVariation;
}
Пример #25
0
bool MyMoneyForecast::isForecastAccount(const MyMoneyAccount& acc)
{
  if(m_nameIdx.isEmpty())
  {
    setForecastAccountList();
  }
  QMap<QString, QString>::Iterator it_n;
  for(it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n) {
    if(*it_n == acc.id())
    {
      return true;
    }
  }
  return false;
}
Пример #26
0
void KForecastView::setValue(QTreeWidgetItem* item, int column, const MyMoneyMoney& amount, const QDate& forecastDate)
{
  MyMoneyAccount account = item->data(0, AccountRole).value<MyMoneyAccount>();
  //calculate the balance in base currency for the total row
  if (account.currencyId() != MyMoneyFile::instance()->baseCurrency().id()) {
    ReportAccount repAcc = ReportAccount(account.id());
    MyMoneyMoney curPrice = repAcc.baseCurrencyPrice(forecastDate);
    MyMoneyMoney baseAmountMM = amount * curPrice;
    MyMoneyMoney value = baseAmountMM.convert(MyMoneyFile::instance()->baseCurrency().smallestAccountFraction());
    item->setData(column, ValueRole, QVariant::fromValue(value));
    adjustParentValue(item->parent(), column, value);
  } else {
    item->setData(column, ValueRole, QVariant::fromValue(item->data(column, ValueRole).value<MyMoneyMoney>() + amount));
    adjustParentValue(item->parent(), column, amount);
  }
}
Пример #27
0
void MyMoneyQifWriter::writeAccountEntry(QTextStream &s, const QString& accountId, const QDate& startDate, const QDate& endDate)
{
  MyMoneyFile* file = MyMoneyFile::instance();
  MyMoneyAccount account;

  account = file->account(accountId);
  MyMoneyTransactionFilter filter(accountId);
  filter.setDateFilter(startDate, endDate);
  QValueList<MyMoneyTransaction> list = file->transactionList(filter);
  QString openingBalanceTransactionId;

  s << "!Type:" << m_qifProfile.profileType() << endl;
  if(!startDate.isValid() || startDate <= account.openingDate()) {
    s << "D" << m_qifProfile.date(account.openingDate()) << endl;
    openingBalanceTransactionId = file->openingBalanceTransaction(account);
    MyMoneySplit split;
    if(!openingBalanceTransactionId.isEmpty()) {
      MyMoneyTransaction openingBalanceTransaction = file->transaction(openingBalanceTransactionId);
      split = openingBalanceTransaction.splitByAccount(account.id(), true /* match */);
    }
    s << "T" << m_qifProfile.value('T', split.value()) << endl;
  } else {
    s << "D" << m_qifProfile.date(startDate) << endl;
    s << "T" << m_qifProfile.value('T', file->balance(accountId, startDate.addDays(-1))) << endl;
  }
  s << "CX" << endl;
  s << "P" << m_qifProfile.openingBalanceText() << endl;
  s << "L";
  if(m_qifProfile.accountDelimiter().length())
    s << m_qifProfile.accountDelimiter()[0];
  s << account.name();
  if(m_qifProfile.accountDelimiter().length() > 1)
    s << m_qifProfile.accountDelimiter()[1];
  s << endl;
  s << "^" << endl;

  QValueList<MyMoneyTransaction>::ConstIterator it;
  signalProgress(0, list.count());
  int count = 0;
  for(it = list.begin(); it != list.end(); ++it) {
    // don't include the openingBalanceTransaction again
    if((*it).id() != openingBalanceTransactionId)
      writeTransactionEntry(s, *it, accountId);
    signalProgress(++count, 0);
  }
}
void onlineJobAdministrationTest::initTestCase()
{
  file = MyMoneyFile::instance();
  storage = new MyMoneySeqAccessMgr;
  file->attachStorage(storage);

  try {
    MyMoneyAccount account = MyMoneyAccount();
    account.setName("Test Account");
    account.setAccountType(MyMoneyAccount::Savings);
    MyMoneyAccount asset = file->asset();
    MyMoneyFileTransaction transaction;
    file->addAccount(account , asset);
    accountId = account.id();
    transaction.commit();
  } catch (const MyMoneyException& ex) {
    QFAIL(qPrintable("Unexpected exception " + ex.what()));
  }
}
Пример #29
0
QString CsvUtil::nameToId(const QString& name, MyMoneyAccount& parent)
{
  //  Adapted from KMyMoneyApp::createAccount(MyMoneyAccount& newAccount, MyMoneyAccount& parentAccount, MyMoneyAccount& brokerageAccount, MyMoneyMoney openingBal)
  //  Needed to find/create category:sub-categories
  MyMoneyFile* file = MyMoneyFile::instance();

  QString id = file->categoryToAccount(name, MyMoneyAccount::UnknownAccountType);
  // if it does not exist, we have to create it
  if (id.isEmpty()) {
    MyMoneyAccount newAccount;
    MyMoneyAccount parentAccount = parent;
    newAccount.setName(name) ;
    int pos;
    // check for ':' in the name and use it as separator for a hierarchy
    while ((pos = newAccount.name().indexOf(MyMoneyFile::AccountSeperator)) != -1) {
      QString part = newAccount.name().left(pos);
      QString remainder = newAccount.name().mid(pos + 1);
      const MyMoneyAccount& existingAccount = file->subAccountByName(parentAccount, part);
      if (existingAccount.id().isEmpty()) {
        newAccount.setName(part);
        newAccount.setAccountType(parentAccount.accountType());
        file->addAccount(newAccount, parentAccount);
        parentAccount = newAccount;
      } else {
        parentAccount = existingAccount;
      }
      newAccount.setParentAccountId(QString());  // make sure, there's no parent
      newAccount.clearId();                       // and no id set for adding
      newAccount.removeAccountIds();              // and no sub-account ids
      newAccount.setName(remainder);
    }//end while
    newAccount.setAccountType(parentAccount.accountType());

    // make sure we have a currency. If none is assigned, we assume base currency
    if (newAccount.currencyId().isEmpty())
      newAccount.setCurrencyId(file->baseCurrency().id());

    file->addAccount(newAccount, parentAccount);
    id = newAccount.id();
  }
  return id;
}
Пример #30
0
int MyMoneyForecast::daysToMinimumBalance(const MyMoneyAccount& acc)
{
  QString minimumBalance = acc.value("minBalanceAbsolute");
  MyMoneyMoney minBalance = MyMoneyMoney(minimumBalance);
  dailyBalances balance;

  //Check if acc is not a forecast account, return -1
  if(!isForecastAccount(acc)) {
    return -1;
  }

  balance = m_accountList[acc.id()];

  for(QDate it_day = QDate::currentDate() ; it_day <= forecastEndDate(); ) {
    if(minBalance > balance[it_day]) {
      return QDate::currentDate().daysTo(it_day);
    }
    it_day = it_day.addDays(1);
  }
  return -1;
}