Exemple #1
0
void DLineEdit::validateDate()
{
  QString dateString = _lineedit.text().stripWhiteSpace();
  bool    isNumeric;

#ifdef OpenMFGGUIClient_h
  QDate today = ofmgThis->dbDate();
#else
  QDate today = QDate::currentDate();
#endif

  _valid = false;

  if (dateString == _nullString || dateString.isEmpty())
    setNull();

  else if (dateString == "0")                           // today
    setDate(today, TRUE);

  else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today
  {
    int offset = dateString.toInt(&isNumeric);
    if (isNumeric)
      setDate(today.addDays(offset), true);
  }

  else if (dateString[0] == '#')                        // julian day
  {
    int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric);
    if (isNumeric)
      setDate(QDate(today.year(), 1, 1).addDays(offset - 1), TRUE);
  }

  else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month
  {
    int offset = dateString.toInt(&isNumeric, 10);
    if (isNumeric)
    {
      if (offset > today.daysInMonth())
        offset = today.daysInMonth();
 
      setDate(QDate(today.year(), today.month(), 1).addDays(offset - 1), TRUE);
    }
  }

  else                                                  // interpret with locale
  {
    // Qt bug 193079: setDate(QDate::fromString(dateString, Qt::LocaleDate), true);

    QDate tmp = QDate::fromString(dateString,
                                  QLocale().dateFormat(QLocale::ShortFormat));
    setDate(QDate(tmp.year(), tmp.month(), tmp.day()), true );
  }

  if (!_valid)
    _lineedit.setText("");

  _parsed = true;
}
Exemple #2
0
MonthView::MonthView(QWidget *parent, const QCategoryFilter& c, QSet<QPimSource> set)
    : QCalendarWidget(parent)
{
    setObjectName("monthview");

    setVerticalHeaderFormat(NoVerticalHeader);
    setFirstDayOfWeek( Qtopia::weekStartsOnMonday() ? Qt::Monday : Qt::Sunday );

    QDate start = QDate::currentDate();
    start.setYMD(start.year(), start.month(), 1);
    QDate end = start.addDays(start.daysInMonth() - 1);

    model = new QOccurrenceModel(QDateTime(start, QTime(0, 0, 0)), QDateTime(end.addDays(1), QTime(0, 0)), this);
    if (set.count() > 0)
        model->setVisibleSources(set);
    model->setCategoryFilter(c);

    connect(model, SIGNAL(modelReset()), this, SLOT(resetFormatsSoon()));
    connect(this, SIGNAL(currentPageChanged(int,int)), this, SLOT(updateModelRange(int,int)));

    // Since we don't know if we'll get a model reset from the model
    // at startup, force a timer
    dirtyTimer = new QTimer();
    dirtyTimer->setSingleShot(true);
    dirtyTimer->setInterval(0);
    connect(dirtyTimer, SIGNAL(timeout()), this, SLOT(resetFormats()));

    resetFormatsSoon();

    // XXX find the QCalendarView class so we can handle Key_Back properly :/
    // [this comes from qtopiaapplication.cpp]
    QWidget *table = findChild<QWidget*>("qt_calendar_calendarview");
    if (table)
        table->installEventFilter(this);
}
bool AccountingForm::accountPatient(const int patientRow, const QDate date)
{
	QSqlRecord patient = m_patients->record(patientRow);
	QString filter("patient_id = ");
	filter.append(patient.value(ID).toString());

	QDate curDate;
	curDate.setDate(date.year(), date.month(), 1);
	QDate futDate;
	futDate.setDate(date.year(), date.month(), date.daysInMonth());
	QString filterString;
	filterString.append(" AND ");
	filterString.append("dateoftreat BETWEEN '");
	filterString.append(curDate.toString("yyyy-MM-dd"));
	filterString.append("' and '");
	filterString.append(futDate.toString("yyyy-MM-dd"));
	filterString.append("'");

	filter.append(filterString);
	m_treats->setFilter(filter);
	m_treats->select();

	PatientAccounter accounter(patient, *m_treats);
	accounter.account(date);

	return true;
}
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;
}
Exemple #5
0
bool
KDateTable::setDate(const QDate& date_)
{
  bool changed=false;
  QDate temp;
  // -----
  if(!date_.isValid())
    {
      kdDebug() << "KDateTable::setDate: refusing to set invalid date." << endl;
      return false;
    }
  if(date!=date_)
    {
      date=date_;
      changed=true;
    }
  temp.setYMD(date.year(), date.month(), 1);
  firstday=temp.dayOfWeek();
  if(firstday==1) firstday=8;
  numdays=date.daysInMonth();
  if(date.month()==1)
    { // set to december of previous year
      temp.setYMD(date.year()-1, 12, 1);
    } else { // set to previous month
      temp.setYMD(date.year(), date.month()-1, 1);
    }
  numDaysPrevMonth=temp.daysInMonth();
  if(changed)
    {
      repaintContents(false);
    }
  emit(dateChanged(date));
  return true;
}
int CalendarBox::Context::rowsCountForMonth(QDate month) {
	Assert(!month.isNull());
	auto daysShift = daysShiftForMonth(month);
	auto daysCount = month.daysInMonth();
	auto cellsCount = daysShift + daysCount;
	auto result = (cellsCount / kDaysInWeek);
	if (cellsCount % kDaysInWeek) ++result;
	return result;
}
Exemple #7
0
// Function: EOMONTH
Value func_eomonth(valVector args, ValueCalc *calc, FuncExtra *)
{
    // add months to date using EDATE
    Value modDate = func_edate(args, calc, 0);
    if (modDate.isError()) return modDate;

    // modDate is currently in Date format
    QDate date = modDate.asDate(calc->settings());
    date.setYMD(date.year(), date.month(), date.daysInMonth());

    return Value(date, calc->settings());
}
Exemple #8
0
ReportPage::ReportPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ReportPage),
    mOppModel(Q_NULLPTR)
{
    ui->setupUi(this);

    // beginning of this month
    const QDate today = QDate::currentDate();
    ui->from->setDate(QDate(today.year(), today.month(), 1));
    // end of this month
    ui->to->setDate(QDate(today.year(), today.month(), today.daysInMonth()));
}
void CalendarBox::Context::applyMonth(const QDate &month, bool forced) {
	_daysCount = month.daysInMonth();
	_daysShift = daysShiftForMonth(month);
	_rowsCount = rowsCountForMonth(month);
	auto yearIndex = month.year();
	auto monthIndex = month.month();
	_highlightedIndex = month.daysTo(_highlighted);
	_minDayIndex = _min.isNull() ? INT_MIN : month.daysTo(_min);
	_maxDayIndex = _max.isNull() ? INT_MAX : month.daysTo(_max);
	if (forced) {
		_month.setForced(month, true);
	} else {
		_month.set(month, true);
	}
}
Exemple #10
0
	void Storage::getDaysForSheet (const QString& account, const QString& entry, int year, int month)
	{
		if (!Accounts_.contains (account))
		{
			qWarning () << Q_FUNC_INFO
					<< "Accounts_ doesn't contain"
					<< account
					<< "; raw contents"
					<< Accounts_;
			return;
		}
		if (!Users_.contains (entry))
		{
			qWarning () << Q_FUNC_INFO
					<< "Users_ doesn't contain"
					<< entry
					<< "; raw contents"
					<< Users_;
			return;
		}

		const QDate lowerDate (year, month, 1);
		const QDateTime lowerBound (lowerDate, QTime (0, 0, 0));
		const QDateTime upperBound (QDate (year, month, lowerDate.daysInMonth ()), QTime (23, 59, 59));

		GetMonthDates_.bindValue (":entry_id", Users_ [entry]);
		GetMonthDates_.bindValue (":account_id", Accounts_ [account]);
		GetMonthDates_.bindValue (":lower_date", lowerBound);
		GetMonthDates_.bindValue (":upper_date", upperBound);

		if (!GetMonthDates_.exec ())
		{
			Util::DBLock::DumpError (GetMonthDates_);
			return;
		}

		QList<int> result;
		while (GetMonthDates_.next ())
		{
			const auto date = GetMonthDates_.value (0).toDate ();
			const int day = date.day ();
			if (!result.contains (day))
				result << day;
		}
		std::sort (result.begin (), result.end ());
		emit gotDaysForSheet (account, entry, year, month, result);
	}
