int weeks_between_dates(const QDate &date1, const QDate &date2) { const KCalendarSystem *calSys = KGlobal::locale()->calendar(); return (calSys->dayOfWeek(date1) - calSys->dayOfWeek(date2) + date1.daysTo(date2)) / 7; }
QArray<int> OContactAccessBackend_XML::queryByExample ( const OContact &query, int settings, const QDateTime& d ) { QArray<int> m_currentQuery( m_contactList.count() ); QListIterator<OContact> it( m_contactList ); uint arraycounter = 0; for( ; it.current(); ++it ){ /* Search all fields and compare them with query object. Store them into list * if all fields matches. */ QDate* queryDate = 0l; QDate* checkDate = 0l; bool allcorrect = true; for ( int i = 0; i < Qtopia::Groups; i++ ) { // Birthday and anniversary are special nonstring fields and should // be handled specially switch ( i ){ case Qtopia::Birthday: queryDate = new QDate( query.birthday() ); checkDate = new QDate( (*it)->birthday() ); case Qtopia::Anniversary: if ( queryDate == 0l ){ queryDate = new QDate( query.anniversary() ); checkDate = new QDate( (*it)->anniversary() ); } if ( queryDate->isValid() ){ if( checkDate->isValid() ){ if ( settings & OContactAccess::DateYear ){ if ( queryDate->year() != checkDate->year() ) allcorrect = false; } if ( settings & OContactAccess::DateMonth ){ if ( queryDate->month() != checkDate->month() ) allcorrect = false; } if ( settings & OContactAccess::DateDay ){ if ( queryDate->day() != checkDate->day() ) allcorrect = false; } if ( settings & OContactAccess::DateDiff ) { QDate current; // If we get an additional date, we // will take this date instead of // the current one.. if ( !d.date().isValid() ) current = QDate::currentDate(); else current = d.date(); // We have to equalize the year, otherwise // the search will fail.. checkDate->setYMD( current.year(), checkDate->month(), checkDate->day() ); if ( *checkDate < current ) checkDate->setYMD( current.year()+1, checkDate->month(), checkDate->day() ); // Check whether the birthday/anniversary date is between // the current/given date and the maximum date // ( maximum time range ) ! qWarning("Checking if %s is between %s and %s ! ", checkDate->toString().latin1(), current.toString().latin1(), queryDate->toString().latin1() ); if ( current.daysTo( *queryDate ) >= 0 ){ if ( !( ( *checkDate >= current ) && ( *checkDate <= *queryDate ) ) ){ allcorrect = false; qWarning (" Nope!.."); } } } } else{ // checkDate is invalid. Therefore this entry is always rejected allcorrect = false; } } delete queryDate; queryDate = 0l; delete checkDate; checkDate = 0l; break; default: /* Just compare fields which are not empty in the query object */ if ( !query.field(i).isEmpty() ){ switch ( settings & ~( OContactAccess::IgnoreCase | OContactAccess::DateDiff | OContactAccess::DateYear | OContactAccess::DateMonth | OContactAccess::DateDay | OContactAccess::MatchOne ) ){ case OContactAccess::RegExp:{ QRegExp expr ( query.field(i), !(settings & OContactAccess::IgnoreCase), false ); if ( expr.find ( (*it)->field(i), 0 ) == -1 ) allcorrect = false; } break; case OContactAccess::WildCards:{ QRegExp expr ( query.field(i), !(settings & OContactAccess::IgnoreCase), true ); if ( expr.find ( (*it)->field(i), 0 ) == -1 ) allcorrect = false; } break; case OContactAccess::ExactMatch:{ if (settings & OContactAccess::IgnoreCase){ if ( query.field(i).upper() != (*it)->field(i).upper() ) allcorrect = false; }else{ if ( query.field(i) != (*it)->field(i) ) allcorrect = false; } } break; } } } } if ( allcorrect ){ m_currentQuery[arraycounter++] = (*it)->uid(); } } // Shrink to fit.. m_currentQuery.resize(arraycounter); return m_currentQuery; }
// export history report as csv, all tasks X all dates in one block QString timetrackerstorage::exportcsvHistory (TaskView *taskview, const QDate &from, const QDate &to, const ReportCriteria &rc) { kDebug(5970) << "Entering function"; QString delim = rc.delimiter; const QString cr = QString::fromLatin1("\n"); QString err=QString::null; QString retval; Task* task; const int intervalLength = from.daysTo(to)+1; QMap< QString, QVector<int> > secsForUid; QMap< QString, QString > uidForName; // Step 1: Prepare two hashmaps: // * "uid -> seconds each day": used while traversing events, as uid is their id // "seconds each day" are stored in a vector // * "name -> uid", ordered by name: used when creating the csv file at the end kDebug(5970) << "Taskview Count: " << taskview->count(); for ( int n=0; n<taskview->count(); n++ ) { task=taskview->itemAt(n); kDebug(5970) << "n: " << n << ", Task Name: " << task->name() << ", UID: " << task->uid(); // uid -> seconds each day // * Init each element to zero QVector<int> vector(intervalLength, 0); secsForUid[task->uid()] = vector; // name -> uid // * Create task fullname concatenating each parent's name QString fullName; Task* parentTask; parentTask = task; fullName += parentTask->name(); parentTask = parentTask->parent(); while (parentTask) { fullName = parentTask->name() + "->" + fullName; kDebug(5970) << "Fullname(inside): " << fullName; parentTask = parentTask->parent(); kDebug(5970) << "Parent task: " << parentTask; } uidForName[fullName] = task->uid(); kDebug(5970) << "Fullname(end): " << fullName; } kDebug(5970) << "secsForUid" << secsForUid; kDebug(5970) << "uidForName" << uidForName; // Step 2: For each date, get the events and calculate the seconds // Store the seconds using secsForUid hashmap, so we don't need to translate uids // We rely on rawEventsForDate to get the events kDebug(5970) << "Let's iterate for each date: "; for ( QDate mdate=from; mdate.daysTo(to)>=0; mdate=mdate.addDays(1) ) { kDebug(5970) << mdate.toString(); KCalCore::Event::List dateEvents = d->mCalendar->rawEventsForDate(mdate); for(KCalCore::Event::List::iterator i = dateEvents.begin();i != dateEvents.end(); ++i) { kDebug(5970) << "Summary: " << (*i)->summary() << ", Related to uid: " << (*i)->relatedTo(); kDebug(5970) << "Today's seconds: " << todaySeconds(mdate, *i); secsForUid[(*i)->relatedTo()][from.daysTo(mdate)] += todaySeconds(mdate, *i); } } // Step 3: For each task, generate the matching row for the CSV file // We use the two hashmaps to have direct access using the task name // First CSV file line // FIXME: localize strings and date formats retval.append("\"Task name\""); for (int i=0; i<intervalLength; i++) { retval.append(delim); retval.append(from.addDays(i).toString()); } retval.append(cr); // Rest of the CSV file QMapIterator<QString, QString> nameUid(uidForName); double time; while (nameUid.hasNext()) { nameUid.next(); retval.append("\"" + nameUid.key() + "\""); kDebug(5970) << nameUid.key() << ": " << nameUid.value() << endl; for (int day=0; day<intervalLength; day++) { kDebug(5970) << "Secs for day " << day << ":" << secsForUid[nameUid.value()][day]; retval.append(delim); time = secsForUid[nameUid.value()][day]/60.0; retval.append(formatTime(time, rc.decimalMinutes)); } retval.append(cr); } kDebug() << "Retval is \n" << retval; if (rc.bExPortToClipBoard) taskview->setClipBoardText(retval); else { // store the file locally or remote if ((rc.url.isLocalFile()) || (!rc.url.url().contains("/"))) { kDebug(5970) << "storing a local file"; QString filename=rc.url.toLocalFile(); if (filename.isEmpty()) filename=rc.url.url(); QFile f( filename ); if( !f.open( QIODevice::WriteOnly ) ) { err = i18n( "Could not open \"%1\".", filename ); kDebug(5970) << "Could not open file"; } kDebug() << "Err is " << err; if (err.length()==0) { QTextStream stream(&f); kDebug(5970) << "Writing to file: " << retval; // Export to file stream << retval; f.close(); } } else // use remote file { KTemporaryFile tmpFile; if ( !tmpFile.open() ) { err = QString::fromLatin1( "Unable to get temporary file" ); } else { QTextStream stream ( &tmpFile ); stream << retval; stream.flush(); if (!KIO::NetAccess::upload( tmpFile.fileName(), rc.url, 0 )) err=QString::fromLatin1("Could not upload"); } } } return err; }
int QtDate::daysTo(const QDate &from, const QDate &to) { return from.daysTo(to); }
static int yearsBetween( const QDate & d1, const QDate & d2 ) { const int days = d1.daysTo( d2 ); return qRound( days / DAYS_IN_GREGORIAN_YEAR ); }
void KMyMoneyBriefSchedule::loadSchedule() { try { if (m_index < m_scheduleList.count()) { MyMoneySchedule sched = m_scheduleList[m_index]; m_indexLabel->setText(i18n("%1 of %2", m_index + 1, m_scheduleList.count())); m_name->setText(sched.name()); m_type->setText(KMyMoneyUtils::scheduleTypeToString(sched.type())); m_account->setText(sched.account().name()); QString text; MyMoneyMoney amount = sched.transaction().splitByAccount(sched.account().id()).value(); amount = amount.abs(); if (sched.willEnd()) { int transactions = sched.paymentDates(m_date, sched.endDate()).count() - 1; text = i18np("Payment on %2 for %3 with %1 transaction remaining occurring %4.", "Payment on %2 for %3 with %1 transactions remaining occurring %4.", transactions, KGlobal::locale()->formatDate(m_date), amount.formatMoney(sched.account().fraction()), i18n(sched.occurrenceToString().toLatin1())); } else { text = i18n("Payment on %1 for %2 occurring %3.", KGlobal::locale()->formatDate(m_date), amount.formatMoney(sched.account().fraction()), i18n(sched.occurrenceToString().toLatin1())); } if (m_date < QDate::currentDate()) { if (sched.isOverdue()) { QDate startD = (sched.lastPayment().isValid()) ? sched.lastPayment() : sched.startDate(); if (m_date.isValid()) startD = m_date; int days = startD.daysTo(QDate::currentDate()); int transactions = sched.paymentDates(startD, QDate::currentDate()).count(); text += "<br><font color=red>"; text += i18np("%1 day overdue", "%1 days overdue", days); text += QString(" "); text += i18np("(%1 occurrence.)", "(%1 occurrences.)", transactions); text += "</color>"; } } m_details->setText(text); m_prevButton->setEnabled(true); m_nextButton->setEnabled(true); m_skipButton->setEnabled(sched.occurrencePeriod() != MyMoneySchedule::OCCUR_ONCE); if (m_index == 0) m_prevButton->setEnabled(false); if (m_index == (m_scheduleList.count() - 1)) m_nextButton->setEnabled(false); } } catch (const MyMoneyException &) { } }
int Tools::daysTo(const QDate &from, const QDate &to) { return from.daysTo(to); }
void MainWindow::on_pushButton_2_clicked() { if(ui->B_NIO->text().isEmpty() || ui->S_NO->text().isEmpty()){ QMessageBox::warning(this,tr("提示"),tr("不能为空"),QMessageBox::Ok); ui->B_NIO->clear(); ui->S_NO->clear(); return; } QSqlQuery query; QString s_num=""; QString b_num=""; QString o_name=""; QString o_author=""; QString o_price =""; QString s_name=""; QString b_id=""; query.prepare("select C_NUM from COUNT where C_NO = :uid"); query.bindValue(":uid",ui->S_NO->text()); query.exec(); if(query.next()){ s_num = query.value(0).toString(); } query.prepare("select * from BOOKS where O_ISBN = :bid"); query.bindValue(":bid",ui->B_NIO->text()); query.exec(); if(query.next()){ o_name = query.value(1).toString(); o_author = query.value(2).toString(); o_price = query.value(4).toString(); b_num = query.value(5).toString(); } qDebug()<<s_num<<b_num; query.prepare("SELECT S_NAME FROM STUDENTS WHERE S_NO = ?"); query.addBindValue(ui->S_NO->text()); query.exec(); if(query.next()){ s_name = query.value(0).toString(); qDebug()<<s_name; } if(s_num.isEmpty()){ QMessageBox::warning(this,tr("提示"),tr("输入学号错误"),QMessageBox::Ok); ui->B_NIO->clear(); ui->S_NO->clear(); return; } if(b_num.isEmpty()){ QMessageBox::warning(this,tr("提示"),tr("输入ISBN错误"),QMessageBox::Ok); ui->B_NIO->clear(); ui->S_NO->clear(); return; } int ss_num=s_num.toInt(); int bb_num=b_num.toInt(); ++bb_num; ++ss_num; qDebug()<<ss_num<<bb_num; query.prepare("UPDATE BOOKS SET O_STORAGE = ? WHERE O_ISBN = ?"); query.addBindValue(QString::number(bb_num,10)); query.addBindValue(ui->B_NIO->text()); query.exec(); query.prepare("UPDATE COUNT SET C_NUM = ? WHERE C_NO = ?"); query.addBindValue(QString::number(ss_num,10)); query.addBindValue(ui->S_NO->text()); query.exec(); QDate date; QDate oldDate; QString oldDatetem; date=date.currentDate(); QString newdate=date.toString("yyyy.M.d"); qDebug()<<newdate; int countI = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(countI); ui->tableWidget->setItem(countI,0,new QTableWidgetItem(ui->S_NO->text())); ui->tableWidget->setItem(countI,1,new QTableWidgetItem(s_name)); ui->tableWidget->setItem(countI,2,new QTableWidgetItem(ui->B_NIO->text())); ui->tableWidget->setItem(countI,3,new QTableWidgetItem(o_name)); ui->tableWidget->setItem(countI,4,new QTableWidgetItem(o_author)); ui->tableWidget->setItem(countI,5,new QTableWidgetItem(o_price)); ui->tableWidget->setItem(countI,6,new QTableWidgetItem(QString(tr("还回")))); ui->tableWidget->setItem(countI,8,new QTableWidgetItem(newdate)); query.prepare("SELECT B_ID,B_TIME FROM BORROW WHERE B_NO = ? AND B_ISBN = ? AND B_ISRENT = 0"); query.addBindValue(ui->S_NO->text()); query.addBindValue(ui->B_NIO->text()); query.exec(); if(query.first()){ b_id = query.value(0).toString(); oldDatetem = query.value(1).toString(); oldDatetem.replace(QString("-"),QString("")); qDebug()<<b_id<<oldDatetem; } query.prepare("UPDATE BORROW SET B_ISRENT=?,B_RENTTIME=? WHERE B_ID = ?"); query.addBindValue(1); query.addBindValue(newdate); query.addBindValue(b_id); query.exec(); oldDate=oldDate.fromString(oldDatetem,"yyyyMMdd"); qDebug()<<oldDate.toString("yyyy.M.d"); int timeforBorrow = oldDate.daysTo(date); if(timeforBorrow > 30){ qDebug()<<timeforBorrow; QString temOfMessage=QString(tr("超期 %1 天")).arg((timeforBorrow-30)); QMessageBox::information(this,tr("提示"),temOfMessage,QMessageBox::Ok); return; } query.clear(); }
bool PSV_Public::getLabels(QVariant &maxValue, QVariant &minValue, QPair<double, double> &range, QList<QPair<QVariant, QString> > &labelList) { if(maxValue.type() != minValue.type()) { return false; } QVariant::Type type = maxValue.type(); switch(type) { case QVariant::Double: case QVariant::Int: case QVariant::UInt: { double max = maxValue.toDouble(); double min = minValue.toDouble(); int numTick = getNumTicks(max, min); if(numTick <= 0) { return false; } adjustRange(max, min); labelList.clear(); for(int i = 0; i <= numTick; ++i) { double value = min + 1.0 * (max - min) * i / numTick; QString str = QObject::tr("%1").arg(value); labelList.append(QPair<QVariant, QString>(value, str)); } maxValue = max; minValue = min; range = QPair<double,double>(min,max); return true; } break; case QVariant::Date: { QDate maxDate = maxValue.toDate(); QDate minDate = minValue.toDate(); bool isOk = getDateLabels(maxDate, minDate, labelList); maxValue = maxDate; minValue = minDate; range = QPair<double,double>(0.0, 1.0 * minDate.daysTo(maxDate)); return isOk; } break; case QVariant::Time: { QTime maxTime = maxValue.toTime(); QTime minTime = minValue.toTime(); bool isOk = getTimeLabels(maxTime, minTime, labelList); maxValue = maxTime; minValue = minTime; range = QPair<double,double>(0.0, 86400.0/*1.0 * minTime.secsTo(maxTime)*/); return isOk; } break; case QVariant::DateTime: { QDateTime maxTime = maxValue.toDateTime(); QDateTime minTime = minValue.toDateTime(); // PSV_Public::printMes(maxTime,"1maxTime"); // PSV_Public::printMes(minTime,"1minTime"); bool isOk = getDateTimeLabels(maxTime, minTime, labelList); maxValue = maxTime; minValue = minTime; // PSV_Public::printMes(maxTime,"2maxTime"); // PSV_Public::printMes(minTime,"2minTime"); range = QPair<double,double>(PSV_BEGIN_DATETIME.secsTo(minValue.toDateTime()),PSV_BEGIN_DATETIME.secsTo(maxValue.toDateTime())); return isOk; } break; default: break; } return false; }
/** \brief Returns a readable age calculated from the date to now */ int ageYears(const QDate &DOB) { int daysTo = DOB.daysTo(QDate::currentDate()); double age = daysTo / 365.242199; return (int)age; }
bool PSV_Public::getDateLabels(QDate &maxDate, QDate &minDate, QList<QPair<QVariant, QString> > &labelList) { labelList.clear(); int maxNum = 31; int days = minDate.daysTo(maxDate); if(days < 0) { days = -days; qSwap(maxDate, minDate); } int min_year = minDate.year(); int min_month = minDate.month(); int max_year = maxDate.year(); int max_month = maxDate.month(); QDate beginDate = QDate(1970, 1, 1); QString dateFormat = ""; if(days <= maxNum) { if(min_year == max_year) { dateFormat = QString::fromLocal8Bit("MM月dd日"); } else { dateFormat = QString::fromLocal8Bit("yyyy年MM月dd日"); } int min_days = beginDate.daysTo(minDate); int max_days = beginDate.daysTo(maxDate); if(min_days >= max_days) { max_days = max_days + 1; min_days = min_days - 1; } for(int i = min_days; i <= max_days; ++i) { QDate tempDate = beginDate.addDays(i); labelList.append(QPair<QVariant, QString>(tempDate, tempDate.toString(dateFormat))); } // m_min_x = min_days; // m_max_x = max_days; } else { int interval = 1; dateFormat = QString::fromLocal8Bit("yyyy年MM月"); int years = max_year - min_year; if(years <= 1) { interval = 1; } else if( years <= 2) { interval = 2; } else if(years <= 3) { interval = 3; } else if(years <= 5) { interval = 6; } else { dateFormat = QString::fromLocal8Bit("yyyy年"); interval = 12; } int tempMonth = 1; int beginMonth =1; do { beginMonth = tempMonth; tempMonth += interval; }while(tempMonth <= min_month); min_month = beginMonth; QDate minDate = QDate(min_year, min_month, 1); QDate maxDate = QDate(max_year, max_month, 1).addMonths(1).addDays(-1); QDate tempDate = minDate; labelList.append(QPair<QVariant, QString>(tempDate, tempDate.toString(dateFormat))); do { tempDate = tempDate.addMonths(interval); labelList.append(QPair<QVariant, QString>(tempDate, tempDate.toString(dateFormat))); }while(maxDate.daysTo(tempDate) <= 0); } if(labelList.count() >= 2) { minDate = labelList.at(0).first.toDate(); maxDate = labelList.at(labelList.count() - 1).first.toDate().addDays(-1); return true; } return false; }
/*! Align a date/time value for a step size For Qt::Day alignments there is no "natural day 0" - instead the first day of the year is used to avoid jumping major ticks positions when panning a scale. For other alignments ( f.e according to the first day of the month ) alignDate() has to be overloaded. \param dateTime Date/time value \param stepSize Step size \param intervalType Interval type \param up When true dateTime is ceiled - otherwise it is floored \return Aligned date/time value */ QDateTime QwtDateScaleEngine::alignDate( const QDateTime &dateTime, double stepSize, QwtDate::IntervalType intervalType, bool up ) const { // what about: (year == 1582 && month == 10 && day > 4 && day < 15) ?? QDateTime dt = dateTime; if ( dateTime.timeSpec() == Qt::OffsetFromUTC ) { dt.setUtcOffset( 0 ); } switch( intervalType ) { case QwtDate::Millisecond: { const int ms = qwtAlignValue( dt.time().msec(), stepSize, up ) ; dt = QwtDate::floor( dateTime, QwtDate::Second ); dt = dt.addMSecs( ms ); break; } case QwtDate::Second: { int second = dt.time().second(); if ( up ) { if ( dt.time().msec() > 0 ) second++; } const int s = qwtAlignValue( second, stepSize, up ); dt = QwtDate::floor( dt, QwtDate::Minute ); dt = dt.addSecs( s ); break; } case QwtDate::Minute: { int minute = dt.time().minute(); if ( up ) { if ( dt.time().msec() > 0 || dt.time().second() > 0 ) minute++; } const int m = qwtAlignValue( minute, stepSize, up ); dt = QwtDate::floor( dt, QwtDate::Hour ); dt = dt.addSecs( m * 60 ); break; } case QwtDate::Hour: { int hour = dt.time().hour(); if ( up ) { if ( dt.time().msec() > 0 || dt.time().second() > 0 || dt.time().minute() > 0 ) { hour++; } } const int h = qwtAlignValue( hour, stepSize, up ); dt = QwtDate::floor( dt, QwtDate::Day ); dt = dt.addSecs( h * 3600 ); break; } case QwtDate::Day: { // What date do we expect f.e. from an alignment of 5 days ?? // Aligning them to the beginning of the year avoids at least // jumping major ticks when panning int day = dt.date().dayOfYear(); if ( up ) { if ( dt.time() > QTime( 0, 0 ) ) day++; } const int d = qwtAlignValue( day, stepSize, up ); dt = QwtDate::floor( dt, QwtDate::Year ); dt = dt.addDays( d - 1 ); break; } case QwtDate::Week: { const QDate date = QwtDate::dateOfWeek0( dt.date().year(), d_data->week0Type ); int numWeeks = date.daysTo( dt.date() ) / 7; if ( up ) { if ( dt.time() > QTime( 0, 0 ) || date.daysTo( dt.date() ) % 7 ) { numWeeks++; } } const int d = qwtAlignValue( numWeeks, stepSize, up ) * 7; dt = QwtDate::floor( dt, QwtDate::Day ); dt.setDate( date ); dt = dt.addDays( d ); break; } case QwtDate::Month: { int month = dt.date().month(); if ( up ) { if ( dt.date().day() > 1 || dt.time() > QTime( 0, 0 ) ) { month++; } } const int m = qwtAlignValue( month - 1, stepSize, up ); dt = QwtDate::floor( dt, QwtDate::Year ); dt = dt.addMonths( m ); break; } case QwtDate::Year: { int year = dateTime.date().year(); if ( up ) { if ( dateTime.date().dayOfYear() > 1 || dt.time() > QTime( 0, 0 ) ) { year++; } } const int y = qwtAlignValue( year, stepSize, up ); dt = QwtDate::floor( dt, QwtDate::Day ); if ( y == 0 ) { // there is no year 0 in the Julian calendar dt.setDate( QDate( stepSize, 1, 1 ).addYears( -stepSize ) ); } else { dt.setDate( QDate( y, 1, 1 ) ); } break; } } if ( dateTime.timeSpec() == Qt::OffsetFromUTC ) { dt.setUtcOffset( dateTime.utcOffset() ); } return dt; }
int FLUtil::daysTo( const QDate &d1, const QDate &d2 ) { return d1.daysTo( d2 ); }
bool CPerson::birthdayIsFuture(void) const{ QDate date = QDate::currentDate(); QDate birthday = QDate::fromString(geburtstag,"yyyy-MM-dd"); return (date.daysTo(birthday) > 0); }
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; }
QgsInterval operator-( QDate date1, QDate date2 ) { qint64 seconds = static_cast< qint64 >( date2.daysTo( date1 ) ) * 24 * 60 * 60; return QgsInterval( seconds ); }
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); } }
/** \fn FillData::Run(SourceList &sourcelist) * \brief Goes through the sourcelist and updates its channels with * program info grabbed with the associated grabber. * \return true if there were no failures */ bool FillData::Run(SourceList &sourcelist) { SourceList::iterator it; SourceList::iterator it2; QString status, querystr; MSqlQuery query(MSqlQuery::InitCon()); QDateTime GuideDataBefore, GuideDataAfter; int failures = 0; int externally_handled = 0; int total_sources = sourcelist.size(); int source_channels = 0; QString sidStr = QString("Updating source #%1 (%2) with grabber %3"); m_need_post_grab_proc = false; int nonewdata = 0; for (it = sourcelist.begin(); it != sourcelist.end(); ++it) { if (!m_fatalErrors.empty()) break; QString xmltv_grabber = (*it).xmltvgrabber; if (xmltv_grabber == "datadirect" || xmltv_grabber == "schedulesdirect1") { LOG(VB_GENERAL, LOG_ERR, QString("Source %1 is configured to use the DataDirect guide" "service from Schedules Direct. That service is no " "longer supported by MythTV. Update to use one of " "the XMLTV grabbers that use the JSON-based guide " "service from Schedules Direct.") .arg((*it).id)); continue; } query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c " "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID " "AND manualid = 0 AND c.xmltvid != '';"); query.bindValue(":SRCID", (*it).id); if (query.exec() && query.next()) { if (!query.isNull(0)) GuideDataBefore = MythDate::fromString(query.value(0).toString()); } m_channel_update_run = false; m_endofdata = false; if (xmltv_grabber == "eitonly") { LOG(VB_GENERAL, LOG_INFO, QString("Source %1 configured to use only the " "broadcasted guide data. Skipping.") .arg((*it).id)); externally_handled++; updateLastRunStart(); updateLastRunEnd(); continue; } else if (xmltv_grabber.trimmed().isEmpty() || xmltv_grabber == "/bin/true" || xmltv_grabber == "none") { LOG(VB_GENERAL, LOG_INFO, QString("Source %1 configured with no grabber. Nothing to do.") .arg((*it).id)); externally_handled++; updateLastRunStart(); updateLastRunEnd(); continue; } LOG(VB_GENERAL, LOG_INFO, sidStr.arg((*it).id) .arg((*it).name) .arg(xmltv_grabber)); query.prepare( "SELECT COUNT(chanid) FROM channel WHERE sourceid = " ":SRCID AND xmltvid != ''"); query.bindValue(":SRCID", (*it).id); if (query.exec() && query.next()) { source_channels = query.value(0).toInt(); if (source_channels > 0) { LOG(VB_GENERAL, LOG_INFO, QString("Found %1 channels for source %2 which use grabber") .arg(source_channels).arg((*it).id)); } else { LOG(VB_GENERAL, LOG_INFO, QString("No channels are configured to use grabber.")); } } else { source_channels = 0; LOG(VB_GENERAL, LOG_INFO, QString("Can't get a channel count for source id %1") .arg((*it).id)); } bool hasprefmethod = false; if (is_grabber_external(xmltv_grabber)) { uint flags = kMSRunShell | kMSStdOut; MythSystemLegacy grabber_capabilities_proc(xmltv_grabber, QStringList("--capabilities"), flags); grabber_capabilities_proc.Run(25); if (grabber_capabilities_proc.Wait() != GENERIC_EXIT_OK) LOG(VB_GENERAL, LOG_ERR, QString("%1 --capabilities failed or we timed out waiting." " You may need to upgrade your xmltv grabber") .arg(xmltv_grabber)); else { QByteArray result = grabber_capabilities_proc.ReadAll(); QTextStream ostream(result); QString capabilities; while (!ostream.atEnd()) { QString capability = ostream.readLine().simplified(); if (capability.isEmpty()) continue; capabilities += capability + ' '; if (capability == "baseline") (*it).xmltvgrabber_baseline = true; if (capability == "manualconfig") (*it).xmltvgrabber_manualconfig = true; if (capability == "cache") (*it).xmltvgrabber_cache = true; if (capability == "preferredmethod") hasprefmethod = true; } LOG(VB_GENERAL, LOG_INFO, QString("Grabber has capabilities: %1") .arg(capabilities)); } } if (hasprefmethod) { uint flags = kMSRunShell | kMSStdOut; MythSystemLegacy grabber_method_proc(xmltv_grabber, QStringList("--preferredmethod"), flags); grabber_method_proc.Run(15); if (grabber_method_proc.Wait() != GENERIC_EXIT_OK) LOG(VB_GENERAL, LOG_ERR, QString("%1 --preferredmethod failed or we timed out " "waiting. You may need to upgrade your xmltv " "grabber").arg(xmltv_grabber)); else { QTextStream ostream(grabber_method_proc.ReadAll()); (*it).xmltvgrabber_prefmethod = ostream.readLine().simplified(); LOG(VB_GENERAL, LOG_INFO, QString("Grabber prefers method: %1") .arg((*it).xmltvgrabber_prefmethod)); } } m_need_post_grab_proc |= true; if ((*it).xmltvgrabber_prefmethod == "allatonce" && !m_no_allatonce) { if (!GrabData(*it, 0)) ++failures; } else if ((*it).xmltvgrabber_baseline) { QDate qCurrentDate = MythDate::current().date(); // We'll keep grabbing until it returns nothing // Max days currently supported is 21 int grabdays = REFRESH_MAX; grabdays = (m_maxDays > 0) ? m_maxDays : grabdays; grabdays = (m_only_update_channels) ? 1 : grabdays; vector<bool> refresh_request; refresh_request.resize(grabdays, m_refresh_all); if (!m_refresh_all) // Set up days to grab if all is not specified // If all was specified the vector was initialized // with true in all occurrences. for (int i = 0; i < grabdays; i++) refresh_request[i] = m_refresh_day[i]; for (int i = 0; i < grabdays; i++) { if (!m_fatalErrors.empty()) break; // We need to check and see if the current date has changed // since we started in this loop. If it has, we need to adjust // the value of 'i' to compensate for this. if (MythDate::current().date() != qCurrentDate) { QDate newDate = MythDate::current().date(); i += (newDate.daysTo(qCurrentDate)); if (i < 0) i = 0; qCurrentDate = newDate; } QString prevDate(qCurrentDate.addDays(i-1).toString()); QString currDate(qCurrentDate.addDays(i).toString()); LOG(VB_GENERAL, LOG_INFO, ""); // add a space between days LOG(VB_GENERAL, LOG_INFO, "Checking day @ " + QString("offset %1, date: %2").arg(i).arg(currDate)); bool download_needed = false; if (refresh_request[i]) { if ( i == 1 ) { LOG(VB_GENERAL, LOG_INFO, "Data Refresh always needed for tomorrow"); } else { LOG(VB_GENERAL, LOG_INFO, "Data Refresh needed because of user request"); } download_needed = true; } else { // Check to see if we already downloaded data for this date. querystr = "SELECT c.chanid, COUNT(p.starttime) " "FROM channel c " "LEFT JOIN program p ON c.chanid = p.chanid " " AND starttime >= " "DATE_ADD(DATE_ADD(CURRENT_DATE(), " "INTERVAL '%1' DAY), INTERVAL '20' HOUR) " " AND starttime < DATE_ADD(CURRENT_DATE(), " "INTERVAL '%2' DAY) " "WHERE c.sourceid = %3 AND c.xmltvid != '' " "GROUP BY c.chanid;"; if (query.exec(querystr.arg(i-1).arg(i).arg((*it).id)) && query.isActive()) { int prevChanCount = 0; int currentChanCount = 0; int previousDayCount = 0; int currentDayCount = 0; LOG(VB_CHANNEL, LOG_INFO, QString("Checking program counts for day %1") .arg(i-1)); while (query.next()) { if (query.value(1).toInt() > 0) prevChanCount++; previousDayCount += query.value(1).toInt(); LOG(VB_CHANNEL, LOG_INFO, QString(" chanid %1 -> %2 programs") .arg(query.value(0).toString()) .arg(query.value(1).toInt())); } if (query.exec(querystr.arg(i).arg(i+1).arg((*it).id)) && query.isActive()) { LOG(VB_CHANNEL, LOG_INFO, QString("Checking program counts for day %1") .arg(i)); while (query.next()) { if (query.value(1).toInt() > 0) currentChanCount++; currentDayCount += query.value(1).toInt(); LOG(VB_CHANNEL, LOG_INFO, QString(" chanid %1 -> %2 programs") .arg(query.value(0).toString()) .arg(query.value(1).toInt())); } } else { LOG(VB_GENERAL, LOG_INFO, QString("Data Refresh because we are unable to " "query the data for day %1 to " "determine if we have enough").arg(i)); download_needed = true; } if (currentChanCount < (prevChanCount * 0.90)) { LOG(VB_GENERAL, LOG_INFO, QString("Data refresh needed because only %1 " "out of %2 channels have at least one " "program listed for day @ offset %3 " "from 8PM - midnight. Previous day " "had %4 channels with data in that " "time period.") .arg(currentChanCount).arg(source_channels) .arg(i).arg(prevChanCount)); download_needed = true; } else if (currentDayCount == 0) { LOG(VB_GENERAL, LOG_INFO, QString("Data refresh needed because no data " "exists for day @ offset %1 from 8PM - " "midnight.").arg(i)); download_needed = true; } else if (previousDayCount == 0) { LOG(VB_GENERAL, LOG_INFO, QString("Data refresh needed because no data " "exists for day @ offset %1 from 8PM - " "midnight. Unable to calculate how " "much we should have for the current " "day so a refresh is being forced.") .arg(i-1)); download_needed = true; } else if (currentDayCount < (currentChanCount * 3)) { LOG(VB_GENERAL, LOG_INFO, QString("Data Refresh needed because offset " "day %1 has less than 3 programs " "per channel for the 8PM - midnight " "time window for channels that " "normally have data. " "We want at least %2 programs, but " "only found %3") .arg(i).arg(currentChanCount * 3) .arg(currentDayCount)); download_needed = true; } else if (currentDayCount < (previousDayCount / 2)) { LOG(VB_GENERAL, LOG_INFO, QString("Data Refresh needed because offset " "day %1 has less than half the number " "of programs as the previous day for " "the 8PM - midnight time window. " "We want at least %2 programs, but " "only found %3").arg(i) .arg(previousDayCount / 2) .arg(currentDayCount)); download_needed = true; } } else { LOG(VB_GENERAL, LOG_INFO, QString("Data Refresh needed because we are unable " "to query the data for day @ offset %1 to " "determine how much we should have for " "offset day %2.").arg(i-1).arg(i)); download_needed = true; } } if (download_needed) { LOG(VB_GENERAL, LOG_NOTICE, QString("Refreshing data for ") + currDate); if (!GrabData(*it, i)) { ++failures; if (!m_fatalErrors.empty() || m_interrupted) { break; } } if (m_endofdata) { LOG(VB_GENERAL, LOG_INFO, "Grabber is no longer returning program data, " "finishing"); break; } } else { LOG(VB_GENERAL, LOG_NOTICE, QString("Data is already present for ") + currDate + ", skipping"); } } if (!m_fatalErrors.empty()) break; } else { LOG(VB_GENERAL, LOG_ERR, QString("Grabbing XMLTV data using ") + xmltv_grabber + " is not supported. You may need to upgrade to" " the latest version of XMLTV."); } if (m_interrupted) { break; } query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c " "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID " "AND manualid = 0 AND c.xmltvid != '';"); query.bindValue(":SRCID", (*it).id); if (query.exec() && query.next()) { if (!query.isNull(0)) GuideDataAfter = MythDate::fromString(query.value(0).toString()); } if (GuideDataAfter == GuideDataBefore) { nonewdata++; } } if (!m_fatalErrors.empty()) { for (int i = 0; i < m_fatalErrors.size(); i++) { LOG(VB_GENERAL, LOG_CRIT, LOC + "Encountered Fatal Error: " + m_fatalErrors[i]); } return false; } if (m_only_update_channels && !m_need_post_grab_proc) return true; if (failures == 0) { if (nonewdata > 0 && (total_sources != externally_handled)) status = QObject::tr( "mythfilldatabase ran, but did not insert " "any new data into the Guide for %1 of %2 sources. " "This can indicate a potential grabber failure.") .arg(nonewdata) .arg(total_sources); else status = QObject::tr("Successful."); updateLastRunStatus(status); } return (failures == 0); }
/** * getCustomerAgingData() * * Utility function that returns the AR Aging data * for the specified customer ID. * * currentBalance = The customer's current balance, including all charges and payments * totalOverdue = What portion of the currentBalance is overdue * currentDue = What portion of the currentBalance is not overdue * overdue = Amount overdue between 0 and 30 days * overdue30 = Amunt overdue between 31 and 60 days * overdue60 = Amount overdue between 61 and 90 days * overdue90 = Amount overdue 91 days or greater. */ const customerARAgingRecord getCustomerAgingData(long custID) { customerARAgingRecord retVal; ADB DB; // Set our return values retVal.customerID = 0; retVal.currentBalance = 0.00; retVal.totalOverdue = 0.00; retVal.currentDue = 0.00; retVal.overdue = 0.00; retVal.overdue30 = 0.00; retVal.overdue60 = 0.00; retVal.overdue90 = 0.00; DB.query("select CurrentBalance from Customers where CustomerID = %ld", custID); if (!DB.rowCount) return retVal; DB.getrow(); retVal.customerID = custID; retVal.currentBalance = atof(DB.curRow["CurrentBalance"]); if (retVal.currentBalance == 0.00) return retVal; // If we've made it here, we have a customer with a balance QDate today = QDate::currentDate(); QDate dueDate = QDate::currentDate(); QString dueDateSt; DB.query("select Amount, ClearedAmount, DueDate from AcctsRecv where CustomerID = %ld and DueDate <> '0000-00-00' and ClearedAmount <> Amount", custID); if (DB.rowCount) while (DB.getrow()) { double amount = 0.00; double cleared = 0.00; double diff = 0.00; int days = 0; dueDateSt = DB.curRow["DueDate"]; myDateToQDate(dueDateSt.ascii(), dueDate); amount = atof(DB.curRow["Amount"]); cleared = atof(DB.curRow["ClearedAmount"]); diff = amount - cleared; days = dueDate.daysTo(today); if (days > 90) { retVal.overdue90 += diff; retVal.totalOverdue += diff; } else if (days > 60) { retVal.overdue60 += diff; retVal.totalOverdue += diff; } else if (days > 30) { retVal.overdue30 += diff; retVal.totalOverdue += diff; } else if (days >= 1) { retVal.overdue += diff; retVal.totalOverdue += diff; } else { // else its not overdue yet, don't necessarily add them retVal.currentDue += diff; } } return retVal; }
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(); }
int durationToPixels(const QDate& begin, const QDate& end) const { float days = qAbs(begin.daysTo(end)); return qRound(days * pixelsPerYear / 365.0); }