Exemple #1
0
void dspPoItemsByVendor::sFillList()
{
  _poitem->clear();

  QString sql( "SELECT pohead_id, poitem_id, pohead_number,"
               "       poitem_status,"
               "       CASE WHEN(poitem_status='C') THEN <? value(\"closed\") ?>"
               "            WHEN(poitem_status='U') THEN <? value(\"unposted\") ?>"
               "            WHEN(poitem_status='O' AND ((poitem_qty_received-poitem_qty_returned) > 0) AND (poitem_qty_ordered>(poitem_qty_received-poitem_qty_returned))) THEN <? value(\"partial\") ?>"
               "            WHEN(poitem_status='O' AND ((poitem_qty_received-poitem_qty_returned) > 0) AND (poitem_qty_ordered<=(poitem_qty_received-poitem_qty_returned))) THEN <? value(\"received\") ?>"
               "            WHEN(poitem_status='O') THEN <? value(\"open\") ?>"
               "            ELSE poitem_status"
               "       END AS poitemstatus,"
               "       CASE WHEN (itemsite_id IS NULL) THEN ( SELECT warehous_code"
               "                                              FROM warehous"
               "                                              WHERE (pohead_warehous_id=warehous_id) )"
               "            ELSE ( SELECT warehous_code"
               "                   FROM warehous"
               "                   WHERE (itemsite_warehous_id=warehous_id) )"
               "       END AS warehousecode,"
               "       COALESCE(item_number, <? value(\"nonInv\") ?>) AS itemnumber,"
               "       COALESCE(item_descrip1, firstLine(poitem_vend_item_descrip)) AS itemdescrip,"
               "       poitem_vend_item_number,"
               "       COALESCE(uom_name, poitem_vend_uom) AS itemuom,"
               "       poitem_duedate, poitem_qty_ordered, poitem_qty_received, poitem_qty_returned,"
               "       CASE WHEN (poitem_duedate < CURRENT_DATE) THEN 'error' END AS poitem_duedate_qtforegroundrole,"
               "       'qty' AS poitem_qty_ordered_xtnumericrole,"
               "       'qty' AS poitem_qty_received_xtnumericrole,"
               "       'qty' AS poitem_qty_returned_xtnumericrole "
               "FROM pohead,"
               "     poitem LEFT OUTER JOIN"
               "     ( itemsite JOIN item"
               "       ON (itemsite_item_id=item_id) JOIN uom ON (item_inv_uom_id=uom_id))"
               "     ON (poitem_itemsite_id=itemsite_id) "
               "WHERE ((poitem_pohead_id=pohead_id)"
               "<? if exists(\"warehous_id\") ?>"
               " AND (((itemsite_id IS NULL) AND"
               "       (pohead_warehous_id=<? value(\"warehous_id\") ?>) ) OR"
               "      ((itemsite_id IS NOT NULL) AND"
               "       (itemsite_warehous_id=<? value(\"warehous_id\") ?>) ) )"
               "<? endif ?>"
               "<? if exists(\"agentUsername\") ?>"
               " AND (pohead_agent_username=<? value(\"agentUsername\") ?>)"
               "<? endif ?>"
               "<? if exists(\"poNumber\") ?>"
               " AND (pohead_number=<? value(\"poNumber\") ?>)"
               "<? endif ?>"
               "<? if exists(\"openItems\") ?>"
               " AND (poitem_status='O')"
               "<? endif ?>"
               "<? if exists(\"closedItems\") ?>"
               " AND (poitem_status='C')"
               "<? endif ?>"
               " AND (pohead_vend_id=<? value(\"vend_id\") ?>) ) "
               "ORDER BY poitem_duedate, pohead_number, poitem_linenumber;" );
  ParameterList params;
  setParams(params);
  MetaSQLQuery mql(sql);
  q = mql.toQuery(params);
  if (q.first())
  {
    _poitem->populate(q, true);
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
XmlRpcPackage *XmlRpcPackage::setParams(const QDomElement &element) {
    return setParams(parseXmlRpcParams(element));
}
bool NeuralNet::loadNet( const char * filename )
{
  // check for existing layers
  if( numLayers() != 0 )
  {
    return false;
  }

  std::ifstream inp;
  assert(inp);
  inp.open(filename, std::ios::in);

  // load network parameters
  unsigned int loadLayers = 0;
  double learnRate = 0.0;
  double mom = 0.0;
  double decay = 0.0;
  unsigned int outType = 0;
  inp >> loadLayers;
  inp >> learnRate;
  inp >> mom;
  inp >> decay;
  inp >> outType;
  setParams(learnRate,mom,decay,outType);

  // construct network
  for(unsigned int m=0;m<loadLayers;++m)
  {
    unsigned int type = 0;
    inp >> type;
    unsigned int inputs = 0;
    inp >> inputs;
    unsigned int nodes = 0;
    inp >> nodes;
    std::vector<std::vector<double> > weights(inputs+1,std::vector<double>(nodes,0.0));
    for(unsigned int i=0;i<inputs+1;++i)
    {
      for(unsigned int j=0;j<nodes;++j)
      {
        inp >> weights[i][j];
      }
    }
    NeuralLayer * pHiddenLayer = nullptr;
    switch(type)
    {
      case(LINEAR):
      pHiddenLayer = new NeuralLinearLayer(inputs,nodes);
      break;
      case(TANH):
      pHiddenLayer = new NeuralTanhLayer(inputs,nodes);
      break;
      case(SIGMOID):
      pHiddenLayer = new NeuralSigmoidLayer(inputs,nodes);
      break;
      case(SOFTMAX):
      pHiddenLayer = new NeuralSoftmaxLayer(inputs,nodes);
      break;
    }
    pHiddenLayer->loadWeights(weights);
    addLayer( pHiddenLayer );
  }

  inp.close();
  return true;

}
WareParamsTree::WareParamsTree(const WareParams_t& Params)
{
  setParams(Params);
}
Exemple #5
0
int driver(const char* szFileStub, int nKStart, int nLMin, unsigned long lSeed, int nMaxIter, double dEpsilon, int bCOut)
{
  t_Params           tParams;
  t_Data             tData;
  gsl_rng            *ptGSLRNG     = NULL;
  const gsl_rng_type *ptGSLRNGType = NULL;
  int i = 0, k = 0, nD = 0, nN = 0;
  char szOFile[MAX_FILE_NAME_LENGTH];
  FILE *ofp = NULL;
  t_VBParams tVBParams;
  t_Cluster  *ptBestCluster = NULL;
  gsl_matrix *ptTemp = NULL;
  gsl_matrix *ptTVar = NULL;
  /*initialise GSL RNG*/
  gsl_rng_env_setup();

  gsl_set_error_handler_off();
  
  ptGSLRNGType = gsl_rng_default;
  ptGSLRNG     = gsl_rng_alloc(ptGSLRNGType);
  
  /*get command line params*/
  tParams.nKStart  = nKStart;
  tParams.nLMin    = nLMin;
  tParams.nMaxIter = nMaxIter;
  tParams.dEpsilon = dEpsilon;
  tParams.lSeed    = lSeed;

  setParams(&tParams,szFileStub);

  /*read in input data*/
  readInputData(tParams.szInputFile, &tData);

  readPInputData(tParams.szPInputFile, &tData);

  nD = tData.nD;
  nN = tData.nN;

  ptTemp = gsl_matrix_alloc(tData.nT,nD);
  ptTVar = gsl_matrix_alloc(tData.nT,tData.nT);

  setVBParams(&tVBParams, &tData);
  
  ptBestCluster = (t_Cluster *) malloc(sizeof(t_Cluster));

  ptBestCluster->nN = nN;
  ptBestCluster->nK = tParams.nKStart;
  ptBestCluster->nD = nD;
  ptBestCluster->ptData = &tData;
  ptBestCluster->ptVBParams = &tVBParams;
  ptBestCluster->lSeed = tParams.lSeed;
  ptBestCluster->nMaxIter = tParams.nMaxIter;
  ptBestCluster->dEpsilon = tParams.dEpsilon;

  if(bCOut > 0){
	ptBestCluster->szCOutFile = szFileStub;
  }
  else{
	ptBestCluster->szCOutFile = NULL;
  }
  runRThreads((void *) &ptBestCluster);

  compressCluster(ptBestCluster);

  calcCovarMatrices(ptBestCluster,&tData);

  sprintf(szOFile,"%sclustering_gt%d.csv",tParams.szOutFileStub,tParams.nLMin);
  writeClusters(szOFile,ptBestCluster,&tData);

  sprintf(szOFile,"%spca_means_gt%d.csv",tParams.szOutFileStub,tParams.nLMin);
  writeMeans(szOFile,ptBestCluster);

  sprintf(szOFile,"%smeans_gt%d.csv",tParams.szOutFileStub,tParams.nLMin);
  writeTMeans(szOFile,ptBestCluster,&tData);

  for(k = 0; k < ptBestCluster->nK; k++){
    sprintf(szOFile,"%spca_variances_gt%d_dim%d.csv",tParams.szOutFileStub,tParams.nLMin,k);
    
    writeSquareMatrix(szOFile, ptBestCluster->aptSigma[k], nD);
  
    /*not entirely sure this is correct?*/
    gsl_blas_dgemm (CblasNoTrans,CblasNoTrans,1.0,tData.ptTMatrix,ptBestCluster->aptSigma[k],0.0,ptTemp);
  
    gsl_blas_dgemm (CblasNoTrans,CblasTrans,1.0,ptTemp,tData.ptTMatrix,0.0,ptTVar);

    sprintf(szOFile,"%svariances_gt%d_dim%d.csv",tParams.szOutFileStub,tParams.nLMin,k);

    writeSquareMatrix(szOFile, ptTVar, nD);
  }

  sprintf(szOFile,"%sresponsibilities.csv",tParams.szOutFileStub);

  ofp = fopen(szOFile,"w");
  if(ofp){    

    for(i = 0; i < nN; i++){
      for(k = 0; k < ptBestCluster->nK - 1; k++){
	fprintf(ofp,"%f,",ptBestCluster->aadZ[i][k]);
      }
      fprintf(ofp,"%f\n",ptBestCluster->aadZ[i][ptBestCluster->nK - 1]);
    }

    fclose(ofp);
  }
  else{
    fprintf(stderr,"Failed openining %s in main\n", szOFile);
    fflush(stderr);
  }

  sprintf(szOFile,"%svbl.csv",tParams.szOutFileStub);

  ofp = fopen(szOFile,"w");
  if(ofp){    
    fprintf(ofp,"%d,%f,%d\n",ptBestCluster->nK,ptBestCluster->dVBL,ptBestCluster->nThread);

    fclose(ofp);
  }
  else{
    fprintf(stderr,"Failed openining %s in main\n", szOFile);
    fflush(stderr);
  }

  /*free up memory in data object*/
  destroyData(&tData);

  /*free up best BIC clusters*/

  destroyCluster(ptBestCluster);
  free(ptBestCluster);

  destroyParams(&tParams);
  gsl_rng_free(ptGSLRNG);
  gsl_matrix_free(tVBParams.ptInvW0);
  gsl_matrix_free(ptTemp);
  gsl_matrix_free(ptTVar);

  return EXIT_SUCCESS;
}
Exemple #6
0
void dspGLSeries::sFillList()
{
  ParameterList params;
  if (! setParams(params))
    return;

  MetaSQLQuery mql("SELECT *, "
                   "       CASE WHEN gltrans_id = -1 THEN 0"
                   "       ELSE 1 END AS xtindentrole,"
                   "       CASE WHEN gltrans_id = -1 THEN gltrans_date"
                   "       END AS transdate,"    // qtdisplayrole isn't working?
                   "       'curr' AS debit_xtnumericrole,"
                   "       'curr' AS credit_xtnumericrole "
                   "FROM (SELECT DISTINCT "
                   "       gltrans_sequence, -1 AS gltrans_id, gltrans_date, "
                   "       gltrans_source, gltrans_journalnumber,"
                   "       gltrans_doctype, '' AS gltrans_docnumber,"
                   "       firstLine(gltrans_notes) AS account,"
                   "       0.0 AS gltrans_amount,"
                   "       CAST(NULL AS NUMERIC) AS debit,"
                   "       CAST(NULL AS NUMERIC) AS credit,"
                   "       gltrans_posted "
                   "FROM gltrans "
                   "WHERE ((gltrans_date BETWEEN <? value(\"startDate\") ?>"
                   "                         AND <? value(\"endDate\") ?>)"
                   "<? if exists(\"source\") ?>"
                   "   AND (gltrans_source=<? value(\"source\") ?>)"
                   "<? endif ?>"
                   "<? if exists(\"startJrnlnum\") ?>"
                   "   AND (gltrans_journalnumber BETWEEN <? value(\"startJrnlnum\") ?>"
                   "                                  AND <? value(\"endJrnlnum\") ?>)"
                   "<? endif ?>"
                   ")"
                   "UNION "
                   "SELECT gltrans_sequence, gltrans_id, gltrans_date, "
                   "       NULL, NULL,"
                   "       NULL, gltrans_docnumber,"
                   "       (formatGLAccount(accnt_id) || ' - ' || accnt_descrip) AS account,"
                   "       gltrans_amount,"
                   "       CASE WHEN (gltrans_amount < 0) THEN (gltrans_amount * -1)"
                   "       END AS debit,"
                   "       CASE WHEN (gltrans_amount > 0) THEN gltrans_amount"
                   "       END AS credit,"
                   "       NULL AS gltrans_posted "
                   "FROM gltrans JOIN accnt ON (gltrans_accnt_id=accnt_id)"
                   "WHERE ((gltrans_date BETWEEN <? value(\"startDate\") ?>"
                   "                         AND <? value(\"endDate\") ?>)"
                   "<? if exists(\"source\") ?>"
                   "   AND (gltrans_source=<? value(\"source\") ?>)"
                   "<? endif ?>"
                   "<? if exists(\"startJrnlnum\") ?>"
                   "   AND (gltrans_journalnumber BETWEEN <? value(\"startJrnlnum\") ?>"
                   "                                  AND <? value(\"endJrnlnum\") ?>)"
                   "<? endif ?>"
                   " ) "
                   ") AS dummy "
                   "ORDER BY gltrans_date, gltrans_sequence,"
                   "         xtindentrole, gltrans_amount;");
  q = mql.toQuery(params);
  _gltrans->populate(q, true);
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Exemple #7
0
void dspTodoByUserAndIncident::sFillList()
{
  if (_selectedIncident->isChecked() && _incident->id() <= 0)
  {
    QMessageBox::critical(this, tr("No Incident"),
			  tr("Please select an Incident before Querying."),
			  QMessageBox::Ok, QMessageBox::NoButton);
    _incident->setFocus();
    return;
  }

  _todoitem->clear();

  // explicitly get todoitem_id and incdt_id first to set id() and altId()
  QString sql = "SELECT todoitem_id, incdt_id, *,"
		"       firstLine(todoitem_description) AS todoitem_description,"
                "  CASE WHEN (todoitem_status != 'C' AND todoitem_due_date < CURRENT_DATE) THEN 'expired'"
                "       WHEN (todoitem_status != 'C' AND todoitem_due_date > CURRENT_DATE) THEN 'future'"
                "  END AS todoitem_due_date_qtforegroundrole "
	        "FROM usr, todoitem LEFT OUTER JOIN"
	        "     incdt ON (todoitem_incdt_id = incdt_id) "
	        "WHERE ((usr_id=todoitem_usr_id)"
		"<? if not exists(\"showInactive\") ?>"
		"  AND todoitem_active "
		"<? endif ?>"
		"<? if not exists(\"showCompleted\") ?>"
		"  AND todoitem_status != 'C' "
		"<? endif ?>"
		"<? if exists(\"usr_id\") ?>"
		"  AND (usr_id=<? value(\"usr_id\") ?>)"
		"<? elseif exists(\"usr_pattern\") ?>"
		"  AND (usr_username ~* <? value(\"usr_pattern\") ?>)"
		"<? endif ?>"
		"<? if exists(\"incdt_id\") ?>"
		"  AND (todoitem_incdt_id=<? value(\"incdt_id\") ?>)"
		"<? endif ?>"
		"<? if exists(\"start_date_start\") ?>"
		"  AND (todoitem_start_date>=<? value(\"start_date_start\") ?>)"
		"<? endif ?>"
		"<? if exists(\"start_date_end\") ?>"
		"  AND (todoitem_start_date<=<? value(\"start_date_end\") ?>)"
		"<? endif ?>"
		"<? if exists(\"due_date_start\") ?>"
		"  AND (todoitem_due_date>=<? value(\"due_date_start\") ?>)"
		"<? endif ?>"
		"<? if exists(\"due_date_end\") ?>"
		"  AND (todoitem_due_date<=<? value(\"due_date_end\") ?>)"
		"<? endif ?>"
		") "
	        "ORDER BY usr_username, todoitem_seq;" ;
  ParameterList params;
  setParams(params);

  MetaSQLQuery mql(sql);
  XSqlQuery todos = mql.toQuery(params);
  _todoitem->populate(todos);
  if (todos.lastError().type() != QSqlError::None)
  {
    systemError(this, todos.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Exemple #8
0
void dspPoItemsByDate::sFillList()
{
  _poitem->clear();

  QString sql( "SELECT pohead_id, poitem_id, pohead_number,"
               "       CASE WHEN (itemsite_id IS NULL) THEN ( SELECT warehous_code"
               "                                              FROM warehous"
               "                                              WHERE (pohead_warehous_id=warehous_id) )"
               "            ELSE ( SELECT warehous_code"
               "                   FROM warehous"
               "                   WHERE (itemsite_warehous_id=warehous_id) )"
               "       END AS warehousecode,"
	       "       poitem_status,"
               "       CASE WHEN(poitem_status='C') THEN <? value(\"closed\") ?>"
               "            WHEN(poitem_status='U') THEN <? value(\"unposted\") ?>"
               "            WHEN(poitem_status='O' AND ((poitem_qty_received-poitem_qty_returned) > 0) AND (poitem_qty_ordered>(poitem_qty_received-poitem_qty_returned))) THEN <? value(\"partial\") ?>"
               "            WHEN(poitem_status='O' AND ((poitem_qty_received-poitem_qty_returned) > 0) AND (poitem_qty_ordered=(poitem_qty_received-poitem_qty_returned))) THEN <? value(\"received\") ?>"
               "            WHEN(poitem_status='O') THEN <? value(\"open\") ?>"
               "            ELSE poitem_status"
               "       END AS poitemstatus,"
               "       vend_name,"
               "       formatDate(poitem_duedate) AS f_duedate,"
               "       COALESCE(item_number, (<? value(\"nonInv\") ?> || poitem_vend_item_number)) AS itemnumber,"
               "       COALESCE(item_descrip1, firstLine(poitem_vend_item_descrip)) AS itemdescrip,"
               "       COALESCE(uom_name, poitem_vend_uom) AS itemuom,"
               "       formatQty(poitem_qty_ordered) AS f_qtyordered,"
               "       formatQty(poitem_qty_received) AS f_qtyreceived,"
               "       formatQty(poitem_qty_returned) AS f_qtyreturned,"
               "       (poitem_duedate < CURRENT_DATE) AS late "
               "FROM pohead, vend,"
               "     poitem LEFT OUTER JOIN"
               "     ( itemsite JOIN item"
               "       ON (itemsite_item_id=item_id) JOIN uom ON (item_inv_uom_id=uom_id))"
               "     ON (poitem_itemsite_id=itemsite_id) "
               "WHERE ((poitem_pohead_id=pohead_id)"
               " AND (pohead_vend_id=vend_id)"
               " AND (poitem_duedate BETWEEN <? value(\"startDate\") ?> AND <? value(\"endDate\") ?>)"
	       "<? if exists(\"warehous_id\") ?>"
	       " AND (((itemsite_id IS NULL) AND"
	       "       (pohead_warehous_id=<? value(\"warehous_id\") ?>)) OR"
	       "      ((itemsite_id IS NOT NULL) AND"
	       "       (itemsite_warehous_id=<? value(\"warehous_id\") ?>)))"
	       "<? endif ?>"
	       "<? if exists(\"agentUsername\") ?>"
	       " AND (pohead_agent_username=<? value(\"agentUsername\") ?>)"
	       "<? endif ?>"
	       "<? if exists(\"openItems\") ?>"
	       " AND (poitem_status='O')"
	       "<? endif ?>"
	       "<? if exists(\"closedItems\") ?>"
	       " AND (poitem_status='C')"
	       "<? endif ?>"
	       ") "
	       "ORDER BY poitem_duedate;" );

  ParameterList params;
  setParams(params);

  MetaSQLQuery mql(sql);
  q = mql.toQuery(params);
  if (q.first())
  {
    XTreeWidgetItem *last = 0;
    do
    {
      last = new XTreeWidgetItem(_poitem, last,
				 q.value("pohead_id").toInt(),
				 q.value("poitem_id").toInt(),
				 q.value("pohead_number"),
				 q.value("warehousecode"),
				 q.value("poitemstatus"), q.value("vend_name"),
				 q.value("f_duedate"), q.value("itemnumber"), 
				 q.value("itemdescrip"), q.value("itemuom"),
				 q.value("f_qtyordered"),
				 q.value("f_qtyreceived"),
				 q.value("f_qtyreturned") );
      last->setText(POITEM_STATUS_COL, q.value("poitem_status").toString());
      if (q.value("late").toBool())
        last->setTextColor(4, "red");
    }
    while (q.next());
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Exemple #9
0
void dspCostedIndentedBOM::sFillList()
{
  if (! _item->isValid())
    return;

  MetaSQLQuery mql( "SELECT bomdata_bomwork_id AS id,"
                    "       CASE WHEN bomdata_bomwork_parent_id = -1 AND "
                    "                 bomdata_bomwork_id = -1 THEN"
                    "                     -1"
                    "            ELSE bomdata_item_id"
                    "       END AS altid,"
                    "       *,"
                    "<? if exists(\"useStandardCosts\") ?>"
                    "       bomdata_stdunitcost AS unitcost,"
                    "       bomdata_stdextendedcost AS extendedcost, "
                    "<? elseif exists(\"useActualCosts\") ?>"
                    "       bomdata_actunitcost AS unitcost,"
                    "       bomdata_actextendedcost AS extendedcost, "
                    "<? endif ?>"
                    "       'qtyper' AS bomdata_qtyper_xtnumericrole,"
                    "       'percent' AS bomdata_scrap_xtnumericrole,"
                    "       'cost' AS unitcost_xtnumericrole,"
                    "       'cost' AS extendedcost_xtnumericrole,"
                    "       CASE WHEN COALESCE(bomdata_effective, startOfTime()) <= startOfTime() THEN <? value(\"always\") ?> END AS bomdata_effective_qtdisplayrole,"
                    "       CASE WHEN COALESCE(bomdata_expires, endOfTime()) <= endOfTime() THEN <? value(\"never\") ?> END AS bomdata_expires_qtdisplayrole,"
                    "       CASE WHEN bomdata_expired THEN 'expired'"
                    "            WHEN bomdata_future  THEN 'future'"
                    "       END AS qtforegroundrole,"
                    "       bomdata_bomwork_level - 1 AS xtindentrole "
                    "FROM indentedbom(<? value(\"item_id\") ?>,"
                    "                 <? value(\"revision_id\") ?>,0,0)");
  ParameterList params;
  if (! setParams(params))
    return;
  q = mql.toQuery(params);
  _bomitem->populate(q, true);
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  q.prepare( "SELECT formatCost(SUM(bomdata_actextendedcost)) AS actextendedcost,"
             "       formatCost(SUM(bomdata_stdextendedcost)) AS stdextendedcost,"
             "       formatCost(actcost(:item_id)) AS actual,"
             "       formatCost(stdcost(:item_id)) AS standard "
             "FROM indentedbom(:item_id,"
             "                 :revision_id,0,0)"
             "WHERE (bomdata_bomwork_level=1) "
             "GROUP BY actual, standard;" );
  q.bindValue(":item_id", _item->id());
  q.bindValue(":revision_id",_revision->id());
  q.exec();
  if (q.first())
  {
    XTreeWidgetItem *last = new XTreeWidgetItem(_bomitem, -1, -1);
    last->setText(0, tr("Total Cost"));
    if(_useStandardCosts->isChecked())
      last->setText(9, q.value("stdextendedcost").toString());
    else
      last->setText(9, q.value("actextendedcost").toString());

    last = new XTreeWidgetItem( _bomitem, -1, -1);
    last->setText(0, tr("Actual Cost"));
    last->setText(9, q.value("actual").toString());

    last = new XTreeWidgetItem( _bomitem, -1, -1);
    last->setText(0, tr("Standard Cost"));
    last->setText(9, q.value("standard").toString());
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  _bomitem->expandAll();
}
Exemple #10
0
void BOM::sFillList(int pItemid, bool)
{
  if (_item->isValid() && (pItemid == _item->id()))
  {
    q.prepare( "SELECT * "
               "FROM bomhead "
               "WHERE ( (bomhead_item_id=:item_id) "
			   "AND (bomhead_rev_id=:revision_id) );" );
    q.bindValue(":item_id", _item->id());
	q.bindValue(":revision_id", _revision->id());
    q.exec();
    if (q.first())
    {
      _documentNum->setText(q.value("bomhead_docnum"));
	  _revision->setNumber(q.value("bomhead_revision").toString());
      _revisionDate->setDate(q.value("bomhead_revisiondate").toDate());
      _batchSize->setDouble(q.value("bomhead_batchsize").toDouble());
      if(q.value("bomhead_requiredqtyper").toDouble()!=0)
      {
        _doRequireQtyPer->setChecked(true);
        _requiredQtyPer->setDouble(q.value("bomhead_requiredqtyper").toDouble());
      }
      if (_revision->description() == "Inactive")
	  {
		  _save->setEnabled(FALSE);
	      _new->setEnabled(FALSE);
		  _documentNum->setEnabled(FALSE);
		  _revisionDate->setEnabled(FALSE);
		  _batchSize->setEnabled(FALSE);
		  _bomitem->setEnabled(FALSE);
	  }

	  if ((_revision->description() == "Pending") || (_revision->description() == "Active"))
	  {
		  _save->setEnabled(TRUE);
	      _new->setEnabled(TRUE);
		  _documentNum->setEnabled(TRUE);
		  _revisionDate->setEnabled(TRUE);
		  _batchSize->setEnabled(TRUE);
		  _bomitem->setEnabled(TRUE);
	  }
    }
    else
    {
      _documentNum->clear();
      _revisionDate->clear();
      _batchSize->clear();
    }
    
    ParameterList params;
    setParams(params);
    
    MetaSQLQuery mql = mqlLoad("bomItems", "detail");
    q = mql.toQuery(params);
    _bomitem->populate(q);
    if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    
    MetaSQLQuery picklistmql("SELECT item_picklist,"
          "       COUNT(*) AS total,"
          "       COALESCE(SUM(bomitem_qtyper * (1 + bomitem_scrap))) AS qtyper "
          "FROM bomitem(<? value(\"item_id\") ?>,"
          "             <? value(\"revision_id\") ?>), item "
          "WHERE ( (bomitem_item_id=item_id)"
          "<? if not exists(\"showExpired\") ?>"
          " AND (bomitem_expires > CURRENT_DATE)"
          "<? endif ?>"
          "<? if not exists(\"showFuture\") ?>"
          " AND (bomitem_effective <= CURRENT_DATE)"
          "<? endif ?>"
          " ) "
          "GROUP BY item_picklist;");
    q = picklistmql.toQuery(params);
    
    bool   foundPick    = FALSE;
    bool   foundNonPick = FALSE;
    int    totalNumber  = 0;
    double totalQtyPer  = 0.0;
    while (q.next())
    {
      totalNumber += q.value("total").toInt();
      totalQtyPer += q.value("qtyper").toDouble();
      
      if (q.value("item_picklist").toBool())
      {
        foundPick = TRUE;
        _pickNumber->setDouble(q.value("total").toDouble());
        _pickQtyPer->setDouble(q.value("qtyper").toDouble());
      }
      else
      {
        foundNonPick = TRUE;
        _nonPickNumber->setDouble(q.value("total").toDouble());
        _nonPickQtyPer->setDouble(q.value("qtyper").toDouble());
      }
    }
    if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    
    if (!foundPick)
    {
      _pickNumber->setDouble(0);
      _pickQtyPer->setDouble(0.0);
    }
    
    if (!foundNonPick)
    {
      _nonPickNumber->setDouble(0);
      _nonPickQtyPer->setDouble(0.0);
    }
    
    _totalNumber->setDouble(totalNumber);
    _totalQtyPer->setDouble(totalQtyPer);
    _totalQtyPerCache = totalQtyPer;
    
    if (_privileges->check("ViewCosts"))
    {
      MetaSQLQuery costsmql("SELECT p.item_maxcost,"
            "       COALESCE(SUM(itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL, bomitem_qtyper * (1 + bomitem_scrap)) * stdCost(c.item_id))) AS stdcost,"
            "       COALESCE(SUM(itemuomtouom(bomitem_item_id, bomitem_uom_id, NULL, bomitem_qtyper * (1 + bomitem_scrap)) * ROUND(actCost(c.item_id),4))) AS actcost "
            "FROM bomitem(<? value(\"item_id\") ?>,"
            "             <? value(\"revision_id\") ?>), item AS c, item AS p "
            "WHERE ( (bomitem_item_id=c.item_id)"
            " AND (p.item_id=<? value(\"item_id\") ?>)"
            "<? if not exists(\"showExpired\") ?>"
            " AND (bomitem_expires > CURRENT_DATE)"
            "<? endif ?>"
            "<? if not exists(\"showFuture\") ?>"
            " AND (bomitem_effective <= CURRENT_DATE)"
            "<? endif ?>"
            " ) "
            "GROUP BY p.item_maxcost;");
      q = costsmql.toQuery(params);
      if (q.first())
      {
        _currentStdCost->setDouble(q.value("stdcost").toDouble());
        _currentActCost->setDouble(q.value("actcost").toDouble());
        _maxCost->setDouble(q.value("item_maxcost").toDouble());
      }
      if (q.lastError().type() != QSqlError::NoError)
      {
        systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
    }
  }
  else if (!_item->isValid())
  {
    _documentNum->clear();
    _revision->clear();
    _revisionDate->clear();
    _batchSize->clear();
    
    _bomitem->clear();
  }
}
Exemple #11
0
void boo::sFillList()
{
  if (_item->itemType() == "J")
  {
    _closeWO->setEnabled(FALSE);
    _closeWO->setChecked(FALSE);
  }

  int locid = _finalLocation->id();
  q.prepare("SELECT location_id, (warehous_code || '-' || formatLocationName(location_id)) AS locationname"
            "  FROM location, warehous"
            " WHERE ( (NOT location_restrict)"
            "   AND   (location_warehous_id=warehous_id) ) "
            "UNION "
            "SELECT location_id, (warehous_code || '-' || formatLocationName(location_id)) AS locationname"
            "  FROM location, warehous, locitem"
            " WHERE ( (location_warehous_id=warehous_id)"
            "   AND   (location_restrict)"
            "   AND   (locitem_location_id=location_id)"
            "   AND   (locitem_item_id=:item_id) ) "
            "ORDER BY locationname;");
  q.bindValue(":item_id", _item->id());
  q.exec();
  _finalLocation->populate(q, locid);

  q.prepare( "SELECT boohead_id, boohead_docnum, boohead_revision,"
             "       boohead_revisiondate, boohead_final_location_id,"
             "       boohead_closewo "
             "FROM boohead "
             "WHERE ((boohead_item_id=:item_id) "
             "AND (boohead_rev_id=:revision_id));" );
  q.bindValue(":item_id", _item->id());
  q.bindValue(":revision_id", _revision->id());
  q.exec();
  if (q.first())
  {
    _booheadid = q.value("boohead_id").toInt();
    _documentNum->setText(q.value("boohead_docnum").toString());
    _revision->setNumber(q.value("boohead_revision").toString());
    _revisionDate->setDate(q.value("boohead_revisiondate").toDate());
    _finalLocation->setId(q.value("boohead_final_location_id").toInt());
    _closeWO->setChecked(q.value("boohead_closewo").toBool());
  }

  if (_revision->description() == "Inactive")
  {
	  _save->setEnabled(FALSE);
          _new->setEnabled(FALSE);
	  _documentNum->setEnabled(FALSE);
	  _revisionDate->setEnabled(FALSE);
	  _closeWO->setEnabled(FALSE);
	  _finalLocation->setEnabled(FALSE);
	  _booitem->setEnabled(FALSE);
  }

  if ((_revision->description() == "Pending") || (_revision->description() == "Active"))
  {
	  _save->setEnabled(TRUE);
          _new->setEnabled(TRUE);
	  _documentNum->setEnabled(TRUE);
	  _revisionDate->setEnabled(TRUE);
	  _closeWO->setEnabled(TRUE);
	  _finalLocation->setEnabled(TRUE);
	  _booitem->setEnabled(TRUE);
  }

  q.prepare( "SELECT MAX(booitem_execday) AS leadtime "
             "FROM booitem(:item_id,:revision_id);" );
  q.bindValue(":item_id", _item->id());
  q.bindValue(":revision_id",_revision->id());
  q.exec();
  if (q.first())
    _productionLeadTime->setText(q.value("leadtime").toString());

  QString sql( "SELECT booitem_id, booitem_seqnumber,"
               "       COALESCE(stdopn_number, <? value(\"none\")?> ) AS f_stdopnnumber,"
               "       wrkcnt_code, (booitem_descrip1 || ' ' || booitem_descrip2) AS description,"
               "       booitem_effective, booitem_expires,"
               "       booitem_execday,"
	       "       CASE WHEN (booitem_configtype<>'N') THEN 'emphasis'"
               "            WHEN (booitem_expires < CURRENT_DATE) THEN 'expired'"
               "            WHEN (booitem_effective >= CURRENT_DATE) THEN 'future'"
               "       END AS qtforegroundrole,"
	       "       CASE WHEN COALESCE(booitem_effective, startOfTime()) ="
               "                 startOfTime() THEN 'Always'"
	       "       END AS booitem_effective_qtdisplayrole,"
	       "       CASE WHEN COALESCE(booitem_expires, endOfTime()) >="
               "                 endOfTime() THEN 'Never'"
	       "       END AS booitem_expires_qtdisplayrole "
               "FROM wrkcnt,"
	       "     booitem(<? value(\"item_id\") ?>,<? value(\"revision_id\") ?>) LEFT OUTER JOIN stdopn ON (booitem_stdopn_id=stdopn_id) "
               "WHERE ((booitem_wrkcnt_id=wrkcnt_id)"
	       "<? if not exists(\"showExpired\") ?> "
	       " AND (booitem_expires > CURRENT_DATE)"
	       "<? endif ?>"
	       "<? if not exists(\"showFuture\") ?> "
	       " AND (booitem_effective <= CURRENT_DATE)"
	       "<? endif ?>"
	       ") "
	       "ORDER BY booitem_seqnumber, booitem_effective" );
  MetaSQLQuery mql(sql);
  ParameterList params;
  if (! setParams(params))
    return;
  q = mql.toQuery(params);
  _booitem->populate(q, true);
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Exemple #12
0
void enterPoReceipt::sPost()
{
  ParameterList params;	// shared by several queries
  setParams(params);

  QString checks = "SELECT SUM(qtyToReceive(recv_order_type,"
		   "                        recv_orderitem_id)) AS qtyToRecv "
		   "FROM recv, orderitem "
		   "WHERE ((recv_order_type=<? value(\"ordertype\") ?>)"
		   "  AND  (recv_orderitem_id=orderitem_id)"
		   "  AND  (orderitem_orderhead_id=<? value(\"orderid\") ?>));";
  MetaSQLQuery checkm(checks);
  q = checkm.toQuery(params);
  if (q.first())
  {
    if (q.value("qtyToRecv").toDouble() == 0)
    {
      QMessageBox::critical(this, tr("Nothing selected for Receipt"),
			    tr("<p>No Line Items have been selected "
			       "for receipt. Select at least one Line Item and "
			       "enter a Receipt before trying to Post."));
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

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

  q.exec("BEGIN;");	// because of possible insertgltransaction failures
  QString posts = "SELECT postReceipts(<? value (\"ordertype\") ?>,"
		  "                    <? value(\"orderid\") ?>,0) AS result;" ;
  MetaSQLQuery postm(posts);
  q = postm.toQuery(params);
  if (q.first())
  {
    int result = q.value("result").toInt();
    if (result < 0)
    {
      rollback.exec();
      systemError(this, storedProcErrorLookup("postReceipts", result),
		  __FILE__, __LINE__);
      return;
    }

    QString lotnum = QString::null;
    QDate expdate = omfgThis->startOfTime();
    QDate warrdate;
    if(result > 0 && _singleLot->isChecked())
    {
      // first find out if we have any lot controlled items that need distribution
      q.prepare("SELECT count(*) AS result"
                "  FROM itemlocdist, itemsite"
                " WHERE ((itemlocdist_itemsite_id=itemsite_id)"
                "   AND  (itemlocdist_reqlotserial)"
                "   AND  (itemsite_controlmethod='L')"
                "   AND  (itemlocdist_series=:itemlocdist_series) ); ");
      q.bindValue(":itemlocdist_series", result);
      q.exec();
      // if we have any then ask for a lot# and optionally expiration date.
      if(q.first() && (q.value("result").toInt() > 0) )
      {
        getLotInfo newdlg(this, "", TRUE);

        // find out if any itemsites that are lot controlled are perishable
        q.prepare("SELECT itemsite_perishable,itemsite_warrpurc"
            "  FROM itemlocdist, itemsite"
            " WHERE ((itemlocdist_itemsite_id=itemsite_id)"
            "   AND  (itemlocdist_series=:itemlocdist_series) ); ");
        q.bindValue(":itemlocdist_series", result);
        q.exec();
        if(q.first())
        {
          newdlg.enableExpiration(q.value("itemsite_perishable").toBool()); 
          newdlg.enableWarranty(q.value("itemsite_warrpurc").toBool());
        }

          if(newdlg.exec() == XDialog::Accepted)
          {
            lotnum = newdlg.lot();
            expdate = newdlg.expiration();
            warrdate = newdlg.warranty();
          }
        }
        else if (q.lastError().type() != QSqlError::None)
        {
          systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
          rollback.exec();
          return;
        }
      }

      if (distributeInventory::SeriesAdjust(result, this, lotnum, expdate, warrdate) == XDialog::Rejected)
      {
        QMessageBox::information( this, tr("Enter Receipts"), tr("Post Canceled") );
        rollback.exec();
        return;
      }
    
      q.exec("COMMIT;");
      
      // TODO: update this to sReceiptsUpdated?
      omfgThis->sPurchaseOrderReceiptsUpdated();
      
      if (_captive)
      {
        _orderitem->clear();
        close();
      }
      else
      {
        _order->setId(-1);
        _close->setText(tr("&Close"));
      }
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      rollback.exec();
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else // select succeeded but returned no rows
      q.exec("COMMIT;");
}
bool ArUrg_2_0::internalConnect(void)

{
  bool ret = true;
  char buf[1024];
  

  ArSerialConnection *serConn = NULL;
  serConn = dynamic_cast<ArSerialConnection *>(myConn);

  bool alreadyAtAutobaud = false;



  // empty the buffer...
  /*
  sendCommandAndRecvStatus(
	  "RS", "reset", 
	  buf, sizeof(buf), 1000);
  readLine(buf, sizeof(buf), 1, true, false);

  sendCommandAndRecvStatus(
	  "SCIP2.0", "SCIP 2.0 request", 
	  buf, sizeof(buf), 1000);
  */

  writeLine("RS");
  ArUtil::sleep(100);

  writeLine("SCIP2.0");
  ArUtil::sleep(100);

  ArTime startedFlushing;

  while (readLine(buf, sizeof(buf), 1, true, false) ||
	 startedFlushing.mSecSince() < 1000);

  buf[0] = '\0';

  if (!(ret = sendCommandAndRecvStatus(
		"VV", "version request", 
		buf, sizeof(buf), 10000)) || 
      strcasecmp(buf, "00") != 0)      
  {
    // if we didn't get it and have an autobaud, try it at what the autobaud rate is
    if (serConn != NULL && atoi(getAutoBaudChoice()) > 0)
    {
      alreadyAtAutobaud = true;
      serConn->setBaud(atoi(getAutoBaudChoice()));
      ArUtil::sleep(100);

      writeLine("RS");
      ArUtil::sleep(100);
      
      writeLine("SCIP2.0");
      ArUtil::sleep(100);
      
      startedFlushing.setToNow();
      while (readLine(buf, sizeof(buf), 1, true, false) ||
	     startedFlushing.mSecSince() < 1000);
      
      if (!(ret = sendCommandAndRecvStatus(
		"VV", "version request after falling back to autobaudchoice", 
		buf, sizeof(buf), 10000)) || 
	  strcasecmp(buf, "00") != 0)      
      {
	if (ret && strcasecmp(buf, "00") != 0)      
	  ArLog::log(ArLog::Normal, 
		     "%s::blockingConnect: Bad status on version response after falling back to autobaudchoice", 
		     getName());
	return false;
      }
    }
    // if we don't have a serial port or no autobaud then we can't
    // change the baud, so just fail
    else
    {
      if (ret && strcasecmp(buf, "00") != 0)      
	ArLog::log(ArLog::Normal, 
		   "%s::blockingConnect: Bad status on version response (%s)",
		   getName(), buf);
      return false;
    }
  }

  // if we want to autobaud, then give it a whirl
  if (!alreadyAtAutobaud && serConn != NULL && atoi(getAutoBaudChoice()) > 0)
  {

    // empty the buffer from the last version request
    while (readLine(buf, sizeof(buf), 100, true, false));

    // now change the baud...
    sprintf(buf, "SS%06d", atoi(getAutoBaudChoice()));
    if (!writeLine(buf))
      return false;

    ArUtil::sleep(100);

    //serConn->setBaud(115200);
    serConn->setBaud(atoi(getAutoBaudChoice()));
    // wait a second for the baud to change...
    ArUtil::sleep(100);

    // empty the buffer from the baud change
    while (readLine(buf, sizeof(buf), 100, true, false));
    
    if (!(ret = sendCommandAndRecvStatus(
		  "VV", "version request after switching to autobaudchoice", 
		  buf, sizeof(buf), 10000)) || 
	strcasecmp(buf, "00") != 0)      
    {
      if (ret && strcasecmp(buf, "00") != 0)      
	ArLog::log(ArLog::Normal, 
		   "%s::blockingConnect: Bad status on version response after switching to autobaudchoice", 
		   getName());
      return false;
    }

    ArLog::log(ArLog::Verbose, "%s: Switched to %s baud rate",
	       getName(), getAutoBaudChoice());
  }

  while (readLine(buf, sizeof(buf), 10000, false, true))
  {
    if (strlen(buf) == 0)
      break;

    if (strncasecmp(buf, "VEND:", strlen("VEND:")) == 0)
      myVendor = &buf[5];
    else if (strncasecmp(buf, "PROD:", strlen("PROD:")) == 0)
      myProduct = &buf[5];
    else if (strncasecmp(buf, "FIRM:", strlen("FIRM:")) == 0)
      myFirmwareVersion = &buf[5];
    else if (strncasecmp(buf, "PROT:", strlen("PROT:")) == 0)
      myProtocolVersion = &buf[5];
    else if (strncasecmp(buf, "SERI:", strlen("SERI:")) == 0)
      mySerialNumber = &buf[5];
    else if (strncasecmp(buf, "STAT:", strlen("STAT:")) == 0)
      myStat = &buf[5];
  }

  if (myVendor.empty() || myProduct.empty() || myFirmwareVersion.empty() || 
      myProtocolVersion.empty() || mySerialNumber.empty())
  {
    ArLog::log(ArLog::Normal, 
	       "%s::blockingConnect: Missing information in version response",
	       getName());
    return false;
  }

  if (!(ret = sendCommandAndRecvStatus(
		"PP", "parameter info request", 
		buf, sizeof(buf), 10000)) || 
      strcasecmp(buf, "00") != 0)      
  {
    ArLog::log(ArLog::Normal, 
	       "%s::blockingConnect: Bad response to parameter info request",
	       getName());
    return false;
  }

  while (readLine(buf, sizeof(buf), 10000, false, true))
  {
    if (strlen(buf) == 0)
      break;

    if (strncasecmp(buf, "MODL:", strlen("MODL:")) == 0)
      myModel = &buf[5];
    else if (strncasecmp(buf, "DMIN:", strlen("DMIN:")) == 0)
      myDMin = atoi(&buf[5]);
    else if (strncasecmp(buf, "DMAX:", strlen("DMAX:")) == 0)
      myDMax = atoi(&buf[5]);
    else if (strncasecmp(buf, "ARES:", strlen("ARES:")) == 0)
      myARes = atoi(&buf[5]);
    else if (strncasecmp(buf, "AMIN:", strlen("AMIN:")) == 0)
      myAMin = atoi(&buf[5]);
    else if (strncasecmp(buf, "AMAX:", strlen("AMAX:")) == 0)
      myAMax = atoi(&buf[5]);
    else if (strncasecmp(buf, "AFRT:", strlen("AFRT:")) == 0)
      myAFront = atoi(&buf[5]);
    else if (strncasecmp(buf, "SCAN:", strlen("SCAN:")) == 0)
      myScan = atoi(&buf[5]);
  }

  if (myModel.empty() || myDMin == 0 || myDMax == 0 || myARes == 0 ||
      myAMin == 0 || myAMax == 0 || myAFront == 0 || myScan == 0)
  {
    ArLog::log(ArLog::Normal, 
	       "%s::blockingConnect: Missing information in parameter info response",
	       getName());
    return false;
  }

  myStepSize = 360.0 / myARes;
  myStepFirst = myAFront * myStepSize;
  
  if (myMaxRange > myDMax)
    setMaxRange(myDMax);

  //log();

  setParams(getStartDegrees(), getEndDegrees(), getIncrement(), getFlipped());

  //myLogMore = true;
  //  myLogMore = false;
  ArUtil::sleep(100);
  
  
  //printf("myRequestString %s\n", myRequestString);

  if (!(ret = sendCommandAndRecvStatus(
		myRequestString, "request distance reading", 
		buf, sizeof(buf), 10000)) || 
      strcasecmp(buf, "00") != 0)
  {
    if (ret && strcasecmp(buf, "00") != 0) 
      ArLog::log(ArLog::Normal, 
	 "%s::blockingConnect: Bad status on distance reading response (%s)",
		 getName(), buf);
    return false;
  }
  
  //myLogMore = false;

  ArTime started;
  started.setToNow();
  while (started.secSince() < 10 && 
	 readLine(buf, sizeof(buf), 10000, true, false))
  {
    if (strlen(buf) == 0)
      return true;
  }

  ArLog::log(ArLog::Normal, "%s::blockingConnect: Did not get distance reading back",
	     getName());
  return false;
}
XmlRpcPackage::XmlRpcPackage(QString name, QVariantList params) {
    setName(name);
    setParams(params);
}
Exemple #15
0
void returnAuthorizationWorkbench::sFillListDue()
{ 
  _radue->clear();
  if (_cust->isChecked() && !_custInfo->isValid())
  {
    QMessageBox::information( this, tr("Customer not selected"),
			      tr("<p>Please select a customer.") );
    _custInfo->setFocus();
    return;
  }

  //Fill Due Credit List
  if ((_creditmemo->isChecked()) || (_check->isChecked()) || (_creditcard->isChecked()))
  {
    bool bc;
    bc = false;
    QString sql ( "SELECT DISTINCT rahead_id, "
		  "CASE "
		  "  WHEN rahead_creditmethod = 'M' THEN "
		  "    1 "
		  "  WHEN rahead_creditmethod = 'K' THEN "
		  "    2 "
		  "  WHEN rahead_creditmethod = 'C' THEN "
		  "    3 "
		  "END, "
		  "rahead_number, cust_name, "
		  "formatDate(rahead_authdate), "
		  "formatMoney(calcradueamt(rahead_id)), "
		  "currConcat(rahead_curr_id), "
		  "formatMoney(currtobase(rahead_curr_id,"
		  "                       calcradueamt(rahead_id), current_date)), "
		  "CASE "
		  "  WHEN rahead_creditmethod = 'M' THEN "
		  "    <? value(\"creditmemo\") ?> "
		  "  WHEN rahead_creditmethod = 'K' THEN "
		  "    <? value(\"check\") ?> "
		  "  WHEN rahead_creditmethod = 'C' THEN "
		  "    <? value(\"creditcard\") ?> "
		  "END AS creditmethod, rahead_authdate "
		  "FROM rahead,custinfo,raitem,custtype "
		  "WHERE ( (rahead_id=raitem_rahead_id) "
		  " AND (rahead_cust_id=cust_id) "
		  " AND (cust_custtype_id=custtype_id) "
		  " AND ((raitem_disposition IN ('R','P') AND rahead_timing = 'R' AND raitem_qtyreceived > raitem_qtycredited) "
      " OR (raitem_disposition IN ('R','P') AND rahead_timing = 'I' AND raitem_qtyauthorized > raitem_qtycredited) "
		  " OR (raitem_disposition = 'C' AND raitem_qtyauthorized > raitem_qtycredited)) "
		  " AND (raitem_status = 'O') "
		  " AND (rahead_creditmethod != 'N') "
		  " AND (calcradueamt(rahead_id) > 0) "
		  " AND (raitem_disposition IN ('C','R','P')) "
		  " <? if exists(\"cust_id\") ?>"
		  " AND (cust_id=<? value(\"cust_id\") ?>) "
		  " <? elseif exists(\"custtype_id\") ?>"
		  " AND (custtype_id=<? value(\"custtype_id\") ?>) "
		  " <? elseif exists(\"custtype_pattern\") ?>"
		  " AND (custtype_pattern=<? value(\"custtype_pattern\") ?>) "
		  " <? endif ?>"
		  " AND (rahead_creditmethod IN ('$'"	// avoid stress over commas
		  " <? if exists(\"doM\") ?>, 'M'<? endif ?>"
		  " <? if exists(\"doK\") ?>, 'K'<? endif ?>"
		  " <? if exists(\"doC\") ?>, 'C'<? endif ?>"
		  " ))"
      " AND   ((SELECT COUNT(*)"
      "         FROM raitem JOIN itemsite ON (itemsite_id=raitem_itemsite_id)"
      "                     JOIN site() ON (warehous_id=itemsite_warehous_id)"
      "         WHERE (raitem_rahead_id=rahead_id)) > 0)"
      " ) "
		  "ORDER BY rahead_authdate,rahead_number;"
		  );

    ParameterList params;
    setParams(params);

    MetaSQLQuery mql(sql);
    XSqlQuery radue = mql.toQuery(params);
    if (radue.first())
      _radue->populate(radue,TRUE);
    else if (radue.lastError().type() != QSqlError::None)
    {
      systemError(this, radue.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
}
Exemple #16
0
void dspTimePhasedOpenAPItems::sFillCustom()
{
  if (!_periods->isPeriodSelected())
  {
    if (isVisible())
      QMessageBox::warning( this, tr("Select Calendar Periods"),
                            tr("Please select one or more Calendar Periods") );
    return;
  }

  _columnDates.clear();
  _apopen->setColumnCount(2);

  QString sql("SELECT vend_id, vend_number, vend_name");
  QStringList linetotal;

  int columns = 1;
  QList<XTreeWidgetItem*> selected = _periods->selectedItems();
  for (int i = 0; i < selected.size(); i++)
  {
    PeriodListViewItem *cursor = (PeriodListViewItem*)selected[i];
    QString bucketname = QString("bucket%1").arg(columns++);
    sql += QString(", openAPItemsValue(vend_id, %2) AS %1,"
                   " 'curr' AS %3_xtnumericrole, 0 AS %4_xttotalrole")
          .arg(bucketname)
          .arg(cursor->id())
          .arg(bucketname)
          .arg(bucketname);

    _apopen->addColumn(formatDate(cursor->startDate()), _bigMoneyColumn, Qt::AlignRight, true, bucketname);
    _columnDates.append(DatePair(cursor->startDate(), cursor->endDate()));
    linetotal << QString("openAPItemsValue(vend_id, %1)").arg(cursor->id());
  }

  _apopen->addColumn(tr("Total"), _bigMoneyColumn, Qt::AlignRight, true, "linetotal");
  sql += ", " + linetotal.join("+") + " AS linetotal,"
         " 'curr' AS linetotal_xtnumericrole,"
         " 0 AS linetotal_xttotalrole,"
         " (" + linetotal.join("+") + ") = 0.0 AS xthiddenrole "
         "FROM vend "
         "<? if exists(\"vend_id\") ?>"
         "WHERE (vend_id=<? value (\"vend_id\") ?>)"
         "<? elseif exists(\"vendtype_id\") ?>"
         "WHERE (vend_vendtype_id=<? value (\"vendtype_id\") ?>)"
         "<? elseif exists(\"vendtype_code\") ?>"
         "WHERE (vend_vendtype_id IN (SELECT vendtype_id FROM vendtype WHERE (vendtype_code ~ <? value (\"vendtype_pattern\") ?>))) "
         "<? endif ?>"
         "ORDER BY vend_number;";

  MetaSQLQuery mql(sql);
  ParameterList params;
  if (! setParams(params))
    return;

  q = mql.toQuery(params);
  _apopen->populate(q);
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Exemple #17
0
void dspUninvoicedReceivings::sFillList()
{
  _porecv->clear();
  QString sql( "SELECT recv_id AS id,"
               "       CASE WHEN(poitem_status='C') THEN 2"
               "            ELSE 1"
               "       END AS doctype,"
               "       recv_date AS thedate,"
               "       recv_trans_usr_name AS f_user,"
               "       recv_order_number AS ponumber, poitem_linenumber,"
               "       vend_name,"
               "       COALESCE(item_number,"
               "       ('Misc. - ' || recv_vend_item_number)) AS itemnumber,"
               "       recv_qty AS qty, 'qty' AS qty_xtnumericrole,"
               "       'Receipt' AS type, "
               "       recv_value AS value,"
               "       'curr' AS value_xtnumericrole, 0 AS value_xttotalrole "
               "FROM recv, vend, poitem LEFT OUTER JOIN"
               "                   ( itemsite JOIN item"
               "                     ON (itemsite_item_id=item_id)"
               "                   ) ON (poitem_itemsite_id=itemsite_id) "
               "WHERE ( (recv_orderitem_id=poitem_id)"
               " AND (recv_order_type='PO')"
               " AND (recv_vend_id=vend_id)"
               " AND (recv_posted)"
               " AND (recv_vohead_id IS NULL)"
               " AND (NOT recv_invoiced) "
	       "<? if exists(\"warehous_id\") ?>"
	       " AND (itemsite_warehous_id=<? value(\"warehous_id\") ?>)"
	       "<? endif ?>"
	       "<? if exists(\"agentUsername\") ?>"
	       " AND (recv_agent_username=<? value(\"agentUsername\") ?>)"
	       "<? endif ?>"
	       ") "
	       "UNION "
               "SELECT poreject_id AS id,"
               "       3 AS doctype,"
               "       poreject_date AS thedate,"
               "       poreject_trans_username AS f_user,"
               "       poreject_ponumber AS ponumber, poitem_linenumber,"
               "       vend_name,"
               "       COALESCE(item_number,"
               "       ('Misc. - ' || poreject_vend_item_number)) AS itemnumber,"
               "       poreject_qty, 'qty' AS qty_xtnumericrole,"
               "       'Return' AS type, "
               "       poreject_value * -1 AS value,"
               "       'curr' AS value_xtnumericrole, 0 AS value_xtotalrole "
               "FROM poreject, vend, poitem LEFT OUTER JOIN"
               "                   ( itemsite JOIN item"
               "                     ON (itemsite_item_id=item_id)"
               "                   ) ON (poitem_itemsite_id=itemsite_id) "
               "WHERE ( (poreject_poitem_id=poitem_id)"
               " AND (poreject_vend_id=vend_id)"
               " AND (poreject_posted)"
               " AND (NOT poreject_invoiced) "
	       "<? if exists(\"warehous_id\") ?>"
	       " AND (itemsite_warehous_id=<? value(\"warehous_id\") ?>)"
	       "<? endif ?>"
	       "<? if exists(\"agentUsername\") ?>"
	       " AND (poreject_agent_username=<? value(\"agentUsername\") ?>)"
	       "<? endif ?>"
	       ") "
	       "ORDER BY ponumber, poitem_linenumber;");

  ParameterList params;
  setParams(params);
  MetaSQLQuery mql(sql);
  q = mql.toQuery(params);
  _porecv->populate(q, true);
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Exemple #18
0
DeviceHandler::DeviceHandler(QObject *parent) :
    JsonHandler(parent)
{
    QVariantMap returns;
    QVariantMap params;

    params.clear(); returns.clear();
    setDescription("GetSupportedVendors", "Returns a list of supported Vendors.");
    setParams("GetSupportedVendors", params);
    QVariantList vendors;
    vendors.append(JsonTypes::vendorRef());
    returns.insert("vendors", vendors);
    setReturns("GetSupportedVendors", returns);

    params.clear(); returns.clear();
    setDescription("GetSupportedDevices", "Returns a list of supported Device classes, optionally filtered by vendorId.");
    params.insert("o:vendorId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("GetSupportedDevices", params);
    QVariantList deviceClasses;
    deviceClasses.append(JsonTypes::deviceClassRef());
    returns.insert("deviceClasses", deviceClasses);
    setReturns("GetSupportedDevices", returns);

    params.clear(); returns.clear();
    setDescription("GetPlugins", "Returns a list of loaded plugins.");
    setParams("GetPlugins", params);
    QVariantList plugins;
    plugins.append(JsonTypes::pluginRef());
    returns.insert("plugins", plugins);
    setReturns("GetPlugins", returns);

    params.clear(); returns.clear();
    setDescription("GetPluginConfiguration", "Get a plugin's params.");
    params.insert("pluginId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("GetPluginConfiguration", params);
    QVariantList pluginParams;
    pluginParams.append(JsonTypes::paramRef());
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    returns.insert("o:configuration", pluginParams);
    setReturns("GetPluginConfiguration", returns);

    params.clear(); returns.clear();
    setDescription("SetPluginConfiguration", "Set a plugin's params.");
    params.insert("pluginId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    params.insert("configuration", pluginParams);
    setParams("SetPluginConfiguration", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    setReturns("SetPluginConfiguration", returns);

    params.clear(); returns.clear();
    setDescription("AddConfiguredDevice", "Add a configured device with a setupMethod of SetupMethodJustAdd. "
                   "For devices with a setupMethod different than SetupMethodJustAdd, use PairDevice. "
                   "Use deviceDescriptorId or deviceParams, depending on the createMethod of the device class. "
                   "CreateMethodJustAdd takes the parameters you want to have with that device. "
                   "CreateMethodDiscovery requires the use of a deviceDescriptorId."
                   );
    params.insert("deviceClassId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    params.insert("o:deviceDescriptorId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    QVariantList deviceParams;
    deviceParams.append(JsonTypes::paramRef());
    params.insert("o:deviceParams", deviceParams);
    setParams("AddConfiguredDevice", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    returns.insert("o:deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setReturns("AddConfiguredDevice", returns);

    returns.clear(); // Reused params from above!
    setDescription("PairDevice", "Pair a device. "
                   "Use this for DeviceClasses with a setupMethod different than SetupMethodJustAdd. "
                   "Use deviceDescriptorId or deviceParams, depending on the createMethod of the device class. "
                   "CreateMethodJustAdd takes the parameters you want to have with that device. "
                   "CreateMethodDiscovery requires the use of a deviceDescriptorId. "
                   "If success is true, the return values will contain a pairingTransactionId, a displayMessage and "
                   "the setupMethod. Depending on the setupMethod you should either proceed with AddConfiguredDevice "
                   "or PairDevice."
                   );
    setParams("PairDevice", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    returns.insert("o:pairingTransactionId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    returns.insert("o:displayMessage", JsonTypes::basicTypeToString(JsonTypes::String));
    returns.insert("o:setupMethod", JsonTypes::setupMethodRef());
    setReturns("PairDevice", returns);

    params.clear(); returns.clear();
    setDescription("ConfirmPairing", "Confirm an ongoing pairing. In case of SetupMethodEnterPin also provide the pin in the params.");
    params.insert("pairingTransactionId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    params.insert("o:secret", JsonTypes::basicTypeToString(JsonTypes::String));
    setParams("ConfirmPairing", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    returns.insert("o:deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setReturns("ConfirmPairing", returns);

    params.clear(); returns.clear();
    setDescription("GetConfiguredDevices", "Returns a list of configured devices.");
    setParams("GetConfiguredDevices", params);
    QVariantList devices;
    devices.append(JsonTypes::deviceRef());
    returns.insert("devices", devices);
    setReturns("GetConfiguredDevices", returns);

    params.clear(); returns.clear();
    setDescription("GetDiscoveredDevices", "Performs a device discovery and returns the results. This function may take a while to return.");
    params.insert("deviceClassId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    QVariantList discoveryParams;
    discoveryParams.append(JsonTypes::paramRef());
    params.insert("o:discoveryParams", discoveryParams);
    setParams("GetDiscoveredDevices", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    QVariantList deviceDescriptors;
    deviceDescriptors.append(JsonTypes::deviceDescriptorRef());
    returns.insert("o:deviceDescriptors", deviceDescriptors);
    setReturns("GetDiscoveredDevices", returns);

    params.clear(); returns.clear();
    setDescription("EditDevice", "Edit the parameters of a device. The device params will be set to the "
                   "passed parameters and the setup device will be called. If the device is discoverable, "
                   "you can perform a GetDiscoveredDevices before calling this method and pass "
                   "the new DeviceDescriptor (rediscover). If a parameter is not writable, you will find a "
                   "'readOnly': true in the ParamType. By default, every Param is writable.");
    params.insert("deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    params.insert("o:deviceDescriptorId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    QVariantList newDeviceParams;
    newDeviceParams.append(JsonTypes::paramRef());
    params.insert("o:deviceParams", newDeviceParams);
    setParams("EditDevice", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    setReturns("EditDevice", returns);

    params.clear(); returns.clear();
    setDescription("RemoveConfiguredDevice", "Remove a device from the system.");
    params.insert("deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    QVariantList removePolicyList;
    QVariantMap policy;
    policy.insert("ruleId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    policy.insert("policy", JsonTypes::removePolicyRef());
    removePolicyList.append(policy);
    params.insert("o:removePolicy", JsonTypes::removePolicyRef());
    params.insert("o:removePolicyList", removePolicyList);
    setParams("RemoveConfiguredDevice", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    returns.insert("o:ruleIds", QVariantList() << JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setReturns("RemoveConfiguredDevice", returns);

    params.clear(); returns.clear();
    setDescription("GetEventTypes", "Get event types for a specified deviceClassId.");
    params.insert("deviceClassId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("GetEventTypes", params);
    QVariantList events;
    events.append(JsonTypes::eventTypeRef());
    returns.insert("eventTypes", events);
    setReturns("GetEventTypes", returns);

    params.clear(); returns.clear();
    setDescription("GetActionTypes", "Get action types for a specified deviceClassId.");
    params.insert("deviceClassId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("GetActionTypes", params);
    QVariantList actions;
    actions.append(JsonTypes::actionTypeRef());
    returns.insert("actionTypes", actions);
    setReturns("GetActionTypes", returns);

    params.clear(); returns.clear();
    setDescription("GetStateTypes", "Get state types for a specified deviceClassId.");
    params.insert("deviceClassId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("GetStateTypes", params);
    QVariantList states;
    states.append(JsonTypes::stateTypeRef());
    returns.insert("stateTypes", states);
    setReturns("GetStateTypes", returns);

    params.clear(); returns.clear();
    setDescription("GetStateValue", "Get the value of the given device and the given stateType");
    params.insert("deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    params.insert("stateTypeId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("GetStateValue", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    returns.insert("o:value", JsonTypes::basicTypeToString(JsonTypes::Variant));
    setReturns("GetStateValue", returns);

    params.clear(); returns.clear();
    setDescription("GetStateValues", "Get all the state values of the given device.");
    params.insert("deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("GetStateValues", params);
    returns.insert("deviceError", JsonTypes::deviceErrorRef());
    states.clear();
    QVariantMap state;
    state.insert("stateTypeId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    state.insert("value", JsonTypes::basicTypeToString(JsonTypes::Variant));
    states.append(state);
    returns.insert("o:values", states);
    setReturns("GetStateValues", returns);

    // Notifications
    params.clear(); returns.clear();
    setDescription("StateChanged", "Emitted whenever a State of a device changes.");
    params.insert("deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    params.insert("stateTypeId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    params.insert("value", JsonTypes::basicTypeToString(JsonTypes::Variant));
    setParams("StateChanged", params);

    params.clear(); returns.clear();
    setDescription("DeviceRemoved", "Emitted whenever a Device was removed.");
    params.insert("deviceId", JsonTypes::basicTypeToString(JsonTypes::Uuid));
    setParams("DeviceRemoved", params);

    params.clear(); returns.clear();
    setDescription("DeviceAdded", "Emitted whenever a Device was added.");
    params.insert("device", JsonTypes::deviceRef());
    setParams("DeviceAdded", params);

    params.clear(); returns.clear();
    setDescription("DeviceParamsChanged", "Emitted whenever the params of a Device changed (by editing or rediscovering).");
    params.insert("device", JsonTypes::deviceRef());
    setParams("DeviceParamsChanged", params);

    connect(GuhCore::instance(), &GuhCore::deviceStateChanged, this, &DeviceHandler::deviceStateChanged);
    connect(GuhCore::instance(), &GuhCore::deviceRemoved, this, &DeviceHandler::deviceRemovedNotification);
    connect(GuhCore::instance(), &GuhCore::deviceAdded, this, &DeviceHandler::deviceAddedNotification);
    connect(GuhCore::instance(), &GuhCore::deviceParamsChanged, this, &DeviceHandler::deviceParamsChangedNotification);
    connect(GuhCore::instance(), &GuhCore::devicesDiscovered, this, &DeviceHandler::devicesDiscovered, Qt::QueuedConnection);
    connect(GuhCore::instance(), &GuhCore::deviceSetupFinished, this, &DeviceHandler::deviceSetupFinished);
    connect(GuhCore::instance(), &GuhCore::deviceEditFinished, this, &DeviceHandler::deviceEditFinished);
    connect(GuhCore::instance(), &GuhCore::pairingFinished, this, &DeviceHandler::pairingFinished);
}
Exemple #19
0
void dspIncidentsByCRMAccount::sFillList()
{
  QString sql = "SELECT  crmacct_id, incdt_id, todoitem_id, "
		"	  crmacct_number, crmacct_name, "
		"	  incdt_number, DATE(incdt_timestamp) AS incdt_timestamp, "
		"         CASE WHEN(incdt_status='N') THEN <? value(\"new\") ?>"
		"              WHEN(incdt_status='F') THEN <? value(\"feedback\") ?>"
		"              WHEN(incdt_status='C') THEN <? value(\"confirmed\") ?>"
		"              WHEN(incdt_status='A') THEN <? value(\"assigned\") ?>"
		"              WHEN(incdt_status='R') THEN <? value(\"resolved\") ?>"
		"              WHEN(incdt_status='L') THEN <? value(\"closed\") ?>"
		"              ELSE incdt_status"
		"         END AS incdt_status,"
		"         incdt_assigned_username, incdt_summary, "
		"	  COALESCE(TEXT(todoitem_seq), '') AS todoitem_seq, todoitem_due_date, todoitem_name, "
		"	  COALESCE(usr_username, '') AS todoitem_usrname, "
		"	  todoitem_assigned_date, todoitem_status, "
		"	  incdtseverity_name, "
		"	  incdtpriority_name "
		"  FROM crmacct "
		"      <? if exists(\"showAcctsWOIncdts\") ?> "
		"	LEFT OUTER "
		"      <? endif ?> "
		"      JOIN incdt ON (incdt_crmacct_id=crmacct_id "
		"                     AND (incdt_timestamp BETWEEN <? value(\"startDate\") ?> "
		"                                              AND <? value(\"endDate\") ?>) "
		"                     <? if not exists(\"showClosed\") ?> "
		"                       AND incdt_status != 'L' "
		"                     <? endif ?>) "
		"      LEFT OUTER JOIN todoitem ON (todoitem_incdt_id=incdt_id) "
		"      LEFT OUTER JOIN usr ON (usr_id = todoitem_usr_id) "
		"      LEFT OUTER JOIN incdtseverity ON (incdt_incdtseverity_id = incdtseverity_id) "
		"      LEFT OUTER JOIN incdtpriority ON (incdt_incdtpriority_id = incdtpriority_id) "
		"  WHERE ((todoitem_status IS NULL OR todoitem_status != 'C') "
		"    <? if exists(\"crmacct_id\") ?> "
		"      AND (crmacct_id=<? value(\"crmacct_id\") ?>) "
		"    <? endif ?> "
		"    <? if exists(\"showAcctsWOIncdts\") ?> "
		"      AND (incdt_id IS NULL OR (true "
		"    <? endif ?> "
		"    <? if exists(\"showAcctsWOIncdts\") ?> "
		"      )) "
		"    <? endif ?> "
		"    )  "
		"  ORDER BY crmacct_name, incdt_timestamp, todoitem_due_date; "
		;
  ParameterList params;
  if (! setParams(params))
    return;

  MetaSQLQuery mql(sql);
  q = mql.toQuery(params);
  if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__,__LINE__);
    return;
  }

  _list->clear();
  XTreeWidgetItem *lastCrmacct	= NULL;
  XTreeWidgetItem *lastIncdt	= NULL;
  XTreeWidgetItem *lastTodo	= NULL;
  int lastCrmacctId	= -1;
  int lastIncdtId	= -1;
  int lastTodoId	= -1;
  while (q.next())
  {
    if (q.value("crmacct_id").toInt() != lastCrmacctId)
      lastCrmacct = new XTreeWidgetItem(_list, lastCrmacct,
			       q.value("crmacct_id").toInt(), 1,
			       q.value("crmacct_number"),
			       q.value("crmacct_name"),
			       "", "", "", "", "", "", "" );
    if (!q.value("incdt_id").isNull() &&
         q.value("incdt_id").toInt() != lastIncdtId)
      lastIncdt = new XTreeWidgetItem(lastCrmacct, lastIncdt,
			       q.value("incdt_id").toInt(), 2,
			       "", "",
			       q.value("incdt_number"),
			       "", 
			       q.value("incdt_summary"),
			       q.value("incdt_timestamp"),
			       q.value("incdt_status"),
			       q.value("incdt_assigned_username"),
			       "" );
    if (!q.value("todoitem_id").isNull() &&
         q.value("todoitem_id").toInt() != lastTodoId)
      lastTodo = new XTreeWidgetItem(lastIncdt, lastTodo,
			       q.value("todoitem_id").toInt(), 3,
			       "", "",
			       "",
			       q.value("todoitem_seq"),
			       q.value("todoitem_name"),
			       q.value("todoitem_assigned_date"),
			       q.value("todoitem_status"),
			       q.value("todoitem_usrname"),
			       q.value("todoitem_due_date") );
  lastCrmacctId = q.value("crmacct_id").toInt();
  lastIncdtId = q.value("incdt_id").toInt();
  lastTodoId = q.value("todoitem_id").toInt();
  }
}