Exemple #11
0
void MainWindow::insertCalendar()
{
//! [1]
    QTextCursor cursor(editor->textCursor());
    cursor.movePosition(QTextCursor::Start); 

    QTextCharFormat format(cursor.charFormat());
    format.setFontFamily("Courier");
    
    QTextCharFormat boldFormat = format;
    boldFormat.setFontWeight(QFont::Bold);

    cursor.insertBlock();
    cursor.insertText(" ", boldFormat);

    QDate date = QDate::currentDate();
    int year = date.year(), month = date.month();

    for (int weekDay = 1; weekDay <= 7; ++weekDay) {
        cursor.insertText(QString("%1 ").arg(QDate::shortDayName(weekDay), 3),
            boldFormat);
    }

    cursor.insertBlock();
    cursor.insertText(" ", format);

    for (int column = 1; column < QDate(year, month, 1).dayOfWeek(); ++column) {
        cursor.insertText("    ", format);
    }

    for (int day = 1; day <= date.daysInMonth(); ++day) {
//! [1] //! [2]
        int weekDay = QDate(year, month, day).dayOfWeek();

        if (QDate(year, month, day) == date)
            cursor.insertText(QString("%1 ").arg(day, 3), boldFormat);
        else
            cursor.insertText(QString("%1 ").arg(day, 3), format);

        if (weekDay == 7) {
            cursor.insertBlock();
            cursor.insertText(" ", format);
        }
//! [2] //! [3]
    }
//! [3]
}
Exemple #12
0
QVector<Event> EventPool::eventsByYearMonth( const int inYear, const int inMonth ) const
{
    QVector<Event> events = m_eventMap.value( inYear );
    if( events.isEmpty() )
        return events;
    QVector<Event> events_month;

    QDate firstOfMonth = QDate( inYear, inMonth, 1 );
    QDate lastOfMonth = QDate( inYear, inMonth, firstOfMonth.daysInMonth() );

    for( const Event e : events )
    {
        if( e.m_endDt.date() >= firstOfMonth and e.m_startDt.date() <= lastOfMonth )
            events_month.append( e );
    }
    return events_month;
}
Exemple #13
0
         //Method to create calendar with an option to or not to fill data in it.
        void MonthView::CreateCalendar(bool toFillData)
         {

                 //Get weekday of 1st of selected Date
                 int day1 = QDate(StartDate.year(),StartDate.month(),1).dayOfWeek();   //SelectedDate.dayOfWeek();

                 QDate dtStart,dtEnd;

                 if(day1 == 1)//If month starts on day 1 of the week.
                 {
                         dtStart.setDate(StartDate.year(),StartDate.month(),1);

                         QDate nextMonth = StartDate.addMonths(1);

                         int endMonthDays = (42) - (StartDate.daysInMonth());

                         dtEnd.setDate(nextMonth.year(),nextMonth.month(), endMonthDays);
                 }
                 else
                 {
                         QDate prevMonth = StartDate.addMonths(-1);
                         int prevMonthDays = prevMonth.daysInMonth();

                         dtStart.setDate(prevMonth.year(),prevMonth.month(), prevMonthDays - day1 + 2 );


                         QDate nextMonth = StartDate.addMonths(1);
                         int endMonthDays = (42) - (day1 + StartDate.daysInMonth()) + 1;

                         dtEnd.setDate(nextMonth.year(),nextMonth.month(),endMonthDays);
                 }

                 ui->labelHeader->setText(QDate::shortMonthName(StartDate.month()) + ", " + QString::number(StartDate.year()));

                 SetDatesInCalendar(dtStart, dtEnd, toFillData);


         }
