Exemplo n.º 1
0
void distributeInventory::sFillList()
{
  q.prepare( "SELECT itemsite_id, "
             "       COALESCE(itemsite_location_id,-1) AS itemsite_location_id,"
             "       formatlotserialnumber(itemlocdist_ls_id) AS lotserial,"
             "       (itemlocdist_order_type || ' ' || formatSoItemNumber(itemlocdist_order_id)) AS order,"
             "       (itemsite_controlmethod IN ('L', 'S')) AS lscontrol,"
             "       parent.itemlocdist_qty AS qtytodistribute,"
             "       ( ( SELECT COALESCE(SUM(child.itemlocdist_qty), 0)"
             "             FROM itemlocdist AS child"
             "            WHERE (child.itemlocdist_itemlocdist_id=parent.itemlocdist_id) ) ) AS qtytagged,"
             "       (parent.itemlocdist_qty - ( SELECT COALESCE(SUM(child.itemlocdist_qty), 0)"
             "                                     FROM itemlocdist AS child"
             "                                    WHERE (child.itemlocdist_itemlocdist_id=parent.itemlocdist_id) ) ) AS qtybalance "
             "FROM itemsite, itemlocdist AS parent "
             "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
             " AND (itemlocdist_id=:itemlocdist_id) );" );
  q.bindValue(":itemlocdist_id", _itemlocdistid);
  q.exec();
  if (q.first())
  {
    _item->setItemsiteid(q.value("itemsite_id").toInt());
    _lotSerial->setText(q.value("lotserial").toString());
    _order->setText(q.value("order").toString());
    _qtyToDistribute->setDouble(q.value("qtytodistribute").toDouble());
    _qtyTagged->setDouble(q.value("qtytagged").toDouble());
    _qtyRemaining->setDouble(q.value("qtybalance").toDouble());

    if ( (q.value("itemsite_location_id").toInt() != -1) &&
         ( (_mode == cNoIncludeLotSerial) || ( (_mode == cIncludeLotSerial) && (!q.value("lscontrol").toBool()) ) ) )
    {
      _default->setEnabled(TRUE);
      _defaultAndPost->setEnabled(TRUE);
    }
    else
    {
      _default->setEnabled(FALSE);
      _defaultAndPost->setEnabled(FALSE);
    }
    
    if (q.value("qtytodistribute").toDouble() < 0)
      _qtyOnly->hide();

    QString sql( "SELECT id, type, locationname, defaultlocation,"
		 "       location_netable, lotserial, f_expiration, expired,"
                 "       qty, qtytagged, (qty + qtytagged) AS balance,"
                 "       'qty' AS qty_xtnumericrole,"
                 "       'qty' AS qtytagged_xtnumericrole,"
                 "       'qty' AS balance_xtnumericrole,"
                 "       CASE WHEN expired THEN 'error' END AS qtforegroundrole "
                 "FROM (" 
		 "<? if exists(\"cNoIncludeLotSerial\") ?>"
		 "SELECT location_id AS id, <? value(\"locationType\") ?> AS type,"
		 "       formatLocationName(location_id) AS locationname,"
		 "       (location_id=itemsite_location_id) AS defaultlocation,"
		 "       location_netable,"
		 "       TEXT('') AS lotserial,"
		 "       TEXT(<? value(\"na\") ?>) AS f_expiration, FALSE AS expired,"
		 "       qtyLocation(location_id, NULL, itemsite_id, itemlocdist_order_type, itemlocdist_order_id) AS qty,"
		 "       itemlocdistQty(location_id, itemlocdist_id) AS qtytagged "
		 "FROM itemlocdist, location, itemsite "
		 "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
		 " AND (itemsite_loccntrl)"
		 " AND (itemsite_warehous_id=location_warehous_id)"
		 " AND (validLocation(location_id, itemsite_id))"
		 " AND (itemlocdist_id=<? value(\"itemlocdist_id\") ?>) ) "
		 "<? elseif exists(\"cIncludeLotSerial\") ?>"
		 "SELECT itemloc_id AS id, <? value(\"itemlocType\") ?> AS type,"
		 "       COALESCE(formatLocationName(location_id),"
		 "                <? value(\"undefined\") ?>) AS locationname,"
		 "       (location_id IS NOT NULL"
		 "        AND location_id=itemsite_location_id) AS defaultlocation,"
		 "       COALESCE(location_netable, false) AS location_netable,"
		 "       ls_number AS lotserial,"
		 "       CASE WHEN (itemsite_perishable) THEN formatDate(itemloc_expiration)"
		 "            ELSE <? value(\"na\") ?>"
		 "       END AS f_expiration,"
		 "       CASE WHEN (itemsite_perishable) THEN (itemloc_expiration < CURRENT_DATE)"
		 "            ELSE FALSE" 
		 "       END AS expired,"
		 "       qtyLocation(itemloc_location_id, itemloc_ls_id, itemsite_id, itemlocdist_order_type, itemlocdist_order_id) AS qty,"
		 "       ( SELECT COALESCE(SUM(target.itemlocdist_qty), 0)"
		 "         FROM itemlocdist AS target"
		 "         WHERE ( (target.itemlocdist_source_type='I')"
		 "          AND (target.itemlocdist_source_id=itemloc_id)"
		 "          AND (target.itemlocdist_itemlocdist_id=source.itemlocdist_id)) ) AS qtytagged "
		 "FROM itemlocdist AS source, itemsite, itemloc "
                 "  LEFT OUTER JOIN location ON (itemloc_location_id=location_id) "
                 "  LEFT OUTER JOIN ls ON (itemloc_ls_id=ls_id) "
		 "WHERE ( (source.itemlocdist_itemsite_id=itemsite_id)"
		 " AND (itemloc_itemsite_id=itemsite_id)"
		 " AND (source.itemlocdist_id=<? value(\"itemlocdist_id\") ?>) ) "
		 " UNION "
		 "SELECT location_id AS id, <? value(\"locationType\") ?> AS type,"
		 "       formatLocationName(location_id) AS locationname,"
		 "       (location_id=itemsite_location_id) AS defaultlocation,"
		 "       location_netable,"
		 "       TEXT('') AS lotserial,"
		 "       TEXT(<? value(\"na\") ?>) AS f_expiration, FALSE AS expired,"
		 "       qtyLocation(location_id, NULL, itemsite_id, itemlocdist_order_type, itemlocdist_order_id) AS qty,"
		 "       itemlocdistQty(location_id, itemlocdist_id) AS qtytagged "
		 "FROM itemlocdist, location, itemsite "
		 "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
		 " AND (itemsite_loccntrl)"
		 " AND (itemsite_warehous_id=location_warehous_id)"
		 " AND (validLocation(location_id, itemsite_id))"
                 " AND (itemsite_id=<? value(\"itemsite_id\") ?> ) "
		 " AND (location_id NOT IN (SELECT DISTINCT itemloc_location_id FROM itemloc WHERE (itemloc_itemsite_id=itemsite_id)))"
		 " AND (itemlocdist_id=<? value(\"itemlocdist_id\") ?>) ) "
		 "<? endif ?>"
		 ") AS data "
                 "WHERE ((TRUE) "
		 "<? if exists(\"showOnlyTagged\") ?>"
		 "AND (qtytagged != 0) "
		 "<? endif ?>"
                 "<? if exists(\"showQtyOnly\") ?>"
                 "AND (qty > 0) "
                 "<? endif ?>"
		 ") ORDER BY locationname;");

    ParameterList params;

    if (_mode == cNoIncludeLotSerial)
      params.append("cNoIncludeLotSerial");
    else if (_mode == cIncludeLotSerial)
      params.append("cIncludeLotSerial");

    if (_taggedOnly->isChecked())
      params.append("showOnlyTagged");
      
    if ( (_qtyOnly->isChecked())  ||
        (q.value("qtytodistribute").toDouble() < 0) )
      params.append("showQtyOnly");

    params.append("locationType",   cLocation);
    params.append("itemlocType",    cItemloc);
    params.append("yes",            tr("Yes"));
    params.append("no",             tr("No"));
    params.append("na",             tr("N/A"));
    params.append("undefined",      tr("Undefined"));
    params.append("itemlocdist_id", _itemlocdistid);
    params.append("itemsite_id",    q.value("itemsite_id").toInt());

    MetaSQLQuery mql(sql);
    q = mql.toQuery(params);

    _itemloc->populate(q, true);
    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;
  }
}
Exemplo n.º 2
0
int distributeInventory::SeriesAdjust(int pItemlocSeries, QWidget *pParent, const QString & pPresetLotnum, const QDate & pPresetLotexp, const QDate & pPresetLotwarr)
{
  if (pItemlocSeries != 0)
  {
    XSqlQuery itemloc;
    itemloc.prepare( "SELECT itemlocdist_id, itemlocdist_reqlotserial," 
                     "       itemlocdist_distlotserial, itemlocdist_qty,"
                     "       itemsite_loccntrl, itemsite_controlmethod,"
                     "       itemsite_perishable, itemsite_warrpurc "
                     "FROM itemlocdist, itemsite "
                     "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
                     " AND (itemlocdist_series=:itemlocdist_series) ) "
                     "ORDER BY itemlocdist_id;" );
    itemloc.bindValue(":itemlocdist_series", pItemlocSeries);
    itemloc.exec();
    while (itemloc.next())
    {
      if (itemloc.value("itemlocdist_reqlotserial").toBool())
      {
        int itemlocSeries = -1;
        XSqlQuery query;
        // Check to see if this is a lot controlled item and if we have
        // a predefined lot#/expdate to use. If so assign that information
        // with itemlocdist_qty and move on. otherwise do the normal dialog
        // to ask the user for that information.
        if(itemloc.value("itemsite_controlmethod").toString() == "L" && !pPresetLotnum.isEmpty())
        {
          query.exec("SELECT nextval('itemloc_series_seq') AS _itemloc_series;");
          if(query.first())
          {
            itemlocSeries = query.value("_itemloc_series").toInt();
            query.prepare( "SELECT createlotserial(itemlocdist_itemsite_id,:lotserial,:itemlocdist_series,'I',itemlocdist_id,:qty,:expiration,:warranty)"
                           "FROM itemlocdist "
                           "WHERE (itemlocdist_id=:itemlocdist_id);"
                           
                           "UPDATE itemlocdist "
                           "SET itemlocdist_source_type='O' "
                           "WHERE (itemlocdist_series=:itemlocdist_series);"
              
                           "DELETE FROM itemlocdist "
                           "WHERE (itemlocdist_id=:itemlocdist_id);" );
            query.bindValue(":lotserial", pPresetLotnum);
            query.bindValue(":qty", itemloc.value("itemlocdist_qty"));
            query.bindValue(":itemlocdist_series", itemlocSeries);
            query.bindValue(":itemlocdist_id", itemloc.value("itemlocdist_id"));
            if(itemloc.value("itemsite_perishable").toBool())
              query.bindValue(":expiration", pPresetLotexp);
            else
              query.bindValue(":expiration", omfgThis->startOfTime());
            if(itemloc.value("itemsite_warrpurc").toBool())
              query.bindValue(":warranty", pPresetLotwarr);
            query.exec();
          }
        }

        if(itemlocSeries == -1)
        {
          ParameterList params;
          params.append("itemlocdist_id", itemloc.value("itemlocdist_id").toInt());

          assignLotSerial newdlg(pParent, "", TRUE);
          newdlg.set(params);
          itemlocSeries = newdlg.exec();
          if (itemlocSeries == -1)
            return XDialog::Rejected;
        }
        
        if (itemloc.value("itemsite_loccntrl").toBool())
        {
          query.prepare( "SELECT itemlocdist_id " 
                         "FROM itemlocdist "
                         "WHERE (itemlocdist_series=:itemlocdist_series) "
                         "ORDER BY itemlocdist_id;" );
          query.bindValue(":itemlocdist_series", itemlocSeries);
          query.exec();
          while (query.next())
          {
            ParameterList params;
            params.append("itemlocdist_id", query.value("itemlocdist_id").toInt());
            distributeInventory newdlg(pParent, "", TRUE);
            newdlg.set(params);
            if (newdlg.exec() == XDialog::Rejected)
              return XDialog::Rejected;
          }
        }
        else
        {
          query.prepare( "UPDATE itemlocdist "
                         "SET itemlocdist_source_type='L', itemlocdist_source_id=-1 "
                         "WHERE (itemlocdist_series=:itemlocdist_series); ");
          query.bindValue(":itemlocdist_series", itemlocSeries);
          query.exec();

          query.prepare( "SELECT distributeItemlocSeries(:itemlocdist_series) AS result;");
          query.bindValue(":itemlocdist_series", itemlocSeries);
          query.exec();
        }
      }
      else
      {
        ParameterList params;
        params.append("itemlocdist_id", itemloc.value("itemlocdist_id").toInt());

        if (itemloc.value("itemlocdist_distlotserial").toBool())
          params.append("includeLotSerialDetail");

        distributeInventory newdlg(pParent, "", TRUE);
        newdlg.set(params);
        if (newdlg.exec() == XDialog::Rejected)
          return XDialog::Rejected;
      }
    }
    
    XSqlQuery post;
    post.prepare("SELECT postItemlocseries(:itemlocseries) AS result;");
    post.bindValue(":itemlocseries",  pItemlocSeries);
    post.exec();
    if (post.first())
      if (!post.value("result").toBool())
            QMessageBox::warning( 0, tr("Inventory Distribution"), 
        tr("There was an error posting the transaction.  Contact your administrator") );
    else if (post.lastError().type() != QSqlError::None)
    {
      systemError(0, post.lastError().databaseText(), __FILE__, __LINE__);
      return XDialog::Rejected;
    }
  }
  
  return XDialog::Accepted;
}
Exemplo n.º 3
0
void dspShipmentsByDate::setParams(ParameterList & params)
{
  if (_metrics->boolean("MultiWhs"))
    params.append("MultiWhs");
  _dates->appendValue(params);
}
Exemplo n.º 4
0
void items::sFillList( int pItemid, bool pLocal )
{
  QString sql( "SELECT item_id, item_number, formatBoolYN(item_active),"
               "       (item_descrip1 || ' ' || item_descrip2), classcode_code,"
               "       CASE WHEN (item_type='P') THEN text(<? value(\"purchased\") ?>)"
               "            WHEN (item_type='M') THEN text(<? value(\"manufactured\") ?>)"
			   "            WHEN (item_type='J') THEN text(<? value(\"job\") ?>)"
               "            WHEN (item_type='F') THEN text(<? value(\"phantom\") ?>)"
               "            WHEN (item_type='B') THEN text(<? value(\"breeder\") ?>)"
               "            WHEN (item_type='C') THEN text(<? value(\"coProduct\") ?>)"
               "            WHEN (item_type='Y') THEN text(<? value(\"byProduct\") ?>)"
               "            WHEN (item_type='R') THEN text(<? value(\"reference\") ?>)"
               "            WHEN (item_type='S') THEN text(<? value(\"costing\") ?>)"
               "            WHEN (item_type='T') THEN text(<? value(\"tooling\") ?>)"
               "            WHEN (item_type='A') THEN text(<? value(\"assortment\") ?>)"
               "            WHEN (item_type='O') THEN text(<? value(\"outside\") ?>)"
               "            WHEN (item_type='L') THEN text(<? value(\"planning\") ?>)"
               "            ELSE text(<? value(\"error\") ?>)"
               "       END,"
               "       uom_name "
               "FROM item, classcode, uom "
               "WHERE ( (item_classcode_id=classcode_id)"
               " AND (item_inv_uom_id=uom_id)"
               "<? if exists(\"showPurchased\") ?>"
               " AND (item_type IN ('P', 'O'))"
               "<? elseif exists(\"showManufactured\") ?>"
               " AND (item_type IN ('M', 'F', 'B', 'J'))"
               "<? elseif exists(\"showSold\") ?>"
               " AND (item_sold)"
               "<? endif ?>"
               "<? if exists(\"onlyShowActive\") ?>"
               " AND (item_active)"
               "<? endif ?>"
               ") ORDER BY"
               "<? if exists(\"ListNumericItemNumbersFirst\") ?>"
               " toNumeric(item_number, 999999999999999),"
               "<? endif ?>"
               " item_number;" );

  ParameterList params;

  if(_showPurchased->isChecked())
    params.append("showPurchased");
  else if(_showManufactured->isChecked())
    params.append("showManufactured");
  else if(_showSold->isChecked())
    params.append("showSold");

  if (!_showInactive->isChecked())
    params.append("onlyShowActive");

  if (_preferences->boolean("ListNumericItemNumbersFirst"))
    params.append("ListNumericItemNumbersFirst");
  
  params.append("purchased", tr("Purchased"));
  params.append("manufactured", tr("Manufactured"));
  params.append("job", tr("Job"));
  params.append("phantom", tr("Phantom"));
  params.append("breeder", tr("Breeder"));
  params.append("coProduct", tr("Co-Product"));
  params.append("byProduct", tr("By-Product"));
  params.append("reference", tr("Reference"));
  params.append("costing", tr("Costing"));
  params.append("tooling", tr("Tooling"));
  params.append("outside", tr("Outside Process"));
  params.append("planning", tr("Planning"));
  params.append("assortment", tr("Assortment"));
  params.append("error", tr("Error"));

  MetaSQLQuery mql(sql);
  q = mql.toQuery(params);

  if ((pItemid != -1) && (pLocal))
    _item->populate(q, pItemid);
  else
    _item->populate(q);
}
Exemplo n.º 5
0
void postCreditMemos::sPost()
{
  q.exec( "SELECT cmhead_printed, COUNT(*) AS number "
          "FROM cmhead "
          "WHERE ( (NOT cmhead_posted) "
          "  AND   (checkCreditMemoSitePrivs(cmhead_id)) ) "
          "GROUP BY cmhead_printed;" );
  if (q.first())
  {
    int printed   = 0;
    int unprinted = 0;

    do
    {
      if (q.value("cmhead_printed").toBool())
        printed = q.value("number").toInt();
      else
        unprinted = q.value("number").toInt();
    }
    while (q.next());

    if ( ( (unprinted) && (!printed) ) && (!_postUnprinted->isChecked()) )
    {
      QMessageBox::warning( this, tr("No Credit Memos to Post"),
                            tr( "Although there are unposted Credit Memos, there are no unposted Credit Memos that have been printed.\n"
                                "You must manually print these Credit Memos or select 'Post Unprinted Credit Memos' before these Credit Memos\n"
                                "may be posted." ) );
      _postUnprinted->setFocus();
      return;
    }
  }
  else
  {
    QMessageBox::warning( this, tr("No Credit Memos to Post"),
                          tr("There are no Credit Memos, printed or not, to post.\n" ) );
    _close->setFocus();
    return;
  }

  q.exec("SELECT fetchJournalNumber('AR-CM') AS result");
  if (!q.first())
  {
    systemError(this, tr("A System Error occurred at %1::%2.")
                      .arg(__FILE__)
                      .arg(__LINE__) );
    return;
  }

  int journalNumber = q.value("result").toInt();
  
  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  q.exec("BEGIN;");	// because of possible lot, serial, or location distribution cancelations
  q.prepare("SELECT postCreditMemos(:postUnprinted, :journalNumber) AS result;");
  q.bindValue(":postUnprinted", QVariant(_postUnprinted->isChecked()));
  q.bindValue(":journalNumber", journalNumber);
  q.exec();
  if (q.first())
  {
    int result = q.value("result").toInt();

    if (result == -5)
    {
      rollback.exec();
      QMessageBox::critical( this, tr("Cannot Post one or more Credit Memos"),
                             tr( "The G/L Account Assignments for one or more of the Credit Memos that you are trying to post are not\n"
                                 "configured correctly.  Because of this, G/L Transactions cannot be posted for these Credit Memos.\n"
                                 "You must contact your Systems Administrator to have this corrected before you may\n"
                                 "post these Credit Memos." ) );
      return;
    }
    else if (result < 0)
    {
      rollback.exec();
      systemError( this, tr("A System Error occurred at postCreditMemos::%1, Error #%2.")
                         .arg(__LINE__)
                         .arg(q.value("result").toInt()) );
      return;
    }
    else if (distributeInventory::SeriesAdjust(q.value("result").toInt(), this) == XDialog::Rejected)
    {
      rollback.exec();
      QMessageBox::information( this, tr("Post Credit Memos"), tr("Transaction Canceled") );
      return;
    }

    q.exec("COMMIT;");

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

      orReport report("CreditMemoJournal", params);
      if (report.isValid())
        report.print();
      else
        report.reportError(this);
    }
  }
  else
  {
    rollback.exec();
    systemError( this, tr("A System Error occurred at postCreditMemos::%1.")
                       .arg(__LINE__) );
    return;
  }

  omfgThis->sCreditMemosUpdated();

  accept();
}
Exemplo n.º 6
0
void creditMemoItem::sListPrices()
{
  q.prepare( "SELECT currToCurr(ipshead_curr_id, :curr_id, ipsprice_price, :effective) AS price"
             "       FROM ipsass, ipshead, ipsprice "
             "       WHERE ( (ipsass_ipshead_id=ipshead_id)"
             "        AND (ipsprice_ipshead_id=ipshead_id)"
             "        AND (ipsprice_item_id=:item_id)"
             "        AND (ipsass_cust_id=:cust_id)"
             "        AND (COALESCE(LENGTH(ipsass_shipto_pattern), 0) = 0)"
             "        AND (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1) ) )"

             "       UNION SELECT ipsprice_price AS price"
             "       FROM ipsass, ipshead, ipsprice "
             "       WHERE ( (ipsass_ipshead_id=ipshead_id)"
             "        AND (ipsprice_ipshead_id=ipshead_id)"
             "        AND (ipsprice_item_id=:item_id)"
             "        AND (ipsass_shipto_id=:shipto_id)"
             "        AND (ipsass_shipto_id != -1)"
             "        AND (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1)) )"
             
             "       UNION SELECT ipsprice_price AS price"
             "       FROM ipsass, ipshead, ipsprice, cust "
             "       WHERE ( (ipsass_ipshead_id=ipshead_id)"
             "        AND (ipsprice_ipshead_id=ipshead_id)"
             "        AND (ipsprice_item_id=:item_id)"
             "        AND (ipsass_custtype_id=cust_custtype_id)"
             "        AND (cust_id=:cust_id)"
             "        AND (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1)) )"
             
             "       UNION SELECT ipsprice_price AS price"
             "       FROM ipsass, ipshead, ipsprice, custtype, cust "
             "       WHERE ( (ipsass_ipshead_id=ipshead_id)"
             "        AND (ipsprice_ipshead_id=ipshead_id)"
             "        AND (ipsprice_item_id=:item_id)"
             "        AND (coalesce(length(ipsass_custtype_pattern), 0) > 0)"
             "        AND (custtype_code ~ ipsass_custtype_pattern)"
             "        AND (cust_custtype_id=custtype_id)"
             "        AND (cust_id=:cust_id)"
             "        AND (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1)))"
             
             "       UNION SELECT ipsprice_price AS price"
             "       FROM ipsass, ipshead, ipsprice, shipto "
             "       WHERE ( (ipsass_ipshead_id=ipshead_id)"
             "        AND (ipsprice_ipshead_id=ipshead_id)"
             "        AND (ipsprice_item_id=:item_id)"
             "        AND (shipto_id=:shipto_id)"
             "        AND (COALESCE(LENGTH(ipsass_shipto_pattern), 0) > 0)"
             "        AND (shipto_num ~ ipsass_shipto_pattern)"
             "        AND (ipsass_cust_id=:cust_id)"
             "        AND (CURRENT_DATE BETWEEN ipshead_effective AND (ipshead_expires - 1)) )"

             "       UNION SELECT ipsprice_price AS price"
             "       FROM sale, ipshead, ipsprice "
             "       WHERE ((sale_ipshead_id=ipshead_id)"
             "        AND (ipsprice_ipshead_id=ipshead_id)"
             "        AND (ipsprice_item_id=:item_id)"
             "        AND (CURRENT_DATE BETWEEN sale_startdate AND (sale_enddate - 1)) ) "

             "       UNION SELECT (item_listprice - (item_listprice * cust_discntprcnt)) AS price "
             "       FROM item, cust "
             "       WHERE ( (item_sold)"
             "        AND (NOT item_exclusive)"
             "        AND (item_id=:item_id)"
             "        AND (cust_id=:cust_id) );");
  q.bindValue(":item_id", _item->id());
  q.bindValue(":cust_id", _custid);
  q.bindValue(":shipto_id", _shiptoid);
  q.bindValue(":curr_id", _netUnitPrice->id());
  q.bindValue(":effective", _netUnitPrice->effective());
  q.exec();
  if (q.size() == 1)
  {
	q.first();
	_netUnitPrice->setLocalValue(q.value("price").toDouble() * (_priceinvuomratio / _priceRatio));
  }
  else
  {
    ParameterList params;
    params.append("cust_id", _custid);
    params.append("shipto_id", _shiptoid);
    params.append("item_id", _item->id());
    // don't params.append("qty", ...) as we don't know how many were purchased
    params.append("curr_id", _netUnitPrice->id());
    params.append("effective", _netUnitPrice->effective());

    priceList newdlg(this);
    newdlg.set(params);
    if (newdlg.exec() == XDialog::Accepted)
    {
      _netUnitPrice->setLocalValue(newdlg._selectedPrice * (_priceinvuomratio / _priceRatio));
      sCalculateDiscountPrcnt();
    }
  }
}
Exemplo n.º 7
0
void dspInventoryAvailabilityByCustomerType::sFillList()
{
  _avail->clear();

  QString sql( "SELECT itemsite_id, coitem_id,"
               "       cohead_id, cohead_number, (cust_number||'-'||cust_name) AS custname,"
               "       item_number, item_description, uom_name, item_picklist,"
               "       qoh, formatQty(qoh) AS f_qoh,sobalance,"
               "       formatQty(sobalance) AS f_sobalance,"
               "       formatQty(allocated) AS f_allocated,"
               "       ordered, formatQty(ordered) AS f_ordered,"
               "       (qoh + ordered - sobalance) AS woavail,"
               "<? if exists(\"useReservationNetting\") ?>"
               "       formatQty(coitem_qtyreserved) AS f_soavail,"
               "<? else ?>"
               "       formatQty(qoh + ordered - sobalance) AS f_soavail,"
               "<? endif ?>"
               "       (qoh + ordered - allocated) AS totalavail,"
               "       formatQty(qoh + ordered - allocated) AS f_totalavail,"
               "       atshipping,formatQty(atshipping) AS f_atshipping,"
               "       formatDate(coitem_scheddate) AS f_scheddate,"
               "       (coitem_qtyreserved > 0 AND sobalance > coitem_qtyreserved) AS partialreservation,"
               "       ((sobalance - coitem_qtyreserved) = 0) AS fullreservation,"
               "       reorderlevel "
               "<? if exists(\"showWoSupply\") ?>, "        
               "       wo_id,"
               "       wo_status,"
               "       wo_number,"
               "       wo_ordered,"
               "       formatQty(wo_ordered) AS f_wo_ordered,"
               "       formatDate(wo_startdate) AS f_wo_startdate, "
               "       formatDate(wo_duedate) AS f_wo_duedate,"
               "       COALESCE(wo_latestart,false) AS wo_latestart,"
               "       COALESCE(wo_latedue,false) AS wo_latedue "
               "<? endif ?>"
               "FROM ( SELECT itemsite_id, coitem_id,"
               "              cohead_id, cohead_number, cust_number, cust_name,"
               "              item_number, (item_descrip1 || ' ' || item_descrip2) AS item_description,"
               "              uom_name, item_picklist,"
               "              noNeg(itemsite_qtyonhand) AS qoh,"
               "              noNeg(coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned) AS sobalance,"
               "              qtyAllocated(itemsite_id, coitem_scheddate) AS allocated,"
               "              qtyOrdered(itemsite_id, coitem_scheddate) AS ordered,"
               "              qtyatshipping(coitem_id) AS atshipping,"
               "              coitem_qtyreserved,"
               "              coitem_scheddate,"
               "              CASE WHEN(itemsite_useparams) THEN itemsite_reorderlevel ELSE 0.0 END AS reorderlevel "
               "<? if exists(\"showWoSupply\") ?>, " 
               "              COALESCE(wo_id,-1) AS wo_id,"
               "              formatwonumber(wo_id) AS wo_number,"
               "              noNeg((wo_qtyord-wo_qtyrcv)) AS wo_ordered,"
               "              wo_status, wo_startdate, wo_duedate,"
               "              ((wo_startdate <= CURRENT_DATE) AND (wo_status IN ('O','E','S','R'))) AS wo_latestart,"
               "              (wo_duedate<=CURRENT_DATE) AS wo_latedue " 
               "<? endif ?>" 
               "       FROM cohead, cust, itemsite, item, uom, coitem "
               "<? if exists(\"showWoSupply\") ?> "
               "            LEFT OUTER JOIN wo"
               "             ON ((coitem_itemsite_id=wo_itemsite_id)"
               "             AND (wo_status IN ('E','R','I'))"
               "             AND (wo_qtyord-wo_qtyrcv > 0)"
               "             AND (noNeg(coitem_qtyord - coitem_qtyshipped + coitem_qtyreturned-qtyatshipping(coitem_id)) > "
               "              (SELECT itemsite_qtyonhand FROM itemsite WHERE (itemsite_id=coitem_itemsite_id))))"
               "<? endif ?>"
               "       WHERE ( (coitem_cohead_id=cohead_id)"
               "        AND (coitem_itemsite_id=itemsite_id)"
               "        AND (itemsite_item_id=item_id)"
               "        AND (item_inv_uom_id=uom_id)"
               "        AND (coitem_status NOT IN ('C', 'X'))"
               "        AND (cohead_cust_id=cust_id)"
               "<? if exists(\"custtype_id\") ?>"
               "        AND (cust_custtype_id=<? value(\"custtype_id\") ?>)"
               "<? elseif exists(\"custtype_pattern\") ?>"
               "        AND (cust_custtype_id IN (SELECT custtype_id "
               "                                    FROM custtype "
               "                                   WHERE(custtype_code ~ <? value(\"custtype_pattern\") ?>)))"
               "<? endif ?>"
               ")) AS data "
               " <? if exists(\"onlyShowShortages\") ?>"
               "WHERE ( ((qoh + ordered - allocated) < 0)"
               " OR ((qoh + ordered - sobalance) < 0) ) "
               "<? endif ?>"
               "ORDER BY cohead_id, cohead_number, item_number"
               "<? if exists(\"showWoSupply\") ?> ,"
               "wo_duedate"
               "<? endif ?>"
               ";");
    
  ParameterList params;             
  _custtype->appendValue(params);
  if (_onlyShowShortages->isChecked())
    params.append("onlyShowShortages");
  if (_showWoSupply->isChecked())
    params.append("showWoSupply");
  if (_useReservationNetting->isChecked())
    params.append("useReservationNetting");
  
  MetaSQLQuery mql(sql);
  q = mql.toQuery(params);
  if (q.first())
  {
    XTreeWidgetItem *coitem = NULL, *cohead = NULL;
    XTreeWidgetItem *wo = NULL;
    int coitemid = -1;
    int coheadid = -1;
      
    do
    {
      if (coitemid != q.value("coitem_id").toInt())
      {
        if(coheadid != q.value("cohead_id").toInt())
        {
          coheadid = q.value("cohead_id").toInt();
          cohead = new XTreeWidgetItem(_avail, cohead, coheadid, -2,
                                       q.value("cohead_number"), q.value("custname"));
        }

        coitemid = q.value("coitem_id").toInt();
        coitem = new XTreeWidgetItem( cohead, coitem,
                                             q.value("itemsite_id").toInt(), q.value("coitem_id").toInt(),
                                             q.value("item_number"),
                                             q.value("item_description"), q.value("uom_name"),
                                             q.value("f_qoh"), q.value("f_sobalance"),
                                             q.value("f_allocated"), q.value("f_ordered"),
                                             q.value("f_soavail"), q.value("f_totalavail"),
                                             q.value("f_atshipping"), q.value("f_scheddate") );

        if (q.value("qoh").toDouble() < 0)
          coitem->setTextColor(3, "red");
        else if (q.value("qoh").toDouble() < q.value("reorderlevel").toDouble())
          coitem->setTextColor(3, "orange");

        if (q.value("woavail").toDouble() < 0.0)
          coitem->setTextColor(7, "red");
        else if (q.value("woavail").toDouble() <= q.value("reorderlevel").toDouble())
          coitem->setTextColor(7, "orange");

        if (q.value("totalavail").toDouble() < 0.0)
          coitem->setTextColor(8, "red");
        else if (q.value("totalavail").toDouble() <= q.value("reorderlevel").toDouble())
          coitem->setTextColor(8, "orange"); 

        if(_useReservationNetting->isChecked())
        {
          if(q.value("partialreservation").toBool())
          {
            coitem->setTextColor(0, "blue");
            coitem->setTextColor(1, "blue");
            coitem->setTextColor(7, "blue");
          }
          else if(q.value("fullreservation").toBool())
          {
            coitem->setTextColor(0, "green");
            coitem->setTextColor(1, "green");
            coitem->setTextColor(7, "green");
          }
        }
      }
      if ((coitem)
      && (_showWoSupply->isChecked())
      && (q.value("wo_id").toInt() != -1) )
      {
        wo = new XTreeWidgetItem( coitem, wo,
                                             q.value("itemsite_id").toInt(),-1,
                                             q.value("wo_number"),"",
                                              q.value("wo_status"),
                                             "", "",
                                             "", q.value("f_wo_ordered"),
                                            q.value("f_wo_startdate"), q.value("f_wo_duedate"),
                                             "" );
                                             
        if (q.value("wo_latestart").toBool())
          wo->setTextColor(7, "red");
        if (q.value("wo_latedue").toBool())
          wo->setTextColor(8, "red");
      }
    }
    while (q.next());
  }
  if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  _avail->expandAll();
}
Exemplo n.º 8
0
bool dspTaxHistory::setParams(ParameterList &params)
{
  if (!(_sales->isChecked() || _purchases->isChecked()))
  {
    QMessageBox::warning( this, tr("Select items to show"),
                          tr("You must select sales or purchase items to show.") );
    return false;
  }
  
  if (!_dates->startDate().isValid())
  {
    QMessageBox::warning( this, tr("Enter Valid Start Date"),
                          tr("You must enter a valid Start Date to print this report.") );
    _dates->setFocus();
    return false;
  }

  if (!_dates->endDate().isValid())
  {
    QMessageBox::warning( this, tr("Enter Valid End Date"),
                          tr("You must enter a valid End Date to print this report.") );
    _dates->setFocus();
    return false;
  }
  
  if (_summary->isChecked())
    params.append("type", "summary");
  else
    params.append("type", "detail");
    
  if (_sales->isChecked())
    params.append("showSales");
  if (_purchases->isChecked())
    params.append("showPurchases");
    
  if (_distDate->isChecked())
    params.append("distDate");

  _dates->appendValue(params);
  
  if (((_showOnlyGroup->isCheckable() && _showOnlyGroup->isChecked()) || 
       !_showOnlyGroup->isCheckable()) &&
        _selection->id() != -1)
  {
    switch (_filterOn->currentIndex())
    {
      case 0:
        params.append("tax_id",_selection->id());
        break;

      case 1:
        params.append("taxtype_id",_selection->id());
        break;

      case 2:
        params.append("taxclass_id",_selection->id());
        break;
 
      case 3:
        params.append("taxauth_id",_selection->id());
        break;
      
      case 4:
        params.append("taxzone_id",_selection->id());
        break;
    }
  }
    
  if (_summary->isChecked())
  {
    params.append("summary");
    switch (_filterOn->currentIndex())
    {
      case 0:
        params.append("groupBy","tax");
        break;

      case 1:
        params.append("groupBy","taxtype");
        break;

      case 2:
        params.append("groupBy","taxclass");
        break;
 
      case 3:
        params.append("groupBy","taxauth");
        break;
      
      case 4:
        params.append("groupBy","taxzone");
        break;
    }
  }
  
  params.append("invoice",tr("Invoice"));
  params.append("creditmemo",tr("Credit Memo"));
  params.append("debitmemo",tr("Debit Memo"));
  params.append("other",tr("Other"));
  params.append("none",tr("None"));
  params.append("sales",tr("Sales"));
  params.append("purchase",tr("Purchase"));
  params.append("voucher",tr("Voucher"));

  return true;
}
bool dspARApplications::setParams(ParameterList & params)
{
  if ( (_selectedCustomer->isChecked()) && (!_cust->isValid()) )
  {
    QMessageBox::warning( this, tr("Select Customer"),
                          tr("You must select a Customer whose A/R Applications you wish to view.") );
    _cust->setFocus();
    return false;
  }

  if (!_dates->startDate().isValid())
  {
    QMessageBox::critical( this, tr("Enter Start Date"),
                           tr("You must enter a valid Start Date.") );
    _dates->setFocus();
    return false;
  }

  if (!_dates->endDate().isValid())
  {
    QMessageBox::critical( this, tr("Enter End Date"),
                           tr("You must enter a valid End Date.") );
    _dates->setFocus();
    return false;
  }

  if ( (!_cashReceipts->isChecked()) && (!_creditMemos->isChecked()) )
  {
    QMessageBox::critical( this, tr("Select Document Type"),
                           tr("You must indicate which Document Type(s) you wish to view.") );
    _cashReceipts->setFocus();
    return false;
  }
  
  if (_cashReceipts->isChecked())
    params.append("includeCashReceipts");

  if (_creditMemos->isChecked())
    params.append("includeCreditMemos");

  _dates->appendValue(params);
  params.append("creditMemo", tr("C/M"));
  params.append("debitMemo", tr("D/M"));
  params.append("cashdeposit", tr("Cash Deposit"));
  params.append("invoice", tr("Invoice"));
  params.append("cash", tr("C/R"));
  params.append("check", tr("Check"));
  params.append("certifiedCheck", tr("Cert. Check"));
  params.append("masterCard", tr("M/C"));
  params.append("visa", tr("Visa"));
  params.append("americanExpress", tr("AmEx"));
  params.append("discoverCard", tr("Discover"));
  params.append("otherCreditCard", tr("Other C/C"));
  params.append("cash", tr("Cash"));
  params.append("wireTransfer", tr("Wire Trans."));
  params.append("other", tr("Other"));
  params.append("apcheck", tr("A/P Check"));

  if (_selectedCustomer->isChecked())
    params.append("cust_id", _cust->id());
  else if (_selectedCustomerType->isChecked())
    params.append("custtype_id", _customerTypes->id());
  else if (_customerTypePattern->isChecked())
    params.append("custtype_pattern", _customerType->text());

  return true; 
}
Exemplo n.º 10
0
void employee::sVendor()
{
  XSqlQuery srq;
  if (_empid < 0 && _code->text().isEmpty())
  {
    QMessageBox::warning(this, tr("Specify an Employee Code"),
                         tr("<p>You must either be editing an existing "
                            "Employee or have at least given an Employee Code "
                            "before trying to associate this Employee with a "
                            "Vendor."));
    return;
  }
  else
  {
    srq.prepare("SELECT vend_id "
                "FROM vendinfo "
                "WHERE (upper(vend_number)=upper(:number));");
    srq.bindValue(":number", _number->text());
  }

  srq.exec();
  if (srq.first() &&
      (_privileges->check("MaintainVendors") ||
       _privileges->check("ViewVendors"))
      )
  {
    _vendor->setEnabled(true);
	sSave(false);
    ParameterList params;
    if (_mode == cView || ! _privileges->check("MaintainVendors"))
      params.append("mode", "view");
    else
	params.append("vend_id", srq.value("vend_id"));
    params.append("crmacct_number", _number->text());
    params.append("crmacct_name", _code->text().toLower());
    params.append("mode", "edit");
    vendor *newdlg = new vendor(this);
    newdlg->set(params);
    omfgThis->handleNewWindow(newdlg);
  }
  else if (srq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, srq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  else if (_privileges->check("MaintainVendors") &&
           (_mode == cEdit || _mode == cNew))
  {
    if (QMessageBox::question(this, tr("Create Vendor?"),
                              tr("<p>There does not appear to be a Vendor "
                                 "associated with this Employee. "
								 "Would you like to create a new Vendor?"),
				  QMessageBox::Yes | QMessageBox::Default,
				  QMessageBox::No) == QMessageBox::Yes)
    {
      sSave(false);
      ParameterList params;
      params.append("crmacct_number", _number->text());
      params.append("crmacct_name", _code->text().toLower());
	  params.append("mode",     "new");
      vendor *newdlg = new vendor(this);
      newdlg->set(params);
      omfgThis->handleNewWindow(newdlg);
    }
  }
}
Exemplo n.º 11
0
void selectOrderForBilling::sFillList()
{
  _soitem->clear();

  if (_so->isValid())
  {
    QString sql( "SELECT coitem_id, coitem_linenumber,"
                 "       item_number, item_invpricerat,"
                 "       warehous_code, coitem_price,"
                 "       formatQty(coitem_qtyord) AS f_qtyord,"
                 "       formatQty(coitem_qtyshipped) AS f_qtyshipped,"
                 "       formatQty(coitem_qtyreturned) AS f_qtyreturned,"
                 "       formatQty( ( SELECT COALESCE(SUM(coship_qty), 0)"
                 "                    FROM coship "
                 "                    WHERE ( (coship_coitem_id=coitem_id)"
                 "                     AND (NOT coship_invoiced) ) )"
                 "                 ) AS f_qtyatship,"
                 "       ( SELECT COALESCE(SUM(cobill_qty), 0)"
                 "         FROM cobill, cobmisc "
                 "         WHERE ( (cobill_cobmisc_id=cobmisc_id)"
                 "          AND (cobill_coitem_id=coitem_id)"
                 "          AND (NOT cobmisc_posted) ) ) AS qtytobill,"
                 "       round((coitem_price * "
                 "         ( SELECT COALESCE(SUM(cobill_qty), 0)"
                 "           FROM cobill, cobmisc "
                 "           WHERE ( (cobill_cobmisc_id=cobmisc_id)"
                 "            AND (cobill_coitem_id=coitem_id)"
                 "            AND (NOT cobmisc_posted) ) ) "
                 "          / item_invpricerat), 2) AS extended, "
                 "       formatMoney(round((coitem_price * "
                 "         ( SELECT COALESCE(SUM(cobill_qty), 0)"
                 "           FROM cobill, cobmisc "
                 "           WHERE ( (cobill_cobmisc_id=cobmisc_id)"
                 "            AND (cobill_coitem_id=coitem_id)"
                 "            AND (NOT cobmisc_posted) ) ) "
                 "          / item_invpricerat), 2)) AS f_extended, "
                 "       formatBoolYN( ( SELECT COALESCE(cobill_toclose, FALSE)"
                 "                       FROM cobill, cobmisc "
                 "                       WHERE ((cobill_cobmisc_id=cobmisc_id)"
                 "                        AND (cobill_coitem_id=coitem_id)"
                 "                        AND (NOT cobmisc_posted))"
                 "                       ORDER BY cobill_toclose DESC"
                 "                       LIMIT 1) ) AS toclose "
                 "FROM coitem, itemsite, item, warehous "
                 "WHERE ( (coitem_itemsite_id=itemsite_id)"
                 " AND (coitem_status <> 'X')"
                 " AND (itemsite_item_id=item_id)"
                 " AND (itemsite_warehous_id=warehous_id)"
		 " <? if exists(\"showOpenOnly\") ?>"
		 " AND (coitem_status <> 'C')"
		 " <? endif ?>"
		 " AND (coitem_cohead_id=<? value(\"sohead_id\") ?>) ) "
		 "ORDER BY coitem_linenumber;" );

    ParameterList params;
    if (!_showClosed->isChecked())
      params.append("showOpenOnly");
    params.append("sohead_id", _so->id());
    MetaSQLQuery mql(sql);
    q = mql.toQuery(params);
    if (q.first())
    {
      double subtotal = 0.0;

      XTreeWidgetItem* last = 0;
      do
      {
        subtotal += q.value("extended").toDouble();

        last = new XTreeWidgetItem(_soitem, last, q.value("coitem_id").toInt(),
                            q.value("coitem_linenumber"), q.value("item_number"),
                            q.value("warehous_code"), q.value("f_qtyord"),
                            q.value("f_qtyshipped"), q.value("f_qtyreturned"),
                            q.value("f_qtyatship"), formatQty(q.value("qtytobill").toDouble()),
                            q.value("f_extended"), q.value("toclose") );
      }
      while (q.next());

      _subtotal->setLocalValue(subtotal);
    }
    else
    {
      if (q.lastError().type() != QSqlError::None)
	systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      _subtotal->clear();
    }

    recalculateTax();
  }
}
Exemplo n.º 12
0
void employee::sSalesrep()
{
  XSqlQuery srq;
  if (_empid < 0 && _code->text().isEmpty())
  {
    QMessageBox::warning(this, tr("Specify an Employee Code"),
                         tr("<p>You must either be editing an existing "
                            "Employee or have at least given an Employee Code "
                            "before trying to associate this Employee with a "
                            "Sales Rep."));
    return;
  }
  else if (_empid >= 0)
  {
    srq.prepare("SELECT salesrep_id "
                "FROM salesrep "
                "WHERE (salesrep_emp_id=:id);");
    srq.bindValue(":id", _empid);
  }
  else
  {
    srq.prepare("SELECT salesrep_id "
                "FROM salesrep "
                "WHERE (salesrep_number=:number);");
    srq.bindValue(":number", _number->text());
  }

  srq.exec();
  if (srq.first() &&
      (_privileges->check("MaintainSalesReps") ||
       _privileges->check("ViewSalesReps"))
      )
  {
    sSave(false);
    ParameterList params;
    if (_mode == cView || ! _privileges->check("MaintainSalesReps"))
      params.append("mode", "view");
    else
      params.append("mode", "edit");
    params.append("salesrep_id", srq.value("salesrep_id"));
    params.append("emp_id",      _empid);
    salesRep newdlg(this, "", TRUE);
    newdlg.set(params);
    _salesrep->setEnabled(newdlg.exec() == QDialog::Rejected);
  }
  else if (srq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, srq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  else if (_privileges->check("MaintainSalesReps") &&
           (_mode == cEdit || _mode == cNew))
  {
    if (QMessageBox::question(this, tr("Create Sales Rep?"),
                              tr("<p>There does not appear to be a Sales "
                                 "Rep associated with this Employee. "
                                 "Would you like to create a new Sales "
                                 "Rep?"),
				  QMessageBox::Yes | QMessageBox::Default,
				  QMessageBox::No) == QMessageBox::Yes)
    {
      sSave(false);
      ParameterList params;
      params.append("mode",     "new");
      params.append("emp_id",   _empid);
      salesRep newdlg(this, "", TRUE);
      newdlg.set(params);
      _salesrep->setEnabled(newdlg.exec() == QDialog::Rejected);
    }
  }
}
Exemplo n.º 13
0
void employee::sSave(const bool pClose)
{
  if (_code->text().length() == 0)
  {
      QMessageBox::warning( this, tr("Cannot Save Employee"),
                            tr("You must enter a valid Employee Code.") );
      return;
  }
  
  if (_code->text() == _mgr->number())
  {
      QMessageBox::warning( this, tr("Cannot Save Employee"),
                            tr("An Employee cannot be his or her own Manager.") );
      return;
  }
  
  if (_mode == cNew)
  {
    q.prepare("SELECT emp_id"
              "  FROM emp"
              " WHERE(emp_code=:code)");
    q.bindValue(":code", _code->text());
    q.exec();
    if(q.first())
    {
      QMessageBox::critical(this, tr("Duplicate Employee"),
        tr("An Employee already exists for the Code specified.") );
      _code->setFocus();
      return;
    }
    q.prepare("SELECT emp_id"
              "  FROM emp"
              " WHERE(emp_number=:number)");
    q.bindValue(":number", _number->text());
    q.exec();
    if(q.first())
    {
      QMessageBox::critical(this, tr("Duplicate Employee"),
        tr("An Employee already exists for the Number specified.") );
      _number->setFocus();
      return;
    }
  }

  if (_user->isChecked() && pClose)
  {
    q.prepare("SELECT usr_id FROM usr WHERE usr_username=:username;");
    q.bindValue(":username", _code->text().toLower());
    q.exec();
    if (q.first())
    {
      // OK
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (_createUsers) // not found
    {
      if (QMessageBox::question(this, tr("No Corresponding User"),
                            tr("There is no User named %1. Would you like to "
                               "create one now?<p>If you answer 'No' then you "
                               "should either Cancel creating this Employee, "
                               "uncheck the User check box, or use a different "
                               "Employee Code.")
                            .arg(_code->text()),
                            QMessageBox::Yes | QMessageBox::Default,
                            QMessageBox::No) == QMessageBox::Yes)
      {
        // don't use sUser() because it asks too many questions
		ParameterList params;
        params.append("mode",     "new");
        params.append("username", _code->text().toLower());
        user newdlg(this);
        newdlg.set(params);
        newdlg.exec();
        _user->setChecked(true);
      }
      return;
    }
    else // not found
    {
      systemError(this, tr("There is no User named %1. Either Cancel creating "
                           "this Employee or use a different Employee Code.")
                         .arg(_code->text()));
      return;
    }
  }
  
  if (_salesrep->isChecked() && pClose)
  {
    q.prepare("SELECT salesrep_id FROM salesrep WHERE salesrep_number=:username;");
    q.bindValue(":username", _code->text());
    q.exec();
    if (q.first())
    {
      // OK
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (_privileges->check("MaintainSalesReps")) // not found
    {
      if (QMessageBox::question(this, tr("No Corresponding SalesRep"),
                            tr("There is no Sales Rep. named %1. Would you "
                               "like to create one now?<p>If you answer 'No' "
                               "then you should either Cancel creating this "
                               "Employee, uncheck the Sales Rep check box, or "
                               "use a different Employee Code.")
                            .arg(_code->text()),
                            QMessageBox::Yes | QMessageBox::Default,
                            QMessageBox::No) == QMessageBox::Yes)
      {
        // don't use sSalesrep() because it asks too many questions
        ParameterList params;
        params.append("mode",     "new");
        params.append("emp_id",   _empid);
        salesRep newdlg(this, "", TRUE);
        newdlg.set(params);
        newdlg.exec();
      }
      return;
    }
    else // not found
    {
      systemError(this, tr("There is no User named %1. Either Cancel creating "
                           "this Employee or use a different Employee Code.")
                         .arg(_code->text()));
      return;
    }
  }

  if (_vendor->isChecked() && pClose)
  {
	q.prepare("SELECT vend_id FROM vendinfo WHERE upper(vend_number)=upper(:number);");
    q.bindValue(":number", _number->text());
    q.exec();
    if (q.first())
    {
      // OK
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (_privileges->check("MaintainVendors")) // not found
    {
      if (QMessageBox::question(this, tr("No Corresponding Vendor"),
                            tr("There is no Vendor named %1. Would you "
                               "like to create one now?<p>If you answer 'No' "
                               "then you should either Cancel creating this "
                               "Employee, uncheck the Vendor check box, or "
                               "use a different Employee Code.")
                            .arg(_code->text()),
                            QMessageBox::Yes | QMessageBox::Default,
                            QMessageBox::No) == QMessageBox::Yes)
      {
		ParameterList params;
		params.append("crmacct_number", _number->text());
		params.append("crmacct_name", _code->text().toLower());
		params.append("mode", "new");
		vendor *newdlg = new vendor(this);
		newdlg->set(params);
		omfgThis->handleNewWindow(newdlg);
      }
      return;
    }
    else // not found
    {
      systemError(this, tr("There is no User named %1. Either Cancel creating "
                           "this Employee or use a different Employee Code.")
                         .arg(_code->text()));
      return;
    }
  }


  _contact->check();

  if (_mode == cNew)
    q.prepare("INSERT INTO api.employee ("
              " code, number, active, start_date,"
              " contact_number, honorific, first, last, job_title,"
              " voice, alternate, fax, email,"
              " web, contact_change,"
              " address_number, address1, address2, address3,"
              " city, state, postalcode,"
              " country, address_change,"
              " site, manager_code,"
              " wage_type, wage, wage_currency, wage_period,"
              " department, shift, is_user, is_salesrep, is_vendor, notes, image, "
			  " rate, billing_currency, billing_period"
              ") VALUES ("
			  " :code, :number, :active, :start_date,"
              " :cntctnumber, :hnfc, :first, :last, :jobtitle,"
              " :voice, :alt, :fax, :email,"
              " :web, :cntctmode,"
              " :addrnumber, :addr1, :addr2, :addr3,"
              " :city, :state, :zip,"
              " :country, :addrmode,"
              " :site, :mgrcode,"
              " :wagetype, :wage, :wagecurr, :wageper,"
			  " :dept, :shift, :isusr, :isrep, :isvendor, :notes, :image, :rate, :billing_currency, :billing_period);");

  else if (_mode == cEdit)
    q.prepare("UPDATE api.employee SET"
              " code=:code,"
              " number=:number,"
              " active=:active,"
			  " start_date=:start_date,"
              " contact_number=:cntctnumber,"
              " honorific=:hnfc,"
              " first=:first,"
              " last=:last,"
              " job_title=:jobtitle,"
              " voice=:voice,"
              " alternate=:alt,"
              " fax=:fax,"
              " email=:email,"
              " web=:web,"
              " contact_change=:cntctmode,"
              " address_number=:addrnumber,"
              " address1=:addr1,"
              " address2=:addr2,"
              " address3=:addr3,"
              " city=:city,"
              " state=:state,"
              " postalcode=:zip,"
              " country=:country,"
              " address_change=:addrmode,"
              " site=:site,"
              " manager_code=:mgrcode,"
              " wage_type=:wagetype,"
              " wage=:wage,"
              " wage_currency=:wagecurr,"
              " wage_period=:wageper,"
              " department=:dept,"
              " shift=:shift,"
              " is_user=:isusr,"
              " is_salesrep=:isrep,"
			  " is_vendor=:isvendor,"
              " notes=:notes,"
              " image=:image,"
			  " rate=:rate,"
			  " billing_currency=:billing_currency,"
			  " billing_period=:billing_period"
              " WHERE (code=:origcode);" );

  q.bindValue(":code",        _code->text());
  q.bindValue(":number",      _number->text());
  q.bindValue(":active",      _active->isChecked());
  q.bindValue(":start_date",   _startDate->date());
  q.bindValue(":cntctnumber", _contact->number());
  q.bindValue(":hnfc",        _contact->honorific());
  q.bindValue(":first",       _contact->first());
  q.bindValue(":last",        _contact->last());
  q.bindValue(":jobtitle",    _contact->title());
  q.bindValue(":voice",       _contact->phone());
  q.bindValue(":alt",         _contact->phone2());
  q.bindValue(":fax",         _contact->fax());
  q.bindValue(":email",       _contact->emailAddress());
  q.bindValue(":web",         _contact->webAddress());
  q.bindValue(":cntctmode",   _contact->change());
  q.bindValue(":addrnumber",  _contact->addressWidget()->number());
  q.bindValue(":addr1",       _contact->addressWidget()->line1());
  q.bindValue(":addr2",       _contact->addressWidget()->line2());
  q.bindValue(":addr3",       _contact->addressWidget()->line3());
  q.bindValue(":city",        _contact->addressWidget()->city());
  q.bindValue(":state",       _contact->addressWidget()->state());
  q.bindValue(":zip",         _contact->addressWidget()->postalCode());
  q.bindValue(":country",     _contact->addressWidget()->country());
  q.bindValue(":addrmode",    _contact->addressWidget()->addrChange());
  q.bindValue(":site",        _site->code());
  q.bindValue(":mgrcode",     _mgr->number());
  q.bindValue(":wagetype",    _wagetype->code());
  q.bindValue(":wage",        _rate->localValue());
  q.bindValue(":wagecurr",    _currabbr);
  q.bindValue(":wageper",     _per->code());
  q.bindValue(":dept",        _dept->number());
  q.bindValue(":shift",       _shift->number());
  q.bindValue(":isusr",       _user->isChecked());
  q.bindValue(":isrep",       _salesrep->isChecked());
  q.bindValue(":isvendor",    _vendor->isChecked());
  q.bindValue(":notes",       _notes->toPlainText());
  q.bindValue(":origcode",    _empcode);
  q.bindValue(":image",       _image->number());
  q.bindValue(":rate",		  _externalRate->localValue());
  q.bindValue(":billing_currency",	_currabbr);
  q.bindValue(":billing_period",	_perExt->code());

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

  if (_mode == cNew)
  {
    q.exec("SELECT CURRVAL('emp_emp_id_seq') AS result;");
    if (q.first())
    {
      _empid = q.value("result").toInt();
      _mode  = cEdit;
      _comments->setId(_empid);
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }

  if (pClose)
    done(_empid);
}
Exemplo n.º 14
0
void AddressSearch::sFillList()
{
    _listTab->clear();
    if (_search->text().isEmpty() ||
        (!_searchStreet->isChecked() && !_searchCity->isChecked() &&
         !_searchState->isChecked()  && !_searchCountry->isChecked() &&
         !_searchPostalCode->isChecked() ))
      return;

    QString sql = _parent->_query +
                  "<? if exists(\"extraClause\") ?> "
                  "  <? value(\"extraClause\") ?> "
                  "<? else ?>"
                  "  WHERE "
                  "<? endif ?> "
                  "<? if exists(\"searchInactive\") ?> "
                  "   true "
                  "<? else ?>"
                  "   addr_active "
                  "<? endif ?>"
                  "<? if reExists(\"search[CPS]\") ?> "
                  "  AND ("
                  "  <? if exists(\"searchStreet\") ?> "
                  "    addr_line1 || '\n' || addr_line2 || '\n' || addr_line3 || '\n' "
                  "  <? else ?>"
                  "    '\n' "
                  "  <? endif ?>"
                  "  <? if exists(\"searchCity\") ?> "
                  "     || addr_city || '\n' "
                  "  <? endif ?>"
                  "  <? if exists(\"searchState\") ?> "
                  "     || addr_state || '\n' "
                  "  <? endif ?>"
                  "  <? if exists(\"searchCountry\") ?> "
                  "     || addr_country || '\n' "
                  "  <? endif ?>"
                  "  <? if exists(\"searchPostalCode\") ?> "
                  "     || addr_postalcode || '\n' "
                  "  <? endif ?>"
                  "  ~* <? value(\"searchText\") ?> )"
                  "<? endif ?>"
                  "ORDER BY addr_country, addr_state, addr_postalcode;";
    ParameterList params;
    if (_searchStreet->isChecked())
      params.append("searchStreet");
    if (_searchCity->isChecked())
      params.append("searchCity");
    if (_searchState->isChecked())
      params.append("searchState");
    if (_searchCountry->isChecked())
      params.append("searchCountry");
    if (_searchPostalCode->isChecked())
      params.append("searchPostalCode");
    if (_searchInactive->isChecked())
      params.append("searchInactive");
    if (! _parent->_extraClause.isEmpty())
      params.append("extraClause", _parent->_extraClause);

    params.append("searchText", _search->text());

    MetaSQLQuery mql(sql);
    XSqlQuery query = mql.toQuery(params);
    query.exec();
    _listTab->populate(query);
    if (query.lastError().type() != QSqlError::NoError)
    {
      QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
                                    .arg(__FILE__)
                                    .arg(__LINE__),
                            query.lastError().databaseText());
      return;
    }

}
bool dspSummarizedSales::setParams(ParameterList & params)
{
  if (!_cust->isChecked() &&
      !_custtype->isChecked() &&
      !_salesrep->isChecked() &&
      !_shipzone->isChecked() &&
      !_item->isChecked() &&
      !_site->isChecked())
  {
    QMessageBox::warning( this, tr("Select a Group By"),
                          tr("Please select at least one Group By option.") );
    return false;
  }

  parameterWidget()->appendValue(params);
  params.append("filter", parameterWidget()->filter());

  QList<QVariant> groupLitList;
  QList<QVariant> groupList;
  QList<QVariant> groupDescripList;
  if (_cust->isChecked())
  {
    groupLitList.append(tr("'Customer:'"));
    groupList.append("cust_number");
    groupDescripList.append("cust_name");
    params.append("byCustomer");
  }
  if (_custtype->isChecked())
  {
    groupLitList.append(tr("'Cust. Type:'"));
    groupList.append("custtype_code");
    groupDescripList.append("custtype_descrip");
    params.append("byCustomerType");
  }
  if (_salesrep->isChecked())
  {
    groupLitList.append(tr("'Sales Rep.:'"));
    groupList.append("salesrep_number");
    groupDescripList.append("salesrep_name");
    params.append("bySalesRep");
  }
  if (_shipzone->isChecked())
  {
    groupLitList.append(tr("'Ship Zone:'"));
    groupList.append("COALESCE(shipzone_name,'')");
    groupDescripList.append("COALESCE(shipzone_descrip,'')");
    params.append("byShippingZone");
  }
  if (_item->isChecked())
  {
    groupLitList.append(tr("'Item:'"));
    groupList.append("item_number");
    groupDescripList.append("itemdescription");
    params.append("byItem");
  }
  if (_site->isChecked())
  {
    groupLitList.append(tr("'Site:'"));
    groupList.append("warehous_code");
    groupDescripList.append("warehous_descrip");
    params.append("bySite");
  }
  if (_units->currentIndex())
  {
    params.append("byCurrency");
  }

  params.append("groupLitList", groupLitList);
  params.append("groupList", groupList);
  params.append("groupDescripList", groupDescripList);

  return true;
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  QString passwd;
  QString company;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    haveEnhancedAuth= false;
  bool    _enhancedAuth   = false;
  bool    haveRequireSSL  = false;
  bool    _requireSSL     = false;
  bool    havePasswd      = false;
  bool    cloudOption     = false;
  bool    haveCloud       = false;

  qInstallMsgHandler(xTupleMessageOutput);
  QApplication app(argc, argv);

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

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

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

  app.processEvents();

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

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

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

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
    params.append("copyright", _Copyright);
    params.append("version", _Version);
    params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__));

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

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

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

    if (haveEnhancedAuth)
      params.append("enhancedAuth", _enhancedAuth);
    
    if (haveRequireSSL)
      params.append("requireSSL", _requireSSL);

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

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

    if (haveCloud)
      params.append("cloud", cloudOption);

    if (!company.isEmpty())
      params.append("company", company);

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

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

  XSqlQuery metric;
  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'Application')" );
  if(!metric.first() || (metric.value("metric_value").toString() == "Standard"))
  {
    // check if the xtmfg package is installed
    metric.exec("SELECT pkghead_name FROM pkghead WHERE pkghead_name='xtmfg'");
    if(metric.first())
    {
      _splash->setPixmap(QPixmap(":/images/splashMfgEdition.png"));
      _Name = _Name.arg("Manufacturing");
    }
    else
    {
      _splash->setPixmap(QPixmap(":/images/splashStdEdition.png"));
      _Name = _Name.arg("Standard");
    }

    _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
    metric.exec("SELECT COUNT(*) as _count"
                "  FROM pg_stat_activity"
                " WHERE(datid IN (SELECT datid"
                "                   FROM pg_stat_activity"
                "                  WHERE(procpid=pg_backend_pid())));");
    int cnt = 50000;
    if(metric.first())
      cnt = metric.value("_count").toInt();
    metric.exec("SELECT metric_value"
                "  FROM metric"
                " WHERE(metric_name = 'RegistrationKey');");
    bool checkPass = true;
    QString checkPassReason;
    QString rkey = "";
    if(metric.first())
      rkey = metric.value("metric_value").toString();
    XTupleProductKey pkey(rkey);
    if(pkey.valid() && pkey.version() == 1)
    {
      if(pkey.expiration() < QDate::currentDate())
      {
        checkPass = false;
        checkPassReason = QObject::tr("Your license has expired.");
      }
      else if(pkey.users() != 0 && (pkey.users()+1) < cnt)
      {
        checkPass = false;
        checkPassReason = QObject::tr("You have exceeded the number of allowed concurrent users for your license.");
      }
    }
    else
    {
      checkPass = false;
      checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid.");
    }
    if(!checkPass)
    {
      _splash->hide();
      QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason);

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

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

      http->setHost("www.xtuple.org");
      http->get(url.toString());
      _splash->show();
    }
  }
  else
  {
    _splash->setPixmap(QPixmap(":/images/splashPostBooks.png"));
    _Name = _Name.arg("PostBooks");
  }

  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'ServerVersion')" );
  if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion))
  {
    bool disallowMismatch = false;
    metric.exec("SELECT metric_value FROM metric WHERE(metric_name='DisallowMismatchClientVersion')");
    if(metric.first() && (metric.value("metric_value").toString() == "t"))
      disallowMismatch = true;
    
    _splash->hide();
    int result;
    if(disallowMismatch)
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. The system has been configured to disallow "
                    "access in this case.<p>Please contact your systems "
                    "administrator.").arg(_dbVersion),
                 QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default );
    else
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. If you continue some or all functionality may "
                    "not work properly or at all. You may also cause other "
                    "problems on the database.<p>Do you want to continue "
                    "anyway?").arg(_dbVersion),
                 QMessageBox::Yes,
                 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
    if(result != QMessageBox::Yes)
      return 0;
    _splash->show();
  }

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

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

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

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

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

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

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

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

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

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

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

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

  qApp->processEvents();
  QString key;

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

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

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

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

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

  omfgThis = 0;
  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;
  omfgThis->_company = company;
  omfgThis->_useCloud = cloudOption;

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

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

  QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows()));
  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->setAttribute(Qt::WA_DeleteOnClose);
    omfgThis->show();
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    ScriptToolbox sb(0);
    QWidget* newdlg = sb.openWindow("woTimeClock");
    if(newdlg)
    {
      XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg);
      if(mw)
      {
        ParameterList params;
        params.append("captive");
        mw->set(params);
      }
      newdlg->setAttribute(Qt::WA_DeleteOnClose);
      QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
      newdlg->show();
    }
    else
    {
Exemplo n.º 17
0
void postCostsByItem::sSubmit()
{
  ParameterList params;

  params.append("action_name", "PostActualCost");
  params.append("item_id", _item->id());

  if (_material->isChecked())
    params.append("Material");

  if (_lowerMaterial->isChecked())
    params.append("LowerMaterial");

  if (_directLabor->isChecked())
    params.append("DirectLabor");

  if (_lowerDirectLabor->isChecked())
    params.append("LowerDirectLabor");

  if (_overhead->isChecked())
    params.append("Overhead");

  if (_lowerOverhead->isChecked())
    params.append("LowerOverhead");

  if (_machOverhead->isChecked())
    params.append("MachineOverhead");

  if (_lowerMachOverhead->isChecked())
    params.append("LowerMachineOverhead");

  if (_user->isChecked())
    params.append("User");

  if (_lowerUser->isChecked())
    params.append("LowerUser");

  if (_rollUp->isChecked())
    params.append("RollUp");

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

  if (newdlg.exec() == XDialog::Accepted)
    accept();
}
Exemplo n.º 18
0
void ContactSearch::sFillList()
{
    _listTab->clear();
    if (_search->text().isEmpty() ||
	(!_searchFirst->isChecked()    && !_searchLast->isChecked() &&
	 !_searchCRMAcct->isChecked()  && !_searchTitle->isChecked() &&
	 !_searchPhones->isChecked()   &&
	 !_searchEmail->isChecked()    && !_searchWebAddr->isChecked() ))
      return;

    QString limits = 
      "<? if exists(\"extraClause\") ?> "
      "  AND "
      "<? else ?>"
      "  WHERE "
      "<? endif ?> "
      "<? if exists(\"searchInactive\") ?> "
      "   true "
      "<? else ?>"
      "   cntct_active "
      "<? endif ?>"
      "<? if reExists(\"search[FLCTPEW]\") ?> "
      "  AND ("
      "  <? if exists(\"searchFirst\") ?> "
      "     COALESCE(cntct_first_name,'') || '\n' "
      "  <? else ?>"
      "    '\n' "
      "  <? endif ?>"
      "  <? if exists(\"searchLast\") ?> "
      "     || COALESCE(cntct_last_name,'') || '\n' "
      "  <? endif ?>"
      "  <? if exists(\"searchCRMAcct\") ?> "
      "     || COALESCE(crmacct_name,'') || '\n' "
      "  <? endif ?>"
      "  <? if exists(\"searchTitle\") ?> "
      "     || COALESCE(cntct_title,'') || '\n' "
      "  <? endif ?>"
      "  <? if exists(\"searchPhones\") ?> "
      "    || COALESCE(cntct_phone,'') || '\n' "
      "    || COALESCE(cntct_phone2,'') || '\n' "
      "    || COALESCE(cntct_fax,'') || '\n' "
      "  <? endif ?>"
      "  <? if exists(\"searchEmail\") ?> "
      "     || COALESCE(cntct_email,'') || '\n' "
      "  <? endif ?>"
      "  <? if exists(\"searchWebAddr\") ?> "
      "     || COALESCE(cntct_webaddr,'') || '\n' "
      "  <? endif ?>"
      "  ~* <? value(\"searchText\") ?> )"
      "<? endif ?>"
      "ORDER BY cntct_last_name, cntct_first_name, crmacct_number;";
    QString sql = _parent->_query +
		  _parent->_extraClause.replace(":searchAcctId",
					QString::number(_parent->_searchAcctId)) +
		  limits;

    ParameterList params;
    if (_searchFirst->isChecked())
      params.append("searchFirst");
    if (_searchLast->isChecked())
      params.append("searchLast");
    if (_searchCRMAcct->isChecked())
      params.append("searchCRMAcct");
    if (_searchTitle->isChecked())
      params.append("searchTitle");
    if (_searchPhones->isChecked())
      params.append("searchPhones");
    if (_searchEmail->isChecked())
      params.append("searchEmail");
    if (_searchWebAddr->isChecked())
      params.append("searchWebAddr");
    if (_searchInactive->isChecked())
      params.append("searchInactive");
    if (! _parent->_extraClause.isEmpty())
      params.append("extraClause", _parent->_extraClause);

    params.append("searchText", _search->text());

    MetaSQLQuery mql(sql);
    XSqlQuery query = mql.toQuery(params);
    if (query.lastError().type() != QSqlError::None)
    {
      QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
				    .arg(__FILE__)
				    .arg(__LINE__),
			    query.lastError().databaseText());
      return;
    }
    else if (query.size() < 1)	// no rows found with limit so try without
    {
      sql = _parent->_query + limits;
      MetaSQLQuery mqlAllAccnts(sql);
      query = mqlAllAccnts.toQuery(params);
      if (query.lastError().type() != QSqlError::None)
      {
	QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
				      .arg(__FILE__)
				      .arg(__LINE__),
			      query.lastError().databaseText());
	return;
      }
    }

    XTreeWidgetItem *last = 0;
    while (query.next())
    {
      last = new XTreeWidgetItem(_listTab, last,
			 query.value("cntct_id").toInt(), 0,
			 query.value("cntct_first_name"),
			 query.value("cntct_last_name"),
			 query.value("crmacct_name"),
			 query.value("cntct_title"),
			 query.value("cntct_phone"),
			 query.value("cntct_phone2"),
			 query.value("cntct_fax"),
			 query.value("cntct_email"),
			 query.value("cntct_webaddr"));
    }
}
Exemplo n.º 19
0
void AddressCluster::populateStateComboBox()
{
  if(_x_metrics == 0)
    return;

  QString tmpstate = _state->currentText();
  if (DEBUG)
    qDebug("%s::populateStateComboBox() entered country %d/%s (matching id = %d) with state %s",
           (objectName().isEmpty() ? "AddressCluster":qPrintable(objectName())),
           _country->id(), qPrintable(_country->currentText()),
           _country->id() == _country->id(_country->findText(_country->currentText(),
                                                             Qt::MatchExactly)),
           qPrintable(tmpstate));
  _state->clear();

  XSqlQuery stateq;
  if (_country->id() >= 0 &&
      _country->id() == _country->id(_country->findText(_country->currentText(),
                                                        Qt::MatchExactly)))
  {
    MetaSQLQuery state("SELECT DISTINCT state_id,"
                       "       CASE WHEN state_abbr IS NULL THEN state_name"
                       "            WHEN TRIM(state_abbr) = '' THEN state_name"
                       "            ELSE state_abbr END,"
                       "       CASE WHEN state_abbr IS NULL THEN state_name"
                       "            WHEN TRIM(state_abbr) = '' THEN state_name"
                       "            ELSE state_abbr END"
                       "  FROM state"
                       " WHERE (state_country_id=<? value(\"country_id\") ?>) "
                       "ORDER BY 2;");
    ParameterList params;
    params.append("country_id", _country->id());

    stateq = state.toQuery(params);
    _state->populate(stateq);

    _state->setEditable(_state->count() <= 1 ||
                        (! tmpstate.isEmpty() &&
                         ! _state->findText(tmpstate, Qt::MatchExactly) >= 0));
    if (_state->count() <= 1)
    {
      if (DEBUG)
        qDebug("%s::populateStateComboBox() find states for stateless country",
           (objectName().isEmpty() ? "AddressCluster":qPrintable(objectName())));
      stateq.prepare("SELECT MIN(addr_id), addr_state, addr_state"
                     "  FROM addr"
                     " WHERE (addr_country=:country)"
                     " GROUP BY addr_state"
                     " ORDER BY addr_state;");
      stateq.bindValue(":country", _country->currentText());
      stateq.exec();
      _state->populate(stateq);
    }
  }
  else
  {
    stateq.exec("SELECT MIN(addr_id), addr_state, addr_state"
                "  FROM addr"
                " GROUP BY addr_state"
                " ORDER BY addr_state;");
    _state->populate(stateq);
    _state->setEditable(true);
  }

  if (_state->isEditable())
    _state->setEditText(tmpstate);
  else
    _state->setText(tmpstate);

  if (DEBUG)
    qDebug("%s::populateStateComboBox() returning id %d, text %s, tmpstate %s",
           (objectName().isEmpty() ? "AddressCluster":qPrintable(objectName())),
         _state->id(), qPrintable(_state->currentText()), qPrintable(tmpstate));
}
int AuthorizeDotNetProcessor::doCredit(const int pccardid, const QString &pcvv, const double pamount, const double ptax, const bool ptaxexempt, const double pfreight, const double pduty, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams)
{
  Q_UNUSED(pcvv);
  if (DEBUG)
    qDebug("AN:doCredit(%d, pcvv, %f, %f, %d, %f, %f, %d, %s, %s, %d)",
	   pccardid, pamount, ptax, ptaxexempt,  pfreight,  pduty, pcurrid,
	   pneworder.toAscii().data(), preforder.toAscii().data(), pccpayid);

  int     returnValue = 0;
  double  amount  = pamount;
  int     currid  = pcurrid;
  bool    tryVoid = false;
  QString approvalCode;
  QString request;

  returnValue = buildFollowup(pccpayid, preforder, amount, currid, request, "CREDIT");
  if (returnValue != 0)
    return returnValue;

  XSqlQuery anq;
  anq.prepare("SELECT ccpay_card_pan_trunc,"
              "  (ccpay_transaction_datetime > CURRENT_DATE"
              "  AND ccpay_amount = :amount) AS tryVoid,"
              "  ccpay_r_code,"
              "  formatbytea(decrypt(setbytea(ccard_number),"
              "              setbytea(:key),'bf')) AS ccard_number"
              "  FROM ccpay LEFT OUTER JOIN ccard ON (ccpay_ccard_id=ccard_id)"
              " WHERE (ccpay_id=:ccpayid);");
  anq.bindValue(":ccpayid", pccpayid);
  anq.bindValue(":key",     omfgThis->_key);
  anq.bindValue(":now",     QDateTime::currentDateTime());
  anq.bindValue(":amount",  amount);
  anq.exec();
  if (anq.first())
  {
    QString cardnum = anq.value("ccpay_card_pan_trunc").toString();
    if (cardnum.isEmpty())
      cardnum = anq.value("ccard_number").toString();
    APPENDFIELD(request, "x_card_num", cardnum.right(4));
    tryVoid = anq.value("tryVoid").toBool();
    approvalCode = anq.value("ccpay_r_code").toString();
  }
  else if (anq.lastError().type() != QSqlError::NoError)
  {
    _errorMsg = anq.lastError().databaseText();
    return -1;
  }

  QString response;
  returnValue = sendViaHTTP(request, response);
  if (returnValue < 0)
    return returnValue;

  returnValue = handleResponse(response, pccardid, "R", amount, currid,
			       pneworder, preforder, pccpayid, pparams);

  // TODO: make more precise - look for return code 54
  if (returnValue < 0 && tryVoid) {
    int voidResult = 0;
    QString tmpErrorMsg = _errorMsg;
    ParameterList voidParams;
    _errorMsg.clear();
    voidResult = doVoidPrevious(pccardid,   pcvv,      amount,       currid,
                                pneworder,  preforder, approvalCode, pccpayid,
                                voidParams);
    if (voidResult >= 0) {
      returnValue = voidResult;
      pparams.clear();
      while (! voidParams.isEmpty())
        pparams.append(voidParams.takeFirst());
    }
    else
      _errorMsg = tmpErrorMsg;
  }

  return returnValue;
}
Exemplo n.º 21
0
void Documents::sOpenDoc(QString mode)
{
  QString ui;
  QString docType = _doc->currentItem()->rawValue("target_type").toString();
  int targetid = _doc->currentItem()->id("target_number");
  ParameterList params;
  if (docType == "Q" && mode == "view")
    params.append("mode", "viewQuote");
  else if (docType == "Q" && mode == "edit")
    params.append("mode", "editQuote");
  else
    params.append("mode", mode);

  // TODO: image -- change to use docass instead of imageass
  if (docType == "IMG")
  {
    XSqlQuery img;
    img.prepare("SELECT imageass_image_id "
                "FROM imageass "
                "WHERE (imageass_id=:imageass_id); ");
    img.bindValue(":imageass_id", _doc->id());
    img.exec();
    img.first();
    if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Getting Image Info"),
                             img, __FILE__, __LINE__))
      return;

    params.append("image_id", img.value("imageass_image_id").toInt());
    imageview newdlg(this, "", TRUE);
    newdlg.set(params);

    if (newdlg.exec() != QDialog::Rejected)
      refresh();
    return;
  }
  // TODO: url -- change to use docass instead of url
  // TODO: separate URL from FILE handling and replace use of url view
  else if (docType == "URL" || docType == "FILE")
  {
    if (mode == "edit")
    {
      ParameterList params;
      params.append("url_id", targetid);

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

      refresh();
      return;
    }

    XSqlQuery qfile;
    qfile.prepare("SELECT url_id, url_source_id, url_source, url_title, url_url, url_stream"
                  " FROM url"
                  " WHERE (url_id=:url_id);");

    qfile.bindValue(":url_id", _doc->id());
    qfile.exec();

    // If file is in the database, copy to a temp. directory in the file system and open it.
    if (qfile.first() && (docType == "FILE"))
    {
      QFileInfo fi( qfile.value("url_url").toString() );
      QDir tdir;
      // TODO: QDesktopServices::openUrl(urldb) on windows does not open files
      // containing spaces. why not?
#ifdef Q_WS_WIN
      QString fileName = fi.fileName().remove(" ");
#else
      QString fileName = fi.fileName();
#endif
      QString filePath = tdir.tempPath() + "/xtTempDoc/" +
	                 qfile.value("url_id").toString() + "/";
      QFile tfile(filePath + fileName);

      // Remove any previous watches
      if (_guiClientInterface)
        _guiClientInterface->removeDocumentWatch(tfile.fileName());

      if (! tdir.exists(filePath))
        tdir.mkpath(filePath);

      if (!tfile.open(QIODevice::WriteOnly))
      {
        QMessageBox::warning( this, tr("File Open Error"),
                             tr("Could Not Create File %1.").arg(tfile.fileName()) );
        return;
      }
      tfile.write(qfile.value("url_stream").toByteArray());
      QUrl urldb;
      urldb.setUrl(tfile.fileName());
#ifndef Q_WS_WIN
      urldb.setScheme("file");
#endif
      tfile.close();
      if (! QDesktopServices::openUrl(urldb))
      {
        QMessageBox::warning(this, tr("File Open Error"),
			     tr("Could not open %1.").arg(urldb.toString()));
	return;
      }

      // Add a watch to the file that will save any changes made to the file back to the database.
      if (_guiClientInterface && !_readOnly) // TODO: only if NOT read-only
        _guiClientInterface->addDocumentWatch(tfile.fileName(),qfile.value("url_id").toInt());
      return;
    }
    else if (ErrorReporter::error(QtCriticalMsg, this,
                                  tr("Error Getting Assignment"),
                                  qfile, __FILE__, __LINE__))
      return;
    else
    {
      QUrl url(_doc->currentItem()->rawValue("description").toString());
      if (url.scheme().isEmpty())
        url.setScheme("file");
      QDesktopServices::openUrl(url);
      return;
    }
  }
  else
  {
    unsigned int i = 0;
    // TODO: find a better data structure than array of structs for _documentMap
    for (  ; i < sizeof(_documentMap) / sizeof(_documentMap[0]); i++)
      if (_documentMap[i].ident == docType)
      {
        params.append(_documentMap[i].keyparam, targetid);
        ui = _documentMap[i].uiname;
        break;
      }
    if (i >= sizeof(_documentMap) / sizeof(_documentMap[0]))
    {
      QMessageBox::critical(this, tr("Error"),
                            tr("Unknown document type %1").arg(docType));
      return;
    }
  }

  QWidget* w = 0;
  if (parentWidget()->window())
  {
    if (parentWidget()->window()->isModal())
      w = _guiClientInterface->openWindow(ui, params, parentWidget()->window(),
                                          Qt::WindowModal, Qt::Dialog);
    else
      w = _guiClientInterface->openWindow(ui, params, parentWidget()->window(),
                                          Qt::NonModal, Qt::Window);
  }

  if (w && w->inherits("QDialog"))
  {
    QDialog* newdlg = qobject_cast<QDialog*>(w);
    newdlg->exec();
  }

  refresh();
}
int AuthorizeDotNetProcessor::handleResponse(const QString &presponse, const int pccardid, const QString &ptype, const double pamount, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams)
{
  if (DEBUG)
    qDebug("AN::handleResponse(%s, %d, %s, %f, %d, %s, %d, pparams)",
	   presponse.toAscii().data(), pccardid,
	   ptype.toAscii().data(), pamount, pcurrid,
	   preforder.toAscii().data(), pccpayid);

  // if we got an error msg very early on
  if (presponse.startsWith("<HTML>"))
  {
    _errorMsg = errorMsg(-207).arg(presponse);
    return -207;
  }

  QString delim = _metrics->value("CCANDelim").isEmpty() ? "," :
						  _metrics->value("CCANDelim");
  QString encap = _metrics->value("CCANEncap");

  QString r_approved;
  QString r_avs;
  QString r_code;
  QString r_cvv;
  QString r_error;
  QString r_message;
  QString r_ordernum;
  QString r_reason;     // not stored
  QString r_ref;
  QString r_shipping;
  QString r_tax;
  QString r_pantrunc;
  QString r_cardtype;

  QString status;

  // TODO: explore using encap here and code from CSV Import to properly split

  /* add an extra field at the beginning. otherwise we'll be off by one
     because the Advanced Integration Method (AIM) Implementation Guide
     numbers fields starting at 1 but QString::split() creates a list
     starting at 0.
   */
  QStringList responseFields = presponse.split(delim);
  
  QString r_response;
  int returnValue = fieldValue(responseFields, 1, r_response);
  if (returnValue < 0)
    return returnValue;

  if (r_response.toInt() == 1)
    r_approved = "APPROVED";
  else if (r_response.toInt() == 2)
    r_approved = "DECLINED";
  else if (r_response.toInt() == 3)
    r_approved = "ERROR";
  else if (r_response.toInt() == 4)
    r_approved = "HELDFORREVIEW";

  // fieldValue(responseFields, 2);				// subcode

  returnValue = fieldValue(responseFields, 3, r_reason);	// reason code
  if (returnValue < 0)
    return returnValue;
  returnValue = fieldValue(responseFields, 4, r_message);	// reason text
  if (returnValue < 0)
    return returnValue;

  returnValue = fieldValue(responseFields, 5, r_code);	 	// approval code
  if (returnValue < 0)
    return returnValue;
  returnValue = fieldValue(responseFields, 6, r_avs);	 	// avs result
  if (returnValue < 0)
    return returnValue;
  returnValue = fieldValue(responseFields, 7, r_ordernum);	// transaction id

  if (returnValue < 0)
    return returnValue;

  // fieldValue(responseFields, 8-10);	// echo invoice_number description amount 
  // fieldValue(responseFields, 11-13);	// echo method transtype cust_id
  // fieldValue(responseFields, 14-24);	// echo name, company, and address info
  // fieldValue(responseFields, 25-32);	// echo ship_to fields

  returnValue = fieldValue(responseFields, 33, r_tax);		// echo x_tax
  if (returnValue < 0)
    return returnValue;

  // fieldValue(responseFields, 34);				// echo x_duty

  returnValue = fieldValue(responseFields, 35, r_shipping);	// echo x_freight
  if (returnValue < 0)
    return returnValue;

  // fieldValue(responseFields, 36);		// echo x_tax_exempt
  // fieldValue(responseFields, 37);		// echo x_po_num
  // fieldValue(responseFields, 38);		// MD5 hash

  returnValue = fieldValue(responseFields, 39, r_cvv); // ccv response code
  if (returnValue < 0 && ptype == "CP") // may not get cvv on preauth capture
    returnValue = 0;
  else if (returnValue < 0)
    return returnValue;

  // fieldValue(responseFields, 40);		// cavv response code
  // fieldValue(responseFields, 41-50);		// reserved for future use

  returnValue = fieldValue(responseFields, 51, r_pantrunc);
  if (returnValue < 0)
    return returnValue;
  r_pantrunc = r_pantrunc.right(4);

  returnValue = fieldValue(responseFields, 52, r_cardtype);
  if (returnValue < 0)
    return returnValue;
  if (r_cardtype == "Discover" || r_cardtype == "MasterCard"
      || r_cardtype == "Visa"  || r_cardtype == "American Express")
    r_cardtype.remove(1, r_cardtype.length());
  else
    r_cardtype = "O";

  // fieldValue(responseFields, 53);            // split tender id
  // fieldValue(responseFields, 54);            // original authorization amt
  // fieldValue(responseFields, 55);            // debit/prepaid card balance
  // fieldValue(responseFields, 56-68);		// reserved for future use
  // fieldValue(responseFields, 69+);		// echo of merchant-defined fields

  /* treat heldforreview as approved because the AIM doc says response
     reason codes 252 and 253 are both approved but being reviewed.
     the intent of the other heldforreview, 193, is ambiguous.
   */
  if (r_approved == "APPROVED" || r_approved == "HELDFORREVIEW")
  {
    _errorMsg = errorMsg(0).arg(r_code);
    if (ptype == "A")
      status = "A";	// Authorized
    else if (ptype == "V")
      status = "V";	// Voided
    else
      status = "C";	// Completed/Charged
  }
  else if (r_approved == "DECLINED")
  {
    _errorMsg = errorMsg(-92).arg(r_message);
    returnValue = -92;
    status = "D";
  }
  else if (r_approved == "ERROR")
  {
    r_error = r_message;
    _errorMsg = errorMsg(-12).arg(r_error).arg(_company);
    returnValue = -12;
    status = "X";
  }

  else if (r_approved.isEmpty() && ! r_message.isEmpty())
  {
    _errorMsg = errorMsg(-95).arg(r_message).arg(_company);
    returnValue = -95;
    status = "X";
  }

  else if (r_approved.isEmpty())
  {
    _errorMsg = errorMsg(-100).arg(r_error).arg(r_message).arg(presponse);
    returnValue = -100;
    status = "X";
  }

  // always use the AVS checking configured on the gateway
  _passedAvs = ((r_reason.toInt() != 27) &&
	        (r_reason.toInt() != 127));

  // always use the CVV checking configured on the gateway
  _passedCvv = (r_reason.toInt() != 78);

  if (DEBUG)
    qDebug("AN:%s _passedAvs %d\t%s _passedCvv %d",
	    qPrintable(r_avs), _passedAvs, qPrintable(r_cvv), _passedCvv);

  pparams.append("ccard_id",    pccardid);
  pparams.append("currid",      pcurrid);
  pparams.append("auth_charge", ptype);
  pparams.append("type",        ptype);
  pparams.append("reforder",    (preforder.isEmpty()) ? pneworder : preforder);
  pparams.append("status",      status);
  pparams.append("avs",         r_avs);
  pparams.append("ordernum",    pneworder);
  pparams.append("xactionid",   r_ordernum);
  pparams.append("error",       r_error);
  pparams.append("approved",    r_approved);
  pparams.append("code",        r_code);
  pparams.append("shipping",    r_shipping);
  pparams.append("tax",         r_tax);
  pparams.append("ref",         r_ref);
  pparams.append("message",     r_message);
  pparams.append("pantrunc",    r_pantrunc);
  pparams.append("cardtype",    r_cardtype);

  pparams.append("auth", QVariant(ptype == "A"));

  if (DEBUG)
    qDebug("AN:r_error.isEmpty() = %d", r_error.isEmpty());

  if (returnValue == 0)
    pparams.append("amount",   pamount);
  else
    pparams.append("amount",   0);	// no money changed hands this attempt

  // don't bother checking MD5 if we hit a bigger problem
  if (returnValue == 0 && _metrics->boolean("CCANMD5HashSetOnGateway"))
  {
    QString expected_hash;
    QString r_hash;

    returnValue = fieldValue(responseFields, 38, r_hash);	// md5 hash
    XSqlQuery anq;
    anq.prepare("SELECT UPPER(MD5(:inputstr)) AS expected;");
    anq.bindValue(":inputstr", _metricsenc->value("CCANMD5Hash") +
			       _metricsenc->value("CCLogin") +
			       r_ordernum +
			       QString::number(pamount, 'f', 2));
    anq.exec();
    if (anq.first())
      expected_hash = anq.value("expected").toString();
    else if (anq.lastError().type() != QSqlError::NoError)
    {
      _errorMsg = errorMsg(-1).arg(anq.lastError().databaseText());
      returnValue = -1;
    }
    if (DEBUG)
      qDebug("AN:handleResponse expected md5 %s and got %s",
	      expected_hash.toAscii().data(), r_hash.toAscii().data());

    if (_metrics->value("CCANMD5HashAction") == "F" && expected_hash != r_hash)
    {
      _errorMsg = errorMsg(-206);
      returnValue = -206;
    }
    else if (_metrics->value("CCANMD5HashAction") == "W" && expected_hash != r_hash)
    {
      _errorMsg = errorMsg(206);
      returnValue = 206;
    }
  }

  if (DEBUG)
    qDebug("AN::handleResponse returning %d %s",
           returnValue, errorMsg().toAscii().data());
  return returnValue;
}
Exemplo n.º 23
0
void purchaseOrderItem::populate()
{
  XSqlQuery purchasepopulate;
  MetaSQLQuery mql = mqlLoad("purchaseOrderItems", "detail");

  ParameterList params;
  params.append("poitem_id", _poitemid);
  params.append("sonum",     tr("Sales Order #")),
  params.append("wonum",     tr("Work Order #")),
  purchasepopulate = mql.toQuery(params);
  if (purchasepopulate.lastError().type() != QSqlError::NoError)
  {
    systemError(this, purchasepopulate.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  if (purchasepopulate.first())
  {
    _poNumber->setText(purchasepopulate.value("pohead_number").toString());
    _lineNumber->setText(purchasepopulate.value("poitem_linenumber").toString());
    _taxzoneid=purchasepopulate.value("pohead_taxzone_id").toInt();   // added  to pick up tax zone id.
    _dueDate->setDate(purchasepopulate.value("poitem_duedate").toDate());
    _ordered->setDouble(purchasepopulate.value("poitem_qty_ordered").toDouble());
    _orderQtyCache = _ordered->toDouble();
    _received->setDouble(purchasepopulate.value("poitem_qty_received").toDouble());
    _unitPrice->set(purchasepopulate.value("poitem_unitprice").toDouble(),
		    purchasepopulate.value("pohead_curr_id").toInt(),
		    purchasepopulate.value("pohead_orderdate").toDate(), false);
    _freight->setLocalValue(purchasepopulate.value("poitem_freight").toDouble());
    _extendedPrice->setLocalValue(purchasepopulate.value("extended_price").toDouble());
    _taxtype->setId(purchasepopulate.value("poitem_taxtype_id").toInt());
    _taxRecoverable->setChecked(purchasepopulate.value("poitem_tax_recoverable").toBool());
    _notes->setText(purchasepopulate.value("poitem_comments").toString());
    _project->setId(purchasepopulate.value("poitem_prj_id").toInt());
    if(purchasepopulate.value("override_cost").toDouble() > 0)
      _overriddenUnitPrice = true;

    if(purchasepopulate.value("poitem_order_id") != -1)
    {
      _ordered->setEnabled(FALSE);
      _dueDate->setEnabled(FALSE);
      _soLit->setText(purchasepopulate.value("demand_type").toString());
      _so->setText(purchasepopulate.value("order_number").toString());
//      _soLine->setText(purchasepopulate.value("orderline_number").toString());
    }
    else
      _tab->setTabEnabled(_tab->indexOf(_demandTab), FALSE);

    if (purchasepopulate.value("poitem_itemsite_id").toInt() == -1)
    {
      _nonInventoryItem->setChecked(TRUE);
      _expcat->setId(purchasepopulate.value("poitem_expcat_id").toInt());
      sPopulateItemSourceInfo(-1);

      _vendorItemNumber->setText(purchasepopulate.value("poitem_vend_item_number").toString());
      _vendorDescrip->setText(purchasepopulate.value("poitem_vend_item_descrip").toString());
      _vendorUOM->setText(purchasepopulate.value("poitem_vend_uom").toString());
      _uom->setText(purchasepopulate.value("poitem_vend_uom").toString());
    }
    else
    {
      _inventoryItem->setChecked(TRUE);
      _item->setItemsiteid(purchasepopulate.value("poitem_itemsite_id").toInt());
      sPopulateItemSourceInfo(purchasepopulate.value("poitem_itemsrc_id").toInt());
      if (_metrics->boolean("RevControl"))
      {
        _bomRevision->setId(purchasepopulate.value("poitem_bom_rev_id").toInt());
        _booRevision->setId(purchasepopulate.value("poitem_boo_rev_id").toInt());
        _bomRevision->setEnabled(purchasepopulate.value("poitem_status").toString() == "U" && _privileges->boolean("UseInactiveRevisions"));
        _booRevision->setEnabled(purchasepopulate.value("poitem_status").toString() == "U" && _privileges->boolean("UseInactiveRevisions"));
      }
    }

    _itemsrcid = purchasepopulate.value("poitem_itemsrc_id").toInt();
    _contrctNumber->setText(purchasepopulate.value("contrct_number").toString());
    _vendorItemNumber->setText(purchasepopulate.value("poitem_vend_item_number").toString());
    _vendorDescrip->setText(purchasepopulate.value("poitem_vend_item_descrip").toString());
    _vendorUOM->setText(purchasepopulate.value("poitem_vend_uom").toString());
    _uom->setText(purchasepopulate.value("poitem_vend_uom").toString());
    _invVendorUOMRatio->setDouble(purchasepopulate.value("poitem_invvenduomratio").toDouble());
    _invVendUOMRatio = purchasepopulate.value("poitem_invvenduomratio").toDouble();
    _manufName->setText(purchasepopulate.value("poitem_manuf_name").toString());
    if (_manufName->id() < 0)
    {
      _manufName->append(_manufName->count(),
                         purchasepopulate.value("poitem_manuf_name").toString());
      _manufName->setText(purchasepopulate.value("poitem_manuf_name").toString());
    }
    _manufItemNumber->setText(purchasepopulate.value("poitem_manuf_item_number").toString());
    _manufItemDescrip->setText(purchasepopulate.value("poitem_manuf_item_descrip").toString());

    if (_itemsrcid != -1)
    {
      _vendorUOM->setEnabled(FALSE);
      _manufName->setEnabled(FALSE);
      _manufItemNumber->setEnabled(FALSE);
      _manufItemDescrip->setEnabled(FALSE);

      if(_vendorItemNumber->text().isEmpty())
        _vendorItemNumber->setText(purchasepopulate.value("itemsrc_vend_item_number").toString());
      if(_vendorDescrip->toPlainText().isEmpty())
        _vendorDescrip->setText(purchasepopulate.value("itemsrc_vend_item_descrip").toString());
      _minOrderQty->setDouble(purchasepopulate.value("itemsrc_minordqty").toDouble());
      _orderQtyMult->setDouble(purchasepopulate.value("itemsrc_multordqty").toDouble());

      _minimumOrder = purchasepopulate.value("itemsrc_minordqty").toDouble();
      _orderMultiple = purchasepopulate.value("itemsrc_multordqty").toDouble();

      if(_manufName->currentText().isEmpty())
        _manufName->setText(purchasepopulate.value("itemsrc_manuf_name").toString());
      if(_manufItemNumber->text().isEmpty())
        _manufItemNumber->setText(purchasepopulate.value("itemsrc_manuf_item_number").toString());
      if(_manufItemDescrip->toPlainText().isEmpty())
        _manufItemDescrip->setText(purchasepopulate.value("itemsrc_manuf_item_descrip").toString());
    }

    purchasepopulate.prepare( "SELECT DISTINCT char_id, char_name,"
               "       COALESCE(b.charass_value, (SELECT c.charass_value FROM charass c WHERE ((c.charass_target_type='I') AND (c.charass_target_id=:item_id) AND (c.charass_default) AND (c.charass_char_id=char_id)) LIMIT 1)) AS charass_value"
               "  FROM charass a, char "
               "    LEFT OUTER JOIN charass b"
               "      ON (b.charass_target_type='PI'"
               "      AND b.charass_target_id=:poitem_id"
               "      AND b.charass_char_id=char_id) "
               " WHERE ( (a.charass_char_id=char_id)"
               "   AND   (a.charass_target_type='I')"
               "   AND   (a.charass_target_id=:item_id) ) "
               " ORDER BY char_name;" );
    purchasepopulate.bindValue(":item_id", _item->id());
    purchasepopulate.bindValue(":poitem_id", _poitemid);
    purchasepopulate.exec();
    int row = 0;
    QModelIndex idx;
    while(purchasepopulate.next())
    {
      _itemchar->insertRow(_itemchar->rowCount());
      idx = _itemchar->index(row, 0);
      _itemchar->setData(idx, purchasepopulate.value("char_name"), Qt::DisplayRole);
      _itemchar->setData(idx, purchasepopulate.value("char_id"), Qt::UserRole);
      idx = _itemchar->index(row, 1);
      _itemchar->setData(idx, purchasepopulate.value("charass_value"), Qt::DisplayRole);
      _itemchar->setData(idx, _item->id(), Xt::IdRole);
      _itemchar->setData(idx, _item->id(), Qt::UserRole);
      row++;
    }

    _comments->setId(_poitemid);
  }
}
Exemplo n.º 24
0
void externalCCTransaction::getResults(ParameterList &pParams)
{
  QVariant amount = pParams.value("amount");
  int amountIndex;
  for (amountIndex = 0; amountIndex < pParams.size(); amountIndex++)
    if (pParams.name(amountIndex) == "amount")
      break;

  switch (_approved->currentIndex())
  {
    case 0:
      pParams.append("approved", "APPROVED");
      if (_transType->currentIndex() == 0)
        pParams.append("status", "A");
      else if (_transType->currentIndex() == 4)
        pParams.append("status", "V");
      else
        pParams.append("status", "C");
      break;
    case 1:
      pParams.append("approved", "DECLINED");
      pParams.append("status",   "D");
      if (amountIndex < pParams.size())
        pParams.removeAt(amountIndex);
      pParams.append("amount",   "0");
      break;
    case 2:
      pParams.append("approved", "ERROR");
      pParams.append("status",   "X");
      if (amountIndex < pParams.size())
        pParams.removeAt(amountIndex);
      pParams.append("amount",   "0");
      break;
    case 3:
      pParams.append("approved", "HELDFORREVIEW");
      if (_transType->currentIndex() == 0)
        pParams.append("status", "A");
      else if (_transType->currentIndex() == 4)
        pParams.append("status", "V");
      else
        pParams.append("status", "C");
      break;
    default:
      pParams.append("status",  "X");
      if (amountIndex < pParams.size())
        pParams.removeAt(amountIndex);
      pParams.append("amount",  "0");
  }

  pParams.append("code",     _approvalCode->text());
  pParams.append("xactionid",_transactionId->text());
  pParams.append("avs",      _passedAVS->isChecked() ? tr("passed") :
                                                 tr("failed or not entered"));
  pParams.append("passedavs",QVariant(_passedAVS->isChecked()));
  pParams.append("passedcvv",QVariant(_passedCVV->isChecked()));
  //pParams.append("error",    );
  //pParams.append("shipping",    );
  //pParams.append("tax",     );
  //pParams.append("ref",     );
  //pParams.append("message", );
}
Exemplo n.º 25
0
void maintainShipping::sFillList()
{
  int currentId = _ship->altId();

  _ship->clear();

//  Grab the contents of shipping for the selected warehous
  ParameterList params;

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

  if (_warehouse->isSelected())
    params.append("warehous_id", _warehouse->id());

  params.append("notPrinted",	tr("No"));
  params.append("dirty",	tr("Dirty"));
  params.append("printed",	tr("Yes"));

  MetaSQLQuery mql = mqlLoad(":/sr/maintainShipping/FillListDetail.mql");
  q = mql.toQuery(params);
  q.exec();
  if (q.first())
  {
    double        atShipping   = 0.0;
    int           shipheadid   = -1;
    int           lineitemid   = -1;
    XTreeWidgetItem *order     = NULL;
    XTreeWidgetItem *line      = NULL;
    XTreeWidgetItem *ship      = NULL;
    XTreeWidgetItem *selected  = NULL;

    do
    {
      if (q.value("shiphead_id").toInt() != shipheadid)
      {
	//  if new order number, make a new list item header and
	//  update the running qty at ship value
        shipheadid = q.value("shiphead_id").toInt();
        if (line != NULL)
        {
          line->setText(7, formatQty(atShipping));
          atShipping = 0;
          line = NULL;
        }

        order = new XTreeWidgetItem( _ship, order, shipheadid, shipheadid,
                                   q.value("shiphead_number"),
				   q.value("order_number"), q.value("sfstatus"),
                                   q.value("dest"), q.value("destcntct"),
                                   q.value("shiphead_shipvia"), "",
                                   "", q.value("holdtype") );

	//  If we are looking for a selected order and this is it, cache it
        if ((_itemtype == 1) && (currentId == shipheadid))
          selected = order;
      }

      //  if this is a new lineitem
      if ((line == NULL) || (q.value("lineitem_id").toInt() != lineitemid))
      {
        lineitemid = q.value("lineitem_id").toInt();

        if (line != NULL)
        {
          line->setText(7, formatQty(atShipping));
          atShipping = 0;
        }

        line = new XTreeWidgetItem( order, line, shipheadid, lineitemid,
                                  "", q.value("linenumber"), "",
                                  q.value("item_number"), q.value("description"),
                                  "", q.value("uom_name"),
                                  "", q.value("holdtype") );

	//  If we are looking for a selected order and this is it, cache it
        if ((_itemtype == 2) && (currentId == lineitemid))
          selected = line;
      }

	//  Add the shipping detail for the current lineitem
        atShipping += q.value("shipqty").toDouble();

        ship = new XTreeWidgetItem( line, ship, shipheadid,
				  q.value("shipitem_id").toInt(),
                                  "", "", "",
                                  "",
				  q.value("shipitem_transdate").toString() + " by " +
				  q.value("shipitem_trans_username").toString(),
                                  "", q.value("uom_name"),
                                  formatQty(q.value("shipqty").toDouble()),
				  q.value("holdtype") );

	//  If we are looking for a selected shipping detail and this is it, cache it
        if ((_itemtype == 3) && (currentId == q.value("shipitem_id").toInt()))
          selected = ship;
    }
    while (q.next());

    line->setText(7, formatQty(atShipping));

    //  Select and show the select item, if any
    if (selected != NULL)
    {
      _ship->setItemSelected(selected, TRUE);
      _ship->scrollToItem(selected);
    }
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Exemplo n.º 26
0
void dspTimePhasedOpenAPItems::sViewOpenItems()
{
  ParameterList params;
  params.append("vend_id", _apopen->id());
  if (_custom->isChecked())
  {
    params.append("startDate", _columnDates[_column - 2].startDate);
    params.append("endDate", _columnDates[_column - 2].endDate);
  }
  else
  {
    QDate asOfDate;
    asOfDate = _asOf->date();
    if (_column == 3)
    {
      params.append("startDate", asOfDate );
    }
    else if (_column == 4)
    {
      params.append("startDate", asOfDate.addDays(-30) );
      params.append("endDate", asOfDate);
    }
    else if (_column == 5)
    {
      params.append("startDate",asOfDate.addDays(-60) );
      params.append("endDate", asOfDate.addDays(-31));
    }
    else if (_column == 6)
    {
      params.append("startDate",asOfDate.addDays(-90) );
      params.append("endDate", asOfDate.addDays(-61));
    }
    else if (_column == 7)
      params.append("endDate",asOfDate.addDays(-91) );
  }
  params.append("run");
  params.append("asofDate",_asOf->date());

  dspAPOpenItemsByVendor *newdlg = new dspAPOpenItemsByVendor();
  newdlg->set(params);
  omfgThis->handleNewWindow(newdlg);
}
Exemplo n.º 27
0
void distributeInventory::sFillList()
{
  q.prepare( "SELECT itemsite_id, "
	     "       COALESCE(itemsite_location_id,-1) AS itemsite_location_id,"
	     "       formatlotserialnumber(itemlocdist_ls_id) AS lotserial,"
             "       (itemsite_controlmethod IN ('L', 'S')) AS lscontrol,"
             "       parent.itemlocdist_qty AS qtytodistribute,"
             "       ( ( SELECT COALESCE(SUM(child.itemlocdist_qty), 0)"
             "             FROM itemlocdist AS child"
             "            WHERE (child.itemlocdist_itemlocdist_id=parent.itemlocdist_id) ) ) AS qtytagged,"
             "       (parent.itemlocdist_qty - ( SELECT COALESCE(SUM(child.itemlocdist_qty), 0)"
             "                                     FROM itemlocdist AS child"
             "                                    WHERE (child.itemlocdist_itemlocdist_id=parent.itemlocdist_id) ) ) AS qtybalance "
             "FROM itemsite, itemlocdist AS parent "
             "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
             " AND (itemlocdist_id=:itemlocdist_id) );" );
  q.bindValue(":itemlocdist_id", _itemlocdistid);
  q.exec();
  if (q.first())
  {
    _item->setItemsiteid(q.value("itemsite_id").toInt());
    _lotSerial->setText(q.value("lotserial").toString());
    _qtyToDistribute->setText(formatNumber(q.value("qtytodistribute").toDouble(),6));
    _qtyTagged->setText(formatNumber(q.value("qtytagged").toDouble(),6));
    _qtyRemaining->setText(formatNumber(q.value("qtybalance").toDouble(),6));

    if ( (q.value("itemsite_location_id").toInt() != -1) &&
         ( (_mode == cNoIncludeLotSerial) || ( (_mode == cIncludeLotSerial) && (!q.value("lscontrol").toBool()) ) ) )
    {
      _default->setEnabled(TRUE);
      _defaultAndPost->setEnabled(TRUE);
    }
    else
    {
      _default->setEnabled(FALSE);
      _defaultAndPost->setEnabled(FALSE);
    }
    
    if (q.value("qtytodistribute").toDouble() < 0)
      _qtyOnly->hide();

    QString sql( "SELECT id, type,"
                 "       locationname,"
		 "       CASE WHEN defaultlocation THEN <? value(\"yes\") ?>"
		 "            ELSE <? value(\"no\") ?>"
		 "       END AS defaultlocation,"
		 "       CASE WHEN (location_netable) THEN <? value(\"yes\") ?>"
		 "            ELSE <? value(\"no\") ?>"
		 "       END AS netable,"
		 "       lotserial, f_expiration, expired,"
                 "       qty,"
                 "       qtytagged,"
                 "       (qty + qtytagged) AS balance "
                 "FROM (" 
		 "<? if exists(\"cNoIncludeLotSerial\") ?>"
		 "SELECT location_id AS id, <? value(\"locationType\") ?> AS type,"
		 "       formatLocationName(location_id) AS locationname,"
		 "       (location_id=itemsite_location_id) AS defaultlocation,"
		 "       location_netable,"
		 "       TEXT('') AS lotserial,"
		 "       TEXT(<? value(\"na\") ?>) AS f_expiration, FALSE AS expired,"
		 "       ( SELECT COALESCE(SUM(itemloc_qty), 0)"
		 "         FROM itemloc "
		 "         WHERE ( (itemloc_location_id=location_id)"
		 "          AND (itemloc_itemsite_id=itemsite_id) ) ) AS qty,"
		 "       itemlocdistQty(location_id, itemlocdist_id) AS qtytagged "
		 "FROM itemlocdist, location, itemsite "
		 "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
		 " AND (itemsite_loccntrl)"
		 " AND (itemsite_warehous_id=location_warehous_id)"
		 " AND (validLocation(location_id, itemsite_id))"
		 " AND (itemlocdist_id=<? value(\"itemlocdist_id\") ?>) ) "
		 "<? elseif exists(\"cIncludeLotSerial\") ?>"
		 "SELECT itemloc_id AS id, <? value(\"itemlocType\") ?> AS type,"
		 "       COALESCE(formatLocationName(location_id),"
		 "                <? value(\"undefined\") ?>) AS locationname,"
		 "       (location_id IS NOT NULL"
		 "        AND location_id=itemsite_location_id) AS defaultlocation,"
		 "       COALESCE(location_netable, false) AS location_netable,"
		 "       ls_number AS lotserial,"
		 "       CASE WHEN (itemsite_perishable) THEN formatDate(itemloc_expiration)"
		 "            ELSE <? value(\"na\") ?>"
		 "       END AS f_expiration,"
		 "       CASE WHEN (itemsite_perishable) THEN (itemloc_expiration < CURRENT_DATE)"
		 "            ELSE FALSE" 
		 "       END AS expired,"
		 "       itemloc_qty AS qty,"
		 "       ( SELECT COALESCE(SUM(target.itemlocdist_qty), 0)"
		 "         FROM itemlocdist AS target"
		 "         WHERE ( (target.itemlocdist_source_type='I')"
		 "          AND (target.itemlocdist_source_id=itemloc_id)"
		 "          AND (target.itemlocdist_itemlocdist_id=source.itemlocdist_id)) ) AS qtytagged "
		 "FROM itemlocdist AS source, itemsite, itemloc "
                 "  LEFT OUTER JOIN location ON (itemloc_location_id=location_id) "
                 "  LEFT OUTER JOIN ls ON (itemloc_ls_id=ls_id) "
		 "WHERE ( (source.itemlocdist_itemsite_id=itemsite_id)"
		 " AND (itemloc_itemsite_id=itemsite_id)"
		 " AND (source.itemlocdist_id=<? value(\"itemlocdist_id\") ?>) ) "
		 " UNION "
		 "SELECT location_id AS id, <? value(\"locationType\") ?> AS type,"
		 "       formatLocationName(location_id) AS locationname,"
		 "       (location_id=itemsite_location_id) AS defaultlocation,"
		 "       location_netable,"
		 "       TEXT('') AS lotserial,"
		 "       TEXT(<? value(\"na\") ?>) AS f_expiration, FALSE AS expired,"
		 "       ( SELECT COALESCE(SUM(itemloc_qty), 0)"
		 "         FROM itemloc "
		 "         WHERE ( (itemloc_location_id=location_id)"
		 "          AND (itemloc_itemsite_id=itemsite_id) ) ) AS qty,"
		 "       itemlocdistQty(location_id, itemlocdist_id) AS qtytagged "
		 "FROM itemlocdist, location, itemsite "
		 "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
		 " AND (itemsite_loccntrl)"
		 " AND (itemsite_warehous_id=location_warehous_id)"
		 " AND (validLocation(location_id, itemsite_id))"
		 " AND (location_id NOT IN (SELECT DISTINCT itemloc_location_id FROM itemloc WHERE (itemloc_itemsite_id=itemsite_id)))"
		 " AND (itemlocdist_id=<? value(\"itemlocdist_id\") ?>) ) "
		 "<? endif ?>"
		 ") AS data "
                 "WHERE ((TRUE) "
		 "<? if exists(\"showOnlyTagged\") ?>"
		 "AND (qtytagged != 0) "
		 "<? endif ?>"
                 "<? if exists(\"showQtyOnly\") ?>"
                 "AND (qty > 0) "
                 "<? endif ?>"
		 ") ORDER BY locationname;");

    ParameterList params;

    if (_mode == cNoIncludeLotSerial)
      params.append("cNoIncludeLotSerial");
    else if (_mode == cIncludeLotSerial)
      params.append("cIncludeLotSerial");

    if (_taggedOnly->isChecked())
      params.append("showOnlyTagged");
      
    if ( (_qtyOnly->isChecked())  ||
        (q.value("qtytodistribute").toDouble() < 0) )
      params.append("showQtyOnly");

    params.append("locationType",   cLocation);
    params.append("itemlocType",    cItemloc);
    params.append("yes",            tr("Yes"));
    params.append("no",             tr("No"));
    params.append("na",             tr("N/A"));
    params.append("undefined",      tr("Undefined"));
    params.append("itemlocdist_id", _itemlocdistid);

    MetaSQLQuery mql(sql);
    q = mql.toQuery(params);

    _itemloc->clear();
    XTreeWidgetItem *last = 0;
    while (q.next())
    {
      last = new XTreeWidgetItem(_itemloc, last,
				 q.value("id").toInt(), q.value("type").toInt(),
				 q.value("locationname"), q.value("defaultlocation"),
				 q.value("netable"), q.value("lotserial"),
				 q.value("f_expiration"),
				 formatNumber(q.value("qty").toDouble(),6),
				 formatNumber(q.value("qtytagged").toDouble(),6),
				 formatNumber(q.value("balance").toDouble(),6) );
      if (q.value("expired").toBool())
        last->setTextColor("red");
    }
  }
}
Exemplo n.º 28
0
void glSeries::sPost()
{
  if (! update())
    return;

  if(_submit)
  {
    ParameterList params;

    params.append("action_name", "PostGLSeries");
    params.append("glseries_sequence", _glsequence); 

    submitAction newdlg(this, "", true);
    newdlg.set(params);

    if(newdlg.exec() == XDialog::Accepted)
    {
      // TODO: do something?
    }
  }
  else
  {
    q.prepare("SELECT postGLSeriesNoSumm(:glseries_sequence,COALESCE(:journal,fetchJournalNumber('G/L'))) AS return;");
    q.bindValue(":glseries_sequence", _glsequence);
    if (_journal)
      q.bindValue(":journal", _journal);
    q.exec();
    if (q.first())
    {
      int returnVal = q.value("return").toInt();
      if (returnVal < 0)
      {
        systemError(this, storedProcErrorLookup("postGLSeriesNoSumm", returnVal),
		    __FILE__, __LINE__);
        return;
      }
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    omfgThis->sGlSeriesUpdated();
  }

  if(cPostStandardJournal == _mode || _journal)
  {
    accept();
    return;
  }

  _date->clear();
  _notes->clear();
  _debits->clear();
  _credits->clear();
  _diff->clear();
  _glseries->clear();
  _docnumber->clear();
  
  ParameterList params;
  params.append("mode", "new");
  set(params);
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
{
#if defined Q_WS_WIN
  OpenRPT::name = QObject::tr("Report Import Tool for Windows");
#elif defined Q_WS_X11
  OpenRPT::name = QObject::tr("Report Import Tool for Linux");
#elif defined Q_WS_MAC
  OpenRPT::name = QObject::tr("Report Import Tool for OS X");
#else
  OpenRPT::name = QObject::tr("Report Import Tool");
#endif

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

  QString databaseURL = "";

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

  if (argc > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd  = FALSE;
    QString passwd      = "";

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

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

    }

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

      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the database driver. Please contact your systems administrator."));
        QApplication::exit(-1);
      }

      db.setUserName(username);
      db.setPassword(passwd);

      if (!db.open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        loggedIn = TRUE;
    }

  }

  if(!loggedIn)
  {
    ParameterList params;
    params.append("name",      OpenRPT::name);
    params.append("copyright", OpenRPT::copyright);
    params.append("version",   OpenRPT::version);
    params.append("build",     OpenRPT::build);

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

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

    login newdlg(0, "", TRUE);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
  }

  ImportWindow mainwin;
  mainwin.show();

  return app.exec();
}
Exemplo n.º 30
0
int PaymentechProcessor::handleResponse(const QString &presponse, const int pccardid, const QString &ptype, const double pamount, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams)
{
  if (DEBUG)
    qDebug("Paymentech::handleResponse(%s, %d, %s, %f, %d, %s, %d, pparams)",
	   presponse.toAscii().data(), pccardid,
	   ptype.toAscii().data(), pamount, pcurrid,
	   preforder.toAscii().data(), pccpayid);

  int returnValue = 0;

  QString r_approved;
  QString r_avs;
  QString r_code;
  QString r_cvv;
  QString r_error;
  QString r_message;
  QString r_ordernum;
  QString r_reason;     // not stored
  QString r_ref;
  QString r_shipping;
  QString r_tax;
  QString r_date;

  QString status;

  QString r_response;
  r_response = presponse.mid(26, 3).trimmed();
  int i_response = r_response.toInt();
  if ((i_response >= 100 && i_response < 200) || i_response == 704)
    r_approved = "APPROVED";
  else if((i_response >= 200 && i_response < 300 && i_response != 260) || (i_response >= 740 && i_response <= 768))
    r_approved = "ERROR"; // REJECTED
  else
    r_approved = "DECLINED";

  r_reason = r_response;

  r_message = "Received return code " + r_response;

  r_date = presponse.mid(29, 6).trimmed();
  r_code = presponse.mid(35, 6).trimmed();
  r_avs = presponse.mid(41, 2).trimmed();
  r_ordernum = presponse.mid(4, 22).trimmed();
  r_cvv = presponse.mid(43, 1).trimmed();

  if (r_approved == "APPROVED")
  {
    _errorMsg = errorMsg(0).arg(r_code);
    if (ptype == "A")
      status = "A";	// Authorized
    else if (ptype == "V")
      status = "V";	// Voided
    else
      status = "C";	// Completed/Charged
  }
  else if (r_approved == "DECLINED")
  {
    _errorMsg = errorMsg(-92).arg(r_message);
    returnValue = -92;
    status = "D";
  }
  else if (r_approved == "ERROR")
  {
    r_error = r_message;
    _errorMsg = errorMsg(-12).arg(r_error);
    returnValue = -12;
    status = "X";
  }

  else if (r_approved.isEmpty() && ! r_message.isEmpty())
  {
    _errorMsg = errorMsg(-95).arg(r_message);
    returnValue = -95;
    status = "X";
  }

  else if (r_approved.isEmpty())
  {
    _errorMsg = errorMsg(-100).arg(r_error).arg(r_message).arg(presponse);
    returnValue = -100;
    status = "X";
  }

  QStringList validAvs;
  // TODO: is this list correct?
  validAvs << "N1" << "N2" << "  " << "IG" << "IU" << "ID" << "IA" << "IB" << "IP" << "A1" << "A3" << "A4" << "A7" << "I3" << "I4";
  _passedAvs = validAvs.contains(r_avs);

  // always use the CVV checking configured on the gateway
  QString validCvv("MPU ");
  _passedCvv = validCvv.contains(r_cvv);

  if (DEBUG)
    qDebug("Paymentech:%s _passedAvs %d\t%s _passedCvv %d",
	    r_avs.toAscii().data(), _passedAvs, 
	    r_cvv.toAscii().data(), _passedCvv);

  pparams.append("ccard_id",    pccardid);
  pparams.append("currid",      pcurrid);
  pparams.append("auth_charge", ptype);
  pparams.append("type",        ptype);
  pparams.append("reforder",    (preforder.isEmpty()) ? pneworder : preforder);
  pparams.append("status",      status);
  pparams.append("avs",         r_avs);
  pparams.append("ordernum",    pneworder);
  pparams.append("xactionid",   r_ordernum);
  pparams.append("error",       r_error);
  pparams.append("approved",    r_approved);
  pparams.append("code",        r_code);
  pparams.append("shipping",    r_shipping);
  pparams.append("tax",         r_tax);
  pparams.append("ref",         r_ref);
  pparams.append("message",     r_message);
  pparams.append("tdate",       r_date);

  if (ptype == "A")
    pparams.append("auth", QVariant(true, 0));
  else
    pparams.append("auth", QVariant(false, 1));

  if (DEBUG)
    qDebug("Paymentech:r_error.isEmpty() = %d", r_error.isEmpty());

  if (returnValue == 0)
    pparams.append("amount",   pamount);
  else
    pparams.append("amount",   0);	// no money changed hands this attempt

  if (DEBUG)
    qDebug("Paymentech::handleResponse returning %d %s",
           returnValue, errorMsg().toAscii().data());
  return returnValue;
}