Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;

#ifdef XQ_WS_WIN
  WSADATA wsaData;
  if (WSAStartup(MAKEWORD(1, 1), &wsaData))
  {
    qDebug("Error starting up Windows Socket system... Database services are not avalable.");
    exit(-1);
  }
#endif

  QApplication app(argc, argv);
  app.addLibraryPath(".");

#ifdef Q_WS_WIN
  if (app.winVersion() == QSysInfo::WV_XP)
    app.setStyle(QStyleFactory::create("windowsxpstyle"));
#if QT_VERSION >= 0x040300 
  else if (app.winVersion() == QSysInfo::WV_VISTA)
    app.setStyle(QStyleFactory::create("windowsvistastyle"));
#endif
  else
    app.setStyle(new QWindowsStyle);
#elif defined Q_WS_MACX
  app.setStyle(new QMacStyle);
#elif defined Q_WS_X11
  app.setStyle(new QWindowsStyle);
#endif

  // Try and load a default translation file and install it
  QTranslator defaultTranslator(0);
  if (defaultTranslator.load("default.qm", app.applicationDirPath()))
    app.installTranslator(&defaultTranslator);

  app.processEvents();

  if (argc > 1)
  {
    bool    havePasswd          = FALSE;
    bool    interactive         = TRUE;
    bool    createCountTags     = FALSE;
    QString passwd;

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL="))
      {
        haveDatabaseURL = TRUE;
        databaseURL = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd="))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth"))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 

      else if (argument.contains("-createCountTags"))
      {
        interactive = FALSE;
        createCountTags = TRUE;
      }
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db.isValid())
      {
        qDebug("Cannot load Database Driver.  Contact your Systems Administrator.");
        exit(-1);
      }

      QString protocol;
      parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);
      db.setDatabaseName(dbName);
      db.setUserName(username);
      db.setPassword(passwd);
      db.setHostName(hostName);
      bool valport = false;
      int iport = port.toInt(&valport);
      if(!valport) iport = 5432;
      db.setPort(iport);

      if (!db.open())
      {
        qDebug( QObject::tr( "Cannot log onto the database with the supplied username/password!\n"
                             "Host = %1\n"
                             "Database = %2\n"
                             "Username = %3\n" )
                .arg(hostName)
                .arg(dbName)
                .arg(username) );
        exit(-1);
      }
      else
        loggedIn = TRUE;
    }

    if (!interactive)
      return 0;
  }

  _splash = new QSplashScreen();
  _splash->setPixmap(QPixmap(":/images/splashEmpty.png"));

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
//    params.append("name", _Name);  -- We can't tell now until were logged in what the app is.
    params.append("copyright", _Copyright);
    params.append("version", _Version);
    params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__));

    if (haveUsername)
      params.append("username", username);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    if (_evaluation)
      params.append("evaluation");

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, _splash);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
    else
    {
      databaseURL = newdlg._databaseURL;
      username = newdlg.username();
    }
  }

  XSqlQuery metric;
  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'Application')" );
  if(!metric.first() || (metric.value("metric_value").toString() == "OpenMFG"))
  {
    _splash->setPixmap(QPixmap(":/images/splashOpenMFG.png"));
    _Name = _Name.arg("OpenMFG");
  }
  else if(!metric.first() || (metric.value("metric_value").toString() == "xTupleERP"))
  {
    _splash->setPixmap(QPixmap(":/images/splashxTupleERP.png"));
    _Name = _Name.arg("Standard");
  }
  else
  {
    _splash->setPixmap(QPixmap(":/images/splashPostBooks.png"));
    _Name = _Name.arg("PostBooks");
  }

  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'OpenMFGServerVersion')" );
  if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion))
  {
    _splash->hide();
    int result;
    result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
      QObject::tr("The version of the database you are connecting to is not the version\n"
                  "this client was designed to work against.\n\n"
                  "This client was designed to work against the database version %1.\n"
                  "If you continue some or all functionality may not work properly\n"
                  "or at all. You may also cause other problems on the database.\n\n"
                  "Do you want to continue anyway?").arg(_dbVersion),
               QMessageBox::Yes,
               QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
    if(result != QMessageBox::Yes)
      return 0;
    _splash->show();
  }

  _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _metrics = new Metrics();

  _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _preferences = new Preferences(username);

  _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _privileges = new Privileges();

  // Load the translator and set the locale from the User's preferences
  QTranslator translator(0);
  _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList paths;
    paths << "dict";
    paths << "";
    paths << "../dict";
    paths << app.applicationDirPath() + "/dict";
    paths << app.applicationDirPath();
    paths << app.applicationDirPath() + "/../dict";
#if defined Q_WS_MACX
    paths << app.applicationDirPath() + "/../../../dict";
    paths << app.applicationDirPath() + "/../../..";
#endif
    
    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    if (!langq.value("lang_abbr2").toString().isEmpty() && 
        !langq.value("country_abbr").toString().isEmpty())
    {
      files << "xTuple." + langq.value("lang_abbr2").toString() + "_" +
               langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      files << "xTuple." + langq.value("lang_abbr2").toString();
    }

    if (files.size() > 0)
    {
      bool langFound = false;

      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit)
        {
          qDebug("looking for %s in %s",
                   (*fit).toAscii().data(), (*pit).toAscii().data());
          if (translator.load(*fit, *pit))
          {
            app.installTranslator(&translator);
            langFound = true;
            break;
          }
        }
      }

      if (!langFound && !_preferences->boolean("IngoreMissingTranslationFiles"))
        QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"),
                              QObject::tr("<p>The Translation Dictionaries %1 "
                                          "cannot be loaded. Reverting "
                                          "to the default dictionary." )
                                       .arg(files.join(QObject::tr(", "))));
    }

    /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or
       lang#, depending on what information is available
     */
    QString langAbbr = langq.value("lang_abbr2").toString();
    QString cntryAbbr = langq.value("country_abbr").toString().toUpper();
    if(cntryAbbr == "UK")
      cntryAbbr = "GB";
    if (! langAbbr.isEmpty() &&
        ! cntryAbbr.isEmpty())
      QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr));
    else if (! langAbbr.isEmpty())
      QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString()));
    else if (langq.value("lang_qt_number").toInt() &&
             langq.value("country_qt_number").toInt())
      QLocale::setDefault(
          QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()),
                  QLocale::Country(langq.value("country_qt_number").toInt())));
    else
      QLocale::setDefault(QLocale::system());

    qDebug("Locale set to language %s and country %s",
           QLocale().languageToString(QLocale().language()).toAscii().data(),
           QLocale().countryToString(QLocale().country()).toAscii().data());

  }
  else if (langq.lastError().type() != QSqlError::None)
  {
    systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__);
  }

  qApp->processEvents();
  QString key;

  // TODO: Add code to check a few locations - Hopefully done

  QString keypath;
  QString keyname;
  QString keytogether;
  
  keytogether = app.applicationDirPath() + "/OpenMFG.key";
#ifdef Q_WS_WIN
  keypath = _metrics->value("CCWinEncKey");
#elif defined Q_WS_MACX
  keypath = _metrics->value("CCMacEncKey");
#elif defined Q_WS_X11
  keypath = _metrics->value("CCLinEncKey");
#endif
  
  if (keypath.isEmpty())
    keypath = app.applicationDirPath();

  if (! keypath.endsWith(QDir::separator()))
    keypath += QDir::separator();

  keyname = _metrics->value("CCEncKeyName");
  if (keyname.isEmpty())
    keyname = "OpenMFG.key";
  
  keytogether = keypath + keyname;
  
  // qDebug("keytogether: %s", keytogether.toAscii().data());
  QFile keyFile(keytogether);

  if(keyFile.exists())
  {
    if(keyFile.open(QIODevice::ReadOnly))
    {
      key = keyFile.readLine(1024);
      // strip off any newline characters
      key = key.stripWhiteSpace();
    }
  }

  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;

// qDebug("Encryption Key: %s", key.toAscii().data() );
  
  if (key.length() > 0) {
	_splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor);
	qApp->processEvents();
	_metricsenc = new Metricsenc(key);
  }
  
  initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace());

  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->show();
    app.setMainWidget(omfgThis);
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    woTimeClock* newdlg = new woTimeClock();
    ParameterList params;
    params.append("captive");
    newdlg->set(params);
    newdlg->show();
    app.setMainWidget(newdlg);
  }

  if(!omfgThis->singleCurrency())
  {
    // Check for the gain/loss and discrep accounts
    q.prepare("SELECT COALESCE((SELECT TRUE"
              "                   FROM accnt, metric"
              "                  WHERE ((CAST(accnt_id AS text)=metric_value)"
              "                    AND  (metric_name='CurrencyGainLossAccount'))), FALSE)"
              "   AND COALESCE((SELECT TRUE"
              "                   FROM accnt, metric"
              "                  WHERE ((CAST(accnt_id AS text)=metric_value)"
              "                    AND  (metric_name='GLSeriesDiscrepancyAccount'))), FALSE) AS result; ");
    q.exec();
    if(q.first() && q.value("result").toBool() != true)
      QMessageBox::warning( omfgThis, QObject::tr("Additional Configuration Required"),
        QObject::tr("Your system is configured to use multiple Currencies, but the\n"
                    "Currency Gain/Loss Account and/or the G/L Series Discrepancy Account\n"
                    "does not appear to be configured correctly. You should define these\n"
                    "Accounts in 'System | Configure Modules | Configure G/L...' before\n"
                    "posting any transactions in the system.") );
  }

  app.exec();

//  Clean up
  delete _metrics;
  delete _preferences;
  delete _privileges;
  if (0 != _metricsenc)
    delete _metricsenc;

#ifdef XQ_WS_WIN
  WSACleanup();