Exemple #14
0
void Calender::setupView(int y, int m)
{
    CalenderDay *cDay = NULL;
    QColor white(255, 255, 255);
    QColor gray(240, 240, 240);
    QString dayNrStr;
    QDate *date = new QDate(y, m, 1);

    int i, j, k, squareNr, dayNr, row, col;

    char *days[] = {
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday"
    };

    i = 0;
    k = 0;
    j = 7;
    squareNr = 1;
    dayNr = 1;
    nrOfDays = date->daysInMonth();
    firstDay = date->dayOfWeek();
    year = y;
    month = m;
    
    if (weekStarts == SUNDAY) {
      horizontalHeader()->setLabel(0, tr(days[6]));
      firstDay += 1;
      i = 1;
    }

    for (; i < j; i++, k++) {
      horizontalHeader()->setLabel(i, tr(days[k]));
    }
 
    for (row = 0; row < numRows(); row++) {
      for (col = 0; col < numCols(); col++) {
 if ((squareNr >= firstDay) && (dayNr <= nrOfDays)) {
   if ((dayLeadingZero == true) && (dayNr <= 9)) {
     dayNrStr += "0";
   }
   dayNrStr += QString::number(dayNr);
   cDay = new CalenderDay(this, QTableItem::Never, white, dayNrStr);
   dayNrStr = "";
   cDay->setDayNr(dayNr++);
   
   setItem(row, col, cDay);
 } else {
   cDay = new CalenderDay(this, QTableItem::Never, gray);
   setItem(row, col, cDay);
 }
 //setRowHeight(row, 80);    //Inte nödv. då col och rows är stretchatble
 ++squareNr;
      }
    }
}
Exemple #15
0
void XDateEdit::parseDate()
{
  QString dateString = text().trimmed();
  bool    isNumeric;

  if (DEBUG)
    qDebug("%s::parseDate() with dateString %s, _currentDate %s, _allowNull %d",
           qPrintable(parent() ? parent()->objectName() : objectName()),
           qPrintable(dateString),
           qPrintable(_currentDate.toString()), _allowNull);

#ifdef GUIClient_h
  QDate today = ofmgThis->dbDate();
#else
  QDate today = QDate::currentDate();
#endif

  if (_parsed)
  {
    if (DEBUG)
      qDebug("%s::parseDate() looks like we've already parsed this string",
             qPrintable(parent() ? parent()->objectName() : objectName()));
    return;
  }

  _valid = false;

  if (dateString == _nullString || dateString.isEmpty())
    setNull();

  else if (dateString == "0")                           // today
    setDate(today, TRUE);

  else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today
  {
    int offset = dateString.toInt(&isNumeric);
    if (isNumeric)
      setDate(today.addDays(offset), true);
  }

  else if (dateString[0] == '#')                        // julian day
  {
    int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric);
    if (isNumeric)
      setDate(QDate(today.year(), 1, 1).addDays(offset - 1), TRUE);
  }

  else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month
  {
    int offset = dateString.toInt(&isNumeric, 10);
    if (isNumeric)
    {
      if (offset > today.daysInMonth())
        offset = today.daysInMonth();
 
      setDate(QDate(today.year(), today.month(), 1).addDays(offset - 1), TRUE);
    }
  }

  else                                                  // interpret with locale
  {
    QString dateFormatStr = QLocale().dateFormat(QLocale::ShortFormat);
    if (DEBUG)
      qDebug("%s::parseDate() trying to parse with %s",
             qPrintable(parent() ? parent()->objectName() : objectName()),
             qPrintable(dateFormatStr));

    QDate tmp = QDate::fromString(dateString, dateFormatStr);
    bool twodigitformat = !(dateFormatStr.indexOf(QRegExp("y{4}")) >= 0);
    if (tmp.isValid())
    {
      if (twodigitformat && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so
      {
        qDebug("%s::parseDate() found valid 2-digit year %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
        tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit
        qDebug("%s::parseDate() altered year to %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
      }
    }
    else if (twodigitformat)
    {
      // try 4 digits, ignoring the possibility of '-literals in the format str
      dateFormatStr.replace(QRegExp("y{2}"), "yyyy");
      if (DEBUG)
        qDebug("%s::parseDate() rewriting 2-digit year format string to %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(dateFormatStr));
      tmp = QDate::fromString(dateString, dateFormatStr);

      if (tmp.isValid())
      {
        if (tmp.year() < 10)
          tmp = tmp.addYears(today.year() - today.year() % 100);
        if (DEBUG)
          qDebug("%s::parseDate() after changing to 4-digit year, year = %d",
                 qPrintable(parent() ? parent()->objectName() : objectName()),
                 tmp.year());
      }
      else if (DEBUG)
        qDebug("%s::parseDate() after changing to 4-digit year, date still isn't valid",
               qPrintable(parent() ? parent()->objectName() : objectName()));

    }
    else
    {
      // try 2 digits, ignoring the possibility of '-literals in the format str
      dateFormatStr.replace(QRegExp("y{4}"), "yy");
      if (DEBUG)
        qDebug("%s::parseDate() rewriting 4-digit year format string to %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(dateFormatStr));
      tmp = QDate::fromString(dateString, dateFormatStr);
      if (tmp.isValid() && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so
      {
        qDebug("%s::parseDate() found valid 2-digit year %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
        tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit
        qDebug("%s::parseDate() altered year to %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
      }
    }
    if(!tmp.isValid())
    {
      // still no match -- we will decompose the format and input and
      // build a date based on that information
      QRegExp rx("(\\d+)");
      QRegExp rx2("(m+|y+|d+)");
      rx2.setCaseSensitivity(Qt::CaseInsensitive);
      QStringList numberList;
      QStringList formatList;
      int pos = 0;
      while ((pos = rx.indexIn(dateString, pos)) != -1)
      {
        numberList << rx.cap(1);
        pos += rx.matchedLength();
      }
      pos = 0;
      while((pos = rx2.indexIn(dateFormatStr, pos)) != -1)
      {
        formatList << rx2.cap(1);
        pos += rx2.matchedLength();
      }

      if (DEBUG)
        qDebug("%s::parseDate() aligning numberList %s with formatList %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(numberList.join(":")), qPrintable(formatList.join(":")));

      // if we don't have exactly 3 and the numberList is not 2 or 3 then don't bother
      if(formatList.size() == 3 && (numberList.size() == 2 || numberList.size() == 3))
      {
        int year = today.year();
        int day = -1;
        int month = -1;

        pos = 0;
        for (int i = 0; i < formatList.size(); ++i)
        {
          QChar ch = formatList.at(i).toLower().at(0);
          if(ch == 'y' && numberList.size() == 3)
          {
            year = numberList.at(pos).toInt();
            pos++;
          }
          else if(ch == 'm')
          {
            month = numberList.at(pos).toInt();
            pos++;
          }
          else if(ch == 'd')
          {
            day = numberList.at(pos).toInt();
            pos++;
          }
        }

        // if single digit year, move it to the current century
        if (year < 10)
          year += today.year() - today.year() % 100;

        if(day > 0 && month > 0 && year > 0)
          tmp = QDate(year, month, day);
      }
      else if(formatList.size() == 3 && numberList.size() == 1)
      {
        QString ns = numberList.at(0);
        bool isNumber = false;
        (void)ns.toInt(&isNumber);
        if(isNumber && (ns.length() == 6 || ns.length() == 8))
        {
          int year = today.year();
          int day = -1;
          int month = -1;

          pos = 0;
          for (int i = 0; i < formatList.size(); ++i)
          {
            QChar ch = formatList.at(i).toLower().at(0);
            if(ch == 'y')
            {
              if(ns.length() == 8)
              {
                year = ns.mid(pos, 4).toInt();
                pos+=4;
              }
              else
              {
                year = ns.mid(pos, 2).toInt(&isNumber);
                pos+=2;
                if(isNumber)
                {
                  if(year < 50)
                    year += 2000;
                  else
                    year += 1900;
                }
              }
            }
            else if(ch == 'm')
            {
              month = ns.mid(pos, 2).toInt();
              pos+=2;
            }
            else if(ch == 'd')
            {
              day = ns.mid(pos, 2).toInt();
              pos+=2;
            }
          }

          if(day > 0 && month > 0 && year > 0)
            tmp = QDate(year, month, day);
        }
      }
    }

    setDate(QDate(tmp.year(), tmp.month(), tmp.day()), true );
  }

  if (!_valid)
    setText("");

  _parsed = true;
}
Exemple #16
0
void Calendar::updateData()
{
    if (m_days == 0 || m_weeks == 0) {
        return;
    }

    m_dayList.clear();
    m_weekList = QJsonArray();

    int totalDays = m_days * m_weeks;

    int daysBeforeCurrentMonth = 0;
    int daysAfterCurrentMonth = 0;

    QDate firstDay(m_displayedDate.year(), m_displayedDate.month(), 1);

    // If the first day is the same as the starting day then we add a complete row before it.
    if (m_firstDayOfWeek < firstDay.dayOfWeek()) {
        daysBeforeCurrentMonth = firstDay.dayOfWeek() - m_firstDayOfWeek;
    } else {
        daysBeforeCurrentMonth = days() - (m_firstDayOfWeek - firstDay.dayOfWeek());
    }

    int daysThusFar = daysBeforeCurrentMonth + m_displayedDate.daysInMonth();
    if (daysThusFar < totalDays) {
        daysAfterCurrentMonth = totalDays - daysThusFar;
    }

    if (daysBeforeCurrentMonth > 0) {
        QDate previousMonth = m_displayedDate.addMonths(-1);
        //QDate previousMonth(m_displayedDate.year(), m_displayedDate.month() - 1, 1);
        for (int i = 0; i < daysBeforeCurrentMonth; i++) {
            DayData day;
            day.isCurrent = false;
            day.dayNumber = previousMonth.daysInMonth() - (daysBeforeCurrentMonth - (i + 1));
            day.monthNumber = previousMonth.month();
            day.yearNumber = previousMonth.year();
            //      day.containsEventItems = false;
            m_dayList << day;
        }
    }

    for (int i = 0; i < m_displayedDate.daysInMonth(); i++) {
        DayData day;
        day.isCurrent = true;
        day.dayNumber = i + 1; // +1 to go form 0 based index to 1 based calendar dates
        //  day.containsEventItems = m_dayHelper->containsEventItems(i + 1);
        day.monthNumber = m_displayedDate.month();
        day.yearNumber = m_displayedDate.year();
        m_dayList << day;

    }

    if (daysAfterCurrentMonth > 0) {
        for (int i = 0; i < daysAfterCurrentMonth; i++) {
            DayData day;
            day.isCurrent = false;
            day.dayNumber = i + 1; // +1 to go form 0 based index to 1 based calendar dates
            //   day.containsEventItems = false;
            day.monthNumber = m_displayedDate.addMonths(1).month();
            day.yearNumber = m_displayedDate.addMonths(1).year();
            m_dayList << day;
        }
    }
    const int numOfDaysInCalendar = m_dayList.count();

    // Week numbers are always counted from Mondays
    // so find which index is Monday
    int mondayOffset = 0;
    if (!m_dayList.isEmpty()) {
        const DayData &data = m_dayList.at(0);
        QDate firstDay(data.yearNumber, data.monthNumber, data.dayNumber);
        // If the first day is not already Monday, get offset for Monday
        if (firstDay.dayOfWeek() != 1) {
            mondayOffset = 8 - firstDay.dayOfWeek();
        }
    }

    // Fill weeksModel with the week numbers
    for (int i = mondayOffset; i < numOfDaysInCalendar; i += 7) {
        const DayData &data = m_dayList.at(i);
        m_weekList.append(QDate(data.yearNumber, data.monthNumber, data.dayNumber).weekNumber());
    }
    emit weeksModelChanged();
    m_daysModel->update();

//    qDebug() << "---------------------------------------------------------------";
//    qDebug() << "Date obj: " << m_displayedDate;
//    qDebug() << "Month: " << m_displayedDate.month();
//    qDebug() << "m_days: " << m_days;
//    qDebug() << "m_weeks: " << m_weeks;
//    qDebug() << "Days before this month: " << daysBeforeCurrentMonth;
//    qDebug() << "Days after this month: " << daysAfterCurrentMonth;
//    qDebug() << "Days in current month: " << m_displayedDate.daysInMonth();
//    qDebug() << "m_dayList size: " << m_dayList.count();
//    qDebug() << "---------------------------------------------------------------";
}
Exemple #17
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!
}
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;
}
Exemple #19
0
//Method to set dates in Calendar
         void MonthView::SetDatesInCalendar(QDate dtStartDate, QDate dtEndDate, bool toFillData)
         {
                m_ptr_growth_animation_timer->stop();

                 int dayStartDate = dtStartDate.day();
                 int StartMonthDays = dtStartDate.daysInMonth();//Total days in selected month


                 int dayCurrMonth = 1;
                 int dayNextMonth = 1;
                   all_week_data = 0;
                 qreal week_total = 0;
                 int data = 0;
                 int sourceData = 0;

                 for(int row = 0; row < 6; row++)
                 {
                          week_total = 0; //add_Weekly_total = true;


                         for(int col = 0; col < 7; col++)
                            {

                              if ( m_vector_vector_view_selected_day_usage_values.size() != 42)
                             {
                                  data = 0 ; sourceData =0;
                              } else
                              {
                              data = (qreal)((qreal)(50 * ( m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][0] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][1] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][2] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][3] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][4]  ) ))/MaxUnit     ; //    qrand() % ((ui->tblDates->rowHeight(0) + 1) - 5) + 5;
                              sourceData  = (qreal)((qreal)(50 * ( m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][source_name] )))/MaxUnit;//    qrand() % (((data/2) + 1) - 2) + 2;  // data % 2;
                          }
                                //Previous Month
                                 if(dayStartDate <= StartMonthDays)
                                 {
                                          QTableWidgetItem *item = new QTableWidgetItem();

                                          int day = dayStartDate++;
                                          item->setData(0,
                                                         qVariantFromValue(StarRating(day,0,0, source_name,data,sourceData)));

                                          if(dtStartDate.day() > 1)//When 3 months are displayed in Calendar, only then prev month date is grayed out
                                          {

                                              item->setData(0,
                                                             qVariantFromValue(StarRating(0,0,0, source_name,data,sourceData)));
                                              data = 0;// Make it zero as not to be added with total
                                          }

                                          item->setTextAlignment(Qt::AlignTop | Qt::AlignRight);

                                          QDate dt(dtStartDate.year(),dtStartDate.month(), locale->toInt(QString::number(day)));
                                          QString str(dt.toString());
                                          item->setWhatsThis(str);

                                          if(dt.operator >(QDate::currentDate()))
                                           {

                                               data= 0;
                                              if(dt.month() == QDate::currentDate().month() && dt.month() == StartDate.month()) //compare to current as well as calendar's month
                                               {
                                                 item->setData(0,
                                                              qVariantFromValue(StarRating(-day,data,0, source_name,data,0)));
                                               }
                                               else
                                               {
                                                   item->setData(0,
                                                                qVariantFromValue(StarRating(0,data,0, source_name,data,0)));
                                               }
                                           }
                                          ui->tblDates->setItem(row,col,item);


                                 }
                                 else
                                 {
                                         QDate date = dtStartDate.addMonths(1);
                                         int CurrentMonthDays = date.daysInMonth();
                                         //Current month
                                         if(dayCurrMonth <= CurrentMonthDays)
                                         {
                                                  QTableWidgetItem *item = new QTableWidgetItem();
                                                  int day = dayCurrMonth++;
                                                   item->setData(0,
                                                                  qVariantFromValue(StarRating(day,0,0, source_name,data,sourceData)));


                                                  if(dtStartDate.day() == 1)//When 2 months are displayed in Calendar, only then current month date is grayed out
                                                  {

                                                      item->setData(0,
                                                                     qVariantFromValue(StarRating(0,0,0, source_name,data,sourceData)));
                                                      data = 0;// Make it zero as not to be added with total

                                                  }

                                                  item->setTextAlignment(Qt::AlignTop | Qt::AlignHCenter);
                                                  QDate dt(date.year(),date.month(), locale->toInt(QString::number(day)));
                                                  QString str(dt.toString());
                                                  item->setWhatsThis(str);

                                                  if(dt.operator >(QDate::currentDate()))
                                                   {

                                                       data= 0;
                                                      if(dt.month() == QDate::currentDate().month() && dt.month() == StartDate.month()) //compare to current as well as calendar's month
                                                       {
                                                         item->setData(0,
                                                                      qVariantFromValue(StarRating(-day,data,0, source_name,data,0)));
                                                       }
                                                       else
                                                       {
                                                           item->setData(0,
                                                                        qVariantFromValue(StarRating(0,data,0, source_name,data,0)));
                                                       }
                                                   }

                                                 ui->tblDates->setItem(row,col,item);


                                         }
                                         //Next month
                                         else
                                         {
                                                 if(dayNextMonth <= dtEndDate.day())
                                                 {
                                                         QTableWidgetItem *item = new QTableWidgetItem();
                                                         item->setForeground(QBrush(Qt::gray,Qt::SolidPattern));//Always grayed out

                                                         item->setData(0,
                                                                        qVariantFromValue(StarRating(0,0,0, source_name,data,sourceData)));

                                                         data = 0;// Make it zero as not to be added with total

                                                         item->setTextAlignment(Qt::AlignTop | Qt::AlignHCenter);
                                                         int day = dayNextMonth++;
                                                         QDate dt(dtEndDate.year(),dtEndDate.month(), locale->toInt(QString::number(day)));
                                                          QString str(dt.toString());
                                                          item->setWhatsThis(str);

                                                          if(dt.operator >(QDate::currentDate()))
                                                       {

                                                           data= 0;
                                                          if(dt.month() == QDate::currentDate().month() && dt.month() == StartDate.month()) //compare to current as well as calendar's month
                                                           {
                                                             item->setData(0,
                                                                          qVariantFromValue(StarRating(-day,data,0, source_name,data,0)));
                                                           }
                                                           else
                                                           {
                                                               item->setData(0,
                                                                            qVariantFromValue(StarRating(0,data,0, source_name,data,0)));
                                                           }
                                                       }
                                                          ui->tblDates->setItem(row,col,item);


                                                 }

                                         }

                                 }
                                 //For weekDays total
                                 if(data > 0)
                                 {
                                     week_total += (m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][source_name]) ;
                                 }
  //                               week_total +=  m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][0] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][1] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][2] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][3] + m_vector_vector_view_selected_day_usage_values[(row * 7) + col ][4]  ;//data;
                         }


                         all_week_data += week_total;
                         QTableWidgetItem *item = new QTableWidgetItem();
                         item->setData(0,
                                        qVariantFromValue(StarRating(100,week_total,0, source_name,data,sourceData)));
                         item->setTextAlignment(Qt::AlignTop | Qt::AlignHCenter);
                          ui->tblDates->setItem(row,7,item);

                 }
                 if(toFillData)
                   {
                      m_ptr_growth_animation_timer->start();
                   }
         }
