Exemplo n.º 1
0
bool Budget::addToSpent(QUrl filePath, QString category, QString month, int amount)
{
    std::string monthSpent;
    std::string prepQuery;
    QDate currentMonth = QDate::currentDate();

    if (month == currentMonth.toString("yyyy-MM")) {
        monthSpent = "monthOneSpent";
    } else if (month == currentMonth.addMonths(-2).toString("yyyy-MM")) {
        monthSpent = "prevTwoSpent";
    } else if (month == currentMonth.addMonths(-1).toString("yyyy-MM")) {
        monthSpent = "prevOneSpent";
    } else if (month == currentMonth.addMonths(1).toString("yyyy-MM")) {
        monthSpent = "monthTwoSpent";
    } else if (month == currentMonth.addMonths(2).toString("yyyy-MM")) {
        monthSpent = "monthThreeSpent";
    } else {
        return false;
    }

    prepQuery = "UPDATE budgets SET " + monthSpent + " = " + monthSpent + " + ? WHERE categoryName == ?";

    io::sqlite::db mbgt(filePath.toLocalFile().toStdString());
    io::sqlite::stmt query(mbgt, prepQuery.c_str());

    query.bind().int32(1, amount);
    query.bind().text(2, category.toStdString());
    query.exec();

    return true;
}
Exemplo n.º 2
0
Time getTime(const QDate& date)
{
    if (date == QDate()) {
        return Time::Never;
    }

    QDate today = QDate::currentDate();
    // clang-format off
    const QMap<Time, QDate> dates {
        { Time::Today,     today.addDays(0)    },
        { Time::Yesterday, today.addDays(-1)   },
        { Time::ThisWeek,  today.addDays(-6)   },
        { Time::ThisMonth, today.addMonths(-1) },
        { Time::Month1Ago, today.addMonths(-2) },
        { Time::Month2Ago, today.addMonths(-3) },
        { Time::Month3Ago, today.addMonths(-4) },
        { Time::Month4Ago, today.addMonths(-5) },
        { Time::Month5Ago, today.addMonths(-6) },
    };
    // clang-format on

    for (Time time : dates.keys()) {
        if (dates[time] <= date) {
            return time;
        }
    }

    return Time::LongAgo;
}
Exemplo n.º 3
0
QList<int> tradeDateCalendar::computeFrequencyTradeMonthly(int date_, int minimumDate_, int maximumDate_)
{
    QList<int> tradeDates;

    QDate monthDayCounter = QDate::fromJulianDay(minimumDate_);
    int dayOfMonth = QDate::fromJulianDay(date_).day();

    forever
    {
        QDate monthDayComputation = monthDayCounter;
        if (monthDayComputation.day() > dayOfMonth)
            monthDayComputation = monthDayComputation.addMonths(1);

        if (dayOfMonth > monthDayComputation.daysInMonth())
        {
            monthDayComputation = monthDayComputation.addMonths(1);
            monthDayComputation = QDate(monthDayComputation.year(), monthDayComputation.month(), 1);
        }
        else
            monthDayComputation = QDate(monthDayComputation.year(), monthDayComputation.month(), dayOfMonth);

        date_ = checkTradeDate(monthDayComputation.toJulianDay(), direction_ascending);
        if (date_ > maximumDate_)
            break;

        tradeDates.append(date_);
        monthDayCounter = monthDayCounter.addMonths(1);
    }

    return tradeDates;
}
Exemplo n.º 4
0
Time getTime(const QDate& date)
{
    if (date == QDate())
        return Never;

    QDate today = QDate::currentDate();

    if (date == today)
        return Today;

    today = today.addDays(-1);

    if (date == today)
        return Yesterday;

    today = today.addDays(-6);

    if (date >= today)
        return ThisWeek;

    today = today.addDays(-today.day() + 1); // Go to the beginning of the month.

    if (last7DaysWasLastMonth())
    {
        if (date >= today)
            return ThisMonth;

        today = today.addMonths(-1);
    }

    if (date >= today)
        return Month1Ago;

    today = today.addMonths(-1);

    if (date >= today)
        return Month2Ago;

    today = today.addMonths(-1);

    if (date >= today)
        return Month3Ago;

    today = today.addMonths(-1);

    if (date >= today)
        return Month4Ago;

    today = today.addMonths(-1);

    if (date >= today)
        return Month5Ago;

    return LongAgo;
}
Exemplo n.º 5
0
NewCalendar::NewCalendar(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewCalendar)
{
    ui->setupUi(this);
    QDate start = QDate::currentDate();
    start = start.addMonths(1);   // next month!
    QDate end = start.addMonths(12);
    ui->monthFromWidget->setDate(start);
    ui->monthToWidget->setDate(end);
}
Exemplo n.º 6
0
// reimplemented from GraphicsButtonReceiver
void CalendarGraphicsItem::buttonMouseReleaseEvent(QGraphicsItem * origin, QGraphicsSceneMouseEvent * /*event*/)
{
  QDate date = _selectedDay;
  if(origin == _items["fastforward"])
    date = date.addYears(1);
  else if(origin == _items["forward"])
    date = date.addMonths(1);
  else if(origin == _items["rewind"])
    date = date.addMonths(-1);
  else if(origin == _items["fastrewind"])
    date = date.addYears(-1);
  setSelectedDay(date);
}
Exemplo n.º 7
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //initialize date pickers to current time
    QDate TimeNow = QDate::currentDate();
    ui->dt_StartDate->setDate( TimeNow );

    //initialize date pickers to next month
    QDate NextMonth = QDate::currentDate();
    NextMonth = NextMonth.addMonths(1);
    ui->dt_EndDate->setDate( NextMonth );

    //populate dropdown lists
    RefreshProductFeatureDropdownContent(0);

    //link events to functions
    connect(ui->b_BrowseClientSeed, SIGNAL(clicked()), this, SLOT(BrowseForSeedFile()));
    connect(ui->CB_ProductIdPicker, SIGNAL(currentIndexChanged(int)), this, SLOT(OnProductDropdownSelected(int)));
    connect(ui->b_AddToLicense, SIGNAL(clicked()), this, SLOT(ProductFeatureAddToLicense()));
    connect(ui->b_RemoveSelectedFromLicense, SIGNAL(clicked()), this, SLOT(OnRemoveSelectedLicenseClicked()));
    connect(ui->b_GenerateLicense, SIGNAL(clicked()), this, SLOT(OnGenerateLicenseClicked()));

    //init table header for license content
    ui->table_LicenseContent->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
    ui->table_LicenseContent->setSelectionBehavior(QAbstractItemView::SelectRows);