#endif

  return 0;
}
Ejemplo n.º 2
0
void bankAdjustment::sSave()
{
  XSqlQuery bankSave;
  
  QList<GuiErrorCheck> errors;
  errors << GuiErrorCheck(!_date->isValid(), _date,
                          tr("You must enter a date before posting this Bank Adjustment."))
         << GuiErrorCheck(_amount->isZero(), _amount,
                          tr("You must enter an amount before posting this Bank Adjustment."))
  ;
  
  bankSave.prepare ("SELECT period_id "
                    "FROM period "
                    "WHERE :date BETWEEN period_start and period_end;");
  bankSave.bindValue(":date", _date->date());
  bankSave.exec();
  if (!bankSave.first())
  {
    errors << GuiErrorCheck(true, _date,
                            tr("You must enter a valid fiscal period date before posting this Bank Adjustment."));
  }
  
  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Bank Adjustment"), errors))
    return;
  
  if (_mode == cNew)
    bankSave.prepare("INSERT INTO bankadj "
                     "(bankadj_bankaccnt_id, bankadj_bankadjtype_id,"
                     " bankadj_date, bankadj_docnumber, bankadj_amount, "
                     " bankadj_notes, bankadj_curr_id ) "
                     "VALUES "
                     "(:bankaccnt_id, :bankadjtype_id,"
                     " :date, :docnumber, :amount, :notes, :curr_id);" );
  else if (_mode == cEdit)
  {
    bankSave.prepare ("UPDATE bankadj "
                      "SET bankadj_bankaccnt_id=:bankaccnt_id,"
                      " bankadj_bankadjtype_id=:bankadjtype_id,"
                      " bankadj_date=:date,"
                      " bankadj_docnumber=:docnumber,"
                      " bankadj_amount=:amount,"
                      " bankadj_notes=:notes, "
                      " bankadj_curr_id=:curr_id "
                      "WHERE ((bankadj_id=:bankadj_id)"
                      " AND (NOT bankadj_posted) ); ");
    bankSave.bindValue(":bankadj_id", _bankadjid);
  }
  
  bankSave.bindValue(":bankaccnt_id", _bankaccnt->id());
  bankSave.bindValue(":bankadjtype_id", _bankadjtype->id());
  bankSave.bindValue(":date", _date->date());
  bankSave.bindValue(":docnumber", _docNumber->text());
  bankSave.bindValue(":amount", _amount->localValue());
  bankSave.bindValue(":notes",   _notes->toPlainText());
  bankSave.bindValue(":curr_id", _amount->id());
  
  if(!bankSave.exec())
  {
    ErrorReporter::error(QtCriticalMsg, this, tr("Error Saving Bank Adjustment"),
                                    bankSave, __FILE__, __LINE__);
    return;
  }
  
  omfgThis->sBankAdjustmentsUpdated(_bankadjid, true);
  
  close();
}
Ejemplo n.º 3
0
void shipOrder::sHandleSo()
{
  XSqlQuery shipHandleSo;
  _coitem->clear();
  _shipment->setEnabled(false);
  _shipment->removeOrderLimit();

  sHandleButtons();


  shipHandleSo.prepare( "SELECT cohead_holdtype, cust_name, cohead_shiptoname, "
             "       cohead_shiptoaddress1, cohead_curr_id, cohead_freight "
             "FROM cohead, custinfo "
             "WHERE ((cohead_cust_id=cust_id) "
             "  AND  (cohead_id=:sohead_id));" );
  shipHandleSo.bindValue(":sohead_id", _order->id());
  shipHandleSo.exec();
  if (shipHandleSo.first())
  {
    QString msg;
    if ( (shipHandleSo.value("cohead_holdtype").toString() == "C"))
      msg = storedProcErrorLookup("shipShipment", -12);
    else if (shipHandleSo.value("cohead_holdtype").toString() == "P")
      msg = storedProcErrorLookup("shipShipment", -13);
    else if (shipHandleSo.value("cohead_holdtype").toString() == "R")
      msg = storedProcErrorLookup("shipShipment", -14);
    else if (shipHandleSo.value("cohead_holdtype").toString() == "S")
      msg = storedProcErrorLookup("shipShipment", -15);

    if (! msg.isEmpty())
    {
      QMessageBox::warning(this, tr("Cannot Ship Order"), msg);
      if (_captive)
      {
        _reject = true;	// so set() can return an error
        reject();	// this only works if shipOrder has been exec()'ed
      }
      else
      {
        _order->setId(-1);
        return;
      }
    }

    _freight->setId(shipHandleSo.value("cohead_curr_id").toInt());
    _freight->setLocalValue(shipHandleSo.value("cohead_freight").toDouble());
    _billToName->setText(shipHandleSo.value("cust_name").toString());
    _shipToName->setText(shipHandleSo.value("cohead_shiptoname").toString());
    _shipToAddr1->setText(shipHandleSo.value("cohead_shiptoaddress1").toString());

    QString sql( "SELECT shiphead_id "
                 "FROM shiphead "
                 "WHERE ( (NOT shiphead_shipped)"
                 "<? if exists(\"shiphead_id\") ?>"
                 " AND (shiphead_id=<? value(\"shiphead_id\") ?>)"
                 "<? endif ?>"
                 " AND (shiphead_order_id=<? value(\"sohead_id\") ?>)"
                 " AND (shiphead_order_type='SO'));" );
    ParameterList params;
    params.append("sohead_id", _order->id());
    if (_shipment->isValid())
      params.append("shiphead_id", _shipment->id());
    MetaSQLQuery mql(sql);
    shipHandleSo = mql.toQuery(params);
    if (shipHandleSo.first())
    {
      if (_shipment->id() != shipHandleSo.value("shiphead_id").toInt())
        _shipment->setId(shipHandleSo.value("shiphead_id").toInt());

      if (shipHandleSo.next())
      {
        _shipment->setType("SO");
        _shipment->limitToOrder(_order->id());
        _shipment->setEnabled(true);
      }
    }
    else if (shipHandleSo.lastError().type() != QSqlError::NoError)
    {
      systemError(this, shipHandleSo.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (_shipment->isValid())
    {
      params.clear();
      params.append("sohead_id", _order->id());
      MetaSQLQuery mql(sql);
      shipHandleSo = mql.toQuery(params);
      if (shipHandleSo.first())
      {
        _shipment->setId(shipHandleSo.value("shiphead_id").toInt());
        if (shipHandleSo.next())
        {
          _shipment->setType("SO");
          _shipment->limitToOrder(_order->id());
          _shipment->setEnabled(true);
        }
      }
      else if (shipHandleSo.lastError().type() != QSqlError::NoError)
      {
        systemError(this, shipHandleSo.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
      else
        _shipment->clear();
    }
    else
    {
      QMessageBox::warning(this, tr("Nothing to ship"),
                        tr("<p>You may not ship this Sales Order because "
                           "no stock has been issued to shipping for it."));
      _order->setFocus();
      return;
    }
  }
  else if (shipHandleSo.lastError().type() != QSqlError::NoError)
  {
    systemError(this, shipHandleSo.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Ejemplo n.º 4
0
void itemPricingScheduleItem::sSave( bool pClose)
{
    if(_itemSelected->isChecked())
    {
        q.prepare( "SELECT ipsitem_id "
                   "  FROM ipsitem "
                   " WHERE((ipsitem_ipshead_id=:ipshead_id)"
                   "   AND (ipsitem_item_id=:item_id)"
                   "   AND (ipsitem_qty_uom_id=:uom_id)"
                   "   AND (ipsitem_qtybreak=:qtybreak)"
                   "   AND (ipsitem_id <> :ipsitem_id));" );
        q.bindValue(":ipshead_id", _ipsheadid);
        q.bindValue(":item_id", _item->id());
        q.bindValue(":qtybreak", _qtyBreak->toDouble());
        q.bindValue(":uom_id", _qtyUOM->id());
        q.bindValue(":ipsitem_id", _ipsitemid);
        q.exec();
        if (q.first())
        {
            QMessageBox::critical( this, tr("Cannot Create Pricing Schedule Item"),
                                   tr( "There is an existing Pricing Schedule Item for the selected Pricing Schedule, Item and Quantity Break defined.\n"
                                       "You may not create duplicate Pricing Schedule Items." ) );
            return;
        }
        else if (q.lastError().type() != QSqlError::NoError)
        {
            systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                        __FILE__, __LINE__);
            done(-1);
        }
    }

    if (_mode == cNew)
    {
        if(_itemSelected->isChecked())
        {
            q.exec("SELECT NEXTVAL('ipsitem_ipsitem_id_seq') AS ipsitem_id;");
            if (q.first())
                _ipsitemid = q.value("ipsitem_id").toInt();
            //  ToDo

            q.prepare( "INSERT INTO ipsitem "
                       "( ipsitem_id, ipsitem_ipshead_id, ipsitem_item_id,"
                       "  ipsitem_qty_uom_id, ipsitem_qtybreak, "
                       "  ipsitem_price_uom_id, ipsitem_price, "
                       "  ipsitem_discntprcnt, ipsitem_fixedamtdiscount ) "
                       "VALUES "
                       "( :ipsitem_id, :ipshead_id, :ipsitem_item_id, "
                       "  :qty_uom_id, :ipsitem_qtybreak, "
                       "  :price_uom_id, :ipsitem_price, "
                       "  :ipsitem_discntprcnt, :ipsitem_fixedamtdiscount );" );
        }
        else if(_discountSelected->isChecked())
        {
            if(_dscbyItem->isChecked())
            {
                q.prepare( "SELECT * "
                           "FROM ipsitem JOIN ipshead ON (ipsitem_ipshead_id=ipshead_id) "
                           "WHERE ((ipshead_id = :ipshead_id)"
                           "   AND (ipsitem_item_id = :item_id)"
                           "   AND (ipsitem_qtybreak = :qtybreak));");

                q.bindValue(":ipshead_id", _ipsheadid);
                q.bindValue(":item_id", _dscitem->id());
                q.bindValue(":qtybreak", _qtyBreakCat->toDouble());
                q.exec();
                if (q.first())
                {
                    QMessageBox::critical( this, tr("Cannot Create Pricing Schedule Item"),
                                           tr( "There is an existing Pricing Schedule Item for the selected Pricing Schedule, Item and Quantity Break defined.\n"
                                               "You may not create duplicate Pricing Schedule Items." ) );
                    return;
                }
                else if (q.lastError().type() != QSqlError::NoError)
                {
                    systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                                __FILE__, __LINE__);
                    done(-1);
                }
                q.exec("SELECT NEXTVAL ('ipsitem_ipsitem_id_seq') AS ipsitem_id;");
                if (q.first())
                    _ipsitemid = q.value("ipsitem_id").toInt();
                else if (q.lastError().type() != QSqlError::NoError)
                {
                    systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                                __FILE__, __LINE__);
                    done(-1);
                }

                q.prepare("INSERT INTO ipsitem "
                          "( ipsitem_id, ipsitem_ipshead_id, "
                          "  ipsitem_item_id, ipsitem_qtybreak, "
                          "  ipsitem_price, ipsitem_qty_uom_id, "
                          "  ipsitem_price_uom_id, ipsitem_discntprcnt, "
                          "  ipsitem_fixedamtdiscount ) "
                          "VALUES "
                          "( :ipsitem_id, :ipshead_id, "
                          "  :ipsitem_item_id, :ipsitem_qtybreak, "
                          "  :ipsitem_price, :ipsitem_qty_uom_id, "
                          "  :ipsitem_price_uom_id, :ipsitem_discntprcnt, "
                          "  :ipsitem_fixedamtdiscount); ");

                XSqlQuery qry;
                qry.prepare("SELECT item_inv_uom_id, item_price_uom_id "
                            "FROM item "
                            "WHERE (item_id=:item_id);");
                qry.bindValue(":item_id", _dscitem->id());
                qry.exec();
                if (qry.first())
                {
                    q.bindValue(":ipsitem_qty_uom_id", qry.value("item_inv_uom_id"));
                    q.bindValue(":ipsitem_price_uom_id", qry.value("item_price_uom_id"));
                }
                else if (qry.lastError().type() != QSqlError::NoError)
                {
                    systemError(this, _rejectedMsg.arg(qry.lastError().databaseText()),
                                __FILE__, __LINE__);
                    done(-1);
                }
            }
            else if(_dscbyprodcat->isChecked())
            {
                q.prepare( "SELECT ipsprodcat_id "
                           "FROM ipsprodcat "
                           "WHERE ( (ipsprodcat_ipshead_id=:ipshead_id)"
                           " AND (ipsprodcat_prodcat_id=:prodcat_id)"
                           " AND (ipsprodcat_qtybreak=:qtybreak) );" );
                q.bindValue(":ipshead_id", _ipsheadid);
                q.bindValue(":prodcat_id", _prodcat->id());
                q.bindValue(":qtybreak", _qtyBreakCat->toDouble());
                q.exec();
                if (q.first())
                {
                    QMessageBox::critical( this, tr("Cannot Create Pricing Schedule Item"),
                                           tr( "There is an existing Pricing Schedule Item for the selected Pricing Schedule, Product Category and Quantity Break defined.\n"
                                               "You may not create duplicate Pricing Schedule Items." ) );
                    return;
                }
                else if (q.lastError().type() != QSqlError::NoError)
                {
                    systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                                __FILE__, __LINE__);
                    done(-1);
                }

                q.exec("SELECT NEXTVAL('ipsprodcat_ipsprodcat_id_seq') AS ipsprodcat_id;");
                if (q.first())
                    _ipsprodcatid = q.value("ipsprodcat_id").toInt();
                else if (q.lastError().type() != QSqlError::NoError)
                {
                    systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                                __FILE__, __LINE__);
                    done(-1);
                }
                //  ToDo

                q.prepare( "INSERT INTO ipsprodcat "
                           "( ipsprodcat_id, ipsprodcat_ipshead_id, ipsprodcat_prodcat_id, ipsprodcat_qtybreak,"
                           "  ipsprodcat_discntprcnt, ipsprodcat_fixedamtdiscount )"
                           "VALUES "
                           "( :ipsprodcat_id, :ipshead_id, :ipsprodcat_prodcat_id, :ipsprodcat_qtybreak,"
                           "  :ipsprodcat_discntprcnt, :ipsprodcat_fixedamtdiscount );" );
            }
        }
        else if(_freightSelected->isChecked())
        {
            q.prepare( "SELECT ipsfreight_id "
                       "FROM ipsfreight "
                       "WHERE ( (ipsfreight_ipshead_id=:ipshead_id)"
                       " AND (ipsfreight_warehous_id=:warehous_id)"
                       " AND (ipsfreight_shipzone_id=:shipzone_id)"
                       " AND (ipsfreight_freightclass_id=:freightclass_id)"
                       " AND (ipsfreight_shipvia=:shipvia)"
                       " AND (ipsfreight_qtybreak=:qtybreak) );" );
            q.bindValue(":ipshead_id", _ipsheadid);
            q.bindValue(":warehous_id", _siteFreight->id());
            q.bindValue(":shipzone_id", _zoneFreight->id());
            q.bindValue(":freightclass_id", _freightClass->id());
            q.bindValue(":shipvia", _shipViaFreight->currentText());
            q.bindValue(":qtybreak", _qtyBreakFreight->toDouble());
            q.exec();
            if (q.first())
            {
                QMessageBox::critical( this, tr("Cannot Create Pricing Schedule Item"),
                                       tr( "There is an existing Pricing Schedule Item for the selected Pricing Schedule, Freight Criteria and Quantity Break defined.\n"
                                           "You may not create duplicate Pricing Schedule Items." ) );
                return;
            }
            else if (q.lastError().type() != QSqlError::NoError)
            {
                systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                            __FILE__, __LINE__);
                done(-1);
            }

            q.exec("SELECT NEXTVAL('ipsfreight_ipsfreight_id_seq') AS ipsfreight_id;");
            if (q.first())
                _ipsfreightid = q.value("ipsfreight_id").toInt();
            else if (q.lastError().type() != QSqlError::NoError)
            {
                systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                            __FILE__, __LINE__);
                done(-1);
            }
            //  ToDo

            q.prepare( "INSERT INTO ipsfreight "
                       "( ipsfreight_id, ipsfreight_ipshead_id, ipsfreight_qtybreak, ipsfreight_price,"
                       "  ipsfreight_type, ipsfreight_warehous_id, ipsfreight_shipzone_id,"
                       "  ipsfreight_freightclass_id, ipsfreight_shipvia ) "
                       "VALUES "
                       "( :ipsfreight_id, :ipshead_id, :ipsfreight_qtybreak, :ipsfreight_price,"
                       "  :ipsfreight_type, :ipsfreight_warehous_id, :ipsfreight_shipzone_id,"
                       "  :ipsfreight_freightclass_id, :ipsfreight_shipvia ) " );
        }
    }
    else if (_mode == cEdit)
    {
        if(_itemSelected->isChecked())
            q.prepare( "UPDATE ipsitem "
                       "   SET ipsitem_qty_uom_id=:qty_uom_id,"
                       "       ipsitem_qtybreak=:ipsitem_qtybreak,"
                       "       ipsitem_price_uom_id=:price_uom_id,"
                       "       ipsitem_price=:ipsitem_price "
                       "WHERE (ipsitem_id=:ipsitem_id);" );
        else if(_discountSelected->isChecked())
        {
            if(_dscbyprodcat->isChecked())
            {
                q.prepare( "UPDATE ipsprodcat "
                           "   SET ipsprodcat_qtybreak=:ipsprodcat_qtybreak,"
                           "       ipsprodcat_discntprcnt=:ipsprodcat_discntprcnt,"
                           "       ipsprodcat_fixedamtdiscount=:ipsprodcat_fixedamtdiscount "
                           "WHERE (ipsprodcat_id=:ipsprodcat_id);" );
            }
            else if(_dscbyItem->isChecked())
            {
                q.prepare("UPDATE ipsiteminfo "
                          "SET ipsitem_qtybreak = :ipsitem_qtybreak, "
                          "    ipsitem_discntprcnt = :ipsitem_discntprcnt, "
                          "    ipsitem_fixedamtdiscount = :ipsitem_fixedamtdiscount "
                          "WHERE (ipsitem_id= :ipsitem_id);");
            }
        }
        else if(_freightSelected->isChecked())
            q.prepare( "UPDATE ipsfreight "
                       "   SET ipsfreight_qtybreak=:ipsfreight_qtybreak,"
                       "       ipsfreight_type=:ipsfreight_type,"
                       "       ipsfreight_price=:ipsfreight_price,"
                       "       ipsfreight_warehous_id=:ipsfreight_warehous_id,"
                       "       ipsfreight_shipzone_id=:ipsfreight_shipzone_id,"
                       "       ipsfreight_freightclass_id=:ipsfreight_freightclass_id,"
                       "       ipsfreight_shipvia=:ipsfreight_shipvia "
                       "WHERE (ipsfreight_id=:ipsfreight_id);" );
    }

    q.bindValue(":ipsitem_id", _ipsitemid);
    q.bindValue(":ipsprodcat_id", _ipsprodcatid);
    q.bindValue(":ipsfreight_id", _ipsfreightid);
    q.bindValue(":ipshead_id", _ipsheadid);

    if(_itemSelected->isChecked())
    {
        q.bindValue(":ipsitem_item_id", _item->id());
        q.bindValue(":ipsitem_qtybreak", _qtyBreak->toDouble());
        q.bindValue(":ipsitem_discntprcnt", 0.00);
        q.bindValue(":ipsitem_fixedamtdiscount", 0.00);
        q.bindValue(":ipsitem_price", _price->localValue());
    }
    else if((_discountSelected->isChecked()) && (_dscbyItem->isChecked()))
    {
        q.bindValue(":ipsitem_item_id", _dscitem->id());
        q.bindValue(":ipsitem_qtybreak", _qtyBreakCat->toDouble());
        q.bindValue(":ipsitem_discntprcnt", (_discount->toDouble() / 100.0));
        q.bindValue(":ipsitem_fixedamtdiscount", (_fixedAmtDiscount->localValue()));
        q.bindValue(":ipsitem_price", 0.00);
    }

    q.bindValue(":ipsprodcat_prodcat_id", _prodcat->id());
    q.bindValue(":ipsprodcat_qtybreak", _qtyBreakCat->toDouble());
    q.bindValue(":ipsfreight_qtybreak", _qtyBreakFreight->toDouble());
    q.bindValue(":ipsprodcat_discntprcnt", (_discount->toDouble() / 100.0));
    q.bindValue(":ipsprodcat_fixedamtdiscount", (_fixedAmtDiscount->localValue()));
    q.bindValue(":ipsfreight_price", _priceFreight->localValue());
    q.bindValue(":qty_uom_id", _qtyUOM->id());
    q.bindValue(":price_uom_id", _priceUOM->id());

    if (_flatRateFreight->isChecked())
        q.bindValue(":ipsfreight_type", "F");
    else
        q.bindValue(":ipsfreight_type", "P");
    if (_siteFreight->isSelected())
        q.bindValue(":ipsfreight_warehous_id", _siteFreight->id());
    if (_selectedZoneFreight->isChecked())
        q.bindValue(":ipsfreight_shipzone_id", _zoneFreight->id());
    if (_selectedFreightClass->isChecked())
        q.bindValue(":ipsfreight_freightclass_id", _freightClass->id());
    if (_selectedShipViaFreight->isChecked())
        q.bindValue(":ipsfreight_shipvia", _shipViaFreight->currentText());
    q.exec();
    if (q.lastError().type() != QSqlError::NoError)
    {
        systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                    __FILE__, __LINE__);
        done(-1);
    }

    if (pClose)
    {
        if(_itemSelected->isChecked())
            done(_ipsitemid);
        if(_discountSelected->isChecked())
        {
            if(_dscbyItem->isChecked())
                done(_ipsitemid);
            else if(_dscbyprodcat->isChecked())
                done(_ipsprodcatid);
        }
        if(_freightSelected->isChecked())
            done(_ipsfreightid);
    }
    else
    {
        _mode = cEdit;

        _item->setReadOnly(TRUE);
        _prodcat->setEnabled(FALSE);
        _typeGroup->setEnabled(FALSE);
    }

}
Ejemplo n.º 5
0
void todoItem::sSave()
{
  RecurrenceWidget::RecurrenceChangePolicy cp = _recurring->getChangePolicy();
  if (cp == RecurrenceWidget::NoPolicy)
    return;

  QString storedProc;
  XSqlQuery beginq("BEGIN;");
  XSqlQuery rollbackq;
  rollbackq.prepare("ROLLBACK;");
  if (_mode == cNew)
  {
    q.prepare( "SELECT createTodoItem(:todoitem_id, :username, :name, :description, "
	       "  :incdt_id, :crmacct_id, :ophead_id, :started, :due, :status, "
	       "  :assigned, :completed, :priority, :notes, :owner) AS result;");
    storedProc = "createTodoItem";
  }
  else if (_mode == cEdit)
  {
    q.prepare( "SELECT updateTodoItem(:todoitem_id, "
	       "  :username, :name, :description, "
	       "  :incdt_id, :crmacct_id, :ophead_id, :started, :due, :status, "
	       "  :assigned, :completed, :priority, :notes, :active, :owner) AS result;");
    storedProc = "updateTodoItem";
  }
  q.bindValue(":todoitem_id", _todoitemid);
  q.bindValue(":owner", _owner->username());
  q.bindValue(":username",   _assignedTo->username());
  if(_assigned->date().isValid())
    q.bindValue(":assigned", _assigned->date());
  q.bindValue(":name",		_name->text());
  q.bindValue(":description",	_description->text());
  if (_incident->id() > 0)
    q.bindValue(":incdt_id",	_incident->id());	// else NULL
  if (_crmacct->id() > 0)
    q.bindValue(":crmacct_id",	_crmacct->id());	// else NULL
  q.bindValue(":started",	_started->date());
  q.bindValue(":due",		_due->date());
  q.bindValue(":assigned",	_assigned->date());
  q.bindValue(":completed",	_completed->date());
  if(_priority->isValid())
    q.bindValue(":priority", _priority->id());
  q.bindValue(":notes",		_notes->toPlainText());
  q.bindValue(":active",	QVariant(_active->isChecked()));
  if(_ophead->id() > 0)
    q.bindValue(":ophead_id", _ophead->id());

  QString status;
  if (_completed->date().isValid())
    status = "C";
  else if (_deferred->isChecked())
    status = "D";
  else if (_pending->isChecked())
    status = "P";
  else if (_started->date().isValid())
    status = "I";
  else
    status = "N";
  q.bindValue(":status", status);

  q.exec();
  if (q.first())
  {
    int result = q.value("result").toInt();
    if (result < 0)
    {
      systemError(this, storedProcErrorLookup(storedProc, result), __FILE__, __LINE__);
      rollbackq.exec();
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    rollbackq.exec();
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  // TODO: make this part of {create,update}TodoItem?
  if (_recurring->isRecurring())
  {
    XSqlQuery recurq;
    recurq.prepare("UPDATE todoitem"
                   "   SET todoitem_recurring_todoitem_id=:parent_id"
                   " WHERE todoitem_id=:id;");
    recurq.bindValue(":parent_id", _recurring->parentId());
    recurq.bindValue(":id",        _todoitemid);
    if (! recurq.exec())
    {
      rollbackq.exec();
      systemError(this, recurq.lastError().text(), __FILE__, __LINE__);
      return;
    }
  }

  QString errmsg;
  if (! _recurring->save(true, cp, errmsg))
  {
    rollbackq.exec();
    systemError(this, errmsg, __FILE__, __LINE__);
    return;
  }

  XSqlQuery commitq("COMMIT;");

  done(_todoitemid);
}
bool dspGLTransactions::setParams(ParameterList &params)
{
  if (!display::setParams(params))
    return false;

  bool valid;
  QVariant param;

  param = params.value("accnttype_id", &valid);
  if (valid)
  {
    int typid = param.toInt();
    QString type;

    if (typid == 1)
      type = "A";
    else if (typid ==2)
      type = "E";
    else if (typid ==3)
      type = "L";
    else if (typid ==4)
      type = "Q";
    else if (typid ==5)
      type = "R";

    params.append("accntType", type);
  }

  param = params.value("source_id", &valid);
  if (valid)
    params.append("source", _sources.at(param.toInt()));

  param = params.value("num_id", &valid);
  if (valid)
  {
    XSqlQuery num;
    num.prepare("SELECT accnt_number "
                "FROM accnt "
                "WHERE (accnt_id=:accnt_id);");
    num.bindValue(":accnt_id", params.value("num_id").toInt());
    num.exec();
    if (num.first())
      params.append("accnt_number", num.value("accnt_number").toString());
  }

  param = params.value("accnt_id", &valid);
  if (valid)
  {
    if (_showRunningTotal->isChecked() &&
        _showRunningTotal->isVisible())
    {
      double beginning = 0;
      QDate  periodStart = params.value("startDate").toDate();
      XSqlQuery begq;
      begq.prepare("SELECT "
                   "  CASE WHEN accnt_type IN ('A','E') THEN "
                   "    trialbal_beginning * -1 "
                   "  ELSE trialbal_beginning END AS trialbal_beginning,"
                   "  period_start "
                   "FROM trialbal "
                   "  JOIN accnt ON (trialbal_accnt_id=accnt_id), "
                   "  period "
                   "WHERE ((trialbal_period_id=period_id)"
                   "  AND  (trialbal_accnt_id=:accnt_id)"
                   "  AND  (:start BETWEEN period_start AND period_end));");
      begq.bindValue(":accnt_id", params.value("accnt_id").toInt());
      begq.bindValue(":start", params.value("startDate").toDate());
      begq.exec();
      if (begq.first())
      {
        beginning   = begq.value("trialbal_beginning").toDouble();
        periodStart = begq.value("period_start").toDate();
      }
      else if (begq.lastError().type() != QSqlError::NoError)
      {
	systemError(this, begq.lastError().databaseText(), __FILE__, __LINE__);
	return false;
      }
      XSqlQuery glq;
      glq.prepare("SELECT CASE WHEN accnt_type IN ('A','E') THEN "
                  "         COALESCE(SUM(gltrans_amount),0) * -1"
                  "       ELSE COALESCE(SUM(gltrans_amount),0) END AS glamount "
                  "FROM gltrans "
                  "  JOIN accnt ON (gltrans_accnt_id=accnt_id) "
                  "WHERE ((gltrans_date BETWEEN :periodstart AND date :querystart - interval '1 day')"
                  "  AND  (gltrans_accnt_id=:accnt_id)"
                  "  AND  (NOT gltrans_deleted)) "
                  "GROUP BY accnt_type;");
      glq.bindValue(":periodstart", periodStart);
      glq.bindValue(":querystart",  params.value("startDate").toDate());
      glq.bindValue(":accnt_id",    params.value("accnt_id").toInt());
      glq.exec();
      if (glq.first())
        beginning   += glq.value("glamount").toDouble();
      else if (glq.lastError().type() != QSqlError::NoError)
      {
	systemError(this, glq.lastError().databaseText(), __FILE__, __LINE__);
	return false;
      }

      params.append("beginningBalance", beginning);
    }
  }

  return true;
}
Ejemplo n.º 7
0
void company::sSave()
{
  XSqlQuery companySave;
  if (_number->text().length() == 0)
  {
      QMessageBox::warning( this, tr("Cannot Save Company"),
                            tr("You must enter a valid Number.") );
      _number->setFocus();
      return;
  }
  
  struct {
    bool	condition;
    QString	msg;
    QWidget*	widget;
  } error[] = {
    { _external->isChecked() && _extServer->text().isEmpty(),
      tr("<p>You must enter a Server if this is an external Company."),
      _extServer
    },
    { _external->isChecked() && _extPort->value() == 0,
      tr("<p>You must enter a Port if this is an external Company."),
      _extPort
    },
    { _external->isChecked() && _extDB->text().isEmpty(),
      tr("<p>You must enter a Database if this is an external Company."),
      _extDB
    },
    { true, "", NULL }
  }; // error[]

  int errIndex;
  for (errIndex = 0; ! error[errIndex].condition; errIndex++)
    ;
  if (! error[errIndex].msg.isEmpty())
  {
    QMessageBox::critical(this, tr("Cannot Save Company"),
			  error[errIndex].msg);
    error[errIndex].widget->setFocus();
    return;
  }

  companySave.prepare("SELECT company_id"
            "  FROM company"
            " WHERE((company_id != :company_id)"
            "   AND (company_number=:company_number))");
  companySave.bindValue(":company_id",       _companyid);
  companySave.bindValue(":company_number",   _number->text());
  companySave.exec();
  if(companySave.first())
  {
    QMessageBox::critical(this, tr("Duplicate Company Number"),
      tr("A Company Number already exists for the one specified.") );
    _number->setFocus();
    return;
  }

  if (_yearend->isValid() &&
      _companyid != _yearend->companyId())
  {
    QMessageBox::critical(this, tr("Company Account Mismatch"),
                          tr("The Retained Earnings Account must belong to this Company.") );
    _yearend->setFocus();
    return;
  }

  if (_gainloss->isValid() &&
      _companyid != _gainloss->companyId())
  {
    QMessageBox::critical(this, tr("Company Account Mismatch"),
                          tr("The Currency Gain/Loss Account must belong to this Company.") );
    _gainloss->setFocus();
    return;
  }

  if (_discrepancy->isValid() &&
      _companyid != _discrepancy->companyId())
  {
    QMessageBox::critical(this, tr("Company Account Mismatch"),
                          tr("The G/L Discrepancy Account must belong to this Company.") );
    _discrepancy->setFocus();
    return;
  }

  if (_unrlzgainloss->isValid() &&
      _companyid != _unrlzgainloss->companyId())
  {
    QMessageBox::critical(this, tr("Company Account Mismatch"),
                          tr("The Unrealized Currency Gain/Loss Account must belong to this Company.") );
    _unrlzgainloss->setFocus();
    return;
  }

  if (_mode == cNew)
  {
    companySave.exec("SELECT NEXTVAL('company_company_id_seq') AS company_id;");
    if (companySave.first())
      _companyid = companySave.value("company_id").toInt();
    else if (companySave.lastError().type() != QSqlError::NoError)
    {
      systemError(this, companySave.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    
    companySave.prepare( "INSERT INTO company "
               "( company_id, company_number, company_descrip,"
               "  company_external, company_server, company_port,"
               "  company_database, company_curr_id, company_yearend_accnt_id, "
               "  company_gainloss_accnt_id, company_dscrp_accnt_id, "
               "  company_unrlzgainloss_accnt_id) "
               "VALUES "
               "( :company_id, :company_number, :company_descrip,"
               "  :company_external, :company_server, :company_port, "
               "  :company_database, :company_curr_id, :company_yearend_accnt_id, "
               "  :company_gainloss_accnt_id, :company_dscrp_accnt_id, "
               "  :company_unrlzgainloss_accnt_id);" );
  }
  else if (_mode == cEdit)
  {
    if (_number->text() != _cachedNumber &&
        QMessageBox::question(this, tr("Change All Accounts?"),
                          _external->isChecked() ?
                              tr("<p>The old Company Number %1 might be used "
                                 "by existing Accounts, including Accounts in "
                                 "the %2 child database. Would you like to "
                                 "change all accounts in the current database "
                                 "that use it to Company Number %3?<p>If you "
                                 "answer 'No' then either Cancel or change the "
                                 "Number back to %4 and Save again. If you "
                                 "answer 'Yes' then change the Company Number "
                                 "in the child database as well.")
                                .arg(_cachedNumber)
                                .arg(_extDB->text())
                                .arg(_number->text())
                                .arg(_cachedNumber)
                            :
                              tr("<p>The old Company Number %1 might be used "
                                 "by existing Accounts. Would you like to "
                                 "change all accounts that use it to Company "
                                 "Number %2?<p>If you answer 'No' then either "
                                 "Cancel or change "
                                 "the Number back to %3 and Save again.")
                                .arg(_cachedNumber)
                                .arg(_number->text())
                                .arg(_cachedNumber),
                              QMessageBox::Yes,
                              QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
      return;

    companySave.prepare( "UPDATE company "
               "SET company_number=:company_number,"
               "    company_descrip=:company_descrip,"
               "    company_external=:company_external,"
               "    company_server=:company_server,"
               "    company_port=:company_port,"
               "    company_database=:company_database, "
               "    company_curr_id=:company_curr_id, "
               "    company_yearend_accnt_id=:company_yearend_accnt_id, "
               "    company_gainloss_accnt_id=:company_gainloss_accnt_id, "
               "    company_dscrp_accnt_id=:company_dscrp_accnt_id, "
               "    company_unrlzgainloss_accnt_id=:company_unrlzgainloss_accnt_id "
               "WHERE (company_id=:company_id);" );
  }
  
  companySave.bindValue(":company_id",       _companyid);
  companySave.bindValue(":company_number",   _number->text());
  companySave.bindValue(":company_descrip",  _descrip->toPlainText());
  companySave.bindValue(":company_external", _external->isChecked());
  companySave.bindValue(":company_server",   _extServer->text());
  companySave.bindValue(":company_port",     _extPort->cleanText());
  companySave.bindValue(":company_database", _extDB->text());
  if (_gainloss->isValid())
    companySave.bindValue(":company_gainloss_accnt_id", _gainloss->id());
  if (_discrepancy->isValid())
    companySave.bindValue(":company_dscrp_accnt_id", _discrepancy->id());
  if (_yearend->isValid())
    companySave.bindValue(":company_yearend_accnt_id", _yearend->id());
  if (_external->isChecked())
  {
    companySave.bindValue(":company_curr_id", _currency->id());
    if (_unrlzgainloss->isValid())
      companySave.bindValue(":company_unrlzgainloss_accnt_id", _unrlzgainloss->id());
  }
  companySave.exec();
  if (companySave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, companySave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if ((!_yearend->isValid()) ||
     (!_gainloss->isValid()) ||
     (!_discrepancy->isValid()) ||
     (_external->isChecked() &&
      _currency->id() != CurrCluster::baseId() &&
      !_unrlzgainloss->isValid()))
  {
    QMessageBox::warning( this, tr("Accounts Required"),
                          tr("You will need to return to this window to set "
                             "required Accounts before you can use Accounts "
                             "for this company in the system.") );
  }
  
  done(_companyid);
}
Ejemplo n.º 8
0
itemSource::itemSource(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)
    : XDialog(parent, name, modal, fl)
{
  XSqlQuery itemitemSource;
  setupUi(this);

  connect(_add,                SIGNAL(clicked()), this, SLOT(sAdd()));
  connect(_close,              SIGNAL(clicked()), this, SLOT(reject()));
  connect(_delete,             SIGNAL(clicked()), this, SLOT(sDelete()));
  connect(_edit,               SIGNAL(clicked()), this, SLOT(sEdit()));
  connect(_itemsrcp,SIGNAL(populateMenu(QMenu*, XTreeWidgetItem*)), this, SLOT(sPopulateMenu(QMenu*)));
  connect(_save,               SIGNAL(clicked()), this, SLOT(sSaveClicked()));
  connect(_vendor,             SIGNAL(newId(int)), this, SLOT(sVendorChanged(int)));
  connect(_vendorCurrency,     SIGNAL(newID(int)), this, SLOT(sFillPriceList()));
  connect(_contract,           SIGNAL(newID(int)), this, SLOT(sContractChanged(int)));
  connect(this,                SIGNAL(rejected()), this, SLOT(sRejected()));

//  TODO method doesn't exist?
//  connect(_vendorUOM, SIGNAL(textChanged()), this, SLOT(sClearVendorUOM()));
//  connect(_invVendorUOMRatio, SIGNAL(textChanged(QString)), this, SLOT(sClearVendorUOM()));

  _vendorUOM->setType(XComboBox::UOMs);

  _item->setType(ItemLineEdit::cGeneralPurchased | ItemLineEdit::cGeneralManufactured | ItemLineEdit::cTooling);
  _item->setDefaultType(ItemLineEdit::cGeneralPurchased);

  _dates->setStartNull(tr("Always"), omfgThis->startOfTime(), true);
  _dates->setStartCaption(tr("Effective"));
  _dates->setEndNull(tr("Never"), omfgThis->endOfTime(), true);
  _dates->setEndCaption(tr("Expires"));

  _captive = false;
  _new = false;
  
  QString base;
  itemitemSource.exec("SELECT currConcat(baseCurrID()) AS base;");
  if (itemitemSource.first())
    base = itemitemSource.value("base").toString();
  else
    base = tr("Base");

  if (_metrics->boolean("MultiWhs"))
  {
    _itemsrcp->addColumn(tr("Site"),                      _qtyColumn, Qt::AlignCenter,true, "warehous_code");
    _itemsrcp->addColumn(tr("Order Type"),                        -1, Qt::AlignCenter,true, "itemsrcp_dropship");
  }
  _itemsrcp->addColumn(tr("Qty Break"),                   _qtyColumn, Qt::AlignRight, true, "itemsrcp_qtybreak");
  _itemsrcp->addColumn(tr("Unit Price"),                          -1, Qt::AlignRight, true, "itemsrcp_price");
  _itemsrcp->addColumn(tr("Currency"),               _currencyColumn, Qt::AlignLeft, !omfgThis->singleCurrency(), "item_curr");
  _itemsrcp->addColumn(tr("Discount Percent"),                    -1, Qt::AlignRight, true, "itemsrcp_discntprcnt" );
  _itemsrcp->addColumn(tr("Discount Fixed Amt."),                 -1, Qt::AlignRight, true, "itemsrcp_fixedamtdiscount" );
  _itemsrcp->addColumn(tr("Unit Price\n(%1)").arg(base),_moneyColumn, Qt::AlignRight, !omfgThis->singleCurrency(), "price_base");
  _itemsrcp->addColumn(tr("Type"),                      _orderColumn, Qt::AlignLeft,  true, "type" );
  _itemsrcp->addColumn(tr("Method"),                    _orderColumn, Qt::AlignLeft,  true, "method" );

  _invVendorUOMRatio->setValidator(omfgThis->ratioVal());
  _minOrderQty->setValidator(omfgThis->qtyVal());
  _multOrderQty->setValidator(omfgThis->qtyVal());
  _contractedQty->setValidator(omfgThis->qtyVal());
  _contractedQty->setAlignment(Qt::AlignRight);

  _vendorCurrency->setType(XComboBox::Currencies);
  _vendorCurrency->setLabel(_vendorCurrencyLit);
  
  itemitemSource.exec("SELECT MAX(itemsrc_id),itemsrc_manuf_name, itemsrc_manuf_name "
                      "FROM itemsrc "
                      "WHERE (itemsrc_manuf_name != '') "
                      "GROUP BY itemsrc_manuf_name "
                      "ORDER BY itemsrc_manuf_name;");
  _manufName->populate(itemitemSource);
  _manufName->setCurrentIndex(0);
}
Ejemplo n.º 9
0
void enterPoReturn::sPost()
{
  bool createMemo = false;
  
  q.prepare("SELECT SUM(poreject_qty) AS qtyToReturn, MIN(poitem_status) AS poitem_status "
            "FROM poreject, poitem "
            "WHERE ((poreject_poitem_id=poitem_id)"
            "  AND  (NOT poreject_posted)"
	    "  AND  (poitem_pohead_id=:pohead_id));");
  q.bindValue(":pohead_id", _po->id());
  q.exec();
  if (q.first())
  {
    if (q.value("qtyToReturn").toDouble() == 0)
    {
      QMessageBox::critical(this, tr("Nothing selected for Return"),
			    tr("<p>No Purchase Order Items have been selected "
			       "to be returned. Select at least one Line Item "
			       "and enter a Return before trying to Post."));
      return;
    }
  //Offer to create credit memo
    if ( (_privileges->check("MaintainAPMemos")) && (q.value("poitem_status").toString() == "C") )
      if ( QMessageBox::question( this, tr("Create Credit Memo"),
                                        tr("One or more line items on this P/O are closed. \n"
                                           "Would you like to automatically create a credit memo against this return?"),
                                        tr("&Yes"), tr("&No"), QString::null, 0, 1 ) == 0 )
        createMemo = true;
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  int saveResult = _returnAddr->save(AddressCluster::CHECK);
  if (-2 == saveResult)
  {
    if (QMessageBox::question(this,
		    tr("Saving Shared Address"),
		    tr("<p>There are multiple uses for this Address. "
		       "If you save this Address, the Address for all "
		       "of these uses will be changed. Would you like to "
		       "save this Address?"),
		    QMessageBox::No | QMessageBox::Default, QMessageBox::Yes))
	saveResult = _returnAddr->save(AddressCluster::CHANGEALL);
  }
  if (0 > saveResult)	// NOT else if
  {
    systemError(this, tr("<p>There was an error saving this address (%1). "
			 "Check the database server log for errors.")
		      .arg(saveResult),
		__FILE__, __LINE__);
  }

  // print while we can still differentiate current from previous returns
  if (_printReport->isChecked())
  {
    ParameterList params;
    params.append("pohead_id", _po->id());
    if (_returnAddr->isValid())
      params.append("addr_id", _returnAddr->id());
    orReport report("UnpostedReturnsForPO", params);
    if (report.isValid())
      report.print();
    else
    {
      report.reportError(this);
      return;
    }
  }
  
  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  // Get the list of returns that are going to be posted
  XSqlQuery reject;
  reject.prepare("SELECT poreject_id"
                 "  FROM poreject, poitem"
                 " WHERE((NOT poreject_posted)"
                 "   AND (poreject_poitem_id=poitem_id)"
                 "   AND (poitem_pohead_id=:pohead_id));");
  reject.bindValue(":pohead_id", _po->id());
  reject.exec();

  q.exec("BEGIN;");	// because of possible insertgltransaction failures

  // post the returns
  q.prepare("SELECT postPoReturns(:pohead_id,false) AS result;");
  q.bindValue(":pohead_id", _po->id());
  q.exec();
  int result = 0;
  if (q.first())
  {
    result = q.value("result").toInt();
    if (result < 0)
    {
      rollback.exec();
      systemError(this, storedProcErrorLookup("postPoReturns", result),
		  __FILE__, __LINE__);
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    rollback.exec();
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (distributeInventory::SeriesAdjust(q.value("result").toInt(), this) == XDialog::Rejected)
  {
    rollback.exec();
    QMessageBox::information( this, tr("Enter PO Return"), tr("Transaction Canceled") );
    return;
  }
  
  q.exec("COMMIT;");

  // if we are creating the credit memo go ahead and loop the returns that
  // we have just posted and create the credit memos.
  if(createMemo)
  {
    while(reject.next())
    {
      ParameterList params;
      params.append("poreject_id", reject.value("poreject_id").toInt());

      postPoReturnCreditMemo newdlg(this, "", TRUE);
      newdlg.set(params);

      newdlg.exec();
    }
  }


  if (_captive)
    close();
  else
  {
    _close->setText(tr("&Close"));
    _po->setId(-1);
  }
}
Ejemplo n.º 10
0
enum SetResponse itemSource::set(const ParameterList &pParams)
{
  XSqlQuery itemet;
  XDialog::set(pParams);
  QVariant param;
  bool     valid;

  param = pParams.value("itemsrc_id", &valid);
  if (valid)
  {
    _itemsrcid = param.toInt();
    _documents->setId(_itemsrcid);
    populate();
  }

  param = pParams.value("item_id", &valid);
  if (valid)
  {
    _item->setId(param.toInt());
    _item->setEnabled(false);
  }

  param = pParams.value("vend_id", &valid);
  if (valid)
  {
    _vendor->setId(param.toInt());
    _vendor->setEnabled(false);
  }
  
  param = pParams.value("contrct_id", &valid);
  if (valid)
  {
    _contract->setId(param.toInt());
  }
  
  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;
      _new = true;

      itemet.exec("SELECT NEXTVAL('itemsrc_itemsrc_id_seq') AS _itemsrc_id;");
      if (itemet.first())
      {
        _itemsrcid = itemet.value("_itemsrc_id").toInt();
        _documents->setId(_itemsrcid);
      }
      else if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Retrieving Item Source Information"),
                                    itemet, __FILE__, __LINE__))
      {
        return UndefinedError;
      }
      _captive = true;
      
      connect(_itemsrcp, SIGNAL(valid(bool)), _edit, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(valid(bool)), _delete, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;

      connect(_itemsrcp, SIGNAL(valid(bool)), _edit, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(valid(bool)), _delete, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));

      _item->setReadOnly(true);
      _vendor->setEnabled(false);
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _item->setReadOnly(true);
      _active->setEnabled(false);
      _default->setEnabled(false);
      _vendor->setEnabled(false);
      _dates->setEnabled(false);
      _vendorItemNumber->setEnabled(false);
      _vendorItemDescrip->setEnabled(false);
      _vendorUOM->setEnabled(false);
      _invVendorUOMRatio->setEnabled(false);
      _vendorRanking->setEnabled(false);
      _minOrderQty->setEnabled(false);
      _multOrderQty->setEnabled(false);
      _leadTime->setEnabled(false);
      _notes->setEnabled(false);
      _upcCode->setEnabled(false);
      _documents->setReadOnly(true);
      _add->setEnabled(false);
      _delete->setEnabled(false);
      _close->setText(tr("&Close"));
      _save->hide();
    }
    if (param.toString() == "copy")
    {
      _mode = cCopy;
      _new = true;
      _captive = true;
      int itemsrcidold = _itemsrcid;

      itemet.exec("SELECT NEXTVAL('itemsrc_itemsrc_id_seq') AS _itemsrc_id;");
      if (itemet.first())
        _itemsrcid = itemet.value("_itemsrc_id").toInt();
      else if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Retrieving Item Source Information"),
                                    itemet, __FILE__, __LINE__))
      {
        return UndefinedError;
      }
      
      connect(_itemsrcp, SIGNAL(valid(bool)), _edit, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(valid(bool)), _delete, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));
      
      _item->setReadOnly(true);
      _vendorItemNumber->setText(_vendorItemNumber->text().prepend("Copy Of "));
      _dates->setStartDate(omfgThis->dbDate());

      if (sSave())
      {
        itemet.prepare("INSERT INTO itemsrcp ( "
                       "itemsrcp_itemsrc_id, itemsrcp_qtybreak, itemsrcp_price, "
                       "itemsrcp_updated, itemsrcp_curr_id, itemsrcp_dropship, "
                       "itemsrcp_warehous_id, itemsrcp_type, itemsrcp_discntprcnt, "
                       "itemsrcp_fixedamtdiscount) "
                       "SELECT :itemsrcid, itemsrcp_qtybreak, itemsrcp_price, "
                       "current_date, itemsrcp_curr_id, itemsrcp_dropship, "
                       "itemsrcp_warehous_id, itemsrcp_type, itemsrcp_discntprcnt, "
                       "itemsrcp_fixedamtdiscount "
                       "FROM itemsrcp "
                       "WHERE (itemsrcp_itemsrc_id=:itemsrcidold); ");
        itemet.bindValue(":itemsrcid", _itemsrcid);
        itemet.bindValue(":itemsrcidold", itemsrcidold);
        itemet.exec();
        sFillPriceList();
      }
    }
  }

  if (_metrics->value("Application") != "Standard")
  {
    _contractedQtyLit->hide();
    _contractedQty->hide();
  }

  return NoError;
}
Ejemplo n.º 11
0
bool itemSource::sSave()
{
  XSqlQuery itemSave;

  QList<GuiErrorCheck> errors;
  errors << GuiErrorCheck(!_item->isValid(), _item,
                          tr( "You must select an Item that this Item Source represents\n"
                              "before you may save this Item Source." ) )
         << GuiErrorCheck(!_vendor->isValid(), _vendor,
                          tr( "You must select this Vendor that this Item Source is sold by\n"
                              "before you may save this Item Source." ) )
         << GuiErrorCheck(_dates->endDate() < _dates->startDate(), _dates,
                          tr("The expiration date cannot be earlier than the effective date."))
         << GuiErrorCheck(_vendorUOM->currentText().length() == 0, _vendorUOM,
                          tr( "You must indicate the Unit of Measure that this Item Source is sold in\n"
                               "before you may save this Item Source." ) )
         << GuiErrorCheck(_invVendorUOMRatio->toDouble() == 0.0, _invVendorUOMRatio,
                          tr( "You must indicate the Ratio of Inventory to Vendor Unit of Measures\n"
                               "before you may save this Item Source." ) )
     ;

  itemSave.prepare( "SELECT itemsrc_id "
                   "  FROM itemsrc "
                   " WHERE ((itemsrc_item_id=:itemsrc_item_id) "
                   "   AND (itemsrc_vend_id=:itemsrc_vend_id) "
                   "   AND ((itemsrc_contrct_id=:itemsrc_contrct_id) "
                   "    OR  (itemsrc_contrct_id IS NULL AND :itemsrc_contrct_id IS NULL)) "
                   "   AND (itemsrc_effective=:itemsrc_effective) "
                   "   AND (itemsrc_expires=:itemsrc_expires) "
                   "   AND (itemsrc_vend_item_number=:itemsrc_vend_item_number) "
                   "   AND (UPPER(itemsrc_manuf_name)=UPPER(:itemsrc_manuf_name)) "
                   "   AND (UPPER(itemsrc_manuf_item_number)=UPPER(:itemsrc_manuf_item_number)) "
                   "   AND (itemsrc_id != :itemsrc_id) );");
  itemSave.bindValue(":itemsrc_id", _itemsrcid);
  itemSave.bindValue(":itemsrc_item_id", _item->id());
  itemSave.bindValue(":itemsrc_vend_id", _vendor->id());
  if (_contract->isValid())
    itemSave.bindValue(":itemsrc_contrct_id", _contract->id());
  itemSave.bindValue(":itemsrc_effective", _dates->startDate());
  itemSave.bindValue(":itemsrc_expires", _dates->endDate());
  itemSave.bindValue(":itemsrc_vend_item_number", _vendorItemNumber->text());
  itemSave.bindValue(":itemsrc_manuf_name", _manufName->currentText());
  itemSave.bindValue(":itemsrc_manuf_item_number", _manufItemNumber->text());
  itemSave.exec();
  if(itemSave.first())
  {
    errors << GuiErrorCheck(true, _item,
                            tr("An Item Source already exists for the Item Number, Vendor,\n"
                               "Contract, Effective Date, Expires Date,\n"
                               "Vendor Item, Manfacturer Name and Manufacturer Item Number you have specified."));
  }
  else if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Saving Item Source Information"),
                                 itemSave, __FILE__, __LINE__))
  {
    return false;
  }
  
  if(_active->isChecked())
  {
    itemSave.prepare("SELECT item_id "
                     "FROM item "
                     "WHERE ((item_id=:item_id)"
                     "  AND  (item_active)) "
                     "LIMIT 1; ");
    itemSave.bindValue(":item_id", _item->id());
    itemSave.exec();
    if (!itemSave.first())         
    { 
      errors << GuiErrorCheck(true, _active,
                              tr("This Item Source refers to an inactive Item and must be marked as inactive.") );
    }
  }
    
  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Item Source"), errors))
    return false;

  if (_mode == cNew || _mode == cCopy)
  {
    itemSave.prepare( "INSERT INTO itemsrc "
               "( itemsrc_id, itemsrc_item_id, itemsrc_active, itemsrc_default, itemsrc_vend_id,"
               "  itemsrc_contrct_id, itemsrc_effective, itemsrc_expires, itemsrc_contrct_min,"
               "  itemsrc_vend_item_number, itemsrc_vend_item_descrip,"
               "  itemsrc_vend_uom, itemsrc_invvendoruomratio,"
               "  itemsrc_minordqty, itemsrc_multordqty, itemsrc_upccode,"
               "  itemsrc_leadtime, itemsrc_ranking,"
               "  itemsrc_comments, itemsrc_manuf_name, "
               "  itemsrc_manuf_item_number, itemsrc_manuf_item_descrip ) "
               "VALUES "
               "( :itemsrc_id, :itemsrc_item_id, :itemsrc_active, :itemsrc_default, :itemsrc_vend_id,"
               "  :itemsrc_contrct_id, :itemsrc_effective, :itemsrc_expires, :itemsrc_contrct_min,"
               "  :itemsrc_vend_item_number, :itemsrc_vend_item_descrip,"
               "  :itemsrc_vend_uom, :itemsrc_invvendoruomratio,"
               "  :itemsrc_minordqty, :itemsrc_multordqty, :itemsrc_upccode,"
               "  :itemsrc_leadtime, :itemsrc_ranking,"
               "  :itemsrc_comments, :itemsrc_manuf_name, "
               "  :itemsrc_manuf_item_number, :itemsrc_manuf_item_descrip );" );
  }
  if (_mode == cEdit)
  {
    itemSave.prepare( "UPDATE itemsrc "
               "SET itemsrc_active=:itemsrc_active,"
               "    itemsrc_default=:itemsrc_default,"
               "    itemsrc_vend_id=:itemsrc_vend_id,"
               "    itemsrc_contrct_id=:itemsrc_contrct_id,"
               "    itemsrc_effective=:itemsrc_effective,"
               "    itemsrc_expires=:itemsrc_expires,"
               "    itemsrc_contrct_min=:itemsrc_contrct_min,"
               "    itemsrc_vend_item_number=:itemsrc_vend_item_number,"
               "    itemsrc_vend_item_descrip=:itemsrc_vend_item_descrip,"
               "    itemsrc_vend_uom=:itemsrc_vend_uom,"
               "    itemsrc_invvendoruomratio=:itemsrc_invvendoruomratio,"
               "    itemsrc_upccode=:itemsrc_upccode,"
               "    itemsrc_minordqty=:itemsrc_minordqty, itemsrc_multordqty=:itemsrc_multordqty,"
               "    itemsrc_leadtime=:itemsrc_leadtime, itemsrc_ranking=:itemsrc_ranking,"
               "    itemsrc_comments=:itemsrc_comments, itemsrc_manuf_name=:itemsrc_manuf_name, "
               "    itemsrc_manuf_item_number=:itemsrc_manuf_item_number, "
               "    itemsrc_manuf_item_descrip=:itemsrc_manuf_item_descrip "
               "WHERE (itemsrc_id=:itemsrc_id);" );
  }

  itemSave.bindValue(":itemsrc_id", _itemsrcid);
  itemSave.bindValue(":itemsrc_item_id", _item->id());
  itemSave.bindValue(":itemsrc_active", QVariant(_active->isChecked()));
  itemSave.bindValue(":itemsrc_default", QVariant(_default->isChecked()));
  itemSave.bindValue(":itemsrc_vend_id", _vendor->id());
  if (_contract->isValid())
    itemSave.bindValue(":itemsrc_contrct_id", _contract->id());
  itemSave.bindValue(":itemsrc_effective", _dates->startDate());
  itemSave.bindValue(":itemsrc_expires", _dates->endDate());
  itemSave.bindValue(":itemsrc_contrct_min", _contractedQty->toDouble());
  itemSave.bindValue(":itemsrc_vend_item_number", _vendorItemNumber->text());
  itemSave.bindValue(":itemsrc_vend_item_descrip", _vendorItemDescrip->toPlainText());
  itemSave.bindValue(":itemsrc_vend_uom", _vendorUOM->currentText());
  itemSave.bindValue(":itemsrc_invvendoruomratio", _invVendorUOMRatio->toDouble());
  itemSave.bindValue(":itemsrc_upccode", _upcCode->text());
  itemSave.bindValue(":itemsrc_minordqty", _minOrderQty->toDouble());
  itemSave.bindValue(":itemsrc_multordqty", _multOrderQty->toDouble());
  itemSave.bindValue(":itemsrc_leadtime", _leadTime->text().toInt());
  itemSave.bindValue(":itemsrc_ranking", _vendorRanking->value());
  itemSave.bindValue(":itemsrc_comments", _notes->toPlainText().trimmed());
  itemSave.bindValue(":itemsrc_manuf_name", _manufName->currentText());
  itemSave.bindValue(":itemsrc_manuf_item_number", _manufItemNumber->text());
  itemSave.bindValue(":itemsrc_manuf_item_descrip", _manufItemDescrip->toPlainText());
  itemSave.exec();
  if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Saving Item Source Information"),
                                itemSave, __FILE__, __LINE__))
  {
    return false;
  }

  if (_captive)
  {
    if (_mode != cCopy)
    {
      _vendor->setEnabled(false);
    }
    _mode = cEdit;
    _item->setReadOnly(true);
    _captive = false;
  }
  else
    done(_itemsrcid);
    
  return true;
}
void applyAPCreditMemo::populate()
{
  XSqlQuery applypopulate;
  applypopulate.prepare( "SELECT apopen_vend_id, apopen_docnumber, apopen_docdate,"
             "       (apopen_amount - apopen_paid) AS available, apopen_curr_id, "
             "       COALESCE(SUM(currToCurr(apcreditapply_curr_id,"
	     "				apopen_curr_id, apcreditapply_amount, "
	     "				CURRENT_DATE)), 0) AS f_applied "
             "FROM apopen LEFT OUTER JOIN apcreditapply ON (apcreditapply_source_apopen_id=apopen_id) "
             "WHERE (apopen_id=:apopen_id) "
             "GROUP BY apopen_vend_id, apopen_docnumber, apopen_docdate,"
             "         apopen_curr_id, apopen_amount, apopen_paid;" );
  applypopulate.bindValue(":apopen_id", _apopenid);
  applypopulate.exec();
  if (applypopulate.first())
  {
    _vend->setId(applypopulate.value("apopen_vend_id").toInt());
    _docDate->setDate(applypopulate.value("apopen_docdate").toDate(), true);
    _available->setId(applypopulate.value("apopen_curr_id").toInt());
    _available->setLocalValue(applypopulate.value("available").toDouble());
    _applied->setLocalValue(applypopulate.value("f_applied").toDouble());
    _balance->setLocalValue(_available->localValue() - _applied->localValue());
    _docNumber->setText(applypopulate.value("apopen_docnumber").toString());
  
    _cachedAmount = applypopulate.value("available").toDouble();
  }
  else if (applypopulate.lastError().type() != QSqlError::NoError)
      systemError(this, applypopulate.lastError().databaseText(), __FILE__, __LINE__);

  applypopulate.prepare( "SELECT apopen_id,"
             "       CASE WHEN (apopen_doctype='V') THEN :voucher"
             "            WHEN (apopen_doctype='D') THEN :debitMemo"
             "       END AS doctype,"
             "       apopen_docnumber,"
             "       apopen_docdate, apopen_duedate,"
             "       (apopen_amount - apopen_paid - COALESCE(selected,0.0) -"
             "          COALESCE(prepared,0.0)) AS openamount,"
	           "       currConcat(apopen_curr_id) AS opencurrabbr, "
             "       apcreditapply_amount, "
	           "       currConcat(apcreditapply_curr_id) AS appliedcurrabbr,"
             "       'curr' AS openamount_xtnumericrole,"
             "       'curr' AS apcreditapply_amount_xtnumericrole"
             "  FROM apopen LEFT OUTER JOIN apcreditapply "
             "         ON ( (apcreditapply_source_apopen_id=:parentApopenid) AND (apcreditapply_target_apopen_id=apopen_id) ) "
             "       LEFT OUTER JOIN (SELECT apopen_id AS selected_apopen_id,"
             "                             SUM(currToCurr(apselect_curr_id, apopen_curr_id, apselect_amount + apselect_discount, apselect_date)) AS selected"
             "                        FROM apselect JOIN apopen ON (apselect_apopen_id=apopen_id)"
             "                       GROUP BY apopen_id) AS sub1"
             "         ON (apopen_id=selected_apopen_id)"
             "       LEFT OUTER JOIN (SELECT apopen_id AS prepared_apopen_id,"
             "                               SUM(checkitem_amount + checkitem_discount) AS prepared"
             "                          FROM checkhead JOIN checkitem ON (checkitem_checkhead_id=checkhead_id)"
             "                                     JOIN apopen ON (checkitem_apopen_id=apopen_id)"
             "                         WHERE ((NOT checkhead_posted)"
             "                           AND  (NOT checkhead_void))"
             "                         GROUP BY apopen_id) AS sub2"
             "         ON (prepared_apopen_id=apopen_id)"
             " WHERE ( (apopen_doctype IN ('V', 'D'))"
             "   AND   (apopen_open)"
             "   AND   ((apopen_amount - apopen_paid - COALESCE(selected,0.0) - COALESCE(prepared,0.0)) > 0.0)"
             "   AND   (apopen_vend_id=:vend_id) ) "
             " ORDER BY apopen_duedate, apopen_docnumber;" );
  applypopulate.bindValue(":parentApopenid", _apopenid);
  applypopulate.bindValue(":vend_id", _vend->id());
  applypopulate.bindValue(":voucher", tr("Voucher"));
  applypopulate.bindValue(":debitMemo", tr("Debit Memo"));
  applypopulate.exec();
  _apopen->populate(applypopulate);
  if (applypopulate.lastError().type() != QSqlError::NoError)
      systemError(this, applypopulate.lastError().databaseText(), __FILE__, __LINE__);
}
Ejemplo n.º 13
0
bool configureSO::sSave()
{
  XSqlQuery configureSave;
  emit saving();

  const char *dispositionTypes[] = { "C", "R", "P", "V", "M", "" };
  const char *timingTypes[] = { "I", "R", "" };
  const char *creditMethodTypes[] = { "N", "M", "K", "C", "" };

  if ( (_metrics->boolean("EnableSOReservationsByLocation")) &&
       (!_locationGroup->isChecked()) )
  {
    if (QMessageBox::warning(this, tr("Reserve by Location Disabled"),
                             tr("<p>All existing location reservations will be removed. Are you sure you want to continue?"),
                             QMessageBox::Yes, QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
    {
      return false;
    }
    else
    {
      configureSave.prepare("DELETE FROM itemlocrsrv "
                " WHERE (itemlocrsrv_source='SO');");
      configureSave.exec();
    }	
  }

  _metrics->set("ShowQuotesAfterSO", _quoteafterSO->isChecked());
  _metrics->set("AllowDiscounts", _allowDiscounts->isChecked());
  _metrics->set("AllowASAPShipSchedules", _allowASAP->isChecked());
  _metrics->set("CustomerChangeLog", _customerChangeLog->isChecked());
  _metrics->set("SalesOrderChangeLog", _salesOrderChangeLog->isChecked());
  _metrics->set("RestrictCreditMemos", _restrictCreditMemos->isChecked());
  _metrics->set("AutoSelectForBilling", _autoSelectForBilling->isChecked());
  _metrics->set("AlwaysShowSaveAndAdd", _saveAndAdd->isChecked());
  _metrics->set("FirmSalesOrderPackingList", _firmAndAdd->isChecked());
  _metrics->set("DisableSalesOrderPriceOverride", _priceOverride->isChecked());
  _metrics->set("AutoAllocateCreditMemos", _autoAllocateCM->isChecked());
  _metrics->set("HideSOMiscCharge", _hideSOMiscChrg->isChecked());
  _metrics->set("EnableSOShipping", _enableSOShipping->isChecked());
  _metrics->set("CONumberGeneration",   _orderNumGeneration->methodCode());
  _metrics->set("QUNumberGeneration",   _quoteNumGeneration->methodCode());
  _metrics->set("CMNumberGeneration",   _creditMemoNumGeneration->methodCode());
  _metrics->set("InvcNumberGeneration", _invoiceNumGeneration->methodCode());
  _metrics->set("DefaultShipFormId", _shipform->id());
  _metrics->set("DefaultShipViaId", _shipvia->id());
  _metrics->set("DefaultCustType", _custtype->id());
  _metrics->set("DefaultSalesRep", _salesrep->id());
  _metrics->set("DefaultTerms", _terms->id());
  _metrics->set("DefaultPartialShipments", _partial->isChecked());
  _metrics->set("DefaultBackOrders", _backorders->isChecked());
  _metrics->set("DefaultFreeFormShiptos", _freeFormShiptos->isChecked());
  _metrics->set("DefaultPrintSOOnSave", _printSO->isChecked());
  _metrics->set("UsePromiseDate", _enablePromiseDate->isChecked());
  _metrics->set("CalculateFreight", _calcFreight->isChecked());
  _metrics->set("IncludePackageWeight", _includePkgWeight->isChecked());
  _metrics->set("EnableReturnAuth", _enableReturns->isChecked());
  _metrics->set("EnableSOReservations", _enableReservations->isChecked());

  _metrics->set("EnableSOReservationsByLocation", _locationGroup->isChecked());
  //SOReservationLocationMethod are three Options Either 
  // Lowest quantity first,
  // Highest quantity first,
  // Alpha by Location Name
  if(_lowest->isChecked())
    _metrics->set("SOReservationLocationMethod", 1);
  else if (_highest->isChecked())
    _metrics->set("SOReservationLocationMethod", 2);
  else if(_alpha->isChecked())
    _metrics->set("SOReservationLocationMethod", 3);

  _metrics->set("SOCreditLimit", _creditLimit->text());
  _metrics->set("SOCreditRate", _creditRating->text());

  if (_priceOrdered->isChecked())
    _metrics->set("soPriceEffective", QString("OrderDate"));
  else if (_priceScheduled->isChecked())
    _metrics->set("soPriceEffective", QString("ScheduleDate"));
  else
    _metrics->set("soPriceEffective", QString("CurrentDate"));

  //UpdatePriceLineEdit are three Options Either 
  // Don't Update price
  // Ask to Update Price,
  // Update Price
  if(_dontUpdatePrice->isChecked())
    _metrics->set("UpdatePriceLineEdit", 1);
  else if (_askUpdatePrice->isChecked())
    _metrics->set("UpdatePriceLineEdit", 2);
  else if(_updatePrice->isChecked())
    _metrics->set("UpdatePriceLineEdit", 3);
  _metrics->set("IgnoreCustDisc", _askUpdatePrice->isChecked() && _ignoreCustDisc->isChecked());

  if(_invcScheddate->isChecked())
    _metrics->set("InvoiceDateSource", QString("scheddate"));
  else if(_invcShipdate->isChecked())
    _metrics->set("InvoiceDateSource", QString("shipdate"));
  else
    _metrics->set("InvoiceDateSource", QString("currdate"));

  if (! _invoiceCopies->save())
    return false;
  if (! _creditMemoCopies->save())
    return false;

  switch (_balanceMethod->currentIndex())
  {
  case 0:
    _metrics->set("DefaultBalanceMethod", QString("B"));
    break;

  case 1:
    _metrics->set("DefaultBalanceMethod", QString("O"));
    break;
  }

  configureSave.prepare( "SELECT setNextSoNumber(:sonumber), setNextQuNumber(:qunumber),"
             "       setNextCmNumber(:cmnumber), setNextInvcNumber(:innumber);" );
  configureSave.bindValue(":sonumber", _nextSoNumber->text().toInt());
  configureSave.bindValue(":qunumber", _nextQuNumber->text().toInt());
  configureSave.bindValue(":cmnumber", _nextCmNumber->text().toInt());
  configureSave.bindValue(":innumber", _nextInNumber->text().toInt());
  configureSave.exec();
  if (configureSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, configureSave.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  if (_enableReturns->isChecked() || !_enableReturns->isCheckable())
  {
    _metrics->set("DefaultRaDisposition", QString(dispositionTypes[_disposition->currentIndex()]));
    _metrics->set("DefaultRaTiming", QString(timingTypes[_timing->currentIndex()]));
    _metrics->set("DefaultRaCreditMethod", QString(creditMethodTypes[_creditBy->currentIndex()]));
    _metrics->set("ReturnAuthorizationChangeLog", _returnAuthChangeLog->isChecked());
    _metrics->set("DefaultPrintRAOnSave", _printRA->isChecked());
    _metrics->set("RANumberGeneration", _returnAuthorizationNumGeneration->methodCode());

    configureSave.prepare( "SELECT setNextRaNumber(:ranumber);" );
    configureSave.bindValue(":ranumber", _nextRaNumber->text().toInt());
    configureSave.exec();
    if (configureSave.lastError().type() != QSqlError::NoError)
    {
      systemError(this, configureSave.lastError().databaseText(), __FILE__, __LINE__);
      return false;
    }
  }
  _metrics->set("EnableReturnAuth", (_enableReturns->isChecked() || !_enableReturns->isCheckable()));

  return true;
}
Ejemplo n.º 14
0
configureSO::configureSO(QWidget* parent, const char* name, bool /*modal*/, Qt::WFlags fl)
    : XAbstractConfigure(parent, fl)
{
  XSqlQuery configureconfigureSO;
  setupUi(this);

  if (name)
    setObjectName(name);

  connect(_creditLimit,          SIGNAL(editingFinished()), this, SLOT(sEditCreditLimit()));
  connect(_askUpdatePrice, SIGNAL(toggled(bool)), _ignoreCustDisc, SLOT(setEnabled(bool)));

  _nextSoNumber->setValidator(omfgThis->orderVal());
  _nextQuNumber->setValidator(omfgThis->orderVal());
  _nextRaNumber->setValidator(omfgThis->orderVal());
  _nextCmNumber->setValidator(omfgThis->orderVal());
  _nextInNumber->setValidator(omfgThis->orderVal());
  _creditLimit->setValidator(omfgThis->moneyVal());

  _orderNumGeneration->setMethod(_metrics->value("CONumberGeneration"));
  _quoteNumGeneration->setMethod(_metrics->value("QUNumberGeneration"));
  _creditMemoNumGeneration->setMethod(_metrics->value("CMNumberGeneration"));
  _invoiceNumGeneration->setMethod(_metrics->value("InvcNumberGeneration"));

  QString metric;
  metric = _metrics->value("InvoiceDateSource");
  if (metric == "scheddate")
    _invcScheddate->setChecked(true);
  else if (metric == "shipdate")
    _invcShipdate->setChecked(true);
  else
    _invcCurrdate->setChecked(true);

  configureconfigureSO.exec( "SELECT sonumber.orderseq_number AS sonumber,"
          "       qunumber.orderseq_number AS qunumber,"
          "       cmnumber.orderseq_number AS cmnumber,"
          "       innumber.orderseq_number AS innumber "
          "FROM orderseq AS sonumber,"
          "     orderseq AS qunumber,"
          "     orderseq AS cmnumber,"
          "     orderseq AS innumber "
          "WHERE ( (sonumber.orderseq_name='SoNumber')"
          " AND (qunumber.orderseq_name='QuNumber')"
          " AND (cmnumber.orderseq_name='CmNumber')"
          " AND (innumber.orderseq_name='InvcNumber') );" );
  if (configureconfigureSO.first())
  {
    _nextSoNumber->setText(configureconfigureSO.value("sonumber"));
    _nextQuNumber->setText(configureconfigureSO.value("qunumber"));
    _nextCmNumber->setText(configureconfigureSO.value("cmnumber"));
    _nextInNumber->setText(configureconfigureSO.value("innumber"));
  }
  else if (configureconfigureSO.lastError().type() != QSqlError::NoError)
  {
    systemError(this, configureconfigureSO.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  _allowDiscounts->setChecked(_metrics->boolean("AllowDiscounts"));
  _allowASAP->setChecked(_metrics->boolean("AllowASAPShipSchedules"));
  _customerChangeLog->setChecked(_metrics->boolean("CustomerChangeLog"));
  _salesOrderChangeLog->setChecked(_metrics->boolean("SalesOrderChangeLog"));
  _restrictCreditMemos->setChecked(_metrics->boolean("RestrictCreditMemos"));
  _autoSelectForBilling->setChecked(_metrics->boolean("AutoSelectForBilling"));
  _saveAndAdd->setChecked(_metrics->boolean("AlwaysShowSaveAndAdd"));
  _firmAndAdd->setChecked(_metrics->boolean("FirmSalesOrderPackingList"));
  _priceOverride->setChecked(_metrics->boolean("DisableSalesOrderPriceOverride"));
  _autoAllocateCM->setChecked(_metrics->boolean("AutoAllocateCreditMemos"));
  _hideSOMiscChrg->setChecked(_metrics->boolean("HideSOMiscCharge"));
  _enableSOShipping->setChecked(_metrics->boolean("EnableSOShipping"));
  _printSO->setChecked(_metrics->boolean("DefaultPrintSOOnSave"));
  _enablePromiseDate->setChecked(_metrics->boolean("UsePromiseDate"));
  _calcFreight->setChecked(_metrics->boolean("CalculateFreight"));
  _includePkgWeight->setChecked(_metrics->boolean("IncludePackageWeight"));
  _quoteafterSO->setChecked(_metrics->boolean("ShowQuotesAfterSO"));

  _shipform->setId(_metrics->value("DefaultShipFormId").toInt());
  _shipvia->setId(_metrics->value("DefaultShipViaId").toInt());

  if (_metrics->value("DefaultBalanceMethod") == "B")
    _balanceMethod->setCurrentIndex(0);
  else if (_metrics->value("DefaultBalanceMethod") == "O")
    _balanceMethod->setCurrentIndex(1);

  _custtype->setId(_metrics->value("DefaultCustType").toInt());
  _salesrep->setId(_metrics->value("DefaultSalesRep").toInt());
  _terms->setId(_metrics->value("DefaultTerms").toInt());

  _partial->setChecked(_metrics->boolean("DefaultPartialShipments"));
  _backorders->setChecked(_metrics->boolean("DefaultBackOrders"));
  _freeFormShiptos->setChecked(_metrics->boolean("DefaultFreeFormShiptos"));

  _creditLimit->setText(_metrics->value("SOCreditLimit"));
  _creditRating->setText(_metrics->value("SOCreditRate"));

  if (_metrics->value("soPriceEffective") == "OrderDate")
    _priceOrdered->setChecked(true);
  else if (_metrics->value("soPriceEffective") == "ScheduleDate")
    _priceScheduled->setChecked(true);

  if(_metrics->value("UpdatePriceLineEdit").toInt() == 1)
    _dontUpdatePrice->setChecked(true);
  else if (_metrics->value("UpdatePriceLineEdit").toInt() == 2)
    _askUpdatePrice->setChecked(true);
  else if(_metrics->value("UpdatePriceLineEdit").toInt() == 3)
    _updatePrice->setChecked(true);
  _ignoreCustDisc->setChecked(_askUpdatePrice->isChecked() && _metrics->boolean("IgnoreCustDisc"));

  this->setWindowTitle("Sales Configuration");

  //Set status of Returns Authorization based on context
  if(_metrics->value("Application") == "PostBooks")
  {
    _authNumGenerationLit->setVisible(false);
    _returnAuthorizationNumGeneration->setVisible(false);
    _nextRaNumberLit->setVisible(false);
    _nextRaNumber->setVisible(false);
    _tab->removeTab(_tab->indexOf(_returns));
    _enableReturns->setChecked(false);
    _enableReservations->hide();
    _enableReservations->setChecked(false);
    _locationGroup->hide();
    _locationGroup->setChecked(false);
    _lowest->setChecked(false);
    _highest->setChecked(false);
    _alpha->setChecked(false);
  }
  else
  {
    configureconfigureSO.exec("SELECT rahead_id FROM rahead LIMIT 1;");
    if (configureconfigureSO.first())
      _enableReturns->setCheckable(false);
    else
      _enableReturns->setChecked(_metrics->boolean("EnableReturnAuth"));

    configureconfigureSO.exec( "SELECT ranumber.orderseq_number AS ranumber "
            "FROM orderseq AS ranumber "
            "WHERE (ranumber.orderseq_name='RaNumber');" );
    if (configureconfigureSO.first())
    {
      _nextRaNumber->setText(configureconfigureSO.value("ranumber"));
    }
    else
      _nextRaNumber->setText("10000");

    metric = _metrics->value("RANumberGeneration");
    if (metric == "M")
      _returnAuthorizationNumGeneration->setCurrentIndex(0);
    else if (metric == "A")
      _returnAuthorizationNumGeneration->setCurrentIndex(1);
    else if (metric == "O")
      _returnAuthorizationNumGeneration->setCurrentIndex(2);

    metric = _metrics->value("DefaultRaDisposition");
    if (metric == "C")
      _disposition->setCurrentIndex(0);
    else if (metric == "R")
      _disposition->setCurrentIndex(1);
    else if (metric == "P")
      _disposition->setCurrentIndex(2);
    else if (metric == "V")
      _disposition->setCurrentIndex(3);
    else if (metric == "M")
      _disposition->setCurrentIndex(4);
    else
      _disposition->setCurrentIndex(5);

    metric = _metrics->value("DefaultRaTiming");
    if (metric == "I")
      _timing->setCurrentIndex(0);
    else if (metric == "R")
      _timing->setCurrentIndex(1);
    else
      _timing->setCurrentIndex(2);

    metric = _metrics->value("DefaultRaCreditMethod");
    if (metric == "N")
      _creditBy->setCurrentIndex(0);
    else if (metric == "M")
      _creditBy->setCurrentIndex(1);
    else if (metric == "K")
      _creditBy->setCurrentIndex(2);
    else if (metric == "C")
      _creditBy->setCurrentIndex(3);
    else
      _creditBy->setCurrentIndex(4);

    _returnAuthChangeLog->setChecked(_metrics->boolean("ReturnAuthorizationChangeLog"));
    _printRA->setChecked(_metrics->boolean("DefaultPrintRAOnSave"));

    _enableReservations->setChecked(_metrics->boolean("EnableSOReservations"));

    _locationGroup->setChecked(_metrics->boolean("EnableSOReservationsByLocation"));
    if(_metrics->value("SOReservationLocationMethod").toInt() == 1)
      _lowest->setChecked(true);
    else if (_metrics->value("SOReservationLocationMethod").toInt() == 2)
      _highest->setChecked(true);
    else if(_metrics->value("SOReservationLocationMethod").toInt() == 3)
      _alpha->setChecked(true);
  }
  adjustSize();
}
Ejemplo n.º 15
0
void plannedOrder::sHandleItemsite(int pWarehousid)
{
  if (_metrics->boolean("UseSiteCalendar"))
  {
    _dueDate->setCalendarSiteId(pWarehousid);
    _startDate->setCalendarSiteId(pWarehousid);
  }

  XSqlQuery plannedHandleItemsite;
  plannedHandleItemsite.prepare( "SELECT itemsite_leadtime, itemsite_wosupply, itemsite_posupply, item_type "
             "FROM itemsite JOIN item ON (item_id=itemsite_item_id) "
             "WHERE ( (itemsite_item_id=:item_id)"
             " AND (itemsite_warehous_id=:warehous_id) );" );
  plannedHandleItemsite.bindValue(":item_id", _item->id());
  plannedHandleItemsite.bindValue(":warehous_id", pWarehousid);
  plannedHandleItemsite.exec();
  if (!plannedHandleItemsite.first())
  {
    systemError(this, plannedHandleItemsite.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  _leadTime->setValue(plannedHandleItemsite.value("itemsite_leadtime").toInt());
  
  if ( plannedHandleItemsite.value("itemsite_posupply").toBool() &&
      (plannedHandleItemsite.value("item_type").toString() == "P" ||
       plannedHandleItemsite.value("item_type").toString() == "O" ||
       plannedHandleItemsite.value("item_type").toString() == "T" ||
       plannedHandleItemsite.value("item_type").toString() == "M") )
    _poButton->setEnabled(TRUE);
  else
    _poButton->setEnabled(FALSE);
  if ( plannedHandleItemsite.value("itemsite_wosupply").toBool() &&
      (plannedHandleItemsite.value("item_type").toString() == "P" ||
       plannedHandleItemsite.value("item_type").toString() == "T" ||
       plannedHandleItemsite.value("item_type").toString() == "M") )
    _woButton->setEnabled(TRUE);
  else
    _woButton->setEnabled(FALSE);
  if ( plannedHandleItemsite.value("itemsite_wosupply").toBool() && plannedHandleItemsite.value("itemsite_posupply").toBool() && plannedHandleItemsite.value("item_type").toString() == "P" )
  {
    _poButton->setChecked(TRUE);
    _woButton->setChecked(FALSE);
  }
  else if ( plannedHandleItemsite.value("itemsite_wosupply").toBool() )
  {
    _poButton->setChecked(FALSE);
    _woButton->setChecked(TRUE);
  }
  else
  {
    _poButton->setChecked(TRUE);
    _woButton->setChecked(FALSE);
  }

  plannedHandleItemsite.prepare( "SELECT COALESCE(COUNT(*), 0) AS supplysites "
             "FROM itemsite "
             "WHERE ( (itemsite_item_id=:item_id)"
             " AND (itemsite_warehous_id <> :warehous_id) );" );
  plannedHandleItemsite.bindValue(":item_id", _item->id());
  plannedHandleItemsite.bindValue(":warehous_id", pWarehousid);
  plannedHandleItemsite.exec();
  if (!plannedHandleItemsite.first())
  {
    systemError(this, plannedHandleItemsite.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (plannedHandleItemsite.value("supplysites").toInt() > 0)
    _toButton->setEnabled(TRUE);
  else
    _toButton->setEnabled(FALSE);

  plannedHandleItemsite.prepare( "SELECT COALESCE(supply.itemsite_id, -1) AS supplyitemsiteid,"
             "       COALESCE(supply.itemsite_warehous_id, -1) AS supplywarehousid "
             "FROM itemsite LEFT OUTER JOIN itemsite supply ON (supply.itemsite_id=itemsite.itemsite_supply_itemsite_id)"
             "WHERE ( (itemsite.itemsite_item_id=:item_id)"
             "  AND   (itemsite.itemsite_warehous_id=:warehous_id) );" );
  plannedHandleItemsite.bindValue(":item_id", _item->id());
  plannedHandleItemsite.bindValue(":warehous_id", pWarehousid);
  plannedHandleItemsite.exec();
  if (!plannedHandleItemsite.first())
  {
    systemError(this, plannedHandleItemsite.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (plannedHandleItemsite.value("supplyitemsiteid").toInt() != -1)
  {
    _toButton->setChecked(TRUE);
    _fromWarehouse->setId(plannedHandleItemsite.value("supplywarehousid").toInt());
  }
  else
    _fromWarehouse->setId(pWarehousid);
}
Ejemplo n.º 16
0
void salesOrderList::sFillList()
{
  QString sql;


  if (_type == cSoAtShipping)
  {
    sql = "SELECT DISTINCT cohead_id, cohead_number, cust_name, cohead_custponumber,"
          "                cohead_orderdate,"
          "                MIN(coitem_scheddate) AS duedate "
          "FROM cosmisc, coship, cohead, coitem, itemsite, cust "
          "WHERE ((cohead_cust_id=cust_id)"
          " AND (coitem_cohead_id=cohead_id)"
          " AND (coitem_itemsite_id=itemsite_id)"
          " AND (coship_coitem_id=coitem_id)"
          " AND (coship_cosmisc_id=cosmisc_id)"
          " AND (NOT cosmisc_shipped)";

    if (_warehouse->isSelected())
      sql += " AND (itemsite_warehous_id=:warehous_id)";

  sql += ") "
         "GROUP BY cohead_id, cohead_number, cust_name,"
         "         cohead_custponumber, cohead_orderdate "
         "ORDER BY cohead_number;";
  }
  else
  {
    bool statusCheck = FALSE;

    sql = "SELECT DISTINCT cohead_id, cohead_number, cust_name, cohead_custponumber,"
          "                cohead_orderdate,"
          "                MIN(coitem_scheddate) AS duedate "
          "FROM cohead, coitem, itemsite, cust "
          "WHERE ((cohead_cust_id=cust_id)"
          " AND (coitem_status <> 'X')"
          " AND (coitem_cohead_id=cohead_id)"
          " AND (coitem_itemsite_id=itemsite_id)";

    if (_warehouse->isSelected())
      sql += " AND (itemsite_warehous_id=:warehous_id)";

    sql += "AND (";

    if (_type & cSoOpen)
    {
      sql += "(coitem_status='O')";
      statusCheck = TRUE;
    }

    if (_type & cSoClosed)
    {
      if (statusCheck)
        sql += " OR ";
      sql += "(coitem_status='C')";
      statusCheck = TRUE;
    }

    if (_type & cSoReleased)
    {
      if (statusCheck)
        sql += " AND ";
      sql += "(cohead_holdtype='N')";
      statusCheck = TRUE;
    }
    
    if (_type & cSoCustomer)
    {
      if (statusCheck)
        sql += " AND ";
      sql += "(cohead_cust_id=:cust_id)";
    }

    sql += ")) "
           "GROUP BY cohead_id, cohead_number, cust_name,"
           "         cohead_custponumber, cohead_orderdate "
           "ORDER BY cohead_number;";
  }

  XSqlQuery q;
  q.prepare(sql);
  _warehouse->bindValue(q);
  q.bindValue(":cust_id", _custid);
  q.exec();
  _so->populate(q, _soheadid);
}
Ejemplo n.º 17
0
void returnAuthCheck::sSave()
{
  XSqlQuery returnSave;
  if (!_date->isValid())
  {
    QMessageBox::warning( this, tr("Cannot Create Miscellaneous Check"),
                          tr("<p>You must enter a date for this check.") );
    _date->setFocus();
    return;
  }

  else if (_amount->isZero())
  {
    QMessageBox::warning( this, tr("Cannot Create Miscellaneous Check"),
                          tr("<p>You must enter an amount for this check.") );
    return;
  }

  else if (!_bankaccnt->isValid())
  {
    QMessageBox::warning( this, tr("Cannot Create Miscellaneous Check"),
                          tr("<p>You must select a bank account for this check.") );
    _date->setFocus();
    return;
  }

  else
  {
    returnSave.prepare("SELECT createCheck(:bankaccnt_id, 'C', :recipid,"
	      "                   :checkDate, :amount, :curr_id, NULL,"
	      "                   NULL, :for, :notes, true, :aropen_id) AS result; ");
    returnSave.bindValue(":bankaccnt_id", _bankaccnt->id());
    returnSave.bindValue(":recipid",	_custid);
    returnSave.bindValue(":checkDate", _date->date());
    returnSave.bindValue(":amount",	_amount->localValue());
    returnSave.bindValue(":curr_id",	_amount->id());
    returnSave.bindValue(":for",	_for->text().trimmed());
    returnSave.bindValue(":notes", _notes->toPlainText().trimmed());
	returnSave.bindValue(":aropen_id", _aropenid);
	returnSave.exec();
    if (returnSave.first())
    {
      _checkid = returnSave.value("result").toInt();
      if (_checkid < 0)
      {
        ErrorReporter::error(QtCriticalMsg, this, tr("Error Retrieving Check Information"),
                               storedProcErrorLookup("createCheck", _checkid),
                               __FILE__, __LINE__);
        return;
      }
      returnSave.prepare( "SELECT checkhead_number "
               "FROM checkhead "
               "WHERE (checkhead_id=:check_id);" );
      returnSave.bindValue(":check_id", _checkid);
      returnSave.exec();
      if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Retrieving Check Information"),
                                    returnSave, __FILE__, __LINE__))
      {
        return;
      }
	  done(true);
	}
    else if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Retrieving Check Information"),
                                  returnSave, __FILE__, __LINE__))
    {
      return;
    }
  }
}
void allocateARCreditMemo::sPopulate()
{
  XSqlQuery populateCM;
  if (_coheadid == -1)
  {
    // get the cohead_id associated with the invoice
    populateCM.prepare("SELECT cohead_id "
              "  FROM invchead JOIN cohead ON (cohead_number=invchead_ordernumber)"
              " WHERE (invchead_id=:invchead_id);");
    populateCM.bindValue(":invchead_id", _invcheadid);
    populateCM.exec();
    if (populateCM.first())
      _coheadid = populateCM.value("cohead_id").toInt();
    if (populateCM.lastError().type() != QSqlError::NoError)
    {
      systemError(this, populateCM.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
  // Get the list of Unallocated CM's with amount
  populateCM.prepare("SELECT aropen_id, "
            "       docnumber, doctype, docdate, duedate,"
            "       amount, paid, balance, allocated, totalallocated, "
            "       CASE WHEN (doctype='C') THEN :creditmemo"
            "            WHEN (doctype='R') THEN :cashdeposit"
            "            WHEN (doctype='S') THEN :salesorder"
            "            WHEN (doctype='I') THEN :invoice"
            "       END AS doctype_qtdisplayrole, "
            "       indent AS xtindentrole "
            "  FROM ( "
            "SELECT aropen_id, 0 AS indent, "
            "       aropen_docnumber AS docnumber, aropen_doctype AS doctype, "
            "       aropen_docdate AS docdate, aropen_duedate AS duedate,"
            "       currToCurr(aropen_curr_id, :curr_id, aropen_amount, :effective) AS amount,"
            "       currToCurr(aropen_curr_id, :curr_id, aropen_paid, :effective) AS paid,"
            "       currToCurr(aropen_curr_id, :curr_id, noNeg(aropen_amount - aropen_paid), :effective) AS balance,"
            "       COALESCE(SUM(CASE WHEN ((aropenalloc_doctype='S' AND aropenalloc_doc_id=:cohead_id) OR "
            "                               (aropenalloc_doctype='I' AND aropenalloc_doc_id=:invchead_id)) THEN "
            "                         currToCurr(aropenalloc_curr_id, :curr_id, aropenalloc_amount, :effective)"
            "                         ELSE 0.00 END), 0.0) AS allocated,"
            "       COALESCE(SUM(currToCurr(aropenalloc_curr_id, :curr_id, aropenalloc_amount, :effective)), 0.0) AS totalallocated "
            "  FROM aropen LEFT OUTER JOIN aropenalloc ON (aropenalloc_aropen_id=aropen_id)"
            " WHERE ( (aropen_cust_id=:cust_id)"
            "   AND   (aropen_doctype IN ('C', 'R'))"
            "   AND   (aropen_open) )"
            " GROUP BY aropen_id, aropen_docnumber, aropen_doctype, aropen_docdate, aropen_duedate,"
            "          aropen_curr_id, aropen_amount, aropen_paid "
            "UNION "
            "SELECT aropen_id, 1 AS indent, "
            "       cohead_number AS docnumber, 'S' AS doctype, "
            "       cohead_orderdate AS docdate, NULL AS duedate,"
            "       NULL AS amount,"
            "       NULL AS paid,"
            "       NULL AS balance,"
            "       NULL AS allocated,"
            "       COALESCE(currToCurr(aropenalloc_curr_id, :curr_id, aropenalloc_amount, :effective), 0.0) AS totalallocated "
            "  FROM aropen JOIN aropenalloc ON (aropenalloc_aropen_id=aropen_id AND aropenalloc_doctype='S')"
            "              JOIN cohead ON (cohead_id=aropenalloc_doc_id) "
            " WHERE ( (aropen_cust_id=:cust_id)"
            "   AND   (aropen_doctype IN ('C', 'R'))"
            "   AND   (aropen_open) ) "
            "UNION "
            "SELECT aropen_id, 1 AS indent, "
            "       invchead_invcnumber AS docnumber, 'I' AS doctype, "
            "       invchead_invcdate AS docdate, NULL AS duedate,"
            "       NULL AS amount,"
            "       NULL AS paid,"
            "       NULL AS balance,"
            "       NULL AS allocated,"
            "       COALESCE(currToCurr(aropenalloc_curr_id, :curr_id, aropenalloc_amount, :effective), 0.0) AS totalallocated "
            "  FROM aropen JOIN aropenalloc ON (aropenalloc_aropen_id=aropen_id AND aropenalloc_doctype='I')"
            "              JOIN invchead ON (invchead_id=aropenalloc_doc_id) "
            " WHERE ( (aropen_cust_id=:cust_id)"
            "   AND   (aropen_doctype IN ('C', 'R'))"
            "   AND   (aropen_open) )"
            " ) AS data "
            " ORDER BY aropen_id, indent, duedate;");
  populateCM.bindValue(":cohead_id", _coheadid);
  populateCM.bindValue(":invchead_id", _invcheadid);
  populateCM.bindValue(":cust_id", _custid);
  populateCM.bindValue(":curr_id",   _total->id());
  populateCM.bindValue(":effective", _total->effective());
  populateCM.bindValue(":creditmemo", tr("Credit Memo"));
  populateCM.bindValue(":cashdeposit", tr("Customer Deposit"));
  populateCM.bindValue(":salesorder", tr("Sales Order"));
  populateCM.bindValue(":invoice", tr("Invoice"));
  populateCM.exec();
  if (populateCM.lastError().type() != QSqlError::NoError)
  {
      systemError(this, populateCM.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  _aropen->populate(populateCM, false);
}
void dspGLTransactions::sViewDocument()
{
  XSqlQuery dspViewDocument;
  XTreeWidgetItem * item = (XTreeWidgetItem*)list()->currentItem();
  if(0 == item)
    return;

  ParameterList params;
  if(item->rawValue("gltrans_doctype").toString() == "VO")
  {
    dspViewDocument.prepare("SELECT vohead_id, vohead_misc"
              "  FROM vohead"
              " WHERE (vohead_number=:vohead_number)");
    dspViewDocument.bindValue(":vohead_number", item->rawValue("docnumber").toString());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("vohead_id", dspViewDocument.value("vohead_id").toInt());
    params.append("mode", "view");
    
    if(dspViewDocument.value("vohead_misc").toBool())
    {
      miscVoucher *newdlg = new miscVoucher();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
    }
    else
    {
      voucher *newdlg = new voucher();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
    }

  }
  else if(item->rawValue("gltrans_doctype").toString() == "IN")
  {
    dspViewDocument.prepare("SELECT invchead_id"
              "  FROM invchead"
              " WHERE (invchead_invcnumber=:invchead_invcnumber)");
    dspViewDocument.bindValue(":invchead_invcnumber", item->rawValue("docnumber").toString());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    invoice::viewInvoice(dspViewDocument.value("invchead_id").toInt());
  }
  else if(item->rawValue("gltrans_doctype").toString() == "PO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    dspViewDocument.prepare("SELECT pohead_id"
              "  FROM pohead"
              " WHERE (pohead_number=:docnumber)");
    dspViewDocument.bindValue(":docnumber", docnumber[0]);
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("pohead_id", dspViewDocument.value("pohead_id").toInt());
    params.append("mode", "view");

    purchaseOrder *newdlg = new purchaseOrder();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
  }
  else if(item->rawValue("gltrans_doctype").toString() == "SH")
  {
    dspViewDocument.prepare("SELECT shiphead_id"
              "  FROM shiphead"
              " WHERE (shiphead_number=:shiphead_number)");
    dspViewDocument.bindValue(":shiphead_number", item->rawValue("docnumber").toString());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("shiphead_id", dspViewDocument.value("shiphead_id").toInt());

    dspShipmentsByShipment *newdlg = new dspShipmentsByShipment();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
  }
  else if( (item->rawValue("gltrans_doctype").toString() == "CM") || (item->rawValue("gltrans_doctype").toString() == "DM") )
  {
    if(item->rawValue("gltrans_source").toString() == "A/P")
    {
      dspViewDocument.prepare("SELECT apopen_id"
                "  FROM apopen"
                " WHERE ( (apopen_docnumber=:docnumber) "
                "  AND (apopen_journalnumber=:journalnumber)"
                "  AND (apopen_doctype IN ('C', 'D')) );");
      dspViewDocument.bindValue(":docnumber", item->rawValue("docnumber").toString());
      dspViewDocument.bindValue(":journalnumber", item->rawValue("gltrans_journalnumber").toString());
      dspViewDocument.exec();
      if(!dspViewDocument.first())
        return;

      params.append("mode", "view");
      params.append("apopen_id", dspViewDocument.value("apopen_id").toInt());
      apOpenItem newdlg(this, "", TRUE);
      newdlg.set(params);
      newdlg.exec();
    }
    else if(item->rawValue("gltrans_source").toString() == "A/R")
    {
      dspViewDocument.prepare("SELECT aropen_id"
                "  FROM aropen"
                " WHERE ((aropen_docnumber=:docnumber) "
                "  AND (aropen_doctype IN ('C', 'D')) );");
      dspViewDocument.bindValue(":docnumber", item->rawValue("docnumber").toString());
      dspViewDocument.exec();
      if(!dspViewDocument.first())
        return;

      params.append("mode", "view");
      params.append("aropen_id", dspViewDocument.value("aropen_id").toInt());
      arOpenItem newdlg(this, "", TRUE);
      newdlg.set(params);
      newdlg.exec();
    }
    else if(item->rawValue("gltrans_source").toString() == "S/O")
    {
      dspViewDocument.prepare("SELECT cmhead_id"
                "  FROM cmhead"
                " WHERE (cmhead_number=:docnumber);");
      dspViewDocument.bindValue(":docnumber", item->rawValue("docnumber").toString());
      dspViewDocument.exec();
      if(!dspViewDocument.first())
        return;

      params.append("mode", "view");
      params.append("cmhead_id", dspViewDocument.value("cmhead_id").toInt());
      creditMemo *newdlg = new creditMemo();
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
    }
  }
  else if(item->rawValue("gltrans_doctype").toString() == "SO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    dspViewDocument.prepare("SELECT cohead_id"
              "  FROM cohead"
              " WHERE (cohead_number=:docnumber)");
    dspViewDocument.bindValue(":docnumber", docnumber[0]);
    dspViewDocument.exec();
    if(dspViewDocument.first())
      salesOrder::viewSalesOrder(dspViewDocument.value("cohead_id").toInt());
  }
  else if(item->rawValue("gltrans_doctype").toString() == "WO")
  {
    QStringList docnumber = item->rawValue("docnumber").toString().split("-");
    params.append("wo_number", docnumber[0]);

    dspWoHistoryByNumber *newdlg = new dspWoHistoryByNumber();
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
  }
  else if(item->rawValue("gltrans_source").toString() == "I/M")
  {
    dspViewDocument.prepare("SELECT gltrans_misc_id"
              "  FROM gltrans"
              " WHERE (gltrans_id=:gltrans_id)");
    dspViewDocument.bindValue(":gltrans_id", item->id());
    dspViewDocument.exec();
    if(!dspViewDocument.first())
      return;

    params.append("mode", "view");
    params.append("invhist_id", dspViewDocument.value("gltrans_misc_id").toInt());

    transactionInformation newdlg(this, "", TRUE);
    newdlg.set(params);
    newdlg.exec();
  }
}
Ejemplo n.º 20
0
void printCreditMemos::sPrint()
{
  XSqlQuery cmhead( "SELECT cmhead_id, cmhead_number,"
                    "       findCustomerForm(cmhead_cust_id, 'C') AS _reportname "
                    "FROM cmhead "
                    "WHERE ( (NOT cmhead_hold)"
                    "  AND   (checkCreditMemoSitePrivs(cmhead_id))"
                    "  AND   (NOT cmhead_printed) );");
  if (cmhead.first())
  {
    QPrinter printer(QPrinter::HighResolution);
    bool     setupPrinter  = TRUE;
    int      itemlocSeries = 0;
    bool userCanceled = false;
    if (orReport::beginMultiPrint(&printer, userCanceled) == false)
    {
      if(!userCanceled)
        systemError(this, tr("Could not initialize printing system for multiple reports."));
      return;
    }

    do
    {
      for (int i = 0; i < _creditMemoWatermarks->topLevelItemCount(); i++ )
      {
        ParameterList params;

        params.append("cmhead_id", cmhead.value("cmhead_id").toInt());
        params.append("showcosts", ((_creditMemoWatermarks->topLevelItem(i)->text(2) == tr("Yes")) ? "TRUE" : "FALSE"));
        params.append("watermark", _creditMemoWatermarks->topLevelItem(i)->text(1));

        orReport report(cmhead.value("_reportname").toString(), params);
        if (!report.isValid())
          QMessageBox::critical( this, tr("Cannot Find Credit Memo Form"),
                                 tr( "The Credit Memo Form '%1' for Credit Memo #%2 cannot be found.\n"
                                     "This Credit Memo cannot be printed until Customer Form Assignments are updated to remove\n"
                                     "any references to this Credit Memo Form or this Credit Memo Form is created." )
                                 .arg(cmhead.value("_reportname").toString())
                                 .arg(cmhead.value("cmhead_number").toString()) );
        else
        {
          if (report.print(&printer, setupPrinter))
            setupPrinter = FALSE;
          else
          {
            systemError( this, tr("A Printing Error occurred at printCreditMemos::%1.")
                               .arg(__LINE__) );
	    orReport::endMultiPrint(&printer);
            return;
          }
        }

        if (_post->isChecked())
        {
          XSqlQuery postCreditMemo;
          postCreditMemo.prepare("SELECT postCreditMemo(:cmhead_id, :itemlocSeries) AS result;");
          postCreditMemo.bindValue(":cmhead_id", cmhead.value("cmhead_id").toInt());
          postCreditMemo.bindValue(":itemlocSeries", itemlocSeries);
          postCreditMemo.exec();
          if (postCreditMemo.first())
            itemlocSeries = postCreditMemo.value("result").toInt();
          else
            systemError(this, tr("A System Error occurred at %1::%2.")
                              .arg(__FILE__)
                              .arg(__LINE__) );
        }
      }
    }
    while (cmhead.next());
    orReport::endMultiPrint(&printer);

    if ( QMessageBox::information( this, tr("Mark Credit Memos as Printed?"),
                                   tr("Did all of the Credit Memos print correctly?"),
                                   tr("&Yes"), tr("&No"), QString::null, 0, 1) == 0)
      XSqlQuery().exec( "UPDATE cmhead "
                        "SET cmhead_printed=TRUE "
                        "WHERE (NOT cmhead_printed);" );

    omfgThis->sCreditMemosUpdated();
  }
  else
    QMessageBox::information( this, tr("No Credit Memos to Print"),
                              tr("There aren't any Credit Memos to print.") );

  accept();
}
Ejemplo n.º 21
0
void company::sTest()
{
  XSqlQuery companyTest;
  if (DEBUG)
    qDebug("company::sTest()");

  QString dbURL;
  QString protocol = "psql";
  QString host = _extServer->text();
  QString db   = _extDB->text();
  QString port = _extPort->cleanText();

  buildDatabaseURL(dbURL, protocol, host, db, port);
  if (DEBUG)
    qDebug("company::sTest() dbURL before login2 = %s", qPrintable(dbURL));

  ParameterList params;
  params.append("databaseURL", dbURL);
  params.append("multipleConnections");

  login2 newdlg(this, "testLogin", false);
  newdlg.set(params);
  if (newdlg.exec() == QDialog::Rejected)
    return;

  dbURL = newdlg._databaseURL;
  if (DEBUG)
    qDebug("company::sTest() dbURL after login2 = %s", qPrintable(dbURL));
  parseDatabaseURL(dbURL, protocol, host, db, port);

  QSqlDatabase testDB = QSqlDatabase::addDatabase("QPSQL7", db);
  testDB.setHostName(host);
  testDB.setDatabaseName(db);
  testDB.setUserName(newdlg.username());
  testDB.setPassword(newdlg.password());
  testDB.setPort(port.toInt());
  if (testDB.open())
  {
    if (DEBUG)
      qDebug("company::sTest() opened testDB!");

    XSqlQuery rmq(testDB);
    rmq.prepare("SELECT fetchMetricText('ServerVersion') AS result;");
    rmq.exec();
    if (rmq.first())
    {
      if (rmq.value("result").toString() != _metrics->value("ServerVersion"))
      {
        QMessageBox::warning(this, tr("Versions Incompatible"),
                             tr("<p>The version of the child database is not "
                                "the same as the version of the parent "
                                "database (%1 vs. %2). The data cannot safely "
                                "be synchronized.")
                             .arg(rmq.value("result").toString())
                             .arg(_metrics->value("ServerVersion")));
        return;
      }
    }
    else if (rmq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, rmq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    rmq.exec("SELECT * FROM curr_symbol WHERE curr_base;");
    if (_external->isChecked())
    {
      companyTest.prepare("SELECT * FROM curr_symbol WHERE curr_id=:curr_id;");
      companyTest.bindValue(":curr_id", _currency->id());
      companyTest.exec();
    }
    else
      companyTest.exec("SELECT * FROM curr_symbol WHERE curr_base;");

    if (companyTest.first() && rmq.first())
    {
      if (rmq.value("curr_symbol").toString() != companyTest.value("curr_symbol").toString() &&
          rmq.value("curr_abbr").toString() != companyTest.value("curr_abbr").toString())
      {
        QMessageBox::warning(this, tr("Currencies Incompatible"),
                             tr("<p>The currency of the child database does "
                                "not appear to match the selected currency for "
                                "the company (%1 %2 %3 vs. %4 %5 %6). The data may "
                                "not synchronize properly.")
                             .arg(rmq.value("curr_name").toString())
                             .arg(rmq.value("curr_symbol").toString())
                             .arg(rmq.value("curr_abbr").toString())
                             .arg(companyTest.value("curr_name").toString())
                             .arg(companyTest.value("curr_symbol").toString())
                             .arg(companyTest.value("curr_abbr").toString()));
        return;
      }
    }
    else if (rmq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, rmq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (companyTest.lastError().type() != QSqlError::NoError)
    {
      systemError(this, companyTest.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (!rmq.first())
    {
      QMessageBox::warning(this, tr("No Base Currency"),
                           tr("<p>The child database does not appear to have "
                              "a base currency defined. The data cannot safely "
                              "be synchronized."));
      return;
    }
    else if (!companyTest.first())
    {
      QMessageBox::warning(this, tr("No Base Currency"),
                           tr("<p>The parent database does not appear to have "
                              "a base currency defined. The data cannot safely "
                              "be synchronized."));
      return;
    }

    rmq.prepare("SELECT * FROM company WHERE (company_number=:number);");
    rmq.bindValue(":number", _number->text());
    rmq.exec();
    if (rmq.first())
    {
      QMessageBox::warning(this, windowTitle(), tr("Test Successful."));
      return;
    }
    else if (rmq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, rmq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else
    {
      QMessageBox::warning(this, tr("No Corresponding Company"),
                           tr("<p>The child database does not appear to have "
                              "a Company %1 defined. The data cannot safely "
                              "be synchronized.").arg(_number->text()));
      return;
    }
  }
}
Ejemplo n.º 22
0
int CreateFunction::writeToDB(const QByteArray &pdata, const QString pkgname,
                              QString &errMsg)
{
  if (DEBUG)
    qDebug("CreateFunction::writeToDb(%s, %s, &errMsg)",
           pdata.data(), qPrintable(pkgname));

  QString destschema;
  if (! _schema.isEmpty())
    destschema = _schema;
  else if (pkgname.isEmpty())
    destschema = "public";
  else if (! pkgname.isEmpty())
    destschema = pkgname;

  XSqlQuery oidq;
  QMap<QString,int> oldoids;

  oidq.prepare("SELECT pg_proc.oid, oidvectortypes(proargtypes) "
               "FROM pg_proc, pg_namespace "
               "WHERE ((pg_namespace.oid=pronamespace)"
               "  AND  (proname=:name)"
               "  AND  (nspname=:schema));");
  oidq.bindValue(":name",   _name);
  oidq.bindValue(":schema", destschema);

  oidq.exec();
  while (oidq.next())
    oldoids.insert(oidq.value(1).toString(), oidq.value(0).toInt());

  if (oidq.lastError().type() != QSqlError::NoError)
  {
    errMsg = _sqlerrtxt.arg(_filename)
                      .arg(oidq.lastError().databaseText())
                      .arg(oidq.lastError().driverText());
    return -1;
  }
  if (DEBUG)
  {
    QMap<QString, int>::const_iterator i = oldoids.constBegin();
    while (i != oldoids.constEnd())
    {
      qDebug("CreateFunction::writeToDB() %s(%s) -> %d",
             qPrintable(_name), qPrintable(i.key()), i.value());
      i++;
    }
  }

  int returnVal = Script::writeToDB(pdata, pkgname, errMsg);
  if (returnVal < 0)
    return returnVal;

  oidq.exec();        // reuse the query
  int count = 0;
  while (oidq.next())
  {
    // error checking - if none found then there's a bug somewhere
    if (DEBUG)
      qDebug("CreateFunction::writeToDB() oid = %d, argtypes = %s",
             oidq.value(0).toInt(), qPrintable(oidq.value(1).toString()));
    count++;
  }
  if (oidq.lastError().type() != QSqlError::NoError)
  {
    errMsg = _sqlerrtxt.arg(_filename)
                      .arg(oidq.lastError().databaseText())
                      .arg(oidq.lastError().driverText());
    return -5;
  }
  if (count == 0)
  {
    errMsg = TR("Could not find function %1 in the database for package %2. "
                "The script %3 does not match the package.xml description.")
              .arg(_name).arg(pkgname).arg(_filename);
    return -6;
  }

  return 0;
}
Ejemplo n.º 23
0
void itemPricingScheduleItem::sUpdateCosts(int pItemid)
{
    XSqlQuery uom;
    uom.prepare("SELECT uom_id, uom_name"
                "  FROM item"
                "  JOIN uom ON (item_inv_uom_id=uom_id)"
                " WHERE(item_id=:item_id)"
                " UNION "
                "SELECT uom_id, uom_name"
                "  FROM item"
                "  JOIN itemuomconv ON (itemuomconv_item_id=item_id)"
                "  JOIN uom ON (itemuomconv_to_uom_id=uom_id)"
                " WHERE((itemuomconv_from_uom_id=item_inv_uom_id)"
                "   AND (item_id=:item_id))"
                " UNION "
                "SELECT uom_id, uom_name"
                "  FROM item"
                "  JOIN itemuomconv ON (itemuomconv_item_id=item_id)"
                "  JOIN uom ON (itemuomconv_from_uom_id=uom_id)"
                " WHERE((itemuomconv_to_uom_id=item_inv_uom_id)"
                "   AND (item_id=:item_id))"
                " ORDER BY uom_name;");
    uom.bindValue(":item_id", _item->id());
    uom.exec();
    if (q.lastError().type() != QSqlError::NoError)
    {
        systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                    __FILE__, __LINE__);
        done(-1);
    }
    _qtyUOM->populate(uom);
    _priceUOM->populate(uom);

    XSqlQuery cost;
    cost.prepare( "SELECT item_inv_uom_id, item_price_uom_id,"
                  "       iteminvpricerat(item_id) AS ratio,"
                  "       item_listprice, "
                  "       (stdcost(item_id) * iteminvpricerat(item_id)) AS standard,"
                  "       (actcost(item_id, :curr_id) * iteminvpricerat(item_id)) AS actual "
                  "  FROM item"
                  " WHERE (item_id=:item_id);" );
    cost.bindValue(":item_id", pItemid);
    cost.bindValue(":curr_id", _actCost->id());
    cost.exec();
    if (cost.first())
    {
        _invuomid = cost.value("item_inv_uom_id").toInt();
        _listPrice->setBaseValue(cost.value("item_listprice").toDouble());
        _pricingRatio->setDouble(cost.value("ratio").toDouble());

        _stdCost->setBaseValue(cost.value("standard").toDouble());
        _actCost->setLocalValue(cost.value("actual").toDouble());

        _qtyUOM->setId(cost.value("item_inv_uom_id").toInt());
        _priceUOM->setId(cost.value("item_price_uom_id").toInt());
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
        systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                    __FILE__, __LINE__);
        done(-1);
    }

    if (_item->isConfigured())
        _tab->setTabEnabled(_tab->indexOf(_configuredPrices),TRUE);
    else
        _tab->setTabEnabled(_tab->indexOf(_configuredPrices),FALSE);
}
Ejemplo n.º 24
0
void subaccount::sSave()
{
  XSqlQuery subaccountSave;
  if (_number->text().length() == 0)
  {
      QMessageBox::warning( this, tr("Cannot Save Sub Account"),
                            tr("You must enter a valid Number.") );
      return;
  }
  
  subaccountSave.prepare("SELECT subaccnt_id"
            "  FROM subaccnt"
            " WHERE((subaccnt_id != :subaccnt_id)"
            "   AND (subaccnt_number=:subaccnt_number))");
  subaccountSave.bindValue(":subaccnt_id", _subaccntid);
  subaccountSave.bindValue(":subaccnt_number", _number->text());
  subaccountSave.exec();
  if(subaccountSave.first())
  {
    QMessageBox::critical(this, tr("Duplicate Sub Account Number"),
      tr("A Sub Account Number already exists for the one specified.") );
    return;
  }

  if (_mode == cNew)
  {
    subaccountSave.exec("SELECT NEXTVAL('subaccnt_subaccnt_id_seq') AS subaccnt_id;");
    if (subaccountSave.first())
      _subaccntid = subaccountSave.value("subaccnt_id").toInt();
    else if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Retrieving Sub Account Information"),
                                  subaccountSave, __FILE__, __LINE__))
    {
      return;
    }
    
    subaccountSave.prepare( "INSERT INTO subaccnt "
               "( subaccnt_id, subaccnt_number, subaccnt_descrip ) "
               "VALUES "
               "( :subaccnt_id, :subaccnt_number, :subaccnt_descrip );" );
  }
  else if (_mode == cEdit)
  {
    if (_number->text() != _cachedNumber &&
        QMessageBox::question(this, tr("Change All Accounts?"),
                              tr("<p>The old Subaccount Number %1 might be "
                                 "used by existing Accounts. Would you like to "
                                 "change all accounts that use it to Subaccount"
                                 " Number %2?<p>If you answer 'No' then change "
                                 "the Number back to %3 and Save again.")
                                .arg(_cachedNumber)
                                .arg(_number->text())
                                .arg(_cachedNumber),
                              QMessageBox::Yes,
                              QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
      return;

    subaccountSave.prepare( "UPDATE subaccnt "
               "SET subaccnt_number=:subaccnt_number,"
               "    subaccnt_descrip=:subaccnt_descrip "
               "WHERE (subaccnt_id=:subaccnt_id);" );
  }
  
  subaccountSave.bindValue(":subaccnt_id", _subaccntid);
  subaccountSave.bindValue(":subaccnt_number", _number->text());
  subaccountSave.bindValue(":subaccnt_descrip", _descrip->toPlainText());
  subaccountSave.exec();
  if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Saving Sub Account Information"),
                                subaccountSave, __FILE__, __LINE__))
  {
    return;
  }
  
  done(_subaccntid);
}
Ejemplo n.º 25
0
enum SetResponse workOrder::set(const ParameterList &pParams)
{
  _captive = TRUE;

  QString  returnValue;
  QVariant param;
  bool     valid;

  param = pParams.value("itemsite_id", &valid);
  if (valid)
  {
    _item->setItemsiteid(param.toInt());
    _item->setEnabled(FALSE);
    _warehouse->setEnabled(FALSE);

    _qty->setFocus();
  }

  param = pParams.value("qty", &valid);
  if (valid)
    _qty->setText(formatQty(param.toDouble()));

  param = pParams.value("dueDate", &valid);
  if (valid)
  {
    _dueDate->setDate(param.toDate());
    sUpdateStartDate();
  }

  param = pParams.value("wo_id", &valid);
  if (valid)
    _woid = param.toInt();

  param = pParams.value("planord_id", &valid);
  if (valid)
    _planordid = param.toInt();

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;

	  _item->setQuery("SELECT DISTINCT item_id, item_number, item_descrip1, item_descrip2,"
                      "       item_active, item_config, item_type, uom_name "
                      "FROM item JOIN uom ON (item_inv_uom_id=uom_id) "
                      "WHERE (item_type IN ('M', 'B') "
					  "AND (item_active)) ");
      _qtyReceivedLit->clear();
      _tabs->removePage(_tabs->page(3));

      populateWoNumber();
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;

     _item->setQuery("SELECT DISTINCT item_id, item_number, item_descrip1, item_descrip2,"
                     "       item_active, item_config, item_type, uom_name "
                     "FROM item JOIN uom ON (item_inv_uom_id=uom_id) "
                     "WHERE (item_type IN ('M', 'B', 'J')) ");
      XSqlQuery wo;
      wo.prepare( "SELECT wo_itemsite_id, wo_priority, wo_status,"
                  "       formatWoNumber(wo_id) AS f_wonumber,"
                  "       formatQty(wo_qtyord) AS f_ordered,"
                  "       formatQty(wo_qtyrcv) AS f_received,"
                  "       wo_startdate, wo_duedate,"
                  "       formatMoney(wo_wipvalue) AS f_wipvalue,"
				  "       formatMoney(wo_postedvalue) AS f_postedvalue,"
				  "       formatMoney(wo_postedvalue-wo_wipvalue) AS f_rcvdvalue,"
                  "       wo_prodnotes, wo_prj_id, "
				  "       wo_bom_rev_id, wo_boo_rev_id, "
				  "       wo_cosmethod "
                  "FROM wo "
                  "WHERE (wo_id=:wo_id);" );
      wo.bindValue(":wo_id", _woid);
      wo.exec();
      if (wo.first())
      {
        _oldPriority = wo.value("wo_priority").toInt();
        _oldStartDate = wo.value("wo_startdate").toDate();
        _oldDueDate = wo.value("wo_duedate").toDate();
        _oldQty = wo.value("f_ordered").toString();

        _woNumber->setText(wo.value("f_wonumber").toString());
        _item->setItemsiteid(wo.value("wo_itemsite_id").toInt());
        _priority->setValue(_oldPriority);
		_postedValue->setText(wo.value("f_postedvalue").toString());
		_rcvdValue->setText(wo.value("f_rcvdvalue").toString());
        _wipValue->setText(wo.value("f_wipvalue").toString());
        _qty->setText(wo.value("f_ordered").toString());
        _qtyReceived->setText(wo.value("f_received").toString());
        _startDate->setDate(_oldStartDate);
        _dueDate->setDate(_oldDueDate);
        _productionNotes->setText(wo.value("wo_prodnotes").toString());
        _comments->setId(_woid);
        _project->setId(wo.value("wo_prj_id").toInt());
		_bomRevision->setId(wo.value("wo_bom_rev_id").toInt());
		_booRevision->setId(wo.value("wo_boo_rev_id").toInt());

		if (wo.value("wo_cosmethod").toString() == "D")
		  _todate->setChecked(TRUE);
		else if (wo.value("wo_cosmethod").toString() == "P")
		  _proportional->setChecked(TRUE);
		else
	      _jobCosGroup->hide();

        // If the W/O is closed or Released don't allow changing some items.
        if(wo.value("wo_status").toString() == "C" || wo.value("wo_status") == "R")
        {
          _priority->setEnabled(false);
          _qty->setEnabled(false);
          _dueDate->setEnabled(false);
          _startDate->setEnabled(false);
        }

        _startDate->setEnabled(true);
        _woNumber->setEnabled(false);
        _item->setReadOnly(true);
	    _bomRevision->setEnabled(wo.value("wo_status").toString() == "O");
        _booRevision->setEnabled(wo.value("wo_status").toString() == "O");
        _warehouse->setEnabled(false);
        _comments->setReadOnly(false);
        _leadTimeLit->hide();
        _leadTime->hide();
        _daysLit->hide();
        _printTraveler->hide();
        _bottomSpacer->hide();
        _create->setText(tr("&Save"));

        _close->setFocus();
      }
      else
      {
        systemError(this, tr("A System Error occurred at %1::%2, W/O ID %3.")
                          .arg(__FILE__)
                          .arg(__LINE__)
                          .arg(_woid) );
        close();
      }
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _item->setQuery("SELECT DISTINCT item_id, item_number, item_descrip1, item_descrip2,"
                      "       item_active, item_config, item_type, uom_name "
                      "FROM item JOIN uom ON (item_inv_uom_id=uom_id) "
                      "WHERE (item_type IN ('M', 'B', 'J')) ");
      XSqlQuery wo;
      wo.prepare( "SELECT wo_itemsite_id, wo_priority,"
                  "       formatWoNumber(wo_id) AS f_wonumber,"
                  "       formatQty(wo_qtyord) AS f_ordered,"
                  "       formatQty(wo_qtyrcv) AS f_received,"
                  "       wo_startdate, wo_duedate,"
                  "       formatMoney(wo_wipvalue) AS f_wipvalue,"
				  "       formatMoney(wo_postedvalue) AS f_postedvalue,"
				  "       formatMoney(wo_postedvalue-wo_wipvalue) AS f_rcvdvalue,"
                  "       wo_prodnotes, wo_prj_id, wo_bom_rev_id, "
				  "       wo_boo_rev_id, wo_cosmethod "
                  "FROM wo "
                  "WHERE (wo_id=:wo_id);" );
      wo.bindValue(":wo_id", _woid);
      wo.exec();
      if (wo.first())
      {
        _mode = cView;

        _woNumber->setText(wo.value("f_wonumber").toString());
        _item->setItemsiteid(wo.value("wo_itemsite_id").toInt());
        _priority->setValue(wo.value("wo_priority").toInt());
		_postedValue->setText(wo.value("f_postedvalue").toString());
		_rcvdValue->setText(wo.value("f_rcvdvalue").toString());
        _wipValue->setText(wo.value("f_wipvalue").toString());
        _qty->setText(wo.value("f_ordered").toString());
        _qtyReceived->setText(wo.value("f_received").toString());
        _startDate->setDate(wo.value("wo_startdate").toDate());
        _dueDate->setDate(wo.value("wo_duedate").toDate());
        _productionNotes->setText(wo.value("wo_prodnotes").toString());
        _comments->setId(_woid);
        _project->setId(wo.value("wo_prj_id").toInt());
		_bomRevision->setId(wo.value("wo_bom_rev_id").toInt());
		_booRevision->setId(wo.value("wo_boo_rev_id").toInt());

		if (wo.value("wo_cosmethod").toString() == "D")
		  _todate->setChecked(TRUE);
		else if (wo.value("wo_cosmethod").toString() == "P")
		  _proportional->setChecked(TRUE);
		else
	      _jobCosGroup->hide();
 
        _woNumber->setEnabled(FALSE);
        _item->setReadOnly(TRUE);
        _bomRevision->setEnabled(FALSE);
        _booRevision->setEnabled(FALSE);
        _warehouse->setEnabled(FALSE);
        _priority->setEnabled(FALSE);
        _qty->setEnabled(FALSE);
        _startDate->setEnabled(FALSE);
        _dueDate->setEnabled(FALSE);
        _productionNotes->setReadOnly(TRUE);
        _create->hide();
        _leadTimeLit->hide();
        _leadTime->hide();
        _daysLit->hide();
        _printTraveler->hide();
        _bottomSpacer->hide();
        _close->setText(tr("&Close"));
        _project->setEnabled(FALSE);
        _itemcharView->setEnabled(false);
		_jobCosGroup->setEnabled(FALSE);
        
        _close->setFocus();
      }
      else
      {
        systemError(this, tr("A System Error occurred at %1::%2, W/O ID %3.")
                          .arg(__FILE__)
                          .arg(__LINE__)
                          .arg(_woid) );
        close();
      }
    }
    else if (param.toString() == "release")
    {
      _mode = cRelease;
      _tabs->removePage(_tabs->page(3));

      q.prepare( "SELECT planord_itemsite_id, planord_duedate,"
                 "       CASE WHEN(planord_mps) THEN 'P'"
                 "            ELSE 'M'"
                 "       END AS sourcetype,"
                 "       CASE WHEN(planord_mps) THEN planord_pschitem_id"
                 "            ELSE planord_id"
                 "       END AS sourceid,"
                 "       formatQty(planord_qty) AS qty "
                 "FROM planord "
                 "WHERE (planord_id=:planord_id);" );
      q.bindValue(":planord_id", _planordid);
      q.exec();
      if (q.first())
      {
        _item->setReadOnly(TRUE);
        _warehouse->setEnabled(FALSE);

        _planordtype=q.value("sourcetype").toString();
        _sourceid=q.value("sourceid").toInt();
        _qty->setText(q.value("qty").toString());
        _dueDate->setDate(q.value("planord_duedate").toDate());
        _item->setItemsiteid(q.value("planord_itemsite_id").toInt());

        sUpdateStartDate();
        populateWoNumber();

        _qty->setEnabled(FALSE);
        _qtyReceivedLit->clear();
        _startDate->setEnabled(FALSE);
        _dueDate->setEnabled(FALSE);
        _wipValueLit->hide();
        _wipValue->hide();
        _leadTimeLit->hide();
        _leadTime->hide();
        _daysLit->hide();

        _create->setFocus();
      }
      else
      {
        systemError(this, tr("A System Error occurred at %1::%2, Planned Order ID %3.")
                          .arg(__FILE__)
                          .arg(__LINE__)
                          .arg(_planordid) );
        close();
      }
    }
  }
  
  return NoError;
}
Ejemplo n.º 26
0
void taxZone::sSave()
{
  XSqlQuery taxSave;
  if (_taxZone->text().length() == 0)
  {
      QMessageBox::warning( this, tr("Cannot Save Tax Zone"),
                            tr("You must enter a valid Code.") );
      return;
  }
  
  if (_mode == cEdit)
  {
    taxSave.prepare( "SELECT taxzone_id "
               "FROM taxzone "
               "WHERE ( (taxzone_id<>:taxzone_id)"
               " AND (UPPER(taxzone_code)=UPPER(:taxzone_code)) );");
    taxSave.bindValue(":taxzone_id", _taxzoneid);
  }
  else
  {
    taxSave.prepare( "SELECT taxzone_id "
               "FROM taxzone "
               "WHERE (taxzone_code=:taxzone_code);");
  }
  taxSave.bindValue(":taxzone_code", _taxZone->text().trimmed());
  taxSave.exec();
  if (taxSave.first())
  {
    QMessageBox::critical( this, tr("Cannot Create Tax Zone"),
			   tr( "A Tax Zone with the entered code already exists."
			       "You may not create a Tax Zone with this code." ) );
    _taxZone->setFocus();
    return;
  }
  else if (taxSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, taxSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

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

  taxSave.exec("BEGIN;");

  if (_mode == cEdit)
  {
    taxSave.prepare( "UPDATE taxzone "
               "SET taxzone_code=:taxzone_code,"
               "    taxzone_descrip=:taxzone_descrip "
               "WHERE (taxzone_id=:taxzone_id);" );
  }
  else if (_mode == cNew)
  {
    taxSave.exec("SELECT NEXTVAL('taxzone_taxzone_id_seq') AS taxzone_id;");
    if (taxSave.first())
      _taxzoneid = taxSave.value("taxzone_id").toInt();
    else if (taxSave.lastError().type() != QSqlError::NoError)
    {
      rollback.exec();
      systemError(this, taxSave.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    taxSave.prepare( "INSERT INTO taxzone "
               "(taxzone_id, taxzone_code, taxzone_descrip)" 
               "VALUES "
               "(:taxzone_id, :taxzone_code, :taxzone_descrip);" ); 
  }
  taxSave.bindValue(":taxzone_id", _taxzoneid);
  taxSave.bindValue(":taxzone_code", _taxZone->text().trimmed());
  taxSave.bindValue(":taxzone_descrip", _description->text());
  taxSave.exec();
  if (taxSave.lastError().type() != QSqlError::NoError)
  {
    rollback.exec();
    systemError(this, taxSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  taxSave.exec("COMMIT;");

  done(_taxzoneid);
}
Ejemplo n.º 27
0
void shipOrder::sShip()
{
  XSqlQuery shipq;
  shipq.prepare( "UPDATE shiphead "
	     "   SET shiphead_shipvia=:shiphead_shipvia,"
	     "       shiphead_freight=:shiphead_freight,"
	     "       shiphead_freight_curr_id=:shiphead_freight_curr_id,"
	     "       shiphead_tracknum=:shiphead_tracknum "
	     " WHERE (shiphead_id=:shiphead_id);");
  shipq.bindValue(":shiphead_shipvia",	_shipVia->currentText());
  shipq.bindValue(":shiphead_freight",	_freight->localValue());
  shipq.bindValue(":shiphead_freight_curr_id", _freight->id());
  shipq.bindValue(":shiphead_tracknum",	_tracknum->currentText());
  shipq.bindValue(":shiphead_id",		_shipment->id());
  shipq.exec();
  if (shipq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, shipq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");
  // failed insertGLTransaction RETURNs -5 rather than RAISE EXCEPTION
  shipq.exec("BEGIN;");

  shipq.prepare( "SELECT shipShipment(:shiphead_id, :ts) AS result;");
  shipq.bindValue(":shiphead_id", _shipment->id());
  shipq.bindValue(":ts",          _transDate->date());
  shipq.exec();
  if (shipq.first())
  {
    int result = shipq.value("result").toInt();
    if (result == -6)
    {
      rollback.exec();
      shipq.prepare("SELECT itemsite_id, tohead_trns_warehous_id,"
	        "       tohead_dest_warehous_id "
	        "FROM shiphead, shipitem, tohead, toitem, itemsite "
	        "WHERE ((itemsite_item_id=toitem_item_id)"
	        "  AND  (itemsite_warehous_id=tohead_src_warehous_id)"
	        "  AND  (toitem_tohead_id=tohead_id)"
	        "  AND  (shipitem_orderitem_id=toitem_id)"
	        "  AND  (shiphead_id=shipitem_shiphead_id)"
	        "  AND  (shiphead_order_type='TO')"
	        "  AND  (NOT shiphead_shipped)"
	        "  AND  (shiphead_id=:shiphead_id));");
      shipq.bindValue(":shiphead_id", _shipment->id());
      shipq.exec();
      while (shipq.next())
      {
	// missing transit itemsite is fatal here but not missing dest
	int transis = itemSite::createItemSite(this,
					       shipq.value("itemsite_id").toInt(),
				     shipq.value("tohead_trns_warehous_id").toInt(),
				     false);
	int destis  = itemSite::createItemSite(this,
					       shipq.value("itemsite_id").toInt(),
				     shipq.value("tohead_dest_warehous_id").toInt(),
				     true);
	if (transis <= 0 || destis < 0)
	  return;
      }
      if (shipq.lastError().type() != QSqlError::NoError)
      {
        systemError(this, shipq.lastError().databaseText(), __FILE__, __LINE__);
	return;
      }
      sShip();	// beware of endless loop if you change createItemSite err check
      return;	// return because the recursive call cleans up for us
    }
    else if (result < 0)
    {
      rollback.exec();
      systemError(this, storedProcErrorLookup("shipShipment", result),
		  __FILE__, __LINE__);
      return;
    }
  }
  else if (shipq.lastError().type() != QSqlError::NoError)
  {
    rollback.exec();
    QString errorStr = shipq.lastError().databaseText();
    if(errorStr.startsWith("ERROR:  null value in column \"gltrans_accnt_id\" violates not-null constraint"))
      errorStr = tr("One or more required accounts are not set or set incorrectly."
                    " Please make sure that all your Cost Category and Sales Account Assignments"
                    " are complete and correct.");
    systemError(this, errorStr, __FILE__, __LINE__);
    return;
  }

  shipq.exec("COMMIT;");
  if (shipq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, shipq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  // END the transaction

  if (_print->isChecked())
  {
    ParameterList params;
    params.append("shiphead_id", _shipment->id());
    params.append("print");

    printPackingList newdlg(this, "", TRUE);
    newdlg.set(params);
  }

  if (_order->isSO() && _select->isChecked())
  {
    shipq.prepare("SELECT selectUninvoicedShipment(:shiphead_id) AS result;");
    shipq.bindValue(":shiphead_id", _shipment->id());
    shipq.exec();
    if (shipq.first())
    {
      int cobmiscid = shipq.value("result").toInt();
      if (cobmiscid < 0)
      {
	systemError(this,
	      storedProcErrorLookup("selectUninvoicedShipment", cobmiscid),
	      __FILE__, __LINE__);
	return;
      }
      else if (0 == cobmiscid)
      {
	QMessageBox::information(this, tr("Already Invoiced"),
				 tr("<p>This shipment appears to have been "
				   "invoiced already. It will not be selected "
				   "for billing again."));
      }
      else if (_create->isChecked())
      {
        shipq.prepare("SELECT createInvoice(:cobmisc_id) AS result;");
	shipq.bindValue(":cobmisc_id", cobmiscid);
	shipq.exec();
	if (shipq.first())
	{
	  int result = shipq.value("result").toInt();
	  if (result < 0)
	  {
	    systemError(this,
		      storedProcErrorLookup("postBillingSelection", result),
		      __FILE__, __LINE__);
	    return;
	  }
	  ParameterList params;
	  params.append("invchead_id", result);

	  printInvoice newdlg(this, "", TRUE);
	  newdlg.set(params);
	  newdlg.exec();

	  omfgThis->sInvoicesUpdated(result, TRUE);
	  omfgThis->sSalesOrdersUpdated(_order->id());
	}
	else if (shipq.lastError().type() != QSqlError::NoError)
	{
	  systemError(this, shipq.lastError().databaseText() +
		      tr("<p>Although Sales Order %1 was successfully shipped "
			 "and selected for billing, the Invoice was not "
			 "created properly. You may need to create an Invoice "
			 "manually from the Billing Selection.")
			.arg(_order->id()),
		      __FILE__, __LINE__);
	  return;
	}

	omfgThis->sBillingSelectionUpdated(_order->id(), TRUE);
      }
    }
    else if (shipq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, shipq.lastError().databaseText() +
		  tr("<p>Although Sales Order %1 was successfully shipped, "
		     "it was not selected for billing. You must manually "
		     "select this Sales Order for Billing.")
		    .arg(_order->id()),
		  __FILE__, __LINE__);
      return;
    }
  }

  if (_order->isTO() && _receive->isChecked())
  {
    QString recverr = tr("<p>Receiving inventory for this Transfer Order "
			"failed although Shipping the Order succeeded. "
			"Manually receive this order using the Enter Order "
			"Receipt window.");
    shipq.exec("BEGIN;");
    ParameterList params;

    if (_metrics->boolean("MultiWhs"))
      params.append("MultiWhs");
    params.append("tohead_id",   _order->id());
    params.append("orderid",     _order->id());
    params.append("ordertype",   "TO");
    params.append("shiphead_id", _shipment->id());

    MetaSQLQuery recvm = mqlLoad("receipt", "receiveAll");
    shipq = recvm.toQuery(params);

    while (shipq.next())
    {
      int result = shipq.value("result").toInt();
      if (result < 0)
      {
	rollback.exec();
	systemError(this,
		    recverr + storedProcErrorLookup("enterReceipt", result),
		    __FILE__, __LINE__);
      }
      omfgThis->sPurchaseOrderReceiptsUpdated();
    }
    if (shipq.lastError().type() != QSqlError::NoError)
    {
      rollback.exec();
      systemError(this, recverr + "<br>" + shipq.lastError().databaseText(),
		  __FILE__, __LINE__);
    }

    shipq.exec("COMMIT;");
    if (shipq.lastError().type() != QSqlError::NoError)
    {
      systemError(this,
		  recverr + "<br>" + shipq.lastError().databaseText(),
		  __FILE__, __LINE__);
    }

    ParameterList recvParams;
    recvParams.append("tohead_id", _order->id());
    enterPoReceipt *newdlg = new enterPoReceipt();
    newdlg->set(recvParams);

    // to address bug 5680, replace
    // omfgThis->handleNewWindow(newdlg, Qt::ApplicationModal);
    // with
    newdlg->sPost();
    // end of replacement
  }

  if (_captive)
    accept();
  else
  {
    _order->setId(-1);
    _order->setEnabled(true);
    sHandleButtons();
    _billToName->clear();
    _shipToName->clear();
    _shipToAddr1->clear();
    _freight->setEnabled(TRUE);
    _freight->reset();
    _shipVia->clear();
    _shipment->clear();
    _shipment->setEnabled(false);
    _close->setText(tr("&Close"));

    _order->setFocus();
  }

  // Update the shipdatasum record to reflect shipped
  shipq.prepare("UPDATE shipdatasum "
		"   SET shipdatasum_shipped=true "
                " WHERE ((shipdatasum_cosmisc_tracknum = :tracknum)"
		"   AND  (   (shipdatasum_shiphead_number=:shiphead_number)"
		"         OR (:shiphead_number IS NULL)));");
  shipq.bindValue(":tracknum", _tracknum->currentText());
  if (! _shipment->number().isEmpty())
    shipq.bindValue(":shiphead_number", _shipment->number());
  shipq.exec();
  if (shipq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, shipq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Ejemplo n.º 28
0
void plannedOrder::sCreate()
{
  XSqlQuery plannedCreate;

  QList<GuiErrorCheck> errors;
  errors << GuiErrorCheck(!_item->isValid(), _item,
                          tr("You must enter or select a valid Item number before creating this Planned Order"))
         << GuiErrorCheck(!_qty->text().length(), _qty,
                          tr("You must enter a valid Qty. Ordered before creating this Planned Order"))
         << GuiErrorCheck(!_dueDate->isValid(), _dueDate,
                          tr("You must enter a valid Due Date before creating this Planned Order"))
     ;

  plannedCreate.prepare( "SELECT itemsite_id "
                         "FROM itemsite "
                         "WHERE ( (itemsite_item_id=:item_id)"
                         " AND (itemsite_warehous_id=:warehous_id) );" );
  plannedCreate.bindValue(":item_id", _item->id());
  plannedCreate.bindValue(":warehous_id", _warehouse->id());
  plannedCreate.exec();
  if (!plannedCreate.first())
  {
    errors << GuiErrorCheck(true, _item,
                            tr("The Item and Site entered is an invalid Item Site combination.")  );
  }

  int itemsiteid = plannedCreate.value("itemsite_id").toInt();
  int _supplyItemsiteId = -1;
  if (_toButton->isChecked())
  {
    plannedCreate.prepare("SELECT itemsite_id "
                          "FROM itemsite "
                          "WHERE ( (itemsite_item_id=:item_id)"
                          "  AND   (itemsite_warehous_id=:warehous_id) ); ");
    plannedCreate.bindValue(":item_id", _item->id());
    plannedCreate.bindValue(":warehous_id", _fromWarehouse->id());
    plannedCreate.exec();
    if (plannedCreate.first())
    {
      if (plannedCreate.value("itemsite_id").toInt() == itemsiteid)
      { 
        errors << GuiErrorCheck(true, _item,
                                tr("The Supplied From Site must be different from the Transfer To Site.") );
      }
      else
        _supplyItemsiteId = plannedCreate.value("itemsite_id").toInt();
    }
    else
    { 
      errors << GuiErrorCheck(true, _item,
                              tr("Cannot find Supplied From Item Site.") );
    }
  }

  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Planned Order"), errors))
    return;

  int foid = 0;

  if(cEdit == _mode)
    plannedCreate.prepare( "UPDATE planord "
               "SET planord_number=:planord_number, "
               "    planord_type=:planord_type, "
               "    planord_itemsite_id=:planord_itemsite_id, "
               "    planord_supply_itemsite_id=:planord_supply_itemsite_id, "
               "    planord_comments=:planord_comments, "
               "    planord_qty=:planord_qty, "
               "    planord_duedate=:planord_duedate, "
               "    planord_startdate=COALESCE(:planord_startdate, date(:planord_duedate) - :planord_leadtime) "
               "WHERE (planord_id=:planord_id);" );
  else
    plannedCreate.prepare( "SELECT createPlannedOrder( :planord_number, :planord_itemsite_id, :planord_qty, "
               "                   COALESCE(:planord_startdate, date(:planord_duedate) - :planord_leadtime), :planord_duedate, "
               "                   :planord_type, :planord_supply_itemsite_id, :planord_comments) AS result;" );

  plannedCreate.bindValue(":planord_number", _number->text().toInt());
  plannedCreate.bindValue(":planord_itemsite_id", itemsiteid);
  if (_poButton->isChecked())
    plannedCreate.bindValue(":planord_type", "P");
  else if (_woButton->isChecked())
    plannedCreate.bindValue(":planord_type", "W");
  else if (_toButton->isChecked())
  {
    plannedCreate.bindValue(":planord_type", "T");
    plannedCreate.bindValue(":planord_supply_itemsite_id", _supplyItemsiteId);
  }
  plannedCreate.bindValue(":planord_qty", _qty->toDouble());
  plannedCreate.bindValue(":planord_duedate", _dueDate->date());
  plannedCreate.bindValue(":planord_startdate", _startDate->date());
  plannedCreate.bindValue(":planord_leadtime", _leadTime->value());
  plannedCreate.bindValue(":planord_comments", _notes->toPlainText());
  plannedCreate.bindValue(":planord_id", _planordid);

  plannedCreate.exec();
  if (plannedCreate.lastError().type() != QSqlError::NoError)
  {
    systemError(this, plannedCreate.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if(cEdit == _mode)
  {
    plannedCreate.prepare( "SELECT explodePlannedOrder( :planord_id, true) AS result;" );
    plannedCreate.bindValue(":planord_id", _planordid);
    plannedCreate.exec();
    if (plannedCreate.first())
    {
      double result = plannedCreate.value("result").toDouble();
      if (result < 0.0)
      {
        systemError(this, tr("ExplodePlannedOrder returned %, indicating an "
                             "error occurred.").arg(result),
                    __FILE__, __LINE__);
        return;
      }
    }
    else if (plannedCreate.lastError().type() != QSqlError::NoError)
    {
      systemError(this, plannedCreate.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
  else
  {
    if (!plannedCreate.first())
    {
      systemError( this, tr("A System Error occurred at %1::%2.")
                         .arg(__FILE__)
                         .arg(__LINE__) );
      return;
    }

    foid = XDialog::Rejected;
    switch (plannedCreate.value("result").toInt())
    {
      case -1:
        QMessageBox::critical( this, tr("Planned Order not Exploded"),
                               tr( "The Planned Order was created but not Exploded as there is no valid Bill of Materials for the selected Item.\n"
                                   "You must create a valid Bill of Materials before you may explode this Planned Order." ));
        break;
  
      case -2:
        QMessageBox::critical( this, tr("Planned Order not Exploded"),
                               tr( "The Planned Order was created but not Exploded as Component Items defined in the Bill of Materials\n"
                                   "for the selected Planned Order Item do not exist in the selected Planned Order Site.\n"
                                   "You must create Item Sites for these Component Items before you may explode this Planned Order." ));
        break;

      default:
        foid = plannedCreate.value("result").toInt();
        break;
    }
  }

  if (_captive)
    done(foid);
  else
  {
    populateFoNumber();
    _item->setId(-1);
    _typeGroup->setEnabled(FALSE);
    _qty->clear();
    _dueDate->setNull();
    _leadTime->setValue(0);
    _startDate->setNull();
    _notes->clear();
    _close->setText(tr("&Close"));

    _item->setFocus();
  }
}
Ejemplo n.º 29
0
void shipOrder::sHandleTo()
{
  XSqlQuery shipHandleTo;
  _coitem->clear();
  _shipment->setEnabled(false);
  _shipment->removeOrderLimit();

  sHandleButtons();

  shipHandleTo.prepare("SELECT tohead_freight_curr_id, tohead_destname,"
            "       tohead_destaddress1,"
            "       SUM(toitem_freight) + tohead_freight AS freight "
            "FROM tohead, toitem "
            "WHERE ((toitem_tohead_id=tohead_id)"
            "  AND  (toitem_status<>'X')"
            "  AND  (tohead_id=:tohead_id)) "
            "GROUP BY tohead_freight_curr_id, tohead_destname,"
            "         tohead_destaddress1, tohead_freight;");
  shipHandleTo.bindValue(":tohead_id", _order->id());
  shipHandleTo.exec();
  if (shipHandleTo.first())
  {
    _freight->setId(shipHandleTo.value("tohead_freight_curr_id").toInt());
    _freight->setLocalValue(shipHandleTo.value("freight").toDouble());
    _billToName->setText(tr("Transfer Order"));
    _shipToName->setText(shipHandleTo.value("tohead_destname").toString());
    _shipToAddr1->setText(shipHandleTo.value("tohead_destaddress1").toString());
  }
  else if (shipHandleTo.lastError().type() != QSqlError::NoError)
  {
    systemError(this, shipHandleTo.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  QString sql( "SELECT shiphead_id "
               "FROM shiphead "
               "WHERE ( (NOT shiphead_shipped)"
               "<? if exists(\"shiphead_id\") ?>"
               " AND (shiphead_id=<? value(\"shiphead_id\") ?>)"
               "<? endif ?>"
               " AND (shiphead_order_id=<? value(\"tohead_id\") ?>)"
               " AND (shiphead_order_type='TO'));" );
  ParameterList params;
  params.append("tohead_id", _order->id());
  if (_shipment->isValid())
    params.append("shiphead_id", _shipment->id());
  MetaSQLQuery mql(sql);
  shipHandleTo = mql.toQuery(params);
  if (shipHandleTo.first())
  {
    if (_shipment->id() != shipHandleTo.value("shiphead_id").toInt())
      _shipment->setId(shipHandleTo.value("shiphead_id").toInt());

    if (shipHandleTo.next())
    {
      _shipment->setType("TO");
      _shipment->limitToOrder(_order->id());
      _shipment->setEnabled(true);
    }
  }
  else if (shipHandleTo.lastError().type() != QSqlError::NoError)
  {
    systemError(this, shipHandleTo.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  else if (_shipment->isValid())
  {
    params.clear();
    params.append("tohead_id", _order->id());
    MetaSQLQuery mql(sql);
    shipHandleTo = mql.toQuery(params);
    if (shipHandleTo.first())
    {
      _shipment->setId(shipHandleTo.value("shiphead_id").toInt());
      if (shipHandleTo.next())
      {
        _shipment->setType("TO");
        _shipment->limitToOrder(_order->id());
        _shipment->setEnabled(true);
      }
    }
    else if (shipHandleTo.lastError().type() != QSqlError::NoError)
    {
      systemError(this, shipHandleTo.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else
      _shipment->clear();
  }
  else
  {
    QMessageBox::warning(this, tr("Nothing to ship"),
                      tr("<p>You may not ship this Transfer Order because "
                         "no stock has been issued to shipping for it."));
    _order->setFocus();
    return;
  }
}
Ejemplo n.º 30
0
bool user::sPopulate()
{
  XSqlQuery usrq;
  if (! _cUsername.isEmpty())
  {
    usrq.prepare("SELECT *, userCanCreateUsers(usr_username) AS createusers,"
                 "       userCanCreateUsers(getEffectiveXtUser()) AS enablecreateusers,"
                 "       crmacct_id, crmacct_emp_id, crmacct_owner_username"
                 "  FROM usr"
                 "  LEFT OUTER JOIN crmacct ON (usr_username=crmacct_usr_username) "
                 "WHERE (usr_username=:usr_username);" );
    usrq.bindValue(":usr_username", _cUsername);
  }
  else if (_crmacctid > 0)
  {
    usrq.prepare("SELECT LOWER(crmacct_number) AS usr_username,"
                 "       crmacct_name          AS usr_propername,"
                 "       (SELECT locale_id"
                 "          FROM locale"
                 "         WHERE locale_code='Default') AS usr_locale_id,"
                 "       NULL  AS usr_passwd,  cntct_initials AS usr_initials,"
                 "       FALSE AS usr_agent,   crmacct_active AS usr_active,"
                 "       NULL  AS usr_window,  cntct_email AS usr_email,"
                 "       FALSE AS createusers,"
                 "       userCanCreateUsers(getEffectiveXtUser()) AS enablecreateusers,"
                 "       crmacct_id, crmacct_emp_id, crmacct_owner_username"
                 "  FROM crmacct"
                 "  LEFT OUTER JOIN cntct ON (crmacct_cntct_id_1=cntct_id)"
                 " WHERE (crmacct_id=:id);");
    usrq.bindValue(":id", _crmacctid);
  }

  usrq.exec();
  if (usrq.first())
  {
    if(omfgThis->useCloud() && usrq.value("usr_username").toString().endsWith("_"+omfgThis->company()))
      _username->setText(usrq.value("usr_username").toString().left(usrq.value("usr_username").toString().length() - (omfgThis->company().length()+1)));
    else
      _username->setText(usrq.value("usr_username"));
    _active->setChecked(usrq.value("usr_active").toBool());
    _properName->setText(usrq.value("usr_propername"));
    _initials->setText(usrq.value("usr_initials"));
    _email->setText(usrq.value("usr_email"));
    _locale->setId(usrq.value("usr_locale_id").toInt());
    _agent->setChecked(usrq.value("usr_agent").toBool());
    _createUsers->setChecked(usrq.value("createusers").toBool());
    _createUsers->setEnabled(usrq.value("enablecreateusers").toBool());
    _employee->setId(usrq.value("crmacct_emp_id").toInt());
    _crmacctid = usrq.value("crmacct_id").toInt();
    _crmowner = usrq.value("crmacct_owner_username").toString();

    _passwd->setText("        ");
    _verify->setText("        ");

    usrq.prepare( "SELECT usrpref_value "
               "  FROM usrpref "
               " WHERE ( (usrpref_name = 'DisableExportContents') "
               "   AND (usrpref_username=:username) ); ");
    usrq.bindValue(":username", _cUsername);
    usrq.exec();
    if(usrq.first())
      _exportContents->setChecked(usrq.value("usrpref_value").toString()=="t");
    else
      _exportContents->setChecked(FALSE);

    usrq.prepare( "SELECT usrpref_value "
               "  FROM usrpref "
               " WHERE ( (usrpref_name = 'UseEnhancedAuthentication') "
               "   AND (usrpref_username=:username) ); ");
    usrq.bindValue(":username", _cUsername);
    usrq.exec();
    _authCache = false;
    if(usrq.first())
      _authCache = (usrq.value("usrpref_value").toString()=="t");
    _enhancedAuth->setChecked(_authCache);

    usrq.prepare( "SELECT priv_module "
               "FROM usrpriv, priv "
               "WHERE ( (usrpriv_priv_id=priv_id)"
               " AND (usrpriv_username=:username) ) "
               "ORDER BY priv_module "
               "LIMIT 1;" );
    usrq.bindValue(":username", _cUsername);
    usrq.exec();
    if (usrq.first())
    {
      _module->setCode(usrq.value("priv_module").toString());
      sModuleSelected(_module->currentText());
    }
    else
    {
      _module->setCurrentIndex(0);
      sModuleSelected(_module->itemText(0));
    }
  }
  else if (ErrorReporter::error(QtCriticalMsg, this, tr("Getting User"),
                                usrq, __FILE__, __LINE__))
    return false;

  usrq.prepare( "SELECT usrpref_value "
             "  FROM usrpref "
             " WHERE ( (usrpref_name = 'selectedSites') "
             "   AND (usrpref_username=:username) "
             "   AND (usrpref_value='t') ); ");
  usrq.bindValue(":username", _cUsername);
  usrq.exec();
  if(usrq.first())
    _selectedSites->setChecked(TRUE);
  else if (ErrorReporter::error(QtCriticalMsg, this, tr("Getting User Sites"),
                                usrq, __FILE__, __LINE__))
    return false;

  if (_metrics->boolean("MultiWhs"))
    populateSite();

  _crmacct->setEnabled(_crmacctid > 0 &&
                       (_privileges->check("MaintainAllCRMAccounts") ||
                        _privileges->check("ViewAllCRMAccounts") ||
                        (omfgThis->username() == _crmowner && _privileges->check("MaintainPersonalCRMAccounts")) ||
                        (omfgThis->username() == _crmowner && _privileges->check("ViewPersonalCRMAccounts"))));


  return true;
}