Exemple #20
0
void XDateEdit::parseDate()
{
  QString dateString = text().stripWhiteSpace();
  bool    isNumeric;

  if (DEBUG)
    qDebug("%s::parseDate() with dateString %s, _currentDate %s, _allowNull %d",
           qPrintable(parent() ? parent()->objectName() : objectName()),
           qPrintable(dateString),
           qPrintable(_currentDate.toString()), _allowNull);

#ifdef OpenMFGGUIClient_h
  QDate today = ofmgThis->dbDate();
#else
  QDate today = QDate::currentDate();
#endif

  if (_parsed)
  {
    if (DEBUG)
      qDebug("%s::parseDate() looks like we've already parsed this string",
             qPrintable(parent() ? parent()->objectName() : objectName()));
    return;
  }

  _valid = false;

  if (dateString == _nullString || dateString.isEmpty())
    setNull();

  else if (dateString == "0")                           // today
    setDate(today, TRUE);

  else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today
  {
    int offset = dateString.toInt(&isNumeric);
    if (isNumeric)
      setDate(today.addDays(offset), true);
  }

  else if (dateString[0] == '#')                        // julian day
  {
    int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric);
    if (isNumeric)
      setDate(QDate(today.year(), 1, 1).addDays(offset - 1), TRUE);
  }

  else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month
  {
    int offset = dateString.toInt(&isNumeric, 10);
    if (isNumeric)
    {
      if (offset > today.daysInMonth())
        offset = today.daysInMonth();
 
      setDate(QDate(today.year(), today.month(), 1).addDays(offset - 1), TRUE);
    }
  }

  else                                                  // interpret with locale
  {
    QString dateFormatStr = QLocale().dateFormat(QLocale::ShortFormat);
    if (DEBUG)
      qDebug("%s::parseDate() trying to parse with %s",
             qPrintable(parent() ? parent()->objectName() : objectName()),
             qPrintable(dateFormatStr));

    QDate tmp = QDate::fromString(dateString, dateFormatStr);
    if (tmp.isValid() && dateFormatStr.indexOf(QRegExp("y{2}")) >= 0)
    {
      qDebug("%s::parseDate() found valid 2-digit year %d",
             qPrintable(parent() ? parent()->objectName() : objectName()),
             tmp.year());
      if (tmp.year() < 1950)     // Qt docs say 2-digit years are 1900-based so
      {
        tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit
        qDebug("%s::parseDate() altered year to %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
      }
    }
    else
    {
      // try 4 digits, ignoring the possibility of '-literals in the format str
      dateFormatStr.replace(QRegExp("y{2}"), "yyyy");
      if (DEBUG)
        qDebug("%s::parseDate() rewriting format string to %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(dateFormatStr));
      tmp = QDate::fromString(dateString, dateFormatStr);
    }

    setDate(QDate(tmp.year(), tmp.month(), tmp.day()), true );
  }

  if (!_valid)
    setText("");

  _parsed = true;
}
void SvgView::loadPlan(vlePlan *plan)
{
    qWarning() << "SvgView::loadPlan";

    if ( mTplHeader.isNull() )
    {
        // ToDo : improve error handling
        qWarning() << "SvgView::loadPlan() Template error";
        return;
    }

    // Compute the height of a group
    if (mTplHeader.hasAttribute("height"))
        mGroupHeight = mTplHeader.attribute("height").toDouble();
    else
        mGroupHeight = 100;

    // Compute size of the whole plan
    int planHeight = mGroupHeight * (1 + plan->countGroups());
    int planWidth  = (mMaxWidth * mZoomLevel);

    // Create SVG document
    QDomDocument planSVG("xml");
    // Create root element
    QDomElement e = planSVG.createElement("svg");
    e.setAttribute("width",   QString(planWidth));
    e.setAttribute("height",  QString(planHeight));
    e.setAttribute("viewBox", QString("0 0 %1 %2").arg(planWidth).arg(planHeight));
    e.setAttribute("version", "1.1");

    QDate dateStart = plan->dateStart();
    QDate dateEnd   = plan->dateEnd();
    int nbDays = dateStart.daysTo(dateEnd);

    // In the plan duration is more than 1500 days
    if (nbDays > mMaxWidth)
    {
        // Update "pixel-per-day" to avoid very large picture
        qreal widgetSize = mMaxWidth;
        mPixelPerDay = (widgetSize / nbDays);
    }

    if (plan != mPlan)
    {
    qWarning() << "Plan period is from" << dateStart.toString("dd/MM/yyyy")
            << "to" << dateEnd.toString("dd/MM/yyyy")
            << "(" << nbDays<< "days)"
            << "[" << mPixelPerDay << "pixel per day]";
    }

    // First insert the time rule
    QDomElement timeGrp = mTplHeader.cloneNode().toElement();
    updateField(timeGrp, "{{name}}", "");
    updatePos  (timeGrp, 0, 0);
    updateAttr (timeGrp, "header_background", "width", QString::number(planWidth));
    float yLen = (mPixelPerDay * 365 * mZoomLevel);
    // Show Weeks
    if (yLen > 2000)
    {
        QDate r;
        if (dateStart.daysInMonth() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year(), dateStart.month() + 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            if (yLen < 5000)
                updateField(newTimeStep, "{{name}}", r.toString("dd/MM") );
            else
                updateField(newTimeStep, "{{name}}", r.toString("dd/MM/yy") );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addDays(7);
        }
    }
    // Show month
    else if (yLen > 500)
    {
        QDate r;
        if (dateStart.daysInMonth() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year(), dateStart.month() + 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            if (yLen < 1000)
                updateField(newTimeStep, "{{name}}", r.toString("MMM") );
            else
                updateField(newTimeStep, "{{name}}", r.toString("MMM yy") );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addMonths(1);
        }
    }
    // Show Year
    else
    {
        QDate r;
        if (dateStart.dayOfYear() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year() + 1, 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            updateField(newTimeStep, "{{name}}", QString::number(r.year()) );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addYears(1);
        }
    }
    e.appendChild(timeGrp);

    // Insert all the known groups
    for (int i=0; i < plan->countGroups(); i++)
    {
        vlePlanGroup *planGroup = plan->getGroup(i);
        vlePlanActivity *prevActivity = 0;
        int prevLen = 0;
        int prevOffset = 0;

        // Create a new Group
        QDomElement newGrp = mTplHeader.cloneNode().toElement();
        updateField(newGrp, "{{name}}", planGroup->getName());
        updatePos  (newGrp, 0, ((i + 1) * mGroupHeight));
        updateAttr (newGrp, "header_background", "width", QString::number(planWidth));

        for (int j = 0; j < planGroup->count(); j++)
        {
            vlePlanActivity *planActivity = planGroup->getActivity(j);

            QDate actStart = planActivity->dateStart();
            QDate actEnd   = planActivity->dateEnd();

            qreal actLength = (mPixelPerDay * actStart.daysTo(actEnd) * mZoomLevel);
            if (actLength < 1)
                actLength = 1;

            QDomElement newAct = mTplTask.cloneNode().toElement();
            updateField(newAct, "{{name}}", planActivity->getName());
            updateAttr (newAct, "activity_block", "width", QString::number(actLength));

            QString cfgColor("#00edda");
            QString activityClass = planActivity->getClass();
            if ( ! activityClass.isEmpty() )
            {
                QString cfg = getConfig("color", activityClass);
                if ( ! cfg.isEmpty() )
                    cfgColor = cfg;
            }
            QString fillStyle = QString(";fill:%1").arg(cfgColor);
            updateAttr (newAct, "activity_block", "style", fillStyle, false);

            int date = dateStart.daysTo(planActivity->dateStart());
            int aPos = (date * mPixelPerDay * mZoomLevel);

            if (prevActivity)
            {
                if (prevLen > aPos)
                {
                    if (prevOffset < 40)
                        prevOffset += 15;
                    updateAttr(newAct, "activity_name", "y", QString::number(prevOffset));
                }
                else
                    prevOffset = 15;
            }

            updatePos(newAct, aPos, 0);
            newGrp.appendChild(newAct);

            prevActivity = planActivity;
            prevLen = aPos + (planActivity->getName().size() * 8);
        }

        e.appendChild(newGrp);
    }
    planSVG.appendChild( e );

    QByteArray data;
    QTextStream stream(&data);
    planSVG.save(stream, QDomNode::EncodingFromTextStream);

#ifdef PLAN_OUT
    QFile File("planOut.svg");
    File.open( QIODevice::WriteOnly );
    QTextStream TextStream(&File);
    planSVG.save(TextStream, 0);
    File.close();
    mFilename = "planOut.svg";
#else
    mFilename.clear();
#endif

    mPlan = plan;

    QXmlStreamReader xData(data);
    mSvgRenderer->load(&xData);
    refresh();
}
void MyDiagrammView::zeichneL3()
{
    //Punkte berechnen
    Linie3.clear();
    QDateTime dt;
    double d;
    QPoint po;
    double wby = maxWertL3 - minWertL3;
    QDate dmin = L3Datum.first().date();
    QDate dmax = L3Datum.last().date();
    if (!day) {
        dmin.setDate(dmin.year(),dmin.month(),1);
        dmax.setDate(dmax.year(),dmax.month(),dmax.daysInMonth());
    }
    int AnzahlTage = dmin.daysTo(dmax);

    for (int i=0; i < L3Daten.count(); i++) {
        //Y
        dt = L3Datum[i];
        d = L3Daten[i] - minWertL3;
        po.setY(qRound(nullY - (zhoehe / wby * d)));
        //X
        if (day) {
            QDateTime dtemp;
            dtemp.setDate(dt.date());
            dtemp.time().setHMS(0,0,0);
            //Zeitoffset berechnen
            int ZeitOffset = qRound(double(abstandX / (24*60*60)) * dtemp.time().secsTo(dt.time()));
            po.setX(qRound(double(nullX+ZeitOffset) + (double(zbreite) / double(AnzahlX) * double(dmin.daysTo(dt.date())))));
        }
        else {
            po.setX(qRound(double(nullX) + (double(zbreite) / double(AnzahlTage) * double(dmin.daysTo(dt.date())))));
        }
        Linie3.append(po);
    }

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing,true);
    QPen pen;
    QBrush brush;

    //Wert Linie zeichnen
    if (WertLinie3Aktiv) {
        d = WertLinie3 - minWertL3;
        pen.setColor(colorL3);
        pen.setWidth(2);
        pen.setStyle(Qt::DashLine);
        brush.setStyle(Qt::SolidPattern);
        painter.setPen(pen);
        painter.setBrush(brush);
        painter.drawLine(nullX+1, qRound(nullY - (zhoehe / wby * d)), nullX + zbreite, qRound(nullY - (zhoehe / wby * d)));
    }

    brush.setStyle(Qt::SolidPattern);
    brush.setColor(Qt::white);
    pen.setColor(colorL3);
    pen.setWidth(2);
    painter.setPen(pen);
    painter.setBrush(brush);
    //Linie Zeichnen
    for (int i=0; i < Linie3.count(); i++) {
        //painter.drawEllipse(Linie1[i],3,3);
        if (i>0)
            painter.drawLine(Linie3[i-1],Linie3[i]);
    }
    //Punkte Zeichnen
    for (int i=0; i < Linie3.count(); i++) {
        //Markierung zeichnen
        if (i == MarkierterPunkt - 1) {
            brush.setColor(Qt::red);
            painter.setBrush(brush);
            painter.drawEllipse(Linie3[i],3,3);
            brush.setColor(Qt::white);
            painter.setBrush(brush);
        }
        else
            painter.drawEllipse(Linie3[i],3,3);

    }
    //Bezeichnung
    if (!BezeichnungL3.isEmpty()) {
        painter.setFont(QFont("Ubuntu", 10));
        painter.drawText(QRectF(qRound(nullX + zbreite / 2.0),0,qRound(zbreite / 2.0),AbstandOben),Qt::AlignRight, BezeichnungL3);
    }
}
Exemple #23
0
/* Calculating the next event of a recuring event is actually
   computationally inexpensive, esp. compared to checking each day
   individually.  There are bad worse cases for say the 29th of
   february or the 31st of some other months.  However
   these are still bounded */