//    ui->table_LicenseContent->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->table_LicenseContent->setColumnCount(2);
    QTableWidgetItem *item1=new QTableWidgetItem ("Product");
    QTableWidgetItem *item2=new QTableWidgetItem ("Feature");
    ui->table_LicenseContent->setHorizontalHeaderItem(0,item1);
    ui->table_LicenseContent->setHorizontalHeaderItem(1,item2);
}
Exemplo n.º 8
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void SIMPLView_UI::checkForUpdatesAtStartup()
{
  SIMPLViewUpdateCheckDialog* d = new SIMPLViewUpdateCheckDialog(this);
  if ( d->getAutomaticallyBtn()->isChecked() )
  {
    SIMPLViewSettings updatePrefs;

    updatePrefs.beginGroup( SIMPLViewUpdateCheckDialog::getUpdatePreferencesGroup() );
    QDate lastUpdateCheckDate = updatePrefs.value(SIMPLViewUpdateCheckDialog::getUpdateCheckKey(), QString("")).toDate();
    updatePrefs.endGroup();

    QDate systemDate;
    QDate currentDateToday = systemDate.currentDate();

    QDate dailyThreshold = lastUpdateCheckDate.addDays(1);
    QDate weeklyThreshold = lastUpdateCheckDate.addDays(7);
    QDate monthlyThreshold = lastUpdateCheckDate.addMonths(1);

    if ( (d->getHowOftenComboBox()->currentIndex() == SIMPLViewUpdateCheckDialog::UpdateCheckDaily && currentDateToday >= dailyThreshold)
         || (d->getHowOftenComboBox()->currentIndex() == SIMPLViewUpdateCheckDialog::UpdateCheckWeekly && currentDateToday >= weeklyThreshold)
         || (d->getHowOftenComboBox()->currentIndex() == SIMPLViewUpdateCheckDialog::UpdateCheckMonthly && currentDateToday >= monthlyThreshold) )
    {
      m_UpdateCheck = QSharedPointer<UpdateCheck>(new UpdateCheck(this));

      connect(m_UpdateCheck.data(), SIGNAL( latestVersion(UpdateCheckData*) ),
              this, SLOT( versionCheckReply(UpdateCheckData*) ) );

      m_UpdateCheck->checkVersion(SIMPLView::UpdateWebsite::UpdateWebSite);
    }
Exemplo n.º 9
0
// --------------------------------------------------------------------------
void ctkDateRangeWidget::setLastMonth()
{
  Q_D(ctkDateRangeWidget);
  d->ForceSelectRange = false;
  QDate today = QDate::currentDate();
  this->setDateRange(today.addMonths(-1), today);
}
void KMyMoneyAccountTreeForecastItem::updateBudget()
{
  MyMoneySecurity currency;
  MyMoneyMoney tAmountMM;

  MyMoneyFile* file = MyMoneyFile::instance();
  int it_c = 1; // iterator for the columns of the listview
  QDate forecastDate = m_forecast.forecastStartDate();

  if(m_account.isInvest()) {
    MyMoneySecurity underSecurity = file->security(m_account.currencyId());
    currency = file->security(underSecurity.tradingCurrency());
  } else {
    currency = file->security(m_account.currencyId());
  }

    //iterate columns
  for(; forecastDate <= m_forecast.forecastEndDate(); forecastDate = forecastDate.addMonths(1), ++it_c) {
    MyMoneyMoney amountMM;
    amountMM = m_forecast.forecastBalance(m_account,forecastDate);
    if(m_account.accountType() == MyMoneyAccount::Expense)
      amountMM = -amountMM;

    tAmountMM += amountMM;
    setAmount(it_c, amountMM);
    setValue(it_c, amountMM, forecastDate);
    showAmount(it_c, amountMM, currency);
  }

  //set total column
  setAmount(it_c, tAmountMM);
  setValue(it_c, tAmountMM, m_forecast.forecastEndDate());
  showAmount(it_c, tAmountMM, currency);
}
Exemplo n.º 11
0
PaymentView::PaymentView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PaymentView)
{
    ui->setupUi(this);

    setWindowTitle(QString::fromUtf8("Платежи"));

    ui->table->setContextMenuPolicy(Qt::CustomContextMenu);
    EntityTable::setup(ui->table);
    ui->table->setSelectionMode(QAbstractItemView::SingleSelection);
    setStyleSheet("QTableView::item {margin-right: 20; margin-left: 20;}");

    model = new PaymentModel(this);
    ui->table->setModel(model);

    QDate current = QDate::currentDate();
    ui->dateTill->blockSignals(true);
    ui->dateTill->setDate(current);
    ui->dateFrom->setDate(current.addMonths(-1));
    ui->dateTill->blockSignals(false);


    accountModel = ModelManager::getInstance()->getAccountModel();
    connect(accountModel, SIGNAL(modelReset()), this, SLOT(cacheChanged()));
    cacheChanged();

    appendMenu();

}
Exemplo n.º 12
0
void Overview::on_rangeCombo_activated(int index)
{
    p_profile->general->setLastOverviewRange(index);
    ui->dateStart->setMinimumDate(p_profile->FirstDay());
    ui->dateEnd->setMaximumDate(p_profile->LastDay());

    QDate end = p_profile->LastDay();
    QDate start;

    if (index == 8) { // Custom
        ui->dateStartLabel->setEnabled(true);
        ui->dateEndLabel->setEnabled(true);
        ui->dateEnd->setEnabled(true);
        ui->dateStart->setEnabled(true);

        ui->dateStart->setMaximumDate(ui->dateEnd->date());
        ui->dateEnd->setMinimumDate(ui->dateStart->date());
        return;
    }

    ui->dateEnd->setEnabled(false);
    ui->dateStart->setEnabled(false);
    ui->dateStartLabel->setEnabled(false);
    ui->dateEndLabel->setEnabled(false);

    if (index == 0) {
        start = end.addDays(-6);
    } else if (index == 1) {
        start = end.addDays(-13);
    } else if (index == 2) {
        start = end.addMonths(-1).addDays(1);
    } else if (index == 3) {
        start = end.addMonths(-2).addDays(1);
    } else if (index == 4) {
        start = end.addMonths(-3).addDays(1);
    } else if (index == 5) {
        start = end.addMonths(-6).addDays(1);
    } else if (index == 6) {
        start = end.addYears(-1).addDays(1);
    } else if (index == 7) { // Everything
        start = p_profile->FirstDay();
    }

    if (start < p_profile->FirstDay()) { start = p_profile->FirstDay(); }

    setRange(start, end);
}
Exemplo n.º 13
0
// taking a QDate, this function will look for an eventlist in the dict
// with that date attached -
Event::List ResourceExchange::rawEventsForDate(const QDate &qd,
        EventSortField sortField,
        SortDirection sortDirection)
{
    if(!mCache) return Event::List();
    // If the events for this date are not in the cache, or if they are old,
    // get them again
    QDateTime now = QDateTime::currentDateTime();
    // kdDebug() << "Now is " << now.toString() << endl;
    // kdDebug() << "mDates: " << mDates << endl;
    QDate start = QDate(qd.year(), qd.month(), 1);   // First day of month
    if(mDates && (!mDates->contains(start) ||
                  (*mCacheDates)[start].secsTo(now) > mCachedSeconds))
    {
        QDate end = start.addMonths(1).addDays(-1);     // Last day of month
        // Get events that occur in this period from the cache
        Event::List oldEvents = mCache->rawEvents(start, end, false);
        // And remove them all
        Event::List::ConstIterator it;
        for(it = oldEvents.begin(); it != oldEvents.end(); ++it)
        {
            mCache->deleteEvent(*it);
        }

        // FIXME: This is needed for the hack below:
        Event::List eventsBefore = mCache->rawEvents();

        kdDebug() << "Reading events for month of " << start.toString() << endl;
        mClient->downloadSynchronous(mCache, start, end, true);   // Show progress dialog

        // FIXME: This is a terrible hack! We need to install the observer for
        // newly downloaded events.However, downloading is done by
        // mClient->downloadSynchronous, where we don't have the pointer to this
        // available... On the other hand, here we don't really know which events
        // are really new.
        Event::List eventsAfter = mCache->rawEvents();
        for(it = eventsAfter.begin(); it != eventsAfter.end(); ++it)
        {
            if(eventsBefore.find(*it) == eventsBefore.end())
            {
                // it's a new event downloaded by downloadSynchronous -> install observer
                (*it)->registerObserver(this);
            }
        }

        mDates->add(start);
        mCacheDates->insert(start, now);
    }

    // Events are safely in the cache now, return them from cache
    Event::List events;
    if(mCache)
        events = mCache->rawEventsForDate(qd, sortField, sortDirection);
    // kdDebug() << "Found " << events.count() << " events." << endl;
    return events;
}
Exemplo n.º 14
0
/*!
 * \brief DAgregarGarantia::actualizarFechaFinGarantia
 * \param fecha
 */
void DAgregarGarantia::actualizarFechaFinGarantia( QDate fecha ) {
    preferencias *p = preferencias::getInstancia();
    p->inicio();
    p->beginGroup( "Preferencias" );
    p->beginGroup( "Garantias" );
    DEFin->setDate( fecha.addMonths( p->value( "duracion_garantia", 6 ).toInt() ) );
    p->endGroup();
    p->endGroup();
    p=0;
}
Exemplo n.º 15
0
void ContentStructuredDocument::parseDate(const string& dateStr,
                                  QDate& dateBegin,
                                  QDate& dateEnd)
{
  dateBegin=QDate();
  dateEnd=QDate();

  char sep('/');

  //uint64_t firstSep,secondSep; portage 32 64
  std::string::size_type firstSep,secondSep;
  try {
    if ( (firstSep=dateStr.find(sep)) != string::npos ) {
      if ( (secondSep=dateStr.find(sep,firstSep+1)) != string::npos ) {
        // suppose day/month/year

        // from_uk_string only defined in recent versions of boost
//         dateBegin=boost::gregorian::from_uk_string(dateStr);
//         dateEnd=boost::gregorian::from_uk_string(dateStr);
        // current version knows only year/month/day

        string day(dateStr,0,firstSep);
        string month(dateStr,firstSep+1,secondSep-firstSep);
        string year(dateStr,secondSep+1);
        string newDateStr=year+'/'+month+'/'+day;
        dateBegin=QDate::fromString(newDateStr.c_str());
        dateEnd=QDate::fromString(newDateStr.c_str());
      }
      else { 
        // one separator : suppose month/year
        // find end of month
        string month(dateStr,0,firstSep);
        string year(dateStr,firstSep+1);
        unsigned short monthNum=atoi(month.c_str());
        unsigned short yearNum=atoi(year.c_str());
        dateBegin=QDate(yearNum,monthNum,1);
        dateEnd=dateBegin.addMonths(1).addDays(-1);
      }
    }
    else if (! dateStr.empty()) {
      // no separator : suppose year
      unsigned short yearNum=atoi(dateStr.c_str());
      dateBegin=QDate(yearNum,01,01);
      dateEnd=QDate(yearNum,12,31);
    }
  }
  //catch (boost::bad_lexical_cast& e) { 
  catch (std::exception& e) { 
    DRLOGINIT;
    LWARN << "Warning: " << e.what();
    LWARN << "Failed parsing of date [" << dateStr << "]";
    // do nothing, keep not_a_date_time as default value
  }
}
static QDate date_by_amount_and_unit( int inAmount, int inUnit ) {
    const QDate current = QDate::currentDate();
    switch ( inUnit ) {
    case Days:   return current.addDays(   inAmount ); break;
    case Weeks:  return current.addDays( 7*inAmount ); break;
    case Months: return current.addMonths( inAmount ); break;
    case Years:  return current.addYears(  inAmount ); break;
    default:
        assert( !"Should not reach here" );
    }
    return QDate();
}
Exemplo n.º 17
0
void VideoFilterSettings::setTextFilter(QString val)
{
    m_changed_state |= kFilterTextFilterChanged;
    if (re_season.indexIn(val) != -1)
    {
        bool res;
        QStringList list = re_season.capturedTexts();
        season = list[1].toInt(&res);
        if (!res)
            season = -1;
        if (list.size() > 2) {
            episode = list[2].toInt(&res);
            if (!res)
                episode = -1;
        }
        else {
            episode = -1;
        }
        //clear \dX\d from string for string-search in plot/title/subtitle
        textfilter = val;
        textfilter.replace(re_season, "");
        textfilter = textfilter.simplified ();
    }
    else
    {
        textfilter = val;
        season = -1;
        episode = -1;
    }
    if (re_date.indexIn(textfilter) != -1)
    {
        QStringList list = re_date.capturedTexts();
        int modnr = list[1].toInt();
        QDate testdate = QDate::currentDate();
        switch(list[2].at(0).toAscii())
        {
            case 'm': testdate = testdate.addMonths(-modnr);break;
            case 'd': testdate = testdate.addDays(-modnr);break;
            case 'w': testdate = testdate.addDays(-modnr * 7);break;
        }
        insertdate = testdate;
        textfilter.replace(re_date, "");
        textfilter = textfilter.simplified ();
    }
    else
    {
        //reset testdate
        insertdate = QDate();
    }
}
Exemplo n.º 18
0
/*! Paints the month scale header.
 * \sa paintHeader()
 */
void DateTimeGrid::paintMonthScaleHeader( QPainter* painter,  const QRectF& headerRect, const QRectF& exposedRect,
                                        qreal offset, QWidget* widget )
{
    QStyle* style = widget?widget->style():QApplication::style();

    // Paint a section for each month
    QDateTime sdt = d->chartXtoDateTime( offset+exposedRect.left() );
    sdt.setTime( QTime( 0, 0, 0, 0 ) );
    sdt = sdt.addDays( 1 - sdt.date().day() );
    QDateTime dt = sdt;
    for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
            dt = dt.addMonths( 1 ),x=d->dateTimeToChartX( dt ) ) {
        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()*dt.date().daysInMonth(), headerRect.height()/2. ).toRect();
        opt.text = QDate::shortMonthName( dt.date().month() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }
    }

    // Paint a section for each year
    dt = sdt;
    for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset; x2=d->dateTimeToChartX( dt ) ) {
        //qDebug()<<"paintMonthScaleHeader()"<<dt;
        QDate next = dt.date().addYears( 1 );
        next = next.addMonths( 1 - next.month() );

        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*dt.date().daysTo( next ), headerRect.height()/2. ).toRect();
        opt.text = QString::number( dt.date().year() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }

        dt.setDate( next );
    }
}
Exemplo n.º 19
0
void AccountingForm::accountEverything()
{
	disableButtons();

	m_progLabel->show();
	QDate firstUnaccMonth = getFirstUnaccMonth();
	if (!firstUnaccMonth.isValid())
	{
		m_progLabel->setText("Keine offenen Abrechnungsposten!");
		return;
	}

	m_progBar->show();

	m_progBar->setMaximum(m_patients->rowCount());

	//get all Patients...
	for (int i = 0; i < m_patients->rowCount(); i++)
	{
		QSqlRecord curPat = m_patients->record(i);
		QString patName = curPat.value(FirstName).toString();
		patName.append(" ");
		patName.append(curPat.value(LastName).toString());
		m_progLabel->setText(patName);
		//std::cerr << "Accounting Patient: " << patName.toStdString() << std::endl;
		m_progBar->setValue(i + 1);

		//Iterate over all open accounting dates for this patient
		QDate curDate = QDate::currentDate();
		//int yearDiff = curDate.year() - firstUnaccMonth.year();
		//int monthDiff = curDate.month() - firstUnaccMonth.month();
		//std::cerr << "First unacc: " << firstUnaccMonth.toString().toStdString() << std::endl;
		//std::cerr << "Cur: " << curDate.toString().toStdString() << std::endl;
		QDate tempDate = firstUnaccMonth;
		while (tempDate < curDate)
		{
			//std::cerr << "Accounting: " << tempDate.toString().toStdString() << std::endl;
			accountPatient(i, tempDate);
			tempDate = tempDate.addMonths(1);
		}

		//Update the view of the form
		update();
	}
	//std::cerr << "Accounting everything finished" << std::endl;
}
Exemplo n.º 20
0
void MainWindow::newCalendar()
{
    NewCalendar nc(this);
    int result = nc.exec();
    if (result == QDialog::Rejected)
        return;

    // set up the months in the main widget and the internal MonthClass list
    ui->monthList->clear();
    months.clear();
    startMonth = nc.startMonth;
    endMonth = nc.endMonth;
    for (QDate iter = startMonth; iter <= endMonth; iter = iter.addMonths(1)) {
        MonthClass mc(iter);
        ui->monthList->addItem(mc.text());
        months.append(mc);
    }
}
Exemplo n.º 21
0
QJsonArray Budget::getCategories(QUrl filePath, int month)
{
    QJsonArray categoryArray;
    std::string prepQuery;
    QDate selectedMonth = QDate::currentDate();
    std::string monthIndex = monthFromIndex(month);

    if (month < 3 && month > -3) {
        selectedMonth = selectedMonth.addMonths(month);
    } else {
        QJsonObject err;
        err.insert("err", "Out of stored range");
        categoryArray.append(err);
        return categoryArray;
    }

    prepQuery = "SELECT categoryName," +
               monthIndex + ", " + monthIndex + "Spent " +
               " FROM budgets WHERE " + monthIndex + "Date == ? ORDER BY categoryName";

    io::sqlite::db mbgt(filePath.toLocalFile().toStdString());
    io::sqlite::stmt query(mbgt, prepQuery.c_str());

    query.bind().text(1, selectedMonth.toString("yyyy-MM").toStdString());

    while (query.step()) {
        QJsonObject category;
        QString categoryName = QString::fromStdString(query.row().text(0));
        int amount = query.row().int32(1);
        int spent = query.row().int32(2);

        QString formattedAmount = intToQs(amount);
        QString formattedRemainingAmount = intToQs(amount - spent);

        category.insert("categoryName", categoryName);
        category.insert("amount", formattedAmount);
        category.insert("remaining", formattedRemainingAmount);

        categoryArray.append(category);
    }

    return categoryArray;
}
Exemplo n.º 22
0
int
RecurrentTransaction::Recurrence::ocurrencesPassed() {
    // simply, do the reverse of the generateMissingDate, we go from last to start
    int count = 0;
    QDate lastCalculated;

    if(lastGenerated.isValid()) {
        lastCalculated = QDate(lastGenerated);
    } else {
        lastCalculated = startDate;
    }

    if(_defaults) {
        while (lastCalculated > startDate) {
            switch (*_defaults) {
                case Recurrence::Defaults::DAILY:
                    DLOG(INFO) << "Daily increased";
                    lastCalculated = lastCalculated.addDays(-1);
                    break;
                case Recurrence::Defaults::WEEKLY:
                    DLOG(INFO) << "Weekly increased";
                    lastCalculated = lastCalculated.addDays(-7);
                    break;
                default:
                    DLOG(INFO) << "Monthly increased";
                    lastCalculated = lastCalculated.addMonths(-1);
                    break;
            }
            if (lastCalculated >= startDate) {
                count++;
            }
        }
    } else {
        while(lastCalculated > startDate) {
            lastCalculated = lastCalculated.addDays(*_numberOfDays * -1);
            if (lastCalculated >= startDate) {
                count++;
            }
        }
    }
    return count;
}
Exemplo n.º 23
0
void AdvancedDistance::UpdateReportTime()
{
    QDate date = handler_->report_date();
    ReportType type = handler_->report_type();

    QDate begin_date;

    switch (type) {
    case Week_Report:
        begin_date = date.addDays(-7);
        break;
    case Month_Report:
        begin_date = date.addMonths(-1);
        break;
    default:
        break;
    }

    QString reportdatestr = STRING_ADVANCED_DISTANCE_REPORT_TIME + begin_date.toString("yyyy/MM/dd") + " 00:00--" +
            date.toString("yyyy/MM/dd") + " 00:00";
    report_time_->setText(reportdatestr);
}
Exemplo n.º 24
0
int MReportDataAdapter::GetExistDayNum(QDate &reference_time, ReportType type)
{
    if (reference_time.isValid())
    {
        return -1;
    }

    QDate begin;
    switch(type)
    {
    case Week_Report:
        begin = reference_time.addDays(-7);
        break;
    case Month_Report:
        begin = reference_time.addMonths(-1);
        break;
    default:
        return -1;
    }

    return GetExistDayNum(begin, reference_time);
}
Exemplo n.º 25
0
void KForecastView::updateBudget(QTreeWidgetItem *item)
{
  MyMoneySecurity currency;
  MyMoneyMoney tAmountMM;

  MyMoneyForecast forecast = item->data(0, ForecastRole).value<MyMoneyForecast>();

  MyMoneyFile* file = MyMoneyFile::instance();
  int it_c = 1; // iterator for the columns of the listview
  QDate forecastDate = forecast.forecastStartDate();

  MyMoneyAccount account = item->data(0, AccountRole).value<MyMoneyAccount>();

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

  //iterate columns
  for (; forecastDate <= forecast.forecastEndDate(); forecastDate = forecastDate.addMonths(1), ++it_c) {
    MyMoneyMoney amountMM;
    amountMM = forecast.forecastBalance(account, forecastDate);
    if (account.accountType() == MyMoneyAccount::Expense)
      amountMM = -amountMM;

    tAmountMM += amountMM;
    setAmount(item, it_c, amountMM);
    setValue(item, it_c, amountMM, forecastDate);
    showAmount(item, it_c, amountMM, currency);
  }

  //set total column
  setAmount(item, it_c, tAmountMM);
  setValue(item, it_c, tAmountMM, forecast.forecastEndDate());
  showAmount(item, it_c, tAmountMM, currency);
}
Exemplo n.º 26
0
QString CrCalendar::generateMonthTitle() {
    QString str;

    QDate daysIterator;
    QDate actualMonth = QDate(_dateFirst.year(),_dateFirst.month(),1);
    int daysCount = 0;

    if(_dateFirst.month() == _dateLast.month() && _dateFirst.year() == _dateLast.year()) {
        str += "<td colspan=\""+ QString::number(_dateFirst.daysTo(_dateLast.addDays(1)))+"\"";;
        str += " class=\""+ Cell::getCssClassAsString(Cell::month_title) +"\">";
        str += getMonthString(_dateFirst.month());
        str += " ";
        str += _dateFirst.toString("yyyy");
        str += "</td>\n";
    } else {
        for(daysIterator = _dateFirst; daysIterator.operator <=(_dateLast); daysIterator = daysIterator.addDays(1)) {

            if(daysIterator.operator ==(QDate(daysIterator.year(), daysIterator.month(),daysIterator.daysInMonth()))
                    || daysIterator.operator ==(_dateLast)) {

                str += "<td colspan=\""+ QString::number(++daysCount) +"\"";
                str += " class=\""+ Cell::getCssClassAsString(Cell::month_title) + "\">";
                str += getMonthString(actualMonth.month());
                str += " ";
                str += actualMonth.toString("yyyy");

                str += "</td>\n";

                daysCount = 0;
                actualMonth = actualMonth.addMonths(1);
            } else {
                daysCount++;
            }
        }
    }

    return str;
}
Exemplo n.º 27
0
void 
DateSettingsEdit::setDateSettings()
{
    if (active) return;

    // first lets disable everything
    active = true;
    fromDateEdit->setEnabled(false);
    toDateEdit->setEnabled(false);
    startDateEdit->setEnabled(false);
    thisperiod->setEnabled(false);
    prevperiod->setEnabled(false);
    lastn->setEnabled(false);
    lastnx->setEnabled(false);

    // the date selection types have changed
    if (radioSelected->isChecked()) {

        // current selection
        emit useStandardRange();

    } else if (radioCustom->isChecked()) {

        // between x and y
        fromDateEdit->setEnabled(true);
        toDateEdit->setEnabled(true);

        // set date range using custom values
        emit useCustomRange(DateRange(fromDateEdit->date(), toDateEdit->date()));

    } else if (radioToday->isChecked()) {

        // current selected thru to today
        emit useThruToday();

    } else if (radioLast->isChecked()) {

        // last n 'weeks etc'
        lastn->setEnabled(true);
        lastnx->setEnabled(true);

        QDate from;
        QDate today = QDate::currentDate();

        // calculate range up to today...
        switch(lastnx->currentIndex()) {
            case 0 : // days
                from = today.addDays(lastn->value() * -1);
                break;

            case 1 :  // weeks
                from = today.addDays(lastn->value() * -7);
                break;

            case 2 :  // months
                from = today.addMonths(lastn->value() * -1);
                break;

            case 3 : // years
                from = today.addYears(lastn->value() * -1);
                break;
        }

        emit useCustomRange(DateRange(from, today));

    } else if (radioFrom->isChecked()) {

        // from date - today
        startDateEdit->setEnabled(true);
        emit useCustomRange(DateRange(startDateEdit->date(), QDate::currentDate()));

    } else if (radioThis->isChecked()) {

        thisperiod->setEnabled(true);
        prevperiod->setEnabled(true);

        QDate today = QDate::currentDate();
        QDate from, to;

        switch(thisperiod->currentIndex()) {

        case 0 : // weeks
            {
                int dow = today.dayOfWeek(); // 1-7, where 1=monday
                from = today.addDays(-1 * (dow-1));
                to = from.addDays(6);
                // prevperiods
                from = from.addDays(prevperiod->value() * -7);
                to = to.addDays(prevperiod->value() * -7);
            }
            break;

        case 1 : // months
            from = QDate(today.year(), today.month(), 1);
            to = from.addMonths(1).addDays(-1);
            from = from.addMonths(prevperiod->value() * -1);
            to = to.addMonths(prevperiod->value() * -1);
            break;

        case 2 : // years
            from = QDate(today.year(), 1, 1);
            to = from.addYears(1).addDays(-1);
            from = from.addYears(prevperiod->value() * -1);
            to = to.addYears(prevperiod->value() * -1);
            break;

        }
        emit useCustomRange(DateRange(from, to));
    }
    active = false;
}
Exemplo n.º 28
0
QList<QDate>
RecurrentTransaction::Recurrence::generateMissingDates() {
    QList<QDate> result;

    // calculate which dates should be used since the last time we had a recurrence created
    auto today = QDate::currentDate();
    if (endDate.isValid() && endDate < today) {
        LOG(INFO) << "Found end date " << endDate.day() << "/" << endDate.month() << "/" << endDate.year();
        today = endDate;
    }

    if (startDate > today) {
        LOG(INFO) << "Returning empty list because the start date is smaller than the current date";
        return result;
    }

    if (lastGenerated.isValid() && lastGenerated == today) {
        LOG(INFO) << "Returning empty list because we are up to date with all the occurrences";
        return result;
    }

    QDate lastCalculated;
    if(lastGenerated.isValid()) {
        lastCalculated = QDate(lastGenerated);
    } else {
        lastCalculated = startDate;
    }

    if(_defaults) {
        while (lastCalculated < today) {
            switch (*_defaults) {
                case Recurrence::Defaults::DAILY:
                    DLOG(INFO) << "Daily increased";
                    lastCalculated = lastCalculated.addDays(1);
                    break;
                case Recurrence::Defaults::WEEKLY:
                    DLOG(INFO) << "Weekly increased";
                    lastCalculated = lastCalculated.addDays(7);
                    break;
                default:
                    DLOG(INFO) << "Monthly increased";
                    lastCalculated = lastCalculated.addMonths(1);
                    break;
            }
            if (lastCalculated <= today) {
                DLOG(INFO) << "New date appended " << lastCalculated.day() << "/" << lastCalculated.month()
                    << "/" << lastCalculated.year();
                result.append(lastCalculated);
            }
        }
    } else {
        while(lastCalculated < today) {
            lastCalculated = lastCalculated.addDays(*_numberOfDays);
            if (lastCalculated <= today) {
                result.append(lastCalculated);
            }
        }
    }

    if (occurrences) {
        auto left = *occurrences - ocurrencesPassed();
        LOG(INFO) << "We have " << left << " occurrences left";
        if (left > 0) {
            return result.mid(0, left);
        } else {
            return QList<QDate>();
        }
    }

    return result;
}
Exemplo n.º 29
0
QDate FLUtil::addMonths(const QDate &d, int nm)
{
  return d.addMonths(nm);
}
Exemplo n.º 30
0
//
// Manage the seasons array
//
void
Seasons::readSeasons()
{
    QFile seasonFile(home.absolutePath() + "/seasons.xml");
    QXmlInputSource source( &seasonFile );
    QXmlSimpleReader xmlReader;
    SeasonParser handler;
    xmlReader.setContentHandler(&handler);
    xmlReader.setErrorHandler(&handler);
    xmlReader.parse( source );
    seasons = handler.getSeasons();

    Season season;
    QDate today = QDate::currentDate();
    QDate eom = QDate(today.year(), today.month(), today.daysInMonth());

    // add Default Date Ranges
    season.setName(tr("All Dates"));
    season.setType(Season::temporary);
    season.setStart(QDate::currentDate().addYears(-50));
    season.setEnd(QDate::currentDate().addYears(50));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000001}"));
    seasons.append(season);

    season.setName(tr("This Year"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), 1,1));
    season.setEnd(QDate(today.year(), 12, 31));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000002}"));
    seasons.append(season);

    season.setName(tr("This Month"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), today.month(),1));
    season.setEnd(eom);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000003}"));
    seasons.append(season);

    season.setName(tr("This Week"));
    season.setType(Season::temporary);
    // from Mon-Sun
    QDate wstart = QDate::currentDate();
    wstart = wstart.addDays(Qt::Monday - wstart.dayOfWeek());
    QDate wend = wstart.addDays(6); // first day + 6 more
    season.setStart(wstart);
    season.setEnd(wend);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000004}"));
    seasons.append(season);

    season.setName(tr("Last 7 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-6)); // today plus previous 6
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000005}"));
    seasons.append(season);

    season.setName(tr("Last 14 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-13));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000006}"));
    seasons.append(season);

    season.setName(tr("Last 21 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-20));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000011}"));
    seasons.append(season);

    season.setName(tr("Last 28 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-27));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000007}"));
    seasons.append(season);

    season.setName(tr("Last 2 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-2));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000008}"));
    seasons.append(season);

    season.setName(tr("Last 3 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-3));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000011}"));
    seasons.append(season);

    season.setName(tr("Last 6 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-6));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000009}"));
    seasons.append(season);

    season.setName(tr("Last 12 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-12));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000010}"));
    seasons.append(season);

    seasonsChanged(); // signal!
}