Пример #1
0
void XDialog::done(int r)
{
  xtsettingsSetValue(objectName() + "/geometry/size", size());
  xtsettingsSetValue(objectName() + "/geometry/pos", pos());

  QDialog::done(r);
}
Пример #2
0
void login2::updateRecentOptions()
{
  //if (_cloudOption->isChecked())
  //  return;
  QStringList list = xtsettingsValue("/xTuple/_recentOptionsList").toStringList();
  _recent->setEnabled(list.size());
  list.removeAll(_databaseURL);
  list.prepend(_databaseURL);
      
  xtsettingsSetValue("/xTuple/_recentOptionsList", list);
  xtsettingsSetValue("/xTuple/_databaseURL", _databaseURL);
}
Пример #3
0
void login2::updateRecentOptions()
{
  if (_demoOption->isChecked())
    return;
    
  QStringList list = xtsettingsValue("/xTuple/_recentOptionsList").toStringList();
  list.removeAll(_databaseURL);
  list.prepend(_databaseURL);
      
  xtsettingsSetValue("/xTuple/_recentOptionsList", list);
  xtsettingsSetValue("/xTuple/_databaseURL", _databaseURL);
}
Пример #4
0
void login2Options::sSave()
{
    buildDatabaseURL(_databaseURL, "psql", _server->text(), _database->text(), _port->text());

    if (_saveSettings)
    {
        xtsettingsSetValue("/xTuple/_databaseURL", _databaseURL);
        xtsettingsSetValue("/xTuple/_enhancedAuthentication", (bool)_enhancedAuth->isChecked());
        xtsettingsSetValue("/xTuple/_requireSSL", (bool)_requireSSL->isChecked());
    }

    accept();
}
Пример #5
0
void XMainWindow::closeEvent(QCloseEvent *event)
{
  event->accept(); // we have no reason not to accept and let the script change it if needed
  _private->callCloseEvent(event);

  if(event->isAccepted())
  {
    QString objName = objectName();
    xtsettingsSetValue(objName + "/geometry/size", size());
    if(omfgThis->showTopLevel() || isModal())
      xtsettingsSetValue(objName + "/geometry/pos", pos());
    else if (parentWidget() != 0)
      xtsettingsSetValue(objName + "/geometry/pos", parentWidget()->pos());
  }
}
Пример #6
0
void printCheck::storeAchFileDir()
{
  if (_metrics->boolean("ACHEnabled") && !achFileDir.isEmpty())
  {
    xtsettingsSetValue("ACHOutputDirectory", achFileDir);
  }
}
Пример #7
0
void printCheck::storeEftFileDir()
{
  if (_metrics->boolean("ACHSupported") && _metrics->boolean("ACHEnabled") && !eftFileDir.isEmpty())
  {
    xtsettingsSetValue("ACHOutputDirectory", eftFileDir);
  }
}
Пример #8
0
void QMainWindowProto::saveState ( int version) const
{
  QMainWindow *item = qscriptvalue_cast<QMainWindow*>(thisObject());
  if (item)
  {
    QByteArray state = item->saveState(version);
    xtsettingsSetValue(item->objectName() + "/WindowState", state);
  }
}
Пример #9
0
void XMainWindow::closeEvent(QCloseEvent *event)
{
  event->accept(); // we have no reason not to accept and let the script change it if needed
  if(_private->_engine && (_private->_engine->globalObject().property("closeEvent").isFunction()))
  {
    QScriptValueList args;
    args << _private->_engine->toScriptValue((QEvent*)event);
    _private->_engine->globalObject().property("closeEvent").call(QScriptValue(), args);
  }

  if(event->isAccepted())
  {
    QString objName = objectName();
    xtsettingsSetValue(objName + "/geometry/size", size());
    if(omfgThis->showTopLevel() || isModal())
      xtsettingsSetValue(objName + "/geometry/pos", pos());
    else
      xtsettingsSetValue(objName + "/geometry/pos", parentWidget()->pos());
  }
}
Пример #10
0
void login2Options::sSave()
{
  buildDatabaseURL(_databaseURL, "psql", _server->text(), _database->text(), _port->text());
  
  if (_saveSettings)
  {
    xtsettingsSetValue("/xTuple/_databaseURL", _databaseURL);
  }

  accept();
}
Пример #11
0
XTreeView::~XTreeView()
{
  if(_x_preferences)
  {
    // window()->objectName() isn't available here, at least for scripted windows!
    QString settingsPrefix = _windowName + "/" + objectName();

    xtsettingsSetValue(settingsPrefix + "/isForgetful", _forgetful);
    QString savedString;
    if(!_forgetful)
    {
      savedString = "";
      for(int i = 0; i < header()->count(); i++)
      {
        int w = -1;
        ColumnProps *cp = _columnByName.value(columnNameFromLogicalIndex(i), 0);
        if (cp)
        {
          if (!cp->stretchy)
            w = cp->savedWidth;
          _columnByName.remove(cp->columnName);
          delete cp;
        }
        if (w >= 0 && ! header()->isSectionHidden(i))
          savedString.append(QString::number(i) + "," +
                             QString::number(header()->sectionSize(i)) + "|");
      }
      xtsettingsSetValue(settingsPrefix + "/columnWidths", savedString);
    }
    savedString = "";
    for(int i = 0; i < header()->count(); i++)
    {
      savedString.append(QString::number(i) + "," + (header()->isSectionHidden(i)?"off":"on") + "|");
    }
    if(!savedString.isEmpty())
      _x_preferences->set(settingsPrefix + "/columnsShown", savedString);
    else
      _x_preferences->remove(settingsPrefix + "/columnsShown");
  }
}
void dspSummarizedSales::sGroupByChanged()
{
  list()->clear();
  list()->setColumnCount(0);

  if (_cust->isChecked())
  {
    list()->addColumn(tr("Customer"),       _itemColumn,      Qt::AlignLeft,   true,  "cust_number"   );
    list()->addColumn(tr("Name"),           -1,               Qt::AlignLeft,   true,  "cust_name" );
  }
  if (_custtype->isChecked())
  {
    list()->addColumn(tr("Customer Type"),  _itemColumn,      Qt::AlignLeft,   true,  "custtype_code"   );
  }
  if (_salesrep->isChecked())
  {
    list()->addColumn(tr("Sales Rep."),     _itemColumn,      Qt::AlignLeft,   true,  "salesrep_number"   );
    list()->addColumn(tr("Name"),           -1,               Qt::AlignLeft,   true,  "salesrep_name" );
  }
  if (_shipzone->isChecked())
    list()->addColumn(tr("Zone"),        _itemColumn,     Qt::AlignLeft,   true,  "shipzone_name"   );
  if (_item->isChecked())
  {
    list()->addColumn(tr("Item"),           _itemColumn,      Qt::AlignLeft,   true,  "item_number"   );
    list()->addColumn(tr("Description"),    -1,               Qt::AlignLeft,   true,  "itemdescription"   );
  }
  if (_site->isChecked())
    list()->addColumn(tr("Site"),         _whsColumn,      Qt::AlignCenter, true,  "warehous_code" );

  list()->addColumn(tr("First Sale"),     _dateColumn,     Qt::AlignCenter, true,  "firstdate" );
  list()->addColumn(tr("Last Sale"),      _dateColumn,     Qt::AlignCenter, true,  "lastdate" );
  list()->addColumn(tr("Min. Price"),     _priceColumn,    Qt::AlignRight,  true,  "minprice"  );
  list()->addColumn(tr("Max. Price"),     _priceColumn,    Qt::AlignRight,  true,  "maxprice"  );
  list()->addColumn(tr("Avg. Price"),     _priceColumn,    Qt::AlignRight,  true,  "avgprice"  );
  list()->addColumn(tr("Wt. Avg. Price"), _priceColumn,    Qt::AlignRight,  true,  "wtavgprice"  );
  list()->addColumn(tr("Total Units"),    _qtyColumn,      Qt::AlignRight,  true,  "totalunits"  );
  list()->addColumn(tr("Total Sales"),    _bigMoneyColumn, Qt::AlignRight,  true,  "totalsales"  );
  if (!omfgThis->singleCurrency())
    list()->addColumn(tr("Currency"),       _currencyColumn,  Qt::AlignLeft,  true,  "currAbbr"  );

  xtsettingsSetValue("dspSummarizedSales/units", _units->id());
}
Пример #13
0
QVariant xtsettingsValue(const QString & key, const QVariant & defaultValue)
{
  QSettings settings(QSettings::UserScope, "xTuple.com", "xTuple");
  QString key2 = key;
  if(key.startsWith("/xTuple/"))
    key2 = key2.replace(0, 8, QString("/OpenMFG/"));
  if(settings.contains(key))
    return settings.value(key, defaultValue);
  else
  {
    QSettings oldsettings(QSettings::UserScope, "OpenMFG.com", "OpenMFG");
    if(oldsettings.contains(key2))
    {
      QVariant val = oldsettings.value(key2, defaultValue);
      xtsettingsSetValue(key, val);
      return val;
    }
  }
  return defaultValue;
}
Пример #14
0
void registration::sDone(bool perror)
{
  disconnect(_postreq,      SIGNAL(done(bool)),     this, SLOT(sDone(bool)));

  QString result = QString(_postreq->readAll());

  if (perror)
  {
    if (QMessageBox::question(this, tr("Problem Registering"),
                              tr("<p>There was a problem sending your "
                                 "registration information to xTuple. Would "
                                 "you like to try again?<p>If you answer No "
                                 "and want to register later, you will have to"
                                 " re-enter all of the data again."),
                              QMessageBox::Yes | QMessageBox::Default,
                              QMessageBox::No) == QMessageBox::Yes)
    {
      sRegister(true);
      return;
    }
    else
    {
      reject();
      return;
    }
  }

  _progress->setValue(100);
  _progressLit->setText(tr("Done!"));
  // TODO: check if the registration failed and handle it here
  _metrics->set("Registered", QString("Yes"));
  xtsettingsSetValue("/xTuple/Registered", QString("Yes"));
  QMessageBox::information(this, tr("Thanks for registering!"),
                           tr("<p>The registration server responded with:<p>%1")
                           .arg(result));
  accept();
}
Пример #15
0
void login2::clearRecentOptions()
{
    QStringList list;
    xtsettingsSetValue("/xTuple/_recentOptionsList", list);
    updateRecentOptionsActions();
}
Пример #16
0
void printOptions::sSave()
{
  xtsettingsSetValue(QString("%1.autoPrint").arg(_parentName), (bool)_autoPrint->isChecked());
  xtsettingsSetValue(QString("%1.defaultPrinter").arg(_parentName), _printers->currentText());
  accept();
}
Пример #17
0
void login2::sLogin()
{
  QSqlDatabase db;

  QString databaseURL;
  databaseURL = _databaseURL;
  if (_demoOption->isChecked())
    databaseURL = _evalDatabaseURL.arg(_username->text().trimmed());

  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);

  if (_splash)
  {
    _splash->show();
    _splash->raise();
    _splash->showMessage(tr("Initializing the Database Connector"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }

  // Open the Database Driver
  if (_multipleConnections)
    db = QSqlDatabase::addDatabase("QPSQL7", dbName);
  else
    db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr("<p>A connection could not be established with "
                             "the specified Database as the Proper Database "
                             "Drivers have not been installed. Contact your "
                             "Systems Administator."));
    
    return;
  }

  if(hostName.isEmpty() || dbName.isEmpty())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning(this, tr("Incomplete Connection Options"),
                         tr("<p>One or more connection options are missing. "
                            "Please check that you have specified the host "
                            "name, database name, and any other required "
                            "options.") );

    return;
  }

  db.setDatabaseName(dbName);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  _cUsername = _username->text().trimmed();
  _cPassword = _password->text().trimmed();

  db.setUserName(_cUsername);
  if(_demoOption->isChecked())
  {
    QString passwd = QMd5(QString(_cPassword + "private" + _cUsername)); 
    db.setPassword(passwd);
  }
  else
  {
    if(_enhancedAuth)
    {
      QString passwd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      db.setPassword(passwd);
    }
    else
      db.setPassword(_cPassword);

    if(_requireSSL)
      db.setConnectOptions("requiressl=1");
  }

  setCursor(QCursor(Qt::WaitCursor));

  if (_splash)
  {
    _splash->showMessage(tr("Connecting to the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  //  Try to connect to the Database
  bool result = db.open();
  if(!result && _enhancedAuth)
  {
    QString altpasswd = QMd5(QString(_cPassword + "OpenMFG" + _cUsername));
    db.setPassword(altpasswd);
    result = db.open();
    if(result)
    {
      altpasswd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      XSqlQuery chgpass(QString("ALTER USER %1 WITH PASSWORD '%2'").arg(_cUsername).arg(altpasswd));
    }
  }

  if (!result)
  {
    if(_requireSSL)
      db.setConnectOptions();

    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::ArrowCursor));

    QMessageBox::critical(this, tr("Cannot Connect to xTuple ERP Server"),
                          tr("<p>A connection to the specified xTuple ERP "
                             "Server cannot be made.  This may be due to an "
                             "incorrect Username and/or Password or the "
                             "server in question cannot support any more "
                             "connections.<p>Please verify your Username and "
                             "Password and try again or wait until the "
                             "specified xTuple ERP Server is less busy.<br>"
                             "System Error<pre>%1" )
                            .arg(db.lastError().driverText() ));
    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  xtsettingsSetValue("/xTuple/_demoOption", (bool)_demoOption->isChecked());

  if (_splash)
  {
    _splash->showMessage(tr("Logging into the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  if(!_nonxTupleDB)
  {
    XSqlQuery login( "SELECT login() AS result,"
                     "       CURRENT_USER AS user;" );
    setCursor(QCursor(Qt::ArrowCursor));
    if (login.first())
    {
      int result = login.value("result").toInt();
      if (result < 0)
      {
        if (_splash)
          _splash->hide();
        QMessageBox::critical(this, tr("Error Logging In"),
                              storedProcErrorLookup("login", result));
        return;
      }
      _user = login.value("user").toString();
      _databaseURL = databaseURL;
      updateRecentOptions();
      accept();
    }
    else if (login.lastError().type() != QSqlError::NoError)
    {
      if (_splash)
        _splash->hide();
      QMessageBox::critical(this, tr("System Error"),
                            tr("A System Error occurred at %1::%2:\n%1")
                              .arg(__FILE__).arg(__LINE__)
                              .arg(login.lastError().databaseText()));
    }
    else
    {
      if (_splash)
        _splash->hide();
      
      QMessageBox::critical(this, tr("System Error"),
                            tr("<p>An unknown error occurred at %1::%2. You may"
                               " not log in to the specified xTuple ERP Server "
                               "at this time.")
                              .arg(__FILE__).arg(__LINE__));
    }
  }
  else
  {
    setCursor(QCursor(Qt::ArrowCursor));
    _databaseURL = databaseURL;
    updateRecentOptions();
    accept();
  }
}
Пример #18
0
int main(int argc, char *argv[])
{
  XSqlQuery main;
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  QString passwd;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    haveEnhancedAuth= false;
  bool    _enhancedAuth   = false;
  bool    havePasswd      = false;
  bool    forceWelcomeStub= false;

  qInstallMsgHandler(xTupleMessageOutput);
  QApplication app(argc, argv);
  app.setOrganizationDomain("xTuple.com");
  app.setOrganizationName("xTuple");
  app.setApplicationName("xTuple");
  app.setApplicationVersion(_Version);

#if QT_VERSION >= 0x040400
  // This is the correct place for this call but on versions less
  // than 4.4 it causes a crash for an unknown reason so it is
  // called later on earlier versions.
  QCoreApplication::addLibraryPath(QString("."));
#endif

#ifndef Q_WS_MACX
  QApplication::setWindowIcon(QIcon(":/images/icon32x32.png"));
#endif

  app.processEvents();

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

      if (argument.contains("-databaseURL=", Qt::CaseInsensitive))
      {
        haveDatabaseURL = TRUE;
        databaseURL = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth", Qt::CaseInsensitive))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 
      else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive))
      {
        haveEnhancedAuth = true;
        _enhancedAuth = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          _enhancedAuth = false;
      }
      else if (argument.contains("-forceWelcomeStub", Qt::CaseInsensitive))
        forceWelcomeStub = true;
    }
  }

  // Try and load a default translation file and install it
  // otherwise if we are non-english inform the user that translation are available
  bool checkLanguage = false;
  QLocale sysl = QLocale::system();
  QTranslator defaultTranslator(&app);
  if (defaultTranslator.load(translationFile(sysl.name().toLower(), "default")))
    app.installTranslator(&defaultTranslator);
  else if(!xtsettingsValue("LanguageCheckIgnore", false).toBool() && sysl.language() != QLocale::C && sysl.language() != QLocale::English)
    checkLanguage = translationFile(sysl.name().toLower(), "xTuple").isNull();
  if (forceWelcomeStub || checkLanguage)
  {
    QTranslator * translator = new QTranslator(&app);
    if (translator->load(translationFile(sysl.name().toLower(), "welcome/wmsg")))
      app.installTranslator(translator);

    welcomeStub wsdlg;
    wsdlg.checkBox->setChecked(xtsettingsValue("LanguageCheckIgnore", false).toBool());
    wsdlg.exec();
    xtsettingsSetValue("LanguageCheckIgnore", wsdlg.checkBox->isChecked());
  }

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

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
    params.append("copyright", _Copyright);
    params.append("version",   _Version);
    params.append("build",     _Build.arg(__DATE__).arg(__TIME__));
    params.append("setSearchPath", true);

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

    if (havePasswd)
      params.append("password", passwd);

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

    if (haveEnhancedAuth)
      params.append("enhancedAuth", _enhancedAuth);
    
    if (_evaluation)
      params.append("evaluation");

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
      params.append("login");

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

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

  // TODO: can/should we compose the splash screen on the fly from parts?
  QList<editionDesc> edition;
  edition << editionDesc( "Enterprise",     ":/images/splashEnterprise.png",        true,
               "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 4"
               " FROM pkghead"
               " WHERE pkghead_name IN ('xtmfg', 'xtprjaccnt', 'asset', 'assetdepn');" )
          << editionDesc( "Manufacturing",  ":/images/splashMfgEdition.png",        true,
               "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 1"
               " FROM pkghead"
               " WHERE pkghead_name IN ('xtmfg');" )
          << editionDesc( "Distribution",       ":/images/splashDistEdition.png",        true,
               "SELECT fetchMetricText('Application') = 'Standard';" )
          << editionDesc( "PostBooks",      ":/images/splashPostBooks.png",        true,
               "SELECT fetchMetricText('Application') = 'PostBooks';" )
  ;

  XSqlQuery metric;
  int editionIdx;       // we'll use this after the loop
  for (editionIdx = 0; editionIdx < edition.size(); editionIdx++)
  {
    metric.exec(edition[editionIdx].queryString);
    if (metric.first() && metric.value(0).toBool())
      break;
  }
  if (editionIdx >= edition.size())
    editionIdx = edition.size(); // default to PostBooks

  _splash->setPixmap(QPixmap(edition[editionIdx].splashResource));
  _Name = _Name.arg(edition[editionIdx].editionName);

  if (edition[editionIdx].shouldCheckLicense)
  {
    _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
	
	// PostgreSQL changed the column "procpid" to just "pid" in 9.2.0+ Incident #21852
	XSqlQuery checkVersion(QString("select compareversion('9.2.0');"));

    if(checkVersion.first())
    {
      if(checkVersion.value("compareversion").toInt() > 0)
      {
	   metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total"
			"  FROM pg_stat_activity, pg_locks"
			" WHERE((database=datid)"
			"   AND (classid=datid)"
			"   AND (objsubid=2)"
			"   AND (procpid = pg_backend_pid()));");
      }
	  else
	  {
	   metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total"
			"  FROM pg_stat_activity, pg_locks"
			" WHERE((database=datid)"
			"   AND (classid=datid)"
			"   AND (objsubid=2)"
			"   AND (pg_stat_activity.pid = pg_backend_pid()));");
      }
    }
	
    int cnt = 50000;
    int tot = 50000;
    if(metric.first())
    {
      cnt = metric.value("registered").toInt();
      tot = metric.value("total").toInt();
    }
    metric.exec("SELECT packageIsEnabled('drupaluserinfo') AS result;");
    bool xtweb = false;
    if(metric.first())
      xtweb = metric.value("result").toBool();
    metric.exec("SELECT fetchMetricBool('ForceLicenseLimit') as metric_value;");
    bool forceLimit = false;
    bool forced = false;
    if(metric.first())
      forceLimit = metric.value("metric_value").toBool();
    metric.exec("SELECT metric_value"
                "  FROM metric"
                " WHERE(metric_name = 'RegistrationKey');");
    bool checkPass = true;
    bool checkLock = false;
    bool expired   = false;
    QString checkPassReason;
    QString rkey = "";
    if(metric.first())
      rkey = metric.value("metric_value").toString();
    XTupleProductKey pkey(rkey);
    QString application;
    metric.exec("SELECT fetchMetricText('Application') as app;");
     if(metric.first())
     {
         application = metric.value("app").toString();
     }
    if(pkey.valid() && (pkey.version() == 1 || pkey.version() == 2 || pkey.version() == 3))
    {
      if(pkey.expiration() < QDate::currentDate())
      {
        checkPass = false;
        checkPassReason = QObject::tr("<p>Your license has expired.");
        if(!pkey.perpetual())
        {
          int daysTo = pkey.expiration().daysTo(QDate::currentDate());
          if(daysTo > 30)
          {
            checkLock = true;
            expired = true;
            checkPassReason = QObject::tr("<p>Your xTuple license expired over 30 days ago, and this software will no longer function. Please contact xTuple immediately to reinstate your software.");
          }
          else
            checkPassReason = QObject::tr("<p>Attention:  Your xTuple license has expired, and in %1 days this software will cease to function.  Please make arrangements for immediate payment").arg(30 - daysTo);
        }
        else
          expired = true;
      }
      else if(application == "PostBooks" && pkey.users() == 1)
      {
        if(pkey.users() < cnt)
          {
          checkPass = false;
          checkPassReason = QObject::tr("<p>Multiple concurrent users of xTuple PostBooks require a license key. Please contact [email protected] to request a free license key for your local installation, or [email protected] to purchase additional users in the xTuple Cloud Service. <p>Thank you.");
          checkLock = forced = forceLimit;
          }
      }
      else if(pkey.users() != 0 && (pkey.users() < cnt || (!xtweb && (pkey.users() * 2 < tot))))
      {
        checkPass = false;
        checkPassReason = QObject::tr("<p>You have exceeded the number of allowed concurrent users for your license.");
        checkLock = forced = forceLimit;
      }
      else
      {
        int daysTo = QDate::currentDate().daysTo(pkey.expiration());
        if(!pkey.perpetual() && daysTo <= 15)
        {
          checkPass = false;
          checkPassReason = QObject::tr("<p>Please note: your xTuple license will expire in %1 days.  You should already have received your renewal invoice; please contact xTuple at your earliest convenience.").arg(daysTo);
        }
      }
    }
    else
    {
      checkPass = false;
      checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid.");
    }
    if(!checkPass)
    {
      _splash->hide();
      if (expired)
      {
        registrationKeyDialog newdlg(0, "", TRUE);
        if(newdlg.exec() == -1)
        {
          QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason);
          return 0;
        }
      }
      else if(checkLock)
      {
        QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason);
        if(!forced)
          return 0;
      }
      else
      {
        if(QMessageBox::critical(0, QObject::tr("Registration Key"), QObject::tr("%1\n<p>Would you like to continue anyway?").arg(checkPassReason), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
          return 0;
      }

      if(forced)
        checkPassReason.append(" FORCED!");

      metric.exec("SELECT current_database() AS db,"
                  "       fetchMetricText('DatabaseName') AS dbname,"
                  "       fetchMetricText('remitto_name') AS name;");
      QString db = "";
      QString dbname = "";
      QString name = "";
      if(metric.first())
      {
        db = metric.value("db").toString();
        dbname = metric.value("dbname").toString();
        name = metric.value("name").toString();
      }

      QHttp *http = new QHttp();
      
      QUrl url;
      url.setPath("/api/regviolation.php");
      url.addQueryItem("key", QUrl::toPercentEncoding(rkey));
      url.addQueryItem("error", QUrl::toPercentEncoding(checkPassReason));
      url.addQueryItem("name", QUrl::toPercentEncoding(name));
      url.addQueryItem("dbname", QUrl::toPercentEncoding(dbname));
      url.addQueryItem("db", QUrl::toPercentEncoding(db));
      url.addQueryItem("cnt", QString::number(cnt));
      url.addQueryItem("tot", QString::number(tot));
      url.addQueryItem("ver", _Version);

      http->setHost("www.xtuple.org");
      http->get(url.toString());

      if(forced)
        return 0;

      _splash->show();
    }
  }

  bool disallowMismatch = false;
  bool shouldCheckForUpdates = false;
  metric.exec("SELECT metric_value"
              " FROM metric"
              " WHERE (metric_name = 'ServerVersion')");
  if (!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) {

    int result = 0;

    metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'DisallowMismatchClientVersion')");
    if (metric.first() && (metric.value("metric_value").toString() == "t")) {
      disallowMismatch = true;
    }

    metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'CheckForUpdates')");
    if (metric.first()) {
		 shouldCheckForUpdates = (metric.value("metric_value").toString() == "t" ? true : false);
	 }

	if (shouldCheckForUpdates) {

      _splash->hide();

      checkForUpdates newdlg(0,"", TRUE);

      result = newdlg.exec();
      if (result == QDialog::Rejected) {
          return 0;
	  }
    }
    else if (!shouldCheckForUpdates && disallowMismatch) {
      _splash->hide();
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
      QObject::tr("<p>The version of the database you are connecting to is "
                  "not the version this client was designed to work against. "
                  "This client was designed to work against the database "
                  "version %1. The system has been configured to disallow "
                  "access in this case.<p>Please contact your systems "
                  "administrator.").arg(_Version),
                  QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default );
      return 0;
    }
    else {
     _splash->hide();
     result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
     QObject::tr("<p>The version of the database you are connecting to is "
                 "not the version this client was designed to work against. "
                 "This client was designed to work against the database "
                 "version %1. If you continue some or all functionality may "
                 "not work properly or at all. You may also cause other "
                 "problems on the database.<p>Do you want to continue "
                 "anyway?").arg(_Version), QMessageBox::Yes,
                 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
      if (result != QMessageBox::Yes) {
        return 0;
      }
      else {
        _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
  _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=getEffectiveXtUser())"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    QString langext;
    if (!langq.value("lang_abbr2").toString().isEmpty() && 
        !langq.value("country_abbr").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString() + "_" +
                langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString();
    }

    if(!langext.isEmpty())
    {
      files << "qt";
      files << "xTuple";
      files << "openrpt";
      files << "reports";

      XSqlQuery pkglist("SELECT pkghead_name"
                        "  FROM pkghead"
                        " WHERE packageIsEnabled(pkghead_name);");
      while(pkglist.next())
        files << pkglist.value("pkghead_name").toString();
    }

    if (files.size() > 0)
    {
      QStringList notfound;
      QTranslator *translator = new QTranslator(&app);
      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        if (DEBUG)
          qDebug("looking for %s", (*fit).toAscii().data());
        if (translator->load(translationFile(langext, *fit)))
        {
          app.installTranslator(translator);
          qDebug("installed %s", (*fit).toAscii().data());
          translator = new QTranslator(&app);
        }
        else
        {
          notfound << *fit;
        }
      }

      if (! notfound.isEmpty() &&
          !_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(notfound.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::NoError)
  {
    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;
  
#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 = "xTuple.key";
    keytogether = keypath + keyname;
    QFile kn(keytogether);
    if(!kn.exists())
      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.trimmed();
    }
  }

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

  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->username(), omfgThis->workspace());