bool nextOccuranceNoExceptions(const Event &e, const QDate &from, QDateTime &next)
{
    // easy checks, first are we too far in the future or too far in the past?
    QDate tmpDate;
    int freq = e.repeatPattern().frequency;
    int diff, diff2, a;
    int iday, imonth, iyear;
    int dayOfWeek = 0;
    int firstOfWeek = 0;
    int weekOfMonth;


    if (e.repeatPattern().hasEndDate && e.repeatPattern().endDate() < from)
        return FALSE;

    if (e.start() >= from) {
        next = e.start();
        return TRUE;
    }

    switch ( e.repeatPattern().type ) {
        case Event::Weekly:
            /* weekly is just daily by 7 */
            /* first convert the repeatPattern.Days() mask to the next
               day of week valid after from */
            dayOfWeek = from.dayOfWeek();
            dayOfWeek--; /* we want 0-6, doco for above specs 1-7 */

            /* this is done in case freq > 1 and from in week not
               for this round */
            // firstOfWeek = 0; this is already done at decl.
            while(!((1 << firstOfWeek) & e.repeatPattern().days))
                firstOfWeek++;



            /* there is at least one 'day', or there would be no event */
            while(!((1 << (dayOfWeek % 7)) & e.repeatPattern().days))
                dayOfWeek++;


            dayOfWeek = dayOfWeek % 7; /* the actual day of week */
            dayOfWeek -= e.start().date().dayOfWeek() -1;

            firstOfWeek = firstOfWeek % 7; /* the actual first of week */
            firstOfWeek -= e.start().date().dayOfWeek() -1;

            // dayOfWeek may be negitive now
            // day of week is number of days to add to start day

            freq *= 7;
            // FALL-THROUGH !!!!!
        case Event::Daily:
            // the add is for the possible fall through from weekly */
            if(e.start().date().addDays(dayOfWeek) > from) {
                /* first week exception */
                next = QDateTime(e.start().date().addDays(dayOfWeek),
                                 e.start().time());
                if ((next.date() > e.repeatPattern().endDate())
                    && e.repeatPattern().hasEndDate)
                    return FALSE;
                return TRUE;
            }
            /* if from is middle of a non-week */

            diff = e.start().date().addDays(dayOfWeek).daysTo(from) % freq;
            diff2 = e.start().date().addDays(firstOfWeek).daysTo(from) % freq;

            if(diff != 0)
                diff = freq - diff;
            if(diff2 != 0)
                diff2 = freq - diff2;
            diff = QMIN(diff, diff2);

            next = QDateTime(from.addDays(diff), e.start().time());
            if ( (next.date() > e.repeatPattern().endDate())
                 && e.repeatPattern().hasEndDate )
                return FALSE;
            return TRUE;
        case Event::MonthlyDay:
            iday = from.day();
            iyear = from.year();
            imonth = from.month();
            /* find equivelent day of month for this month */
            dayOfWeek = e.start().date().dayOfWeek();
            weekOfMonth = (e.start().date().day() - 1) / 7;

            /* work out when the next valid month is */
            a = from.year() - e.start().date().year();
            a *= 12;
            a = a + (imonth - e.start().date().month());
            /* a is e.start()monthsFrom(from); */
            if(a % freq) {
                a = freq - (a % freq);
                imonth = from.month() + a;
                if (imonth > 12) {
                    imonth--;
                    iyear += imonth / 12;
                    imonth = imonth % 12;
                    imonth++;
                }
            }
            /* imonth is now the first month after or on
               from that matches the frequency given */

            /* find for this month */
            tmpDate = QDate( iyear, imonth, 1 );

            iday = 1;
            iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7;
            iday += 7 * weekOfMonth;
            while (iday > tmpDate.daysInMonth()) {
                imonth += freq;
                if (imonth > 12) {
                    imonth--;
                    iyear += imonth / 12;
                    imonth = imonth % 12;
                    imonth++;
                }
                tmpDate = QDate( iyear, imonth, 1 );
                /* these loops could go for a while, check end case now */
                if ((tmpDate > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                    return FALSE;
                iday = 1;
                iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7;
                iday += 7 * weekOfMonth;
            }
            tmpDate = QDate(iyear, imonth, iday);

            if (tmpDate >= from) {
                next = QDateTime(tmpDate, e.start().time());
                if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                    return FALSE;
                return TRUE;
            }

            /* need to find the next iteration */
            do {
                imonth += freq;
                if (imonth > 12) {
                    imonth--;
                    iyear += imonth / 12;
                    imonth = imonth % 12;
                    imonth++;
                }
                tmpDate = QDate( iyear, imonth, 1 );
                /* these loops could go for a while, check end case now */
                if ((tmpDate > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                    return FALSE;
                iday = 1;
                iday += (7 + dayOfWeek - tmpDate.dayOfWeek()) % 7;
                iday += 7 * weekOfMonth;
            } while (iday > tmpDate.daysInMonth());
            tmpDate = QDate(iyear, imonth, iday);

            next = QDateTime(tmpDate, e.start().time());
            if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                return FALSE;
            return TRUE;
        case Event::MonthlyDate:
            iday = e.start().date().day();
            iyear = from.year();
            imonth = from.month();

            a = from.year() - e.start().date().year();
            a *= 12;
            a = a + (imonth - e.start().date().month());
            /* a is e.start()monthsFrom(from); */
            if(a % freq) {
                a = freq - (a % freq);
                imonth = from.month() + a;
                if (imonth > 12) {
                    imonth--;
                    iyear += imonth / 12;
                    imonth = imonth % 12;
                    imonth++;
                }
            }
            /* imonth is now the first month after or on
               from that matches the frequencey given */

            /* this could go for a while, worse case, 4*12 iterations, probably */
            while(!QDate::isValid(iyear, imonth, iday) ) {
                imonth += freq;
                if (imonth > 12) {
                    imonth--;
                    iyear += imonth / 12;
                    imonth = imonth % 12;
                    imonth++;
                }
                /* these loops could go for a while, check end case now */
                if ((QDate(iyear, imonth, 1) > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                    return FALSE;
            }

            if(QDate(iyear, imonth, iday) >= from) {
                /* done */
                next = QDateTime(QDate(iyear, imonth, iday),
                        e.start().time());
                if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                    return FALSE;
                return TRUE;
            }

            /* ok, need to cycle */
            imonth += freq;
            imonth--;
            iyear += imonth / 12;
            imonth = imonth % 12;
            imonth++;

            while(!QDate::isValid(iyear, imonth, iday) ) {
                imonth += freq;
                imonth--;
                iyear += imonth / 12;
                imonth = imonth % 12;
                imonth++;
                if ((QDate(iyear, imonth, 1) > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                    return FALSE;
            }

            next = QDateTime(QDate(iyear, imonth, iday), e.start().time());
            if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                return FALSE;
            return TRUE;
        case Event::Yearly:
            iday = e.start().date().day();
            imonth = e.start().date().month();
            iyear = from.year(); // after all, we want to start in this year

            diff = 1;
            if(imonth == 2 && iday > 28) {
                /* leap year, and it counts, calculate actual frequency */
                if(freq % 4)
                    if (freq % 2)
                        freq = freq * 4;
                    else
                        freq = freq * 2;
                /* else divides by 4 already, leave freq alone */
                diff = 4;
            }

            a = from.year() - e.start().date().year();
            if(a % freq) {
                a = freq - (a % freq);
                iyear = iyear + a;
            }

            /* under the assumption we won't hit one of the special not-leap years twice */
            if(!QDate::isValid(iyear, imonth, iday)) {
                /* must have been skipping by leap years and hit one that wasn't, (e.g. 2100) */
                iyear += freq;
            }

            if(QDate(iyear, imonth, iday) >= from) {
                next = QDateTime(QDate(iyear, imonth, iday),
                        e.start().time());
                if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                    return FALSE;
                return TRUE;
            }
            /* iyear == from.year(), need to advance again */
            iyear += freq;
            /* under the assumption we won't hit one of the special not-leap years twice */
            if(!QDate::isValid(iyear, imonth, iday)) {
                /* must have been skipping by leap years and hit one that wasn't, (e.g. 2100) */
                iyear += freq;
            }

            next = QDateTime(QDate(iyear, imonth, iday), e.start().time());
            if ((next.date() > e.repeatPattern().endDate()) && e.repeatPattern().hasEndDate)
                return FALSE;
            return TRUE;
        default:
            return FALSE;
    }
}
Exemple #24
0
void HtmlExport::createMonthView(QTextStream *ts)
{
    QDate start = fromDate();
    start.setYMD( start.year(), start.month(), 1 );  // go back to first day in month

    QDate end( start.year(), start.month(), start.daysInMonth() );

    int startmonth = start.month();
    int startyear = start.year();

    while ( start < toDate() ) {
        // Write header
        *ts << "<h2>" << (i18n("month_year","%1 %2").arg(KGlobal::locale()->calendar()->monthName(start))
                          .arg(start.year())) << "</h2>\n";
        if ( KGlobal::locale()->weekStartDay() == 1 ) {
            start = start.addDays(1 - start.dayOfWeek());
        } else {
            if (start.dayOfWeek() != 7) {
                start = start.addDays(-start.dayOfWeek());
            }
        }
        *ts << "<table border=\"1\">\n";

        // Write table header
        *ts << "  <tr>";
        for(int i=0; i<7; ++i) {
            *ts << "<th>" << KGlobal::locale()->calendar()->weekDayName( start.addDays(i) ) << "</th>";
        }
        *ts << "</tr>\n";

        // Write days
        while (start <= end) {
            *ts << "  <tr>\n";
            for(int i=0; i<7; ++i) {
                *ts << "    <td valign=\"top\"><table border=\"0\">";

                *ts << "<tr><td ";
                if (mHolidayMap.contains(start) || start.dayOfWeek() == 7) {
                    *ts << "class=\"dateholiday\"";
                } else {
                    *ts << "class=\"date\"";
                }
                *ts << ">" << QString::number(start.day());

                if (mHolidayMap.contains(start)) {
                    *ts << " <em>" << mHolidayMap[start] << "</em>";
                }

                *ts << "</td></tr><tr><td valign=\"top\">";

                Event::List events = mCalendar->events( start,
                                                        EventSortStartDate,
                                                        SortDirectionAscending );
                if (events.count()) {
                    *ts << "<table>";
                    Event::List::ConstIterator it;
                    for( it = events.begin(); it != events.end(); ++it ) {
                        if ( checkSecrecy( *it ) ) {
                            createEvent( ts, *it, start, false );
                        }
                    }
                    *ts << "</table>";
                } else {
                    *ts << "&nbsp;";
                }

                *ts << "</td></tr></table></td>\n";
                start = start.addDays(1);
            }
            *ts << "  </tr>\n";
        }
        *ts << "</table>\n";
        startmonth += 1;
        if ( startmonth > 12 ) {
            startyear += 1;
            startmonth = 1;
        }
        start.setYMD( startyear, startmonth, 1 );
        end.setYMD(start.year(),start.month(),start.daysInMonth());
    }
}
Exemple #25
0
int main(int argc, char *argv[])
{

    QDir dir;
    QString path=dir.absolutePath();

    QDate data = QDate::currentDate();
    int DaysInMonths = data.daysInMonth();
    int ActualDay = data.day();

    int currentExitCode = 0;

    do
    {
            QApplication a(argc, argv);
            a.setStyle("fusion");

            QFont font("Calibri Light", 12, QFont::Light ,false);
            QFont font_main("Calibri Light", 10, QFont::Light ,false);
            QFont splash_font("Calibri Light", 24, QFont::Bold);

            LoginDialog *logindialog = new LoginDialog;
            MainWindow w;

            logindialog->setWindowFlags(((logindialog->windowFlags() | Qt::CustomizeWindowHint) & Qt::WindowCloseButtonHint & ~Qt::WindowContextHelpButtonHint) );

            /* Ekran startowy*/
            if(currentExitCode != MainWindow::EXIT_CODE_REBOOT)
            {
                QSplashScreen * splash = new QSplashScreen;
                splash->setPixmap(QPixmap(path+"/obrazy/splash.png"));
                splash->setFont(splash_font);
                splash->show();
                splash->showMessage(QObject::tr("Uruchamianie programu "),
                                Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position

                qApp->processEvents();
                QTimer::singleShot(2000,splash,SLOT(close()));
                QString Splash_string = "Uruchamianie programu";
                QString Splash_string_add = "Uruchamianie programu";

                for(int i=0;i<12;i++)
                {
                    QThread::msleep(150);
                    Splash_string_add = Splash_string_add + ".";

                    if(i==3 || i==7 || i==11) Splash_string_add = Splash_string;

                    splash->showMessage(Splash_string_add,
                                    Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position
                }
            }



            /* signal-slot - connect login and password from logindialog with MainWindow */
            QObject::connect(logindialog, SIGNAL(sendAccess(QString,QString)),
                             &w, SLOT(receiveAccess(QString,QString)));



            logindialog->setWindowIcon(QIcon(path+"/obrazy/log_icon.png"));
            logindialog->setWindowTitle("SERWIS - Logowanie");
            logindialog->setFont(font);
            if (logindialog->exec() != QDialog::Accepted) {
                a.quit();
                return 0;
            } else {
                delete logindialog;
                w.showMaximized();
                w.setWindowTitle("SERWIS");
                w.setWindowIcon(QIcon(path+"/obrazy/services_icon.png"));
                w.setFont(font_main);
                w.show();

                QFile file;
                QString file_name="AUTO_BACKUP.txt";
                file.setFileName(file_name);
                if(!file.exists() && (DaysInMonths-ActualDay)==1){

                    QMessageBox::warning(&w,"Informacja","****************** Do końca miesiąca został 1 dzień! *******************\n"
                                                         "Wykonany zostanie automatyczny zapis kopii zapasowej bazy danych. \n"
                                                         "*************************************************************************");
                    QTimer::singleShot(500,&w,SLOT(create_backup()));

                    qDebug() << "Doesn't exists: "<<file_name;
                    file.open(QIODevice::ReadWrite | QIODevice::Text);
                    QTextStream stream(&file);
                    file.close();

                }else if (file.exists() && (DaysInMonths-ActualDay)!=1){
                    qDebug() << file_name <<" removing ...";
                    file.remove();
                }else if (file.exists() && (DaysInMonths-ActualDay)==1)
                {
                    qDebug() << file_name <<" already created ...";
                }

            }
             currentExitCode = a.exec();
     } while( currentExitCode == MainWindow::EXIT_CODE_REBOOT );

    return currentExitCode;
}
QStringList scheduler::calculateDifferenceInDates(QDate start, QDate end, int type)
{
//qDebug() << " \n\n CALCULATING DIFFERENCE IN DATES ";

    QStringList listOfDates;

    int difference  = start.daysTo(end);

    listOfDates.append(start.toString(STANDARD_DATE_FORMAT_2));

    switch(type)
    {
    case 0:
    {
        QDate temp;
        int difference  = start.daysTo(end);

        // Daily Delivery. Make dates for all days except Sat/Sun.

        for( int i = 1; i <= difference; i++ )
        {
            // Add days to start
            temp = start.addDays(i);

            // Ensure non-weekend
            if ( temp.dayOfWeek() != 6 && temp.dayOfWeek() != 7 )
            {
                // Add to list
                listOfDates.append(temp.toString(STANDARD_DATE_FORMAT_2));
            }
        }
        break;
    }
    case 1:
    {
//qDebug() << "\n TYPE = " << type << "\n";

        // Weekly Delivery. Make dates for every 7 days.

        int numberOfDeliveries = difference / 7;

//qDebug() << "\n NUM OF DELIVERIES : " << numberOfDeliveries;

        for( int i = 0, j = 7; i < numberOfDeliveries; i++ )
        {
            QDate temp = start.addDays(j);
            listOfDates.append(temp.toString(STANDARD_DATE_FORMAT_2));
            j+=7;
        }
        break;
    }
    case 2:
    {
//qDebug() << "\n TYPE = " << type << "\n";

        // Monthly. Make dates for every month in series.

        QDate temp;
        bool includedStart = false;
        int daysThisMonth = start.daysInMonth();

        while ( difference != 0 )
        {
            if ( !includedStart )
            {
                temp = start.addDays(daysThisMonth);
                listOfDates.append(temp.toString(STANDARD_DATE_FORMAT_2));
                includedStart = true;
            }
            else
            {
                daysThisMonth = temp.daysInMonth();
                temp = temp.addDays(daysThisMonth);
                listOfDates.append(temp.toString(STANDARD_DATE_FORMAT_2));
            }
            difference -= daysThisMonth;

            if ( difference < 0 )
            {
                // Should never be the case, but if so it prevens infinite loop.
                difference = 0;
            }
        }
        break;
    }
    case 3:
    {
//qDebug() << "\n TYPE = " << type << "\n";

        // Tuesday / Thursday Delivery. Make dates for all in series.

        for( int i = 1; i <= difference; i++ )
        {
            // Add days to start
            QDate temp = start.addDays(i);

            // Ensure is on tuesday or thursday
            if ( temp.dayOfWeek() == 2 || temp.dayOfWeek() == 4 )
            {
                // Add to list
                listOfDates.append(temp.toString(STANDARD_DATE_FORMAT_2));
            }
        }
        break;
    }
    case 4:
    {
//qDebug() << "\n TYPE = " << type << "\n";

        // Monday / Wednesday / Friday Delivery. Make dates for all in series.

        for( int i = 1; i <= difference; i++ )
        {
            // Add days to start
            QDate temp = start.addDays(i);

            // Ensure is on MWF day.
            if ( temp.dayOfWeek() == 1 || temp.dayOfWeek() == 3 || temp.dayOfWeek() == 5)
            {
                // Add to list
                listOfDates.append(temp.toString(STANDARD_DATE_FORMAT_2));
            }
        }
        break;
    }
    case 5:
    {
//qDebug() << "\n TYPE = " << type << "\n";

        // Daily Delivery. Make dates for all days except Sat/Sun.

        for( int i = 1; i <= difference; i++ )
        {
            // Add days to start
            QDate temp = start.addDays(i);

            // Ensure non-weekend
            if ( temp.dayOfWeek() != 6 && temp.dayOfWeek() != 7 )
            {
                // Add to list
                listOfDates.append(temp.toString(STANDARD_DATE_FORMAT_2));
            }
        }
        break;
    }
    default:
        // DONT DO ANYTHING
        break;
    }
    return listOfDates;
}
inline int UFormSalaryEditTabelWidget::currentPidrozdil()
{
    return ui.comboBox_pidrozdil->itemData(ui.comboBox_pidrozdil->currentIndex(), Qt::UserRole).toInt();
}
//--------------------utech--------------------utech--------------------utech--------------------
//Заповнює поля таблиці табеля з таблиці табеля бази даних
void UFormSalaryEditTabelWidget::populateTabel()
{
    disconnect(ui.tableWidget_tabel->selectionModel(), SIGNAL(currentRowChanged( const QModelIndex &, const QModelIndex &)),
               this, SLOT(sumTabelCurRowChanged( const QModelIndex &, const QModelIndex &)));

    QTableWidgetItem *item;
    QSqlQuery query;
    QString str;
    QDate begMonthDate(ui.dateEdit_tabelDate->date().year(), ui.dateEdit_tabelDate->date().month(),1), endMonthDate;
    endMonthDate.setDate(begMonthDate.year(), begMonthDate.month(), begMonthDate.daysInMonth());
    ui.dateEdit_dateFilter->setDate(begMonthDate);

    QString pidrozdilFilter = currentPidrozdil()?QString("Pidrozdil_id=")+sqlStr(currentPidrozdil()):
                              QString(" Pidrozdil_id not in (SELECT id FROM pidrozdily_salary) ");

    //Заповнення комбо пошуку працівника
    ui.comboBox_nprFilter->clear();
    ui.comboBox_nprFilter->addItem("",0);
    query.exec("SELECT id, Prizv, Imia, Pobatk FROM npr \
				WHERE "+pidrozdilFilter+" \
				ORDER BY Prizv, Imia, Pobatk");
    while (query.next())
        ui.comboBox_nprFilter->addItem("["+query.value(0).toString()+"] "+query.value(1).toString()+" "+
                                       query.value(2).toString()+" "+query.value(3).toString(), query.value(0));
Exemple #28
0
TimeSpans::TimeSpans(const QDate &today)
{
    m_today.name = tr( "Today" );
    m_today.timespan =
        TimeSpan( today,
                  today.addDays( 1 ) );
    m_today.timeSpanType = Day;

    m_yesterday.name = tr( "Yesterday" );
    m_yesterday.timespan =
        TimeSpan( m_today.timespan.first.addDays( -1 ),
                  m_today.timespan.second.addDays( -1 ) );
    m_yesterday.timeSpanType = Day;

    m_dayBeforeYesterday.name = tr( "The Day Before Yesterday" );
    m_dayBeforeYesterday.timespan =
        TimeSpan( m_today.timespan.first.addDays( -2 ),
                  m_today.timespan.second.addDays( -2 ) );
    m_dayBeforeYesterday.timeSpanType = Day;
    m_thisWeek.name = tr( "This Week" );
    m_thisWeek.timespan =
        TimeSpan( today.addDays( - today.dayOfWeek() + 1 ),
                  today.addDays( 7 - today.dayOfWeek() + 1 ) );
    m_thisWeek.timeSpanType = Week;

    m_lastWeek.name = tr( "Last Week" );
    m_lastWeek.timespan =
        TimeSpan( m_thisWeek.timespan.first.addDays( -7 ),
                  m_thisWeek.timespan.second.addDays( -7 ) );
    m_lastWeek.timeSpanType = Week;

    m_theWeekBeforeLast.name = tr( "The Week Before Last Week" );
    m_theWeekBeforeLast.timespan =
        TimeSpan( m_thisWeek.timespan.first.addDays( -14 ),
                  m_thisWeek.timespan.second.addDays( -14 ) );
    m_theWeekBeforeLast.timeSpanType = Week;

    m_3WeeksAgo.name = tr( "3 Weeks Ago" );
    m_3WeeksAgo.timespan =
        TimeSpan( m_thisWeek.timespan.first.addDays( -21 ),
                  m_thisWeek.timespan.second.addDays( -21 ) );
    m_3WeeksAgo.timeSpanType = Week;

    m_thisMonth.name = tr( "This Month" );
    m_thisMonth.timespan =
        TimeSpan( today.addDays( - today.day() + 1 ),
                  today.addDays( today.daysInMonth() - today.day() + 1) );
    m_thisMonth.timeSpanType = Month;

    m_lastMonth.name = tr( "Last Month" );
    m_lastMonth.timespan =
        TimeSpan( m_thisMonth.timespan.first.addMonths( -1 ),
                  m_thisMonth.timespan.second.addMonths( -1 ) );
    m_lastMonth.timeSpanType = Month;

    m_theMonthBeforeLast.name = tr( "The Month Before Last Month" );
    m_theMonthBeforeLast.timespan =
        TimeSpan( m_thisMonth.timespan.first.addMonths( -2 ),
                  m_thisMonth.timespan.second.addMonths( -2 ) );
    m_theMonthBeforeLast.timeSpanType = Month;

    m_3MonthsAgo.name = tr( "3 Months Ago" );
    m_3MonthsAgo.timespan =
        TimeSpan( m_thisMonth.timespan.first.addMonths( -3 ),
                  m_thisMonth.timespan.second.addMonths( -3 ) );
    m_3MonthsAgo.timeSpanType = Month;

    m_thisYear.name = tr( "This year" );
    m_thisYear.timespan =
       TimeSpan( QDate( today.year(), 1, 1 ),
                 QDate( today.year(), 12, 31 ) );
    m_thisYear.timeSpanType = Year;
}
void MyMoneyForecast::createBudget ( MyMoneyBudget& budget, QDate historyStart, QDate historyEnd, QDate budgetStart, QDate budgetEnd, const bool returnBudget )
{
  // clear all data except the id and name
  QString name = budget.name();
  budget = MyMoneyBudget(budget.id(), MyMoneyBudget());
  budget.setName(name);

  //check parameters
  if ( historyStart > historyEnd ||
       budgetStart > budgetEnd ||
       budgetStart <= historyEnd )
  {
    throw new MYMONEYEXCEPTION ( "Illegal parameters when trying to create budget" );
  }

  //get forecast method
  int fMethod = forecastMethod();

  //set start date to 1st of month and end dates to last day of month, since we deal with full months in budget
  historyStart = QDate ( historyStart.year(), historyStart.month(), 1 );
  historyEnd = QDate ( historyEnd.year(), historyEnd.month(), historyEnd.daysInMonth() );
  budgetStart = QDate ( budgetStart.year(), budgetStart.month(), 1 );
  budgetEnd = QDate ( budgetEnd.year(), budgetEnd.month(), budgetEnd.daysInMonth() );

  //set forecast parameters
  setHistoryStartDate ( historyStart );
  setHistoryEndDate ( historyEnd );
  setForecastStartDate ( budgetStart );
  setForecastEndDate ( budgetEnd );
  setForecastDays ( budgetStart.daysTo ( budgetEnd ) + 1 );
  if ( budgetStart.daysTo ( budgetEnd ) > historyStart.daysTo ( historyEnd ) ) { //if history period is shorter than budget, use that one as the trend length
    setAccountsCycle ( historyStart.daysTo ( historyEnd ) ); //we set the accountsCycle to the base timeframe we will use to calculate the average (eg. 180 days, 365, etc)
  } else { //if one timeframe is larger than the other, but not enough to be 1 time larger, we take the lowest value
    setAccountsCycle ( budgetStart.daysTo ( budgetEnd ) );
  }
  setForecastCycles ( ( historyStart.daysTo ( historyEnd ) / accountsCycle() ) );
  if ( forecastCycles() == 0 ) //the cycles must be at least 1
    setForecastCycles ( 1 );

  //do not skip opening date
  setSkipOpeningDate ( false );

  //clear and set accounts list we are going to use. Categories, in this case
  m_nameIdx.clear();
  setBudgetAccountList();

  //calculate budget according to forecast method
  switch(fMethod)
  {
    case eScheduled:
      doFutureScheduledForecast();
      calculateScheduledMonthlyBalances();
      break;
    case eHistoric:
      pastTransactions(); //get all transactions for history period
      calculateAccountTrendList();
      calculateHistoricMonthlyBalances(); //add all balances of each month and put at the 1st day of each month
      break;
    default:
      break;
  }

  //flag the forecast as done
  m_forecastDone = true;

  //only fill the budget if it is going to be used
  if ( returnBudget ) {
    //setup the budget itself
    MyMoneyFile* file = MyMoneyFile::instance();
    budget.setBudgetStart ( budgetStart );

    //go through all the accounts and add them to budget
    QMap<QString, QString>::ConstIterator it_nc;
    for ( it_nc = m_nameIdx.begin(); it_nc != m_nameIdx.end(); ++it_nc ) {
      MyMoneyAccount acc = file->account ( *it_nc );

      MyMoneyBudget::AccountGroup budgetAcc;
      budgetAcc.setId ( acc.id() );
      budgetAcc.setBudgetLevel ( MyMoneyBudget::AccountGroup::eMonthByMonth );

      for ( QDate f_date = forecastStartDate(); f_date <= forecastEndDate(); ) {
        MyMoneyBudget::PeriodGroup period;

        //add period to budget account
        period.setStartDate ( f_date );
        period.setAmount ( forecastBalance ( acc, f_date ) );
        budgetAcc.addPeriod ( f_date, period );

        //next month
        f_date = f_date.addMonths ( 1 );
      }
      //add budget account to budget
      budget.setAccount ( budgetAcc, acc.id() );
    }
  }
}
Exemple #30
0
NovelDialog::NovelDialog(const QString& novel, Database* data, QWidget* parent) :
	QDialog(parent),
	m_data(data),
	m_new(novel.isEmpty())
{
	// Create name widget
	m_name = new QLineEdit(this);
	connect(m_name, &QLineEdit::textChanged, this, &NovelDialog::checkAcceptAllowed);

	QHBoxLayout* name_layout = new QHBoxLayout;
	name_layout->addWidget(new QLabel(tr("Name:"), this));
	name_layout->addWidget(m_name);

	// Create goals widgets
	QGroupBox* goals = new QGroupBox(tr("Goals"), this);

	m_total = new QSpinBox(goals);
	m_total->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_total->setRange(0, 9999999);
	m_total->setSpecialValueText(tr("N/A"));

	m_daily = new QSpinBox(goals);
	m_daily->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_daily->setRange(0, 9999999);
	m_daily->setSpecialValueText(tr("N/A"));

	// Create date widgets
	QGroupBox* dates = new QGroupBox(tr("Date Range"), this);

	m_start = new QDateEdit(dates);
	m_start->setCalendarPopup(true);
	connect(m_start, &QDateEdit::dateChanged, this, &NovelDialog::checkAcceptAllowed);

	m_end = new QDateEdit(dates);
	m_end->setCalendarPopup(true);
	connect(m_end, &QDateEdit::dateChanged, this, &NovelDialog::checkAcceptAllowed);

	// Create word count widgets
	QGroupBox* wordcount = new QGroupBox(tr("Word Count"), this);

	m_start_value = new QSpinBox(wordcount);
	m_start_value->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_start_value->setRange(0, 9999999);

	// Create buttons
	QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
	m_accept = buttons->button(QDialogButtonBox::Ok);
	connect(buttons, &QDialogButtonBox::accepted, this, &NovelDialog::accept);
	connect(buttons, &QDialogButtonBox::rejected, this, &NovelDialog::reject);

	// Lay out window
	QFormLayout* goals_layout = new QFormLayout(goals);
	goals_layout->addRow(tr("Total:"), m_total);
	goals_layout->addRow(tr("Daily:"), m_daily);

	QFormLayout* dates_layout = new QFormLayout(dates);
	dates_layout->addRow(tr("Start On:"), m_start);
	dates_layout->addRow(tr("End On:"), m_end);

	QFormLayout* wordcount_layout = new QFormLayout(wordcount);
	wordcount_layout->addRow(tr("Start At:"), m_start_value);

	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->addLayout(name_layout);
	layout->addWidget(goals);
	layout->addWidget(dates);
	layout->addWidget(wordcount);
	layout->addStretch();
	layout->addWidget(buttons);

	resize(sizeHint().width() * 1.25, sizeHint().height());

	// Load values
	if (m_new) {
		setWindowTitle(tr("Add Novel"));
		m_accept->setEnabled(false);
		m_total->setValue(50000);
		m_daily->setValue(2000);
		m_start_value->setValue(0);
		QDate date = QDate::currentDate();
		m_start->setDate(QDate(date.year(), date.month(), 1));
		m_end->setDate(QDate(date.year(), date.month(), date.daysInMonth()));
	} else {
		setWindowTitle(tr("Edit Novel"));
		m_name->setText(novel);
		m_total->setValue(m_data->goal(Database::Total));
		m_daily->setValue(m_data->goal(Database::Daily));
		m_start_value->setValue(m_data->startValue());
		m_start->setDate(m_data->startDate());
		m_end->setDate(m_data->endDate());
	}
}