Esempio n. 1
0
void transferOrderList::sFillList()
{
  QString sql;

  sql = "SELECT DISTINCT tohead_id, tohead_number, tohead_srcname, "
	"                tohead_destname,"
	"                tohead_orderdate,"
	"                MIN(toitem_schedshipdate) AS scheddate "
	"<? if exists(\"atshipping\") ?>"
	"FROM tohead, toitem, tosmisc, toship "
	"WHERE ((tohead_id=toitem_tohead_id)"
	"  AND  (toitem_status<>'X')"
	"  AND  (toitem_id=toship_toitem_id)"
	"  AND  (toship_tosmisc_id=tosmisc_id)"
	"  AND  (NOT tosmisc_shipped)"
	"<? else ?>"	// not restricted to atshipping
	"FROM tohead, toitem "
	"WHERE ((tohead_id=toitem_tohead_id)"
	"  AND  (toitem_status<>'X')"
	"  <? if exists(\"toitem_statuslist\") ?>"
	"  AND  (toitem_status IN (<? literal(\"toitem_statuslist\") ?>))"
	"  <? endif ?>"
	"<? endif ?>"
	"<? if exists(\"srcwarehous_id\") ?>"
	" AND (tohead_src_warehous_id=<? value(\"srcwarehous_id\") ?>)"
	"<? endif ?>"
	"<? if exists(\"dstwarehous_id\") ?>"
	" AND (tohead_dest_warehous_id=<? value(\"dstwarehous_id\") ?>)"
	"<? endif ?>"
	") "
	"GROUP BY tohead_id, tohead_number, tohead_srcname,"
	"         tohead_destname, tohead_orderdate "
	"ORDER BY tohead_number;";

  ParameterList params;
  if (_type == cToAtShipping)
    params.append("atshipping");
  else
  {
    QString toitem_statuslist;

    bool statusCheck = FALSE;
    if (_type & cToOpen)
    {
      toitem_statuslist += "'O'";
      statusCheck = TRUE;
    }

    if (_type & cToClosed)
    {
      if (statusCheck)
        toitem_statuslist += ", ";
      toitem_statuslist += "'C'";
      statusCheck = TRUE;
    }

    if (statusCheck)
      params.append("toitem_statuslist", toitem_statuslist);
  }

  if (_srcwhs->isSelected())
    params.append("srcwarehous_id", _srcwhs->id());
  if (_dstwhs->isSelected())
    params.append("dstwarehous_id", _dstwhs->id());

  MetaSQLQuery mql(sql);
  XSqlQuery q = mql.toQuery(params);
  _to->populate(q, _toheadid);
}
Esempio n. 2
0
// -------------------------------------------------------------------------
int main(int argc, char ** argv)
{
  int logLevel = 5;
  Logger::setDefaultLogger(Logger::getLogger(logLevel));

  string initialStageString("");
  string finalStageString("");
  string statusFileName("status.txt");

  bool resumeFlag = false;
  bool gridExecutionFlag = false;
  bool runGenoMSFlag = false;
  bool runMergedFlag = false;

  bool showHelp = false;
  for (size_t i = 0; i < argc; i++)
  {
    string arg(argv[i]);
    if (arg.compare("--help") == 0)
    {
      showHelp = true;
    }
  }

  if (argc < 2 || showHelp)
  {
    if (showHelp)
    {
      cout << "Usage: main_flr [PARAM FILE] [OPTION]..." << endl << endl;
      cout << "Optional arguments are listed below " << endl;
      cout << "  -i  <intialstage>   begin processing at specified stage:"
          << endl;
      cout << "                         begin,pairspectra,lpsolver,flr" << endl;
      cout
          << "  -f  <finalstage>   end processing after completing specified stage:"
          << endl;
      cout << "                        lpsolver,flr" << endl;

      cout << "  -g                  execution is on a grid" << endl;
      cout << "  -lf <filename>      name of log file for output" << endl;
      cout << "  -ll <loglevel>      log level for debug/warn/error output:"
          << endl;
      cout << "                         9 for errors only" << endl;
      cout << "                         5 for warnings and errors" << endl;
      cout << "                         0 for all debug output" << endl;
      cout << "  -s                   execute a single step then exit" << endl;
    }
    else
    {
      cerr << "main_specnets: insufficient arguments" << endl;
      cerr << "Try \'main_specnets --help\' for more information." << endl
          << endl;
    }

    cout << PROGRAM_NAME << endl;
    cout << "main_specnets 3.0." << XSTR(SPS_VERSION) << endl;
    cout << endl;

    cout << COPYRIGHT1 << endl;
    cout << COPYRIGHT2 << endl;
    cout << endl;

    return -1;
  }
  // Parse the command line parameters
  vector<CommandLineParser::Option> listOptions;
  listOptions.push_back(CommandLineParser::Option("i", "INITIAL_STAGE", 1));
  listOptions.push_back(CommandLineParser::Option("f", "FINAL_STAGE", 1));
  listOptions.push_back(CommandLineParser::Option("g", "GRID_EXECUTION", 0));
  listOptions.push_back(CommandLineParser::Option("lf", "LOG_FILE_NAME", 1));
  listOptions.push_back(CommandLineParser::Option("ll", "LOG_LEVEL", 1));
  listOptions.push_back(CommandLineParser::Option("s", "SINGLE_STEP", 0));

  CommandLineParser clp(argc, argv, 1, listOptions);
  string parser_error;
  if (!clp.validate(parser_error))
  {
    ERROR_MSG(parser_error);
    return -2;
  }

  ParameterList commandLineParams;
  clp.getOptionsAsParameterList(commandLineParams);

  ParameterList ip;
  ip.readFromFile(argv[1]);
  ip.writeToFile("debug_sps.params");

  // Combine the command line parameters to the file ones
  //   Command line parameters take precedence (hence the overwrite flag set)
  ip.addList(commandLineParams, true);
  ip.writeToFile("debug_wcommand.params");

  logLevel = ip.getValueInt("LOG_LEVEL", 5);
  if (ip.exists("LOG_FILE_NAME"))
  {
    string logFileName = ip.getValue("LOG_FILE_NAME");
    Logger::setDefaultLogger(Logger::getLogger(logFileName, logLevel));
  }
  else
  {
    Logger::setDefaultLogger(Logger::getLogger(logLevel));
  }

  // add divert for segfault
  addSegFaultDivert();

  DEBUG_TRACE;

  if (!ip.exists("EXE_DIR"))
  {

    // extract EXE_DIR from command line
    string exeDir(argv[0]);

    // find last /, and remove from that point on
    size_t found = exeDir.find_last_of("/\\");
    string aux = exeDir.substr(0, found);

    //string mainSpecnetsStr = "/main_specnets";
    //exeDir.erase(exeDir.length() - mainSpecnetsStr.length(), mainSpecnetsStr.length());

    // remove /ExecFramework, if it exists
    ip.setValue("EXE_DIR", aux);
  }

  if (ip.exists("INITIAL_STAGE"))
  {
    initialStageString = commandLineParams.getValue("INITIAL_STAGE");
  }
  DEBUG_VAR(initialStageString);

  if (ip.exists("FINAL_STAGE"))
  {
    finalStageString = commandLineParams.getValue("FINAL_STAGE");
  }
  DEBUG_VAR(finalStageString);

  addDefaultParameterValues(ip);
  ip.writeToFile("debug_default.params");

  if (ip.exists("EXE_DIR"))
  {
    string exeDir = ip.getValue("EXE_DIR");

    // if path begins with '~', exit program.
    if (exeDir[0] == '~')
    {
      cout
          << "EXE_DIR path begins with tilde (~). Paths beginning with tilde are not supported."
          << endl;
      exit(0);
    }

    // In case there is a "/" at the end of EXE_DIR.. remove it
    if (exeDir.length() > 2 && exeDir[exeDir.length() - 1] == '/')
    {
      exeDir = exeDir.substr(0, exeDir.length() - 1);
      ip.setValue("EXE_DIR", exeDir);
    }
  }

  if (ip.exists("GRID_EXE_DIR"))
  {
    // In case there is a "/" at the end of EXE_DIR.. remove it
    string gridExeDir = ip.getValue("GRID_EXE_DIR");
    if (gridExeDir.length() > 2 && gridExeDir[gridExeDir.length() - 1] == '/')
    {
      gridExeDir = gridExeDir.substr(0, gridExeDir.length() - 1);
      ip.setValue("GRID_EXE_DIR", gridExeDir);
    }
  }

  if (ip.exists("GRID_SGE_EXE_DIR"))
  {
    // In case there is a "/" at the end of GRID_SGE_EXE_DIR.. remove it
    string gridSgeExeDir = ip.getValue("GRID_SGE_EXE_DIR");
    if (gridSgeExeDir.length() > 2
        && gridSgeExeDir[gridSgeExeDir.length() - 1] == '/')
    {
      gridSgeExeDir = gridSgeExeDir.substr(0, gridSgeExeDir.length() - 1);
      ip.setValue("GRID_SGE_EXE_DIR", gridSgeExeDir);
    }
  }

  if (ip.exists("INITIAL_STAGE"))
  {
    initialStageString = ip.getValue("INITIAL_STAGE");
  }
  DEBUG_VAR(initialStageString);
  if (initialStageString.empty())
  {
    initialStageString = "begin";
  }
  DEBUG_VAR(initialStageString);

  if (ip.exists("FINAL_STAGE"))
  {
    finalStageString = ip.getValue("FINAL_STAGE");
  }
  DEBUG_VAR(finalStageString);
  if (finalStageString.empty())
  {
    finalStageString = "flr";
  }
  DEBUG_VAR(finalStageString);

  map<string, Stage> map_stage;
  map_stage["begin"] = STAGE_BEGIN;
  map_stage["pairspectra"] = STAGE_PAIRSPECTRA;
  map_stage["lpsolver"] = STAGE_LPSOLVER;
  map_stage["flr"] = STAGE_FLR;

  if (map_stage.find(initialStageString) == map_stage.end())
  {
    ERROR_MSG("Unknown starting stage [" << initialStageString << "]");
    return -1;
  }

  if (map_stage.find(finalStageString) == map_stage.end())
  {
    ERROR_MSG("Unknown final stage [" << finalStageString << "]");
    return -1;
  }

  //Start the status as "running" and write itout
  writeStatusFile(statusFileName, "Running");

  int initialStage = map_stage[initialStageString];
  DEBUG_VAR(initialStage);
  int finalStage = map_stage[finalStageString];
  DEBUG_VAR(finalStage);

  bool res;
  res = mkdir_if_not_exist("spectra");
  if (res)
  {
    DEBUG_MSG("Made directory \'spectra\'");
  }

  // get LD_LIBRARY_PATH from system
  char *curLibPath = getenv("LD_LIBRARY_PATH");

  // Build the needed library path
  string libPath;
  libPath = ip.getValue("EXE_DIR");
  // set LD_LIBRARY_PATH to EXE_DIR + /libs.
  libPath += "/libs";

  string fullLibPath;
  // check if LD_LIBRARY_PATH is already defined.
  if (curLibPath)
  {
    // if it is, check if it contains the path we want.
    fullLibPath = curLibPath;
    // if the library path IS NOT contained in the path variable, add it, and set the environment variable.
    if (fullLibPath.find(libPath) == string::npos)
    {
      fullLibPath += ':';
      fullLibPath += libPath;
      mysetenv("LD_LIBRARY_PATH", fullLibPath.c_str());
    }
  }
  else
  {
    // if LD_LIBRARY_PATH is not defined,, define it with what we want.
    mysetenv("LD_LIBRARY_PATH", libPath.c_str());
  }

  if (commandLineParams.exists("GRID_EXECUTION"))
  {
    gridExecutionFlag = true;
  }
  DEBUG_VAR(gridExecutionFlag);

  //---------------------------------
  // Load amino acid masses
  //---------------------------------
  AAJumps jumps(1); // Amino acid masses
  if (ip.exists("AMINO_ACID_MASSES"))
  {
    DEBUG_MSG("Loading amino acid masses from [" << ip.getValue("AMINO_ACID_MASSES") << "]");
    if (!jumps.loadJumps(ip.getValue("AMINO_ACID_MASSES").c_str(), true))
    {
      ERROR_MSG("Unable to load amino acid jumps");
      ERROR_MSG("Aborting!");
      exit(-1);
    }
  }
  else
  {
    DEBUG_MSG("No amino acid masses loaded. Using defaults");
  }

  string exeDir = ip.getValue("EXE_DIR");
  string convertCmd = exeDir + "/convert ";

  PeptideSpectrumMatchSet peptideResults;
  SpecSet filteredSpectra;

  if (initialStage == STAGE_BEGIN)
  {
    DEBUG_TRACE;

    //load results
    if (!loadPsmResults(ip, peptideResults))
    {
      return false;
    }

    if (!loadResultSpectrum(ip,
            ip.getValue("INPUT_SPECTRA_FILE_LIST").c_str(),
            peptideResults,
            filteredSpectra,
            ip.getValueBool("REINDEX_SCANS")))
    {
      return false;
    }

    if (commandLineParams.exists("SINGLE_STEP"))
    {
      DEBUG_MSG("Option -s given. Exiting after single step.");
      writeStatusFile(statusFileName, "Finished");
      exit(0);
    }
  }
  else
  {
    if (initialStage == STAGE_PAIRSPECTRA)
    {
      //load results
      if (!loadPsmResults(ip, peptideResults))
      {
        return false;
      }

      if (!loadSpecsMS(ip.getValue("EXE_DIR"), DEFAULT_INPUT_FILES_LIST, filteredSpectra))
      {
        ERROR_MSG("loadSpecsMS() exited in error. Exiting program");
        exit(0);
      }
      filteredSpectra.index();
      peptideResults.addSpectraByFilename(&filteredSpectra,false);
    }
  }

  DEBUG_VAR(peptideResults.size());
  DEBUG_VAR(filteredSpectra.size());

  if (finalStage == STAGE_BEGIN)
  {
    DEBUG_MSG("Option -f given. Exiting after step: " << finalStageString);
    writeStatusFile(statusFileName, "Finished");
    exit(0);
  }

  if (initialStage <= STAGE_PAIRSPECTRA)
  {
    DEBUG_TRACE;

    if (!performPairSpectra(ip,
            peptideResults,
            filteredSpectra,
            ip.getValueBool("GRID_EXECUTION")))
    {
      exit(0);
    }

    if (commandLineParams.exists("SINGLE_STEP"))
    {
      DEBUG_MSG("Option -s given. Exiting after single step.");
      writeStatusFile(statusFileName, "Finished");
      exit(0);
    }
  }

  if (finalStage == STAGE_PAIRSPECTRA)
  {
    DEBUG_MSG("Option -f given. Exiting after step: " << finalStageString);
    writeStatusFile(statusFileName, "Finished");
    exit(0);
  }

  if (initialStage <= STAGE_LPSOLVER)
  {
    DEBUG_TRACE;
    if (!performLpSolver(ip,
            ip.getValueBool("GRID_EXECUTION")))
    {
      exit(0);
    }

    if (commandLineParams.exists("SINGLE_STEP"))
    {
      DEBUG_MSG("Option -s given. Exiting after single step.");
      writeStatusFile(statusFileName, "Finished");
      exit(0);
    }
  }

  if (finalStage == STAGE_LPSOLVER)
  {
    DEBUG_MSG("Option -f given. Exiting after step: " << finalStageString);
    writeStatusFile(statusFileName, "Finished");
    exit(0);
  }

  if (initialStage <= STAGE_FLR)
  {
    DEBUG_TRACE;
    if (!performLpSolver(ip,
            ip.getValueBool("GRID_EXECUTION")))
    {
      exit(0);
    }

    if (commandLineParams.exists("SINGLE_STEP"))
    {
      DEBUG_MSG("Option -s given. Exiting after single step.");
      writeStatusFile(statusFileName, "Finished");
      exit(0);
    }
  }

  if (finalStage == STAGE_FLR)
  {
    DEBUG_MSG("Option -f given. Exiting after step: " << finalStageString);
    writeStatusFile(statusFileName, "Finished");
    exit(0);
  }

}
Esempio n. 3
0
void shipOrder::sHandleSo()
{
  _coitem->clear();
  _shipment->setEnabled(false);
  _shipment->removeOrderLimit();

  sHandleButtons();


  q.prepare( "SELECT cohead_holdtype, cust_name, cohead_shiptoname, "
             "       cohead_shiptoaddress1, cohead_curr_id, cohead_freight "
             "FROM cohead, cust "
             "WHERE ((cohead_cust_id=cust_id) "
             "  AND  (cohead_id=:sohead_id));" );
  q.bindValue(":sohead_id", _order->id());
  q.exec();
  if (q.first())
  {
    QString msg;
    if ( (q.value("cohead_holdtype").toString() == "C"))
      msg = storedProcErrorLookup("shipShipment", -12);
    else if (q.value("cohead_holdtype").toString() == "P")
      msg = storedProcErrorLookup("shipShipment", -13);
    else if (q.value("cohead_holdtype").toString() == "R")
      msg = storedProcErrorLookup("shipShipment", -14);
    else if (q.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(q.value("cohead_curr_id").toInt());
    _freight->setLocalValue(q.value("cohead_freight").toDouble());
    _billToName->setText(q.value("cust_name").toString());
    _shipToName->setText(q.value("cohead_shiptoname").toString());
    _shipToAddr1->setText(q.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);
    q = mql.toQuery(params);
    if (q.first())
    {
      if (_shipment->id() != q.value("shiphead_id").toInt())
        _shipment->setId(q.value("shiphead_id").toInt());

      if (q.next())
      {
        _shipment->setType("SO");
        _shipment->limitToOrder(_order->id());
        _shipment->setEnabled(true);
      }
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (_shipment->isValid())
    {
      params.clear();
      params.append("sohead_id", _order->id());
      MetaSQLQuery mql(sql);
      q = mql.toQuery(params);
      if (q.first())
      {
        _shipment->setId(q.value("shiphead_id").toInt());
        if (q.next())
        {
          _shipment->setType("SO");
          _shipment->limitToOrder(_order->id());
          _shipment->setEnabled(true);
        }
      }
      else if (q.lastError().type() != QSqlError::None)
      {
        systemError(this, q.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 (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Esempio n. 4
0
void incidentWorkbench::setParams(ParameterList & params)
{
  params.append("new",		tr("New"));
  params.append("feedback",	tr("Feedback"));
  params.append("confirmed",	tr("Confirmed"));
  params.append("assigned",	tr("Assigned"));
  params.append("resolved",	tr("Resolved"));
  params.append("closed",	tr("Closed"));

  _assignedTo->appendValue(params);

  if(_statusNew->isChecked())
    params.append("isnew");
  if(_statusFeedback->isChecked())
    params.append("isfeedback");
  if(_statusConfirmed->isChecked())
    params.append("isconfirmed");
  if(_statusAssigned->isChecked())
    params.append("isassigned");
  if(_statusResolved->isChecked())
    params.append("isresolved");
  if(_statusClosed->isChecked())
    params.append("isclosed");

  if(!_textPattern->text().trimmed().isEmpty())
    params.append("pattern", _textPattern->text().trimmed());

  _createdDates->appendValue(params);
}
Esempio n. 5
0
void addDefaultParameterValues(ParameterList &p)
{
  // Basic parameters
  p.addIfDoesntExist("TOLERANCE_PEAK", "0.45");
  p.addIfDoesntExist("MAX_MOD_COUNT", "2");
  p.addIfDoesntExist("NORMALIZE_SPECTRUM", "1");
  p.addIfDoesntExist("UNIQUE_MODIFIED_PEPTIDES", "0");
  p.addIfDoesntExist("REINDEX_SCANS", "0");
  p.addIfDoesntExist("NUM_GROUPING_THRESHOLDS",30);
  p.addIfDoesntExist("GROUPING_THRESHOLD_STEPS",.015);


  // Grid parameters

  p.addIfDoesntExist("GRID_TYPE", "sge");
  p.addIfDoesntExist("GRID_NUMNODES", "0");
  p.addIfDoesntExist("GRID_NUMCPUS", "4");
  p.addIfDoesntExist("GRID_SGE_EXE_DIR", "");
  p.addIfDoesntExist("GRID_PARAMS", "-l h_vmem=1G");

  string currDir = getCurrentDirectory();
  p.addIfDoesntExist("PROJECT_DIR", currDir);
  p.addIfDoesntExist("RELATIVE_DIR", "1");
}
Esempio n. 6
0
void arOpenItem::sTaxDetail()
{
    XSqlQuery ar;
    if (_aropenid == -1)
    {
        if (!_docDate->isValid() || !_dueDate->isValid())
        {
            QMessageBox::critical( this, tr("Cannot set tax amounts"),
                                   tr("You must enter document and due dates for this Receivable Memo before you may set tax amounts.") );
            _docDate->setFocus();
            return;
        }

        if (_amount->isZero())
        {
            QMessageBox::critical( this, tr("Cannot set tax amounts"),
                                   tr("You must enter an amount for this Receivable Memo before you may set tax amounts.") );
            _amount->setFocus();
            return;
        }

        ar.prepare("SELECT nextval('aropen_aropen_id_seq') AS result;");
        ar.exec();
        if (ar.first())
            _aropenid = ar.value("result").toInt();
        else if (ar.lastError().type() != QSqlError::NoError)
        {
            systemError(this, ar.lastError().databaseText(), __FILE__, __LINE__);
            return;
        }
        else
            return;

        ar.prepare("INSERT INTO aropen "
                   "( aropen_id, aropen_docdate, aropen_duedate, aropen_doctype, "
                   "  aropen_docnumber, aropen_curr_id, aropen_open, aropen_posted, aropen_amount ) "
                   "VALUES "
                   "( :aropen_id, :docDate, :dueDate, :docType, :docNumber, :currId, true, false, :amount ); ");
        ar.bindValue(":aropen_id",_aropenid);
        ar.bindValue(":docDate", _docDate->date());
        ar.bindValue(":dueDate", _dueDate->date());
        ar.bindValue(":amount", _amount->localValue());
        if (_docType->currentIndex())
            ar.bindValue(":docType", "D" );
        else
            ar.bindValue(":docType", "C" );
        ar.bindValue(":docNumber", _docNumber->text());
        ar.bindValue(":currId", _amount->id());
        ar.exec();
        if (ar.lastError().type() != QSqlError::NoError)
        {
            systemError(this, ar.lastError().databaseText(), __FILE__, __LINE__);
            reset();
            return;
        }
    }

    taxDetail newdlg(this, "", true);
    ParameterList params;

    params.append("curr_id", _tax->id());
    params.append("date",    _tax->effective());
    if (!_docType->currentIndex())
        params.append("sense",-1);
    if (_mode != cNew)
        params.append("readOnly");

    ar.exec("SELECT getadjustmenttaxtypeid() as taxtype;");
    if(ar.first())
        params.append("taxtype_id", ar.value("taxtype").toInt());

    params.append("order_type", "AR");
    params.append("order_id", _aropenid);
    params.append("display_type", "A");
    params.append("subtotal", _amount->localValue());
    params.append("adjustment");
    if (!_docType->currentIndex())
        params.append("sense",-1);
    if (newdlg.set(params) == NoError)
    {
        newdlg.exec();
        XSqlQuery taxq;
        taxq.prepare( "SELECT SUM(taxhist_tax) AS tax "
                      "FROM aropentax "
                      "WHERE (taxhist_parent_id=:aropen_id);" );
        taxq.bindValue(":aropen_id", _aropenid);
        taxq.exec();
        if (taxq.first())
        {
            if (!_docType->currentIndex())
                _tax->setLocalValue(taxq.value("tax").toDouble() * -1);
            else
                _tax->setLocalValue(taxq.value("tax").toDouble());
        }
        else if (taxq.lastError().type() != QSqlError::NoError)
        {
            systemError(this, taxq.lastError().databaseText(), __FILE__, __LINE__);
            return;
        }
    }
}
Esempio n. 7
0
Chordino::ParameterList
Chordino::getParameterDescriptors() const
{
    if (debug_on) cerr << "--> getParameterDescriptors" << endl;
    ParameterList list;

    ParameterDescriptor useNNLSParam;
    useNNLSParam.identifier = "useNNLS";
    useNNLSParam.name = "use approximate transcription (NNLS)";
    useNNLSParam.description = "Toggles approximate transcription (NNLS).";
    useNNLSParam.unit = "";
    useNNLSParam.minValue = 0.0;
    useNNLSParam.maxValue = 1.0;
    useNNLSParam.defaultValue = 1.0;
    useNNLSParam.isQuantized = true;
	useNNLSParam.quantizeStep = 1.0;
    list.push_back(useNNLSParam);

    ParameterDescriptor rollonParam;
    rollonParam.identifier = "rollon";
    rollonParam.name = "bass noise threshold";
    rollonParam.description = "Consider the cumulative energy spectrum (from low to high frequencies). All bins below the first bin whose cumulative energy exceeds the quantile [bass noise threshold] x [total energy] will be set to 0. A threshold value of 0 means that no bins will be changed.";
    rollonParam.unit = "%";
    rollonParam.minValue = 0;
    rollonParam.maxValue = 5;
    rollonParam.defaultValue = 0.0;
    rollonParam.isQuantized = true;
	rollonParam.quantizeStep = 0.5;
    list.push_back(rollonParam);

    ParameterDescriptor tuningmodeParam;
    tuningmodeParam.identifier = "tuningmode";
    tuningmodeParam.name = "tuning mode";
    tuningmodeParam.description = "Tuning can be performed locally or on the whole extraction segment. Local tuning is only advisable when the tuning is likely to change over the audio, for example in podcasts, or in a cappella singing.";
    tuningmodeParam.unit = "";
    tuningmodeParam.minValue = 0;
    tuningmodeParam.maxValue = 1;
    tuningmodeParam.defaultValue = 0.0;
    tuningmodeParam.isQuantized = true;
    tuningmodeParam.valueNames.push_back("global tuning");
    tuningmodeParam.valueNames.push_back("local tuning");
    tuningmodeParam.quantizeStep = 1.0;
    list.push_back(tuningmodeParam);

    ParameterDescriptor whiteningParam;
    whiteningParam.identifier = "whitening";
    whiteningParam.name = "spectral whitening";
    whiteningParam.description = "Spectral whitening: no whitening - 0; whitening - 1.";
    whiteningParam.unit = "";
    whiteningParam.isQuantized = true;
    whiteningParam.minValue = 0.0;
    whiteningParam.maxValue = 1.0;
    whiteningParam.defaultValue = 1.0;
    whiteningParam.isQuantized = false;
    list.push_back(whiteningParam);

    ParameterDescriptor spectralShapeParam;
    spectralShapeParam.identifier = "s";
    spectralShapeParam.name = "spectral shape";
    spectralShapeParam.description = "Determines how individual notes in the note dictionary look: higher values mean more dominant higher harmonics.";
    spectralShapeParam.unit = "";
    spectralShapeParam.minValue = 0.5;
    spectralShapeParam.maxValue = 0.9;
    spectralShapeParam.defaultValue = 0.7;
    spectralShapeParam.isQuantized = false;
    list.push_back(spectralShapeParam);

    ParameterDescriptor boostnParam;
    boostnParam.identifier = "boostn";
    boostnParam.name = "boost N";
    boostnParam.description = "Boost likelihood of the N (no chord) label.";
    boostnParam.unit = "";
    boostnParam.minValue = 0.0;
    boostnParam.maxValue = 1.0;
    boostnParam.defaultValue = 0.1;
    boostnParam.isQuantized = false;
    list.push_back(boostnParam);

    ParameterDescriptor usehartesyntaxParam;
    usehartesyntaxParam.identifier = "usehartesyntax";
    usehartesyntaxParam.name = "use Harte syntax";
    usehartesyntaxParam.description = "Use the chord syntax proposed by Harte";
    usehartesyntaxParam.unit = "";
    usehartesyntaxParam.minValue = 0.0;
    usehartesyntaxParam.maxValue = 1.0;
    usehartesyntaxParam.defaultValue = 0.0;
    usehartesyntaxParam.isQuantized = true;
	usehartesyntaxParam.quantizeStep = 1.0;
	usehartesyntaxParam.valueNames.push_back("no");
    usehartesyntaxParam.valueNames.push_back("yes");
    list.push_back(usehartesyntaxParam);

    return list;
}
Esempio n. 8
0
void ItemLineEdit::setItemNumber(const QString& pNumber)
{
  XSqlQuery item;
  bool      found = FALSE;

  _parsed = TRUE;

  if (pNumber == text())
    return;

  if (!pNumber.isEmpty())
  {
    if (_useValidationQuery)
    {
      item.prepare(_validationSql);
      item.bindValue(":item_number", pNumber);
      item.exec();
      if (item.first())
        found = TRUE;
    }
    else if (_useQuery)
    {
      item.prepare(_sql);
      item.exec();
      found = (item.findFirst("item_number", pNumber) != -1);
    }
    else if (pNumber != QString::Null())
    {
      QString pre( "SELECT DISTINCT item_id, item_number, item_descrip1, item_descrip2,"
                   "                uom_name, item_type, item_config, item_upccode");

      QStringList clauses;
      clauses = _extraClauses;
      clauses << "(item_number=:item_number OR item_upccode=:item_number)";

      item.prepare(buildItemLineEditQuery(pre, clauses, QString::null, _type));
      item.bindValue(":item_number", pNumber);
      item.exec();
      
      if (item.size() > 1)
      { 
        ParameterList params;
        params.append("search", pNumber);
        params.append("searchNumber");
        params.append("searchUpc");
        sSearch(params);
        return;
      }
      else
        found = item.first();
    }
  }
  if (found)
  {
    _itemNumber = pNumber;
    _uom        = item.value("uom_name").toString();
    _itemType   = item.value("item_type").toString();
    _configured = item.value("item_config").toBool();
    _id         = item.value("item_id").toInt();
    _upc        = item.value("item_upccode").toInt();
    _valid      = TRUE;

    setText(item.value("item_number").toString());

    emit aliasChanged("");
    emit typeChanged(_itemType);
    emit descrip1Changed(item.value("item_descrip1").toString());
    emit descrip2Changed(item.value("item_descrip2").toString());
    emit uomChanged(item.value("uom_name").toString());
    emit configured(item.value("item_config").toBool());
    emit upcChanged(item.value("item_upccode").toString());
    
    emit valid(TRUE);
  }
  else
  {
    _itemNumber = "";
    _uom        = "";
    _itemType   = "";
    _id         = -1;
    _valid      = FALSE;
    _upc        = "";

    setText("");

    emit aliasChanged("");
    emit typeChanged("");
    emit descrip1Changed("");
    emit descrip2Changed("");
    emit uomChanged("");
    emit configured(FALSE);
    emit upcChanged("");

    emit valid(FALSE);
  }
}
Esempio n. 9
0
void ItemLineEdit::sParse()
{
  if (!_parsed)
  {
    _parsed = TRUE;

    if (text().length() == 0)
    {
      setId(-1);
      return;
    }
    else if (_useValidationQuery)
    {
      XSqlQuery item;
      item.prepare("SELECT item_id FROM item WHERE (item_number = :searchString OR item_upccode = :searchString);");
      item.bindValue(":searchString", text().trimmed().toUpper());
      item.exec();
      if (item.first())
      {
        int itemid = item.value("item_id").toInt();
        item.prepare(_validationSql);
        item.bindValue(":item_id", itemid);
        item.exec();
        if (item.size() > 1)
        {
          ParameterList params;
          params.append("search", text().trimmed().toUpper());
          params.append("searchNumber");
          params.append("searchUpc");
          sSearch(params);
          return;
        }
        else if (item.first())
        {
          setId(itemid);
          return;
        }
      }
    }
    else if (_useQuery)
    {
      XSqlQuery item;
      item.prepare(_sql);
      item.exec();
      if (item.first())
      {
        do
        {
          if (item.value("item_number").toString().startsWith(text().trimmed().toUpper()))
          {
            setId(item.value("item_id").toInt());
            return;
          }
        }
        while (item.next());
      }
    }
    else
    {
      XSqlQuery item;

      QString pre( "SELECT DISTINCT item_id, item_number AS number, "
                   "(item_descrip1 || ' ' || item_descrip2) AS name, "
                   "item_upccode AS description " );

      QStringList clauses;
      clauses = _extraClauses;
      clauses << "(item_number ~* :searchString OR item_upccode ~* :searchString)";
      item.prepare(buildItemLineEditQuery(pre, clauses, QString::null, _type).replace(";"," ORDER BY item_number LIMIT 1;"));
      item.bindValue(":searchString", QString(text().trimmed().toUpper()).prepend("^"));
      item.exec();
      if (item.first())
      {
        setId(item.value("item_id").toInt());
        return;
      }
    }
    setId(-1);
  }
}
Esempio n. 10
0
void returnAuthorizationWorkbench::sProcess()
{
  if (!checkSitePrivs(_radue->id()))
    return;
  
  bool _post = ((_radue->altId() > 1) ||
		(_radue->altId() == 1 && _postmemos->isChecked())) ;

  q.prepare("SELECT createRaCreditMemo(:rahead_id,:post) AS result;");
  q.bindValue(":rahead_id",_radue->id());
  q.bindValue(":post",QVariant(_post));
  q.exec();
  if (q.first())
  {
    int cmheadid = q.value("result").toInt();
    if (cmheadid < 0)
    {
      systemError(this, storedProcErrorLookup("createRaCreditMemo", cmheadid), __FILE__, __LINE__);
      return;
    }
    q.prepare( "SELECT cmhead_number "
               "FROM cmhead "
               "WHERE (cmhead_id=:cmhead_id);" );
    q.bindValue(":cmhead_id", cmheadid);
    q.exec();
    if (q.first())
    {
      QMessageBox::information( this, tr("New Credit Memo Created"),
                                tr("<p>A new CreditMemo has been created and "
				                   "assigned #%1")
                                   .arg(q.value("cmhead_number").toString()));
	  if (_printmemo->isChecked())
	  {
		ParameterList params;
		params.append("cmhead_id", cmheadid);
		if (_post)
		  params.append("posted");

		printCreditMemo newdlg(this, "", TRUE);
		newdlg.set(params);
		newdlg.exec();
	  }
      if (_radue->altId() == 2)
      {
        ParameterList params;
        params.append("cmhead_id", cmheadid);

        returnAuthCheck newdlg(this, "", TRUE);
        newdlg.set(params);
        if (newdlg.exec() != XDialog::Rejected)
          sFillListDue();
      }
      else if (_radue->altId() == 3)
      {
	ParameterList ccp;
	ccp.append("cmhead_id", cmheadid);
	MetaSQLQuery ccm = mqlLoad(":/so/creditMemoCreditCard.mql");
	XSqlQuery ccq = ccm.toQuery(ccp);
	if (ccq.first())
	{
	  int ccpayid = ccq.value("ccpay_id").toInt();
	  CreditCardProcessor *cardproc = CreditCardProcessor::getProcessor();
	  if (! cardproc)
	    QMessageBox::critical(this, tr("Credit Card Processing Error"),
				  CreditCardProcessor::errorMsg());
	  else if (! cardproc->errorMsg().isEmpty())
	    QMessageBox::critical(this, tr("Credit Card Processing Warning"),
				 cardproc->errorMsg());
	  else
	  {
	    QString docnum = q.value("cmhead_number").toString();
	    QString refnum = ccq.value("cohead_number").toString();
	    int refid = -1;
	    int returnValue = cardproc->credit(ccq.value("ccard_id").toInt(),
					 -2,
					 ccq.value("total").toDouble(),
					 ccq.value("tax_in_cmcurr").toDouble(),
					 ccq.value("cmhead_tax_id").isNull(),
					 ccq.value("cmhead_freight").toDouble(),
					 0,
					 ccq.value("cmhead_curr_id").toInt(),
					 docnum, refnum, ccpayid,
					 QString(), refid);
	    if (returnValue < 0)
	      QMessageBox::critical(this, tr("Credit Card Processing Error"),
				    cardproc->errorMsg());
	    else if (returnValue > 0)
	      QMessageBox::warning(this, tr("Credit Card Processing Warning"),
				   cardproc->errorMsg());
	    else if (! cardproc->errorMsg().isEmpty())
	      QMessageBox::information(this, tr("Credit Card Processing Note"),
				   cardproc->errorMsg());
	  }
	  // requery regardless 'cause the new credit memo means nothing's "due"
	  sFillListDue();
	}
	else if (ccq.lastError().type() != QSqlError::None)
	{
	  systemError(this, ccq.lastError().databaseText(), __FILE__, __LINE__);
	  return;
	}
	else
	{
	  QMessageBox::critical(this, tr("Credit Card Processing Error"),
				tr("Could not find a Credit Card to use for "
				   "this Credit transaction."));
	  sFillListDue();
	  return;
	}
      }
      else
	sFillListDue();
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
void enterPoitemReceipt::populate()
{
  XSqlQuery enterpopulate;
  ParameterList params;

  if (_metrics->boolean("MultiWhs"))
    params.append("MultiWhs");
  if (_metrics->boolean("EnableReturnAuth"))
    params.append("EnableReturnAuth");

  // NOTE: this crashes if popm is defined and toQuery() is called outside the blocks
  if (_mode == cNew)
  {
    MetaSQLQuery popm = mqlLoad("itemReceipt", "populateNew");

    params.append("ordertype",    _ordertype);
    params.append("orderitem_id", _orderitemid);

    enterpopulate = popm.toQuery(params);
  }
  else if (_mode == cEdit)
  {
    MetaSQLQuery popm = mqlLoad("itemReceipt", "populateEdit");
    params.append("recv_id", _recvid);
    enterpopulate = popm.toQuery(params);
  }
  else
  {
    systemError(this, tr("<p>Incomplete Parameter List: "
			 "_orderitem_id=%1, _ordertype=%2, _mode=%3.")
                       .arg(_orderitemid)
                       .arg(_ordertype)
                       .arg(_mode) );
    return;
  }

  if (enterpopulate.first())
  {
    _orderNumber->setText(enterpopulate.value("order_number").toString());
    _lineNumber->setText(enterpopulate.value("orderitem_linenumber").toString());
    _vendorItemNumber->setText(enterpopulate.value("vend_item_number").toString());
    _vendorDescrip->setText(enterpopulate.value("vend_item_descrip").toString());
    _vendorUOM->setText(enterpopulate.value("vend_uom").toString());
    _invVendorUOMRatio->setDouble(enterpopulate.value("orderitem_qty_invuomratio").toDouble());
    _dueDate->setDate(enterpopulate.value("duedate").toDate());
    _ordered->setDouble(enterpopulate.value("orderitem_qty_ordered").toDouble());
    _received->setDouble(enterpopulate.value("qtyreceived").toDouble());
    _returned->setDouble(enterpopulate.value("qtyreturned").toDouble());
    _receivable = enterpopulate.value("receivable").toDouble();
    _notes->setText(enterpopulate.value("notes").toString());
    _receiptDate->setDate(enterpopulate.value("effective").toDate());
    _freight->setId(enterpopulate.value("curr_id").toInt());
    _freight->setLocalValue(enterpopulate.value("recv_freight").toDouble());

    if (_ordertype.isEmpty())
      _ordertype = enterpopulate.value("recv_order_type").toString();
    if (_ordertype == "PO")
      _orderType->setText(tr("P/O"));
    else if (_ordertype == "TO")
    {
      _returnedLit->setText(tr("Qty. Shipped:"));
      _orderType->setText(tr("T/O"));
    }
    else if (_ordertype == "RA")
      _orderType->setText(tr("R/A"));

    int itemsiteid = enterpopulate.value("itemsiteid").toInt();
    if (itemsiteid > 0)
      _item->setItemsiteid(itemsiteid);
    _item->setEnabled(false);

    _purchCost->setId(enterpopulate.value("recv_purchcost_curr_id").toInt());
    _purchCost->setLocalValue(enterpopulate.value("recv_purchcost").toDouble());
    _purchCost->setEnabled(enterpopulate.value("costmethod_average").toBool() && _metrics->boolean("AllowReceiptCostOverride"));

    _extendedCost->setId(enterpopulate.value("recv_purchcost_curr_id").toInt());

    if (enterpopulate.value("inventoryitem").toBool() && itemsiteid <= 0)
    {
      MetaSQLQuery ism = mqlLoad("itemReceipt", "sourceItemSite");
      XSqlQuery isq = ism.toQuery(params);
      if (isq.first())
      {
        itemsiteid = itemSite::createItemSite(this,
                      isq.value("itemsite_id").toInt(),
                      isq.value("warehous_id").toInt(),
                      true);
        if (itemsiteid < 0)
          return;
        _item->setItemsiteid(itemsiteid);
      }
      else if (isq.lastError().type() != QSqlError::NoError)
      {
        systemError(this, isq.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
    }
  }
  else if (enterpopulate.lastError().type() != QSqlError::NoError)
  {
    systemError(this, enterpopulate.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Esempio n. 12
0
void alarmMaint::set( const ParameterList & pParams )
{
  QVariant param;
  bool        valid;
  
  param = pParams.value("source", &valid);
  if (valid)
  {
    _source = (enum Alarms::AlarmSources)param.toInt();
    if ( (Alarms::_alarmMap[_source].ident == "TODO") || (Alarms::_alarmMap[_source].ident == "J") )
      _alarmDate->setEnabled(false);
  }
    
  param = pParams.value("source_id", &valid);
  if(valid)
    _sourceid = param.toInt();

  param = pParams.value("due_date", &valid);
  if(valid)
    _alarmDate->setDate(param.toDate());

  param = pParams.value("usrId1", &valid);
  if(valid)
    sGetUser(param.toInt());

  param = pParams.value("usrId2", &valid);
  if(valid)
    sGetUser(param.toInt());

  param = pParams.value("usrId3", &valid);
  if(valid)
    sGetUser(param.toInt());

  param = pParams.value("cntctId1", &valid);
  if(valid)
    sGetContact(param.toInt());

  param = pParams.value("cntctId2", &valid);
  if(valid)
    sGetContact(param.toInt());

  param = pParams.value("cntctId3", &valid);
  if(valid)
    sGetContact(param.toInt());

  param = pParams.value("mode", &valid);
  if(valid)
  {
    if(param.toString() == "new")
    {
      _mode = cNew;
    }
    else if(param.toString() == "edit")
      _mode = cEdit;
    else if(param.toString() == "view")
    {
      _mode = cView;
      _save->hide();
    }
  }

  param = pParams.value("alarm_id", &valid);
  if (valid)
  {
    _alarmid = param.toInt();
    sPopulate();
  }

}
Esempio n. 13
0
enum SetResponse selectBillingQty::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("soitem_id", &valid);
  if (valid)
  {
    _soitemid = param.toInt();

    _item->setReadOnly(TRUE);

    // get taxauth_id before item->setId()
    XSqlQuery taxauth;
    taxauth.prepare("SELECT cobmisc_taxauth_id "
		    "FROM coitem, cobmisc "
		    "WHERE ((coitem_cohead_id=cobmisc_cohead_id)"
		    "  AND  (coitem_id=:soitem_id));");
    taxauth.bindValue(":soitem_id", _soitemid);
    taxauth.exec();
    if (taxauth.first())
      _taxauthid=taxauth.value("cobmisc_taxauth_id").toInt();
    else if (taxauth.lastError().type() != QSqlError::None)
    {
      systemError(this, taxauth.lastError().databaseText(), __FILE__, __LINE__);
      return UndefinedError;
    }

    XSqlQuery soitem;
    soitem.prepare( "SELECT itemsite_item_id, cust_partialship,"
                    "       cohead_number, coitem_linenumber,"
                    "       uom_name,"
                    "       coitem_qtyord,"
                    "       coitem_qtyshipped,"
                    "       (coitem_qtyord - coitem_qtyshipped) AS qtybalance,"
                    "       COALESCE(coitem_tax_id, -1) AS tax_id "
                    "FROM coitem, itemsite, cohead, cust, uom "
                    "WHERE ( (coitem_itemsite_id=itemsite_id)"
                    " AND (coitem_cohead_id=cohead_id)"
                    " AND (coitem_status <> 'X')"
                    " AND (coitem_qty_uom_id=uom_id)"
                    " AND (cohead_cust_id=cust_id)"
                    " AND (coitem_id=:soitem_id) )" );
    soitem.bindValue(":soitem_id", _soitemid);
    soitem.exec();
    if (soitem.first())
    {
      _cachedBalanceDue = soitem.value("qtybalance").toDouble();

      _item->setId(soitem.value("itemsite_item_id").toInt());
      _salesOrderNumber->setText(soitem.value("cohead_number").toString());
      _lineNumber->setText(soitem.value("coitem_linenumber").toString());
      _qtyUOM->setText(soitem.value("uom_name").toString());
      _ordered->setDouble(soitem.value("coitem_qtyord").toDouble());
      _shipped->setDouble(soitem.value("coitem_qtyshipped").toDouble());
      _balance->setDouble(soitem.value("qtybalance").toDouble());
      _taxCode->setId(soitem.value("tax_id").toInt());

      _cachedPartialShip = soitem.value("cust_partialship").toBool();
      _closeLine->setChecked(!_cachedPartialShip);
      _closeLine->setEnabled(_cachedPartialShip);

      double uninvoiced;
      XSqlQuery coship;
      coship.prepare( "SELECT SUM(coship_qty) AS uninvoiced "
                      "FROM cosmisc, coship "
                      "WHERE ( (coship_cosmisc_id=cosmisc_id)"
                      " AND (NOT coship_invoiced)"
                      " AND (cosmisc_shipped)"
                      " AND (coship_coitem_id=:soitem_id) );" );
      coship.bindValue(":soitem_id", _soitemid);
      coship.exec();
      if (coship.first())
      {
        uninvoiced = coship.value("uninvoiced").toDouble();
        _uninvoiced->setDouble(coship.value("uninvoiced").toDouble());
      }
      else
      {
        uninvoiced = 0.0;
        _uninvoiced->setDouble(0.0);
      }

      // take uninvoiced into account
      _cachedBalanceDue += uninvoiced;

      XSqlQuery cobill;
      cobill.prepare( "SELECT cobill_qty, cobill_toclose,"
		      "       cobill_taxtype_id, cobill_tax_id "
                      "FROM cobill, cobmisc "
                      "WHERE ( (cobill_cobmisc_id=cobmisc_id) "
		      "  AND   (NOT cobmisc_posted)"
                      "  AND   (cobill_coitem_id=:soitem_id) );" );
      cobill.bindValue(":soitem_id", _soitemid);
      cobill.exec();
      if (cobill.first())
      {
	_toBill->setDouble(cobill.value("cobill_qty").toDouble());

        if (soitem.value("cust_partialship").toBool())
	  _closeLine->setChecked(cobill.value("cobill_toclose").toBool());

	// overwrite automatically-found values if user previously set them
	_taxType->setId(cobill.value("cobill_taxtype_id").toInt());
	_taxCode->setId(cobill.value("cobill_tax_id").toInt());
      }
      else if (cobill.lastError().type() != QSqlError::None)
      {
	systemError(this, cobill.lastError().databaseText(), __FILE__, __LINE__);
	return UndefinedError;
      }
      else
      {
	_toBill->setDouble(uninvoiced);

        if (soitem.value("cust_partialship").toBool())
	  _closeLine->setChecked((uninvoiced == _cachedBalanceDue));
      }

      _toBill->setSelection(0, _toBill->text().length());
    }
    else if (soitem.lastError().type() != QSqlError::None)
    {
      systemError(this, soitem.lastError().databaseText(), __FILE__, __LINE__);
      return UndefinedError;
    }
  }

  return NoError;
}
bool dspFreightPricesByCustomer::setParams(ParameterList &params)
{
  if(!_cust->isValid())
  {
    QMessageBox::warning(this, tr("Customer Required"),
      tr("You must specify a valid Customer."));
    return false;
  }

  params.append("byCust");

  params.append("na", tr("N/A"));
  params.append("any", tr("Any"));
  params.append("flatrate", tr("Flat Rate"));
  params.append("peruom", tr("Per UOM"));
  params.append("customer", tr("Customer"));
  params.append("custType", tr("Cust. Type"));
  params.append("custTypePattern", tr("Cust. Type Pattern"));
  params.append("sale", tr("Sale"));

  if (_cust->isValid())
    params.append("cust_id", _cust->id());

  if (_showExpired->isChecked())
    params.append("showExpired");

  if (_showFuture->isChecked())
    params.append("showFuture");

  return true;
}
Esempio n. 15
0
void reprintInvoices::sPrint()
{
  QPrinter printer;
  bool     setupPrinter = TRUE;

  XListViewItem *cursor = _invoice->firstChild();
  bool userCanceled = false;
  if (orReport::beginMultiPrint(&printer, userCanceled) == false)
  {
    if(!userCanceled)
      systemError(this, tr("Could not initialize printing system for multiple reports."));
    return;
  }
  while (cursor != 0)
  {
    if (_invoice->isSelected(cursor))
    {
      int counter = 0;

      for ( XListViewItem *watermark = _watermarks->firstChild();
            watermark; watermark = watermark->nextSibling(), counter++ )
      {
        q.prepare("SELECT findCustomerForm(:cust_id, 'I') AS _reportname;");
        q.bindValue(":cust_id", cursor->altId());
        q.exec();
        if (q.first())
        {
          ParameterList params;
          params.append("invchead_id", cursor->id());
          params.append("showcosts", ((watermark->text(2) == tr("Yes")) ? "TRUE" : "FALSE") );
          params.append("watermark", watermark->text(1));

          orReport report(q.value("_reportname").toString(), params);
          if (report.isValid())
          {
            if (report.print(&printer, setupPrinter))
	           setupPrinter = FALSE;
	        else 
	        {
	          report.reportError(this);
	          orReport::endMultiPrint(&printer);
	          return;
  	        }
          }
	      else
            QMessageBox::critical( this, tr("Cannot Find Invoice Form"),
                                   tr( "The Invoice Form '%1' cannot be found.\n"
                                       "One or more of the selected Invoices cannot be printed until a Customer Form Assignment\n"
                                       "is updated to remove any references to this Invoice Form or this Invoice Form is created." )
                                   .arg(q.value("_reportname").toString()) );
        }
	    else if (q.lastError().type() != QSqlError::None)
	    {
	      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
	     return;
        }
      }
      if (_metrics->boolean("EnableBatchManager"))
      {
        // TODO: Check for EDI and handle submission to Batch here
        q.prepare("SELECT CASE WHEN (COALESCE(shipto_ediprofile_id, -2) = -2)"
                "              THEN COALESCE(cust_ediprofile_id,-1)"
                "            ELSE COALESCE(shipto_ediprofile_id,-2)"
                "       END AS result,"
                "       COALESCE(cust_emaildelivery, false) AS custom"
                "  FROM cust, invchead"
                "       LEFT OUTER JOIN shipto"
                "         ON (invchead_shipto_id=shipto_id)"
                "  WHERE ((invchead_cust_id=cust_id)"
                "    AND  (invchead_id=:invchead_id)); ");
        q.bindValue(":invchead_id", cursor->id());
        q.exec();
        if(q.first())
        {
          if(q.value("result").toInt() == -1)
          {
            if(q.value("custom").toBool())
            {
              ParameterList params;
              params.append("invchead_id", cursor->id());
    
              deliverInvoice newdlg(this, "", TRUE);
              newdlg.set(params);
              newdlg.exec();
            }
          }
          else
          {
            ParameterList params;
            params.append("action_name", "TransmitInvoice");
            params.append("invchead_id", cursor->id());
    
            submitAction newdlg(this, "", TRUE);
            newdlg.set(params);
            newdlg.exec();
          }
        }
      }
      else if (q.lastError().type() != QSqlError::None)
      {
        systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
    }
  cursor = cursor->nextSibling();
  }
  orReport::endMultiPrint(&printer);

  _invoice->clearSelection();
  _close->setText(tr("&Close"));
  _print->setEnabled(FALSE);
}
Esempio n. 16
0
int main(int argc, char *argv[]) 
{
#ifdef HAVE_MPI
  MPI_Init(&argc, &argv);
  Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
  Epetra_SerialComm Comm;
#endif

  int NumGlobalRows = 10000; // must be a square for the
                             // matrix generator.
  int NumVectors = 1;        // number of rhs's. Amesos
                             // supports single or
			     // multiple RHS.

  // Initializes an Gallery object.
  // NOTE: this example uses the Trilinos package Galeri
  // to define in an easy way the linear system matrix.
  // The user can easily change the matrix type; consult the 
  // Galeri documentation for mode details.
  //
  // Here the problem has size nx x ny, and the 2D Cartesian
  // grid is divided into mx x my subdomains.
  ParameterList GaleriList;
  GaleriList.set("nx", 100);
  GaleriList.set("ny", 100 * Comm.NumProc());
  GaleriList.set("mx", 1);
  GaleriList.set("my", Comm.NumProc());

  Epetra_Map* Map = CreateMap("Cartesian2D", Comm, GaleriList);
  Epetra_CrsMatrix* Matrix = CreateCrsMatrix("Laplace2D", Map, GaleriList);

  // Creates vectors for right-hand side and solution, and the
  // linear problem container.

  Epetra_Vector LHS(*Map); LHS.PutScalar(0.0); // zero solution
  Epetra_Vector RHS(*Map); RHS.Random();       // random rhs
  Epetra_LinearProblem Problem(Matrix, &LHS, &RHS);

  // ===================================================== //
  // B E G I N N I N G   O F  T H E   AM E S O S   P A R T //
  // ===================================================== //

  // Initializes the Amesos solver. This is the base class for
  // Amesos. It is a pure virtual class (hence objects of this
  // class cannot be allocated, and can exist only as pointers 
  // or references).
  //
  Amesos_BaseSolver* Solver;

  // Initializes the Factory. Factory is a function class (a
  // class that contains methods only, no data). Factory
  // will be used to create Amesos_BaseSolver derived objects.
  //
  Amesos Factory;

  Solver = Factory.Create("Klu", Problem);

  // Parameters for all Amesos solvers are set through
  // a call to SetParameters(List). List is a Teuchos
  // parameter list (Amesos requires Teuchos to compile).
  // In most cases, users can proceed without calling
  // SetParameters(). Please refer to the Amesos guide
  // for more details.
  // NOTE: you can skip this call; then the solver will
  // use default parameters.
  //
  // Parameters in the list are set using 
  // List.set("parameter-name", ParameterValue);
  // In this example, we specify that we want more output.
  //
  Teuchos::ParameterList List;
  List.set("PrintTiming", true);
  List.set("PrintStatus", true);
  
  Solver->SetParameters(List);
  
  // Now we are ready to solve. Generally, users will
  // call SymbolicFactorization(), then NumericFactorization(),
  // and finally Solve(). Note that:
  // - the numerical values of the linear system matrix
  //   are *not* required before NumericFactorization();
  // - solution and rhs are *not* required before calling
  //   Solve().
  if (Comm.MyPID() == 0)
    cout << "Starting symbolic factorization..." << endl;
  Solver->SymbolicFactorization();
  
  // you can change the matrix values here
  if (Comm.MyPID() == 0)
    cout << "Starting numeric factorization..." << endl;
  Solver->NumericFactorization();
  
  // you can change LHS and RHS here
  if (Comm.MyPID() == 0)
    cout << "Starting solution phase..." << endl;
  Solver->Solve();

  // =========================================== //
  // E N D   O F   T H E   A M E S O S   P A R T //
  // =========================================== //

  // delete Solver. MPI calls can occur.
  delete Solver;
    
  // delete the objects created by Galeri
  delete Matrix;
  delete Map;

#ifdef HAVE_MPI
  MPI_Finalize();
#endif

  return(EXIT_SUCCESS);

} // end of main()
Esempio n. 17
0
void ParameterGroup::appendValue(ParameterList &pParams)
{
  if (_selected->isChecked())
  {
    if (_type == ClassCode)
      pParams.append("classcode_id", _items->id());
    else if (_type == PlannerCode)
      pParams.append("plancode_id", _items->id());
    else if (_type == ProductCategory)
      pParams.append("prodcat_id", _items->id());
    else if (_type == ItemGroup)
      pParams.append("itemgrp_id", _items->id());
    else if (_type == CostCategory)
      pParams.append("costcat_id", _items->id());
    else if (_type == CustomerType)
      pParams.append("custtype_id", _items->id());
    else if (_type == CustomerGroup)
      pParams.append("custgrp_id", _items->id());
    else if (_type == CurrencyNotBase || _type == Currency)
      pParams.append("curr_id", _items->id());
    else if (_type == WorkCenter)
      pParams.append("wrkcnt_id", _items->id());
    else if (_type == OpportunitySource)
      pParams.append("opsource_id", _items->id());
    else if (_type == OpportunityStage)
      pParams.append("opstage_id", _items->id());
    else if (_type == OpportunityType)
      pParams.append("optype_id", _items->id());
    else if (_type == User || _type == ActiveUser )
    {
      pParams.append("usr_id", _items->id());
      pParams.append("username", _items->itemText(_items->currentIndex()));
    }
  }
  else if (_usePattern->isChecked() && !_pattern->text().isEmpty())
  {
    if (_type == ClassCode)
      pParams.append("classcode_pattern", _pattern->text());
    else if (_type == PlannerCode)
      pParams.append("plancode_pattern", _pattern->text());
    else if (_type == ProductCategory)
      pParams.append("prodcat_pattern", _pattern->text());
    else if (_type == ItemGroup)
      pParams.append("itemgrp_pattern", _pattern->text());
    else if (_type == CostCategory)
      pParams.append("costcat_pattern", _pattern->text());
    else if (_type == CustomerType)
      pParams.append("custtype_pattern", _pattern->text());
    else if (_type == CustomerGroup)
      pParams.append("custgrp_pattern", _pattern->text());
    else if (_type == CurrencyNotBase || _type == Currency)
      pParams.append("currConcat_pattern", _pattern->text());
    else if (_type == WorkCenter)
      pParams.append("wrkcnt_pattern", _pattern->text());
    else if (_type == OpportunitySource)
      pParams.append("opsource_pattern", _pattern->text());
    else if (_type == OpportunityStage)
      pParams.append("opstage_pattern", _pattern->text());
    else if (_type == OpportunityType)
      pParams.append("optype_pattern", _pattern->text());
    else if (_type == User || _type == ActiveUser)
      pParams.append("usr_pattern", _pattern->text());
  }
}
int main(int argc, char *argv[]) {
  //
#ifdef EPETRA_MPI	
  MPI_Init(&argc,&argv);
  Belos::MPIFinalize mpiFinalize; // Will call finalize with *any* return
  (void)mpiFinalize;
#endif	
  //
  typedef double                            ST;
  typedef Teuchos::ScalarTraits<ST>        SCT;
  typedef SCT::magnitudeType                MT;
  typedef Epetra_MultiVector                MV;
  typedef Epetra_Operator                   OP;
  typedef Belos::MultiVecTraits<ST,MV>     MVT;
  typedef Belos::OperatorTraits<ST,MV,OP>  OPT;

  using Teuchos::ParameterList;
  using Teuchos::RCP;
  using Teuchos::rcp;

  bool verbose = false, proc_verbose = false;
  bool pseudo = false;   // use pseudo block CG to solve this linear system.
  int frequency = -1;
  int blocksize = 1;
  int numrhs = 1;
  int maxrestarts = 15; // number of restarts allowed 
  int maxiters = -1;    // maximum number of iterations allowed per linear system
  std::string filename("bcsstk14.hb");
  MT tol = 1.0e-5;  // relative residual tolerance

  Teuchos::CommandLineProcessor cmdp(false,true);
  cmdp.setOption("verbose","quiet",&verbose,"Print messages and results.");
  cmdp.setOption("pseudo","regular",&pseudo,"Use pseudo-block CG to solve the linear systems.");
  cmdp.setOption("frequency",&frequency,"Solvers frequency for printing residuals (#iters).");
  cmdp.setOption("filename",&filename,"Filename for Harwell-Boeing test matrix.");
  cmdp.setOption("tol",&tol,"Relative residual tolerance used by CG solver.");
  cmdp.setOption("max-restarts",&maxrestarts,"Maximum number of restarts allowed for CG solver.");
  cmdp.setOption("blocksize",&blocksize,"Block size used by CG.");
  cmdp.setOption("maxiters",&maxiters,"Maximum number of iterations per linear system (-1 = adapted to problem/block size).");
  if (cmdp.parse(argc,argv) != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
    return -1;
  }
  if (!verbose)
    frequency = -1;  // reset frequency if test is not verbose
  //
  // Get the problem
  //
  int MyPID;
  RCP<Epetra_CrsMatrix> A;
  RCP<Epetra_MultiVector> B, X;
  int return_val =Belos::createEpetraProblem(filename,NULL,&A,&B,&X,&MyPID);
  if(return_val != 0) return return_val;
  const Epetra_Map &Map = A->RowMap();
  proc_verbose = verbose && (MyPID==0);  /* Only print on the zero processor */
  //
  // ********Other information used by block solver***********
  // *****************(can be user specified)******************
  //
  const int NumGlobalElements = B->GlobalLength();
  if (maxiters == -1)
    maxiters = NumGlobalElements/blocksize - 1; // maximum number of iterations to run
  //
  ParameterList belosList;
  belosList.set( "Num Blocks", maxiters );               // Maximum number of blocks in Krylov factorization
  belosList.set( "Block Size", blocksize );              // Blocksize to be used by iterative solver
  belosList.set( "Maximum Iterations", maxiters );       // Maximum number of iterations allowed
  belosList.set( "Maximum Restarts", maxrestarts );      // Maximum number of restarts allowed
  belosList.set( "Convergence Tolerance", tol );         // Relative convergence tolerance requested
  if (verbose) {
    belosList.set( "Verbosity", Belos::Errors + Belos::Warnings + 
		   Belos::TimingDetails + Belos::FinalSummary + Belos::StatusTestDetails );
    if (frequency > 0)
      belosList.set( "Output Frequency", frequency );
  }
  else
    belosList.set( "Verbosity", Belos::Errors + Belos::Warnings );
  //
  //
  // Construct an unpreconditioned linear problem instance.
  //
  Belos::LinearProblem<double,MV,OP> problem( A, X, B );
  bool set = problem.setProblem();
  if (set == false) {
    if (proc_verbose)
      std::cout << std::endl << "ERROR:  Belos::LinearProblem failed to set up correctly!" << std::endl;
    return -1;
  }
  //
  // *******************************************************************
  // *************Start the block CG iteration*************************
  // *******************************************************************
  //
  Teuchos::RCP< Belos::SolverManager<double,MV,OP> > solver;
  solver = Teuchos::rcp( new Belos::BlockCGSolMgr<double,MV,OP>( rcp(&problem,false), rcp(&belosList,false) ) );
  //
  // Perform solve
  //
  Belos::ReturnType ret = solver->solve();
  //
  // Get the number of iterations for this solve.
  //
  int numIters = solver->getNumIters();
  std::cout << "Number of iterations performed for this solve: " << numIters << std::endl;

  if (ret!=Belos::Converged) {
    if (proc_verbose)
      std::cout << "End Result: TEST FAILED" << std::endl;	
    return -1;
  }
  //
  //
  // Compute actual residuals.
  //
  std::vector<double> actual_resids( numrhs );
  std::vector<double> rhs_norm( numrhs );
  Epetra_MultiVector resid(Map, numrhs);
  OPT::Apply( *A, *X, resid );
  MVT::MvAddMv( -1.0, resid, 1.0, *B, resid ); 
  MVT::MvNorm( resid, actual_resids );
  MVT::MvNorm( *B, rhs_norm );
  if (proc_verbose) {
    std::cout<< "---------- Actual Residuals (normalized) ----------"<<std::endl<<std::endl;
    for ( int i=0; i<numrhs; i++) {
      std::cout<<"Problem "<<i<<" : \t"<< actual_resids[i]/rhs_norm[i] <<std::endl;
    }
  }
  //
  // -----------------------------------------------------------------
  // Resolve the first problem by just resetting the solver manager.
  // -----------------------------------------------------------------
  X->PutScalar( 0.0 );  
  solver->reset( Belos::Problem );
  //
  // Perform solve (again)
  //
  ret = solver->solve();
  //
  // Get the number of iterations for this solve.
  //
  numIters = solver->getNumIters();
  std::cout << "Number of iterations performed for this solve (manager reset): " << numIters << std::endl;

  if (ret!=Belos::Converged) {
    if (proc_verbose)
      std::cout << "End Result: TEST FAILED" << std::endl;	
    return -1;
  }
  //
  // Compute actual residuals.
  //
  OPT::Apply( *A, *X, resid );
  MVT::MvAddMv( -1.0, resid, 1.0, *B, resid ); 
  MVT::MvNorm( resid, actual_resids );
  MVT::MvNorm( *B, rhs_norm );
  if (proc_verbose) {
    std::cout<< "---------- Actual Residuals (normalized) ----------"<<std::endl<<std::endl;
    for ( int i=0; i<numrhs; i++) {
      std::cout<<"Problem "<<i<<" : \t"<< actual_resids[i]/rhs_norm[i] <<std::endl;
    }
  }
  //
  // -------------------------------------------------------------
  // Construct a second unpreconditioned linear problem instance.
  // -------------------------------------------------------------
  RCP<Epetra_MultiVector> X2 = MVT::Clone(*X, numrhs); 
  MVT::MvInit( *X2, 0.0 );
  Belos::LinearProblem<double,MV,OP> problem2( A, X2, B );
  problem2.setLabel("Belos Resolve");
  set = problem2.setProblem();
  if (set == false) {
    if (proc_verbose)
      std::cout << std::endl << "ERROR:  Belos::LinearProblem failed to set up correctly!" << std::endl;
    return -1;
  }
  //
  // *******************************************************************
  // *************Start the block CG iteration*************************
  // *******************************************************************
  //
  // Create the solver without either the problem or parameter list.
  solver = Teuchos::rcp( new Belos::BlockCGSolMgr<double,MV,OP>() );

  // Get the valid list of parameters from the solver and print it.
  RCP<const Teuchos::ParameterList> validList = solver->getValidParameters();
  if (proc_verbose) {
    std::cout << std::endl << "Valid parameters from the block CG solver manager:" << std::endl;
    std::cout << *validList << std::endl;
  }
  //
  // Set the problem after the solver construction.
  solver->setProblem( rcp( &problem2, false ) );

  // Set the parameter list after the solver construction.
  belosList.set( "Timer Label", "Belos Resolve" );         // Set timer label to discern between the two solvers.
  solver->setParameters( rcp( &belosList, false ) );
  //
  // Perform solve
  //
  ret = solver->solve();
  //
  // Get the number of iterations for this solve.
  //
  numIters = solver->getNumIters();
  std::cout << "Number of iterations performed for this solve (new solver): " << numIters << std::endl;

  //
  // Compute actual residuals.
  //
  bool badRes = false;
  std::vector<double> actual_resids2( numrhs );
  Epetra_MultiVector resid2(Map, numrhs);
  OPT::Apply( *A, *X2, resid2 );
  MVT::MvAddMv( -1.0, resid2, 1.0, *B, resid2 ); 
  MVT::MvNorm( resid2, actual_resids2 );
  MVT::MvNorm( *B, rhs_norm );
  if (proc_verbose) {
    std::cout<< "---------- Actual Residuals 2 (normalized) ----------"<<std::endl<<std::endl;
    for ( int i=0; i<numrhs; i++) {
      std::cout<<"Problem "<<i<<" : \t"<< actual_resids2[i]/rhs_norm[i] <<std::endl;
      if ( ( actual_resids2[i] - actual_resids[i] ) > SCT::prec() ) { 
        badRes = true;
      }
    }
  }
  //
  // **********Print out information about problem*******************
  //
  if (proc_verbose) {
    std::cout << std::endl << std::endl;
    std::cout << "Dimension of matrix: " << NumGlobalElements << std::endl;
    std::cout << "Number of right-hand sides: " << numrhs << std::endl;
    std::cout << "Block size used by solver: " << blocksize << std::endl;
    std::cout << "Relative residual tolerance: " << tol << std::endl;
    std::cout << std::endl;
  }

  if (ret!=Belos::Converged || badRes) {
    if (proc_verbose)
      std::cout << "End Result: TEST FAILED" << std::endl;	
    return -1;
  }
  //
  // Default return value
  //
  if (proc_verbose)
    std::cout << "End Result: TEST PASSED" << std::endl;
  return 0;
  //
} // end test_resolve_gmres_hb.cpp
Esempio n. 19
0
enum SetResponse arOpenItem::set( const ParameterList &pParams )
{
    XSqlQuery aret;
    XDialog::set(pParams);
    QVariant param;
    bool     valid;

    param = pParams.value("docType", &valid);
    if (valid)
    {
        if (param.toString() == "creditMemo")
        {
            setWindowTitle(windowTitle() + tr(" - Enter Misc. Credit Memo"));
            _docType->setCurrentIndex(0);
            _rsnCode->setType(XComboBox::ARCMReasonCodes);
        }
        else if (param.toString() == "debitMemo")
        {
            setWindowTitle(windowTitle() + tr(" - Enter Misc. Debit Memo"));
            _docType->setCurrentIndex(1);
            _rsnCode->setType(XComboBox::ARDMReasonCodes);
        }
        else if (param.toString() == "invoice")
            _docType->setCurrentIndex(2);
        else if (param.toString() == "customerDeposit")
            _docType->setCurrentIndex(3);
        else
            return UndefinedError;
//  ToDo - better error return types

        _docType->setEnabled(FALSE);
    }

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

            aret.exec("SELECT fetchARMemoNumber() AS number;");
            if (aret.first())
            {
                _docNumber->setText(aret.value("number").toString());
                _seqiss = aret.value("number").toInt();
            }
            else if (aret.lastError().type() != QSqlError::NoError)
            {
                systemError(this, aret.lastError().databaseText(), __FILE__, __LINE__);
                return UndefinedError;
            }

            _paid->clear();
            _save->setText(tr("Post"));
            _printOnPost->setVisible(true);
        }
        else if (param.toString() == "edit")
        {
            _mode = cEdit;

            _cust->setReadOnly(TRUE);
            _docDate->setEnabled(FALSE);
            _docType->setEnabled(FALSE);
            _docNumber->setEnabled(FALSE);
            _orderNumber->setEnabled(FALSE);
            _journalNumber->setEnabled(FALSE);
            _terms->setEnabled(FALSE);
            _useAltPrepaid->setEnabled(FALSE);
            _altPrepaid->setEnabled(FALSE);
        }
        else if (param.toString() == "view")
        {
            _mode = cView;

            _cust->setReadOnly(TRUE);
            _docDate->setEnabled(FALSE);
            _dueDate->setEnabled(FALSE);
            _docType->setEnabled(FALSE);
            _docNumber->setEnabled(FALSE);
            _orderNumber->setEnabled(FALSE);
            _journalNumber->setEnabled(FALSE);
            _amount->setEnabled(FALSE);
            _terms->setEnabled(FALSE);
            _terms->setType(XComboBox::Terms);
            _salesrep->setEnabled(FALSE);
            _commissionDue->setEnabled(FALSE);
            _rsnCode->setEnabled(FALSE);
            _useAltPrepaid->setEnabled(FALSE);
            _altPrepaid->setEnabled(FALSE);
            _notes->setReadOnly(TRUE);
            _buttonBox->clear();
            _buttonBox->addButton(QDialogButtonBox::Close);
        }
        else
            return UndefinedError;
    }

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

    param = pParams.value("aropen_id", &valid);
    if (valid)
    {
        _aropenid = param.toInt();
        populate();
    }

    return NoError;
}
Esempio n. 20
0
void arWorkBench::sCCRefundCM()
{
  if (_aropenCM->altId() < 0)
  {
    QMessageBox::warning(this, tr("Cannot Refund by Credit Card"),
			 tr("<p>The application cannot refund this "
			    "transaction using a credit card."));
    return;
  }
  
  int     ccardid = -1;
  double  total   =  0.0;
  int     currid  = -1;
  QString docnum;
  QString refnum;
  int     ccpayid = -1;

  q.prepare("SELECT cmhead_id "
	    "FROM cmhead "
	    "WHERE (cmhead_number=:cmheadnumber);");
  q.bindValue(":cmheadnumber", _aropenCM->currentItem()->text(1));
  q.exec();
  if (q.first())
  {
    ParameterList ccp;
    ccp.append("cmhead_id", q.value("cmhead_id"));
    MetaSQLQuery ccm = mqlLoad(":/so/creditMemoCreditCard.mql");
    XSqlQuery ccq = ccm.toQuery(ccp);
    if (ccq.first())
    {
      ccardid = ccq.value("ccard_id").toInt();
      total   = ccq.value("total").toDouble();
      currid  = ccq.value("cmhead_curr_id").toInt();
      docnum  = ccq.value("cmhead_number").toString();
      refnum  = ccq.value("cohead_number").toString();
      ccpayid = ccq.value("ccpay_id").toInt();
    }
    else if (ccq.lastError().type() != QSqlError::None)
    {
      systemError(this, ccq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else
    {
      QMessageBox::critical(this, tr("Credit Card Processing Error"),
			    tr("Could not find a Credit Card to use for "
			       "this Credit transaction."));
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  else // cmhead not found - maybe it's just an open item
  {
    q.prepare("SELECT ccard_id, aropen_amount - aropen_paid AS balance,"
	      "       aropen_curr_id, aropen_docnumber "
	      "FROM aropen, ccard "
	      "WHERE ((aropen_cust_id=ccard_cust_id)"
	      "  AND  (ccard_active)"
	      "  AND  (aropen_open)"
	      "  AND  (aropen_id=:aropenid));");
    q.bindValue(":aropenid", _aropenCM->id());
    q.exec();

    if (q.first())
    {
      ccardid = q.value("ccard_id").toInt();
      total   = q.value("balance").toDouble();
      currid  = q.value("aropen_curr_id").toInt();
      docnum  = q.value("aropen_docnumber").toString();
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else
    {
      QMessageBox::critical(this, tr("Credit Card Processing Error"),
			    tr("Could not find a Credit Card to use for "
			       "this Credit transaction."));
      return;
    }
  }

  CreditCardProcessor *cardproc = CreditCardProcessor::getProcessor();
  if (! cardproc)
    QMessageBox::critical(this, tr("Credit Card Processing Error"),
			  CreditCardProcessor::errorMsg());
  else
  {
    int returnValue = cardproc->credit(ccardid, total, currid,
				       docnum, refnum, ccpayid);
    if (returnValue < 0)
      QMessageBox::critical(this, tr("Credit Card Processing Error"),
			    cardproc->errorMsg());
    else if (returnValue > 0)
      QMessageBox::warning(this, tr("Credit Card Processing Warning"),
			   cardproc->errorMsg());
    else if (! cardproc->errorMsg().isEmpty())
      QMessageBox::information(this, tr("Credit Card Processing Note"),
			   cardproc->errorMsg());
  }

  sFillList();
}
Esempio n. 21
0
enum SetResponse invoice::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("invchead_id", &valid);
  if (valid)
  {
    _invcheadid = param.toInt();
    populate();
    populateCMInfo();
    populateCCInfo();
  }

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

      q.exec("SELECT NEXTVAL('invchead_invchead_id_seq') AS invchead_id;");
      if (q.first())
        _invcheadid = q.value("invchead_id").toInt();
      else if (q.lastError().type() != QSqlError::None)
      {
	systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
	return UndefinedError;
      }

      q.exec("SELECT fetchInvcNumber() AS number;");
      if (q.first())
        _invoiceNumber->setText(q.value("number").toString());
      else if (q.lastError().type() != QSqlError::None)
      {
	systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
	return UndefinedError;
      }

      _orderDate->setDate(omfgThis->dbDate());
      _shipDate->setDate(omfgThis->dbDate());
      _invoiceDate->setDate(omfgThis->dbDate(), true);

      q.prepare("INSERT INTO invchead ("
	        "    invchead_id, invchead_invcnumber, invchead_orderdate,"
		"    invchead_invcdate, invchead_cust_id, invchead_posted,"
		"    invchead_printed, invchead_commission, invchead_freight,"
		"    invchead_tax, invchead_misc_amount"
		") VALUES ("
		"    :invchead_id, :invchead_invcnumber, :invchead_orderdate, "
		"    :invchead_invcdate, -1, false,"
		"    false, 0, 0,"
		"    0, 0"
		");");
      q.bindValue(":invchead_id",	 _invcheadid);
      q.bindValue(":invchead_invcnumber",_invoiceNumber->text());
      q.bindValue(":invchead_orderdate", _orderDate->date());
      q.bindValue(":invchead_invcdate",	 _invoiceDate->date());
      q.exec();
      if (q.lastError().type() != QSqlError::None)
      {
	systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
	return UndefinedError;
      }

      connect(_cust,	    SIGNAL(valid(bool)), _new, SLOT(setEnabled(bool)));
      connect(_cust,        SIGNAL(valid(bool)), this, SLOT(populateCMInfo()));
      connect(_orderNumber, SIGNAL(lostFocus()), this, SLOT(populateCCInfo()));
    }
    else if (param.toString() == "edit")
Esempio n. 22
0
enum SetResponse taxDetail::set(const ParameterList & pParams )
{
  QVariant param;
  bool     valid;
  
   _readonly = pParams.inList("readOnly");

   _new->hide();
   _delete->hide();

   param = pParams.value("taxzone_id", &valid);
   if (valid)
	   _taxzoneId = param.toInt();

   param = pParams.value("taxtype_id", &valid);
   if (valid)
   	   _taxType->setId(param.toInt());
   else
    clear();

   param = pParams.value("date", &valid);
   if (valid)
      _subtotal->setEffective(param.toDate());

   param = pParams.value("subtotal", &valid);
   if (valid)
	   _subtotal->setLocalValue(param.toDouble());
    
   param = pParams.value("curr_id", &valid);
   if (valid)
	   _subtotal->setId(param.toInt());

   param = pParams.value("order_id", &valid);
   if (valid)
    _orderid = param.toInt();

   param = pParams.value("order_type", &valid);
   if (valid)
    _ordertype = param.toString();

   param = pParams.value("display_type", &valid);
   if (valid)
    _displayType = param.toString();
	
   _adjustment = pParams.inList("adjustment"); 
   
   param = pParams.value("sense", &valid);
   if (valid)
    _sense = param.toInt();

   if (_readonly)
   {
     _taxType->setEnabled(FALSE);
     _cancel->setText(tr("&Close"));
   }

   if(_adjustment && !_readonly)
   {	
     _taxType->setEnabled(FALSE);
	   _new->show();
	   _delete->show();
   }

   sPopulate();

  return NoError;
}
void printPackingListBatchByShipvia::sPrint()
{
  QPrinter printer(QPrinter::HighResolution);
  bool     setupPrinter = TRUE;

  if (!_dates->allValid())
  {
    QMessageBox::warning( this, tr("Enter a Valid Start and End Date"),
                          tr("You must enter a valid Start and End Date for this report.") );
    _dates->setFocus();
    return;
  }

  XSqlQuery prtd;
  QString prts("UPDATE pack SET pack_printed=TRUE"
               " WHERE ((pack_head_id=<? value(\"head_id\") ?>) "
	       "   AND  (pack_head_type=<? value(\"head_type\") ?>)"
	       "<? if exists(\"shiphead_id\") ?>"
	       "   AND  (pack_shiphead_id=<? value(\"shiphead_id\") ?>)"
	       "<? else ?>"
	       "   AND (pack_shiphead_id IS NULL)"
	       "<? endif ?>"
	       ");" );


  XSqlQuery packq;
  ParameterList params;
  _dates->appendValue(params);
  if (_metrics->boolean("MultiWhs"))
    params.append("MultiWhs");
  params.append("shipvia", _shipvia->currentText());
  MetaSQLQuery packm = mqlLoad("packingListBatchByShipVia", "print");
  packq = packm.toQuery(params);
  if (packq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, packq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  bool userCanceled = false;
  if (orReport::beginMultiPrint(&printer, userCanceled) == false)
  {
    if(!userCanceled)
      systemError(this, tr("Could not initialize printing system for multiple reports."));
    return;
  }
  while (packq.next())
  {
    // leave sohead_id and cosmisc_id for compatibility with existing reports
    ParameterList params;
    params.append("head_id",   packq.value("pack_head_id").toInt());
    params.append("head_type", packq.value("pack_head_type").toString());
    if (packq.value("pack_head_type").toString() == "SO")
      params.append("sohead_id", packq.value("pack_head_id").toInt());
    else if (packq.value("pack_head_type").toString() == "TO")
      params.append("tohead_id", packq.value("pack_head_id").toInt());
    if (! packq.value("pack_shiphead_id").isNull())
    {
      params.append("cosmisc_id", packq.value("pack_shiphead_id").toInt());
      params.append("shiphead_id",  packq.value("pack_shiphead_id").toInt());
    }
    if (_metrics->boolean("MultiWhs"))
      params.append("MultiWhs");

    if (packq.value("orderhead_status").toString() != "C")
    {
      bool usePickForm;
      if (_auto->isChecked())
        usePickForm = packq.value("pack_shiphead_id").isNull();
      else
        usePickForm = _pick->isChecked();
        
      orReport report(packq.value( usePickForm ? "pickform" : "packform").toString(), params);

      if (report.isValid())
      {
        if (report.print(&printer, setupPrinter))
          setupPrinter = FALSE;
        else
        {
          orReport::endMultiPrint(&printer);
          return;
        }
      }
      else
      {
        report.reportError(this);
        orReport::endMultiPrint(&printer);
        return;
      }
    }

    MetaSQLQuery mql(prts);
    prtd = mql.toQuery(params);
    if (prtd.lastError().type() != QSqlError::NoError)
    {
      systemError(this, prtd.lastError().databaseText(), __FILE__, __LINE__);
      orReport::endMultiPrint(&printer);
      return;
    }

  }
  orReport::endMultiPrint(&printer);
  sPopulateShipVia();
}
Esempio n. 24
0
int main(int argc, char *argv[])
{

#ifdef EPETRA_MPI
  MPI_Init(&argc,&argv);
  Epetra_MpiComm Comm(MPI_COMM_WORLD);
#else
  Epetra_SerialComm Comm;
#endif

  // `Laplace2D' is a symmetric matrix; an example of non-symmetric
  // matrices is `Recirc2D' (advection-diffusion in a box, with
  // recirculating flow). The grid has nx x ny nodes, divided into
  // mx x my subdomains, each assigned to a different processor.
  int nx = 8;
  int ny = 8 * Comm.NumProc();

  ParameterList GaleriList;
  GaleriList.set("nx", nx);
  GaleriList.set("ny", ny);
  GaleriList.set("mx", 1);
  GaleriList.set("my", Comm.NumProc());

  Epetra_Map* Map = CreateMap("Cartesian2D", Comm, GaleriList);
  Epetra_CrsMatrix* A = CreateCrsMatrix("Laplace2D", Map, GaleriList);

  // use the following Galeri function to get the
  // coordinates for a Cartesian grid.

  Epetra_MultiVector* Coord = CreateCartesianCoordinates("2D", &(A->Map()),
                                                         GaleriList);
  double* x_coord = (*Coord)[0];
  double* y_coord = (*Coord)[1];

  // Create the linear problem, with a zero solution
  Epetra_Vector LHS(*Map); LHS.Random();
  Epetra_Vector RHS(*Map); RHS.PutScalar(0.0);

  Epetra_LinearProblem Problem(A, &LHS, &RHS);

  // As we wish to use AztecOO, we need to construct a solver object for this problem
  AztecOO solver(Problem);

  // =========================== begin of ML part ===========================

  // create a parameter list for ML options
  ParameterList MLList;

  // set defaults for classic smoothed aggregation.
  ML_Epetra::SetDefaults("SA",MLList);

  // use user's defined aggregation scheme to create the aggregates
  // 1.- set "user" as aggregation scheme (for all levels, or for
  //     a specify level only)
  MLList.set("aggregation: type", "user");
  // 2.- set the label (for output)
  ML_SetUserLabel(UserLabel);
  // 3.- set the aggregation scheme (see function above)
  ML_SetUserPartitions(UserPartitions);
  // 4.- set the coordinates.
  MLList.set("x-coordinates", x_coord);
  MLList.set("y-coordinates", y_coord);
  MLList.set("aggregation: dimensions", 2);

  // also setup some variables to visualize the aggregates
  // (more details are reported in example `ml_viz.cpp'.
  MLList.set("viz: enable", true);

  // now we create the preconditioner
  ML_Epetra::MultiLevelPreconditioner * MLPrec =
    new ML_Epetra::MultiLevelPreconditioner(*A, MLList);

  MLPrec->VisualizeAggregates();

  // tell AztecOO to use this preconditioner, then solve
  solver.SetPrecOperator(MLPrec);

  // =========================== end of ML part =============================

  solver.SetAztecOption(AZ_solver, AZ_cg_condnum);
  solver.SetAztecOption(AZ_output, 32);

  // solve with 500 iterations and 1e-12 tolerance
  solver.Iterate(500, 1e-12);

  delete MLPrec;

  // compute the real residual

  double residual;
  LHS.Norm2(&residual);

  if (Comm.MyPID() == 0)
  {
    cout << "||b-Ax||_2 = " << residual << endl;
  }

  delete Coord;
  delete A;
  delete Map;

  if (residual > 1e-3)
    exit(EXIT_FAILURE);

#ifdef EPETRA_MPI
  MPI_Finalize();
#endif

  exit(EXIT_SUCCESS);

}
Esempio n. 25
0
// -------------------------------------------------------------------------
bool performFlr(ParameterList & ip, bool gridExecutionFlag)
{
  DEBUG_TRACE;
  ExecFlr moduleFlr(ip);
  DEBUG_TRACE;

  string errorString;
  bool isValid = moduleFlr.validateParams(errorString);
  DEBUG_VAR(isValid);
  if (!isValid)
  {
    ERROR_MSG(errorString);
    return false;
  }

  isValid = moduleFlr.loadInputData();
  DEBUG_VAR(isValid);
  if (!isValid)
  {
    ERROR_MSG(errorString);
    return false;
  }

  bool returnStatus;

  if (!ip.exists("GRID_NUMNODES") || ip.getValueInt("GRID_NUMNODES") <= 0)
  {
    returnStatus = moduleFlr.invoke();
  }
  else
  {
    DEBUG_TRACE;
    int numNodes = ip.getValueInt("GRID_NUMNODES");

    string gridType = ip.getValue("GRID_TYPE");
    if (gridType == "pbs")
    {
      ParallelPbsExecution exec(&moduleFlr,
          gridExecutionFlag,
          !gridExecutionFlag,
          false);
      returnStatus = exec.invoke(numNodes);
    }
    else if (gridType == "sge")
    {
      ParallelSgeExecution exec(&moduleFlr,
          gridExecutionFlag,
          !gridExecutionFlag,
          false);
      returnStatus = exec.invoke(numNodes);
    }
  }
  // Test for return status
  DEBUG_VAR( returnStatus);
  if (!returnStatus)
  {
    ERROR_MSG("invoking moduleFlr exited in error.");
    return false;
  }

  DEBUG_TRACE;

  moduleFlr.saveOutputData();
  return true;
}
Esempio n. 26
0
void enterPoReturn::sFillList()
{
  _poitem->clear();

  if (_po->id() != -1)
  {
    q.prepare( "SELECT 1, vendaddr_addr_id AS addr_id, pohead_dropship "
	       "FROM vendaddrinfo, pohead "
	       "WHERE ((vendaddr_id=pohead_vendaddr_id)"
	       "  AND  (pohead_id=:pohead_id))"
	       "UNION "
	       "SELECT 2, vend_addr_id AS addr_id, pohead_dropship "
	       "FROM vendinfo, pohead "
	       "WHERE ((vend_id=pohead_vend_id)"
	       "  AND  (pohead_id=:pohead_id)) "
	       "ORDER BY 1 "
	       "LIMIT 1;");
    q.bindValue(":pohead_id", _po->id());
    q.exec();
    if (q.first())
	{
      _returnAddr->setId(q.value("addr_id").toInt());
	  _dropShip->setChecked(q.value("pohead_dropship").toBool());
	}
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    QString sql( "SELECT poitem_id, poitem_linenumber,"
               "       warehous_code, "
               "       COALESCE(item_number, <? value(\"nonInventory\") ?>) AS item_number,"
               "       CASE WHEN (LENGTH(TRIM(BOTH '    ' FROM poitem_vend_item_descrip)) <= 0) THEN "
               "                 (item_descrip1 || ' ' || item_descrip2) "
               "            ELSE poitem_vend_item_descrip "
               "       END AS itemdescription, "
               "       COALESCE(uom_name, <? value(\"na\") ?>) AS inv_uom,"
               "       poitem_vend_item_number, poitem_vend_uom,"
               "       poitem_qty_ordered,"
               "       poitem_qty_received,"
               "       poitem_qty_returned,"
               "       COALESCE( ( SELECT SUM(poreject_qty)"
               "                              FROM poreject"
               "                              WHERE ( (poreject_poitem_id=poitem_id)"
               "                               AND (NOT poreject_posted) ) ), 0 ) AS poitem_qty_toreturn, "
               "      'qty' AS poitem_qty_ordered_xtnumericrole, "
               "      'qty' AS poitem_qty_received_xtnumericrole, "
               "      'qty' AS poitem_qty_returned_xtnumericrole, "
               "      'qty' AS poitem_qty_toreturn_xtnumericrole "
               "FROM poitem LEFT OUTER JOIN "
               "     ( itemsite "
               "        JOIN item ON (itemsite_item_id=item_id) "
               "        JOIN uom ON (item_inv_uom_id=uom_id) "
               "        JOIN site() ON (itemsite_warehous_id=warehous_id) "
               "     ) ON (poitem_itemsite_id=itemsite_id) "
               "WHERE (poitem_pohead_id= <? value(\"pohead_id\") ?>) "
               "ORDER BY poitem_linenumber;" );
          
    ParameterList params;
    params.append("na", tr("N/A"));
    params.append("nonInventory", tr("Non-Inventory"));
    params.append("pohead_id", _po->id());
    MetaSQLQuery mql(sql);
    q = mql.toQuery(params);
    _poitem->populate(q);
    if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
}
Esempio 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::None)
  {
    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::None)
      {
        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::None)
  {
    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::None)
  {
    systemError(this, shipq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  // END the transaction

  if (_print->isChecked())
  {
    ParameterList params;
    params.append("cosmisc_id",  _shipment->id());
    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 postBillingSelection(: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::None)
	{
	  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::None)
    {
      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(":/sr/enterReceipt/ReceiveAll.mql");
    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::None)
    {
      rollback.exec();
      systemError(this, recverr + "<br>" + shipq.lastError().databaseText(),
		  __FILE__, __LINE__);
    }

    shipq.exec("COMMIT;");
    if (shipq.lastError().type() != QSqlError::None)
    {
      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);
    _select->setChecked(_privileges->check("SelectBilling") && _metrics->boolean("AutoSelectForBilling"));
    _select->setEnabled(_privileges->check("SelectBilling"));
    _create->setEnabled(_privileges->check("SelectBilling"));
    _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 = :cosmisc_tracknum)"
		"   AND  (   (shipdatasum_shiphead_number=:shiphead_number)"
		"         OR (:shiphead_number IS NULL)));");
  shipq.bindValue(":cosmisc_tracknum", _tracknum->currentText());
  if (! _shipment->number().isEmpty())
    shipq.bindValue(":shiphead_number", _shipment->number());
  shipq.exec();
  if (shipq.lastError().type() != QSqlError::None)
  {
    systemError(this, shipq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Esempio n. 28
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::NoError)
  {
    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);
  }
}
Esempio n. 29
0
void shipOrder::sHandleTo()
{
  _coitem->clear();
  _shipment->setEnabled(false);
  _shipment->removeOrderLimit();

  sHandleButtons();

  q.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;");
  q.bindValue(":tohead_id", _order->id());
  q.exec();
  if (q.first())
  {
    _freight->setId(q.value("tohead_freight_curr_id").toInt());
    _freight->setLocalValue(q.value("freight").toDouble());
    _billToName->setText(tr("Transfer Order"));
    _shipToName->setText(q.value("tohead_destname").toString());
    _shipToAddr1->setText(q.value("tohead_destaddress1").toString());
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.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);
  q = mql.toQuery(params);
  if (q.first())
  {
    if (_shipment->id() != q.value("shiphead_id").toInt())
      _shipment->setId(q.value("shiphead_id").toInt());

    if (q.next())
    {
      _shipment->setType("TO");
      _shipment->limitToOrder(_order->id());
      _shipment->setEnabled(true);
    }
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  else if (_shipment->isValid())
  {
    params.clear();
    params.append("tohead_id", _order->id());
    MetaSQLQuery mql(sql);
    q = mql.toQuery(params);
    if (q.first())
    {
      _shipment->setId(q.value("shiphead_id").toInt());
      if (q.next())
      {
        _shipment->setType("TO");
        _shipment->limitToOrder(_order->id());
        _shipment->setEnabled(true);
      }
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.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;
  }
}
int
main (int argc, char *argv[])
{
  using namespace TrilinosCouplings; // Yes, this means I'm lazy.

  using TpetraIntrepidPoissonExample::exactResidualNorm;
  using TpetraIntrepidPoissonExample::makeMatrixAndRightHandSide;
  using TpetraIntrepidPoissonExample::solveWithBelos;
  using TpetraIntrepidPoissonExample::solveWithBelosGPU;
  using IntrepidPoissonExample::makeMeshInput;
  using IntrepidPoissonExample::setCommandLineArgumentDefaults;
  using IntrepidPoissonExample::setUpCommandLineArguments;
  using IntrepidPoissonExample::parseCommandLineArguments;
  using Tpetra::DefaultPlatform;
  using Teuchos::Comm;
  using Teuchos::outArg;
  using Teuchos::ParameterList;
  using Teuchos::parameterList;
  using Teuchos::RCP;
  using Teuchos::rcp;
  using Teuchos::rcpFromRef;
  using Teuchos::getFancyOStream;
  using Teuchos::FancyOStream;
  using std::endl;
  // Pull in typedefs from the example's namespace.
  typedef TpetraIntrepidPoissonExample::ST ST;
  typedef TpetraIntrepidPoissonExample::LO LO;
  typedef TpetraIntrepidPoissonExample::GO GO;
  typedef TpetraIntrepidPoissonExample::Node Node;
  typedef Teuchos::ScalarTraits<ST> STS;
  typedef STS::magnitudeType MT;
  typedef Teuchos::ScalarTraits<MT> STM;
  typedef TpetraIntrepidPoissonExample::sparse_matrix_type sparse_matrix_type;
  typedef TpetraIntrepidPoissonExample::vector_type vector_type;
  typedef TpetraIntrepidPoissonExample::operator_type operator_type;

  bool success = true;
  try {

  Teuchos::oblackholestream blackHole;
  Teuchos::GlobalMPISession mpiSession (&argc, &argv, &blackHole);
  const int myRank = mpiSession.getRank ();
  //const int numProcs = mpiSession.getNProc ();

  // Get the default communicator and Kokkos Node instance
  RCP<const Comm<int> > comm =
    DefaultPlatform::getDefaultPlatform ().getComm ();
  RCP<Node> node = DefaultPlatform::getDefaultPlatform ().getNode ();

  // Did the user specify --help at the command line to print help
  // with command-line arguments?
  bool printedHelp = false;
  // Values of command-line arguments.
  int nx, ny, nz;
  std::string xmlInputParamsFile;
  bool verbose, debug;

  // Set default values of command-line arguments.
  setCommandLineArgumentDefaults (nx, ny, nz, xmlInputParamsFile,
                                  verbose, debug);
  // Parse and validate command-line arguments.
  Teuchos::CommandLineProcessor cmdp (false, true);
  setUpCommandLineArguments (cmdp, nx, ny, nz, xmlInputParamsFile,
                             verbose, debug);
  bool gpu = false;
  cmdp.setOption ("gpu", "no-gpu", &gpu,
                  "Run example using GPU node (if supported)");
  int ranks_per_node = 1;
  cmdp.setOption("ranks_per_node", &ranks_per_node,
                 "Number of MPI ranks per node");
  int gpu_ranks_per_node = 1;
  cmdp.setOption("gpu_ranks_per_node", &gpu_ranks_per_node,
                 "Number of MPI ranks per node for GPUs");
  int device_offset = 0;
  cmdp.setOption("device_offset", &device_offset,
                 "Offset for attaching MPI ranks to CUDA devices");
  parseCommandLineArguments (cmdp, printedHelp, argc, argv, nx, ny, nz,
                             xmlInputParamsFile, verbose, debug);
  if (printedHelp) {
    // The user specified --help at the command line to print help
    // with command-line arguments.  We printed help already, so quit
    // with a happy return code.
    return EXIT_SUCCESS;
  }

  // Both streams only print on MPI Rank 0.  "out" only prints if the
  // user specified --verbose.
  RCP<FancyOStream> out =
    getFancyOStream (rcpFromRef ((myRank == 0 && verbose) ? std::cout : blackHole));
  RCP<FancyOStream> err =
    getFancyOStream (rcpFromRef ((myRank == 0 && debug) ? std::cerr : blackHole));

#ifdef HAVE_MPI
  *out << "PARALLEL executable" << endl;
#else
  *out << "SERIAL executable" << endl;
#endif

/**********************************************************************************/
/********************************** GET XML INPUTS ********************************/
/**********************************************************************************/
  ParameterList inputList;
  if (xmlInputParamsFile != "") {
    *out << "Reading parameters from XML file \""
         << xmlInputParamsFile << "\"..." << endl;
    Teuchos::updateParametersFromXmlFile (xmlInputParamsFile,
                                          outArg (inputList));
    if (myRank == 0) {
      inputList.print (*out, 2, true, true);
      *out << endl;
    }
  }

  // Get Pamgen mesh definition string, either from the input
  // ParameterList or from our function that makes a cube and fills in
  // the number of cells along each dimension.
  std::string meshInput = inputList.get("meshInput", "");
  if (meshInput == "") {
    *out << "Generating mesh input string: nx = " << nx
         << ", ny = " << ny
         << ", nz = " << nz << endl;
    meshInput = makeMeshInput (nx, ny, nz);
  }

  // Total application run time
  {
  TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Time", total_time);

  RCP<sparse_matrix_type> A;
  RCP<vector_type> B, X_exact, X;
  {
    TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Assembly", total_assembly);
    makeMatrixAndRightHandSide (A, B, X_exact, X, comm, node, meshInput,
                                out, err, verbose, debug);
  }

  const std::vector<MT> norms = exactResidualNorm (A, B, X_exact);
  // X_exact is the exact solution of the PDE, projected onto the
  // discrete mesh.  It may not necessarily equal the exact solution
  // of the linear system.
  *out << "||B - A*X_exact||_2 = " << norms[0] << endl
       << "||B||_2 = " << norms[1] << endl
       << "||A||_F = " << norms[2] << endl;

  // Setup preconditioner
  std::string prec_type = inputList.get("Preconditioner", "None");
  RCP<operator_type> M;
  {
    TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Preconditioner Setup", total_prec);

    if (prec_type == "MueLu") {
      if (inputList.isSublist("MueLu")) {
        ParameterList mueluParams = inputList.sublist("MueLu");
        M = MueLu::CreateTpetraPreconditioner<ST,LO,GO,Node>(A,mueluParams);
      } else {
        M = MueLu::CreateTpetraPreconditioner<ST,LO,GO,Node>(A);
      }
    }
  }

  bool converged = false;
  int numItersPerformed = 0;
  const MT tol = inputList.get("Convergence Tolerance",
                               STM::squareroot (STM::eps ()));
  const int maxNumIters = inputList.get("Maximum Iterations", 200);
  const int num_steps = inputList.get("Number of Time Steps", 1);
  if (gpu) {
    TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total GPU Solve", total_solve);
    solveWithBelosGPU(converged, numItersPerformed, tol, maxNumIters, num_steps,
                      ranks_per_node, gpu_ranks_per_node, device_offset,
                      prec_type,
                      X, A, B, Teuchos::null, M);
  }
  else {
    TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Solve", total_solve);
    solveWithBelos (converged, numItersPerformed, tol, maxNumIters, num_steps,
                    X, A, B, Teuchos::null, M);
  }

  // Compute ||X-X_exact||_2
  MT norm_x = X_exact->norm2();
  X_exact->update(-1.0, *X, 1.0);
  MT norm_error = X_exact->norm2();
  *out << endl
       << "||X-X_exact||_2 / ||X_exact||_2 = " << norm_error / norm_x
       << endl;

  } // total time block

  // Summarize timings
  // RCP<ParameterList> reportParams = parameterList ("TimeMonitor::report");
  // reportParams->set ("Report format", std::string ("YAML"));
  // reportParams->set ("writeGlobalStats", true);
  // Teuchos::TimeMonitor::report (*out, reportParams);
  Teuchos::TimeMonitor::summarize(std::cout);

  } //try
  TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success);

  if (success)
    return EXIT_SUCCESS;
  return EXIT_FAILURE;
}