// START code for updating the locale settings if they haven't been already
  XSqlQuery lc;
  lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';");
  lc.first();
  if(lc.value(0).toInt() == 0)
  {
    lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');");
    lc.exec("SELECT locale_id from locale;");
    while(lc.next())
    {
      ParameterList params;
      params.append("mode","edit");
      params.append("locale_id", lc.value(0));
      sysLocale lcdlg;
      lcdlg.set(params);
      lcdlg.sSave();
    }
  }
// END code for updating locale settings

  QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows()));
  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->setAttribute(Qt::WA_DeleteOnClose);
    omfgThis->show();
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    ScriptToolbox sb(0);
    QWidget* newdlg = sb.openWindow("woTimeClock");
    if(newdlg)
    {
      XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg);
      if(mw)
      {
        ParameterList params;
        params.append("captive");
        mw->set(params);
      }
      newdlg->setAttribute(Qt::WA_DeleteOnClose);
      QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
      newdlg->show();
    }
    else
    {
Пример #19
0
void login2::sLogin()
{
  QSqlDatabase db;

  QString databaseURL;
  databaseURL = _databaseURL;
  if (_demoOption->isChecked())
    databaseURL = _evalDatabaseURL.arg(_username->text().trimmed());
  else if(_cloudOption->isChecked())
    databaseURL = _cloudDatabaseURL.arg(_company->text().trimmed());

  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);

  if (_splash)
  {
    _splash->show();
    _splash->raise();
    _splash->showMessage(tr("Initializing the Database Connector"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }

  // Open the Database Driver
  if (_multipleConnections)
    db = QSqlDatabase::addDatabase("QPSQL7", dbName);
  else
    db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr("<p>A connection could not be established with "
                             "the specified Database as the Proper Database "
                             "Drivers have not been installed. Contact your "
                             "Systems Administator."));
    
    return;
  }

  if(hostName.isEmpty() || dbName.isEmpty())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning(this, tr("Incomplete Connection Options"),
                         tr("<p>One or more connection options are missing. "
                            "Please check that you have specified the host "
                            "name, database name, and any other required "
                            "options.") );

    return;
  }

  db.setDatabaseName(dbName);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  _cUsername = _username->text().trimmed();
  _cPassword = _password->text().trimmed();
  _cCompany  = _company->text().trimmed();
  if(_cloudOption->isChecked())
  {
    if(_cCompany.isEmpty())
    {
      QMessageBox::warning(this, tr("Incomplete Connection Options"),
        tr("<p>You must specify the Company name to connect to the cloud."));
      return;
    }
    _cUsername = _cUsername + "_" + _cCompany;
  }

  db.setUserName(_cUsername);
  if(_demoOption->isChecked())
  {
    QString passwd = QMd5(QString(_cPassword + "private" + _cUsername)); 
    db.setPassword(passwd);
  }
  else if(_cloudOption->isChecked())
  {
    QString passwd = QMd5(QString(_cPassword + "cloudkey" + _cUsername)); 
    db.setPassword(passwd);
  }
  else
  {
    if(_enhancedAuth)
    {
      QString passwd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      db.setPassword(passwd);
    }
    else
      db.setPassword(_cPassword);

    if(_requireSSL)
      db.setConnectOptions("requiressl=1");
  }

  setCursor(QCursor(Qt::WaitCursor));

  if (_splash)
  {
    _splash->showMessage(tr("Connecting to the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  //  Try to connect to the Database
  bool result = db.open();
  if(!result && _enhancedAuth)
  {
    QString altpasswd = QMd5(QString(_cPassword + "OpenMFG" + _cUsername));
    db.setPassword(altpasswd);
    result = db.open();
    if(result)
    {
      altpasswd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      XSqlQuery chgpass(QString("ALTER USER %1 WITH PASSWORD '%2'").arg(_cUsername).arg(altpasswd));
    }
  }

  if (!result)
  {
    if(_requireSSL)
      db.setConnectOptions();

    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::ArrowCursor));

    QMessageBox::critical(this, tr("Cannot Connect to xTuple ERP Server"),
                          tr("<p>Sorry, can't connect to the specified xTuple ERP server. "
                             "<p>This may be due to a problem with your user name, password, or server connection information. "
                             "<p>Below is more detail on the connection problem: "
                             "<p>%1" )
                            .arg(db.lastError().databaseText().replace('\n', "<br>") ));
    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  xtsettingsSetValue("/xTuple/_demoOption", (bool)_demoOption->isChecked());
  xtsettingsSetValue("/xTuple/_cloudOption", (bool)_cloudOption->isChecked());
  xtsettingsSetValue("/xTuple/cloud_company", _company->text());

  if (_splash)
  {
    _splash->showMessage(tr("Logging into the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  if(!_nonxTupleDB)
  {
    XSqlQuery login( "SELECT login() AS result,"
                     "       CURRENT_USER AS user;" );
    setCursor(QCursor(Qt::ArrowCursor));
    if (login.first())
    {
      int result = login.value("result").toInt();
      if (result < 0)
      {
        if (_splash)
          _splash->hide();
        QMessageBox::critical(this, tr("Error Logging In"),
                              storedProcErrorLookup("login", result));
        return;
      }
      _user = login.value("user").toString();
      _databaseURL = databaseURL;
      updateRecentOptions();

      if (login.exec("SELECT getEffectiveXtUser() AS user;") &&
          login.first() &&
          ! login.value("user").toString().isEmpty())
        _user = login.value("user").toString();
      // no error check - older databases don't have getEffectiveXtUser

      accept();
    }
    else if (login.lastError().type() != QSqlError::NoError)
    {
      if (_splash)
        _splash->hide();
      QMessageBox::critical(this, tr("System Error"),
                            tr("A System Error occurred at %1::%2:\n%3")
                              .arg(__FILE__).arg(__LINE__)
                              .arg(login.lastError().databaseText()));
    }
    else
    {
      if (_splash)
        _splash->hide();
      
      QMessageBox::critical(this, tr("System Error"),
                            tr("<p>An unknown error occurred at %1::%2. You may"
                               " not log in to the specified xTuple ERP Server "
                               "at this time.")
                              .arg(__FILE__).arg(__LINE__));
    }
  }
  else
  {
    setCursor(QCursor(Qt::ArrowCursor));
    _databaseURL = databaseURL;
    updateRecentOptions();
    accept();
  }
}
Пример #20
0
void XDialog::saveSize()
{
  xtsettingsSetValue(objectName() + "/geometry/size", size());
  xtsettingsSetValue(objectName() + "/geometry/pos", pos());
}