コード例 #1
0
void state::sSave()
{
  _abbr->setText(_abbr->text().trimmed());
  _name->setText(_name->text().trimmed());

  struct {
    bool	condition;
    QString	msg;
    QWidget*	widget;
  } error[] = {
    { (! _country->isValid()), tr("<p>You must select a country."), _country },
    { _name->text().isEmpty(),
            tr("<p>You must enter a name for the state/province."), _name    },
    { true, "", NULL }
  }; // error[]

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

  XSqlQuery stateq;
  stateq.prepare("SELECT state_id "
                 "FROM state "
                 "WHERE ((state_country_id=:country_id)"
                 "   AND ((UPPER(state_abbr)=UPPER(:state_abbr) AND :state_abbr != '')"
                 "        OR (UPPER(state_name)=UPPER(:state_name) AND :state_name != ''))"
                 "   AND (state_id!=:state_id));");
  stateq.bindValue(":country_id", _country->id());
  stateq.bindValue(":state_abbr", _abbr->text());
  stateq.bindValue(":state_name", _name->text());
  stateq.bindValue(":state_id",   _stateid);
  stateq.exec();
  if (stateq.first())
  {
    QMessageBox::warning(this, tr("Cannot Save State/Province"),
                         tr("There is already another state/province for %1 "
                            "with the same name or abbreviation.")
                           .arg(_country->currentText()));
    _abbr->setFocus();
    return;

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

  if (_mode == cNew)
    q.prepare("INSERT INTO state ("
              "  state_id, state_abbr, state_name, state_country_id"
              ") VALUES ("
              "  DEFAULT, :state_abbr, :state_name, :country_id"
              ") RETURNING state_id;");
  else if (_mode == cEdit)
  {
    q.prepare("UPDATE state "
              "SET state_abbr=:state_abbr, state_name=:state_name,"
              "    state_country_id=:country_id "
              "WHERE (state_id=:state_id) RETURNING state_id;" );
    q.bindValue(":state_id", _stateid);
  }

  q.bindValue(":state_abbr", _abbr->text().trimmed());
  q.bindValue(":state_name", _name->text().trimmed());
  q.bindValue(":country_id", _country->id());
  q.exec();
  if (q.first())
    _stateid = q.value("state_id").toInt();
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  done(_stateid);
}
コード例 #2
0
void apOpenItem::sTaxDetail()
{ 
  if (_apopenid == -1)
  {
    if (!_docDate->isValid() || !_dueDate->isValid())
    {
      QMessageBox::critical( this, tr("Cannot set tax amounts"),
                             tr("You must enter document and due dates for this A/P Memo before you may set tax amounts.") );
      _docDate->setFocus();
      return;
    }
    
    XSqlQuery ap;
    ap.prepare("SELECT nextval('apopen_apopen_id_seq') AS result;");
    ap.exec();
    if (ap.first())
      _apopenid = ap.value("result").toInt();
    else if (ap.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else
      return;
    
    ap.prepare("INSERT INTO apopen "
      "( apopen_id, apopen_docdate, apopen_duedate, apopen_doctype, "
      "  apopen_docnumber, apopen_curr_id, apopen_posted, apopen_amount ) "
      "VALUES "
      "( :apopen_id, :docDate, :dueDate, :docType, :docNumber, :currId, false, 0 ); ");
    ap.bindValue(":apopen_id",_apopenid);
    ap.bindValue(":docDate", _docDate->date());
    ap.bindValue(":dueDate", _dueDate->date());
    if (_docType->currentIndex())
      ap.bindValue(":docType", "D" );
    else
      ap.bindValue(":docType", "C" );
    ap.bindValue(":docNumber", _docNumber->text());
    ap.bindValue(":currId", _amount->id());
    ap.exec();
    if (ap.lastError().type() != QSqlError::NoError)
    {
      q.exec("ROLLBACK;");
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
  
  taxDetail newdlg(this, "", true);
  ParameterList params;

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

  q.exec("SELECT getadjustmenttaxtypeid() as taxtype;");
  if(q.first())
    params.append("taxtype_id", q.value("taxtype").toInt());  
   
  params.append("order_type", "AP");
  params.append("order_id", _apopenid);
  params.append("display_type", "A");
  params.append("subtotal", _amount->localValue());
  params.append("adjustment");
  if (_docType->currentIndex())
    params.append("sense",-1);
  if (newdlg.set(params) == NoError)  
  {
    newdlg.exec();
    XSqlQuery taxq;
    taxq.prepare( "SELECT SUM(taxhist_tax) AS tax "
      "FROM apopentax "
      "WHERE (taxhist_parent_id=:apopen_id);" );
    taxq.bindValue(":apopen_id", _apopenid);
    taxq.exec();
    if (taxq.first())
    {
      if (_docType->currentIndex())
        _tax->setLocalValue(taxq.value("tax").toDouble() * -1);
      else
        _tax->setLocalValue(taxq.value("tax").toDouble());
    }
    else if (taxq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, taxq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
}
コード例 #3
0
ファイル: itemSource.cpp プロジェクト: AlFoX/qt-client
enum SetResponse itemSource::set(const ParameterList &pParams)
{
  XSqlQuery itemet;
  XDialog::set(pParams);
  QVariant param;
  bool     valid;

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

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

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

      itemet.exec("SELECT NEXTVAL('itemsrc_itemsrc_id_seq') AS _itemsrc_id;");
      if (itemet.first())
        _itemsrcid = itemet.value("_itemsrc_id").toInt();
      else if (itemet.lastError().type() != QSqlError::NoError)
      {
        systemError(this, itemet.lastError().databaseText(), __FILE__, __LINE__);
        return UndefinedError;
      }
      _captive = true;
      
      connect(_itemsrcp, SIGNAL(valid(bool)), _edit, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(valid(bool)), _delete, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;

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

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

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

      itemet.exec("SELECT NEXTVAL('itemsrc_itemsrc_id_seq') AS _itemsrc_id;");
      if (itemet.first())
        _itemsrcid = itemet.value("_itemsrc_id").toInt();
      else if (itemet.lastError().type() != QSqlError::NoError)
      {
        systemError(this, itemet.lastError().databaseText(), __FILE__, __LINE__);
        return UndefinedError;
      }
      
      connect(_itemsrcp, SIGNAL(valid(bool)), _edit, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(valid(bool)), _delete, SLOT(setEnabled(bool)));
      connect(_itemsrcp, SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));
      
      _item->setReadOnly(TRUE);
      _vendorItemNumber->setText(_vendorItemNumber->text().prepend("Copy Of "));
      _dates->setStartDate(omfgThis->dbDate());

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

  return NoError;
}
コード例 #4
0
ファイル: userPreferences.cpp プロジェクト: AlFoX/qt-client
bool userPreferences::save()
{
  XSqlQuery userave;
  
  if (_currentpassword->text().length() == 0)
  {
    QMessageBox::warning( this, tr("Cannot save User"),
                          tr( "You must enter a valid Current Password before you can save this User." ));
    _currentpassword->setFocus();
    return false;
  }

  if (_newpassword->text().length() == 0)
  {
    QMessageBox::warning( this, tr("Cannot save User"),
                          tr( "You must enter a valid Password before you can save this User." ));
    _newpassword->setFocus();
    return false;
  }

  QString passwd = _newpassword->text();
  QString currentpasswd = _currentpassword->text();
   
  // TODO: have to compare this against something usefull
  if(currentpasswd != __password)
  {
    QMessageBox::warning( this, tr("Cannot save User"),
                  tr( "Please Verify Current Password." ));
    _currentpassword->setFocus();
    return false;
  }

  if (_newpassword->text() != _retypepassword->text())
  {
    QMessageBox::warning( this, tr("Password do not Match"),
                   tr( "The entered password and verify do not match\n"
                       "Please enter both again carefully." ));

    _newpassword->clear();
    _retypepassword->clear();
    _newpassword->setFocus();
    return false;
  }   

  if (_newpassword->text() != "        ")
  {
    userave.prepare( "SELECT usrpref_value "
                "  FROM usrpref "
                " WHERE ( (usrpref_name = 'UseEnhancedAuthentication') "
                "   AND (usrpref_username=:username) ); ");
    userave.bindValue(":username", _username->text().trimmed().toLower());         
    userave.exec();
    if(userave.first())
    {
      if (userave.value("usrpref_value").toString()=="t")
      {
          QRegExp xtuplecloud(".*\\.xtuplecloud\\.com.*");
          QRegExp xtuple(".*\\.xtuple\\.com.*");

          bool isCloud = xtuplecloud.exactMatch(omfgThis->databaseURL());
          bool isXtuple = xtuple.exactMatch(omfgThis->databaseURL());
          QString salt;

          if(isCloud || isXtuple)
          {
            salt = "private";
          }
          else
          {
            salt = "xTuple";
          }
        passwd = passwd + salt + _username->text();
        passwd = QMd5(passwd);
      }
    }
    userave.prepare( QString( "ALTER USER \"%1\" WITH PASSWORD :password;")
           .arg(_username->text()) );
    userave.bindValue(":password", passwd);
    userave.exec();
    if (userave.lastError().type() != QSqlError::NoError)
    {
      systemError(this, userave.lastError().databaseText(), __FILE__, __LINE__);
      return false;
    }
  }
  return true;
}
コード例 #5
0
void PoitemTableModel::findHeadData()
{
  _poheadcurrid = CurrDisplay::baseId();
  _poheaddate	= QDate();
  _postatus	= "U";	// safest default
  _vendid	= -1;
  _vendrestrictpurch = false;

  XSqlQuery poheadq;
  XSqlQuery vendq;
  if (_poheadid > 0)
  {
    poheadq.prepare("SELECT pohead_id, pohead_curr_id, pohead_orderdate,"
		    "       pohead_status "
		    "FROM pohead "
		    "WHERE (pohead_id=:pohead_id);");
    poheadq.bindValue(":pohead_id", _poheadid);
    vendq.prepare("SELECT vend_id, vend_restrictpurch "
		  "FROM vend, pohead "
		  "WHERE ((vend_id=pohead_vend_id)"
		  "  AND  (pohead_id=:id));");
    vendq.bindValue(":id", _poheadid);
  }
  else if (_poheadid > 0)
  {
    poheadq.prepare("SELECT pohead_id, pohead_curr_id, pohead_orderdate,"
		    "       pohead_status "
		    "FROM pohead "
		    "WHERE pohead_id IN (SELECT poitem_pohead_id "
		    "                    FROM poitem WHERE poitem_id=:poitem_id);");
    poheadq.bindValue(":poitem_id", _poitemid);
    vendq.prepare("SELECT vend_id, vend_restrictpurch "
		  "FROM vend, pohead, poitem "
		  "WHERE ((vend_id=pohead_vend_id)"
		  "  AND  (pohead_id=poitem_pohead_id)"
		  "  AND  (poitem_id=:id));");
    vendq.bindValue(":id", _poitemid);
  }
  else
    return;

  poheadq.exec();
  if (poheadq.first())
  {
    _poheadcurrid = poheadq.value("pohead_curr_id").toInt();
    _poheaddate   = poheadq.value("pohead_orderdate").toDate();
    _postatus	  = poheadq.value("pohead_status").toString();
  }
  else if (poheadq.lastError().type() != QSqlError::NoError)
  {
    systemError(0, poheadq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  vendq.exec();
  if (vendq.first())
  {
    _vendid		= vendq.value("vend_id").toInt();
    _vendrestrictpurch	= vendq.value("vend_restrictpurch").toBool();
  }
  else if (vendq.lastError().type() != QSqlError::NoError)
  {
    systemError(0, vendq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
コード例 #6
0
void creditMemoItem::sPopulateItemInfo()
{
  XSqlQuery uom;
  uom.prepare("SELECT uom_id, uom_name"
              "  FROM item"
              "  JOIN uom ON (item_inv_uom_id=uom_id)"
              " WHERE(item_id=:item_id)"
              " UNION "
              "SELECT uom_id, uom_name"
              "  FROM item"
              "  JOIN itemuomconv ON (itemuomconv_item_id=item_id)"
              "  JOIN uom ON (itemuomconv_to_uom_id=uom_id)"
              " WHERE((itemuomconv_from_uom_id=item_inv_uom_id)"
              "   AND (item_id=:item_id))"
              " UNION "
              "SELECT uom_id, uom_name"
              "  FROM item"
              "  JOIN itemuomconv ON (itemuomconv_item_id=item_id)"
              "  JOIN uom ON (itemuomconv_from_uom_id=uom_id)"
              " WHERE((itemuomconv_to_uom_id=item_inv_uom_id)"
              "   AND (item_id=:item_id))"
              " ORDER BY uom_name;");
  uom.bindValue(":item_id", _item->id());
  uom.exec();
  _qtyUOM->populate(uom);
  _pricingUOM->populate(uom);

  XSqlQuery item;
  item.prepare( "SELECT item_inv_uom_id, item_price_uom_id,"
                "       iteminvpricerat(item_id) AS iteminvpricerat,"
                "       item_listprice, "
                "       stdCost(item_id) AS f_cost,"
		"       getItemTaxType(item_id, :taxauth) AS taxtype_id "
                "  FROM item"
                " WHERE (item_id=:item_id);" );
  item.bindValue(":item_id", _item->id());
  item.exec();
  if (item.first())
  {
    _invuomid = item.value("item_inv_uom_id").toInt();
    _priceRatio = item.value("iteminvpricerat").toDouble();
    _qtyUOM->setId(item.value("item_inv_uom_id").toInt());
    _pricingUOM->setId(item.value("item_price_uom_id").toInt());
    _priceinvuomratio = item.value("iteminvpricerat").toDouble();
    _qtyinvuomratio = 1.0;
    _ratio=item.value("iteminvpricerat").toDouble();
    // {_listPrice,_unitCost}->setBaseValue() because they're stored in base
    _listPrice->setBaseValue(item.value("item_listprice").toDouble());
    _unitCost->setBaseValue(item.value("f_cost").toDouble());
    _taxType->setId(item.value("taxtype_id").toInt());
  }
  else if (item.lastError().type() != QSqlError::NoError)
  {
    systemError(this, item.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (_invoiceNumber != -1)
  {
    XSqlQuery cmitem;
    cmitem.prepare( "SELECT invcitem_warehous_id,"
                    "       invcitem_qty_uom_id, invcitem_qty_invuomratio,"
                    "       invcitem_price_uom_id, invcitem_price_invuomratio,"
                    "       invcitem_billed * invcitem_qty_invuomratio AS f_billed,"
                    "       currToCurr(invchead_curr_id, :curr_id, "
		    "                  invcitem_price / invcitem_price_invuomratio, invchead_invcdate) AS invcitem_price_local "
                    "FROM invchead, invcitem "
                    "WHERE ( (invcitem_invchead_id=invchead_id)"
                    " AND (invchead_invcnumber=:invoiceNumber::TEXT)"
                    " AND (invcitem_item_id=:item_id) ) "
                    "LIMIT 1;" );
    cmitem.bindValue(":invoiceNumber", _invoiceNumber);
    cmitem.bindValue(":item_id", _item->id());
    cmitem.bindValue(":curr_id", _netUnitPrice->id());
    cmitem.exec();
    if (cmitem.first())
    {
      _qtyUOM->setId(cmitem.value("invcitem_qty_uom_id").toInt());
      _pricingUOM->setId(cmitem.value("invcitem_price_uom_id").toInt());
      _priceinvuomratio = cmitem.value("invcitem_price_invuomratio").toDouble();
      _ratio=_priceinvuomratio;
      _salePrice->setLocalValue(cmitem.value("invcitem_price_local").toDouble() * _priceinvuomratio);

      if (_mode == cNew)
        _netUnitPrice->setLocalValue(cmitem.value("invcitem_price_local").toDouble() * _priceinvuomratio);

      _warehouse->setId(cmitem.value("invcitem_warehous_id").toInt());
      _qtyShippedCache = cmitem.value("f_billed").toDouble();
      _qtyShipped->setDouble(cmitem.value("f_billed").toDouble() / _qtyinvuomratio);
    }
    else if (cmitem.lastError().type() != QSqlError::NoError)
    {
      systemError(this, cmitem.lastError().databaseText(), __FILE__, __LINE__);
      _salePrice->clear();
      return;
    }
  }
}
コード例 #7
0
void arWorkBench::sPostCashrcpt()
{
  XSqlQuery arPostCashrcpt;
  int journalNumber = -1;
  bool changeDate = false;
  QDate newDate = QDate();
  
  if (_privileges->check("ChangeCashRecvPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Distribution Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  arPostCashrcpt.exec("BEGIN;");
  arPostCashrcpt.exec("SELECT fetchJournalNumber('C/R') AS journalnumber;");
  if (arPostCashrcpt.first())
    journalNumber = arPostCashrcpt.value("journalnumber").toInt();
  else if (arPostCashrcpt.lastError().type() != QSqlError::NoError)
  {
    systemError(this, arPostCashrcpt.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE cashrcpt SET cashrcpt_distdate=:distdate,"
                  "                    cashrcpt_applydate=CASE WHEN (cashrcpt_applydate < :distdate) THEN :distdate"
                  "                                            ELSE cashrcpt_applydate END "
                  "WHERE cashrcpt_id=:cashrcpt_id;");
  
  QList<XTreeWidgetItem*> selected = _cashrcpt->selectedItems();
  
  for (int i = 0; i < selected.size(); i++)
  {
    int id = ((XTreeWidgetItem*)(selected[i]))->id();
    
    if (changeDate)
    {
      setDate.bindValue(":distdate",    newDate);
      setDate.bindValue(":cashrcpt_id", id);
      setDate.exec();
      ErrorReporter::error(QtCriticalMsg, this, tr("Changing Dist. Date"),
                           setDate, __FILE__, __LINE__);
    }
  }
  
  for (int i = 0; i < selected.size(); i++)
  {
    arPostCashrcpt.prepare("SELECT postCashReceipt(:cashrcpt_id, :journalNumber) AS result;");
    arPostCashrcpt.bindValue(":cashrcpt_id", ((XTreeWidgetItem*)(selected[i]))->id());
    arPostCashrcpt.bindValue(":journalNumber", journalNumber);
    arPostCashrcpt.exec();
    if (arPostCashrcpt.first())
    {
      int result = arPostCashrcpt.value("result").toInt();
      if (result < 0)
      {
        systemError(this, storedProcErrorLookup("postCashReceipt", result),
                    __FILE__, __LINE__);
        arPostCashrcpt.exec("ROLLBACK;");
        return;
      }
    }
    else if (arPostCashrcpt.lastError().type() != QSqlError::NoError)
    {
      systemError(this, arPostCashrcpt.lastError().databaseText(), __FILE__, __LINE__);
      arPostCashrcpt.exec("ROLLBACK;");
      return;
    }
  }
  arPostCashrcpt.exec("COMMIT;");
  sFillList();
}
コード例 #8
0
void PoitemTableDelegate::setModelData(QWidget *editor, QAbstractItemModel *pModel, const QModelIndex &index) const
{
  if (DEBUG)
    qDebug("PoitemTableDelegate::setModelData() entered");
  bool hitError = false;
  QVariant oldval = pModel->data(index);
  PoitemTableModel *model = static_cast<PoitemTableModel*>(pModel);

  switch (index.column())
  {
    case ITEM_NUMBER_COL:
    {
      ItemLineEdit *item = static_cast<ItemLineEdit*>(editor);
      if (item->itemNumber() != oldval.toString())
      {
	if (item->itemNumber().isEmpty())
	{
	  model->setData(index, new QVariant());
	  model->setData(model->index(index.row(), ITEM_ID_COL), new QVariant());
	  model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), new QVariant());
	  model->setData(model->index(index.row(), WAREHOUS_ID_COL), new QVariant());
	  model->setData(model->index(index.row(), WAREHOUS_CODE_COL), new QVariant());
	  model->setData(model->index(index.row(), POITEM_ITEMSRC_ID_COL), new QVariant());
	  model->setData(model->index(index.row(), POITEM_VEND_ITEM_NUMBER_COL), new QVariant());
	  model->setData(model->index(index.row(), POITEM_VEND_ITEM_DESCRIP_COL), new QVariant());
	  model->setData(model->index(index.row(), POITEM_VEND_UOM_COL), new QVariant());
	  model->setData(model->index(index.row(), ITEMSRC_MINORDQTY_COL), new QVariant());
	  model->setData(model->index(index.row(), ITEMSRC_MULTORDQTY_COL), new QVariant());
	  model->setData(model->index(index.row(), ITEMSRC_INVVENDORUOMRATIO_COL), new QVariant());
	  model->setData(model->index(index.row(), POITEM_INVVENDUOMRATIO_COL), new QVariant());
	  model->setData(model->index(index.row(), EARLIESTDATE_COL), new QVariant());
	}
	else
	{
	  model->setData(index, item->itemNumber());
	  model->setData(model->index(index.row(), ITEM_ID_COL), item->id());

	  if (item->isValid())
	  {
	    XSqlQuery itemq;
	    itemq.prepare("SELECT (warehous_id=:preferred) AS preferred, "
			  "       itemsite_id, warehous_id, warehous_code "
			  "FROM itemsite, whsinfo "
			  "WHERE ((itemsite_item_id=:item_id)"
			  "   AND (itemsite_warehous_id=warehous_id)) "
			  "ORDER BY preferred DESC, warehous_code "
			  "LIMIT 1;");
	    itemq.bindValue(":item_id", item->id());
	    itemq.bindValue(":preferred",
			   _x_preferences->value("PreferredWarehouse").toInt());
	    itemq.exec();
	    if (itemq.first())
	    {
	      model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), itemq.value("itemsite_id").toInt());
	      model->setData(model->index(index.row(), WAREHOUS_ID_COL), itemq.value("warehous_id").toInt());
	      model->setData(model->index(index.row(), WAREHOUS_CODE_COL), itemq.value("warehous_code").toString());
	    }
	    else if (itemq.lastError().type() != QSqlError::None)
	    {
	      systemError(0, itemq.lastError().databaseText(), __FILE__, __LINE__);
	      hitError = true;
	      break;
	    }
	    else
	    {
	      systemError(0, QString("Could not find Item Site for %1 (%2).")
			      .arg(item->itemNumber()).arg(item->id()));
	      hitError = true;
	      break;
	    }

	    if (_metrics->boolean("RequireStdCostForPOItem"))
	    {
	      XSqlQuery stdcostq;
	      stdcostq.prepare("SELECT stdCost(:item_id) AS result");
	      stdcostq.bindValue(":item_id", item->id());
	      stdcostq.exec();
	      if(stdcostq.first() && stdcostq.value("result").toDouble() == 0.0)
	      {
		QMessageBox::critical(0, tr("Selected Item Missing Cost"),
			tr("<p>The selected item has no Std. Costing information. "
			   "Please see your controller to correct this situation "
			   "before continuing."));
		model->setData(index, new QString());
		model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), new QVariant());
		model->setData(model->index(index.row(), WAREHOUS_ID_COL), new QVariant());
		model->setData(model->index(index.row(), WAREHOUS_CODE_COL), new QString());
		model->setData(index, new QString());
		hitError = true;
		break;
	      }
	      else if (stdcostq.lastError().type() != QSqlError::None)
	      {
		systemError(0, stdcostq.lastError().databaseText(), __FILE__, __LINE__);
		hitError = true;
		break;
	      }
	    }

	    XSqlQuery itemsrcq;
	    itemsrcq.prepare( "SELECT itemsrc_id, itemsrc_vend_item_number,"
		       "       itemsrc_vend_item_descrip, itemsrc_vend_uom,"
		       "       itemsrc_minordqty,"
		       "       itemsrc_multordqty,"
		       "       itemsrc_invvendoruomratio,"
		       "       (CURRENT_DATE + itemsrc_leadtime) AS earliestdate "
		       "FROM pohead, itemsrc "
		       "WHERE ( (itemsrc_vend_id=pohead_vend_id)"
		       " AND (itemsrc_item_id=:item_id)"
		       " AND (pohead_id=:pohead_id) );" );
	    itemsrcq.bindValue(":item_id", item->id());
	    itemsrcq.bindValue(":pohead_id", model->headId());
	    itemsrcq.exec();
	    if (itemsrcq.first())
	    {
	      model->setData(model->index(index.row(), POITEM_ITEMSRC_ID_COL), itemsrcq.value("itemsrc_id").toInt());
	      model->setData(model->index(index.row(), POITEM_VEND_ITEM_NUMBER_COL), itemsrcq.value("itemsrc_vend_item_number").toString());
	      model->setData(model->index(index.row(), POITEM_VEND_ITEM_DESCRIP_COL), itemsrcq.value("itemsrc_vend_item_descrip").toString());
	      model->setData(model->index(index.row(), POITEM_VEND_UOM_COL), itemsrcq.value("itemsrc_vend_uom").toString());
	      model->setData(model->index(index.row(), ITEMSRC_MINORDQTY_COL), itemsrcq.value("itemsrc_minordqty").toDouble());
	      model->setData(model->index(index.row(), ITEMSRC_MULTORDQTY_COL), itemsrcq.value("itemsrc_multordqty").toDouble());
	      model->setData(model->index(index.row(), ITEMSRC_INVVENDORUOMRATIO_COL), itemsrcq.value("itemsrc_invvendoruomratio").toDouble());
	      model->setData(model->index(index.row(), POITEM_INVVENDUOMRATIO_COL), itemsrcq.value("itemsrc_invvendoruomratio").toDouble());
	      model->setData(model->index(index.row(), EARLIESTDATE_COL), itemsrcq.value("earliestdate").toDate());

	      if (_metrics->boolean("UseEarliestAvailDateOnPOItem"))
		model->setData(model->index(index.row(), POITEM_DUEDATE_COL), itemsrcq.value("earliestdate").toDate());
	    }
	    else if (itemsrcq.lastError().type() != QSqlError::None)
	    {
	      systemError(0, itemsrcq.lastError().databaseText(), __FILE__, __LINE__);
	      hitError = true;
	      break;
	    }
	  }
	}
      }
      break;
    }

    case WAREHOUS_CODE_COL:
    {
      WComboBox *whs = static_cast<WComboBox*>(editor);
      if (whs->id() < 0)
      {
	model->setData(model->index(index.row(), WAREHOUS_ID_COL), QVariant());
	model->setData(index, QVariant());
      }
      else if (whs->id() != oldval.toInt())
      {
	model->setData(model->index(index.row(), WAREHOUS_ID_COL), whs->id());
	model->setData(index, whs->currentText());

	if (whs->isValid())
	{
	  XSqlQuery itemq;
	  itemq.prepare("SELECT itemsite_id "
			"FROM itemsite "
			"WHERE ((itemsite_item_id=:item_id)"
			"   AND (itemsite_warehous_id=:whs_id)) "
			"LIMIT 1;");
	  itemq.bindValue(":item_id", model->index(index.row(), ITEM_ID_COL).data());
	  itemq.bindValue(":whs_id",  whs->id());
	  itemq.exec();
	  if (itemq.first())
	  {
	    model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), itemq.value("itemsite_id").toInt());
	  }
	  else if (itemq.lastError().type() != QSqlError::None)
	  {
	    systemError(0, itemq.lastError().databaseText(), __FILE__, __LINE__);
	    hitError = true;
	    break;
	  }
	  else
	  {
	    systemError(0, QString("Could not find Item Site for %1 in %2.")
			    .arg(model->index(index.row(), ITEM_NUMBER_COL).data().toString())
			    .arg(whs->currentText()));
	    hitError = true;
	    break;
	  }
	}
      }
      break;
    }

    case POITEM_VEND_ITEM_NUMBER_COL:
    {
      XLineEdit *lineedit = static_cast<XLineEdit*>(editor);
      if (lineedit->text() != oldval.toString())
	model->setData(index, lineedit->text());
      break;
    }
    
    case POITEM_FREIGHT_COL:
    {
      XLineEdit *lineedit = static_cast<XLineEdit*>(editor);
      if (lineedit->toDouble() != oldval.toDouble())
	model->setData(index, lineedit->toDouble());
      break;
    }


    case POITEM_QTY_ORDERED_COL:
    {
      XLineEdit *lineedit = static_cast<XLineEdit*>(editor);
      if (lineedit->text().isEmpty())
      {
	model->setData(index, QVariant());
	model->setData(model->index(index.row(), EXTPRICE_COL), QVariant());
	break;
      }
      double qty = lineedit->toDouble();
      if (qty != oldval.toDouble())
      {
	model->setData(index, qty);
	if (model->data(model->index(index.row(), POITEM_QTY_ORDERED_COL)).toDouble() > 0 &&
	  model->data(model->index(index.row(), POITEM_ITEMSRC_ID_COL)).toInt() > 0)
	{
	  q.prepare( "SELECT ROUND(currToCurr(itemsrcp_curr_id, :curr_id, itemsrcp_price, :effective), :prec) "
		      "AS new_itemsrcp_price "
		     "FROM itemsrcp "
		     "WHERE ( (itemsrcp_itemsrc_id=:itemsrc_id)"
		     " AND (itemsrcp_qtybreak <= :qty) ) "
		     "ORDER BY itemsrcp_qtybreak DESC "
		     "LIMIT 1;" );
	  q.bindValue(":itemsrc_id", model->data(model->index(index.row(), POITEM_ITEMSRC_ID_COL)).toInt());
	  q.bindValue(":qty", model->data(model->index(index.row(), POITEM_QTY_ORDERED_COL)).toDouble());
	  q.bindValue(":curr_id", model->currId());
	  q.bindValue(":effective", model->transDate().toString());
	  q.bindValue(":prec", omfgThis->priceVal()->decimals());
	  q.exec();
	  if (q.first())
	  {
	    model->setData(model->index(index.row(), POITEM_UNITPRICE_COL), q.value("new_itemsrcp_price").toDouble());
	  }
	  else if (q.lastError().type() != QSqlError::None)
	  {
	    systemError(0, q.lastError().databaseText(), __FILE__, __LINE__);
	    hitError = true;
	    break;
	  }
	  else
	    model->setData(model->index(index.row(), POITEM_UNITPRICE_COL), 0);
	}

	double prc = model->data(model->index(index.row(), POITEM_UNITPRICE_COL)).toDouble();
	model->setData(model->index(index.row(), EXTPRICE_COL), (qty * prc));
      }
      break;
    }
    
    case POITEM_UNITPRICE_COL:
    {
      XLineEdit *lineedit = static_cast<XLineEdit*>(editor);
      if (lineedit->text().isEmpty())
      {
	model->setData(index, QVariant());
	model->setData(model->index(index.row(), EXTPRICE_COL), QVariant());
	break;
      }
      double prc = lineedit->text().toDouble();
      if (prc != oldval.toDouble())
      {
	model->setData(index, prc);
	double qty = model->data(model->index(index.row(),POITEM_QTY_ORDERED_COL)).toDouble();
	model->setData(model->index(index.row(), EXTPRICE_COL), (qty * prc));
      }
      break;
    }

    case POITEM_DUEDATE_COL:
    {
      XDateEdit *duedate = static_cast<XDateEdit*>(editor);
      duedate->parseDate();
      if (duedate->date() != oldval.toDate())
      {
        if (DEBUG)
          qDebug("PoitemTableDelegate::setModelData() setting duedate to %s with null %d, valid %d", 
                 qPrintable(duedate->date().toString()), duedate->isNull(),
                 duedate->isValid());
	model->setData(index, duedate->date());
      }

      break;
    }

#ifdef QE_NONINVENTORY
    case EXPCAT_CODE_COL:
    {
      ExpenseLineEdit *exp = static_cast<ExpenseLineEdit*>(editor);
      if (exp->id() != oldval.toInt())
      {
	model->setData(model->index(index.row(), POITEM_EXPCAT_ID_COL), exp->id());
	model->setData(index, exp->text());
      }
      break;
    }
#endif

    default:
      break;
  }

  QTableView *view = qobject_cast<QTableView*>(parent());
  if (view)
  {
    if (hitError)
      view->setCurrentIndex(index);
    else if (index.row() >= (model->rowCount() - 1))
    {
      QHeaderView* header = view->horizontalHeader();
      if (header->visualIndex(index.column()) >=
	  (header->count() - header->hiddenSectionCount() - 1))
      {
	model->insertRow(model->rowCount());
      }
    }
  }

  return;
}
コード例 #9
0
void enterPoitemReceipt::populate()
{
  XSqlQuery enterpopulate;
  ParameterList params;

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

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

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

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

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

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

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

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

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

    if (enterpopulate.value("inventoryitem").toBool() && itemsiteid <= 0)
    {
      MetaSQLQuery ism = mqlLoad("itemReceipt", "sourceItemSite");
      XSqlQuery isq = ism.toQuery(params);
      if (isq.first())
      {
        itemsiteid = itemSite::createItemSite(this,
                      isq.value("itemsite_id").toInt(),
                      isq.value("warehous_id").toInt(),
                      true);
        if (itemsiteid < 0)
          return;
        _item->setItemsiteid(itemsiteid);
      }
      else if (isq.lastError().type() != QSqlError::NoError)
      {
        systemError(this, isq.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
    }
  }
  else if (enterpopulate.lastError().type() != QSqlError::NoError)
  {
    systemError(this, enterpopulate.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
コード例 #10
0
enum SetResponse lotSerialRegistration::set(const ParameterList &pParams)
{
  XSqlQuery lotet;
  XDialog::set(pParams);
  QVariant param;
  bool     valid;

  param = pParams.value("crmacct_id", &valid);
  if (valid)
    _crmacct->setId(param.toInt());
  
  param = pParams.value("item_id", &valid);
  if (valid)
    _item->setId(param.toInt());
  
  param = pParams.value("ls_id", &valid);
  if (valid)
    _lotSerial->setId(param.toInt());
  
  param = pParams.value("lsreg_id", &valid);
  if (valid)
    _lsregid=param.toInt();

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

    if (param.toString() == "new")
    {
      _mode = cNew;
      lotet.exec ("SELECT fetchlsregnumber() AS number;");
      if (lotet.first())
	_regNumber->setText(lotet.value("number").toString());
      else if(lotet.lastError().type() != QSqlError::NoError)
      {
        systemError(this, lotet.lastError().databaseText(), __FILE__, __LINE__);
        reject();
      }
      lotet.exec("SELECT NEXTVAL('lsreg_lsreg_id_seq') AS _lsreg_id;");
      if (lotet.first())
        _lsregid = lotet.value("_lsreg_id").toInt();
      else if (lotet.lastError().type() != QSqlError::NoError)
      {
        systemError(this, lotet.lastError().databaseText(), __FILE__, __LINE__);
        reject();
      }
      _qty->setText("1");
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;
      populate();
      _itemGroup->setEnabled(false);
    }
    else if (param.toString() == "view")
    {
      _mode = cView;
      _regDate->setEnabled(false);
      _soldDate->setEnabled(false);
      _expireDate->setEnabled(false);
      _crmacct->setEnabled(false);
      _cntct->setEnabled(false);
      _type->setEnabled(false);
      _item->setReadOnly(true);
      _lotSerial->setEnabled(false);
      _newChar->setEnabled(false);
      _editChar->setEnabled(false);
      _deleteChar->setEnabled(false);
      _notes->setEnabled(false);
      _buttonBox->clear();
      _buttonBox->addButton(QDialogButtonBox::Close);
    }
  }

  param = pParams.value("crmacct_id", &valid);
  if (valid)
  {
    _crmacct->setId(param.toInt());
    _crmacct->setEnabled(false);
  }
  return NoError;
}
コード例 #11
0
void printInvoice::sPrint()
{
  q.prepare( "SELECT invchead_invcnumber, invchead_printed, invchead_posted,"
             "       findCustomerForm(invchead_cust_id, 'I') AS reportname "
             "FROM invchead "
             "WHERE (invchead_id=:invchead_id);" );
  q.bindValue(":invchead_id", _invcheadid);
  q.exec();
  if (q.first())
  {
    XSqlQuery xrate;
    xrate.prepare("SELECT curr_rate "
		  "FROM curr_rate, invchead "
		  "WHERE ((curr_id=invchead_curr_id)"
		  "  AND  (invchead_id=:invchead_id)"
		  "  AND  (invchead_invcdate BETWEEN curr_effective AND curr_expires));");
    // if SUM becomes dependent on curr_id then move XRATE before it in the loop
    XSqlQuery sum;
    sum.prepare("SELECT COALESCE(SUM(round((invcitem_billed * invcitem_qty_invuomratio) *"
                "                 (invcitem_price / "
                "                  CASE WHEN (item_id IS NULL) THEN 1"
                "                       ELSE invcitem_price_invuomratio"
                "                  END), 2)),0) + "
                "       invchead_freight + invchead_tax + "
                "       invchead_misc_amount AS subtotal "
                "  FROM invchead LEFT OUTER JOIN invcitem ON (invcitem_invchead_id=invchead_id) LEFT OUTER JOIN"
                "       item ON (invcitem_item_id=item_id) "
                " WHERE(invchead_id=:invchead_id) "
                " GROUP BY invchead_freight, invchead_tax, invchead_misc_amount;");
    QString reportname = q.value("reportname").toString();
    QString invchead_invcnumber = q.value("invchead_invcnumber").toString();

    bool dosetup = (!_setup);
    if (dosetup)
    {
      bool userCanceled = false;
      if (orReport::beginMultiPrint(&_printer, userCanceled) == false)
      {
	if(!userCanceled)
          systemError(this, tr("Could not initialize printing system for multiple reports."));
	return;
      }
    }

    // TODO: do we really want error checking & invoice posting INSIDE the loop?
    for (int i = 0; i < _invoiceWatermarks->topLevelItemCount(); i++ )
    {
      QTreeWidgetItem *cursor = _invoiceWatermarks->topLevelItem(i);
      ParameterList params;
      params.append("invchead_id", _invcheadid);
      params.append("showcosts", ((cursor->text(2) == tr("Yes")) ? "TRUE" : "FALSE"));
      params.append("watermark", cursor->text(1));

      orReport report(reportname, params);
      if (!report.isValid())
        QMessageBox::critical( this, tr("Cannot Find Invoice Form"),
                               tr( "The Invoice Form '%1' cannot be found for Invoice #%2.\n"
                                   "This Invoice cannot be printed until a Customer Form Assignment is updated to remove any\n"
                                   "references to this Invoice Form or this Invoice Form is created." )
                               .arg(reportname)
                               .arg(invchead_invcnumber) );
          
      else
      {
        if (report.print(&_printer, dosetup))
          dosetup = FALSE;
        else
        {
          systemError( this, tr("A Printing Error occurred at printInvoice::%1.")
                             .arg(__LINE__) );
	  if (!_captive)
	    orReport::endMultiPrint(&_printer);
          return;
        }

        q.prepare( "UPDATE invchead "
                   "SET invchead_printed=TRUE "
                   "WHERE (invchead_id=:invchead_id);" );
        q.bindValue(":invchead_id", _invcheadid);
        q.exec();

        if (_alert)
          omfgThis->sInvoicesUpdated(_invcheadid, TRUE);

        if (_post->isChecked())
        {
	  sum.bindValue(":invchead_id", _invcheadid);
	  if (sum.exec() && sum.first() && sum.value("subtotal").toDouble() == 0)
	  {
	    if (QMessageBox::question(this, tr("Invoice Has Value 0"),
				      tr("Invoice #%1 has a total value of 0.\n"
					 "Would you like to post it anyway?")
					.arg(invchead_invcnumber),
				      QMessageBox::Yes,
				      QMessageBox::No | QMessageBox::Default)
		  == QMessageBox::No)
	      continue;
	  }
	  else if (sum.lastError().type() != QSqlError::NoError)
	  {
	    systemError(this, sum.lastError().databaseText(), __FILE__, __LINE__);
	    continue;
	  }
	  else if (sum.value("subtotal").toInt() != 0)
	  {
	    xrate.bindValue(":invchead_id", _invcheadid);
	    xrate.exec();
	    if (xrate.lastError().type() != QSqlError::NoError)
	    {
	      systemError(this, tr("System Error posting Invoice #%1\n%2")
				  .arg(cursor->text(0))
				  .arg(xrate.lastError().databaseText()),
			  __FILE__, __LINE__);
	      continue;
	    }
	    else if (!xrate.first() || xrate.value("curr_rate").isNull())
	    {
	      systemError(this, tr("Could not post Invoice #%1 because of a missing exchange rate.")
				  .arg(cursor->text(0)));
	      continue;
	    }
	  }

          q.prepare("SELECT postInvoice(:invchead_id) AS result;");
          q.bindValue(":invchead_id", _invcheadid);
          q.exec();
	  if (q.lastError().type() != QSqlError::NoError)
	      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
        }
      }
    }

    if (_metrics->boolean("EnableBatchManager"))
    {
      // TODO: Check for EDI and handle submission to Batch here
      q.prepare("SELECT CASE WHEN (COALESCE(shipto_ediprofile_id, -2) = -2)"
              "              THEN COALESCE(cust_ediprofile_id,-1)"
              "            ELSE COALESCE(shipto_ediprofile_id,-2)"
              "       END AS result,"
              "       COALESCE(cust_emaildelivery, false) AS custom"
              "  FROM cust, invchead"
              "       LEFT OUTER JOIN shipto"
              "         ON (invchead_shipto_id=shipto_id)"
              "  WHERE ((invchead_cust_id=cust_id)"
              "    AND  (invchead_id=:invchead_id)); ");
      q.bindValue(":invchead_id", _invcheadid);
      q.exec();
      if(q.first())
      {
        if(q.value("result").toInt() == -1)
        {
          if(q.value("custom").toBool())
          {
            ParameterList params;
            params.append("invchead_id", _invcheadid);

            deliverInvoice newdlg(this, "", TRUE);
            newdlg.set(params);
            newdlg.exec();
          }
        }
        else
        {
          ParameterList params;
          params.append("action_name", "TransmitInvoice");
          params.append("invchead_id", _invcheadid);

          submitAction newdlg(this, "", TRUE);
          newdlg.set(params);
          newdlg.exec();
        }
      }
    }
    
    if (_captive)
      accept();
    else
      orReport::endMultiPrint(&_printer);
  }
  else
    systemError(this, tr("A System Error occurred at %1::%2.")
                      .arg(__FILE__)
                      .arg(__LINE__) );
}
コード例 #12
0
void lotSerialRegistration::sSave()
{
  XSqlQuery lotSave;
  if(cView == _mode)
    return;

  if (!_crmacct->isValid())
  {
    QMessageBox::warning(this, windowTitle(), tr("You must provide a CRM Account."));
    _crmacct->setFocus();
    return;
  }
  
  if (!_regDate->isValid())
  {
    QMessageBox::warning(this, windowTitle(), tr("You must provide a registration date."));
    _regDate->setFocus();
    return;
  }
  
  if (!_soldDate->isValid())
  {
    QMessageBox::warning(this, windowTitle(), tr("You must provide a sold date."));
    _soldDate->setFocus();
    return;
  }

  if (!_expireDate->isValid())
  {
    QMessageBox::warning(this, windowTitle(), tr("You must provide a expiration date."));
    _expireDate->setFocus();
    return;
  }
  
  if (_lotSerial->id() == -1)
  {
    QMessageBox::warning(this, windowTitle(), tr("You must provide a lot/serial number."));
    _lotSerial->setFocus();
    return;
  }
  
  if (!(_qty->toDouble() > 0))
  {
    QMessageBox::warning(this, windowTitle(), tr("You must provide a quantity greater than zero."));
    _qty->setFocus();
    return;
  }

  if (_cntct->id() == -1)
  {
    QMessageBox::warning(this, windowTitle(), "You must provide a contact.");
    _cntct->setFocus();
    return;
  }

  if(cNew == _mode)
  {
    lotSave.prepare("INSERT INTO lsreg"
              "      (lsreg_id, lsreg_number, lsreg_regtype_id,"
              "       lsreg_ls_id, lsreg_qty, lsreg_regdate, lsreg_solddate,"
              "       lsreg_expiredate, lsreg_crmacct_id, lsreg_cntct_id,"
              "       lsreg_notes, lsreg_cohead_id, lsreg_shiphead_id) "
              "VALUES(:lsreg_id, :lsreg_number, :lsreg_regtype_id,"
              "       :lsreg_ls_id, :lsreg_qty, :lsreg_regdate, :lsreg_solddate,"
              "       :lsreg_expiredate, :lsreg_crmacct_id, :lsreg_cntct_id,"
              "       :lsreg_notes, :lsreg_cohead_id, :lsreg_shiphead_id);");
  }
  else if(cEdit == _mode)
    lotSave.prepare("UPDATE lsreg"
              "   SET lsreg_number=:lsreg_number,"
              "       lsreg_regtype_id=:lsreg_regtype_id,"
              "       lsreg_ls_id=:lsreg_ls_id,"
              "       lsreg_qty=:lsreg_qty,"
              "       lsreg_regdate=:lsreg_regdate,"
              "       lsreg_solddate=:lsreg_solddate,"
              "       lsreg_expiredate=:lsreg_expiredate,"
              "       lsreg_crmacct_id=:lsreg_crmacct_id,"
              "       lsreg_cntct_id=:lsreg_cntct_id,"
              "       lsreg_notes=:lsreg_notes,"
              "       lsreg_cohead_id=:lsreg_cohead_id,"
              "       lsreg_shiphead_id=:lsreg_shiphead_id"
              " WHERE(lsreg_id=:lsreg_id);");
  
  lotSave.bindValue(":lsreg_id", _lsregid);
  lotSave.bindValue(":lsreg_number", _regNumber->text().trimmed());
  lotSave.bindValue(":lsreg_regtype_id", _type->id());
  lotSave.bindValue(":lsreg_ls_id", _lotSerial->id());
  lotSave.bindValue(":lsreg_qty", _qty->toDouble());
  lotSave.bindValue(":lsreg_regdate", _regDate->date());
  lotSave.bindValue(":lsreg_solddate", _soldDate->date());
  lotSave.bindValue(":lsreg_expiredate", _expireDate->date());
  lotSave.bindValue(":lsreg_crmacct_id", _crmacct->id());
  lotSave.bindValue(":lsreg_cntct_id", _cntct->id());
  lotSave.bindValue(":lsreg_notes",    _notes->toPlainText());
  if(_so->id() != -1)
    lotSave.bindValue(":lsreg_cohead_id", _so->id());
  if(_shipment->id() != -1)
    lotSave.bindValue(":lsreg_shiphead_id", _shipment->id());

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

  _mode = 0;
  close();
}
コード例 #13
0
ファイル: taxCodeRate.cpp プロジェクト: Wushaowei001/xtuple-1
enum SetResponse taxCodeRate::set( const ParameterList & pParams )
{
  XDialog::set(pParams);
  QVariant param;
  bool     valid;

  param = pParams.value("taxrate_id", &valid);
  if (valid)
    _taxrateid = param.toInt();
  
  param = pParams.value("tax_id", &valid);
  if (valid)
    _taxId = param.toInt(); 

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;
	  q.prepare(" (SELECT taxrate_id "
                " FROM taxrate "
                " WHERE taxrate_tax_id = :taxrate_tax_id); ");
	  q.bindValue(":taxrate_tax_id", _taxId);
	  q.exec();
	  if(q.first())
      {
	    XSqlQuery maxdate;
		maxdate.prepare(" (SELECT (MAX(taxrate_expires) + 1) AS max_expires"
                        " FROM taxrate "
                        " WHERE taxrate_tax_id = :taxrate_tax_id) ");
	    maxdate.bindValue(":taxrate_tax_id", _taxId);
	    maxdate.exec();
	    if(maxdate.first())
		{
		  _dates->setStartDate(maxdate.value("max_expires").toDate());
		}
		else if (maxdate.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, maxdate.lastError().databaseText(), __FILE__, __LINE__);
          return UndefinedError;
        }
	  }
	  _dates->setFocus();
      
      q.exec("SELECT NEXTVAL('taxrate_taxrate_id_seq') AS taxrate_id");
      if (q.first())
        _taxrateid = q.value("taxrate_id").toInt();
      else if (q.lastError().type() != QSqlError::NoError)
      {
	    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
		return UndefinedError;
      }
	}
    else if (param.toString() == "edit")
    {
      _mode = cEdit;
	  sPopulate();
      
      _save->setFocus();
    }
    else if (param.toString() == "view")
    {
      _mode = cView;
	  sPopulate();

      _dates->setEnabled(FALSE);
	  _percent->setEnabled(FALSE);
	  _flat->setEnabled(FALSE);
      _close->setText(tr("&Close"));
      _save->hide();
      
      _close->setFocus();
    }
  }
  
  return NoError;
}
コード例 #14
0
void postCashReceipts::sPost()
{
  int journalNumber;

  q.exec("SELECT fetchJournalNumber('C/R') AS journalnumber;");
  if (q.first())
    journalNumber = q.value("journalnumber").toInt();
  else
  {
    systemError(this, tr("A System Error occurred at %1::%2.")
                      .arg(__FILE__)
                      .arg(__LINE__) );
    return;
  }

  q.exec( "SELECT cashrcpt_id, cust_number "
          "FROM cashrcpt, cust "
          "WHERE (cashrcpt_cust_id=cust_id);" );
  if (q.first())
  {
    int counter = 0;

    XSqlQuery post;
    post.prepare("SELECT postCashReceipt(:cashrcpt_id, :journalNumber) AS result;");
    
    do
    {
      message( tr("Posting Cash Receipt #%1...")
               .arg(q.value("cust_number").toString()) );

      post.bindValue(":cashrcpt_id", q.value("cashrcpt_id"));
      post.bindValue(":journalNumber", journalNumber);
      post.exec();
      if (post.first())
      {
        switch (post.value("result").toInt())
        {
          case -1:
            QMessageBox::critical( this, tr("Cannot Post Cash Receipt"),
                                   tr( "The selected Cash Receipt cannot be posted as the amount distributed is greater than\n"
                                       "the amount received. You must correct this before you may post this Cash Receipt." ) );
            break;

          case -5:
            QMessageBox::critical( this, tr("Cannot Post Cash Receipt"),
                                   tr( "A Cash Receipt for Customer #%1 cannot be posted as the A/R Account cannot be determined.\n"
                                       "You must make a A/R Account Assignment for the Customer Type to which this Customer\n"
                                       "is assigned for you may post this Cash Receipt." )
                                   .arg(q.value("cust_number").toString())  );
            break;

          case -6:
            QMessageBox::critical( this, tr("Cannot Post Cash Receipt"),
                                   tr( "A Cash Receipt for Customer #%1 cannot be posted as the Bank Account cannot be determined.\n"
                                       "You must make a Bank Account Assignment for this Cash Receipt before you may post it." )
                                   .arg(q.value("cust_number").toString())  );
            break;

          case -7:
            QMessageBox::critical( this, tr("Cannot Post Cash Receipt"),
                                   tr( "A Cash Receipt for Customer #%1 cannot be posted due to an unknown error.\n"
                                       "Contact you Systems Administrator." )
                                   .arg(q.value("cust_number").toString())  );

          default:
            counter++;
        }
      }
      else
      {
        systemError( this, tr("While posting the cash receipt for Customer %1:"
			      "\n\n%2")
                           .arg(q.value("cust_number").toString())
                           .arg(post.lastError().databaseText()),
		     __FILE__, __LINE__ );
        break;
      }
    }
    while (q.next());

    resetMessage();

    if ( (counter) && (_printJournal->isChecked()) )
    {
      ParameterList params;
      params.append("journalNumber", journalNumber);
     
      orReport report("CashReceiptsJournal", params);
      if (report.isValid())
        report.print();
      else
        report.reportError(this);
    }

    omfgThis->sCashReceiptsUpdated(-1, true);

    accept();
  }
  else
  {
    QMessageBox::information( this, tr("No Unposted Cash Receipts"),
                              tr("There are no unposted Cash Receipts to post.") );
  }
}
コード例 #15
0
void dspInvoiceInformation::sParseInvoiceNumber()
{
  XSqlQuery dspParseInvoiceNumber;
  dspParseInvoiceNumber.prepare( "SELECT invchead_id, invchead_cust_id, invchead_ponumber,"
             "       invchead_shipdate, invchead_invcdate,"
             "       invoiceTotal(invchead_id) AS amount,"
             "       invchead_billto_name, invchead_billto_address1,"
             "       invchead_billto_address2, invchead_billto_address3,"
             "       invchead_billto_city, invchead_billto_state, invchead_billto_zipcode,"
             "       invchead_shipto_name, invchead_shipto_address1,"
             "       invchead_shipto_address2, invchead_shipto_address3,"
             "       invchead_shipto_city, invchead_shipto_state, invchead_shipto_zipcode,"
             "       invchead_notes "
             "FROM invchead LEFT OUTER JOIN"
             "     ( invcitem LEFT OUTER JOIN item"
             "       ON (invcitem_item_id=item_id) )"
             "     ON (invcitem_invchead_id=invchead_id) "
             "WHERE (invchead_invcnumber=:invoiceNumber) "
             "GROUP BY invchead_id, invchead_cust_id, invchead_ponumber,"
             "         invchead_shipdate, invchead_invcdate,"
             "         invchead_misc_amount, invchead_freight,"
             "         invchead_billto_name, invchead_billto_address1,"
             "         invchead_billto_address2, invchead_billto_address3,"
             "         invchead_billto_city, invchead_billto_state, invchead_billto_zipcode,"
             "         invchead_shipto_name, invchead_shipto_address1,"
             "         invchead_shipto_address2, invchead_shipto_address3,"
             "         invchead_shipto_city, invchead_shipto_state, invchead_shipto_zipcode,"
             "         invchead_notes;" );
  dspParseInvoiceNumber.bindValue(":invoiceNumber", _invoiceNumber->invoiceNumber());
  dspParseInvoiceNumber.exec();
  if (dspParseInvoiceNumber.first())
  {
    _print->setEnabled(true);
    _view->setEnabled(true);

    _invcheadid = dspParseInvoiceNumber.value("invchead_id").toInt();

    _custPoNumber->setText(dspParseInvoiceNumber.value("invchead_ponumber").toString());
    _cust->setId(dspParseInvoiceNumber.value("invchead_cust_id").toInt());
    _invoiceDate->setDate(dspParseInvoiceNumber.value("invchead_invcdate").toDate());
    _shipDate->setDate(dspParseInvoiceNumber.value("invchead_shipdate").toDate());
    _invoiceAmount->setDouble(dspParseInvoiceNumber.value("amount").toDouble());

    _billToName->setText(dspParseInvoiceNumber.value("invchead_billto_name"));
    _billToAddress1->setText(dspParseInvoiceNumber.value("invchead_billto_address1"));
    _billToAddress2->setText(dspParseInvoiceNumber.value("invchead_billto_address2"));
    _billToAddress3->setText(dspParseInvoiceNumber.value("invchead_billto_address3"));
    _billToCity->setText(dspParseInvoiceNumber.value("invchead_billto_city"));
    _billToState->setText(dspParseInvoiceNumber.value("invchead_billto_state"));
    _billToZip->setText(dspParseInvoiceNumber.value("invchead_billto_zipcode"));

    _shipToName->setText(dspParseInvoiceNumber.value("invchead_shipto_name"));
    _shipToAddress1->setText(dspParseInvoiceNumber.value("invchead_shipto_address1"));
    _shipToAddress2->setText(dspParseInvoiceNumber.value("invchead_shipto_address2"));
    _shipToAddress3->setText(dspParseInvoiceNumber.value("invchead_shipto_address3"));
    _shipToCity->setText(dspParseInvoiceNumber.value("invchead_shipto_city"));
    _shipToState->setText(dspParseInvoiceNumber.value("invchead_shipto_state"));
    _shipToZip->setText(dspParseInvoiceNumber.value("invchead_shipto_zipcode"));

    _notes->setText(dspParseInvoiceNumber.value("invchead_notes").toString());

    MetaSQLQuery mql = mqlLoad("invoiceInformation", "detail");
    ParameterList params;
    if (! setParams(params))
      return;

    dspParseInvoiceNumber = mql.toQuery(params);
    _arapply->populate(dspParseInvoiceNumber);
  }
  else
  {
    if (dspParseInvoiceNumber.lastError().type() != QSqlError::NoError)
      systemError(this, dspParseInvoiceNumber.lastError().databaseText(), __FILE__, __LINE__);
    _print->setEnabled(false);
    _view->setEnabled(false);
    _invoiceNumber->clear();
    _arapply->clear();
    _invcheadid = -1;
  }
}
コード例 #16
0
void enterPoitemReceipt::sReceive()
{
  XSqlQuery enterReceive;
  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");
    
  if(_metrics->boolean("DisallowReceiptExcessQty") && _receivable < _toReceive->toDouble())
  {
    XMessageBox::message( (isVisible() ? this : parentWidget()), QMessageBox::Warning, tr("Cannot Receive"),
                          tr(  "<p>Cannot receive more quantity than ordered." ),
                          QString::null, QString::null, _snooze );
    return;
  }

  if(_ordertype == "RA" && _receivable < _toReceive->toDouble())
  {
    XMessageBox::message( (isVisible() ? this : parentWidget()), QMessageBox::Warning, tr("Cannot Receive"),
                          tr(  "<p>Cannot receive more quantity than authorized." ),
                          QString::null, QString::null, _snooze );
    return;
  }

  double tolerance = _metrics->value("ReceiptQtyTolerancePct").toDouble() / 100.0;
  if(_metrics->boolean("WarnIfReceiptQtyDiffers") &&
      (_receivable < _toReceive->toDouble() * (1.0 - tolerance) ||
       _receivable > _toReceive->toDouble() * (1.0 + tolerance)))
  {
    if(XMessageBox::message( (isVisible() ? this : parentWidget()) , QMessageBox::Question, tr("Receipt Qty. Differs"),
        tr("<p>The Qty entered does not match the receivable Qty for this order. "
		   "Do you wish to continue anyway?"),
        tr("Yes"), tr("No"), _snooze, 0, 1) == 1)
      return;
  }

  int result = 0;
  QString storedProc;
  if (_mode == cNew)
  {
    enterReceive.prepare("SELECT enterReceipt(:ordertype, :poitem_id, :qty, :freight, :notes, "
              ":curr_id, :effective, :purchcost) AS result;");
    enterReceive.bindValue(":poitem_id",	_orderitemid);
    enterReceive.bindValue(":ordertype",	_ordertype);
    storedProc = "enterReceipt";
  }
  else if (_mode == cEdit)
  {
    enterReceive.exec("BEGIN;");	// because of possible lot, serial, or location distribution cancelations
    enterReceive.prepare("UPDATE recv SET recv_notes = :notes WHERE (recv_id=:recv_id);" );
    enterReceive.bindValue(":notes",	_notes->toPlainText());
    enterReceive.bindValue(":recv_id",	_recvid);
    enterReceive.exec();
    if (enterReceive.lastError().type() != QSqlError::NoError)
    {
      rollback.exec();
      systemError(this, enterReceive.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    
    enterReceive.prepare("SELECT correctReceipt(:recv_id, :qty, :freight, 0, "
              ":curr_id, :effective, :purchcost) AS result;");
    enterReceive.bindValue(":recv_id", _recvid);
    storedProc = "correctReceipt";
  }

  enterReceive.bindValue(":qty",		_toReceive->toDouble());
  enterReceive.bindValue(":freight",	_freight->localValue());
  enterReceive.bindValue(":notes",		_notes->toPlainText());
  enterReceive.bindValue(":curr_id",	_freight->id());
  enterReceive.bindValue(":effective",	_receiptDate->date());
  enterReceive.bindValue(":purchcost",     _purchCost->localValue());
  enterReceive.exec();
  if (enterReceive.first())
  {
    result = enterReceive.value("result").toInt();
    if (result < 0)
    {
      rollback.exec();
      systemError(this, storedProcErrorLookup(storedProc, result),
		  __FILE__, __LINE__);
      return;
    }
  }
  else if (enterReceive.lastError().type() != QSqlError::NoError)
  {
      rollback.exec();
      systemError(this, enterReceive.lastError().databaseText(), __FILE__, __LINE__);
      return;
  }

  if(cEdit == _mode)
  {
    if (distributeInventory::SeriesAdjust(result, this) == XDialog::Rejected)
    {
      rollback.exec();
      XMessageBox::message( (isVisible() ? this : parentWidget()), QMessageBox::Warning, tr("Enter PO Receipt"),
                            tr(  "<p>Transaction Cancelled." ),
                            QString::null, QString::null, _snooze );
      return;
    }

    enterReceive.exec("COMMIT;");
  }

  omfgThis->sPurchaseOrderReceiptsUpdated();
  accept();
  
  if (_printLabel->isChecked())
    sPrintItemLabel();
}
コード例 #17
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;
}
コード例 #18
0
void invoiceItem::sSave()
{
  QList<GuiErrorCheck> errors;
  errors << GuiErrorCheck(_itemSelected->isChecked() && !_item->isValid(), _item,
                          tr("<p>You must select an Item for this Invoice Item before you may save it."))
         << GuiErrorCheck(!_itemSelected->isChecked() && !_itemNumber->text().length(), _itemNumber,
                          tr("<p>You must enter an Item Number for this Miscellaneous Invoice Item before you may save it."))
         << GuiErrorCheck(!_itemSelected->isChecked() && !_itemDescrip->toPlainText().length(), _itemDescrip,
                          tr("<p>You must enter a Item Description for this Miscellaneous Invoice Item before you may save it."))
         << GuiErrorCheck(!_itemSelected->isChecked() && !_salescat->isValid(), _salescat,
                          tr("<p>You must select a Sales Category for this Miscellaneous Invoice Item before you may save it."))
  ;
  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Invoice Item"), errors))
    return;

  XSqlQuery invoiceSave;

  if (_mode == cNew)
  {
    invoiceSave.prepare( "INSERT INTO invcitem "
               "( invcitem_id, invcitem_invchead_id, invcitem_linenumber,"
               "  invcitem_item_id, invcitem_warehous_id,"
               "  invcitem_number, invcitem_descrip, invcitem_salescat_id,"
               "  invcitem_custpn,"
               "  invcitem_ordered, invcitem_billed, invcitem_updateinv,"
               "  invcitem_qty_uom_id, invcitem_qty_invuomratio,"
               "  invcitem_custprice, invcitem_price,"
               "  invcitem_price_uom_id, invcitem_price_invuomratio,"
               "  invcitem_notes, "
               "  invcitem_taxtype_id, invcitem_rev_accnt_id) "
               "VALUES "
               "( :invcitem_id, :invchead_id, :invcitem_linenumber,"
               "  :item_id, :warehous_id,"
               "  :invcitem_number, :invcitem_descrip, :invcitem_salescat_id,"
               "  :invcitem_custpn,"
               "  :invcitem_ordered, :invcitem_billed, :invcitem_updateinv,"
               "  :qty_uom_id, :qty_invuomratio,"
               "  :invcitem_custprice, :invcitem_price,"
               "  :price_uom_id, :price_invuomratio,"
               "  :invcitem_notes, "
               "  :invcitem_taxtype_id, :invcitem_rev_accnt_id);");
	       
    invoiceSave.bindValue(":invchead_id", _invcheadid);
    invoiceSave.bindValue(":invcitem_linenumber", _lineNumber->text());
  }
  else if (_mode == cEdit)
    invoiceSave.prepare( "UPDATE invcitem "
               "SET invcitem_item_id=:item_id, invcitem_warehous_id=:warehous_id,"
               "    invcitem_number=:invcitem_number, invcitem_descrip=:invcitem_descrip,"
               "    invcitem_salescat_id=:invcitem_salescat_id,"
               "    invcitem_custpn=:invcitem_custpn, invcitem_updateinv=:invcitem_updateinv,"
               "    invcitem_ordered=:invcitem_ordered, invcitem_billed=:invcitem_billed,"
               "    invcitem_qty_uom_id=:qty_uom_id, invcitem_qty_invuomratio=:qty_invuomratio,"
               "    invcitem_custprice=:invcitem_custprice, invcitem_price=:invcitem_price,"
               "    invcitem_price_uom_id=:price_uom_id, invcitem_price_invuomratio=:price_invuomratio,"
               "    invcitem_notes=:invcitem_notes,"
               "    invcitem_taxtype_id=:invcitem_taxtype_id,"
               "    invcitem_rev_accnt_id=:invcitem_rev_accnt_id "
	           "WHERE (invcitem_id=:invcitem_id);" );

  if (_itemSelected->isChecked())
  {
    invoiceSave.bindValue(":item_id", _item->id());
    invoiceSave.bindValue(":warehous_id", _warehouse->id());
  }
  else
  {
    invoiceSave.bindValue(":item_id", -1);
    invoiceSave.bindValue(":warehous_id", -1);
  }

  invoiceSave.bindValue(":invcitem_id", _invcitemid);
  invoiceSave.bindValue(":invcitem_number", _itemNumber->text());
  invoiceSave.bindValue(":invcitem_descrip", _itemDescrip->toPlainText());
  invoiceSave.bindValue(":invcitem_salescat_id", _salescat->id());
  invoiceSave.bindValue(":invcitem_custpn", _custPn->text());
  invoiceSave.bindValue(":invcitem_ordered", _ordered->toDouble());
  invoiceSave.bindValue(":invcitem_billed", _billed->toDouble());
  invoiceSave.bindValue(":invcitem_updateinv", QVariant(_updateInv->isChecked()));
  if(!_miscSelected->isChecked())
    invoiceSave.bindValue(":qty_uom_id", _qtyUOM->id());
  invoiceSave.bindValue(":qty_invuomratio", _qtyinvuomratio);
  invoiceSave.bindValue(":invcitem_custprice", _custPrice->localValue());
  invoiceSave.bindValue(":invcitem_price", _price->localValue());
  if(!_miscSelected->isChecked())
    invoiceSave.bindValue(":price_uom_id", _pricingUOM->id());
  invoiceSave.bindValue(":price_invuomratio", _priceinvuomratio);
  invoiceSave.bindValue(":invcitem_notes", _notes->toPlainText());
  if(_taxtype->isValid())
    invoiceSave.bindValue(":invcitem_taxtype_id",	_taxtype->id());
  if (_altRevAccnt->isValid())
    invoiceSave.bindValue(":invcitem_rev_accnt_id", _altRevAccnt->id());

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

  done(_invcitemid);
}
コード例 #19
0
bool taxAuthority::sSave()
{
  QList<GuiErrorCheck> errors;
  errors << GuiErrorCheck(_code->text().isEmpty(), _code,
                          tr("You must enter a valid Code."))
    ;

  XSqlQuery dupq;
  dupq.prepare("SELECT taxauth_id "
               "FROM taxauth "
               "WHERE ( (taxauth_id<>:taxauth_id)"
               " AND (UPPER(taxauth_code)=UPPER(:taxauth_code)) );");
  dupq.bindValue(":taxauth_id", _taxauthid);
  dupq.bindValue(":taxauth_code", _code->text().trimmed());
  dupq.exec();
  if (dupq.first())
    errors << GuiErrorCheck(true, _code,
                            tr("A Tax Authority with the entered code already "
                               "exists. You may not create a Tax Authority "
                               "with this code."));
  else if (ErrorReporter::error(QtCriticalMsg, this,
                                tr("Cannot Create Tax Authority"),
                                dupq, __FILE__, __LINE__))
    return false;

  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Tax Authority"), errors))
    return false;

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

  XSqlQuery begin("BEGIN;");

  int saveResult = _address->save(AddressCluster::CHECK);
  if (-2 == saveResult)
  {
    int answer = QMessageBox::question(this,
                   tr("Question Saving Address"),
                   tr("<p>There are multiple uses of this "
                      "Address. What would you like to do?"),
                   tr("Change This One"),
                   tr("Change Address for All"),
                   tr("Cancel"),
                   2, 2);
    if (0 == answer)
      saveResult = _address->save(AddressCluster::CHANGEONE);
    else if (1 == answer)
      saveResult = _address->save(AddressCluster::CHANGEALL);
  }
  if (saveResult < 0)  // not else-if: this is error check for CHANGE{ONE,ALL}
  {
    rollback.exec();
    ErrorReporter::error(QtCriticalMsg, this, tr("Error saving Address"),
                          storedProcErrorLookup("saveAddr", saveResult),
                          __FILE__, __LINE__);
    _address->setFocus();
    return false;
  }

  XSqlQuery upsq;
  if (_mode == cEdit)
  {
    upsq.prepare( "UPDATE taxauth "
               "   SET taxauth_code=:taxauth_code,"
               "       taxauth_name=:taxauth_name,"
               "       taxauth_extref=:taxauth_extref,"
               "       taxauth_curr_id=:taxauth_curr_id,"
               "       taxauth_addr_id=:taxauth_addr_id,"
               "       taxauth_county=:taxauth_county,"
               "       taxauth_accnt_id=:taxauth_accnt_id "
               "WHERE (taxauth_id=:taxauth_id) "
               "RETURNING taxauth_id;" );
    upsq.bindValue(":taxauth_id", _taxauthid);
  }
  else if (_mode == cNew)
    upsq.prepare( "INSERT INTO taxauth "
               "( taxauth_id, taxauth_code, taxauth_name, taxauth_extref,"
               "  taxauth_curr_id, taxauth_addr_id, taxauth_county,"
               "  taxauth_accnt_id) "
               "VALUES "
               "( DEFAULT, :taxauth_code, :taxauth_name, :taxauth_extref,"
               "  :taxauth_curr_id, :taxauth_addr_id, :taxauth_county,"
               "  :taxauth_accnt_id) "
               "RETURNING taxauth_id;" );

  upsq.bindValue(":taxauth_code", _code->text().trimmed());
  upsq.bindValue(":taxauth_name", _name->text());
  upsq.bindValue(":taxauth_extref", _extref->text());
  if(_currency->isValid())
    upsq.bindValue(":taxauth_curr_id", _currency->id());
  if(_address->isValid())
    upsq.bindValue(":taxauth_addr_id", _address->id());
  upsq.bindValue(":taxauth_county",    _county->text());
  if(_glaccnt->isValid())
    upsq.bindValue(":taxauth_accnt_id", _glaccnt->id());
  upsq.exec();
  if (upsq.first())
    _taxauthid = upsq.value("taxauth_id").toInt();
  else if (upsq.lastError().type() != QSqlError::NoError)
  {
    rollback.exec();
    ErrorReporter::error(QtCriticalMsg, this, tr("Cannot save Tax Authority"),
                         upsq, __FILE__, __LINE__);
    return false;
  }

  XSqlQuery commit("COMMIT;");
  _NumberGen = -1;

  omfgThis->sTaxAuthsUpdated(_taxauthid);

  done(_taxauthid);
  return true;
}
コード例 #20
0
void invoiceItem::populate()
{
  XSqlQuery invcitem;
  invcitem.prepare( "SELECT invcitem.*, invchead_invcnumber,"
                    "       CASE WHEN (item_id IS NULL) THEN :na"
                    "            ELSE item_listprice"
                    "       END AS f_listprice,"
                    "		taxzone_id,"
                    "       invchead_curr_id AS taxcurr_id,"
                    "       itemsite_costmethod"
                    " FROM invcitem JOIN "
                    "     invchead LEFT OUTER JOIN taxzone ON "
                    "       (invchead_taxzone_id = taxzone_id) "
                    "     ON (invcitem_invchead_id = invchead_id) LEFT OUTER JOIN "
                    "     item ON (invcitem_item_id = item_id) "
                    " LEFT OUTER JOIN invcitemtax ON (invcitem_id = taxhist_parent_id) "
                    " LEFT OUTER JOIN itemsite ON (itemsite_item_id=item_id "
                    "                          AND itemsite_warehous_id=invcitem_warehous_id)"
                    "WHERE (invcitem_id = :invcitem_id);" );
  invcitem.bindValue(":invcitem_id", _invcitemid);
  invcitem.exec();
  if (invcitem.first())
  {
    _invcheadid = invcitem.value("invcitem_invchead_id").toInt();
    _invoiceNumber->setText(invcitem.value("invchead_invcnumber").toString());
    _lineNumber->setText(invcitem.value("invcitem_linenumber").toString());

    // TODO: should this check itemsite_controlmethod == N?
    _trackqoh = (invcitem.value("invcitem_coitem_id").toInt() > 0 &&
                 invcitem.value("itemsite_costmethod").toString() != "J");

    if (invcitem.value("invcitem_item_id").toInt() != -1)
    {
      _itemSelected->setChecked(TRUE);
      _item->setId(invcitem.value("invcitem_item_id").toInt());
      _warehouse->setId(invcitem.value("invcitem_warehous_id").toInt());
    }
    else
    {
      _miscSelected->setChecked(TRUE);
      _itemNumber->setText(invcitem.value("invcitem_number"));
      _itemDescrip->setText(invcitem.value("invcitem_descrip").toString());
      _salescat->setId(invcitem.value("invcitem_salescat_id").toInt());
    }

    _qtyUOM->setId(invcitem.value("invcitem_qty_uom_id").toInt());
    _qtyinvuomratio = invcitem.value("invcitem_qty_invuomratio").toDouble();
    _pricingUOM->setId(invcitem.value("invcitem_price_uom_id").toInt());
    _priceinvuomratio = invcitem.value("invcitem_price_invuomratio").toDouble();

    // do tax stuff before invcitem_price and _tax_* to avoid signal cascade problems
    if (! invcitem.value("taxzone_id").isNull())
      _taxzoneid = invcitem.value("taxzone_id").toInt();
	_tax->setId(invcitem.value("taxcurr_id").toInt());
    _taxtype->setId(invcitem.value("invcitem_taxtype_id").toInt());
    _altRevAccnt->setId(invcitem.value("invcitem_rev_accnt_id").toInt());

    _ordered->setDouble(invcitem.value("invcitem_ordered").toDouble());
    _billed->setDouble(invcitem.value("invcitem_billed").toDouble());

    // TODO: why not setChecked then call sHandleUpdateInv
    if ( (invcitem.value("invcitem_coitem_id").toInt() > 0) ||
         (invcitem.value("itemsite_costmethod").toString() == "J") ||
         (invcitem.value("invcitem_item_id").toInt() == -1) )
    {
      _updateInv->setChecked(false);
      _updateInv->setEnabled(false);
    }
    else
    {
      _updateInv->setChecked(invcitem.value("invcitem_updateinv").toBool());
      _updateInv->setEnabled(true);
    }
    _price->setLocalValue(invcitem.value("invcitem_price").toDouble());
    _custPrice->setLocalValue(invcitem.value("invcitem_custprice").toDouble());
    _listPrice->setBaseValue(invcitem.value("f_listprice").toDouble() * (_priceinvuomratio / _priceRatioCache));

    _custPn->setText(invcitem.value("invcitem_custpn").toString());
    _notes->setText(invcitem.value("invcitem_notes").toString());
  }
  else if (invcitem.lastError().type() != QSqlError::NoError)
  {
    systemError(this, invcitem.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  invcitem.prepare( "SELECT SUM(COALESCE(taxhist_tax, 0.00)) AS lineTaxTotal "
                    "FROM invcitem LEFT OUTER JOIN invcitemtax "
                    "  ON (invcitem_id = taxhist_parent_id) "
                    "WHERE invcitem_id = :invcitem_id;" );
  invcitem.bindValue(":invcitem_id", _invcitemid);
  invcitem.exec();
  if (invcitem.first())
    _tax->setLocalValue(invcitem.value("lineTaxTotal").toDouble());
  else if (invcitem.lastError().type() != QSqlError::NoError)
  {
    systemError(this, invcitem.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  sCalculateExtendedPrice();

  _saved = true;
  emit populated();
}
コード例 #21
0
enum SetResponse shipTo::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("cust_id", &valid);
  if (valid)
    _custid = param.toInt();

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

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

      XSqlQuery cust;
      cust.prepare( "SELECT cust_number, cust_name, cust_taxauth_id, "
                 "       cust_salesrep_id, cust_shipform_id, cust_shipvia "
                 "FROM custinfo "
                 "WHERE (cust_id=:cust_id);" );
      cust.bindValue(":cust_id", _custid);
      cust.exec();
      if (cust.first())
      {
        _custNum->setText(cust.value("cust_number").toString());
        _custName->setText(cust.value("cust_name").toString());
        _salesRep->setId(cust.value("cust_salesrep_id").toInt());
        _shipform->setId(cust.value("cust_shipform_id").toInt());
        _taxauth->setId(cust.value("cust_taxauth_id").toInt());

	//  Handle the free-form Ship Via
        _shipVia->setId(-1);
        QString shipvia = cust.value("cust_shipvia").toString().stripWhiteSpace();
        if (shipvia.length())
        {
          for (int counter = 0; counter < _shipVia->count(); counter++)
            if (_shipVia->text(counter) == shipvia)
              _shipVia->setCurrentItem(counter);

          if (_shipVia->id() == -1)
          {
            _shipVia->insertItem(shipvia);
            _shipVia->setCurrentItem(_shipVia->count() - 1);
          }
        }
      }
      if (cust.lastError().type() != QSqlError::None)
      {
	systemError(this, cust.lastError().databaseText(), __FILE__, __LINE__);
	return UndefinedError;
      }

      _shipToNumber->setFocus();
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;
      _shipToNumber->setEnabled(FALSE);
      _save->setFocus();
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _shipToNumber->setEnabled(FALSE);
      _active->setEnabled(FALSE);
      _default->setEnabled(FALSE);
      _name->setEnabled(FALSE);
      _contact->setEnabled(FALSE);
      _address->setEnabled(FALSE);
      _salesRep->setEnabled(FALSE);
      _commission->setEnabled(FALSE);
      _shipZone->setEnabled(FALSE);
      _taxauth->setEnabled(FALSE);
      _shipVia->setEnabled(FALSE);
      _shipform->setEnabled(FALSE);
      _shipchrg->setEnabled(FALSE);
      _ediProfile->setEnabled(FALSE);
      _comments->setEnabled(FALSE);
      _shippingComments->setEnabled(FALSE);
      _close->setText(tr("&Close"));
      _save->hide();

      _close->setFocus();
    }
  }

  return NoError;
}
コード例 #22
0
void invoiceItem::sPopulateItemInfo(int pItemid)
{
  XSqlQuery invoicePopulateItemInfo;
  if ( (_itemSelected->isChecked()) && (pItemid != -1) )
  {
    XSqlQuery uom;
    uom.prepare("SELECT uom_id, uom_name"
                "  FROM item"
                "  JOIN uom ON (item_inv_uom_id=uom_id)"
                " WHERE(item_id=:item_id)"
                " UNION "
                "SELECT uom_id, uom_name"
                "  FROM item"
                "  JOIN itemuomconv ON (itemuomconv_item_id=item_id)"
                "  JOIN uom ON (itemuomconv_to_uom_id=uom_id)"
                " WHERE((itemuomconv_from_uom_id=item_inv_uom_id)"
                "   AND (item_id=:item_id))"
                " UNION "
                "SELECT uom_id, uom_name"
                "  FROM item"
                "  JOIN itemuomconv ON (itemuomconv_item_id=item_id)"
                "  JOIN uom ON (itemuomconv_from_uom_id=uom_id)"
                " WHERE((itemuomconv_to_uom_id=item_inv_uom_id)"
                "   AND (item_id=:item_id))"
                " ORDER BY uom_name;");
    uom.bindValue(":item_id", _item->id());
    uom.exec();
    _qtyUOM->populate(uom);
    _pricingUOM->populate(uom);

    invoicePopulateItemInfo.prepare( "SELECT item_inv_uom_id, item_price_uom_id,"
               "       iteminvpricerat(item_id) AS invpricerat,"
               "       item_listprice, item_fractional, "
               "       stdcost(item_id) AS f_unitcost,"
               "       getItemTaxType(item_id, :taxzone) AS taxtype_id,"
               "       itemsite_costmethod"
               "  FROM item"
               "  JOIN itemsite ON (item_id=itemsite_item_id)"
               " WHERE ((item_id=:item_id)"
               "    AND (itemsite_warehous_id=:whsid));" );
    invoicePopulateItemInfo.bindValue(":item_id", pItemid);
    invoicePopulateItemInfo.bindValue(":taxzone", _taxzoneid);
    invoicePopulateItemInfo.bindValue(":whsid",   _warehouse->id());
    invoicePopulateItemInfo.exec();
    if (invoicePopulateItemInfo.first())
    {
      _priceRatioCache = invoicePopulateItemInfo.value("invpricerat").toDouble();
      _listPrice->setBaseValue(invoicePopulateItemInfo.value("item_listprice").toDouble());

      _invuomid = invoicePopulateItemInfo.value("item_inv_uom_id").toInt();
      _qtyUOM->setId(invoicePopulateItemInfo.value("item_inv_uom_id").toInt());
      _pricingUOM->setId(invoicePopulateItemInfo.value("item_price_uom_id").toInt());
      _qtyinvuomratio = 1.0;
      _priceinvuomratio = invoicePopulateItemInfo.value("invpricerat").toDouble();
      _unitCost->setBaseValue(invoicePopulateItemInfo.value("f_unitcost").toDouble());
      _taxtype->setId(invoicePopulateItemInfo.value("taxtype_id").toInt());
      if (invoicePopulateItemInfo.value("item_fractional").toBool())
      {
        _ordered->setValidator(omfgThis->qtyVal());
        _billed->setValidator(omfgThis->qtyVal());
      }
      else
      {
        _ordered->setValidator(new XDoubleValidator(0, 999999, 0, this));
        _billed->setValidator(new XDoubleValidator(0, 999999, 0, this));
      }
      sDeterminePrice();

      // TODO: should this check itemsite_controlmethod == N?
      _trackqoh = (invoicePopulateItemInfo.value("itemsite_costmethod").toString() != "J");
    }
    else if (invoicePopulateItemInfo.lastError().type() != QSqlError::NoError)
    {
      systemError(this, invoicePopulateItemInfo.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
  else
  {
    _priceRatioCache = 1.0;
    _qtyinvuomratio = 1.0;
    _priceinvuomratio = 1.0;
    _qtyUOM->clear();
    _pricingUOM->clear();
    _listPrice->clear();
    _unitCost->clear();
  }
}
コード例 #23
0
/*
    Make sure the row is internally consistent. If so then fix it so the
    parent class has a valid row to insert (some of the SELECTed columns
    shouldn't be directly modified in the db 'cause they're not part of the
    model's current table).
*/
bool PoitemTableModel::validRow(QSqlRecord& record)
{
  QString errormsg;
  QString warningmsg;

  // TODO: what is a better way to decide if this is an inventory item or not?
  bool inventoryItem = ! record.value("item_number").toString().isEmpty();

  if (! inventoryItem &&
      record.value("poitem_expcat_id").toInt() < 0)
    errormsg = tr("<p>You must specify an Expense Category for this "
		  "non-Inventory Item before you may save it.");

  else if (inventoryItem &&
	   record.value("item_number").toString().isEmpty())
    errormsg = tr("<p>You must select an Item Number before you may save.");

  else if (inventoryItem &&
	   record.value("warehous_id").toInt() <= 0)
    errormsg = tr("<p>You must select a Supplying Site before you may save.");

  else if (record.value("poitem_qty_ordered").toDouble() <= 0)
    errormsg = tr("<p>You must enter a quantity before you may save this "
		  "Purchase Order Item.");

  else if (record.value("itemsrc_minordqty").toDouble() > 0 &&
	   record.value("poitem_qty_ordered").toDouble() < record.value("itemsrc_minordqty").toDouble())
    warningmsg = tr("<p>The quantity that you are ordering is below the "
		    "Minimum Order Quantity for this Item Source.  You may "
		    "continue but this Vendor may not honor pricing or "
		    "delivery quotations. ");

  else if (record.value("itemsrc_multordqty").toDouble() > 0 &&
	   record.value("poitem_qty_ordered").toInt() % (int)(record.value("itemsrc_multordqty").toDouble()))
    warningmsg = tr("<p>The quantity that you are ordering does not fall "
		    "within the Order Multiple for this Item Source.  You may "
		    "continue but this Vendor may not honor pricing or "
		    "delivery quotations.");

  else if (! record.value("poitem_duedate").toDate().isValid())
    errormsg = tr("<p>You must enter a due date.");

  else if (record.value("earliestDate").toDate().isValid() &&
	   record.value("poitem_duedate").toDate() < record.value("earliestDate").toDate())
    warningmsg = tr("<p>The Due Date that you are requesting does not fall "
		    "within the Lead Time Days for this Item Source.  You may "
		    "continue but this Vendor may not honor pricing or "
		    "delivery quotations or may not be able to deliver by the "
		    "requested Due Date.");

  else if (record.value("poitem_pohead_id").toInt() <= 0 &&
	   _poheadid <= 0)
    errormsg = tr("<p>There is no Purchase Order header yet. "
	     "Try entering a Vendor if you are using the Purchase Order "
	     "window.");

  else if (inventoryItem &&
	   record.value("item_id").toInt() > 0 &&
	   record.value("warehous_id").toInt() > 0)
  {
    XSqlQuery isq;
    isq.prepare("SELECT itemsite_id, item_id "
		"FROM itemsite, item "
		"WHERE ((itemsite_item_id=item_id)"
		"  AND  (itemsite_warehous_id=:whs_id)"
		"  AND  (item_id=:item_id));");
    isq.bindValue(":whs_id", record.value("warehous_id").toInt());
    isq.bindValue(":item_id", record.value("item_id").toInt());
    isq.exec();
    if (isq.first())
    {
      int itemsiteid = isq.value("itemsite_id").toInt();
      if (itemsiteid != record.value("poitem_itemsite_id").toInt())
	record.setValue("poitem_itemsite_id", itemsiteid);
    }
    else if (isq.lastError().type() != QSqlError::NoError)
      errormsg = isq.lastError().databaseText();
    else
      errormsg = tr("<p>There is no Item Site for this Site (%1) and "
	       "Item Number (%2).")
	       .arg(record.value("warehous_code").toInt())
	       .arg(record.value("item_number").toString());
  }

  int index = record.indexOf("poitem_pohead_id");
  if (index < 0)
  {
    QSqlField field("poitem_pohead_id", QVariant::Int);
    field.setValue(_poheadid);
    record.append(field);
  }
  else
    record.setValue(index, _poheadid);

  XSqlQuery ln;
  /*
  ln.prepare("SELECT MAX(poitem_linenumber) + 1 AS newln "
	     "FROM poitem "
	     "WHERE (poitem_pohead_id=:pohead_id);");
             */
  // get the smallest available line number
  ln.prepare("SELECT MIN(sequence_value) AS newln "
             "FROM sequence "
             "WHERE sequence_value NOT IN (SELECT poitem_linenumber "
             "                             FROM poitem"
             "                             WHERE (poitem_pohead_id=:pohead_id));");
  ln.bindValue(":pohead_id", _poheadid);
  if (record.indexOf("poitem_linenumber") < 0)
  {
    ln.exec();
    if (ln.first())
    {
      QSqlField field("poitem_linenumber", QVariant::Int);
      field.setValue(ln.value("newln"));
      record.append(field);
    }
    else if (ln.lastError().type() != QSqlError::NoError)
    {
      errormsg = ln.lastError().databaseText();
    }
  }
  else if (record.value("poitem_linenumber").toInt() <= 0)
  {
    ln.exec();
    if (ln.first())
      record.setValue("poitem_linenumber", ln.value("newln"));
    else if (ln.lastError().type() != QSqlError::NoError)
    {
      errormsg = ln.lastError().databaseText();
    }
  }

  if (record.value("poitem_id").isNull())
  {
    XSqlQuery idq("SELECT NEXTVAL('poitem_poitem_id_seq') AS poitem_id;");
    if (idq.first())
      record.setValue("poitem_id", idq.value("poitem_id"));
    else
    {
      errormsg = idq.lastError().databaseText();
    }
  }

  if (_postatus.isEmpty())
    findHeadData();

  index = record.indexOf("poitem_status");
  if (index < 0)
  {
    QSqlField field("poitem_status", QVariant::String);
    field.setValue(_postatus);
    record.append(field);
  }
  else if (record.field(index).value().toString().isEmpty())
    record.setValue(index, _postatus);

  if (record.field("poitem_invvenduomratio").value().isNull() &&
      record.field("itemsrc_invvendoruomratio").value().isNull())
    record.setValue("poitem_invvenduomratio", 1);
  else if (record.field("poitem_invvenduomratio").value().isNull())
    record.setValue("poitem_invvenduomratio", record.value("itemsrc_invvendoruomratio"));

  if (! errormsg.isEmpty())
  {
    setLastError(QSqlError(QString("PoitemTableModel::validRow() error"),
			   errormsg, QSqlError::UnknownError));
    return false;
  }
  else if (! warningmsg.isEmpty())
  {
    if (QMessageBox::question(0, tr("Are you sure you want to continue?"),
		    warningmsg + tr("<p>Do you wish to Save this Order?"),
		    QMessageBox::Yes,
		    QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
    return false;
  }

  record.remove(record.indexOf("earliestdate"));
  record.remove(record.indexOf("itemsrc_invvendoruomratio"));
  record.remove(record.indexOf("itemsrc_multordqty"));
  record.remove(record.indexOf("itemsrc_minordqty"));
  record.remove(record.indexOf("expcat_code"));
  record.remove(record.indexOf("prj_number"));
  record.remove(record.indexOf("extprice"));
  record.remove(record.indexOf("warehous_code"));
  record.remove(record.indexOf("warehous_id"));
  record.remove(record.indexOf("item_number"));
  record.remove(record.indexOf("item_id"));
  record.remove(record.indexOf("pohead_number"));

  return true;
}
コード例 #24
0
enum SetResponse invoiceItem::set(const ParameterList &pParams)
{
  XSqlQuery invoiceet;
  XDialog::set(pParams);
  QVariant param;
  bool     valid;

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

    invoiceet.prepare("SELECT * "
                      "FROM invchead "
			  "WHERE (invchead_id = :invchead_id);");
    invoiceet.bindValue(":invchead_id", _invcheadid);
    invoiceet.exec();
    if (invoiceet.first())
    {
      _invoiceNumber->setText(invoiceet.value("invchead_invcnumber").toString());
      _custid = invoiceet.value("invchead_cust_id").toInt();
      _taxzoneid = invoiceet.value("invchead_taxzone_id").toInt();
      _tax->setId(invoiceet.value("invchead_curr_id").toInt());
      _price->setId(invoiceet.value("invchead_curr_id").toInt());
      _price->setEffective(invoiceet.value("invchead_invcdate").toDate());
      sPriceGroup();
    }
    else if (invoiceet.lastError().type() != QSqlError::NoError)
    {
      systemError(this, invoiceet.lastError().databaseText(), __FILE__, __LINE__);
      return UndefinedError;
    }
  }

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

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

      invoiceet.exec("SELECT NEXTVAL('invcitem_invcitem_id_seq') AS invcitem_id;");
      if (invoiceet.first())
        _invcitemid = invoiceet.value("invcitem_id").toInt();
      else if (invoiceet.lastError().type() != QSqlError::NoError)
      {
            systemError(this, invoiceet.lastError().databaseText(), __FILE__, __LINE__);
            return UndefinedError;
      }

      invoiceet.prepare( "SELECT (COALESCE(MAX(invcitem_linenumber), 0) + 1) AS linenumber "
                         "FROM invcitem "
                         "WHERE (invcitem_invchead_id=:invchead_id);" );
      invoiceet.bindValue(":invchead_id", _invcheadid);
      invoiceet.exec();
      if (invoiceet.first())
        _lineNumber->setText(invoiceet.value("linenumber").toString());
      else if (invoiceet.lastError().type() != QSqlError::NoError)
      {
	    systemError(this, invoiceet.lastError().databaseText(), __FILE__, __LINE__);
	    return UndefinedError;
      }

      connect(_billed, SIGNAL(editingFinished()), this, SLOT(sDeterminePrice()));
      connect(_billed, SIGNAL(editingFinished()), this, SLOT(sCalculateExtendedPrice()));
      connect(_price, SIGNAL(editingFinished()), this, SLOT(sCalculateExtendedPrice()));
      _item->setType(ItemLineEdit::cSold);
      _salescat->setType(XComboBox::SalesCategoriesActive);
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;

      connect(_billed, SIGNAL(editingFinished()), this, SLOT(sDeterminePrice()));
      connect(_billed, SIGNAL(editingFinished()), this, SLOT(sCalculateExtendedPrice()));
      connect(_price, SIGNAL(editingFinished()), this, SLOT(sCalculateExtendedPrice()));
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _itemTypeGroup->setEnabled(FALSE);
      _custPn->setEnabled(FALSE);
      _ordered->setEnabled(FALSE);
      _billed->setEnabled(FALSE);
      _price->setEnabled(FALSE);
      _notes->setReadOnly(TRUE);
      _taxtype->setEnabled(false);
      _altRevAccnt->setEnabled(false);
      _qtyUOM->setEnabled(false);
      _pricingUOM->setEnabled(false);

      _save->hide();
      _close->setText(tr("&Cancel"));
    }
  }

  return NoError;
}
コード例 #25
0
void booItem::populate()
{
  XSqlQuery booitem;
  booitem.prepare( "SELECT item_config,"
                   "       booitem_effective, booitem_expires,"
                   "       booitem_execday, booitem_item_id, booitem_seqnumber,"
                   "       booitem_wrkcnt_id, booitem_stdopn_id,"
                   "       booitem_descrip1, booitem_descrip2, booitem_toolref,"
                   "       booitem_sutime, booitem_sucosttype, booitem_surpt,"
                   "       booitem_rntime, booitem_rncosttype, booitem_rnrpt,"
                   "       booitem_produom, uom_name,"
                   "       booitem_invproduomratio,"
                   "       booitem_rnqtyper,"
                   "       booitem_issuecomp, booitem_rcvinv,"
                   "       booitem_pullthrough, booitem_overlap,"
                   "       booitem_configtype, booitem_configid, booitem_configflag,"
                   "       booitem_instruc, booitem_wip_location_id "
                   "FROM booitem, item, uom "
                   "WHERE ( (booitem_item_id=item_id)"
                   " AND (item_inv_uom_id=uom_id)"
                   " AND (booitem_id=:booitem_id) );" );
  booitem.bindValue(":booitem_id", _booitemid);
  booitem.exec();
  if (booitem.first())
  {
    _stdopn->setId(booitem.value("booitem_stdopn_id").toInt());
    if (booitem.value("booitem_stdopn_id").toInt() != -1)
    {
      _description1->setEnabled(FALSE);
      _description2->setEnabled(FALSE);
      _instructions->setEnabled(FALSE);
    }

    _dates->setStartDate(booitem.value("booitem_effective").toDate());
    _dates->setEndDate(booitem.value("booitem_expires").toDate());
    _executionDay->setValue(booitem.value("booitem_execday").toInt());
    _operSeqNum->setText(booitem.value("booitem_seqnumber").toString());
    _description1->setText(booitem.value("booitem_descrip1"));
    _description2->setText(booitem.value("booitem_descrip2"));
    _toolingReference->setText(booitem.value("booitem_toolref"));
    _setupTime->setDouble(booitem.value("booitem_sutime").toDouble());
    _prodUOM->setText(booitem.value("booitem_produom"));
    _invUOM1->setText(booitem.value("uom_name").toString());
    _invUOM2->setText(booitem.value("uom_name").toString());
    _invProdUOMRatio->setDouble(booitem.value("booitem_invproduomratio").toDouble());
    _runTime->setDouble(booitem.value("booitem_rntime").toDouble());
    _runTimePer->setDouble(booitem.value("booitem_rnqtyper").toDouble());

    _reportSetup->setChecked(booitem.value("booitem_surpt").toBool());
    _reportRun->setChecked(booitem.value("booitem_rnrpt").toBool());
    _issueComp->setChecked(booitem.value("booitem_issuecomp").toBool());
    _receiveStock->setChecked(booitem.value("booitem_rcvinv").toBool());
    _overlap->setChecked(booitem.value("booitem_overlap").toBool());
    _pullThrough->setChecked(booitem.value("booitem_pullthrough").toBool());
    _instructions->setText(booitem.value("booitem_instruc").toString());
    _wrkcnt->setId(booitem.value("booitem_wrkcnt_id").toInt());
    _wipLocation->setId(booitem.value("booitem_wip_location_id").toInt());

    if (booitem.value("booitem_sucosttype").toString() == "D")
      _setupReport->setCurrentIndex(0);
    else if (booitem.value("booitem_sucosttype").toString() == "O")
      _setupReport->setCurrentIndex(1);
    else if (booitem.value("booitem_sucosttype").toString() == "N")
      _setupReport->setCurrentIndex(2);

    if (booitem.value("booitem_rncosttype").toString() == "D")
      _runReport->setCurrentIndex(0);
    else if (booitem.value("booitem_rncosttype").toString() == "O")
      _runReport->setCurrentIndex(1);
    else if (booitem.value("booitem_rncosttype").toString() == "N")
      _runReport->setCurrentIndex(2);

    _item->setId(booitem.value("booitem_item_id").toInt());
	if (_item->itemType() == "J")
	{
      _receiveStock->setEnabled(FALSE);
	  _receiveStock->setChecked(FALSE);
	}

    sCalculateInvRunTime();
    sFillImageList();
  }
  else if (booitem.lastError().type() != QSqlError::NoError)
  {
    systemError(this, booitem.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
コード例 #26
0
void returnAuthorizationWorkbench::sProcess()
{
  XSqlQuery returnProcess;
  if (!checkSitePrivs(_radue->id()))
    return;
  
  bool _post = ((_radue->altId() > 1) ||
		(_radue->altId() == 1 && _postmemos->isChecked())) ;

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

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

        returnAuthCheck newdlg(this, "", TRUE);
        newdlg.set(params);
        if (newdlg.exec() != XDialog::Rejected)
          sFillListDue();
      }
      else if (_radue->altId() == 3)
      {
	ParameterList ccp;
	ccp.append("cmhead_id", cmheadid);
  MetaSQLQuery ccm = mqlLoad("creditMemoCreditCards", "detail");
	XSqlQuery ccq = ccm.toQuery(ccp);
	if (ccq.first())
	{
	  int ccpayid = ccq.value("ccpay_id").toInt();
	  CreditCardProcessor *cardproc = CreditCardProcessor::getProcessor();
	  if (! cardproc)
	    QMessageBox::critical(this, tr("Credit Card Processing Error"),
				  CreditCardProcessor::errorMsg());
	  else if (! cardproc->errorMsg().isEmpty())
	    QMessageBox::critical(this, tr("Credit Card Processing Warning"),
				 cardproc->errorMsg());
	  else
	  {
	    QString docnum = returnProcess.value("cmhead_number").toString();
	    QString refnum = ccq.value("cohead_number").toString();
	    int refid = -1;
	    int returnValue = cardproc->credit(ccq.value("ccard_id").toInt(),
					 "-2",
					 ccq.value("total").toDouble(),
					 ccq.value("tax_in_cmcurr").toDouble(),
					 ccq.value("cmhead_tax_id").isNull(),
					 ccq.value("cmhead_freight").toDouble(),
					 0,
					 ccq.value("cmhead_curr_id").toInt(),
					 docnum, refnum, ccpayid,
					 QString(), refid);
	    if (returnValue < 0)
	      QMessageBox::critical(this, tr("Credit Card Processing Error"),
				    cardproc->errorMsg());
	    else if (returnValue > 0)
	      QMessageBox::warning(this, tr("Credit Card Processing Warning"),
				   cardproc->errorMsg());
	    else if (! cardproc->errorMsg().isEmpty())
	      QMessageBox::information(this, tr("Credit Card Processing Note"),
				   cardproc->errorMsg());
	  }
	  // requery regardless 'cause the new return means nothing's "due"
	  sFillListDue();
	}
	else if (ccq.lastError().type() != QSqlError::NoError)
	{
	  systemError(this, ccq.lastError().databaseText(), __FILE__, __LINE__);
	  return;
	}
	else
	{
	  QMessageBox::critical(this, tr("Credit Card Processing Error"),
				tr("Could not find a Credit Card to use for "
				   "this Credit transaction."));
	  sFillListDue();
	  return;
	}
      }
      else
	sFillListDue();
    }
    else if (returnProcess.lastError().type() != QSqlError::NoError)
    {
      systemError(this, returnProcess.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
  else if (returnProcess.lastError().type() != QSqlError::NoError)
  {
    systemError(this, returnProcess.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
コード例 #27
0
ファイル: reportwindow.cpp プロジェクト: Wushaowei001/xtuple
bool ReportWindow::saveToDb() {
    // do what we need to do
    DBFileDialog rptDiag;
    rptDiag.setCaption(tr("Save Report to Database"));
    if(!dbRecordName.isEmpty()) {
        rptDiag._name->setText(dbRecordName);
    } else {
        rptDiag._name->setText(reportName());
    }
    rptDiag._grade->setValue(dbRecordGrade);
    if(rptDiag.exec() == QDialog::Accepted) {
        QString name = rptDiag.getName();
        QString desc = reportDescription();
        QString src  = document().toString();
        int grade = rptDiag.getGrade();

        XSqlQuery q;
        XSqlQuery qry;

        q.prepare("SELECT report_id "
                  "  FROM report "
                  " WHERE ((report_name=:report_name) "
                  "   AND (report_grade=:report_grade)); ");
        q.bindValue(":report_name", name);
        q.bindValue(":report_grade", grade);
        q.exec();
        if(q.first()) {
            // update old record
            qry.prepare("UPDATE report "
                        "   SET report_source=:report_source, "
                        "       report_descrip=:report_descrip "
                        " WHERE (report_id=:report_id);");
            qry.bindValue(":report_source", src);
            qry.bindValue(":report_descrip", desc);
            qry.bindValue(":report_id", q.value("report_id").toInt());
        } else {
            // insert new record
            qry.prepare("INSERT INTO report "
                        "       (report_name, report_source, report_descrip, report_grade) "
                        "VALUES (:report_name, :report_source, :report_descrip, :report_grade);");
            qry.bindValue(":report_name", name);
            qry.bindValue(":report_source", src);
            qry.bindValue(":report_descrip", desc);
            qry.bindValue(":report_grade", grade);
        }

        if(qry.exec()) {
            lastSaveToDb = TRUE;
            setModified(FALSE);
            dbRecordName = name;
            dbRecordGrade = grade;
            if(_handler)
            {
              q.exec();
              if(q.first())
                _handler->sReportsChanged(q.value("report_id").toInt(), true);
              else
                _handler->sReportsChanged(-1, true);
            }
            return TRUE;
        } else {
            // no good lets tell the user
	          QSqlError sqlErr = qry.lastError();   
            QMessageBox::critical(this,tr("Error saving to database"),sqlErr.databaseText());
        }
    }
    return FALSE;   
}
コード例 #28
0
void unpostedPoReceipts::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privileges->check("ChangePORecvPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Receipt Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE recv SET recv_gldistdate=:distdate "
		  "WHERE recv_id=:recv_id;");

  QList<XTreeWidgetItem*>selected = _recv->selectedItems();
  QList<XTreeWidgetItem*>triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    int id = ((XTreeWidgetItem*)(selected[i]))->id();

    if (changeDate)
    {
      setDate.bindValue(":distdate",  newDate);
      setDate.bindValue(":recv_id", id);
      setDate.exec();
      if (setDate.lastError().type() != QSqlError::NoError)
      {
        systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
      }
    }
  }
  
  XSqlQuery postLine;
  postLine.prepare("SELECT postReceipt(:id, NULL::integer) AS result;");
  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      q.exec("BEGIN;");
      postLine.bindValue(":id", id);
      postLine.exec();
      if (postLine.first())
      {
        int result = postLine.value("result").toInt();
        if (result < 0)
        {
          rollback.exec();
          systemError(this, storedProcErrorLookup("postReceipt", result),
              __FILE__, __LINE__);
          continue;
        }

        if (distributeInventory::SeriesAdjust(result, this) == XDialog::Rejected)
        {
          QMessageBox::information( this, tr("Unposted Receipts"), tr("Post Canceled") );
          rollback.exec();
          return;
        }
        q.exec("COMMIT;");
         
      }
      // contains() string is hard-coded in stored procedure
      else if (postLine.lastError().databaseText().contains("posted to closed period"))
      {
        if (changeDate)
        {
          triedToClosed = selected;
          break;
        }
        else
          triedToClosed.append(selected[i]);
      }
      else if (postLine.lastError().type() != QSqlError::NoError)
      {
        rollback.exec();
        systemError(this, postLine.lastError().databaseText(), __FILE__, __LINE__);
      }
    } // for each selected line

    if (triedToClosed.size() > 0)
    {
      failedPostList newdlg(this, "", true);
      newdlg.sSetList(triedToClosed, _recv->headerItem(), _recv->header());
      tryagain = (newdlg.exec() == XDialog::Accepted);
      selected = triedToClosed;
      triedToClosed.clear();
    }
  } while (tryagain);

  omfgThis->sPurchaseOrderReceiptsUpdated();
}
コード例 #29
0
ファイル: itemSource.cpp プロジェクト: AlFoX/qt-client
bool itemSource::sSave()
{
  XSqlQuery itemSave;

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

  /* TODO - need this?
  itemSave.prepare( "SELECT count(*) AS numberOfOverlaps "
                    "FROM itemsrc "
                    "WHERE (itemsrc_item_id = :itemsrc_item_id)"
                    "  AND (itemsrc_vend_id = :itemsrc_vend_id)"
                    "  AND (itemsrc_id != :itemsrc_id)"
                    "  AND ( (itemsrc_effective BETWEEN :itemsrc_effective AND :itemsrc_expires OR"
                    "         itemsrc_expires BETWEEN :itemsrc_effective AND :itemsrc_expires)"
                    "   OR   (itemsrc_effective <= :itemsrc_effective AND"
                    "         itemsrc_expires   >= :itemsrc_expires) );" );
  itemSave.bindValue(":itemsrc_id", _itemsrcid);
  itemSave.bindValue(":itemsrc_item_id", _item->id());
  itemSave.bindValue(":itemsrc_vend_id", _vendor->id());
  itemSave.bindValue(":itemsrc_effective", _dates->startDate());
  itemSave.bindValue(":itemsrc_expires", _dates->endDate());
  itemSave.exec();
  if (itemSave.first())
  {
    if (itemSave.value("numberOfOverlaps").toInt() > 0)
    {
      errors << GuiErrorCheck(true, _dates,
                              tr("The date range overlaps with another date range.\n"
                                 "Please check the values of these dates."));
    }
  }
  else if (itemSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, itemSave.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }
  */

  if(_mode == cNew || _mode == cCopy)
  {
    itemSave.prepare( "SELECT itemsrc_id "
                      "  FROM itemsrc "
                      " WHERE ((itemsrc_item_id=:item_id) "
                      "   AND (itemsrc_vend_id=:vend_id) "
                      "   AND (itemsrc_vend_item_number=:itemsrc_vend_item_number) "
                      "   AND (UPPER(itemsrc_manuf_name)=UPPER(:itemsrc_manuf_name)) "
                      "   AND (UPPER(itemsrc_manuf_item_number)=UPPER(:itemsrc_manuf_item_number)) ) ");
    itemSave.bindValue(":item_id", _item->id());
    itemSave.bindValue(":vend_id", _vendor->id());
    itemSave.bindValue(":itemsrc_vend_item_number", _vendorItemNumber->text());
    itemSave.bindValue(":itemsrc_manuf_name", _manufName->currentText());
    itemSave.bindValue(":itemsrc_manuf_item_number", _manufItemNumber->text());
    itemSave.exec();
    if(itemSave.first())
    {
      errors << GuiErrorCheck(true, _item,
                              tr("An Item Source already exists for the Item Number, Vendor,\n"
                                 "Vendor Item, Manfacturer Name and Manufacturer Item Number you have specified."));
    }
    else if (itemSave.lastError().type() != QSqlError::NoError)
    {
      systemError(this, itemSave.lastError().databaseText(), __FILE__, __LINE__);
      return false;
    }
  }
  
  if(_active->isChecked())
  {
    itemSave.prepare("SELECT item_id "
                     "FROM item "
                     "WHERE ((item_id=:item_id)"
                     "  AND  (item_active)) "
                     "LIMIT 1; ");
    itemSave.bindValue(":item_id", _item->id());
    itemSave.exec();
    if (!itemSave.first())         
    { 
      errors << GuiErrorCheck(true, _active,
                              tr("This Item Source refers to an inactive Item and must be marked as inactive.") );
    }
  }
    
  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Item Source"), errors))
    return false;

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

  itemSave.bindValue(":itemsrc_id", _itemsrcid);
  itemSave.bindValue(":itemsrc_item_id", _item->id());
  itemSave.bindValue(":itemsrc_active", QVariant(_active->isChecked()));
  itemSave.bindValue(":itemsrc_default", QVariant(_default->isChecked()));
  itemSave.bindValue(":itemsrc_vend_id", _vendor->id());
  if (_contract->isValid())
    itemSave.bindValue(":itemsrc_contrct_id", _contract->id());
  itemSave.bindValue(":itemsrc_effective", _dates->startDate());
  itemSave.bindValue(":itemsrc_expires", _dates->endDate());
  itemSave.bindValue(":itemsrc_vend_item_number", _vendorItemNumber->text());
  itemSave.bindValue(":itemsrc_vend_item_descrip", _vendorItemDescrip->toPlainText());
  itemSave.bindValue(":itemsrc_vend_uom", _vendorUOM->currentText());
  itemSave.bindValue(":itemsrc_invvendoruomratio", _invVendorUOMRatio->toDouble());
  itemSave.bindValue(":itemsrc_upccode", _upcCode->text());
  itemSave.bindValue(":itemsrc_minordqty", _minOrderQty->toDouble());
  itemSave.bindValue(":itemsrc_multordqty", _multOrderQty->toDouble());
  itemSave.bindValue(":itemsrc_leadtime", _leadTime->text().toInt());
  itemSave.bindValue(":itemsrc_ranking", _vendorRanking->value());
  itemSave.bindValue(":itemsrc_comments", _notes->toPlainText().trimmed());
  itemSave.bindValue(":itemsrc_manuf_name", _manufName->currentText());
  itemSave.bindValue(":itemsrc_manuf_item_number", _manufItemNumber->text());
  itemSave.bindValue(":itemsrc_manuf_item_descrip", _manufItemDescrip->toPlainText());
  itemSave.exec();
  if (itemSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, itemSave.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  if (_captive)
  {
    if (_mode != cCopy)
    {
      _vendor->setEnabled(FALSE);
    }
    _mode = cEdit;
    _item->setReadOnly(TRUE);
    _captive = false;
  }
  else
    done(_itemsrcid);
    
  return true;
}
コード例 #30
0
void unpostedInvoices::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privileges->check("ChangeARInvcDistDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Invoice Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  int journal = -1;
  q.exec("SELECT fetchJournalNumber('AR-IN') AS result;");
  if (q.first())
  {
    journal = q.value("result").toInt();
    if (journal < 0)
    {
      systemError(this, storedProcErrorLookup("fetchJournalNumber", journal), __FILE__, __LINE__);
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  XSqlQuery xrate;
  xrate.prepare("SELECT curr_rate "
		"FROM curr_rate, invchead "
		"WHERE ((curr_id=invchead_curr_id)"
		"  AND  (invchead_id=:invchead_id)"
		"  AND  (invchead_invcdate BETWEEN curr_effective AND curr_expires));");
  // if SUM becomes dependent on curr_id then move XRATE before it in the loop
  XSqlQuery sum;
  sum.prepare("SELECT COALESCE(SUM(round((invcitem_billed * invcitem_qty_invuomratio) *"
	      "                 (invcitem_price / "
	      "                  CASE WHEN (item_id IS NULL) THEN 1"
	      "                       ELSE invcitem_price_invuomratio"
	      "                  END), 2)),0) + "
	      "       invchead_freight + invchead_tax + "
	      "       invchead_misc_amount AS subtotal "
	      "  FROM invchead LEFT OUTER JOIN invcitem ON (invcitem_invchead_id=invchead_id) LEFT OUTER JOIN"
	      "       item ON (invcitem_item_id=item_id) "
	      " WHERE(invchead_id=:invchead_id) "
	      " GROUP BY invchead_freight, invchead_tax, invchead_misc_amount;");

  XSqlQuery post;
  post.prepare("SELECT postInvoice(:invchead_id, :journal) AS result;");

  XSqlQuery setDate;
  setDate.prepare("UPDATE invchead SET invchead_gldistdate=:distdate "
		  "WHERE invchead_id=:invchead_id;");

  QList<QTreeWidgetItem *> selected = _invchead->selectedItems();
  QList<QTreeWidgetItem *> triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
	{
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      if (changeDate)
      {
        setDate.bindValue(":distdate",    newDate);
        setDate.bindValue(":invchead_id", id);
        setDate.exec();
        if (setDate.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
        }
      }
	}
  }

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      if (checkSitePrivs(((XTreeWidgetItem*)(selected[i]))->id()))
	  {
        int id = ((XTreeWidgetItem*)(selected[i]))->id();

        sum.bindValue(":invchead_id", id);
        if (sum.exec() && sum.first() && sum.value("subtotal").toDouble() == 0)
        {
	      if (QMessageBox::question(this, tr("Invoice Has Value 0"),
		      		  tr("Invoice #%1 has a total value of 0.\n"
			     	     "Would you like to post it anyway?")
				    .arg(selected[i]->text(0)),
				  QMessageBox::Yes,
				  QMessageBox::No | QMessageBox::Default)
	      == QMessageBox::No)
	        continue;
        }
        else if (sum.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, sum.lastError().databaseText(), __FILE__, __LINE__);
	      continue;
        }
        else if (sum.value("subtotal").toDouble() != 0)
        {
	      xrate.bindValue(":invchead_id", id);
	      xrate.exec();
	      if (xrate.lastError().type() != QSqlError::NoError)
	      {
	        systemError(this, tr("System Error posting Invoice #%1\n%2")
			            .arg(selected[i]->text(0))
			            .arg(xrate.lastError().databaseText()),
		                __FILE__, __LINE__);
	        continue;
	      }
	      else if (!xrate.first() || xrate.value("curr_rate").isNull())
	      {
	        systemError(this, tr("Could not post Invoice #%1 because of a missing exchange rate.")
						.arg(selected[i]->text(0)));
	        continue;
	      }
        }

        post.bindValue(":invchead_id", id);
        post.bindValue(":journal",     journal);
        post.exec();
        if (post.first())
        {
	      int result = post.value("result").toInt();
	      if (result < 0)
	        systemError(this, storedProcErrorLookup("postInvoice", result),
		            __FILE__, __LINE__);
        }
        // contains() string is hard-coded in stored procedure
        else if (post.lastError().databaseText().contains("post to closed period"))
        {
	    if (changeDate)
	    {
	      triedToClosed = selected;
	      break;
	    }
	    else
	      triedToClosed.append(selected[i]);
      }
      else if (post.lastError().type() != QSqlError::NoError)
	    systemError(this, tr("A System Error occurred posting Invoice #%1.\n%2")
	    	    .arg(selected[i]->text(0))
	     		.arg(post.lastError().databaseText()),
		        __FILE__, __LINE__);
    }

      if (triedToClosed.size() > 0)
      {
        failedPostList newdlg(this, "", true);
        newdlg.sSetList(triedToClosed, _invchead->headerItem(), _invchead->header());
        tryagain = (newdlg.exec() == XDialog::Accepted);
        selected = triedToClosed;
        triedToClosed.clear();
      }
	}
  } while (tryagain);

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

    orReport report("SalesJournal", params);
    if (report.isValid())
      report.print();
    else
      report.reportError(this);
  }

  omfgThis->sInvoicesUpdated(-1, TRUE);
}