Example #1
0
void unpostedPoReceipts::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privileges->check("ChangePORecvPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Receipt Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE recv SET recv_gldistdate=:distdate "
		  "WHERE recv_id=:recv_id;");

  QList<XTreeWidgetItem*>selected = _recv->selectedItems();
  QList<XTreeWidgetItem*>triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    int id = ((XTreeWidgetItem*)(selected[i]))->id();

    if (changeDate)
    {
      setDate.bindValue(":distdate",  newDate);
      setDate.bindValue(":recv_id", id);
      setDate.exec();
      if (setDate.lastError().type() != QSqlError::NoError)
      {
        systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
      }
    }
  }
  
  XSqlQuery postLine;
  postLine.prepare("SELECT postReceipt(:id, NULL::integer) AS result;");
  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      q.exec("BEGIN;");
      postLine.bindValue(":id", id);
      postLine.exec();
      if (postLine.first())
      {
        int result = postLine.value("result").toInt();
        if (result < 0)
        {
          rollback.exec();
          systemError(this, storedProcErrorLookup("postReceipt", result),
              __FILE__, __LINE__);
          continue;
        }

        if (distributeInventory::SeriesAdjust(result, this) == XDialog::Rejected)
        {
          QMessageBox::information( this, tr("Unposted Receipts"), tr("Post Canceled") );
          rollback.exec();
          return;
        }
        q.exec("COMMIT;");
         
      }
      // contains() string is hard-coded in stored procedure
      else if (postLine.lastError().databaseText().contains("posted to closed period"))
      {
        if (changeDate)
        {
          triedToClosed = selected;
          break;
        }
        else
          triedToClosed.append(selected[i]);
      }
      else if (postLine.lastError().type() != QSqlError::NoError)
      {
        rollback.exec();
        systemError(this, postLine.lastError().databaseText(), __FILE__, __LINE__);
      }
    } // for each selected line

    if (triedToClosed.size() > 0)
    {
      failedPostList newdlg(this, "", true);
      newdlg.sSetList(triedToClosed, _recv->headerItem(), _recv->header());
      tryagain = (newdlg.exec() == XDialog::Accepted);
      selected = triedToClosed;
      triedToClosed.clear();
    }
  } while (tryagain);

  omfgThis->sPurchaseOrderReceiptsUpdated();
}
void TaskItemDelegate::paintTask(QPainter* painter, const QStyleOptionViewItem &option, const QModelIndex& index) const
{
  QRect rect = option.rect;
  QFontMetrics fm = QApplication::fontMetrics();
  
  // Painting Order:
  //    Background wash
  //    Mouseover highlight
  //    Priority Tab on left
  //    Bounding Box
  //    Task name
  //    If not small, other task information
  
  painter->save();
  if (smallTasks) { // Paint the background for a small task
    painter->save();
    painter->setOpacity(0.7);
    painter->setBrush(itemPriorityColor(index));
    painter->setPen(Qt::NoPen);
    painter->drawRect(rect.adjusted(leftMargin, MARGIN, -MARGIN, -MARGIN));
    painter->restore();
  }
  else { // Paint the background for a two row task
    painter->save();
    painter->setOpacity(0.7);
    painter->setBrush(Plasma::Theme::defaultTheme()->color(Plasma::Theme::BackgroundColor));
    painter->drawRect(option.rect.adjusted(leftMargin, MARGIN, -MARGIN, -MARGIN));
    
    painter->restore();
    painter->drawRect(QRectF(option.rect.topLeft()+QPointF(leftMargin, MARGIN), option.rect.bottomLeft()+QPointF(COLORTAB, -MARGIN))); 
  }
  
  if (option.state & QStyle::State_MouseOver) {
    painter->save();
    painter->setBrush(Plasma::Theme::defaultTheme()->color(Plasma::Theme::HighlightColor));
    painter->setPen(Qt::NoPen);
    if (smallTasks)
      painter->drawRect(rect.adjusted(leftMargin, MARGIN, -MARGIN, -MARGIN));
    else
      painter->drawRect(rect.adjusted(leftMargin, MARGIN, -MARGIN, -MARGIN));
    painter->restore();
  }
  
  // Draw Task information
  painter->setPen(Plasma::Theme::defaultTheme()->color(Plasma::Theme::TextColor));
  
  QString task = index.data(Qt::RTMNameRole).toString();
  QString due = index.data(Qt::RTMDueRole).toDate().toString("MMM d");
  QString tags = index.data(Qt::RTMTagsRole).toStringList().join(", ");
  if (!tags.isEmpty())
    tags.prepend(tagsPrefix);
  
  QFont font = painter->font();
  font.setPointSize(font.pointSize());
  QFontMetrics largerFM(font);
  
  QDate date = index.data(Qt::RTMDueRole).toDate();
  
  if (smallTasks && date.isValid() && date < QDate::currentDate()) {
    // Elide (text with dots like th...) if wider than view and draw
    font.setBold(true);
    QFontMetrics boldLargerFM(font);
    due = due.append(" "); // So that we have a space after the date before the task name
    task = largerFM.elidedText(task, Qt::ElideRight, option.rect.width()-COLORTAB-3*MARGIN - boldLargerFM.width(due));
    painter->setFont(font);
    painter->drawText(option.rect.topLeft()+QPoint(COLORTAB+MARGIN,largerFM.height()),due);
    
    font.setBold(false);
    painter->setFont(font);
    painter->drawText(option.rect.topLeft()+QPoint(COLORTAB+3*MARGIN + boldLargerFM.width(due),boldLargerFM.height()),task);
  }
  else {
    // Elide (text with dots like th...) if wider than view and draw
    task = largerFM.elidedText(task, Qt::ElideRight, option.rect.width()-COLORTAB-3*MARGIN);
    painter->setFont(font);
    painter->drawText(option.rect.topLeft()+QPoint(COLORTAB+MARGIN,largerFM.height()),task);
  }
  
  if (smallTasks) {
    painter->restore();
    return;
  }
  
  // Set our smaller attributes and blue hue for additional text
  font.setPointSize(font.pointSize()-1);
  font.setItalic(true);
  painter->setFont(font);
  fm = QFontMetrics(font);
  QColor moreText(Plasma::Theme::defaultTheme()->color(Plasma::Theme::TextColor));
  
  qreal red = moreText.redF();
  qreal green = moreText.greenF();
  qreal blue = moreText.blueF();
  qreal colorChangeMult = 0.85;
  if (blue < colorChangeMult)
    blue /= colorChangeMult;
  else {
    red *= colorChangeMult;
    green *= colorChangeMult;
  }
  moreText.setRgbF(red, green, blue);
  painter->setPen(moreText);
  
  // Elide the due from the front because "Due on" isn't necessary
  due = fm.elidedText(due, Qt::ElideLeft, option.rect.width() - COLORTAB+3*MARGIN - fm.width(tags));
  painter->drawText(option.rect.bottomLeft()+QPoint(COLORTAB+MARGIN, -MARGINH), tags);
  painter->drawText(option.rect.bottomRight()+QPoint(-COLORTAB+MARGIN-fm.width(due), -MARGINH), due);

  painter->restore();
}
QDate QQmlStringConverters::dateFromString(const QString &s, bool *ok)
{
    QDate d = QDate::fromString(s, Qt::ISODate);
    if (ok) *ok =  d.isValid();
    return d;
}
Example #4
0
void IPTCOrigin::readMetadata(QByteArray& iptcData)
{
    blockSignals(true);
    KExiv2 exiv2Iface;
    exiv2Iface.setIptc(iptcData);

    QString     data;
    QStringList code, list;
    QDate       date;
    QTime       time;
    QString     dateStr, timeStr;

    dateStr = exiv2Iface.getIptcTagString("Iptc.Application2.DateCreated", false);
    timeStr = exiv2Iface.getIptcTagString("Iptc.Application2.TimeCreated", false);

    d->dateCreatedSel->setDate(QDate::currentDate());
    d->dateCreatedCheck->setChecked(false);
    if (!dateStr.isEmpty())
    {
        date = QDate::fromString(dateStr, Qt::ISODate);
        if (date.isValid())
        {
            d->dateCreatedSel->setDate(date);
            d->dateCreatedCheck->setChecked(true);
        }
    }
    d->dateCreatedSel->setEnabled(d->dateCreatedCheck->isChecked());
    d->syncHOSTDateCheck->setEnabled(d->dateCreatedCheck->isChecked());
    d->syncEXIFDateCheck->setEnabled(d->dateCreatedCheck->isChecked());

    d->timeCreatedSel->setTime(QTime::currentTime());
    d->timeCreatedCheck->setChecked(false);
    if (!timeStr.isEmpty())
    {
        time = QTime::fromString(timeStr, Qt::ISODate);
        if (time.isValid())
        {
            d->timeCreatedSel->setTime(time);
            d->timeCreatedCheck->setChecked(true);
        }
    }
    d->timeCreatedSel->setEnabled(d->timeCreatedCheck->isChecked());

    dateStr = exiv2Iface.getIptcTagString("Iptc.Application2.DigitizationDate", false);
    timeStr = exiv2Iface.getIptcTagString("Iptc.Application2.DigitizationTime", false);

    d->dateDigitalizedSel->setDate(QDate::currentDate());
    d->dateDigitalizedCheck->setChecked(false);
    if (!dateStr.isEmpty())
    {
        date = QDate::fromString(dateStr, Qt::ISODate);
        if (date.isValid())
        {
            d->dateDigitalizedSel->setDate(date);
            d->dateDigitalizedCheck->setChecked(true);
        }
    }
    d->dateDigitalizedSel->setEnabled(d->dateDigitalizedCheck->isChecked());

    d->timeDigitalizedSel->setTime(QTime::currentTime());
    d->timeDigitalizedCheck->setChecked(false);
    if (!timeStr.isEmpty())
    {
        time = QTime::fromString(timeStr, Qt::ISODate);
        if (time.isValid())
        {
            d->timeDigitalizedSel->setTime(time);
            d->timeDigitalizedCheck->setChecked(true);
        }
    }
    d->timeDigitalizedSel->setEnabled(d->timeDigitalizedCheck->isChecked());


    code = exiv2Iface.getIptcTagsStringList("Iptc.Application2.LocationCode", false);
    for (QStringList::Iterator it = code.begin(); it != code.end(); ++it)
    {
        QStringList data = d->locationEdit->getData();
        QStringList::Iterator it2;
        for (it2 = data.begin(); it2 != data.end(); ++it2)
        {
            if ((*it2).left(3) == (*it))
            {
                list.append(*it2);
                break;
            }
        }
        if (it2 == data.end())
            d->locationEdit->setValid(false);
    }
    d->locationEdit->setValues(list);

    d->cityEdit->clear();
    d->cityCheck->setChecked(false);
    data = exiv2Iface.getIptcTagString("Iptc.Application2.City", false);
    if (!data.isNull())
    {
        d->cityEdit->setText(data);
        d->cityCheck->setChecked(true);
    }
    d->cityEdit->setEnabled(d->cityCheck->isChecked());

    d->sublocationEdit->clear();
    d->sublocationCheck->setChecked(false);
    data = exiv2Iface.getIptcTagString("Iptc.Application2.SubLocation", false);
    if (!data.isNull())
    {
        d->sublocationEdit->setText(data);
        d->sublocationCheck->setChecked(true);
    }
    d->sublocationEdit->setEnabled(d->sublocationCheck->isChecked());

    d->provinceEdit->clear();
    d->provinceCheck->setChecked(false);
    data = exiv2Iface.getIptcTagString("Iptc.Application2.ProvinceState", false);
    if (!data.isNull())
    {
        d->provinceEdit->setText(data);
        d->provinceCheck->setChecked(true);
    }
    d->provinceEdit->setEnabled(d->provinceCheck->isChecked());

    d->countryCB->setCurrentIndex(0);
    d->countryCheck->setChecked(false);
    data = exiv2Iface.getIptcTagString("Iptc.Application2.CountryCode", false);
    if (!data.isNull())
    {
        int item = -1;
        for (int i = 0 ; i < d->countryCB->count() ; i++)
            if (d->countryCB->item(i).left(3) == data)
                item = i;

        if (item != -1)
        {
            d->countryCB->setCurrentIndex(item);
            d->countryCheck->setChecked(true);
        }
        else
            d->countryCheck->setValid(false);
    }
    d->countryCB->setEnabled(d->countryCheck->isChecked());

    blockSignals(false);
}
void RecurrenceWidget::setEndDate(QDate p)
{
  _dates->setEndDate(p.isValid() ? p : _eot.date());
  _endTime->setTime(QTime(23, 59, 59, 999));
}
//XML
//Parse XML into tasklist form
int TaskList_Main::parseXML(QDomDocument &domTree){
    QDomElement set = domTree.namedItem("listset").toElement();
    QMessageBox msgBox;
    //If tree doesn't exist, stop
    if(set.isNull()){
        msgBox.setText("No <listset> element at top level");
        msgBox.setWindowTitle("Erorr parsing XML");
        msgBox.exec();
        return -1;
    }

    //Iterate through all "list" items
    QDomElement n = set.firstChildElement("list");
    for( ; !n.isNull(); n = n.nextSiblingElement("list")){
        emit createList(n.namedItem("list_title").toElement().text());
        delListAction->setEnabled(true);
        printAction->setEnabled(true);
        printAllAction->setEnabled(true);

        //Iterate through all "task" items part of "list"
        QDomElement o = n.firstChildElement("task");
        for( ; !o.isNull(); o = o.nextSiblingElement("task")){
            my_listwidget *currList = notePane->listMap[notePane->currList];
            QListWidgetItem *currItem;
            QString tempStr;

            //If task is 'main' (not subtext/subnote)
            if(o.attribute("task_type") == "main"){
                //Change task name
                notePane->addItemAction(o.namedItem("task_title").toElement().text(), false);
                currItem = currList->currentItem();

                //Change task check state
                tempStr = o.namedItem("task_check").toElement().text();
                if(tempStr == "unchecked")
                    currItem->setCheckState(Qt::Unchecked);
                else if (tempStr == "checked")
                    currItem->setCheckState(Qt::Checked);
                else if (tempStr == "part_check")
                    currItem->setCheckState(Qt::PartiallyChecked);
                else{
                    msgBox.setText("Unknown check state");
                    msgBox.setWindowTitle("Erorr parsing XML");
                    msgBox.exec();
                    return -1;
                }

                //Change task subnote
                currItem->setData(32, QVariant(
                                      o.namedItem("task_note").toElement().text()));

                //Change if task subnote is displayed
                tempStr = o.namedItem("task_display").toElement().text();
                if(tempStr == "false"){
                    currItem->setData(33, QVariant(false));
                    currItem->setData(35, QVariant(false));
                }
                else if(tempStr == "true"){
                    currItem->setData(33, QVariant(true));
                    currItem->setData(35, QVariant(true));
                }
                else{
                    msgBox.setText("Unknown bool type - display");
                    msgBox.setWindowTitle("Erorr parsing XML");
                    msgBox.exec();
                    return -1;
                }

                //Change the task due date
                tempStr = o.namedItem("task_date").toElement().text();
                qDebug((const char *)tempStr.toAscii().data());
                QDate tempDate;
                int year = tempStr.left(4).toInt();
                int month = tempStr.mid(5, 2).toInt();
                int day = tempStr.right(2).toInt();

                tempDate.setDate(year, month, day);
                if(!tempDate.isValid()){
                    msgBox.setText("Unknown date type");
                    msgBox.setWindowTitle("Erorr parsing XML");
                    msgBox.exec();
                    return -1;
                }
                currItem->setData(34, QVariant(tempDate));

                //Change the task font
                tempStr = o.namedItem("task_font").toElement().text();
                QFont tempFont;
                if(!tempFont.fromString(tempStr)){
                    msgBox.setText("Unknown font");
                    msgBox.setWindowTitle("Erorr parsing XML");
                    msgBox.exec();
                    return -1;
                }
                currItem->setFont(tempFont);
            }
            //Else if it is a subtext/subnote for a 'main'
            else if (o.attribute("task_type") == "sub"){
                //Change note's text
                notePane->addItemAction(o.namedItem("task_title").toElement().text(), true);
                currItem = currList->currentItem();
                currItem->setFlags(0);

                //Change note's font
                tempStr = o.namedItem("task_font").toElement().text();
                QFont tempFont;
                if(!tempFont.fromString(tempStr)){
                    msgBox.setText("Unknown font");
                    msgBox.setWindowTitle("Erorr parsing XML");
                    msgBox.exec();
                    return -1;
                }
                currItem->setFont(tempFont);
            }
            //Else, exit gracefully
            else{
                msgBox.setText("Unknown list type");
                msgBox.setWindowTitle("Erorr parsing XML");
                msgBox.exec();
                return -1;
            }

            //Synchronize the option pane
            optionPane->itemSelectDataIn(*currItem);
        }
    }

    return 0;
}
Example #7
0
File: main.cpp Project: KDE/kdepim
int main(int argc, char *argv[])
{
    KLocalizedString::setApplicationDomain("konsolekalendar");
    K4AboutData aboutData(
        progName, 0,                 // internal program name
        ki18n(progDisplay),          // displayable program name.
        progVersion,                 // version string
        ki18n(progDesc),             // short program description
        K4AboutData::License_GPL,     // license type
        ki18n("(c) 2002-2009, Tuukka Pasanen and Allen Winter"),
        ki18n(0),                    // any free form text
        progURL,                     // program home page address
        "bugs.kde.org"               // bug report email address
    );

    aboutData.addAuthor(
        ki18n("Allen Winter"),       // developer's name
        ki18n("Maintainer"),         // task or role
        "*****@*****.**",            // email address
        0                            // home page or relevant link
    );
    aboutData.addAuthor(
        ki18n("Tuukka Pasanen"),     // developer's name
        ki18n("Author"),             // task or role
        "*****@*****.**",     // email address
        0                            // home page or relevant link
    );

    KCmdLineArgs::init(argc, argv, &aboutData, KCmdLineArgs::CmdLineArgNone);

    KCmdLineOptions options;
    options.add("verbose",
                ki18n("Print helpful runtime messages"));
    options.add("dry-run",
                ki18n("Print what would have been done, but do not execute"));
    options.add("allow-gui",
                ki18n("Allow calendars which might need an interactive user interface"));
    options.add(":",
                ki18n("Incidence types (these options can be combined):"));
    options.add("event",
                ki18n("  Operate for Events only (Default)"));
    options.add("todo",
                ki18n("  Operate for To-dos only [NOT WORKING YET]"));
    options.add("journal",
                ki18n("  Operate for Journals only [NOT WORKING YET]"));
    options.add(":",
                ki18n("Major operation modes:"));
    options.add("view",
                ki18n("  Print incidences in specified export format"));
    options.add("add",
                ki18n("  Insert an incidence into the calendar"));
    options.add("change",
                ki18n("  Modify an existing incidence"));
    options.add("delete",
                ki18n("  Remove an existing incidence"));
    options.add("create",
                ki18n("  Create new calendar file if one does not exist"));
    options.add("import <import-file>",
                ki18n("  Import this calendar to main calendar"));
    options.add("list-calendars",
                ki18n("  List available calendars"));
    options.add(":",
                ki18n("Operation modifiers:"));
    options.add("all",
                ki18n("  View all calendar entries, ignoring date/time options"));
    options.add("next",
                ki18n("  View next activity in calendar"));
    options.add("show-next <days>",
                ki18n("  From start date show next # days' activities"));
    options.add("uid <uid>",
                ki18n("  Incidence Unique-string identifier"));
    options.add("date <start-date>",
                ki18n("  Start from this day [YYYY-MM-DD]"));
    options.add("time <start-time>",
                ki18n("  Start from this time [HH:MM:SS]"));
    options.add("end-date <end-date>",
                ki18n("  End at this day [YYYY-MM-DD]"));
    options.add("end-time <end-time>",
                ki18n("  End at this time [HH:MM:SS]"));
    options.add("epoch-start <epoch-time>",
                ki18n(" Start from this time [secs since epoch]"));
    options.add("epoch-end <epoch-time>",
                ki18n("  End at this time [secs since epoch]"));
    options.add("summary <summary>",
                ki18n("  Add summary to incidence (for add/change modes)"));
    options.add("description <description>",
                ki18n("Add description to incidence (for add/change modes)"));
    options.add("location <location>",
                ki18n("  Add location to incidence (for add/change modes)"));
    options.add("calendar <calendar id>",
                ki18n("  Calendar to use when creating a new incidence"));
    options.add(":",
                ki18n("Export options:"));
    options.add("export-type <export-type>",
                ki18n("Export file type (Default: text)"));
    options.add("export-file <export-file>",
                ki18n("Export to file (Default: stdout)"));
    options.add("export-list",
                ki18n("  Print list of export types supported and exit"));
    options.add("",
                ki18n("Examples:\n"
                      "  konsolekalendar --view\n"
                      "  konsolekalendar --list-calendars\n"
                      "  konsolekalendar --add --collection 42 --date 2003-06-04 "
                      "--time 10:00 --end-time 12:00 \\\n"
                      "                  --summary \"Doctor Visit\" "
                      "--description \"Get My Head Examined\"\n"
                      "  konsolekalendar --delete --uid KOrganizer-1740326.803"));
    options.add("",
                ki18n("For more information visit the program home page at:\n"
                      "  http://pim.kde.org/components/konsolekalendar.php"));
    KCmdLineArgs::addCmdLineOptions(options);   // Add our own options.

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication app(
        // when not set (default) GUI is not enabled - disable all GUI stuff
        args->isSet("allow-gui")
    );

    // Default values for start date/time (today at 07:00)
    QDate startdate = QDate::currentDate();
    QTime starttime(7, 0);

    // Default values for end date/time (today at 17:00)
    QDate enddate = QDate::currentDate();
    QTime endtime(17, 0);

    // Default values for switches
    bool view = true;
    bool add = false;
    bool change = false;
    bool del = false;
    bool create = false;
    //bool calendarFile = false;
    bool importFile = false;

    QString option;

    KonsoleKalendarVariables variables;
    KonsoleKalendarEpoch epochs;

    variables.setFloating(false);   // by default, new events do NOT float

    if (args->isSet("verbose")) {
        variables.setVerbose(true);
    }

    if (args->isSet("dry-run")) {
        variables.setDryRun(true);
    }

    if (args->isSet("allow-gui")) {
        variables.setAllowGui(true);
    }

    /*
     * Switch on export list
     */
    if (args->isSet("export-list")) {
        cout << endl;
        cout << i18n("%1 supports these export formats:",
                     QString::fromLatin1(progDisplay)).toLocal8Bit().data()
             << endl;
        cout << i18nc("the default export format", "  %1 [Default]",
                      QStringLiteral("Text")).toLocal8Bit().data()
             << endl;
        cout << i18nc("short text export", "  %1 (like %2, but more compact)",
                      QStringLiteral("Short"), QStringLiteral("Text")).toLocal8Bit().data()
             << endl;
        cout << i18nc("HTML export", "  %1",
                      QStringLiteral("HTML")).toLocal8Bit().data()
             << endl;
        cout << i18nc("HTMLmonth export", "  %1 (like %2, but in a month view)",
                      QStringLiteral("HTMLmonth"), QStringLiteral("HTML")).toLocal8Bit().data()
             << endl;
        cout << i18nc("comma-separated values export", "  %1 (Comma-Separated Values)",
                      QStringLiteral("CSV")).toLocal8Bit().data()
             << endl;
        cout << endl;
        return 0;
    }

    /*
     * Set incidence type(s)
     */
    if (args->isSet("event")) {
        variables.setUseEvents(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use Events";
    }
    if (args->isSet("todo")) {
        variables.setUseTodos(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use To-dos";
        cout << i18n("Sorry, To-dos are not working yet.").toLocal8Bit().data()
             << endl;
        return 1;
    }
    if (args->isSet("journal")) {
        variables.setUseJournals(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use Journals";
        cout << i18n("Sorry, Journals are not working yet.").toLocal8Bit().data()
             << endl;
        return 1;
    }
    // Use Events if no incidence type is specified on the command line
    if (!args->isSet("event") &&
            !args->isSet("todo") &&
            !args->isSet("journal")) {
        variables.setUseEvents(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use Events (Default)";
    }

    /*
     * Switch on exporting
     */
    variables.setExportType(ExportTypeText);
    if (args->isSet("export-type")) {
        option = args->getOption("export-type");

        if (option.toUpper() == QLatin1String("HTML")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to HTML";
            variables.setExportType(ExportTypeHTML);
        } else if (option.toUpper() == QLatin1String("HTMLMONTH")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to HTML by Month";
            variables.setExportType(ExportTypeMonthHTML);
        } else if (option.toUpper() == QLatin1String("CSV")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to CSV";
            variables.setExportType(ExportTypeCSV);
        } else if (option.toUpper() == QLatin1String("TEXT")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to TEXT (default)";
            variables.setExportType(ExportTypeText);
        } else if (option.toUpper() == QLatin1String("SHORT")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to TEXT-SHORT";
            variables.setExportType(ExportTypeTextShort);
        } else {
            cout << i18n("Invalid Export Type Specified: %1", option).toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    /*
     * Switch on export file name
     */
    if (args->isSet("export-file")) {
        option = args->getOption("export-file");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Export File:"
                                     << "(" << option << ")";

        variables.setExportFile(option);
    }

    /*
     * Switch on View (Print Entries).  This is the default mode of operation.
     */
    if (args->isSet("view")) {
        view = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Print incidences)";
    }

    /*
     * Switch on Add (Insert Entry)
     */
    if (args->isSet("add")) {
        view = false;
        add = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Add incidence)";
    }

    /*
     * Switch on Change (Modify Entry)
     */
    if (args->isSet("change")) {
        view = false;
        change = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Change incidence)";
    }

    /*
     * Switch on Delete (Remove Entry)
     */
    if (args->isSet("delete")) {
        view = false;
        del = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Delete incidence)";
    }

    /*
     * Switch on Create
     */
    if (args->isSet("create")) {
        view = false;
        create = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Calendar File: (Create)";
    }

    /*
     * If there is summary attached.
     */
    if (args->isSet("summary")) {
        option = args->getOption("summary");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Summary:"
                                     << "(" << option << ")";

        variables.setSummary(option);
    }

    /*
     * If there is description attached.
     */
    if (args->isSet("description")) {
        option = args->getOption("description");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Description:"
                                     << "(" << option << ")";

        variables.setDescription(option);
    }

    if (args->isSet("calendar")) {
        option = args->getOption("calendar");
        bool ok = false;
        int colId = option.toInt(&ok);
        if (ok) {
            variables.setCollectionId(colId);
        }
    }

    /*
     * If there is location information
     */
    if (args->isSet("location")) {
        option = args->getOption("location");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Location:"
                                     << "(" << option << ")";

        variables.setLocation(option);
    }

    /*
     * Show next happening and exit
     */
    if (args->isSet("next")) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Show next incidence only";

        variables.setNext(true);
    }

    /*
     * Set incidence unique string identifier
     */
    if (args->isSet("uid")) {
        option = args->getOption("uid");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "incidence UID:"
                                     << "(" << option << ")";

        variables.setUID(option);
    }

    /*
     * Set starting date for calendar
     */
    if (args->isSet("date")) {
        option = args->getOption("date");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Start date before conversion:"
                                     << "(" << option << ")";

        startdate = QDate::fromString(option, Qt::ISODate);
        if (!startdate.isValid()) {
            cout << i18n("Invalid Start Date Specified: %1",
                         option).toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Start date after conversion:"
                                     << "(" << startdate.toString() << ")";
    }

    /*
     * Set starting time
     */
    if (args->isSet("time")) {
        option = args->getOption("time");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Start time before conversion :"
                                     << "(" << option << ")";

        if (option.toUpper() != QLatin1String("FLOAT")) {
            if (option.count(QLatin1Char(':')) < 2) {
                // need to append seconds
                option.append(QLatin1String(":00"));
            }
            starttime = QTime::fromString(option, Qt::ISODate);
            if (!starttime.isValid()) {
                cout << i18n("Invalid Start Time Specified: %1", option).toLocal8Bit().data()
                     << endl;
                return 1;
            }
            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "Start time after conversion:"
                                         << "(" << starttime.toString() << ")";
        } else {
            variables.setFloating(true);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "Floating event time specified";
        }
    }

    /*
     * Set end date for calendar
     */
    if (args->isSet("end-date")) {
        option = args->getOption("end-date");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End date before conversion:"
                                     << "(" << option << ")";

        enddate = QDate::fromString(option, Qt::ISODate);
        if (!enddate.isValid()) {
            cout << i18n("Invalid End Date Specified: %1",
                         option).toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End date after conversion:"
                                     << "(" << enddate.toString() << ")";
    }

    /*
     * Show next # days and exit
     */
    if (args->isSet("show-next")) {
        bool ok;

        option = args->getOption("show-next");
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Show" << option << "days ahead";
        variables.setDaysCount(option.toInt(&ok, 10));

        if (!ok) {
            cout << i18n("Invalid Date Count Specified: %1", option).toLocal8Bit().data()
                 << endl;
            return 1;
        }

        enddate = startdate;
        enddate = enddate.addDays(variables.getDaysCount());
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End date after conversion:"
                                     << "(" << enddate.toString() << ")";
    }

    /*
     * Set ending time
     */
    if (args->isSet("end-time")) {
        option = args->getOption("end-time");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End time before conversion:"
                                     << "(" << option << ")";

        if (option.toUpper() != QLatin1String("FLOAT")) {
            if (option.count(QLatin1Char(':')) < 2) {
                // need to append seconds
                option.append(QLatin1String(":00"));
            }
            endtime = QTime::fromString(option, Qt::ISODate);
            if (!endtime.isValid()) {
                cout << i18n("Invalid End Time Specified: %1", option).toLocal8Bit().data()
                     << endl;
                return 1;
            }

            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "End time after conversion:"
                                         << "(" << endtime.toString() << ")";
        } else {
            variables.setFloating(true);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "Floating event time specified";
        }
    }

    /*
     * Set start date/time from epoch
     */
    time_t epochstart = 0;
    if (args->isSet("epoch-start")) {
        option = args->getOption("epoch-start");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Epoch start:"
                                     << "(" << option << ")";

        epochstart = (time_t) option.toULong(0, 10);
    }

    /*
     * Set end date/time from epoch
     */
    time_t epochend = 0;
    if (args->isSet("epoch-end")) {
        option = args->getOption("epoch-end");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Epoch end:"
                                     << "(" << option << ")";

        epochend = (time_t) option.toULong(0, 10);
    }

    if (args->isSet("all")) {
        variables.setAll(true);
    } else {
        variables.setAll(false);
    }

    if (args->isSet("import")) {
        view = false;
        importFile = true;
        option = args->getOption("import");
        variables.setImportFile(option);

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "importing file from:"
                                     << "(" << option << ")";
    }

    KonsoleKalendar *konsolekalendar = new KonsoleKalendar(&variables);

    if (args->isSet("list-calendars")) {
        konsolekalendar->printCalendarList();
        return 0;
    }

    QEventLoop loop;
    Akonadi::FetchJobCalendar::Ptr calendar = Akonadi::FetchJobCalendar::Ptr(new Akonadi::FetchJobCalendar());
    QObject::connect(calendar.data(), &Akonadi::FetchJobCalendar::loadFinished, &loop, &QEventLoop::quit);
    qCDebug(KONSOLEKALENDAR_LOG) << "Starting to load calendar";
    QElapsedTimer t;
    t.start();
    loop.exec();
    qCDebug(KONSOLEKALENDAR_LOG) << "Calendar loaded in" << t.elapsed() << "ms; success=" << calendar->isLoaded() << "; num incidences=" << calendar->incidences().count();

    if (!args->isSet("import")) {
        variables.setCalendar(calendar);
    }

    /***************************************************************************
     * Glorious date/time checking and setting code                            *
     ***************************************************************************/
    QDateTime startdatetime, enddatetime;

    // Handle case with either date or end-date unspecified
    if (!args->isSet("end-date") && !args->isSet("show-next") &&
            args->isSet("date")) {
        enddate = startdate;
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting enddate to startdate";
    } else if (args->isSet("end-date") && !args->isSet("date")) {
        startdate = enddate;
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting startdate to enddate";
    }

    // NOTE: If neither date nor end-date specified, then event will be today.

    // Case:
    //   End time (or epoch) unspecified, and start time (or epoch) IS specified.
    //   In this case, set the ending to 1 hour after starting.
    if (!args->isSet("end-time") && !args->isSet("epoch-end")) {
        if (args->isSet("time")) {
            endtime = starttime.addSecs(60 * 60);    // end is 1 hour after start
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting endtime 1 hour after starttime";
        } else if (args->isSet("epoch-start")) {
            startdatetime = epochs.epoch2QDateTime(epochstart);
            enddatetime = startdatetime.addSecs(60 * 60);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting endtime 1 hour after epochstart";
        }
    }

    // Case:
    //   Time (or epoch) unspecified, and end-time (or epoch) IS specified.
    //   In this case, set the starting to 1 hour before ending.
    if (!args->isSet("time") && !args->isSet("epoch-start")) {
        if (args->isSet("end-time")) {
            starttime = endtime.addSecs(-60 * 60);    // start is 1 hour before end
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting starttime 1 hour before endtime";
        } else if (args->isSet("epoch-end")) {
            enddatetime = epochs.epoch2QDateTime(epochend);
            startdatetime = enddatetime.addSecs(-60 * 60);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting starttime 1 before after epochend";
        }
    }

    // Case:
    //   Time (or epoch) unspecified, and end-time (or epoch) unspecified.
    if (!args->isSet("time")     && !args->isSet("epoch-start") &&
            !args->isSet("end-time") && !args->isSet("epoch-end")) {
        // set default start date/time
        startdatetime = QDateTime(startdate, starttime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting startdatetime from"
                                     << "default startdate (today) and starttime";
        // set default end date/time
        enddatetime = QDateTime(enddate, endtime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting enddatetime from"
                                     << "default enddate (today) and endtime";
    }

    // Set startdatetime, enddatetime if still necessary
    if (startdatetime.isNull()) {
        startdatetime = QDateTime(startdate, starttime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting startdatetime from startdate and starttime";
    }
    if (enddatetime.isNull()) {
        enddatetime = QDateTime(enddate, endtime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting enddatetime from enddate and endtime";
    }

    // Float check for add mode:
    //   Events float if time AND end-time AND epoch times are UNspecified
    if (add) {
        if (!args->isSet("time")        && !args->isSet("end-time") &&
                !args->isSet("epoch-start") && !args->isSet("epoch-end")) {
            variables.setFloating(true);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | floatingcheck |"
                                         << "turn-on floating event";
        }
    }

    // Finally! Set the start/end date times
    if (!change) {
        variables.setStartDateTime(startdatetime);
        variables.setEndDateTime(enddatetime);
    } else {
        // Do NOT set start/end datetimes in change mode,
        //   unless they were specified on commandline
        if (args->isSet("time")     || args->isSet("epoch-start") ||
                args->isSet("end-time") || args->isSet("epoch-end")) {
            variables.setStartDateTime(startdatetime);
            variables.setEndDateTime(enddatetime);
        }
    }

    // Some more debug prints
    qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp | StartDate="
                                 << startdatetime.toString(Qt::TextDate);
    qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp | EndDate="
                                 << enddatetime.toString(Qt::TextDate);

    /***************************************************************************
     * Sanity checks                                                           *
     ***************************************************************************/

    // Cannot combine modes
    if (create + view + add + change + del > 1) {
        cout << i18n("Only 1 operation mode "
                     "(view, add, change, delete, create) "
                     "permitted at any one time").toLocal8Bit().data() << endl;
        return 1;
    }

    // Cannot have a ending before starting
    if (startdatetime > enddatetime) {
        cout << i18n("Ending Date/Time occurs before the Starting Date/Time").toLocal8Bit().data()
             << endl;
        return 1;
    }

    /***************************************************************************
     * And away we go with the real work...                                    *
     ***************************************************************************/

    args->clear(); // Free up some memory.

    /*
     * Set our application name for use in unique IDs and error messages,
     * and product ID for incidence PRODID property
     */
    QString prodId = QStringLiteral("-//K Desktop Environment//NONSGML %1 %2//EN");
    CalFormat::setApplication(QLatin1String(progDisplay),
                              prodId.arg(QLatin1String(progDisplay)).arg(QLatin1String(progVersion)));

    if (importFile) {
        if (konsolekalendar->importCalendar()) {
            cout << i18n("Calendar %1 successfully imported",
                         variables.getImportFile()).toLocal8Bit().data()
                 << endl;
            return 0;
        } else {
            cout << i18n("Unable to import calendar: %1",
                         variables.getImportFile()).toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    if (add) {
        if (!konsolekalendar->isEvent(startdatetime, enddatetime,
                                      variables.getSummary())) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                         << "calling addEvent()";
            konsolekalendar->addEvent();
        } else {
            cout << i18n("Attempting to insert an event that already exists").toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    if (change) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "calling changeEvent()";
        if (!variables.isUID()) {
            cout << i18n("Missing event UID: "
                         "use --uid command line option").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        if (!konsolekalendar->changeEvent()) {
            cout << i18n("No such event UID: change event failed").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "successful changeEvent()";
    }

    if (del) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "calling deleteEvent()";
        if (!variables.isUID()) {
            cout << i18n("Missing event UID: "
                         "use --uid command line option").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        if (!konsolekalendar->deleteEvent()) {
            cout << i18n("No such event UID: delete event failed").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "successful deleteEvent()";
    }

    if (view) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "calling showInstance() to view events";
        if (!konsolekalendar->showInstance()) {
            cout << i18n("Cannot open specified export file: %1",
                         variables.getExportFile()).toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    delete konsolekalendar;

    qCDebug(KONSOLEKALENDAR_LOG) << "main | exiting";

    return 0;
}
void TimeEntryDialog::setDateRange( const QDate & start, const QDate & end )
{
	mStartDateEdit->setDate( start );
	mEndDateEdit->setDate( (!end.isValid() || end < start) ? start : end );
}
void KEquityPriceUpdateDlg::slotReceivedQuote(const QString& _id, const QString& _symbol, const QDate& _date, const double& _price)
{
  QList<QTreeWidgetItem*> foundItems = lvEquityList->findItems(_id, Qt::MatchExactly, ID_COL);
  QTreeWidgetItem* item = 0;

  if (! foundItems.empty())
    item = foundItems.at(0);

  QTreeWidgetItem* next = 0;

  if (item) {
    if (_price > 0.0f && _date.isValid()) {
      QDate date = _date;
      if (date > QDate::currentDate())
        date = QDate::currentDate();

      double price = _price;
      QString id = _id.toUtf8();
      MyMoneySecurity sec;
      if (_id.contains(" ") == 0) {
        MyMoneySecurity security = MyMoneyFile::instance()->security(id);
        QString factor = security.value("kmm-online-factor");
        if (!factor.isEmpty()) {
          price *= MyMoneyMoney(factor).toDouble();
        }
        try {
          sec = MyMoneyFile::instance()->security(id);
          sec = MyMoneyFile::instance()->security(sec.tradingCurrency());
        } catch (const MyMoneyException &) {
          sec = MyMoneySecurity();
        }

      } else {
        QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
        if (splitrx.indexIn(_id) != -1) {
          try {
            sec = MyMoneyFile::instance()->security(splitrx.cap(2).toUtf8());
          } catch (const MyMoneyException &) {
            sec = MyMoneySecurity();
          }
        }
      }
      item->setText(PRICE_COL, KGlobal::locale()->formatMoney(price, sec.tradingSymbol(), KMyMoneyGlobalSettings::pricePrecision()));
      item->setText(DATE_COL, date.toString(Qt::ISODate));
      logStatusMessage(i18n("Price for %1 updated (id %2)", _symbol, _id));
      // make sure to make OK button available
      btnOK->setEnabled(true);
    } else {
      logErrorMessage(i18n("Received an invalid price for %1, unable to update.", _symbol));
    }

    prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
    item->setSelected(false);

    // launch the NEXT one ... in case of m_fUpdateAll == false, we
    // need to parse the list to find the next selected one
    next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(item) + 1);
    if (!m_fUpdateAll) {
      while (next && !next->isSelected()) {
        prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
        next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(next) + 1);
      }
    }
  } else {
    logErrorMessage(i18n("Received a price for %1 (id %2), but this symbol is not on the list. Aborting entire update.", _symbol, _id));
  }

  if (next) {
    m_webQuote.launch(next->text(SYMBOL_COL), next->text(ID_COL), next->text(SOURCE_COL));
  } else {
    finishUpdate();
  }
}
Example #10
0
void unpostedInvoices::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privileges->check("ChangeARInvcDistDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Invoice Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  int journal = -1;
  q.exec("SELECT fetchJournalNumber('AR-IN') AS result;");
  if (q.first())
  {
    journal = q.value("result").toInt();
    if (journal < 0)
    {
      systemError(this, storedProcErrorLookup("fetchJournalNumber", journal), __FILE__, __LINE__);
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  XSqlQuery xrate;
  xrate.prepare("SELECT curr_rate "
		"FROM curr_rate, invchead "
		"WHERE ((curr_id=invchead_curr_id)"
		"  AND  (invchead_id=:invchead_id)"
		"  AND  (invchead_invcdate BETWEEN curr_effective AND curr_expires));");
  // if SUM becomes dependent on curr_id then move XRATE before it in the loop
  XSqlQuery sum;
  sum.prepare("SELECT invoicetotal(:invchead_id) AS subtotal;");

  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  XSqlQuery post;
  post.prepare("SELECT postInvoice(:invchead_id, :journal) AS result;");

  XSqlQuery setDate;
  setDate.prepare("UPDATE invchead SET invchead_gldistdate=:distdate "
		  "WHERE invchead_id=:invchead_id;");

  QList<XTreeWidgetItem*> selected = _invchead->selectedItems();
  QList<XTreeWidgetItem*> triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
    {
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      // always change gldistdate.  if using invoice date then will set to null
      //if (changeDate)
      //{
        setDate.bindValue(":distdate",    newDate);
        setDate.bindValue(":invchead_id", id);
        setDate.exec();
        if (setDate.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
        }
      //}
    }
  }

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
      {
        int id = ((XTreeWidgetItem*)(selected[i]))->id();

        sum.bindValue(":invchead_id", id);
        if (sum.exec() && sum.first() && sum.value("subtotal").toDouble() == 0)
        {
	      if (QMessageBox::question(this, tr("Invoice Has Value 0"),
		      		  tr("Invoice #%1 has a total value of 0.\n"
			     	     "Would you like to post it anyway?")
				    .arg(selected[i]->text(0)),
				  QMessageBox::Yes,
				  QMessageBox::No | QMessageBox::Default)
	      == QMessageBox::No)
	        continue;
        }
        else if (sum.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, sum.lastError().databaseText(), __FILE__, __LINE__);
	      continue;
        }
        else if (sum.value("subtotal").toDouble() != 0)
        {
	      xrate.bindValue(":invchead_id", id);
	      xrate.exec();
	      if (xrate.lastError().type() != QSqlError::NoError)
	      {
	        systemError(this, tr("System Error posting Invoice #%1\n%2")
			            .arg(selected[i]->text(0))
			            .arg(xrate.lastError().databaseText()),
		                __FILE__, __LINE__);
	        continue;
	      }
	      else if (!xrate.first() || xrate.value("curr_rate").isNull())
	      {
	        systemError(this, tr("Could not post Invoice #%1 because of a missing exchange rate.")
						.arg(selected[i]->text(0)));
	        continue;
	      }
        }

        q.exec("BEGIN;");	// because of possible lot, serial, or location distribution cancelations
        post.bindValue(":invchead_id", id);
        post.bindValue(":journal",     journal);
        post.exec();
        if (post.first())
        {
	      int result = post.value("result").toInt();
	      if (result < 0)
              {
                rollback.exec();
                systemError(this, storedProcErrorLookup("postInvoice", result),
		            __FILE__, __LINE__);
              }
              else if (distributeInventory::SeriesAdjust(result, this) == XDialog::Rejected)
              {
                rollback.exec();
                QMessageBox::information( this, tr("Post Invoices"), tr("Transaction Canceled") );
                return;
              }

              q.exec("COMMIT;");
        }
        // contains() string is hard-coded in stored procedure
        else if (post.lastError().databaseText().contains("post to closed period"))
        {
          rollback.exec();
            if (changeDate)
              triedToClosed = selected;
            else
              triedToClosed.append(selected[i]);
      }
      else if (post.lastError().type() != QSqlError::NoError)
      {
        rollback.exec();
        systemError(this, tr("A System Error occurred posting Invoice #%1.\n%2")
                    .arg(selected[i]->text(0))
                        .arg(post.lastError().databaseText()),
                        __FILE__, __LINE__);
      }
    }

    if (triedToClosed.size() > 0)
    {
      failedPostList newdlg(this, "", true);
      newdlg.sSetList(triedToClosed, _invchead->headerItem(), _invchead->header());
      tryagain = (newdlg.exec() == XDialog::Accepted);
      selected = triedToClosed;
      triedToClosed.clear();
      }
    }
  } while (tryagain);

  if (_printJournal->isChecked())
  {
    ParameterList params;
    params.append("source", tr("A/R"));
    params.append("startJrnlnum", journal);
    params.append("endJrnlnum", journal);

    if (_metrics->boolean("UseJournals"))
    {
      params.append("title",tr("Journal Series"));
      params.append("table", "sltrans");
    }
    else
    {
      params.append("title",tr("General Ledger Series"));
      params.append("gltrans", true);
      params.append("table", "gltrans");
    }

    orReport report("GLSeries", params);
    if (report.isValid())
      report.print();
    else
      report.reportError(this);
  }

  omfgThis->sInvoicesUpdated(-1, TRUE);
}
Example #11
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;
}
Example #12
0
/*
 * name : get_copyTgt_List
 * desc : Scan whole source list and target path,
 *        if path has existed and optionOverwrite is off,
 *        the source path would removed from list
 */
void PicIn_Core::get_copyTgt_List(void)
{
    QFile file;
    QString tgtName;
    QString tgtPath;
    QString yearPath;
    QString monthPath;
    QString dayPath;
    QString srcPath;
    QDate date;
    QDir dir;
    QFileInfoList tempSrcList;

    tempSrcList.clear();
    m_copyTgtList.clear();

    for(int i = 0; i < m_fileInfoList_src.size(); i++){
        srcPath = m_fileInfoList_src.at(i).absoluteFilePath();

        tgtName.clear();
        tgtName.append(m_fileInfoList_src.at(i).fileName());

        tgtPath.clear();
        tgtPath.append(m_pathList_target.at(0)); // Only support 1 target path

        //
        // Check whether need to separate pics to folders as date
        //

        if(checkOption(optionExifDate)){
            date = getExifDate(srcPath);
        }
        if(!date.isValid() || !checkOption(optionExifDate)){
            date = m_fileInfoList_src.at(i).lastModified().date();
        }

        yearPath.clear();
        monthPath.clear();
        dayPath.clear();
        if(checkOption(optionDirYear)){
            yearPath.sprintf("/%04d/", date.year());
            tgtPath.append(yearPath);
        }
        if(checkOption(optionDirMon)){
            monthPath.sprintf("/%02d/", date.month());
            tgtPath.append(monthPath);
        }
        if(checkOption(optionDirDay)){
            dayPath.sprintf("/%02d/", date.day());
            tgtPath.append(dayPath);
        }

        //
        // Check whether file need to be copied
        //

        tgtPath.append(tgtName);
        if(!file.exists(tgtPath) || checkOption(optionOverwrite)){
            m_copyTgtList.append(tgtPath);
            tempSrcList.append(m_fileInfoList_src.at(i));
        }
    }

    m_fileInfoList_src = tempSrcList;

    return;
}
Example #13
0
// METODO Database::saveUsersList
void Database::saveUsersList() const {

    QString path( "users.xml" );
    QFile file( path );
    file.open( QFile::WriteOnly );

    QXmlStreamWriter xmlWriter( &file );
    xmlWriter.setAutoFormatting( true );
    xmlWriter.writeStartDocument();
    xmlWriter.writeStartElement( "users" );

    QMapIterator<QString, SmartUtente> it( database_rapp->users_list );
    while( it.hasNext() ) {
        Utente* u = it.next().value().operator ->();

        // <user>
        xmlWriter.writeStartElement( "user" );
        xmlWriter.writeAttribute( "login", u->getUsername() );

        if( dynamic_cast<UtenteBasic*>( u ) )
            xmlWriter.writeAttribute( "type", "basic" );
        else if( dynamic_cast<UtenteExecutive*>( u ) )
            xmlWriter.writeAttribute( "type", "executive" );
        else if( dynamic_cast<UtenteBusiness*>( u ) )
            xmlWriter.writeAttribute( "type", "business" );

        // <profile>
        xmlWriter.writeStartElement( "profile" );
        xmlWriter.writeTextElement( "name", u->getName() );
        xmlWriter.writeTextElement( "surname", u->getSurname() );
        // <birthday>
        xmlWriter.writeStartElement( "birthday" );
        QDate birthday = u->getBirthday();
        if( birthday.isValid() ) {
            QStringList list = birthday.toString( "yyyy/MM/dd" ).split( "/" );
            xmlWriter.writeTextElement( "year", list[0] );
            xmlWriter.writeTextElement( "month", list[1] );
            xmlWriter.writeTextElement( "day", list[2] );
        }
        xmlWriter.writeEndElement();
        // </birthday>
        xmlWriter.writeTextElement( "maritialStatus", u->getMaritialStatus() );
        xmlWriter.writeEndElement();
        // </profile>

        // <net>
        xmlWriter.writeStartElement( "net" );
        QVectorIterator<SmartUtente> contacts_it( u->getContactsList() );
        while( contacts_it.hasNext() ) {
            xmlWriter.writeTextElement( "contact", contacts_it.next()->getUsername() );
        }
        xmlWriter.writeEndElement();
        // </net>

        // <educations>
        xmlWriter.writeStartElement( "educations" );
        Formazione::Iteratore educations_it( u->getEducationsIterator() );
        while( educations_it.hasNext() ) {
            // <title>
            SmartTitolo t = educations_it.next();
            xmlWriter.writeStartElement( "title" );
            xmlWriter.writeTextElement( "school", t->getSchool());

            // <dateAttended>
            xmlWriter.writeStartElement( "dateAttended" );
            QDate d = t->getDateAttended();
            if( d.isValid() ) {
                QStringList list = d.toString( "yyyy/MM/dd" ).split( "/" );
                xmlWriter.writeTextElement( "year", list[0] );
                xmlWriter.writeTextElement( "month", list[1] );
                xmlWriter.writeTextElement( "day", list[2] );
            }
            xmlWriter.writeEndElement();
            // </dateAttended>

            xmlWriter.writeTextElement( "fieldOfStudy", t->getFieldOfStudy() );
            xmlWriter.writeEndElement();
            // </title>
        }
        xmlWriter.writeEndElement();
        // </educations>

        // <experiences>
        xmlWriter.writeStartElement( "experiences" );
        Esperienza::Iteratore it_ex( u->getExperiencesIterator() );
        while( it_ex.hasNext() ) {
            // <job>
            SmartLavoro j = it_ex.next();
            xmlWriter.writeStartElement( "job" );
            xmlWriter.writeTextElement( "companyName", j->getCompanyName() );
            xmlWriter.writeTextElement( "title", j->getTitle() );
            // <begin>
            xmlWriter.writeStartElement( "begin" );
            QDate begin = j->getBegin();
            if( begin.isValid() ) {
                QStringList list = begin.toString( "yyyy/MM/dd" ).split( "/" );
                xmlWriter.writeTextElement( "year", list[0] );
                xmlWriter.writeTextElement( "month", list[1] );
                xmlWriter.writeTextElement( "day", list[2] );
            }
            xmlWriter.writeEndElement();
            // </begin>
            // <end>
            xmlWriter.writeStartElement( "end" );
            QDate end = j->getEnd();
            if( end.isValid() ) {
                QStringList list = end.toString( "yyyy/MM/dd" ).split( "/" );
                xmlWriter.writeTextElement( "year", list[0] );
                xmlWriter.writeTextElement( "month", list[1] );
                xmlWriter.writeTextElement( "day", list[2] );
            }
            xmlWriter.writeEndElement();
            // </end>
            xmlWriter.writeEndElement();
            // </job>
        }
        xmlWriter.writeEndElement();
        // </experiences>

        xmlWriter.writeEndElement();
        // </user>
    }

    // </users>
    xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();
}
void arWorkBench::sPostCashrcpt()
{
  XSqlQuery arPostCashrcpt;
  int journalNumber = -1;
  bool changeDate = false;
  QDate newDate = QDate();
  
  if (_privileges->check("ChangeCashRecvPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Distribution Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  arPostCashrcpt.exec("BEGIN;");
  arPostCashrcpt.exec("SELECT fetchJournalNumber('C/R') AS journalnumber;");
  if (arPostCashrcpt.first())
    journalNumber = arPostCashrcpt.value("journalnumber").toInt();
  else if (arPostCashrcpt.lastError().type() != QSqlError::NoError)
  {
    systemError(this, arPostCashrcpt.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE cashrcpt SET cashrcpt_distdate=:distdate,"
                  "                    cashrcpt_applydate=CASE WHEN (cashrcpt_applydate < :distdate) THEN :distdate"
                  "                                            ELSE cashrcpt_applydate END "
                  "WHERE cashrcpt_id=:cashrcpt_id;");
  
  QList<XTreeWidgetItem*> selected = _cashrcpt->selectedItems();
  
  for (int i = 0; i < selected.size(); i++)
  {
    int id = ((XTreeWidgetItem*)(selected[i]))->id();
    
    if (changeDate)
    {
      setDate.bindValue(":distdate",    newDate);
      setDate.bindValue(":cashrcpt_id", id);
      setDate.exec();
      ErrorReporter::error(QtCriticalMsg, this, tr("Changing Dist. Date"),
                           setDate, __FILE__, __LINE__);
    }
  }
  
  for (int i = 0; i < selected.size(); i++)
  {
    arPostCashrcpt.prepare("SELECT postCashReceipt(:cashrcpt_id, :journalNumber) AS result;");
    arPostCashrcpt.bindValue(":cashrcpt_id", ((XTreeWidgetItem*)(selected[i]))->id());
    arPostCashrcpt.bindValue(":journalNumber", journalNumber);
    arPostCashrcpt.exec();
    if (arPostCashrcpt.first())
    {
      int result = arPostCashrcpt.value("result").toInt();
      if (result < 0)
      {
        systemError(this, storedProcErrorLookup("postCashReceipt", result),
                    __FILE__, __LINE__);
        arPostCashrcpt.exec("ROLLBACK;");
        return;
      }
    }
    else if (arPostCashrcpt.lastError().type() != QSqlError::NoError)
    {
      systemError(this, arPostCashrcpt.lastError().databaseText(), __FILE__, __LINE__);
      arPostCashrcpt.exec("ROLLBACK;");
      return;
    }
  }
  arPostCashrcpt.exec("COMMIT;");
  sFillList();
}
Example #15
0
bool QgsAttributeEditor::retrieveValue( QWidget *widget, QgsVectorLayer *vl, int idx, QVariant &value )
{
  if ( !widget )
    return false;

  const QgsField &theField = vl->pendingFields()[idx];
  QgsVectorLayer::EditType editType = vl->editType( idx );
  bool modified = false;
  QString text;

  QSettings settings;
  QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString();

  QLineEdit *le = qobject_cast<QLineEdit *>( widget );
  if ( le )
  {
    text = le->text();
    modified = le->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QTextEdit *te = qobject_cast<QTextEdit *>( widget );
  if ( te )
  {
    text = te->toHtml();
    modified = te->document()->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QPlainTextEdit *pte = qobject_cast<QPlainTextEdit *>( widget );
  if ( pte )
  {
    text = pte->toPlainText();
    modified = pte->document()->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QComboBox *cb = qobject_cast<QComboBox *>( widget );
  if ( cb )
  {
    if ( editType == QgsVectorLayer::UniqueValues ||
         editType == QgsVectorLayer::ValueMap ||
         editType == QgsVectorLayer::Classification ||
         editType == QgsVectorLayer::ValueRelation )
    {
      text = cb->itemData( cb->currentIndex() ).toString();
      if ( text == nullValue )
      {
        text = QString::null;
      }
    }
    else
    {
      text = cb->currentText();
    }
    modified = true;
  }

  QListWidget *lw = qobject_cast<QListWidget *>( widget );
  if ( lw )
  {
    if ( editType == QgsVectorLayer::ValueRelation )
    {
      text = '{';
      for ( int i = 0, n = 0; i < lw->count(); i++ )
      {
        if ( lw->item( i )->checkState() == Qt::Checked )
        {
          if ( n > 0 )
          {
            text.append( ',' );
          }
          text.append( lw->item( i )->data( Qt::UserRole ).toString() );
          n++;
        }
      }
      text.append( '}' );
    }
    else
    {
      text = QString::null;
    }
    modified = true;
  }

  QSpinBox *sb = qobject_cast<QSpinBox *>( widget );
  if ( sb )
  {
    text = QString::number( sb->value() );
  }

  QAbstractSlider *slider = qobject_cast<QAbstractSlider *>( widget );
  if ( slider )
  {
    text = QString::number( slider->value() );
  }

  QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox *>( widget );
  if ( dsb )
  {
    text = QString::number( dsb->value() );
  }

  QCheckBox *ckb = qobject_cast<QCheckBox *>( widget );
  if ( ckb )
  {
    QPair<QString, QString> states = vl->checkedState( idx );
    text = ckb->isChecked() ? states.first : states.second;
  }

  QCalendarWidget *cw = qobject_cast<QCalendarWidget *>( widget );
  if ( cw )
  {
    text = cw->selectedDate().toString();
  }

  le = widget->findChild<QLineEdit *>();
  if ( le )
  {
    text = le->text();
  }

  switch ( theField.type() )
  {
    case QVariant::Int:
    {
      bool ok;
      int myIntValue = text.toInt( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myIntValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    case QVariant::LongLong:
    {
      bool ok;
      qlonglong myLongValue = text.toLong( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myLongValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    case QVariant::Double:
    {
      bool ok;
      double myDblValue = text.toDouble( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myDblValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    case QVariant::Date:
    {
      QDate myDateValue = QDate::fromString( text, Qt::ISODate );
      if ( myDateValue.isValid() && !text.isEmpty() )
      {
        value = myDateValue;
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    default: //string
      modified = true;
      value = QVariant( text );
      break;
  }

  return modified;
}
Example #16
0
void openVouchers::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privileges->check("ChangeVOPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Distribution Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE vohead SET vohead_gldistdate=:distdate "
		  "WHERE vohead_id=:vohead_id;");

  QList<XTreeWidgetItem*>selected = _vohead->selectedItems();
  QList<XTreeWidgetItem*>triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
    {
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      if (changeDate)
      {
        setDate.bindValue(":distdate",  newDate);
        setDate.bindValue(":vohead_id", id);
        setDate.exec();
        if (setDate.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
        }
      }
    }
  }
  
  XSqlQuery post;
  post.prepare("SELECT fetchJournalNumber('AP-VO') AS result;");
  post.exec();
  int journalNumber = 0;
  if(post.first())
    journalNumber = post.value("result").toInt();
  else
  {
    systemError(this, post.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  post.prepare("SELECT postVoucher(:vohead_id, :journalNumber, FALSE) AS result;");

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
      {
        int id = ((XTreeWidgetItem*)(selected[i]))->id();

        post.bindValue(":vohead_id", id);
        post.bindValue(":journalNumber", journalNumber);
        post.exec();
        if (post.first())
        {
	      int result = post.value("result").toInt();
	      if (result < 0)
	        systemError(this, storedProcErrorLookup("postVoucher", result),
		            __FILE__, __LINE__);
        }
      // contains() string is hard-coded in stored procedure
        else if (post.lastError().databaseText().contains("post to closed period"))
        {
	      if (changeDate)
	      {
	        triedToClosed = selected;
	        break;
	      }
	      else
	        triedToClosed.append(selected[i]);
        }
        else if (post.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, post.lastError().databaseText(), __FILE__, __LINE__);
        }
      }
    }

    if (triedToClosed.size() > 0)
    {
      failedPostList newdlg(this, "", true);
      newdlg.sSetList(triedToClosed, _vohead->headerItem(), _vohead->header());
      tryagain = (newdlg.exec() == XDialog::Accepted);
      selected = triedToClosed;
      triedToClosed.clear();
    }
  } while (tryagain);

  if (_printJournal->isChecked())
  {
    ParameterList params;
    params.append("journalNumber", journalNumber);

    orReport report("PayablesJournal", params);
    if (report.isValid())
      report.print();
    else
      report.reportError(this);
  }

  omfgThis->sVouchersUpdated();
}
void KODayMatrix::updateView( const QDate &actdate )
{
  if ( !actdate.isValid() ) {
    return;
  }
  //flag to indicate if the starting day of the matrix has changed by this call
  bool daychanged = false;

  // if a new startdate is to be set then apply Cornelius's calculation
  // of the first day to be shown
  if ( actdate != mStartDate ) {
    // reset index of selection according to shift of starting date from
    // startdate to actdate.
    if ( mSelStart != NOSELECTION ) {
      int tmp = actdate.daysTo( mStartDate );
      // shift selection if new one would be visible at least partly !
      if ( mSelStart + tmp < NUMDAYS && mSelEnd + tmp >= 0 ) {
        // nested if required for next X display pushed from a different month
        // correction required. otherwise, for month forward and backward,
        // it must be avoided.
        if ( mSelStart > NUMDAYS || mSelStart < 0 ) {
          mSelStart = mSelStart + tmp;
        }
        if ( mSelEnd > NUMDAYS || mSelEnd < 0 ) {
          mSelEnd = mSelEnd + tmp;
        }
      }
    }

    mStartDate = actdate;
    daychanged = true;
  }

  if ( daychanged ) {
    recalculateToday();
  }

  // The calendar has not changed in the meantime and the selected range
  // is still the same so we can save the expensive updateIncidences() call
  if ( !daychanged && !mPendingChanges ) {
    return;
  }

  // TODO_Recurrence: If we just change the selection, but not the data,
  // there's no need to update the whole list of incidences... This is just a
  // waste of computational power
  updateIncidences();
  for ( int i = 0; i < NUMDAYS; i++ ) {
    //if it is a holy day then draw it red. Sundays are consider holidays, too
    QStringList holidays = KOGlobals::self()->holiday( mDays[i] );
    QString holiStr;

    if ( ( KOGlobals::self()->calendarSystem()->dayOfWeek( mDays[i] ) ==
           KOGlobals::self()->calendarSystem()->weekDayOfPray() ) ||
         !holidays.isEmpty() ) {
      if ( !holidays.isEmpty() ) {
        holiStr = holidays.join( i18nc( "delimiter for joining holiday names", "," ) );
      }
      if ( holiStr.isEmpty() ) {
        holiStr = "";
      }
    }
    mHolidays[i] = holiStr;
  }
}
Example #18
0
uint DBEvent::UpdateDB(
    MSqlQuery &query, uint chanid, const DBEvent &match) const
{
    QString  ltitle     = title;
    QString  lsubtitle  = subtitle;
    QString  ldesc      = description;
    QString  lcategory  = category;
    uint16_t lairdate   = airdate;
    QString  lprogramId = programId;
    QString  lseriesId  = seriesId;
    QDate loriginalairdate = originalairdate;

    if (match.title.length() >= ltitle.length())
        ltitle = match.title;

    if (match.subtitle.length() >= lsubtitle.length())
        lsubtitle = match.subtitle;

    if (match.description.length() >= ldesc.length())
        ldesc = match.description;

    if (lcategory.isEmpty() && !match.category.isEmpty())
        lcategory = match.category;

    if (!lairdate && !match.airdate)
        lairdate = match.airdate;

    if (!loriginalairdate.isValid() && match.originalairdate.isValid())
        loriginalairdate = match.originalairdate;

    if (lprogramId.isEmpty() && !match.programId.isEmpty())
        lprogramId = match.programId;

    if (lseriesId.isEmpty() && !match.seriesId.isEmpty())
        lseriesId = match.seriesId;

    uint tmp = categoryType;
    if (!categoryType && match.categoryType)
        tmp = match.categoryType;

    QString lcattype = myth_category_type_to_string(tmp);

    unsigned char lsubtype = subtitleType | match.subtitleType;
    unsigned char laudio   = audioProps   | match.audioProps;
    unsigned char lvideo   = videoProps   | match.videoProps;

    uint lpartnumber =
        (!partnumber && match.partnumber) ? match.partnumber : partnumber;
    uint lparttotal =
        (!parttotal  && match.parttotal ) ? match.parttotal  : parttotal;

    bool lpreviouslyshown = previouslyshown | match.previouslyshown;

    uint32_t llistingsource = listingsource | match.listingsource;

    QString lsyndicatedepisodenumber = syndicatedepisodenumber;
    if (lsyndicatedepisodenumber.isEmpty() &&
        !match.syndicatedepisodenumber.isEmpty())
        lsyndicatedepisodenumber = match.syndicatedepisodenumber;

    query.prepare(
        "UPDATE program "
        "SET title          = :TITLE,     subtitle      = :SUBTITLE, "
        "    description    = :DESC, "
        "    category       = :CATEGORY,  category_type = :CATTYPE, "
        "    starttime      = :STARTTIME, endtime       = :ENDTIME, "
        "    closecaptioned = :CC,        subtitled     = :HASSUBTITLES, "
        "    stereo         = :STEREO,    hdtv          = :HDTV, "
        "    subtitletypes  = :SUBTYPE, "
        "    audioprop      = :AUDIOPROP, videoprop     = :VIDEOPROP, "
        "    partnumber     = :PARTNO,    parttotal     = :PARTTOTAL, "
        "    syndicatedepisodenumber = :SYNDICATENO, "
        "    airdate        = :AIRDATE,   originalairdate=:ORIGAIRDATE, "
        "    listingsource  = :LSOURCE, "
        "    seriesid       = :SERIESID,  programid     = :PROGRAMID, "
        "    previouslyshown = :PREVSHOWN "
        "WHERE chanid    = :CHANID AND "
        "      starttime = :OLDSTART ");

    query.bindValue(":CHANID",      chanid);
    query.bindValue(":OLDSTART",    match.starttime);
    query.bindValue(":TITLE",       ltitle);
    query.bindValue(":SUBTITLE",    lsubtitle);
    query.bindValue(":DESC",        ldesc);
    query.bindValue(":CATEGORY",    lcategory);
    query.bindValue(":CATTYPE",     lcattype);
    query.bindValue(":STARTTIME",   starttime);
    query.bindValue(":ENDTIME",     endtime);
    query.bindValue(":CC",          lsubtype & SUB_HARDHEAR ? true : false);
    query.bindValue(":HASSUBTITLES",lsubtype & SUB_NORMAL   ? true : false);
    query.bindValue(":STEREO",      laudio   & AUD_STEREO   ? true : false);
    query.bindValue(":HDTV",        lvideo   & VID_HDTV     ? true : false);
    query.bindValue(":SUBTYPE",     lsubtype);
    query.bindValue(":AUDIOPROP",   laudio);
    query.bindValue(":VIDEOPROP",   lvideo);
    query.bindValue(":PARTNO",      lpartnumber);
    query.bindValue(":PARTTOTAL",   lparttotal);
    query.bindValue(":SYNDICATENO", lsyndicatedepisodenumber);
    query.bindValue(":AIRDATE",     lairdate?QString::number(lairdate):"0000");
    query.bindValue(":ORIGAIRDATE", loriginalairdate);
    query.bindValue(":LSOURCE",     llistingsource);
    query.bindValue(":SERIESID",    lseriesId);
    query.bindValue(":PROGRAMID",   lprogramId);
    query.bindValue(":PREVSHOWN",   lpreviouslyshown);

    if (!query.exec())
    {
        MythDB::DBError("InsertDB", query);
        return 0;
    }

    if (credits)
    {
        for (uint i = 0; i < credits->size(); i++)
            (*credits)[i].InsertDB(query, chanid, starttime);
    }

    return 1;
}
Example #19
0
	inline bool setBegin(const QDate& d){
		if (d.isValid() == false)
			return false;
		begin_ = d;
		return true;
	}
Example #20
0
void VariantDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
    QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
    if (!lineEdit->isModified())
        return;

    QString text = lineEdit->text();
    const QValidator *validator = lineEdit->validator();
    if (validator) {
        int pos;
        if (validator->validate(text, pos) != QValidator::Acceptable)
            return;
    }

    QVariant originalValue = index.model()->data(index, Qt::UserRole);
    QVariant value;

    switch (originalValue.type()) {
    case QVariant::Char:
        value = text.at(0);
        break;
    case QVariant::Color:
        colorExp.exactMatch(text);
        value = QColor(qMin(colorExp.cap(1).toInt(), 255),
                       qMin(colorExp.cap(2).toInt(), 255),
                       qMin(colorExp.cap(3).toInt(), 255),
                       qMin(colorExp.cap(4).toInt(), 255));
        break;
    case QVariant::Date:
        {
            QDate date = QDate::fromString(text, Qt::ISODate);
            if (!date.isValid())
                return;
            value = date;
        }
        break;
    case QVariant::DateTime:
        {
            QDateTime dateTime = QDateTime::fromString(text, Qt::ISODate);
            if (!dateTime.isValid())
                return;
            value = dateTime;
        }
        break;
    case QVariant::Point:
        pointExp.exactMatch(text);
        value = QPoint(pointExp.cap(1).toInt(), pointExp.cap(2).toInt());
        break;
    case QVariant::Rect:
        rectExp.exactMatch(text);
        value = QRect(rectExp.cap(1).toInt(), rectExp.cap(2).toInt(),
                      rectExp.cap(3).toInt(), rectExp.cap(4).toInt());
        break;
    case QVariant::Size:
        sizeExp.exactMatch(text);
        value = QSize(sizeExp.cap(1).toInt(), sizeExp.cap(2).toInt());
        break;
    case QVariant::StringList:
        value = text.split(',');
        break;
    case QVariant::Time:
        {
            QTime time = QTime::fromString(text, Qt::ISODate);
            if (!time.isValid())
                return;
            value = time;
        }
        break;
    default:
        value = text;
        value.convert(originalValue.type());
    }

    model->setData(index, displayText(value), Qt::DisplayRole);
    model->setData(index, value, Qt::UserRole);
}
Example #21
0
// Function: WORKDAY
//
// - negative days count backwards
// - if holidays is not an array it is only added to days (neg. are not allowed)
//
Value func_workday(valVector args, ValueCalc *calc, FuncExtra *e)
{
    Value v(calc->conv()->asDate(args[0]));

    if (v.isError()) return v;
    QDate startdate = v.asDate(calc->settings());

    if (!startdate.isValid())
        return Value::errorVALUE();

    //
    // vars
    //
    int days = calc->conv()->asInteger(args[1]).asInteger();

    QDate date0 = calc->settings()->referenceDate();   // referenceDate
    QDate enddate = startdate;                    // enddate
    valVector holidays;                           // stores holidays
    int sign = 1;                                 // sign 1 = forward, -1 = backward

    if (days < 0) {
        // change sign and set count to ccw
        days = days * -1;
        sign = -1;
    }

    //
    // check for holidays
    //
    if (args.count() > 2) {
        if (args[2].type() == Value::Array) { // parameter is array
            unsigned int row1, col1, rows, cols;

            row1 = e->ranges[2].row1;
            col1 = e->ranges[2].col1;
            rows = e->ranges[2].row2 - row1 + 1;
            cols = e->ranges[2].col2 - col1 + 1;

            Value holiargs = args[2];

            for (unsigned r = 0; r < rows; ++r) {
                for (unsigned c = 0; c < cols; ++c) {
                    // only append if element is a valid date
                    if (!holiargs.element(c + col1, r + row1).isEmpty()) {
                        Value v(calc->conv()->asDate(holiargs.element(c + col1, r + row1)));
                        if (v.isError())
                            return Value::errorVALUE();

                        if (v.asDate(calc->settings()).isValid())
                            holidays.append(v);
                    }
                } // cols
            }   // rows
        } else {
            // no array parameter
            if (args[2].isString()) {
                // isString
                Value v(calc->conv()->asDate(args[2]));
                if (v.isError())
                    return Value::errorVALUE();

                if (v.asDate(calc->settings()).isValid())
                    holidays.append(v);
            } else {
                // isNumber
                int hdays = calc->conv()->asInteger(args[2]).asInteger();

                if (hdays < 0)
                    return Value::errorVALUE();
                days = days + hdays;
            }
        }
    }

    //
    // count days
    //
    while (days) {
        // exclude weekends and holidays
        do {
            enddate = enddate.addDays(1 * sign);
        } while (enddate.dayOfWeek() > 5 || holidays.contains(Value(date0.daysTo(enddate))));

        days--;
    }

    return Value(enddate, calc->settings());
}
Example #22
0
Value ValueParser::tryParseDate(const QString& str, bool *ok) const
{
    bool valid = false;
    QDate tmpDate = m_settings->locale()->readDate(str, &valid);
    if (!valid) {
        // Try without the year
        // The tricky part is that we need to remove any separator around the year
        // For instance %Y-%m-%d becomes %m-%d and %d/%m/%Y becomes %d/%m
        // If the year is in the middle, say %m-%Y/%d, we'll remove the sep.
        // before it (%m/%d).
        QString fmt = m_settings->locale()->dateFormatShort();
        int yearPos = fmt.indexOf("%Y", 0, Qt::CaseInsensitive);
        if (yearPos > -1) {
            if (yearPos == 0) {
                fmt.remove(0, 2);
                while (fmt[0] != '%')
                    fmt.remove(0, 1);
            } else {
                fmt.remove(yearPos, 2);
                for (; yearPos > 0 && fmt[yearPos-1] != '%'; --yearPos)
                    fmt.remove(yearPos, 1);
            }
            //kDebug(36001) <<"Cell::tryParseDate short format w/o date:" << fmt;
            tmpDate = m_settings->locale()->readDate(str, fmt, &valid);
        }
    }
    if (valid) {
        // Note: if shortdate format only specifies 2 digits year, then 3/4/1955
        // will be treated as in year 3055, while 3/4/55 as year 2055
        // (because 55 < 69, see KLocale) and thus there's no way to enter for
        // year 1995

        // The following fixes the problem, 3/4/1955 will always be 1955

        QString fmt = m_settings->locale()->dateFormatShort();
        if ((fmt.contains("%y") == 1) && (tmpDate.year() > 2999))
            tmpDate = tmpDate.addYears(-1900);

        // this is another HACK !
        // with two digit years, 0-69 is treated as year 2000-2069 (see KLocale)
        // however, in Excel only 0-29 is year 2000-2029, 30 or later is 1930
        // onwards

        // the following provides workaround for KLocale so we're compatible
        // with Excel
        // (e.g 3/4/45 is Mar 4, 1945 not Mar 4, 2045)
        if ((tmpDate.year() >= 2030) && (tmpDate.year() <= 2069)) {
            QString yearFourDigits = QString::number(tmpDate.year());
            QString yearTwoDigits = QString::number(tmpDate.year() % 100);

            // if year is 2045, check to see if "2045" isn't there --> actual
            // input is "45"
            if ((str.count(yearTwoDigits) >= 1) &&
                    (str.count(yearFourDigits) == 0))
                tmpDate = tmpDate.addYears(-100);
        }
    }
    if (!valid) {
        //try to use the standard Qt date parsing, using ISO 8601 format
        tmpDate = QDate::fromString(str, Qt::ISODate);
        if (tmpDate.isValid()) {
            valid = true;
        }
    }

    if (ok)
        *ok = valid;

    return Value(tmpDate, m_settings);
}
Example #23
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;
}
Example #24
0
void CSV::parse ()
{
  Setting rule;
  getRule(rule);

  if (! rule.count())
  {
    QString s(tr("Empty rule"));
    printStatusLogMessage(s);
    downloadComplete();
    return;
  }

  QString ts = "Rule";
  QString ts2, s;
  rule.getData(ts, ts2);
  if (! ts2.contains("Date:"))
  {
    QString ss(tr("Rule missing Date field"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  ts = "Delimiter";
  rule.getData(ts, s);
  if (! s.length())
  {
    QString ss(tr("Delimiter not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }
  setDelimiter(s);

  if (dateRange->isChecked())
  {
    if (sdate->date() >= edate->date() || edate->date() <= sdate->date())
    {
      QString ss = stringDone + " " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
      printStatusLogMessage(ss);
      downloadComplete();
      return;
    }
  }

  QString type;
  ts = "Type";
  rule.getData(ts, type);
  if (! type.length())
  {
    QString ss(tr("Type not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  ts = "Rule";
  rule.getData(ts, ts2);
  QStringList fieldList = QStringList::split(",", ts2, FALSE);
  if (! fieldList.count())
  {
    QString ss(tr("No rule found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  // get the directory path offset
  ts = "Directory";
  QString directory;
  rule.getData(ts, directory);
  if (! directory.length())
  {
    QString ss(tr("Directory not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  // get the symbol filter
  ts = "SymbolFilter";
  rule.getData(ts, ts2);
  QStringList symbolFilter = QStringList::split(",", ts2, FALSE);

  // check for time field and set the tickflag
  bool tickFlag = FALSE;
  ts = "Rule";
  rule.getData(ts, ts2);
  if (ts2.contains("Time"))
    tickFlag = TRUE;
  else
  {
    if (ts2.contains("HHMMSS"))
      tickFlag = TRUE;
  }

  QStringList list;
  file->getFile(list);

  int loop;
  for (loop = 0; loop < (int) list.count(); loop++)
  {
    if (cancelFlag)
      break;

    QFile f(list[loop]);
    if (! f.open(QIODevice::ReadOnly))
      continue;
    Q3TextStream stream(&f);

    QString symbol = symbolOveride;
    if (! symbol.length() && fieldList.findIndex("Symbol") == -1)
    {
      QStringList l = QStringList::split("/", list[loop], FALSE);
      symbol = l[l.count() - 1];

      if (symbol.right(4).contains(".txt"))
        symbol.truncate(symbol.length() - 4);

      if (symbol.right(4).contains(".TXT"))
        symbol.truncate(symbol.length() - 4);

      while (symbol.contains("_"))
        symbol = symbol.remove(symbol.find("_", 0, TRUE), 1);
    }

    QString path;
    if (! type.compare("Stocks"))
    {
      QString tmp = "Stocks/" + directory;
      createDirectory(tmp, path);
      if (! path.length())
      {
        QString ss(tr("CSVPlugin::Unable to create directory"));
        printStatusLogMessage(ss);
        downloadComplete();
        f.close();
        return;
      }
    }
    else
    {
      if (! type.compare("Futures"))
      {
        QString tmp = "Futures/" + directory;
        createDirectory(tmp, path);
        if (! path.length())
        {
          QString ss(tr("CSVPlugin::Unable to create directory"));
          printStatusLogMessage(ss);
          downloadComplete();
          f.close();
          return;
        }
      }
    }

    path.append("/");

    if (symbol.length())
    {
      QString s = path;
      s.append(symbol);
      if (openDb(s, symbol, type, tickFlag))
        continue;
//      QString ss = tr("Updating") + " " + symbol;
//      printStatusLogMessage(ss);
        progressBar->setProgress(loop, (int) list.count());
    }

    int lineCount = 0;
    QFileInfo fi(f);
    QString fName = fi.fileName();
    while(stream.atEnd() == 0)
    {
      QString ts = stream.readLine();
      QStringList l = QStringList::split( '\n', substituteSeparator(ts, delim, '\n'), FALSE);

      lineCount++;
      if (l.count() != fieldList.count())
      {
        QString ss = QString().sprintf(
          "%s - %s - %s: %s Number of fields in file (%i) != rule format (%i)",
          fName.latin1(), symbol.latin1(), tr("Line").latin1(),
          QString::number(lineCount).latin1(),  l.count(), fieldList.count()
          );
        printStatusLogMessage(ss);
        continue;
      }

      int fieldLoop;
      bool flag = FALSE;
      Setting r;
      for (fieldLoop = 0; fieldLoop < (int) fieldList.count(); fieldLoop++)
      {
        QString listItem = l[fieldLoop].stripWhiteSpace();
        if (fieldList[fieldLoop].contains("Date:"))
	{
          QDate dt;
          getDate(fieldList[fieldLoop], listItem, r, dt);
          if (! dt.isValid())
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad date").latin1(), listItem.latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }

          if (dateRange->isChecked())
          {
            if (dt < sdate->date() || dt > edate->date())
	    {
	      flag = TRUE;
	      break;
	    }
          }
          ts = "Date";
          ts2 = dt.toString("yyyyMMdd");
	  r.setData(ts, ts2);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Time"))
	{
          getTime(listItem, s);
          if (! s.length())
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad time").latin1(), listItem.latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = "Time";
	  r.setData(ts, s);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Symbol"))
	{
	  if (symbolFilter.count())
	  {
	    if (symbolFilter.findIndex(listItem) == -1)
	    {
	      flag = TRUE;
	      break;
	    }
	  }

          ts = "Symbol";
	  r.setData(ts, listItem);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Name"))
	{
          ts = "Name";
	  r.setData(ts, listItem);
	  continue;
	}

	if (! fieldList[fieldLoop].compare("Open") ||
	    ! fieldList[fieldLoop].compare("High") ||
	    ! fieldList[fieldLoop].compare("Low") ||
	    ! fieldList[fieldLoop].compare("Close"))
	{
          if (setTFloat(listItem, TRUE))
	  {
            QString ss = QString().sprintf("%s - %s - %s: %i %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), lineCount,
              tr("Bad value").latin1(), tr(fieldList[fieldLoop]).latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = QString::number(tfloat);
	  r.setData(fieldList[fieldLoop], ts);
	  continue;
	}

	if (! fieldList[fieldLoop].compare("Volume") ||
	    ! fieldList[fieldLoop].compare("OI"))
	{
          if (setTFloat(listItem, FALSE))
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad value").latin1(), tr(fieldList[fieldLoop]).latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = QString::number(tfloat);
	  r.setData(fieldList[fieldLoop], ts);
	  continue;
	}
      }

      if (flag)
	continue;

      ts = "Date";
      r.getData(ts, s);
      if (! s.length())
	continue;

      ts = "Time";
      r.getData(ts, ts2);
      if (ts2.length())
        s.append(ts2);
      else
        s.append("000000");

      Bar bar;
      if (bar.setDate(s))
      {
        ts = "Date";
        r.getData(ts, ts2);
        QString ss = tr("Bad date") + " " + ts2;
        printStatusLogMessage(ss);
        continue;
      }
      bar.setTickFlag(tickFlag);
      ts = "Open";
      bar.setOpen(r.getDouble(ts));
      ts = "High";
      bar.setHigh(r.getDouble(ts));
      ts = "Low";
      bar.setLow(r.getDouble(ts));
      ts = "Close";
      bar.setClose(r.getDouble(ts));
      ts = "Volume";
      bar.setVolume(r.getDouble(ts));
      ts = "OI";
      bar.setOI(r.getInt(ts));

      DBIndexItem item;

      if (! symbol.length())
      {
        ts = "Symbol";
        QString t;
        r.getData(ts, t);
	s = path;
	s.append(t);
	if (openDb(s, t, type, tickFlag))
	  continue;

        ts = "Name";
	r.getData(ts, s);
	if (s.length())
        {
          chartIndex->getIndexItem(t, item);
          item.setTitle(s);
	  chartIndex->setIndexItem(t, item);
        }

        db.setBar(bar);

        ts = "Symbol";
        r.getData(ts, ts2);
//        QString ss = tr("Updating") + " " + ts2;
//        printStatusLogMessage(ss);
	config.closePlugin(type);

        db.close();

        emit signalWakeup();
      }
      else
      {
        ts = "Name";
	r.getData(ts, s);
	if (s.length())
        {
          chartIndex->getIndexItem(symbol, item);
          item.setTitle(s);
	  chartIndex->setIndexItem(symbol, item);
        }
        db.setBar(bar);

        emit signalWakeup();
      }
    }

    db.close();
    f.close();
  }

  progressBar->setProgress((int) list.count(), (int) list.count());
  downloadComplete();
  if (cancelFlag)
  {
    cancelFlag = FALSE;
    printStatusLogMessage(stringCanceled);
  }
  else {
    QString ss = stringDone + " " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    printStatusLogMessage(ss);
  }
  progressBar->reset();
}
void RecurrenceWidget::setStartDate(QDate p)
{
  _dates->setStartDate(p.isValid() ? p : QDate::currentDate());
  _startTime->setTime(QTime(0, 0));
}
Example #26
0
void unpostedCreditMemos::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privileges->check("ChangeSOMemoPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Credit Memo Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE cmhead SET cmhead_gldistdate=:distdate "
		  "WHERE cmhead_id=:cmhead_id;");

  QList<QTreeWidgetItem *> selected = _cmhead->selectedItems();
  QList<QTreeWidgetItem *> triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
    {
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      if (changeDate)
      {
        setDate.bindValue(":distdate",  newDate);
        setDate.bindValue(":cmhead_id", id);
        setDate.exec();
        if (setDate.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
        }
      }
    }
  }

  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");
    
  XSqlQuery postq;
  postq.prepare("SELECT postCreditMemo(:cmhead_id, 0) AS result;");

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
      {
        int id = ((XTreeWidgetItem*)(selected[i]))->id();
 
        XSqlQuery tx;
        tx.exec("BEGIN;");	// because of possible lot, serial, or location distribution cancelations
      
        postq.bindValue(":cmhead_id", id);
        postq.exec();
        if (postq.first())
        {
          int result = postq.value("result").toInt();
          if (result < 0)
          {
            rollback.exec();
            systemError( this, storedProcErrorLookup("postCreditMemo", result),
                  __FILE__, __LINE__);
            return;
          }
          else
          {
            if (distributeInventory::SeriesAdjust(result, this) == XDialog::Rejected)
            {
              rollback.exec();
              QMessageBox::information( this, tr("Post Credit Memo"), tr("Transaction Canceled") );
              return;
            }

            q.exec("COMMIT;");
          }
        }
        // contains() string is hard-coded in stored procedure
        else if (postq.lastError().databaseText().contains("post to closed period"))
        {
          rollback.exec();
          if (changeDate)
          {
            triedToClosed = selected;
            break;
          }
          else
            triedToClosed.append(selected[i]);
        }
        else if (postq.lastError().type() != QSqlError::NoError)
        {
          rollback.exec();
          systemError(this, tr("A System Error occurred posting Credit Memo#%1.\n%2")
                  .arg(selected[i]->text(0))
                  .arg(postq.lastError().databaseText()),
                __FILE__, __LINE__);
        }
      }

      if (triedToClosed.size() > 0)
      {
        failedPostList newdlg(this, "", true);
        newdlg.sSetList(triedToClosed, _cmhead->headerItem(), _cmhead->header());
        tryagain = (newdlg.exec() == XDialog::Accepted);
        selected = triedToClosed;
        triedToClosed.clear();
      }
    }
  } while (tryagain);

  omfgThis->sCreditMemosUpdated();
}
Example #27
0
void IPTCEnvelope::readMetadata(QByteArray& iptcData)
{
    blockSignals(true);
    KPMetadata meta;
    meta.setIptc(iptcData);

    QString     data, format, version;
    QStringList list;
    QDate       date;
    QTime       time;
    QString     dateStr, timeStr;

    d->destinationEdit->clear();
    d->destinationCheck->setChecked(false);
    data = meta.getIptcTagString("Iptc.Envelope.Destination", false);

    if (!data.isNull())
    {
        d->destinationEdit->setText(data);
        d->destinationCheck->setChecked(true);
    }

    d->destinationEdit->setEnabled(d->destinationCheck->isChecked());

    d->envelopeIDEdit->clear();
    d->envelopeIDCheck->setChecked(false);
    data = meta.getIptcTagString("Iptc.Envelope.EnvelopeNumber", false);

    if (!data.isNull())
    {
        d->envelopeIDEdit->setText(data);
        d->envelopeIDCheck->setChecked(true);
    }

    d->envelopeIDEdit->setEnabled(d->envelopeIDCheck->isChecked());

    d->serviceIDEdit->clear();
    d->serviceIDCheck->setChecked(false);
    data = meta.getIptcTagString("Iptc.Envelope.ServiceId", false);

    if (!data.isNull())
    {
        d->serviceIDEdit->setText(data);
        d->serviceIDCheck->setChecked(true);
    }

    d->serviceIDEdit->setEnabled(d->serviceIDCheck->isChecked());

    d->unoIDEdit->clear();
    d->unoIDCheck->setChecked(false);
    data = meta.getIptcTagString("Iptc.Envelope.UNO", false);

    if (!data.isNull())
    {
        d->unoIDEdit->setText(data);
        d->unoIDCheck->setChecked(true);
    }

    d->unoIDEdit->setEnabled(d->unoIDCheck->isChecked());

    d->productIDEdit->clear();
    d->productIDCheck->setChecked(false);
    data = meta.getIptcTagString("Iptc.Envelope.ProductId", false);

    if (!data.isNull())
    {
        d->productIDEdit->setText(data);
        d->productIDCheck->setChecked(true);
    }

    d->productIDEdit->setEnabled(d->productIDCheck->isChecked());

    d->priorityCB->setCurrentIndex(0);
    d->priorityCheck->setChecked(false);
    data = meta.getIptcTagString("Iptc.Envelope.EnvelopePriority", false);

    if (!data.isNull())
    {
        const int val = data.toInt();
        if (val >= 0 && val <= 9)
        {
            d->priorityCB->setCurrentIndex(val);
            d->priorityCheck->setChecked(true);
        }
        else
            d->priorityCheck->setValid(false);
    }

    d->priorityCB->setEnabled(d->priorityCheck->isChecked());

    d->formatCB->setCurrentIndex(0);
    d->formatCheck->setChecked(false);
    format  = meta.getIptcTagString("Iptc.Envelope.FileFormat", false);
    version = meta.getIptcTagString("Iptc.Envelope.FileVersion", false);

    if (!format.isNull())
    {
        if (!version.isNull())
        {
            if (format.size() == 1) format.prepend("0");
            if (version.size() == 1) version.prepend("0");
            QString key = QString("%1-%2").arg(format).arg(version);
            int index = -1, i = 0;
            for (IPTCEnvelopePriv::FileFormatMap::Iterator it = d->fileFormatMap.begin();
                    it != d->fileFormatMap.end(); ++it)
            {
                if (it.key() == key) index = i;
                i++;
            }

            if (index != -1)
            {
                d->formatCB->setCurrentIndex(index);
                d->formatCheck->setChecked(true);
            }
            else
                d->formatCheck->setValid(false);
        }
        else
            d->formatCheck->setValid(false);
    }

    d->formatCB->setEnabled(d->formatCheck->isChecked());

    dateStr = meta.getIptcTagString("Iptc.Envelope.DateSent", false);
    timeStr = meta.getIptcTagString("Iptc.Envelope.TimeSent", false);

    d->dateSentSel->setDate(QDate::currentDate());
    d->dateSentCheck->setChecked(false);

    if (!dateStr.isEmpty())
    {
        date = QDate::fromString(dateStr, Qt::ISODate);
        if (date.isValid())
        {
            d->dateSentSel->setDate(date);
            d->dateSentCheck->setChecked(true);
        }
    }

    d->dateSentSel->setEnabled(d->dateSentCheck->isChecked());

    d->timeSentSel->setTime(QTime::currentTime());
    d->timeSentCheck->setChecked(false);
    d->zoneSentSel->setToUTC();

    if (!timeStr.isEmpty())
    {
        time = QTime::fromString(timeStr, Qt::ISODate);
        if (time.isValid())
        {
            d->timeSentSel->setTime(time);
            d->timeSentCheck->setChecked(true);
            d->zoneSentSel->setTimeZone(timeStr);
        }
    }

    d->timeSentSel->setEnabled(d->timeSentCheck->isChecked());
    d->zoneSentSel->setEnabled(d->timeSentCheck->isChecked());

    blockSignals(false);
}
Example #28
0
QVariant KConfigGroup::convertToQVariant(const char *pKey, const QByteArray& value, const QVariant& aDefault)
{
    // if a type handler is added here you must add a QVConversions definition
    // to conversion_check.h, or ConversionCheck::to_QVariant will not allow
    // readEntry<T> to convert to QVariant.
    switch( aDefault.type() ) {
        case QVariant::Invalid:
            return QVariant();
        case QVariant::String:
            // this should return the raw string not the dollar expanded string.
            // imho if processed string is wanted should call
            // readEntry(key, QString) not readEntry(key, QVariant)
            return QString::fromUtf8(value);
        case QVariant::List:
        case QVariant::StringList:
            return KConfigGroupPrivate::deserializeList(QString::fromUtf8(value));
        case QVariant::ByteArray:
            return value;
        case QVariant::Bool: {
            const QByteArray lower(value.toLower());
            if (lower == "false" || lower == "no" || lower == "off" || lower == "0")
                return false;
            return true;
        }
        case QVariant::Double:
        case QMetaType::Float:
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::LongLong:
        case QVariant::ULongLong: {
            QVariant tmp = value;
            if ( !tmp.convert(aDefault.type()) )
                tmp = aDefault;
            return tmp;
        }
        case QVariant::Point: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            return QPoint(list.at( 0 ), list.at( 1 ));
        }
        case QVariant::PointF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            return QPointF(list.at( 0 ), list.at( 1 ));
        }
        case QVariant::Rect: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 4 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 4, list.count() );
                return aDefault;
            }
            const QRect rect(list.at( 0 ), list.at( 1 ), list.at( 2 ), list.at( 3 ));
            if ( !rect.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return rect;
        }
        case QVariant::RectF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 4 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 4, list.count() );
                return aDefault;
            }
            const QRectF rect(list.at( 0 ), list.at( 1 ), list.at( 2 ), list.at( 3 ));
            if ( !rect.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return rect;
        }
        case QVariant::Size: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            const QSize size(list.at( 0 ), list.at( 1 ));
            if ( !size.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return size;
        }
        case QVariant::SizeF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            const QSizeF size(list.at( 0 ), list.at( 1 ));
            if ( !size.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return size;
        }
        case QVariant::DateTime: {
            const QList<int> list = asIntList(value);
            if ( list.count() != 6 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 6, list.count() );
                return aDefault;
            }
            const QDate date( list.at( 0 ), list.at( 1 ), list.at( 2 ) );
            const QTime time( list.at( 3 ), list.at( 4 ), list.at( 5 ) );
            const QDateTime dt( date, time );
            if ( !dt.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return dt;
        }
        case QVariant::Date: {
            QList<int> list = asIntList(value);
            if ( list.count() == 6 )
                list = list.mid(0, 3); // don't break config files that stored QDate as QDateTime
            if ( list.count() != 3 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 3, list.count() );
                return aDefault;
            }
            const QDate date( list.at( 0 ), list.at( 1 ), list.at( 2 ) );
            if ( !date.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return date;
        }
        case QVariant::Color:
        case QVariant::Font:
            qWarning() << "KConfigGroup::readEntry was passed GUI type '"
                    << aDefault.typeName()
                    << "' but kdeui isn't linked! If it is linked to your program, "
                    "this is a platform bug. Please inform the KDE developers";
            break;
        case QVariant::Url:
            return QUrl(QString::fromUtf8(value));

        default:
            break;
    }

    qWarning() << "unhandled type " << aDefault.typeName();
    return QVariant();
}
Example #29
0
void MyMoneyForecast::addScheduledTransactions (void)
{
  MyMoneyFile* file = MyMoneyFile::instance();

  // now process all the schedules that may have an impact
  QValueList<MyMoneySchedule> schedule;

  schedule = file->scheduleList("", MyMoneySchedule::TYPE_ANY, MyMoneySchedule::OCCUR_ANY, MyMoneySchedule::STYPE_ANY,
                                QDate(), forecastEndDate());
  if(schedule.count() > 0) {
    QValueList<MyMoneySchedule>::Iterator it;
    do {
      qBubbleSort(schedule);
      it = schedule.begin();
      if(it == schedule.end())
        break;

      if((*it).isFinished()) {
        schedule.erase(it);
        continue;
      }

      QDate date = (*it).nextPayment((*it).lastPayment());
      if(!date.isValid()) {
        schedule.remove(it);
        continue;
      }

      QDate nextDate =
        (*it).adjustedNextPayment((*it).adjustedDate((*it).lastPayment(),
                                                     (*it).weekendOption()));
      if (nextDate > forecastEndDate()) {
        // We're done with this schedule, let's move on to the next
        schedule.remove(it);
        continue;
      }

      // found the next schedule. process it

      MyMoneyAccount acc = (*it).account();

      if(!acc.id().isEmpty()) {
        try {
          if(acc.accountType() != MyMoneyAccount::Investment) {
            MyMoneyTransaction t = (*it).transaction();

            // only process the entry, if it is still active
            if(!(*it).isFinished() && nextDate != QDate()) {
              // make sure we have all 'starting balances' so that the autocalc works
              QValueList<MyMoneySplit>::const_iterator it_s;
              QMap<QString, MyMoneyMoney> balanceMap;

              for(it_s = t.splits().begin(); it_s != t.splits().end(); ++it_s ) {
                MyMoneyAccount acc = file->account((*it_s).accountId());
                if(isForecastAccount(acc)) {
                  // collect all overdues on the first day
                  QDate forecastDate = nextDate;
                  if(QDate::currentDate() >= nextDate)
                    forecastDate = QDate::currentDate().addDays(1);

                  dailyBalances balance;
                  balance = m_accountList[acc.id()];
                  for(QDate f_day = QDate::currentDate(); f_day < forecastDate; ) {
                    balanceMap[acc.id()] += m_accountList[acc.id()][f_day];
                    f_day = f_day.addDays(1);
                  }
                }
              }

              // take care of the autoCalc stuff
              calculateAutoLoan(*it, t, balanceMap);

              // now add the splits to the balances
              for(it_s = t.splits().begin(); it_s != t.splits().end(); ++it_s ) {
                MyMoneyAccount acc = file->account((*it_s).accountId());
                if(isForecastAccount(acc)) {
                  dailyBalances balance;
                  balance = m_accountList[acc.id()];
                  //int offset = QDate::currentDate().daysTo(nextDate);
                  //if(offset <= 0) {  // collect all overdues on the first day
                  //  offset = 1;
                  //}
                  // collect all overdues on the first day
                  QDate forecastDate = nextDate;
                  if(QDate::currentDate() >= nextDate)
                    forecastDate = QDate::currentDate().addDays(1);

                  if(acc.accountType() == MyMoneyAccount::Income) {
                    balance[forecastDate] += ((*it_s).shares() * MyMoneyMoney(-1, 1));
                  } else {
                    balance[forecastDate] += (*it_s).shares();
                  }
                  m_accountList[acc.id()] = balance;
                }
              }
            }
          }
          (*it).setLastPayment(date);

        } catch(MyMoneyException* e) {
          kdDebug(2) << __func__ << " Schedule " << (*it).id() << " (" << (*it).name() << "): " << e->what() << endl;

          schedule.remove(it);
          delete e;
        }
      } else {
        // remove schedule from list
        schedule.remove(it);
      }
    }
    while(1);
  }

#if 0
{
  s << "\n\nAdded scheduled transactions\n";
  QMap<QString, dailyBalances>::Iterator it_a;
  QMap<QString, QString>::ConstIterator it_n;
  for(it_n = m_nameIdx.begin(); it_n != m_nameIdx.end(); ++it_n) {
  MyMoneyAccount acc = file->account(*it_n);
  it_a = m_accountList.find(*it_n);
  s << "\"" << acc.name() << "\",";
  for(int i = 0; i < 90; ++i) {
    s << "\"" << (*it_a)[i].formatMoney("") << "\",";
  }
  s << "\n";
}
}
#endif
}
Example #30
0
bool
Field::setDefaultValue(const QByteArray& def)
{
    if (def.isNull()) {
        m_defaultValue = QVariant();
        return true;
    }

    bool ok;
    switch (type()) {
    case Byte: {
        unsigned int v = def.toUInt(&ok);
        if (!ok || v > 255)
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(v);
        break;
    }
    case ShortInteger: {
        int v = def.toInt(&ok);
        if (!ok || (!(m_options & Unsigned) && (v < -32768 || v > 32767)) || ((m_options & Unsigned) && (v < 0 || v > 65535)))
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(v);
        break;
    }
    case Integer: {//4 bytes
        long v = def.toLong(&ok);
//js: FIXME   if (!ok || (!(m_options & Unsigned) && (-v > 0x080000000 || v > (0x080000000-1))) || ((m_options & Unsigned) && (v < 0 || v > 0x100000000)))
        if (!ok || (!(m_options & Unsigned) && (-v > (int)0x07FFFFFFF || v > (int)(0x080000000 - 1))))
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant((qint64)v);
        break;
    }
    case BigInteger: {//8 bytes
//! @todo BigInteger support
        /*
              qint64 long v = def.toLongLong(&ok);
        //TODO: 2-part decoding
              if (!ok || (!(m_options & Unsigned) && (-v > 0x080000000 || v > (0x080000000-1))))
                m_defaultValue = QVariant();
              else
                if (m_options & Unsigned)
                  m_defaultValue=QVariant((quint64) v);
                else
                  m_defaultValue = QVariant((qint64)v);*/
        break;
    }
    case Boolean: {
        unsigned short v = def.toUShort(&ok);
        if (!ok || v > 1)
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant((bool)v);
        break;
    }
    case Date: {//YYYY-MM-DD
        QDate date = QDate::fromString(def, Qt::ISODate);
        if (!date.isValid())
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(date);
        break;
    }
    case DateTime: {//YYYY-MM-DDTHH:MM:SS
        QDateTime dt = QDateTime::fromString(def, Qt::ISODate);
        if (!dt.isValid())
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(dt);
        break;
    }
    case Time: {//HH:MM:SS
        QTime time = QTime::fromString(def, Qt::ISODate);
        if (!time.isValid())
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(time);
        break;
    }
    case Float: {
        float v = def.toFloat(&ok);
        if (!ok || ((m_options & Unsigned) && (v < 0.0)))
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(v);
        break;
    }
    case Double: {
        double v = def.toDouble(&ok);
        if (!ok || ((m_options & Unsigned) && (v < 0.0)))
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(v);
        break;
    }
    case Text: {
        if (def.isNull() || (uint(def.length()) > maxLength()))
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant((QString)def);
        break;
    }
    case LongText: {
        if (def.isNull())
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant((QString)def);
        break;
    }
    case BLOB: {
//TODO
        if (def.isNull())
            m_defaultValue = QVariant();
        else
            m_defaultValue = QVariant(def);
        break;
    }
    default:
        m_defaultValue = QVariant();
    }
    return m_defaultValue.isNull();
}