Esempio n. 1
0
void arOpenItem::sTaxDetail()
{
  XSqlQuery ar;
  if (_aropenid == -1)
  {
    QList<GuiErrorCheck>errors;
    errors<<GuiErrorCheck(!_docDate->isValid(), _docDate,
                            tr("You must enter a document date for this Receivable Memo before you may set tax amounts."))
          <<GuiErrorCheck(!_dueDate->isValid(), _dueDate,
                            tr("You must enter a due date for this Receivable Memo before you may set tax amounts."))
          <<GuiErrorCheck(_amount->isZero(), _amount,
                           tr("You must enter an amount for this Receivable Memo before you may set tax amounts."));

    if(GuiErrorCheck::reportErrors(this,tr("Cannot Set Tax Amounts"),errors))
        return;


    if (!sInitializeMemo())
      return;
  }

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

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

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

  params.append("order_type", "AR");
  params.append("order_id", _aropenid);
  params.append("display_type", "A");
  params.append("subtotal", _amount->localValue());
  params.append("adjustment");
  if (newdlg.set(params) == NoError)
  {
    newdlg.exec();
    XSqlQuery taxq;
    taxq.prepare( "SELECT SUM(taxhist_tax) AS tax "
      "FROM aropentax "
      "WHERE (taxhist_parent_id=:aropen_id);" );
    taxq.bindValue(":aropen_id", _aropenid);
    taxq.exec();
    if (taxq.first())
    {
      if (_docType->code() == "C")
        _tax->setLocalValue(taxq.value("tax").toDouble() * -1);
      else
        _tax->setLocalValue(taxq.value("tax").toDouble());
    }
    else if (ErrorReporter::error(QtCriticalMsg, this, tr("Cannot set tax amounts"),
                                  taxq, __FILE__, __LINE__))
    {
      return;
    }
  }
}
void purchaseOrderItem::sPopulateItemInfo(int pItemid)
{
  XSqlQuery item;
  if (pItemid != -1 && _mode == cNew)
  {
      item.prepare("SELECT stdCost(item_id) AS stdcost, "
                   "       getItemTaxType(item_id, pohead_taxzone_id) AS taxtype_id, "
                   "       item_tax_recoverable, COALESCE(item_maxcost, 0.0) AS maxcost "
                   "FROM item, pohead "
                   "WHERE ( (item_id=:item_id) "
                   "  AND   (pohead_id=:pohead_id) );");
      item.bindValue(":item_id", pItemid);
      item.bindValue(":pohead_id", _poheadid);
      item.exec();

      if (item.first())
      {
          // Reset order qty cache
          _orderQtyCache = -1;

          if(_metrics->boolean("RequireStdCostForPOItem") && item.value("stdcost").toDouble() == 0.0)
          {
            QMessageBox::critical( this, 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."));
            _item->setId(-1);
            return;
          }

        _taxtype->setId(item.value("taxtype_id").toInt());
        _taxRecoverable->setChecked(item.value("item_tax_recoverable").toBool());
        _maxCost = item.value("maxcost").toDouble();

        sPopulateItemsiteInfo();

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

        item.prepare("SELECT itemsrc_id "
                     "FROM itemsrc, pohead "
                     "WHERE ( (itemsrc_vend_id=pohead_vend_id)"
                     " AND (itemsrc_item_id=:item_id)"
                     " AND (:effective BETWEEN itemsrc_effective AND (itemsrc_expires - 1))"
                     " AND (itemsrc_active)"
                     " AND (pohead_id=:pohead_id) );" );
        item.bindValue(":item_id", pItemid);
        item.bindValue(":pohead_id", _poheadid);
        item.bindValue(":effective", _unitPrice->effective());
        item.exec();
        if (item.size() == 1)
        {
          item.first();

          if (item.value("itemsrc_id").toInt() != _itemsrcid)
            sPopulateItemSourceInfo(item.value("itemsrc_id").toInt());
        }
        else if (item.size() > 1)
        {
          bool isCurrent = false;
          while (item.next())
          {
            if (item.value("itemsrc_id").toInt() == _itemsrcid)
              isCurrent = true;
          }
          if (!isCurrent)
          {
            _vendorItemNumber->clear();
            sVendorItemNumberList();
          }
        }
        else
        {
          _itemsrcid = -1;

          _vendorItemNumber->clear();
          _vendorDescrip->clear();
          _vendorUOM->setText(_item->uom());
          _uom->setText(_item->uom());
          _minOrderQty->clear();
          _orderQtyMult->clear();
          _invVendorUOMRatio->setDouble(1.0);
          _earliestDate->setDate(omfgThis->dbDate());
          _manufName->setId(-1);
          _manufItemNumber->clear();
          _manufItemDescrip->clear();

          _invVendUOMRatio = 1;
          _minimumOrder = 0;
          _orderMultiple = 0;
        }
      }
  }
}
Esempio n. 3
0
void postMiscProduction::sPost()
{
    q.prepare( "SELECT itemsite_id "
               "FROM itemsite "
               "WHERE ( (itemsite_item_id=:item_id)"
               " AND (itemsite_warehous_id=:warehous_id) );" );
    q.bindValue(":item_id", _item->id());
    q.bindValue(":warehous_id", _warehouse->id());
    q.exec();
    if (q.first())
    {
        int itemsiteid = q.value("itemsite_id").toInt();

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

        q.exec("BEGIN;");	// because of possible lot, serial, or location distribution cancelations
        q.prepare( "SELECT postMiscProduction( :itemsite_id, :qty, :backflushMaterials,"
                   "                           :docNumber, :comments ) AS result;" );
        q.bindValue(":itemsite_id", itemsiteid);
        q.bindValue(":qty", _qtyToPost->toDouble());
        q.bindValue(":backflushMaterials", QVariant(_backflush->isChecked(), 0));
        q.bindValue(":docNumber", _documentNum->text().stripWhiteSpace());
        q.bindValue(":comments", _comments->text());
        q.exec();
        if (q.first())
        {
            if (q.value("result").toInt() < 0)
            {
                rollback.exec();
                systemError(this, tr("A System Error occurred at %1::%2, Item Number %3, Error %4.")
                            .arg(__FILE__)
                            .arg(__LINE__)
                            .arg(_item->itemNumber())
                            .arg(q.value("result").toInt()) );
                return;
            }
            else
            {
                if (distributeInventory::SeriesAdjust(q.value("result").toInt(), this) == XDialog::Rejected)
                {
                    rollback.exec();
                    QMessageBox::information( this, tr("Post Misc. Production"), tr("Transaction Canceled") );
                    return;
                }

                if (_immediateTransfer->isChecked())
                {
                    if (_warehouse->id() == _transferWarehouse->id())
                    {
                        rollback.exec();
                        QMessageBox::warning( this, tr("Cannot Post Immediate Transfer"),
                                              tr( "Transaction canceled. OpenMFG cannot post an immediate transfer for the newly posted production as the\n"
                                                  "transfer Warehouse is the same as the production Warehouse.  You must manually\n"
                                                  "transfer the production to the intended Warehouse." ) );
                        return;
                    }
                    else
                    {
                        q.prepare( "SELECT interWarehouseTransfer( :item_id, :from_warehous_id, :to_warehous_id,"
                                   "                               :qty, 'W', :documentNumber, 'Transfer from Misc. Production Posting' ) AS result;" );
                        q.bindValue(":item_id", _item->id());
                        q.bindValue(":from_warehous_id", _warehouse->id());
                        q.bindValue(":to_warehous_id", _transferWarehouse->id());
                        q.bindValue(":qty", _qtyToPost->toDouble());
                        q.bindValue(":documentNumber", _documentNum->text().stripWhiteSpace());
                        q.exec();
                        if (q.first())
                        {
                            if (distributeInventory::SeriesAdjust(q.value("result").toInt(), this) == XDialog::Rejected)
                            {
                                rollback.exec();
                                QMessageBox::information( this, tr("Post Misc. Production"), tr("Transaction Canceled") );
                                return;
                            }

                            q.exec("COMMIT;");
                        }
                        else
                        {
                            rollback.exec();
                            systemError( this, tr("A System Error occurred at interWarehousTransfer::%1, Item Site ID #%2, Warehouse ID #%3 to Warehouse ID #%4.")
                                         .arg(__LINE__)
                                         .arg(_item->id())
                                         .arg(_warehouse->id())
                                         .arg(_transferWarehouse->id()));
                        }
                    }
                }
                else
                    q.exec("COMMIT;");
            }
        }
        else
        {
            rollback.exec();
            systemError(this, tr("A System Error occurred at %1::%2, Item Number %3.")
                        .arg(__FILE__)
                        .arg(__LINE__)
                        .arg(_item->itemNumber()) );
            return;
        }

        if (_captive)
            accept();
        else
        {
            _item->setId(-1);
            _qtyToPost->clear();
            _documentNum->clear();
            _comments->clear();
            _close->setText(tr("&Close"));

            _item->setFocus();
        }
    }
    else
        systemError(this, tr("A System Error occurred at %1::%2, Item Number %3.")
                    .arg(__FILE__)
                    .arg(__LINE__)
                    .arg(_item->itemNumber()) );
}
void purchaseOrderItem::sPopulateItemSourceInfo(int pItemsrcid)
{
  XSqlQuery src;
  bool skipClear = false;
  if (!_item->isValid())
    skipClear = true;
  if (_mode == cNew)
  {
    if (pItemsrcid != -1)
    {
      src.prepare( "SELECT itemsrc_id, itemsrc_item_id, itemsrc_vend_item_number,"
                 "       itemsrc_vend_item_descrip, itemsrc_vend_uom,"
                 "       itemsrc_minordqty,"
                 "       itemsrc_multordqty,"
                 "       itemsrc_invvendoruomratio,"
                 "       (CURRENT_DATE + itemsrc_leadtime) AS earliestdate, "
                 "       itemsrc_manuf_name, "
                 "       itemsrc_manuf_item_number, "
                 "       itemsrc_manuf_item_descrip, "
                 "       contrct_number "
				 "FROM itemsrc LEFT OUTER JOIN contrct ON (itemsrc_contrct_id = contrct_id) "
                 "WHERE (itemsrc_id=:itemsrc_id);" );
      src.bindValue(":itemsrc_id", pItemsrcid);
      src.exec();
      if (src.first())
      {
        _itemsrcid = src.value("itemsrc_id").toInt();
        _item->setId(src.value("itemsrc_item_id").toInt());
  
        _vendorItemNumber->setText(src.value("itemsrc_vend_item_number").toString());
        _vendorDescrip->setText(src.value("itemsrc_vend_item_descrip").toString());
        _vendorUOM->setText(src.value("itemsrc_vend_uom").toString());
        _uom->setText(src.value("itemsrc_vend_uom").toString());
        _minOrderQty->setDouble(src.value("itemsrc_minordqty").toDouble());
        _orderQtyMult->setDouble(src.value("itemsrc_multordqty").toDouble());
        _invVendorUOMRatio->setDouble(src.value("itemsrc_invvendoruomratio").toDouble());
        _earliestDate->setDate(src.value("earliestdate").toDate());

        _invVendUOMRatio = src.value("itemsrc_invvendoruomratio").toDouble();
        _minimumOrder = src.value("itemsrc_minordqty").toDouble();
        _orderMultiple = src.value("itemsrc_multordqty").toDouble();
        _contrctNumber->setText(src.value("contrct_number").toString());
        
        _manufName->setCode(src.value("itemsrc_manuf_name").toString());
        _manufItemNumber->setText(src.value("itemsrc_manuf_item_number").toString());
        _manufItemDescrip->setText(src.value("itemsrc_manuf_item_descrip").toString());

        if (_ordered->toDouble() != 0)
          sDeterminePrice();

        _ordered->setFocus();

        if(_metrics->boolean("UseEarliestAvailDateOnPOItem") && _dueDate->date() < _earliestDate->date())
          _dueDate->setDate(_earliestDate->date());

        skipClear = true;
      }
    }

    if(!skipClear)
    {
      _itemsrcid = -1;
  
      _vendorItemNumber->clear();
      _vendorDescrip->clear();
      _vendorUOM->setText(_item->uom());
      _uom->setText(_item->uom());
      _minOrderQty->clear();
      _orderQtyMult->clear();
      _invVendorUOMRatio->setDouble(1.0);
      _earliestDate->setDate(omfgThis->dbDate());
      _manufName->setId(-1);
      _manufItemNumber->clear();
      _manufItemDescrip->clear();
  
      _invVendUOMRatio = 1;
      _minimumOrder = 0;
      _orderMultiple = 0;
    }
  }
}
void purchaseOrderItem::populate()
{
  XSqlQuery purchasepopulate;
  MetaSQLQuery mql = mqlLoad("purchaseOrderItems", "detail");

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

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

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

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

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

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

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

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

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

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

    _comments->setId(_poitemid);
  }
}
Esempio n. 6
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;
}
Esempio n. 7
0
void CLineEdit::sNew()
{
  QString uiName="customer";
  ParameterList params;
  QMessageBox ask(this);
  ask.setIcon(QMessageBox::Question);
  QPushButton *pbutton = ask.addButton(tr("Prospect"), QMessageBox::YesRole);
  QPushButton *cbutton = ask.addButton(tr("Customer"), QMessageBox::YesRole);
  ask.setDefaultButton(cbutton);
  ask.setWindowTitle(tr("Customer or Prospect?"));

  if (_subtype == CRMAcctLineEdit::Prospect ||
      (_subtype == CRMAcctLineEdit::CustAndProspect &&
       !_x_privileges->check("MaintainCustomerMasters")))
  {
    params.append("mode", "new");
    uiName="prospect";
  }
  if (_subtype == CRMAcctLineEdit::CustAndProspect &&
       !_x_privileges->check("MaintainProspectMasters"))
    params.append("mode", "new");
  else
  {
    if (_subtype == CRMAcctLineEdit::Cust)
      ask.setText(tr("<p>Would you like to create a new Customer or convert "
                     "an existing Prospect?"));
    else
      ask.setText(tr("<p>Would you like to create a new Customer or "
                     "a new Prospect?"));

    ask.exec();

    if (ask.clickedButton() == pbutton &&
        _subtype == CRMAcctLineEdit::Cust)  // converting prospect
    {
      int prospectid = -1;
      if (_x_preferences->value("DefaultEllipsesAction") == "search")
      {
        CRMAcctSearch* search = new CRMAcctSearch(this);
        search->setSubtype(CRMAcctLineEdit::Prospect);
        prospectid = search->exec();
      }
      else
      {
        CRMAcctList* list = new CRMAcctList(this);
        list->setSubtype(CRMAcctLineEdit::Prospect);
        prospectid = list->exec();
      }

      if (prospectid > 0)
      {
        XSqlQuery convertq;
        convertq.prepare("SELECT convertProspectToCustomer(:id) AS result;");
        convertq.bindValue(":id", prospectid);
        convertq.exec();
        if (convertq.first())
        {
          int result = convertq.value("result").toInt();
          if (result < 0)
          {
            QMessageBox::critical(this, tr("Processing Error"),
                                  storedProcErrorLookup("convertProspectToCustomer", result));
            return;
          }
          params.append("cust_id", prospectid);
          params.append("mode", "edit");
        }
      }
      else
        return;
    }
    else
    {
      params.append("mode", "new");
      if (ask.clickedButton() == pbutton)
        uiName = "prospect";
    }
  }

  sOpenWindow(uiName, params);
}
Esempio n. 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, QVariant());
	  model->setData(model->index(index.row(), ITEM_ID_COL), QVariant());
	  model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), QVariant());
	  model->setData(model->index(index.row(), WAREHOUS_ID_COL), QVariant());
	  model->setData(model->index(index.row(), WAREHOUS_CODE_COL), QVariant());
	  model->setData(model->index(index.row(), POITEM_ITEMSRC_ID_COL), QVariant());
	  model->setData(model->index(index.row(), POITEM_VEND_ITEM_NUMBER_COL), QVariant());
	  model->setData(model->index(index.row(), POITEM_VEND_ITEM_DESCRIP_COL), QVariant());
	  model->setData(model->index(index.row(), POITEM_VEND_UOM_COL), QVariant());
	  model->setData(model->index(index.row(), ITEMSRC_MINORDQTY_COL), QVariant());
	  model->setData(model->index(index.row(), ITEMSRC_MULTORDQTY_COL), QVariant());
	  model->setData(model->index(index.row(), ITEMSRC_INVVENDORUOMRATIO_COL), QVariant());
	  model->setData(model->index(index.row(), POITEM_INVVENDUOMRATIO_COL), QVariant());
	  model->setData(model->index(index.row(), EARLIESTDATE_COL), 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::NoError)
	    {
	      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, QString());
		model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), QVariant());
		model->setData(model->index(index.row(), WAREHOUS_ID_COL), QVariant());
		model->setData(model->index(index.row(), WAREHOUS_CODE_COL), QString());
		model->setData(index, QString());
		hitError = true;
		break;
	      }
	      else if (stdcostq.lastError().type() != QSqlError::NoError)
	      {
		systemError(0, stdcostq.lastError().databaseText(), __FILE__, __LINE__);
		hitError = true;
		break;
	      }
	    }

	    XSqlQuery itemsrcq;
	    itemsrcq.prepare( "SELECT pohead_vend_id, 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.size() > 1)
            {
              itemsrcq.first();
              ParameterList params;
              params.append("vend_id",  itemsrcq.value("pohead_vend_id").toInt());
              params.append("search", item->itemNumber());
              itemSourceSearch newdlg(0, "", true);
              newdlg.set(params);
              if(newdlg.exec() == XDialog::Accepted)
              {
                int itemsrcid = newdlg.itemsrcId();
                if(itemsrcid != -1)
                {
                  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_id=:itemsrc_id);" );
                  itemsrcq.bindValue(":itemsrc_id", itemsrcid);
                  itemsrcq.exec();
                }
              }
              else
                itemsrcq.clear();
            }
	    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(), POITEM_MANUF_NAME_COL), itemsrcq.value("itemsrc_manuf_name").toString());
          model->setData(model->index(index.row(), POITEM_MANUF_ITEM_NUMBER_COL), itemsrcq.value("itemsrc_manuf_item_number").toString());
          model->setData(model->index(index.row(), POITEM_MANUF_ITEM_DESCRIP_COL), itemsrcq.value("itemsrc_manuf_item_descrip").toString());
	      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::NoError)
	    {
	      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::NoError)
	  {
	    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_DESCRIP_COL:
    {
      XLineEdit *lineedit = static_cast<XLineEdit*>(editor);
      if (lineedit->text() != oldval.toString())
	model->setData(index, lineedit->text());
      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::NoError)
	  {
	    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;
}
void arCreditMemoApplication::populate()
{
  XSqlQuery arpopulate;
  arpopulate.prepare( "SELECT aropen_cust_id, aropen_docnumber, aropen_doctype,"
             "       aropen_docdate, aropen_duedate, "
             "       aropen_amount, "
             "       aropen_paid, "
             "       calcpendingarapplications(aropen_id) AS pending, "
             "       (aropen_amount - aropen_paid - calcpendingarapplications(aropen_id)) AS f_balance, "
             "       aropen_curr_id "
             "FROM aropen "
             "WHERE (aropen_id=:aropen_id);" );
  arpopulate.bindValue(":aropen_id", _targetAropenid);
  arpopulate.exec();
  if (arpopulate.first())
  {
    _cust->setId(arpopulate.value("aropen_cust_id").toInt());
    _docNumber->setText(arpopulate.value("aropen_docnumber").toString());
    _docType->setText(arpopulate.value("aropen_doctype").toString());
    _docDate->setDate(arpopulate.value("aropen_docdate").toDate(), true);
    _dueDate->setDate(arpopulate.value("aropen_duedate").toDate());
    _targetAmount->set(arpopulate.value("aropen_amount").toDouble(),
		       arpopulate.value("aropen_curr_id").toInt(),
		       arpopulate.value("aropen_docdate").toDate(), false);
    _targetPaid->setLocalValue(arpopulate.value("aropen_paid").toDouble());
    _targetPending->setLocalValue(arpopulate.value("pending").toDouble());
    _targetBalance->setLocalValue(arpopulate.value("f_balance").toDouble());
  }
  else if (arpopulate.lastError().type() != QSqlError::NoError)
  {
    systemError(this, arpopulate.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  arpopulate.prepare( "SELECT COALESCE(arcreditapply_curr_id,aropen_curr_id) AS curr_id,"
             "       currToCurr(aropen_curr_id,"
             "                 COALESCE(arcreditapply_curr_id,aropen_curr_id),"
             "                 aropen_amount - aropen_paid, aropen_docdate) - "
             "		COALESCE(SUM(arcreditapply_amount), 0) - COALESCE(prepared,0.0) - COALESCE(cashapplied,0.0) AS available,"
             "       current_date AS docdate "
             "FROM aropen LEFT OUTER JOIN arcreditapply ON (arcreditapply_source_aropen_id=aropen_id) "
    	     "       LEFT OUTER JOIN (SELECT aropen_id AS prepared_aropen_id,"
             "                               SUM(checkitem_amount + checkitem_discount) AS prepared"
             "                          FROM checkhead JOIN checkitem ON (checkitem_checkhead_id=checkhead_id)"
             "                                     JOIN aropen ON (checkitem_aropen_id=aropen_id)"
             "                         WHERE ((NOT checkhead_posted)"
             "                           AND  (NOT checkhead_void))"
             "                         GROUP BY aropen_id) AS sub1 "
             "         ON (prepared_aropen_id=aropen_id)"
             "       LEFT OUTER JOIN (SELECT aropen_id AS cash_aropen_id,"
             "                               SUM(cashrcptitem_amount + cashrcptitem_discount) * -1.0 AS cashapplied"
             "                          FROM cashrcpt JOIN cashrcptitem ON (cashrcptitem_cashrcpt_id=cashrcpt_id)"
             "                                     JOIN aropen ON (cashrcptitem_aropen_id=aropen_id)"
             "                         WHERE ((NOT cashrcpt_posted)"
             "                           AND  (NOT cashrcpt_void))"
             "                         GROUP BY aropen_id ) AS sub2"
             "         ON (cash_aropen_id=aropen_id)"
             "WHERE (aropen_id=:aropen_id) "
             "GROUP BY aropen_amount, aropen_paid, aropen_docdate,"
                 "         arcreditapply_curr_id, aropen_curr_id, prepared, cashapplied;" );
  arpopulate.bindValue(":aropen_id", _sourceAropenid);
  arpopulate.exec();
  if (arpopulate.first())
  {
    _availableToApply->set(arpopulate.value("available").toDouble(),
		           arpopulate.value("curr_id").toInt(),
		           arpopulate.value("docdate").toDate(), false);
  }
  else if (arpopulate.lastError().type() != QSqlError::NoError)
    systemError(this, arpopulate.lastError().databaseText(), __FILE__, __LINE__);

  arpopulate.prepare( "SELECT currToCurr(arcreditapply_curr_id, :curr_id, "
	     "                  arcreditapply_amount, :effective) AS arcreditapply_amount "
             "FROM arcreditapply "
             "WHERE ( (arcreditapply_source_aropen_id=:source_aropen_id)"
             " AND (arcreditapply_target_aropen_id=:target_aropen_id) );" );
  arpopulate.bindValue(":source_aropen_id", _sourceAropenid);
  arpopulate.bindValue(":target_aropen_id", _targetAropenid);
  arpopulate.bindValue(":curr_id", _amountToApply->id());
  arpopulate.bindValue(":effective", _amountToApply->effective());
  arpopulate.exec();
  if (arpopulate.first())
    _amountToApply->setLocalValue(arpopulate.value("arcreditapply_amount").toDouble());
  else if (arpopulate.lastError().type() != QSqlError::NoError)
    systemError(this, arpopulate.lastError().databaseText(), __FILE__, __LINE__);
}
Esempio n. 10
0
void postCashReceipts::sPost()
{
  XSqlQuery postPost;
  int journalNumber;

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

  postPost.exec( "SELECT cashrcpt_id, cust_number "
          "FROM cashrcpt, custinfo "
          "WHERE ( (NOT cashrcpt_posted)"
          "  AND   (NOT cashrcpt_void)"
          "  AND   (cashrcpt_cust_id=cust_id) );" );
  if (postPost.first())
  {
    int counter = 0;

    XSqlQuery post;
    post.prepare("SELECT postCashReceipt(:cashrcpt_id, :journalNumber) AS result;");

    do
    {
      message( tr("Posting Cash Receipt #%1...")
               .arg(postPost.value("cust_number").toString()) );

      post.bindValue(":cashrcpt_id", postPost.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(postPost.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(postPost.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(postPost.value("cust_number").toString())  );

          default:
            counter++;
        }
      }
      else if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Posting"),
                                    post, __FILE__, __LINE__))
      {
        break;
      }
    }
    while (postPost.next());

    resetMessage();

    if ( (counter) && (_printJournal->isChecked()) )
    {
      ParameterList params;
      params.append("source", "A/R");
      params.append("sourceLit", tr("A/R"));
      params.append("startJrnlnum", journalNumber);
      params.append("endJrnlnum", journalNumber);

      if (_metrics->boolean("UseJournals"))
      {
        params.append("title",tr("Journal Series"));
        params.append("table", "sltrans");
      }
      else
      {
        params.append("title",tr("General Ledger Series"));
        params.append("gltrans", true);
        params.append("table", "gltrans");
      }

      orReport report("GLSeries", 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.") );
  }
}
Esempio n. 11
0
void postCreditMemos::sPost()
{
  q.exec( "SELECT cmhead_printed, COUNT(*) AS number "
          "FROM cmhead "
          "WHERE ( (NOT cmhead_posted) "
          "  AND   (checkCreditMemoSitePrivs(cmhead_id)) ) "
          "GROUP BY cmhead_printed;" );
  if (q.first())
  {
    int printed   = 0;
    int unprinted = 0;

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

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

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

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

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

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

    q.exec("COMMIT;");

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

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

  omfgThis->sCreditMemosUpdated();

// START_RW
  if(_metrics->boolean("EnableExternalAccountingInterface"))
  {
//  Check to see if any aropen items are available to post
    q.exec( "SELECT aropen_id "
            "FROM aropen "
            "WHERE (NOT aropen_posted) "
            "LIMIT 1;" );
    if (!q.first())
    {
      QMessageBox::information( this, tr("No A/R Open Items"),
                                tr( "There are no A/R Open Items to post.\n"
                                    "This means that there are no Credit Memos that have not been posted to A/R.\n"
                                    "Make sure that you have printed all Credit Memos and select Post Credit Memos again.") );
    }
    else
    {
      if ( (_metrics->value("AccountingSystem") == "RW2000") ||
           (_metrics->value("AccountingSystem") == "RealWorld91") )
      {
        if (QMessageBox::critical( this, tr("Create New AROPEN and ARDIST Files?"),
                                   tr( "Creating new Export Files will delete the previous Export Files.\n"
                                       "You should make sure that the previous Export Files have been\n"
                                       "imported into RealWorld before Proceeding.\n\n"
                                       "Are you sure that you want to Create New Export Files?" ),
                                       "&Yes", "&No", QString::null, 0, 1  ) == 0)
        {
          if (rwInterface::exportAropen(this))
          {
            rwInterface::exportArdist(this);
  
            if ( (_metrics->value("AccountingSystem") == "RW2000") ||
                 (_metrics->value("AccountingSystem") == "RealWorld91") )
              if ( QMessageBox::information( this, tr("Mark Distributions as Posted"),
                                             tr( "New ARDIST and AROPEN files have been generated in the RealWorld directory.\n"
                                                 "You should now use the RealWorld arfu/arutil tool to import these files.\n"
                                                 "After you have successfully imported the ARDIST and AROPEN files click the 'Post'\n"
                                                 "button to mark these items as distributed.\n"
                                                 "If, for any reason, you were unable to post the ARDIST and AROPEN files click\n"
                                                 "on the 'Do Not Post' button and Re-Post Invoices to re-create the ARDIST and AROPEN files.\n" ),
                                             tr("&Post"), tr("Do &Not Post"), QString::null, 0, 1) == 0)
                q.exec( "SELECT postSoGLTransactions();"
                        "SELECT postAropenItems();" );
          }
        }
      }
    }
  }
// END_RW

  accept();
}
Esempio n. 12
0
/*
   return +N addr_id if save is successful or if found another addr with the same info
   return  0 if there is no address to save
   return -1 if there was an error
   return -2 if there are N contacts sharing this address
  
 */
int AddressCluster::save(enum SaveFlags flag)
{

  if (_number->text() == "" &&
      _addr1->text() == "" && _addr2->text() == "" &&
      _addr3->text() == "" && _city->text() == "" &&
      _state->currentText() == "" && _postalcode->text() == "" &&
      (_country->currentText() == "" || (_x_metrics && _country->currentText()==_x_metrics->value("DefaultAddressCountry")))
     )
  {
    silentSetId(-1);
    return 0;
  }
  if (_x_metrics && _x_metrics->boolean("StrictAddressCountry") &&
      !_country->currentText().isEmpty() &&
      _country->findText(_country->currentText(), Qt::MatchExactly) < 0)
  {
    QMessageBox::critical(this, tr("Error"),
                          tr("<p>This address appears to have a non-standard "
                             "country. Please select a country from the list "
                             "before saving."));
    return -3;
  }
  
  XSqlQuery datamodQ;
  datamodQ.prepare("SELECT saveAddr(:addr_id,:addr_number,:addr1,:addr2,:addr3," 
		   ":city,:state,:postalcode,:country,:active,:notes,:flag) AS result;");
  datamodQ.bindValue(":addr_id", id());
  if (!_number->text().isEmpty())
    datamodQ.bindValue(":addr_number", _number->text());
  datamodQ.bindValue(":addr1", _addr1->text());
  datamodQ.bindValue(":addr2", _addr2->text());
  datamodQ.bindValue(":addr3", _addr3->text());
  datamodQ.bindValue(":city", _city->text());
  datamodQ.bindValue(":state", _state->currentText());
  datamodQ.bindValue(":postalcode", _postalcode->text());
  datamodQ.bindValue(":country", _country->currentText());
  datamodQ.bindValue(":active", QVariant(_active->isChecked()));
  datamodQ.bindValue(":notes", _notes);
  if (flag == CHECK)
    datamodQ.bindValue(":flag", QString("CHECK"));
  else if (flag == CHANGEALL)
    datamodQ.bindValue(":flag", QString("CHANGEALL"));
  else if (flag == CHANGEONE)
    datamodQ.bindValue(":flag", QString("CHANGEONE"));
  else
    return -1;
    
  datamodQ.exec();
  if (datamodQ.first())
  {
    if (datamodQ.value("result").toInt() > 0)
    {
      _id=datamodQ.value("result").toInt();
      _selected = FALSE;
      _valid = true;
      return id();
    }
    if (datamodQ.value("result").toInt() == -2)
      return -2;
    else
      return -1; //error
  }
  return id();
}
Esempio n. 13
0
void AddressCluster::silentSetId(const int pId)
{
    if (pId == -1)
    {
      _id = pId;
      _valid = false;
      clear();
    }
    else
    {
      clear();
      XSqlQuery idQ;
      idQ.prepare("SELECT * from addr WHERE addr_id = :id;");
      idQ.bindValue(":id", pId);
      idQ.exec();
      if (idQ.first())
      {
        _id = pId;
        _valid = true;
        _number->setText(idQ.value("addr_number").toString());
        _addr1->setText(idQ.value("addr_line1").toString());
        _addr2->setText(idQ.value("addr_line2").toString());
        _addr3->setText(idQ.value("addr_line3").toString());
        _city->setText(idQ.value("addr_city").toString());
        _postalcode->setText(idQ.value("addr_postalcode").toString());

        // set country before state or populateStateComboBox may clear the state
        setCountry(idQ.value("addr_country").toString());
        setState(idQ.value("addr_state").toString());

        _active->setChecked(idQ.value("addr_active").toBool());
        _notes = idQ.value("addr_notes").toString();

        if (_mapper->model())
        {
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_number)), _number->text());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_active)), _active->isChecked());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_addr1)), _addr1->text());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_addr2)), _addr2->text());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_addr3)), _addr3->text());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_city)), _city->text());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_state)), _state->currentText());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_postalcode)), _postalcode->text());
           _mapper->model()->setData(_mapper->model()->index(_mapper->currentIndex(),_mapper->mappedSection(_country)), _country->currentText());    
        }

        c_number     = _number->text();
        c_addr1      = _addr1->text();
        c_addr2      = _addr2->text();
        c_addr3      = _addr3->text();
        c_city       = _city->text();
        c_state      = _state->currentText();
        c_postalcode = _postalcode->text();
        c_country    = _country->currentText();
        c_active     = _active->isChecked();
        c_notes      = _notes;
      }
      else if (idQ.lastError().type() != QSqlError::NoError)
          QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
                                        .arg(__FILE__)
                                        .arg(__LINE__),
                                idQ.lastError().databaseText());
  }

    // _parsed = TRUE;
}
Esempio n. 14
0
void AddressCluster::populateStateComboBox()
{
  if(_x_metrics == 0)
    return;

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

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

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

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

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

  if (DEBUG)
    qDebug("%s::populateStateComboBox() returning id %d, text %s, tmpstate %s",
           (objectName().isEmpty() ? "AddressCluster":qPrintable(objectName())),
         _state->id(), qPrintable(_state->currentText()), qPrintable(tmpstate));
}
Esempio n. 15
0
void todoList::sDelete()
{
  QString recurstr;
  QString recurtype;
  if (list()->altId() == 1)
  {
    recurstr = "SELECT MAX(todoitem_due_date) AS max"
               "  FROM todoitem"
               " WHERE todoitem_recurring_todoitem_id=:id"
               "   AND todoitem_id!=:id;" ;
    recurtype = "TODO";
  }
  /* TODO: can't delete incidents from here. why not?
  else if (list()->altId() == 2)
  {
    recurstr = "SELECT MAX(incdt_timestamp) AS max"
               "   FROM incdt"
               " WHERE incdt_recurring_incdt_id=:id;" ;
    recurtype = "INCDT";
  }
   */

  bool deleteAll  = false;
  bool createMore = false;
  if (! recurstr.isEmpty())
  {
    XSqlQuery recurq;
    recurq.prepare(recurstr);
    recurq.bindValue(":id", list()->id());
    recurq.exec();
    if (recurq.first() && !recurq.value("max").isNull())
    {
      QMessageBox askdelete(QMessageBox::Question, tr("Delete Recurring Item?"),
                            tr("<p>This is a recurring item. Do you want to "
                               "delete just this one item or delete all open "
                               "items in this recurrence?"),
                            QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::Cancel,
                            this);
      askdelete.setDefaultButton(QMessageBox::Cancel);
      int ret = askdelete.exec();
      if (ret == QMessageBox::Cancel)
        return;
      else if (ret == QMessageBox::YesToAll)
        deleteAll = true;
      // user said delete one but the only one that exists is the base
      else if (ret == QMessageBox::Yes && recurq.value("max").isNull())
        createMore = true;
    }
    else if (recurq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, recurq.lastError().text(), __FILE__, __LINE__);
      return;
    }
    else if (QMessageBox::warning(this, tr("Delete List Item?"),
                                  tr("<p>Are you sure that you want to "
                                     "completely delete the selected item?"),
	  		    QMessageBox::Yes | QMessageBox::No,
			    QMessageBox::No) == QMessageBox::No)
      return;
  }
  else if (QMessageBox::warning(this, tr("Delete List Item?"),
                                tr("<p>Are you sure that you want to "
                                   "completely delete the selected item?"),
	  		    QMessageBox::Yes | QMessageBox::No,
			    QMessageBox::No) == QMessageBox::No)
    return;

  QString procname;
  int procresult = 0;
  if (deleteAll)
  {
    procname = "deleteOpenRecurringItems";
    q.prepare("SELECT deleteOpenRecurringItems(:id, :type, NULL, TRUE)"
              "       AS result;");
    q.bindValue(":id",   list()->id());
    q.bindValue(":type", recurtype);
    q.exec();
    if (q.first())
      procresult = q.value("result").toInt();
  }
  if (procresult >= 0 && createMore)
  {
    procname = "createRecurringItems";
    q.prepare("SELECT createRecurringItems(:id, :type) AS result;");
    q.bindValue(":id",   list()->id());
    q.bindValue(":type", recurtype);
    q.exec();
    if (q.first())
      procresult = q.value("result").toInt();
  }

  // not elseif - error handling for 1 or 2 queries
  if (procresult < 0)
  {
    systemError(this, storedProcErrorLookup(procname, procresult));
    return;
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (list()->altId() == 1)
    q.prepare("SELECT deleteTodoItem(:todoitem_id) AS result;");
  else if (list()->altId() == 3)
    q.prepare("DELETE FROM prjtask"
              " WHERE (prjtask_id=:todoitem_id); ");
  else if (list()->altId() == 4)
    q.prepare("SELECT deleteProject(:todoitem_id) AS result");
  else
    return;
  q.bindValue(":todoitem_id", list()->id());
  q.exec();
  if (q.first())
  {
    int result = q.value("result").toInt();
    if (result < 0)
    {
      systemError(this, storedProcErrorLookup("deleteTodoItem", result));
      return;
    }
  }
  else if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  sFillList();
}
Esempio n. 16
0
void arCreditMemoApplication::sSave()
{
  XSqlQuery arSave;
  double amountToApply = _amountToApply->localValue();

  // check to make sure the amount being applied does not exceed
  // the balance due on the target item.
  arSave.prepare( "SELECT ROUND(currToCurr(aropen_curr_id, :curr_id,"
             "      (aropen_amount - aropen_paid - calcpendingarapplications(aropen_id)), current_date), 2) AS balance "
             "  FROM aropen "
             " WHERE (aropen_id=:aropen_id);");
  arSave.bindValue(":aropen_id", _targetAropenid);
  arSave.bindValue(":curr_id",   _amountToApply->id());
  arSave.exec();
  double targetBalance = 0.0;
  if(arSave.first())
    targetBalance = arSave.value("balance").toDouble();
  else if (arSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, arSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  if(amountToApply > targetBalance)
  {
    QMessageBox::warning(this, tr("Invalid Application"),
      tr("You may not apply more than the balance due to this Document.") );
    return;
  }

  // check to make sure the mount being applied does not exceed
  // the remaining balance of the source item.
  arSave.prepare( "SELECT round((aropen_amount - aropen_paid) - "
	     "	COALESCE(SUM(currToCurr(arcreditapply_curr_id, "
	     "				aropen_curr_id, "
	     "				arcreditapply_amount, "
             "				aropen_docdate)), 0), 2) - COALESCE(prepared,0.0) - COALESCE(cashapplied,0.0) AS available "
             "FROM aropen LEFT OUTER JOIN arcreditapply "
             "  ON ((arcreditapply_source_aropen_id=aropen_id) "
             "  AND (arcreditapply_target_aropen_id<>:targetAropenid)) "
             "       LEFT OUTER JOIN (SELECT aropen_id AS prepared_aropen_id,"
             "                               SUM(checkitem_amount + checkitem_discount) AS prepared"
             "                          FROM checkhead JOIN checkitem ON (checkitem_checkhead_id=checkhead_id)"
             "                                     JOIN aropen ON (checkitem_aropen_id=aropen_id)"
             "                         WHERE ((NOT checkhead_posted)"
             "                           AND  (NOT checkhead_void))"
             "                         GROUP BY aropen_id) AS sub1"
             "         ON (prepared_aropen_id=aropen_id)"
             "       LEFT OUTER JOIN (SELECT aropen_id AS cash_aropen_id,"
             "                               SUM(cashrcptitem_amount + cashrcptitem_discount) * -1.0 AS cashapplied"
             "                          FROM cashrcpt JOIN cashrcptitem ON (cashrcptitem_cashrcpt_id=cashrcpt_id)"
             "                                     JOIN aropen ON (cashrcptitem_aropen_id=aropen_id)"
             "                         WHERE (NOT cashrcpt_posted)"
             "                         GROUP BY aropen_id ) AS sub2"
             "         ON (cash_aropen_id=aropen_id)"
             "WHERE (aropen_id=:sourceAropenid) "
             "GROUP BY aropen_amount, aropen_paid, prepared, cashapplied;" );
  arSave.bindValue(":sourceAropenid", _sourceAropenid);
  arSave.bindValue(":targetAropenid", _targetAropenid);
  arSave.exec();
  double sourceBalance = 0.0;
  if(arSave.first())
    sourceBalance = arSave.value("available").toDouble();
  else if (arSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, arSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  if(amountToApply > sourceBalance)
  {
    QMessageBox::warning(this, tr("Invalid Application"),
      tr("You may not apply more than the amount available to apply for this Credit Memo.") );
    return;
  }

  arSave.prepare( "SELECT arcreditapply_id "
             "FROM arcreditapply "
             "WHERE ( (arcreditapply_source_aropen_id=:sourceAropenid)"
             " AND (arcreditapply_target_aropen_id=:targetAropenid) );" );
  arSave.bindValue(":sourceAropenid", _sourceAropenid);
  arSave.bindValue(":targetAropenid", _targetAropenid);
  arSave.exec();
  if (arSave.first())
  {
    int arcreditapplyid = arSave.value("arcreditapply_id").toInt();

    arSave.prepare( "UPDATE arcreditapply "
               "SET arcreditapply_amount=:arcreditapply_amount, "
	       "    arcreditapply_curr_id = :arcreditapply_curr_id "
               "WHERE (arcreditapply_id=:arcreditapply_id);" );
    arSave.bindValue(":arcreditapply_id", arcreditapplyid);
  }
  else if (arSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, arSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  else
  {
    arSave.prepare( "INSERT INTO arcreditapply "
               "( arcreditapply_source_aropen_id, arcreditapply_target_aropen_id, "
	       " arcreditapply_amount, arcreditapply_curr_id ) "
               "VALUES "
               "( :sourceAropenid, :targetAropenid, "
	       "  :arcreditapply_amount, :arcreditapply_curr_id );" );
    arSave.bindValue(":sourceAropenid", _sourceAropenid);
    arSave.bindValue(":targetAropenid", _targetAropenid);
  }

  arSave.bindValue(":arcreditapply_amount", amountToApply);
  arSave.bindValue(":arcreditapply_curr_id", _amountToApply->id());
  arSave.exec();
  if (arSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, arSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  accept();
}
Esempio n. 17
0
void returnAuthCheck::sSave()
{
  XSqlQuery returnSave;
  if (!_date->isValid())
  {
    QMessageBox::warning( this, tr("Cannot Create Miscellaneous Check"),
                          tr("<p>You must enter a date for this check.") );
    _date->setFocus();
    return;
  }

  else if (_amount->isZero())
  {
    QMessageBox::warning( this, tr("Cannot Create Miscellaneous Check"),
                          tr("<p>You must enter an amount for this check.") );
    return;
  }

  else if (!_bankaccnt->isValid())
  {
    QMessageBox::warning( this, tr("Cannot Create Miscellaneous Check"),
                          tr("<p>You must select a bank account for this check.") );
    _date->setFocus();
    return;
  }

  else
  {
    returnSave.prepare("SELECT createCheck(:bankaccnt_id, 'C', :recipid,"
	      "                   :checkDate, :amount, :curr_id, NULL,"
	      "                   NULL, :for, :notes, TRUE, :aropen_id) AS result; ");
    returnSave.bindValue(":bankaccnt_id", _bankaccnt->id());
    returnSave.bindValue(":recipid",	_custid);
    returnSave.bindValue(":checkDate", _date->date());
    returnSave.bindValue(":amount",	_amount->localValue());
    returnSave.bindValue(":curr_id",	_amount->id());
    returnSave.bindValue(":for",	_for->text().trimmed());
    returnSave.bindValue(":notes", _notes->toPlainText().trimmed());
	returnSave.bindValue(":aropen_id", _aropenid);
	returnSave.exec();
    if (returnSave.first())
    {
      _checkid = returnSave.value("result").toInt();
      if (_checkid < 0)
      {
        systemError(this, storedProcErrorLookup("createCheck", _checkid),
		    __FILE__, __LINE__);
        return;
      }
      returnSave.prepare( "SELECT checkhead_number "
               "FROM checkhead "
               "WHERE (checkhead_id=:check_id);" );
      returnSave.bindValue(":check_id", _checkid);
      returnSave.exec();
      if (returnSave.lastError().type() != QSqlError::NoError)
      {
        systemError(this, returnSave.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
	  done(TRUE);
	}
    else if (returnSave.lastError().type() != QSqlError::NoError)
    {
     systemError(this, returnSave.lastError().databaseText(), __FILE__, __LINE__);
        return;
    }
  }
}
Esempio n. 18
0
void cashReceiptItem::populate()
{
  XSqlQuery query;

  if (_mode == cNew)
  {
    query.prepare( "SELECT aropen_cust_id, aropen_docnumber, aropen_doctype, "
                   "       aropen_docdate, aropen_duedate, "
                   "       cashrcpt_curr_id, cashrcpt_distdate, "
                   "       currToCurr(aropen_curr_id, cashrcpt_curr_id, (aropen_amount - aropen_paid), "
                   "       cashrcpt_distdate) AS f_amount, "
                   "       COALESCE(ABS(cashrcptitem_discount), 0.00) AS discount "
                   "FROM cashrcpt, aropen LEFT OUTER JOIN cashrcptitem ON (aropen_id=cashrcptitem_aropen_id) "
                   "WHERE ( (aropen_id=:aropen_id)"
                   " AND (cashrcpt_id=:cashrcpt_id))" );
    query.bindValue(":aropen_id", _aropenid);
    query.bindValue(":cashrcpt_id", _cashrcptid);
    query.exec();
    if (query.first())
    {
      _cust->setId(query.value("aropen_cust_id").toInt());
      _docNumber->setText(query.value("aropen_docnumber").toString());
      _docType->setText(query.value("aropen_doctype").toString());
      _docDate->setDate(query.value("aropen_docdate").toDate(), true);
      _dueDate->setDate(query.value("aropen_duedate").toDate());
      _discountAmount->setLocalValue(query.value("discount").toDouble());
      _openAmount->set(query.value("f_amount").toDouble(),
                       query.value("cashrcpt_curr_id").toInt(),
                       query.value("cashrcpt_distdate").toDate(), false);
      _discount->setEnabled(query.value("aropen_doctype").toString() == "I" ||
                            query.value("aropen_doctype").toString() == "D");
    } 
  }
  else if (_mode == cEdit)
  {
    query.prepare( "SELECT aropen_cust_id, aropen_docnumber, aropen_doctype, "
                   "       aropen_docdate, aropen_duedate, "
                   "       currToCurr(aropen_curr_id, cashrcpt_curr_id, (aropen_amount - aropen_paid), "
                   "       cashrcpt_distdate) AS balance, "
                   "       ABS(cashrcptitem_amount) AS cashrcptitem_amount, "
                   "       cashrcpt_curr_id, cashrcpt_distdate,  "
                   "       ABS(cashrcptitem_discount) AS discount "
                   "FROM cashrcptitem, cashrcpt, aropen "
                   "WHERE ( (cashrcptitem_cashrcpt_id=cashrcpt_id)"
                   " AND (cashrcptitem_aropen_id=aropen_id)"
                   " AND (cashrcptitem_id=:cashrcptitem_id) );" );
    query.bindValue(":cashrcptitem_id", _cashrcptitemid);
    query.exec();
    if (query.first())
    {
      _cust->setId(query.value("aropen_cust_id").toInt());
      _docNumber->setText(query.value("aropen_docnumber").toString());
      _docType->setText(query.value("aropen_doctype").toString());
      _docDate->setDate(query.value("aropen_docdate").toDate(), true);
      _dueDate->setDate(query.value("aropen_duedate").toDate());
      _openAmount->set(query.value("balance").toDouble(),
		       query.value("cashrcpt_curr_id").toInt(),
                       query.value("cashrcpt_distdate").toDate(), false);
      _amountToApply->setLocalValue(query.value("cashrcptitem_amount").toDouble());
      _discountAmount->setLocalValue(query.value("discount").toDouble());
      _discount->setEnabled(query.value("aropen_doctype").toString() == "I" ||
                            query.value("aropen_doctype").toString() == "D");
    }
//  ToDo
  }
}
Esempio n. 19
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;
  }
}
Esempio n. 20
0
bool incident::save(bool partial)
{
  if (! partial)
  {
    if(_crmacct->id() == -1)
    {
      QMessageBox::critical( this, tr("Incomplete Information"),
        tr("You must specify the Account that this incident is for.") );
      return false;
    }

    if(_cntct->id() <= 0 && _cntct->name().simplified().isEmpty())
    {
      QMessageBox::critical( this, tr("Incomplete Information"),
        tr("You must specify a Contact for this Incident.") );
      return false;
    }

    if(_description->text().trimmed().isEmpty())
    {
      QMessageBox::critical( this, tr("Incomplete Information"),
        tr("You must specify a description for this incident report.") );
      _description->setFocus();
      return false;
    }

    if (_status->currentIndex() == 3 && _assignedTo->username().isEmpty())
    {
      QMessageBox::critical( this, tr("Incomplete Information"),
        tr("You must specify an assignee when the status is assigned.") );
      _description->setFocus();
      return false;
    }
  }

  RecurrenceWidget::RecurrenceChangePolicy cp = _recurring->getChangePolicy();
  if (cp == RecurrenceWidget::NoPolicy)
    return false;

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

  if (!q.exec("BEGIN"))
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  if (cNew == _mode && !_saved)
    q.prepare("INSERT INTO incdt"
              "      (incdt_id, incdt_number, incdt_crmacct_id, incdt_cntct_id,"
              "       incdt_summary, incdt_descrip, incdt_item_id,"
              "       incdt_status, incdt_assigned_username,"
              "       incdt_incdtcat_id, incdt_incdtseverity_id,"
              "       incdt_incdtpriority_id, incdt_incdtresolution_id,"
              "       incdt_ls_id, incdt_aropen_id, incdt_owner_username,"
              "       incdt_recurring_incdt_id) "
              "VALUES(:incdt_id, :incdt_number, :incdt_crmacct_id, :incdt_cntct_id,"
              "       :incdt_description, :incdt_notes, :incdt_item_id,"
              "       :incdt_status, :incdt_assigned_username,"
              "       :incdt_incdtcat_id, :incdt_incdtseverity_id,"
              "       :incdt_incdtpriority_id, :incdt_incdtresolution_id,"
              "       :incdt_ls_id, :incdt_aropen_id, :incdt_owner_username,"
              "       :incdt_recurring_incdt_id);" );
  else if (cEdit == _mode || _saved)
    q.prepare("UPDATE incdt"
              "   SET incdt_cntct_id=:incdt_cntct_id,"
              "       incdt_crmacct_id=:incdt_crmacct_id,"
              "       incdt_summary=:incdt_description,"
              "       incdt_descrip=:incdt_notes,"
              "       incdt_item_id=:incdt_item_id,"
              "       incdt_status=:incdt_status,"
              "       incdt_assigned_username=:incdt_assigned_username,"
              "       incdt_incdtcat_id=:incdt_incdtcat_id,"
              "       incdt_incdtpriority_id=:incdt_incdtpriority_id,"
              "       incdt_incdtseverity_id=:incdt_incdtseverity_id,"
              "       incdt_incdtresolution_id=:incdt_incdtresolution_id,"
              "       incdt_ls_id=:incdt_ls_id,"
              "       incdt_owner_username=:incdt_owner_username,"
              "       incdt_recurring_incdt_id=:incdt_recurring_incdt_id"
              " WHERE (incdt_id=:incdt_id); ");

  q.bindValue(":incdt_id", _incdtid);
  q.bindValue(":incdt_number", _number->text());
  q.bindValue(":incdt_owner_username", _owner->username());
  if (_crmacct->id() > 0)
    q.bindValue(":incdt_crmacct_id", _crmacct->id());
  if (_cntct->id() > 0)
    q.bindValue(":incdt_cntct_id", _cntct->id());
  q.bindValue(":incdt_description", _description->text().trimmed());
  q.bindValue(":incdt_notes", _notes->toPlainText().trimmed());
  if(-1 != _item->id())
    q.bindValue(":incdt_item_id", _item->id());
  q.bindValue(":incdt_assigned_username", _assignedTo->username());
  q.bindValue(":incdt_status", _statusCodes.at(_status->currentIndex()));
  if(_category->isValid())
    q.bindValue(":incdt_incdtcat_id", _category->id());
  if(_severity->isValid())
    q.bindValue(":incdt_incdtseverity_id", _severity->id());
  if(_priority->isValid())
    q.bindValue(":incdt_incdtpriority_id", _priority->id());
  if(_resolution->isValid())
    q.bindValue(":incdt_incdtresolution_id", _resolution->id());
  if ((_item->id() != -1) && (_lotserial->id() != -1))
    q.bindValue(":incdt_ls_id", _lotserial->id());
  if (_aropenid > 0)
    q.bindValue(":incdt_aropen_id", _aropenid);
  if (_recurring->isRecurring())
    q.bindValue(":incdt_recurring_incdt_id", _recurring->parentId());

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

  QString errmsg;
  if (! _recurring->save(true, cp, &errmsg))
  {
    rollback.exec();
    systemError(this, errmsg, __FILE__, __LINE__);
    return false;
  }

  q.exec("COMMIT;");
  if(q.lastError().type() != QSqlError::NoError)
  {
    rollback.exec();
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  _saved = true;
  return true;
}
Esempio n. 21
0
void createItemSitesByClassCode::sSave()
{
    if (_warehouse->id() == -1)
    {
        QMessageBox::critical( this, tr("Select a Site"),
                               tr( "You must select a Site for this Item Site before creating it.\n" ) );
        _warehouse->setFocus();
        return;
    }

    if ( (_metrics->boolean("InterfaceToGL")) && (_costcat->id() == -1) )
    {
        QMessageBox::critical( this, tr("Cannot Create Item Sites"),
                               tr("You must select a Cost Category for these Item Sites before you may create them.") );
        _costcat->setFocus();
        return;
    }

    if (_plannerCode->id() == -1)
    {
        QMessageBox::critical( this, tr("Cannot Create Item Sites"),
                               tr("You must select a Planner Code for these Item Sites before you may create them.") );
        _plannerCode->setFocus();
        return;
    }

    if (_controlMethod->currentItem() == -1)
    {
        QMessageBox::critical( this, tr("Cannot Create Item Sites"),
                               tr("You must select a Control Method for these Item Sites before you may create them.") );
        _controlMethod->setFocus();
        return;
    }

    if(!_costNone->isChecked() && !_costAvg->isChecked()
            && !_costStd->isChecked() && !_costJob->isChecked())
    {
        QMessageBox::critical(this, tr("Cannot Save Item Site"),
                              tr("<p>You must select a Cost Method for this "
                                 "Item Site before you may save it.") );
        return;
    }

    if (_stocked->isChecked() && _reorderLevel->toDouble() == 0)
    {
        QMessageBox::critical( this, tr("Cannot Save Item Site"),
                               tr("<p>You must set a reorder level "
                                  "for a stocked item before you may save it.") );
        _reorderLevel->setFocus();
        return;
    }

    if ( _locationControl->isChecked() )
    {
        XSqlQuery locationid;
        locationid.prepare( "SELECT location_id "
                            "FROM location "
                            "WHERE (location_warehous_id=:warehous_id)"
                            "LIMIT 1;" );
        locationid.bindValue(":warehous_id", _warehouse->id());
        locationid.exec();
        if (!locationid.first())
        {
            QMessageBox::critical( this, tr("Cannot Save Item Site"),
                                   tr( "You must first create at least one valid "
                                       "Location for this Site before items may be "
                                       "multiply located." ) );
            return;
        }
    }

    QString sql( "INSERT INTO itemsite "
                 "( itemsite_item_id,"
                 "  itemsite_warehous_id, itemsite_qtyonhand, itemsite_value,"
                 "  itemsite_useparams, itemsite_useparamsmanual,"
                 "  itemsite_reorderlevel, itemsite_ordertoqty,"
                 "  itemsite_minordqty, itemsite_maxordqty, itemsite_multordqty,"
                 "  itemsite_safetystock, itemsite_cyclecountfreq,"
                 "  itemsite_leadtime, itemsite_eventfence, itemsite_plancode_id, itemsite_costcat_id,"
                 "  itemsite_supply, itemsite_createpr, itemsite_createwo,"
                 "  itemsite_sold, itemsite_soldranking,"
                 "  itemsite_stocked,"
                 "  itemsite_controlmethod, itemsite_perishable, itemsite_active,"
                 "  itemsite_loccntrl, itemsite_location_id, itemsite_location,"
                 "  itemsite_location_comments, itemsite_notes,"
                 "  itemsite_abcclass, itemsite_freeze, itemsite_datelastused,"
                 "  itemsite_ordergroup, itemsite_mps_timefence, "
                 "  itemsite_autoabcclass, itemsite_costmethod ) "
                 "SELECT item_id,"
                 "       :warehous_id, 0.0, 0.0,"
                 "       :itemsite_useparams, :itemsite_useparamsmanual,"
                 "       :itemsite_reorderlevel, :itemsite_ordertoqty,"
                 "       :itemsite_minordqty, :itemsite_maxordqty, :itemsite_multordqty,"
                 "       :itemsite_safetystock, :itemsite_cyclecountfreq,"
                 "       :itemsite_leadtime, :itemsite_eventfence, :itemsite_plancode_id, :itemsite_costcat_id,"
                 "       :itemsite_supply, :itemsite_createpr, :itemsite_createwo,"
                 "       :itemsite_sold, :itemsite_soldranking,"
                 "       :itemsite_stocked,"
                 "       :itemsite_controlmethod, :itemsite_perishable, TRUE,"
                 "       :itemsite_loccntrl, :itemsite_location_id, :itemsite_location,"
                 "       :itemsite_location_comments, '',"
                 "       :itemsite_abcclass, FALSE, startOfTime(),"
                 "       :itemsite_ordergroup, :itemsite_mps_timefence, "
                 "       FALSE, CASE WHEN(item_type='R') THEN 'N' WHEN(item_type='J') THEN 'J' ELSE :itemsite_costmethod END "
                 "FROM item "
                 "WHERE ( (item_id NOT IN ( SELECT itemsite_item_id"
                 "                          FROM itemsite"
                 "                          WHERE (itemsite_warehous_id=:warehous_id) ) )" );

    if (_classCode->isSelected())
        sql += " AND (item_classcode_id=:classcode_id)";
    else if (_classCode->isPattern())
        sql += " AND (item_classcode_id IN (SELECT classcode_id FROM classcode WHERE (classcode_code ~ :classcode_pattern)))";

    sql += ");";

    q.prepare(sql);
    q.bindValue(":itemsite_reorderlevel", _reorderLevel->toDouble());
    q.bindValue(":itemsite_ordertoqty", _orderUpToQty->toDouble());
    q.bindValue(":itemsite_minordqty", _minimumOrder->toDouble());
    q.bindValue(":itemsite_maxordqty", _maximumOrder->toDouble());
    q.bindValue(":itemsite_multordqty", _orderMultiple->toDouble());
    q.bindValue(":itemsite_safetystock", _safetyStock->toDouble());
    q.bindValue(":itemsite_cyclecountfreq", _cycleCountFreq->value());
    q.bindValue(":itemsite_leadtime", _leadTime->value());
    q.bindValue(":itemsite_eventfence", _eventFence->value());
    q.bindValue(":itemsite_plancode_id", _plannerCode->id());
    q.bindValue(":itemsite_costcat_id", _costcat->id());
    q.bindValue(":itemsite_useparams", QVariant(_useParameters->isChecked(), 0));
    q.bindValue(":itemsite_useparamsmanual", QVariant(_useParametersOnManual->isChecked(), 0));
    q.bindValue(":itemsite_supply", QVariant(_supply->isChecked(), 0));
    q.bindValue(":itemsite_createpr", QVariant(_createPr->isChecked(), 0));
    q.bindValue(":itemsite_createwo", QVariant(_createWo->isChecked(), 0));
    q.bindValue(":itemsite_sold", QVariant(_sold->isChecked(), 0));
    q.bindValue(":itemsite_stocked", QVariant(_stocked->isChecked(), 0));
    q.bindValue(":itemsite_loccntrl", QVariant(_locationControl->isChecked(), 0));
    q.bindValue(":itemsite_perishable", QVariant(_perishable->isChecked(), 0));
    q.bindValue(":itemsite_soldranking", _soldRanking->value());
    q.bindValue(":itemsite_location_comments", _locationComments->text().stripWhiteSpace());
    q.bindValue(":itemsite_abcclass", _abcClass->currentText());

    q.bindValue(":itemsite_ordergroup", _orderGroup->value());
    q.bindValue(":itemsite_mps_timefence", _mpsTimeFence->value());

    if (_useDefaultLocation->isChecked())
    {
        if (_location->isChecked())
        {
            q.bindValue(":itemsite_location", "");
            q.bindValue(":itemsite_location_id", _locations->id());
        }
        else if (_miscLocation->isChecked())
        {
            q.bindValue(":itemsite_location", _miscLocationName->text().stripWhiteSpace());
            q.bindValue(":itemsite_location_id", -1);
        }
    }
    else
    {
        q.bindValue(":itemsite_location", "");
        q.bindValue(":itemsite_location_id", -1);
    }

    if (_controlMethod->currentItem() == 0)
        q.bindValue(":itemsite_controlmethod", "N");
    else if (_controlMethod->currentItem() == 1)
        q.bindValue(":itemsite_controlmethod", "R");
    else if (_controlMethod->currentItem() == 2)
        q.bindValue(":itemsite_controlmethod", "L");
    else if (_controlMethod->currentItem() == 3)
        q.bindValue(":itemsite_controlmethod", "S");

    if(_costNone->isChecked())
        q.bindValue(":itemsite_costmethod", "N");
    else if(_costAvg->isChecked())
        q.bindValue(":itemsite_costmethod", "A");
    else if(_costStd->isChecked())
        q.bindValue(":itemsite_costmethod", "S");
    else if(_costJob->isChecked())
        q.bindValue(":itemsite_costmethod", "J");

    q.bindValue(":warehous_id", _warehouse->id());
    _classCode->bindValue(q);
    q.exec();

    omfgThis->sItemsitesUpdated();

    accept();
}
void reconcileBankaccount::sReconcile()
{
  XSqlQuery reconcileReconcile;
  if(_bankrecid == -1)
  {
    QMessageBox::critical( this, tr("Cannot Reconcile Account"),
      tr("<p>There was an error trying to reconcile this account. "
         "Please contact your Systems Administrator.") );
    return;
  }

  if (!_startDate->isValid())
  {
    QMessageBox::warning( this, tr("Missing Opening Date"),
      tr("<p>No Opening Date was specified for this reconciliation. Please specify an Opening Date.") );
    _startDate->setFocus();
    return;
  }

  if (!_endDate->isValid())
  {
    QMessageBox::warning( this, tr("Missing Ending Date"),
      tr("<p>No Ending Date was specified for this reconciliation. Please specify an Ending Date.") );
    _endDate->setFocus();
    return;
  }

  if (_endDate->date() < _startDate->date())
  {
    QMessageBox::warning( this, tr("Invalid End Date"),
                           tr("The end date cannot be earlier than the start date.") );
    _endDate->setFocus();
    return;
  }

  if(!_datesAreOK)
  {
    QMessageBox::critical( this, tr("Dates already reconciled"),
                tr("The date range you have entered already has "
                   "reconciled dates in it. Please choose a different "
                   "date range.") );
    _startDate->setFocus();
    _datesAreOK = false;
    return;
  }

  double begBal = _openBal->localValue();
  double endBal = _endBal->localValue();

  // calculate cleared balance
  MetaSQLQuery mbal = mqlLoad("bankrec", "clearedbalance");
  ParameterList params;
  params.append("bankaccntid", _bankaccnt->id());
  params.append("bankrecid", _bankrecid);
  params.append("endBal", endBal);
  params.append("begBal", begBal);
  params.append("curr_id",   _currency->id());
  params.append("effective", _startDate->date());
  params.append("expires",   _endDate->date());
  XSqlQuery bal = mbal.toQuery(params);
  if(!bal.first())
  {
    systemError(this, bal.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if(bal.value("diff_value").toDouble() != 0.0)
  {
    QMessageBox::critical( this, tr("Balances Do Not Match"),
      tr("The cleared amounts do not balance with the specified\n"
         "beginning and ending balances.\n"
         "Please correct this before continuing.") );
    return;
  }

  if (! sSave(false))
    return;

  reconcileReconcile.prepare("SELECT postBankReconciliation(:bankrecid) AS result;");
  reconcileReconcile.bindValue(":bankrecid", _bankrecid);
  reconcileReconcile.exec();
  if (reconcileReconcile.first())
  {
    int result = reconcileReconcile.value("result").toInt();
    if (result < 0)
    {
      systemError(this, storedProcErrorLookup("postBankReconciliation", result),
		  __FILE__, __LINE__);
      return;
    }
    _bankrecid = -1;
    close();
  }
  else if (reconcileReconcile.lastError().type() != QSqlError::NoError)
  {
    systemError(this, reconcileReconcile.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
enum SetResponse purchaseOrderItem::set(const ParameterList &pParams)
{
  XSqlQuery purchaseet;
  XDialog::set(pParams);
  QVariant param;
  bool     valid;
  bool     haveQty  = FALSE;
  bool     haveDate = FALSE;



  param = pParams.value("vend_id", &valid);
  if (valid)
    _vendid = param.toInt();

  param = pParams.value("warehous_id", &valid);
  if (valid)
    _preferredWarehouseid = param.toInt();

  param = pParams.value("dropship", &valid);
  if (valid)
    _dropship = param.toBool();

  param = pParams.value("parentWo", &valid);
  if (valid)
    _parentwo = param.toInt();

  param = pParams.value("parentSo", &valid);
  if (valid)
    _parentso = param.toInt();

  if (_metrics->boolean("CopyPRtoPOItem"))
  {
    param = pParams.value("pr_releasenote", &valid);
    if(valid)
      _notes->setText(param.toString());
  }

  param = pParams.value("pohead_id", &valid);
  if (valid)
  {
    _poheadid = param.toInt();

    purchaseet.prepare( "SELECT pohead_taxzone_id, pohead_number, pohead_orderdate, pohead_status, " // pohead_taxzone_id added
               "       vend_id, vend_restrictpurch, pohead_curr_id "
               "FROM pohead, vendinfo "
               "WHERE ( (pohead_vend_id=vend_id)"
               " AND (pohead_id=:pohead_id) );" );
    purchaseet.bindValue(":pohead_id", param.toInt());
    purchaseet.exec();
    if (purchaseet.first())
    {
      _poNumber->setText(purchaseet.value("pohead_number").toString());
      _poStatus = purchaseet.value("pohead_status").toString();
      _unitPrice->setEffective(purchaseet.value("pohead_orderdate").toDate());
      _unitPrice->setId(purchaseet.value("pohead_curr_id").toInt());
	  _taxzoneid=purchaseet.value("pohead_taxzone_id").toInt();   // added  to pick up tax zone id.
	  _tax->setEffective(purchaseet.value("pohead_orderdate").toDate());
      _tax->setId(purchaseet.value("pohead_curr_id").toInt());

      if (purchaseet.value("vend_restrictpurch").toBool())
      {
        _item->setQuery( QString( "SELECT DISTINCT item_id, item_number, item_descrip1, item_descrip2,"
                                  "                (item_descrip1 || ' ' || item_descrip2) AS itemdescrip,"
                                  "                uom_name, item_type, item_config, item_active, item_upccode "
                                  "FROM item, itemsite, itemsrc, uom  "
                                  "WHERE ( (itemsite_item_id=item_id)"
                                  " AND (itemsrc_item_id=item_id)"
                                  " AND (item_inv_uom_id=uom_id)"
                                  " AND (itemsite_active)"
                                  " AND (item_active)"
                                  " AND (itemsrc_active)"
                                  " AND (itemsrc_vend_id=%1) ) "
                                  "ORDER BY item_number" )
                         .arg(purchaseet.value("vend_id").toInt()) );
        _item->setValidationQuery( QString( "SELECT DISTINCT item_id, item_number, item_descrip1, item_descrip2,"
                                            "                (item_descrip1 || ' ' || item_descrip2) AS itemdescrip,"
                                            "                uom_name, item_type, item_config, item_active, item_upccode "
                                            "FROM item, itemsite, itemsrc, uom  "
                                            "WHERE ( (itemsite_item_id=item_id)"
                                            " AND (itemsrc_item_id=item_id)"
                                            " AND (item_inv_uom_id=uom_id)"
                                            " AND (itemsite_active)"
                                            " AND (item_active)"
                                            " AND (itemsrc_active)"
                                            " AND (itemsrc_vend_id=%1) "
                                            " AND (itemsite_item_id=:item_id) ) ")
                                   .arg(purchaseet.value("vend_id").toInt()) );
      }
      else
      {
        _item->setType(ItemLineEdit::cGeneralPurchased | ItemLineEdit::cGeneralManufactured |
		               ItemLineEdit::cTooling | ItemLineEdit::cActive);
        _item->setDefaultType(ItemLineEdit::cGeneralPurchased | ItemLineEdit::cActive);
      }
    }
    else
    {
      systemError(this, tr("A System Error occurred at %1::%2.")
                        .arg(__FILE__)
                        .arg(__LINE__) );
      return UndefinedError;
    }
  }

  param = pParams.value("poitem_id", &valid);
  if (valid)
  {
    _poitemid = param.toInt();

    purchaseet.prepare( "SELECT pohead_number, pohead_id "
               "FROM pohead, poitem "
               "WHERE ( (pohead_id=poitem_pohead_id) "
               " AND (poitem_id=:poitem_id) );" );
    purchaseet.bindValue(":poitem_id", param.toInt());
    purchaseet.exec();
    if (purchaseet.first())
    {
      _poNumber->setText(purchaseet.value("pohead_number").toString());
	  _poheadid = purchaseet.value("pohead_id").toInt();
    }

    populate();
	sCalculateTax();
  }
  // connect here and not in the .ui to avoid timing issues at initialization
  connect(_unitPrice, SIGNAL(valueChanged()), this, SLOT(sPopulateExtPrice()));

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;
      _save->setEnabled(false);

      purchaseet.exec("SELECT NEXTVAL('poitem_poitem_id_seq') AS poitem_id;");
      if (purchaseet.first())
        _poitemid = purchaseet.value("poitem_id").toInt();
      else
      {
        systemError(this, tr("A System Error occurred at %1::%2.")
                          .arg(__FILE__)
                          .arg(__LINE__) );
        return UndefinedError;
      }

      if(_parentwo != -1)
      {
        purchaseet.prepare("SELECT wo_number"
                  "  FROM womatl JOIN wo ON (wo_id=womatl_wo_id)"
                  " WHERE (womatl_id=:parentwo); ");
        purchaseet.bindValue(":parentwo", _parentwo);
        purchaseet.exec();
        if(purchaseet.first())
        {
          _so->setText(purchaseet.value("wo_number").toString());
          _soLine->setText("");
        }
      }

      if(_parentso != -1)
      {
        purchaseet.prepare( "INSERT INTO charass"
                   "      (charass_target_type, charass_target_id,"
                   "       charass_char_id, charass_value) "
                   "SELECT 'PI', :orderid, charass_char_id, charass_value"
                   "  FROM charass"
                   " WHERE ((charass_target_type='SI')"
                   "   AND  (charass_target_id=:soitem_id));");
        purchaseet.bindValue(":orderid", _poitemid);
        purchaseet.bindValue(":soitem_id", _parentso);
        purchaseet.exec();
      }

      purchaseet.prepare( "SELECT (COALESCE(MAX(poitem_linenumber), 0) + 1) AS _linenumber "
                 "FROM poitem "
                 "WHERE (poitem_pohead_id=:pohead_id);" );
      purchaseet.bindValue(":pohead_id", _poheadid);
      purchaseet.exec();
      if (purchaseet.first())
        _lineNumber->setText(purchaseet.value("_linenumber").toString());
      else
      {
        systemError(this, tr("A System Error occurred at %1::%2.")
                          .arg(__FILE__)
                          .arg(__LINE__) );

        return UndefinedError;
      }

      _bomRevision->setEnabled(_privileges->boolean("UseInactiveRevisions"));
      _booRevision->setEnabled(_privileges->boolean("UseInactiveRevisions"));
      _comments->setId(_poitemid);
      _tab->setTabEnabled(_tab->indexOf(_demandTab), FALSE);
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;

      _typeGroup->setEnabled(FALSE);
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _typeGroup->setEnabled(FALSE);
      _vendorItemNumber->setEnabled(FALSE);
      _vendorItemNumberList->setEnabled(FALSE);
      _vendorDescrip->setEnabled(FALSE);
      _warehouse->setEnabled(FALSE);
      _dueDate->setEnabled(FALSE);
      _ordered->setEnabled(FALSE);
      _unitPrice->setEnabled(FALSE);
      _freight->setEnabled(FALSE);
      _notes->setReadOnly(TRUE);
      _comments->setReadOnly(TRUE);
      _project->setEnabled(FALSE);
      _taxtype->setEnabled(FALSE);
      _taxRecoverable->setEnabled(FALSE);
      _bomRevision->setEnabled(FALSE);
      _booRevision->setEnabled(FALSE);

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

  param = pParams.value("itemsite_id", &valid);
  if (valid)
  {
    _item->setItemsiteid(param.toInt());
    _item->setEnabled(FALSE);
    _warehouse->setEnabled(FALSE);
  }
  
  param = pParams.value("itemsrc_id", &valid);
  if (valid)
    sPopulateItemSourceInfo(param.toInt());

  param = pParams.value("qty", &valid);
  if (valid)
  {
    _ordered->setDouble((param.toDouble()/_invVendUOMRatio));

    if (_item->isValid())
      sDeterminePrice();

    haveQty = TRUE;
  }

  param = pParams.value("dueDate", &valid);
  if (valid)
  {
    _dueDate->setDate(param.toDate());
    haveDate = TRUE;
  }

  param = pParams.value("prj_id", &valid);
  if (valid)
    _project->setId(param.toInt());

  if(_parentso != -1)
  {
    purchaseet.prepare("SELECT cohead_number, coitem_linenumber, coitem_prcost"
              "  FROM coitem JOIN cohead ON (cohead_id=coitem_cohead_id)"
              " WHERE (coitem_id=:parentso); ");
    purchaseet.bindValue(":parentso", _parentso);
    purchaseet.exec();
    if(purchaseet.first())
    {
      _so->setText(purchaseet.value("cohead_number").toString());
      _soLine->setText(purchaseet.value("coitem_linenumber").toString());
      if(purchaseet.value("coitem_prcost").toDouble() > 0)
      {
        _overriddenUnitPrice = true;
        _unitPrice->setLocalValue(purchaseet.value("coitem_prcost").toDouble());
        sPopulateExtPrice();
      }
    }
  }

  param = pParams.value("captive", &valid);
  if (valid)
    _captive = true;
  
  return NoError;
}
void reconcileBankaccount::sReceiptsToggleCleared()
{
  XSqlQuery reconcileReceiptsToggleCleared;
  XTreeWidgetItem *item = (XTreeWidgetItem*)_receipts->currentItem();
  XTreeWidgetItem *child = 0;
  bool setto = true;

  if(0 == item)
    return;

  _receipts->scrollToItem(item);

  if(item->altId() == 9)
  {
    setto = item->text(0) == tr("No");
    for (int i = 0; i < item->childCount(); i++)
    {
      child = item->child(i);
      if(child->text(0) != (setto ? tr("Yes") : tr("No")))
      {
        double rate = QLocale().toDouble(child->text(6));
        double baseamount = QLocale().toDouble(child->text(7));
        double amount = QLocale().toDouble(child->text(8));

        if (_allowEdit->isChecked() && child->text(0) != tr("Yes"))
        {
          ParameterList params;
          params.append("transtype", "receipt");
          params.append("bankaccntid", _bankaccnt->id());
          params.append("bankrecid", _bankrecid);
          params.append("sourceid", child->id());
          if(child->altId()==1)
            params.append("source", "GL");
          else if(child->altId()==2)
            params.append("source", "SL");
          else if(child->altId()==3)
            params.append("source", "AD");
          toggleBankrecCleared newdlg(this, "", TRUE);
          newdlg.set(params);
          newdlg.exec();
        }
        else
        {
          reconcileReceiptsToggleCleared.prepare("SELECT toggleBankrecCleared(:bankrecid, :source, :sourceid, :currrate, :amount) AS cleared");
          reconcileReceiptsToggleCleared.bindValue(":bankrecid", _bankrecid);
          reconcileReceiptsToggleCleared.bindValue(":sourceid", child->id());
          if(child->altId()==1)
            reconcileReceiptsToggleCleared.bindValue(":source", "GL");
          else if(child->altId()==2)
            reconcileReceiptsToggleCleared.bindValue(":source", "SL");
          else if(child->altId()==3)
            reconcileReceiptsToggleCleared.bindValue(":source", "AD");
          reconcileReceiptsToggleCleared.bindValue(":currrate", rate);
          reconcileReceiptsToggleCleared.bindValue(":amount", amount);
          reconcileReceiptsToggleCleared.exec();
          if(reconcileReceiptsToggleCleared.first())
            child->setText(0, (reconcileReceiptsToggleCleared.value("cleared").toBool() ? tr("Yes") : tr("No") ));
          else if (reconcileReceiptsToggleCleared.lastError().type() != QSqlError::NoError)
          {
            systemError(this, reconcileReceiptsToggleCleared.lastError().databaseText(), __FILE__, __LINE__);
            return;
          }
        }
      }
    }
    item->setText(0, (setto ? tr("Yes") : tr("No")));
    populate();
  }
  else
  {
    double rate = QLocale().toDouble(item->text(6));
    double baseamount = QLocale().toDouble(item->text(7));
    double amount = QLocale().toDouble(item->text(8));
    
    if (_allowEdit->isChecked() && item->text(0) != tr("Yes"))
    {
      ParameterList params;
      params.append("transtype", "receipt");
      params.append("bankaccntid", _bankaccnt->id());
      params.append("bankrecid", _bankrecid);
      params.append("sourceid", item->id());
      if(item->altId()==1)
        params.append("source", "GL");
      else if(item->altId()==2)
        params.append("source", "SL");
      else if(item->altId()==3)
        params.append("source", "AD");
      toggleBankrecCleared newdlg(this, "", TRUE);
      newdlg.set(params);
      newdlg.exec();
      populate();
    }
    else
    {
      reconcileReceiptsToggleCleared.prepare("SELECT toggleBankrecCleared(:bankrecid, :source, :sourceid, :currrate, :amount) AS cleared");
      reconcileReceiptsToggleCleared.bindValue(":bankrecid", _bankrecid);
      reconcileReceiptsToggleCleared.bindValue(":sourceid", item->id());
      if(item->altId()==1)
        reconcileReceiptsToggleCleared.bindValue(":source", "GL");
      else if(item->altId()==2)
        reconcileReceiptsToggleCleared.bindValue(":source", "SL");
      else if(item->altId()==3)
        reconcileReceiptsToggleCleared.bindValue(":source", "AD");
      reconcileReceiptsToggleCleared.bindValue(":currrate", rate);
      reconcileReceiptsToggleCleared.bindValue(":amount", amount);
      reconcileReceiptsToggleCleared.exec();
      if(reconcileReceiptsToggleCleared.first())
      {
        item->setText(0, (reconcileReceiptsToggleCleared.value("cleared").toBool() ? tr("Yes") : tr("No") ));

        item = (XTreeWidgetItem*)item->QTreeWidgetItem::parent();
        if(item != 0 && item->altId() == 9)
        {
          setto = true;
          for (int i = 0; i < item->childCount(); i++)
          {
            setto = (setto && (item->child(i)->text(0) == tr("Yes")));
          }
          item->setText(0, (setto ? tr("Yes") : tr("No")));
        }
      }
      else
      {
        populate();
        if (reconcileReceiptsToggleCleared.lastError().type() != QSqlError::NoError)
        {
          systemError(this, reconcileReceiptsToggleCleared.lastError().databaseText(), __FILE__, __LINE__);
          return;
        }
      }
    }
  }
}
void purchaseOrderItem::sSave()
{
  QList<GuiErrorCheck> errors;
  errors << GuiErrorCheck(!_inventoryItem->isChecked() && _expcat->id() == -1, _expcat,
                          tr("<p>You must specify an Expense Category for this non-Inventory Item before you may save."))
         << GuiErrorCheck(_inventoryItem->isChecked() && !_item->isValid(), _item,
                          tr("<p>You must select an Item Number before you may save."))
         << GuiErrorCheck(_inventoryItem->isChecked() && _warehouse->id() == -1, _warehouse,
                          tr("<p>You must select a Supplying Site before you may save."))
         << GuiErrorCheck(!_dueDate->isValid(), _dueDate,
                          tr("<p>You must enter a due date before you may save this Purchase Order Item."))
         << GuiErrorCheck(_metrics->boolean("RequirePOTax") && !_taxtype->isValid(), _taxtype,
                          tr("<p>You must select a Tax Type before you may save." ))
         << GuiErrorCheck(_so->text().length() == 0 && _costmethod == "J", _item,
                          tr("<p>You may not purchase a Job Item without an associated demand."))
         << GuiErrorCheck(!_project->isValid() && _metrics->boolean("RequireProjectAssignment"), _project,
                          tr("<p>You must enter a Project for this order item before you may save it."))
     ;

  if (GuiErrorCheck::reportErrors(this, tr("Cannot Save Purchase Order Item"), errors))
    return;

  XSqlQuery purchaseSave;
  if (_ordered->toDouble() == 0.0)
  {
    if (QMessageBox::critical( this, tr("Zero Order Quantity"),
                               tr( "<p>The quantity that you are ordering is zero. "
                                   "<p>Do you wish to Continue or Change the Order Qty?" ),
                               QString("&Continue"), QString("Change Order &Qty."), QString::null, 1, 1 ) == 1)
    {
      _ordered->setFocus();
      return;
    }
  }

  if (_ordered->toDouble() < _minimumOrder)
  {
    if (QMessageBox::critical( this, tr("Invalid Order Quantity"),
                               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. "
                                   "<p>Do you wish to Continue or Change the Order Qty?" ),
                               QString("&Continue"), QString("Change Order &Qty."), QString::null, 1, 1 ) == 1)
    {
      _ordered->setFocus();
      return;
    }
  }

  if ((int)_orderMultiple)
  {
    if (qRound(_ordered->toDouble()) % (int)_orderMultiple)
    {
      if (QMessageBox::critical( this, tr("Invalid Order Quantity"),
                                 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. "
                                     "<p>Do you wish to Continue or Change the Order Qty?" ),
                                 QString("&Continue"), QString("Change Order &Qty."), QString::null, 1, 1 ) == 1)
      {
        _ordered->setFocus();
        return;
      }
    }
  }

  if (_unitPrice->baseValue() > _maxCost && _maxCost > 0.0)
  {
    if (QMessageBox::critical( this, tr("Invalid Unit Price"),
                               tr( "<p>The Unit Price is above the Maximum Desired Cost for this Item."
                                   "<p>Do you wish to Continue or Change the Unit Price?" ),
                               QString("&Continue"), QString("Change Unit &Price."), QString::null, 1, 1 ) == 1)
    {
      _unitPrice->setFocus();
      return;
    }
  }

  if (_dueDate->date() < _earliestDate->date())
  {
    if (QMessageBox::critical( this, tr("Invalid Due Date "),
                               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. "
                                   "<p>Do you wish to Continue or Change the Due Date?" ),
                               QString("&Continue"), QString("Change Order &Due Date"), QString::null, 1, 1 ) == 1)
    {
      _dueDate->setFocus();
      return;
    }
  }

  if (_mode == cNew)
  {
    purchaseSave.prepare( "INSERT INTO poitem "
               "( poitem_id, poitem_pohead_id, poitem_status, poitem_linenumber,"
               "  poitem_taxtype_id, poitem_tax_recoverable,"
               "  poitem_itemsite_id, poitem_expcat_id,"
               "  poitem_itemsrc_id, poitem_vend_item_number, poitem_vend_item_descrip,"
               "  poitem_vend_uom, poitem_invvenduomratio,"
               "  poitem_qty_ordered,"
               "  poitem_unitprice, poitem_freight, poitem_duedate, "
               "  poitem_bom_rev_id, poitem_boo_rev_id, "
               "  poitem_comments, poitem_prj_id, poitem_stdcost, poitem_manuf_name, "
               "  poitem_manuf_item_number, poitem_manuf_item_descrip, poitem_rlsd_duedate ) "
               "VALUES "
               "( :poitem_id, :poitem_pohead_id, :status, :poitem_linenumber,"
               "  :poitem_taxtype_id, :poitem_tax_recoverable,"
               "  :poitem_itemsite_id, :poitem_expcat_id,"
               "  :poitem_itemsrc_id, :poitem_vend_item_number, :poitem_vend_item_descrip,"
               "  :poitem_vend_uom, :poitem_invvenduomratio,"
               "  :poitem_qty_ordered,"
               "  :poitem_unitprice, :poitem_freight, :poitem_duedate, "
               "  :poitem_bom_rev_id, :poitem_boo_rev_id, "
               "  :poitem_comments, :poitem_prj_id, stdcost(:item_id), :poitem_manuf_name, "
               "  :poitem_manuf_item_number, :poitem_manuf_item_descrip, :poitem_duedate) ;" );

    purchaseSave.bindValue(":status", _poStatus);
    purchaseSave.bindValue(":item_id", _item->id());

    if (_inventoryItem->isChecked())
    {
      XSqlQuery itemsiteid;
      itemsiteid.prepare( "SELECT itemsite_id "
                          "FROM itemsite "
                          "WHERE ( (itemsite_item_id=:item_id)"
                          " AND (itemsite_warehous_id=:warehous_id) );" );
      itemsiteid.bindValue(":item_id", _item->id());
      itemsiteid.bindValue(":warehous_id", _warehouse->id());
      itemsiteid.exec();
      if (itemsiteid.first())
        purchaseSave.bindValue(":poitem_itemsite_id", itemsiteid.value("itemsite_id").toInt());
      else
      {
        QMessageBox::critical( this, tr("Invalid Item/Site"),
                               tr("<p>The Item and Site you have selected does not appear to be a valid combination. "
                                  "Make sure you have a Site selected and that there is a valid itemsite for "
                                  "this Item and Site combination.") );
        return;
      }
    }
    else
    {
      purchaseSave.bindValue(":poitem_expcat_id", _expcat->id());
    }
  }
  else if (_mode == cEdit)
    purchaseSave.prepare( "UPDATE poitem "
               "SET poitem_itemsrc_id=:poitem_itemsrc_id,"   
               "    poitem_taxtype_id=:poitem_taxtype_id,"
               "    poitem_tax_recoverable=:poitem_tax_recoverable,"
               "    poitem_vend_item_number=:poitem_vend_item_number,"
               "    poitem_vend_item_descrip=:poitem_vend_item_descrip,"
               "    poitem_vend_uom=:poitem_vend_uom, poitem_invvenduomratio=:poitem_invvenduomratio,"
               "    poitem_qty_ordered=:poitem_qty_ordered, poitem_unitprice=:poitem_unitprice,"
               "    poitem_freight=:poitem_freight,"
               "    poitem_duedate=:poitem_duedate, poitem_comments=:poitem_comments,"
               "    poitem_prj_id=:poitem_prj_id, "
               "    poitem_bom_rev_id=:poitem_bom_rev_id, "
               "    poitem_boo_rev_id=:poitem_boo_rev_id, "
               "    poitem_manuf_name=:poitem_manuf_name, "
               "    poitem_manuf_item_number=:poitem_manuf_item_number, "
               "    poitem_manuf_item_descrip=:poitem_manuf_item_descrip "
               "WHERE (poitem_id=:poitem_id);" );

  purchaseSave.bindValue(":poitem_id", _poitemid);
  if (_taxtype->id() != -1)
    purchaseSave.bindValue(":poitem_taxtype_id", _taxtype->id());
  purchaseSave.bindValue(":poitem_tax_recoverable", QVariant(_taxRecoverable->isChecked()));
  purchaseSave.bindValue(":poitem_pohead_id", _poheadid);
  purchaseSave.bindValue(":poitem_linenumber", _lineNumber->text().toInt());
  if (_itemsrcid != -1)
    purchaseSave.bindValue(":poitem_itemsrc_id", _itemsrcid);
  purchaseSave.bindValue(":poitem_vend_item_number", _vendorItemNumber->text());
  purchaseSave.bindValue(":poitem_vend_item_descrip", _vendorDescrip->toPlainText());
  purchaseSave.bindValue(":poitem_vend_uom", _vendorUOM->text());
  purchaseSave.bindValue(":poitem_invvenduomratio", _invVendorUOMRatio->toDouble());
  purchaseSave.bindValue(":poitem_qty_ordered", _ordered->toDouble());
  purchaseSave.bindValue(":poitem_unitprice", _unitPrice->localValue());
  purchaseSave.bindValue(":poitem_freight", _freight->localValue());
  purchaseSave.bindValue(":poitem_duedate", _dueDate->date());
  purchaseSave.bindValue(":poitem_manuf_name", _manufName->currentText());
  purchaseSave.bindValue(":poitem_manuf_item_number", _manufItemNumber->text());
  purchaseSave.bindValue(":poitem_manuf_item_descrip", _manufItemDescrip->toPlainText());
  purchaseSave.bindValue(":poitem_comments", _notes->toPlainText());
  if (_project->isValid())
    purchaseSave.bindValue(":poitem_prj_id", _project->id());
  if (_metrics->boolean("RevControl"))
  {
    purchaseSave.bindValue(":poitem_bom_rev_id", _bomRevision->id());
    purchaseSave.bindValue(":poitem_boo_rev_id", _booRevision->id());
  }
  purchaseSave.exec();
  if (purchaseSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, purchaseSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (_parentwo != -1)
  {
    purchaseSave.prepare("UPDATE poitem SET poitem_order_id=:parentwo, poitem_order_type='W' WHERE (poitem_id=:poitem_id);");
    purchaseSave.bindValue(":parentwo", _parentwo);
    purchaseSave.bindValue(":poitem_id", _poitemid);
    purchaseSave.exec();
  }

  if (_parentso != -1)
  {
    purchaseSave.prepare("UPDATE poitem SET poitem_order_id=:parentso, poitem_order_type='S' WHERE (poitem_id=:poitem_id);");
    purchaseSave.bindValue(":parentso", _parentso);
    purchaseSave.bindValue(":poitem_id", _poitemid);
    purchaseSave.exec();
    purchaseSave.prepare("UPDATE coitem SET coitem_order_id=:poitem_id, coitem_order_type='P' WHERE (coitem_id=:parentso);");
    purchaseSave.bindValue(":parentso", _parentso);
    purchaseSave.bindValue(":poitem_id", _poitemid);
    purchaseSave.exec();
  }

  if ( _mode != cView )
  {
    purchaseSave.prepare("SELECT updateCharAssignment('PI', :target_id, :char_id, :char_value);");

    QModelIndex idx1, idx2;
    for(int i = 0; i < _itemchar->rowCount(); i++)
    {
      idx1 = _itemchar->index(i, 0);
      idx2 = _itemchar->index(i, 1);
      purchaseSave.bindValue(":target_id", _poitemid);
      purchaseSave.bindValue(":char_id", _itemchar->data(idx1, Qt::UserRole));
      purchaseSave.bindValue(":char_value", _itemchar->data(idx2, Qt::DisplayRole));
      purchaseSave.exec();
    }
  }

  
  if (cNew == _mode && !_captive)
  {
    clear();
    prepare();
    _item->setFocus();
  }
  else
    done(_poitemid);
}
void reconcileBankaccount::sBankaccntChanged()
{
  XSqlQuery reconcileBankaccntChanged;
  if(_bankrecid != -1)
  {
    reconcileBankaccntChanged.prepare("SELECT count(*) AS num"
	          "  FROM bankrecitem"
	          " WHERE (bankrecitem_bankrec_id=:bankrecid); ");
    reconcileBankaccntChanged.bindValue(":bankrecid", _bankrecid);
    reconcileBankaccntChanged.exec();
    if (reconcileBankaccntChanged.first() && reconcileBankaccntChanged.value("num").toInt() > 0)
    {
      if (QMessageBox::question(this, tr("Save Bank Reconciliation?"),
				                      tr("<p>Do you want to save this Bank Reconciliation?"),
				                QMessageBox::No,
				                QMessageBox::Yes | QMessageBox::Default) == QMessageBox::Yes)
      {
	    sSave(false);
      }
      else
	  {
        reconcileBankaccntChanged.prepare( "SELECT deleteBankReconciliation(:bankrecid) AS result;" );
        reconcileBankaccntChanged.bindValue(":bankrecid", _bankrecid);
        reconcileBankaccntChanged.exec();
        if (reconcileBankaccntChanged.first())
        {
	      int result = reconcileBankaccntChanged.value("result").toInt();
	      if (result < 0)
	      {
	        systemError(this, storedProcErrorLookup("deleteBankReconciliation", result),
		                __FILE__, __LINE__);
	        return;
	      }
        }
        else if (reconcileBankaccntChanged.lastError().type() != QSqlError::NoError)
        {
	      systemError(this, reconcileBankaccntChanged.lastError().databaseText(), __FILE__, __LINE__);
	      return;
        }
      }
	}
  }

  _bankaccntid = _bankaccnt->id();
  XSqlQuery accntq;
  accntq.prepare("SELECT bankaccnt_curr_id "
            "FROM bankaccnt WHERE bankaccnt_id = :accntId;");
  accntq.bindValue(":accntId", _bankaccnt->id());
  accntq.exec();
  if (accntq.first())
    _currency->setId(accntq.value("bankaccnt_curr_id").toInt());
  else if (accntq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, accntq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  accntq.prepare("SELECT * FROM bankrec "
		 "WHERE ((bankrec_bankaccnt_id=:accntId)"
		 "  AND  (NOT bankrec_posted));");
  accntq.bindValue(":accntId", _bankaccnt->id());
  accntq.exec();
  if (accntq.first())
  {
    _bankrecid = accntq.value("bankrec_id").toInt();
    _startDate->setDate(accntq.value("bankrec_opendate").toDate(), true);
    _endDate->setDate(accntq.value("bankrec_enddate").toDate(), true);
    _openBal->setLocalValue(accntq.value("bankrec_openbal").toDouble());
    _endBal->setLocalValue(accntq.value("bankrec_endbal").toDouble());
  }
  else if (accntq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, accntq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
  else
  {
    accntq.prepare("SELECT NEXTVAL('bankrec_bankrec_id_seq') AS bankrec_id");
    accntq.exec();
    if (accntq.first())
      _bankrecid = accntq.value("bankrec_id").toInt();
    else if (accntq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, accntq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    
    accntq.prepare("SELECT bankrec_enddate + 1 AS startdate, "
                   " bankrec_endbal AS openbal "
                   "FROM bankrec "
                   "WHERE (bankrec_bankaccnt_id=:accntId) "
                   "ORDER BY bankrec_enddate DESC "
                   "LIMIT 1");
    accntq.bindValue(":accntId", _bankaccnt->id());
    accntq.exec();
    if (accntq.first())
    {
      _startDate->setDate(accntq.value("startdate").toDate());
      _openBal->setLocalValue(accntq.value("openbal").toDouble());
    }
    else
    {
      _startDate->clear();
      _openBal->clear();
    }
    if (accntq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, accntq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }

  populate();
}
Esempio n. 27
0
void purchaseOrder::populate()
{
  XSqlQuery po;
  po.prepare( "SELECT pohead_number, COALESCE(pohead_warehous_id,-1) AS pohead_warehous_id, "
              "       pohead_orderdate, pohead_status, pohead_printed, "
              "       pohead_shipvia, pohead_comments,"
              "       pohead_fob, COALESCE(pohead_terms_id,-1) AS pohead_terms_id, "
              "       COALESCE(pohead_vend_id,-1) AS pohead_vend_id,"
              "       pohead_tax, pohead_freight,"
              "       pohead_agent_username,"
              "       vend_name, vend_address1, vend_address2, vend_address3,"
              "       vend_city, vend_state, vend_zip, vend_country,"
              "       COALESCE(vendaddr_id, -1) AS vendaddrid,"
              "       vendaddr_code, vendaddr_name, vendaddr_address1, vendaddr_address2,"
              "       vendaddr_address3, vendaddr_city, vendaddr_state, vendaddr_zipcode,"
              "       vendaddr_country, pohead_curr_id, vend_emailpodelivery "
              "FROM vend, pohead LEFT OUTER JOIN vendaddr ON (pohead_vendaddr_id=vendaddr_id) "
              "WHERE ( (pohead_vend_id=vend_id)"
              " AND (pohead_id=:pohead_id) );" );
  po.bindValue(":pohead_id", _poheadid);
  po.exec();
  if (po.first())
  {
    _orderNumber->setText(po.value("pohead_number"));
    _warehouse->setId(po.value("pohead_warehous_id").toInt());
    _orderDate->setDate(po.value("pohead_orderdate").toDate(), true);
    _agent->setText(po.value("pohead_agent_username").toString());
    _status->setText(po.value("pohead_status").toString());
    _printed = po.value("pohead_printed").toBool();
    _terms->setId(po.value("pohead_terms_id").toInt());
    _shipVia->setText(po.value("pohead_shipvia"));
    _fob->setText(po.value("pohead_fob"));
    _notes->setText(po.value("pohead_comments").toString());

    _vendaddrid = po.value("vendaddrid").toInt();
    if (_vendaddrid == -1)
    {
      _vendaddrCode->setText(tr("Main"));
      _vendaddrName->setText(po.value("vend_name"));
      _vendaddrAddr1->setText(po.value("vend_address1"));
      _vendaddrAddr2->setText(po.value("vend_address2"));
      _vendaddrAddr3->setText(po.value("vend_address3"));
      _vendaddrCity->setText(po.value("vend_city"));
      _vendaddrState->setText(po.value("vend_state"));
      _vendaddrZipCode->setText(po.value("vend_zip"));
      _vendaddrCountry->setText(po.value("vend_country"));
    }
    else
    {
      _vendaddrCode->setText(po.value("vendaddr_code"));
      _vendaddrName->setText(po.value("vendaddr_name"));
      _vendaddrAddr1->setText(po.value("vendaddr_address1"));
      _vendaddrAddr2->setText(po.value("vendaddr_address2"));
      _vendaddrAddr3->setText(po.value("vendaddr_address3"));
      _vendaddrCity->setText(po.value("vendaddr_city"));
      _vendaddrState->setText(po.value("vendaddr_state"));
      _vendaddrZipCode->setText(po.value("vendaddr_zipcode"));
      _vendaddrCountry->setText(po.value("vendaddr_country"));
    }

    _comments->setId(_poheadid);
    _vendor->setId(po.value("pohead_vend_id").toInt());
    _vendEmail = po.value("vend_emailpodelivery").toBool();
    _poCurrency->setId(po.value("pohead_curr_id").toInt());
    _tax->setLocalValue(po.value("pohead_tax").toDouble());
    _freight->setLocalValue(po.value("pohead_freight").toDouble());
  }

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

  param = pParams.value("itemloc_series", &valid);
  if (valid)
    _itemlocSeries = param.toInt();

  param = pParams.value("itemlocdist_id", &valid);
  if (valid)
  {
    _itemlocdistid = param.toInt();

    q.prepare( "SELECT item_fractional, itemsite_controlmethod, itemsite_item_id,"
	       "       itemsite_id, itemsite_perishable, itemsite_warrpurc, "
               "       invhist_transtype, invhist_docnumber "
               "FROM itemlocdist, itemsite, item, invhist "
               "WHERE ( (itemlocdist_itemsite_id=itemsite_id)"
               " AND (itemsite_item_id=item_id)"
               " AND (itemlocdist_invhist_id=invhist_id) "
               " AND (itemlocdist_id=:itemlocdist_id) );" );
    q.bindValue(":itemlocdist_id", _itemlocdistid);
    q.exec();
    if (q.first())
    {
      if (q.value("itemsite_controlmethod").toString() == "S")
      {
	_serial = true;
        _qtyToAssign->setText("1");
        _qtyToAssign->setEnabled(FALSE);
      }
      else
	_serial = false;

      _item->setItemsiteid(q.value("itemsite_id").toInt());
      _itemsiteid = q.value("itemsite_id").toInt();
      _expiration->setEnabled(q.value("itemsite_perishable").toBool());
      _warranty->setEnabled(q.value("itemsite_warrpurc").toBool() && q.value("invhist_ordtype").toString() == "PO");
      _fractional = q.value("item_fractional").toBool();
      
      //If there is preassigned trace info for an associated order, force user to select from list
      XSqlQuery preassign;
      preassign.prepare("SELECT lsdetail_id,ls_number,ls_number "
                "FROM lsdetail,ls "
                "WHERE ( (lsdetail_source_number=:docnumber) "
                "AND (lsdetail_source_type=:transtype) "
                "AND (lsdetail_ls_id=ls_id) "
                "AND (lsdetail_qtytoassign > 0) )");
      preassign.bindValue(":transtype", q.value("invhist_transtype").toString());
      preassign.bindValue(":docnumber", q.value("invhist_docnumber").toString());
      preassign.exec();
      if (preassign.first())
      {
        _lotSerial->setEditable(FALSE);
        _lotSerial->populate(preassign);
        _preassigned = true;
      }
      else if (q.lastError().type() != QSqlError::None)
      {
        systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
        return UndefinedError;
      }
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return UndefinedError;
    }
  }
  
  param = pParams.value("qtyRemaining", &valid);
  if (valid)
    _qtyRemaining->setText(param.toString());

  return NoError;
}
Esempio n. 29
0
void unpostedPoReceipts::sPost()
{
  XSqlQuery unpostedPost;
  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, "
                   "  (recv_order_type = 'RA' AND COALESCE(itemsite_costmethod, '') = 'J') AS issuewo, "
                   "  COALESCE(pohead_dropship, false) AS dropship "
                   "FROM recv "
                   "  LEFT OUTER JOIN itemsite ON (itemsite_id=recv_itemsite_id) "
                   "  LEFT OUTER JOIN poitem ON ((recv_order_type='PO') "
                   "                         AND (recv_orderitem_id=poitem_id)) "
                   "  LEFT OUTER JOIN pohead ON (poitem_pohead_id=pohead_id) "
                   "WHERE (recv_id=:id);");
  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  bool tryagain = false;
  do {
    unpostedPost.exec("BEGIN;");

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

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

        if (distributeInventory::SeriesAdjust(result, this) == XDialog::Rejected)
        {
          rollback.exec();
          QMessageBox::information( this, tr("Unposted Receipts"), tr("Post Canceled") );
          return;
        }

        // Job item for Return Service; issue this to work order
        if (postLine.value("issuewo").toBool())
        {
          XSqlQuery issuewo;
          issuewo.prepare("SELECT issueWoRtnReceipt(coitem_order_id, invhist_id) AS result "
                          "FROM invhist, recv "
                          " JOIN raitem ON (raitem_id=recv_orderitem_id) "
                          " JOIN coitem ON (coitem_id=raitem_new_coitem_id) "
                          "WHERE ((invhist_series=:itemlocseries) "
                          " AND (recv_id=:id));");
          issuewo.bindValue(":itemlocseries", postLine.value("result").toInt());
          issuewo.bindValue(":id", id);
          issuewo.exec();
          if (issuewo.lastError().type() != QSqlError::NoError)
          {
            systemError(this, issuewo.lastError().databaseText(), __FILE__, __LINE__);
            rollback.exec();
            return;
          }
        }
        // Issue drop ship orders to shipping
        else if (postLine.value("dropship").toBool())
        {
          XSqlQuery issue;
          issue.prepare("SELECT issueToShipping('SO', coitem_id, "
                        "  (recv_qty * poitem_invvenduomratio / coitem_qty_invuomratio), "
                        "  :itemlocseries, now(), invhist_id ) AS result, "
                        "  coitem_cohead_id, cohead_holdtype, pohead_number "
                        "FROM invhist, recv "
                        " JOIN poitem ON (poitem_id=recv_orderitem_id) "
                        " JOIN pohead ON (poitem_pohead_id=pohead_id) "
                        " JOIN coitem ON (coitem_id=poitem_order_id AND poitem_order_type='S') "
                        " JOIN cohead ON (coitem_cohead_id=cohead_id) "
                        "WHERE ((invhist_series=:itemlocseries) "
                        " AND (recv_id=:id));");
          issue.bindValue(":itemlocseries", postLine.value("result").toInt());
          issue.bindValue(":id",  id);
          issue.exec();
          if (issue.first())
          {
            if (issue.value("cohead_holdtype").toString() != "N")
            {
              QString msg = tr("Purchase Order %1 is being drop shipped against "
                       "a Sales Order that is on Hold.  The Sales Order must "
                       "be taken off Hold before the Receipt may be Posted.")
                  .arg(issue.value("pohead_number").toString());
              rollback.exec();
              QMessageBox::warning(this, tr("Cannot Ship Order"), msg);
              sFillList();
              return;
            }

            if (!_soheadid.contains(issue.value("coitem_cohead_id").toInt()))
              _soheadid.append(issue.value("coitem_cohead_id").toInt());
            issue.prepare("SELECT postItemLocSeries(:itemlocseries);");
            issue.bindValue(":itemlocseries", postLine.value("result").toInt());
            issue.exec();
          }
          if (issue.lastError().type() != QSqlError::NoError)
          {
            systemError(this, issue.lastError().databaseText(), __FILE__, __LINE__);
            rollback.exec();
            return;
          }
        }    
      }
      // 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

    // Ship any drop shipped orders
    while (_soheadid.count())
    {
      XSqlQuery ship;
      ship.prepare("SELECT shipShipment(shiphead_id) AS result, "
                   "  shiphead_id "
                   "FROM shiphead "
                   "WHERE ( (shiphead_order_type='SO') "
                   " AND (shiphead_order_id=:cohead_id) "
                   " AND (NOT shiphead_shipped) );");
      ship.bindValue(":cohead_id", _soheadid.at(0));
      ship.exec();
      if (_metrics->boolean("BillDropShip") && ship.first())
      {
        int shipheadid = ship.value("shiphead_id").toInt();
        ship.prepare("SELECT selectUninvoicedShipment(:shiphead_id);");
        ship.bindValue(":shiphead_id", shipheadid);
        ship.exec();
        if (ship.lastError().type() != QSqlError::NoError)
        {
          rollback.exec();
          systemError(this, ship.lastError().databaseText(), __FILE__, __LINE__);
          return;
        }
      }
      if (ship.lastError().type() != QSqlError::NoError)
      {
        rollback.exec();
        systemError(this, ship.lastError().databaseText(), __FILE__, __LINE__);
        return;
      }
      _soheadid.takeFirst();
    }

    unpostedPost.exec("COMMIT;");

    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();
}
Esempio n. 30
0
void arOpenItem::populate()
{
  XSqlQuery arpopulate;
  arpopulate.prepare( "SELECT aropen_cust_id, aropen_docdate, aropen_duedate,"
             "       aropen_doctype, aropen_docnumber,"
             "       aropen_ordernumber, aropen_journalnumber,"
             "       aropen_amount, aropen_amount,"
             "       aropen_paid, "
             "       (aropen_amount - aropen_paid) AS f_balance,"
             "       aropen_terms_id, aropen_salesrep_id,"
             "       aropen_commission_due, cust_commprcnt,"
             "       aropen_notes, aropen_rsncode_id, aropen_salescat_id, "
             "       aropen_accnt_id, aropen_curr_id, aropen_taxzone_id, "
             "       COALESCE(SUM(taxhist_tax),0) AS tax, "
             "       CASE WHEN (aropen_doctype = 'D' OR "
             "                 (aropen_doctype='C' AND cmhead_id IS NULL)) THEN "
             "         true "
             "       ELSE "
             "         false "
             "       END AS showTax "
             "FROM aropen "
             "  JOIN custinfo ON (cust_id=aropen_cust_id) "
             "  LEFT OUTER JOIN aropentax ON (aropen_id=taxhist_parent_id) "
             "  LEFT OUTER JOIN cmhead ON ((aropen_doctype='C') "
             "                         AND (aropen_docnumber=cmhead_number)) "
             "WHERE (aropen_id=:aropen_id) "
             "GROUP BY aropen_cust_id, aropen_docdate, aropen_duedate,      "
             "  aropen_doctype, aropen_docnumber, aropen_ordernumber, aropen_journalnumber,  "
             "  aropen_amount, aropen_amount, aropen_paid, f_balance, aropen_terms_id, "
             "  aropen_salesrep_id, aropen_commission_due, cust_commprcnt, aropen_notes, aropen_rsncode_id, "
             "  aropen_salescat_id, aropen_accnt_id, aropen_curr_id, aropen_taxzone_id, cmhead_id;" );
  arpopulate.bindValue(":aropen_id", _aropenid);
  arpopulate.exec();
  if (arpopulate.first())
  {
    _cust->setId(arpopulate.value("aropen_cust_id").toInt());
    _docDate->setDate(arpopulate.value("aropen_docdate").toDate(), true);
    _dueDate->setDate(arpopulate.value("aropen_duedate").toDate());
    _docNumber->setText(arpopulate.value("aropen_docnumber").toString());
    _orderNumber->setText(arpopulate.value("aropen_ordernumber").toString());
    _journalNumber->setText(arpopulate.value("aropen_journalnumber").toString());
    _amount->set(arpopulate.value("aropen_amount").toDouble(),
                 arpopulate.value("aropen_curr_id").toInt(),
                 arpopulate.value("aropen_docdate").toDate(), false);
    _paid->setLocalValue(arpopulate.value("aropen_paid").toDouble());
    _balance->setLocalValue(arpopulate.value("f_balance").toDouble());
    _terms->setId(arpopulate.value("aropen_terms_id").toInt());
    _salesrep->setId(arpopulate.value("aropen_salesrep_id").toInt());
    _commissionDue->setBaseValue(arpopulate.value("aropen_commission_due").toDouble());
    _commprcnt = arpopulate.value("cust_commprcnt").toDouble();
    _notes->setText(arpopulate.value("aropen_notes").toString());
    _taxzone->setId(arpopulate.value("aropen_taxzone_id").toInt());
    if (arpopulate.value("showTax").toBool())
      _tax->setLocalValue(arpopulate.value("tax").toDouble());
    else
    {
      _taxzoneLit->hide();
      _taxzone->hide();
      _taxLit->hide();
      _tax->hide();
    }

    if(!arpopulate.value("aropen_rsncode_id").isNull() && arpopulate.value("aropen_rsncode_id").toInt() != -1)
      _rsnCode->setId(arpopulate.value("aropen_rsncode_id").toInt());

    if(!arpopulate.value("aropen_accnt_id").isNull() && arpopulate.value("aropen_accnt_id").toInt() != -1)
    {
      _useAltPrepaid->setChecked(true);
      _altAccntidSelected->setChecked(true);
      _altAccntid->setId(arpopulate.value("aropen_accnt_id").toInt());
    }

    if(!arpopulate.value("aropen_salescat_id").isNull() && arpopulate.value("aropen_salescat_id").toInt() != -1)
    {
      _useAltPrepaid->setChecked(true);
      _altSalescatidSelected->setChecked(true);
      _altSalescatid->setId(arpopulate.value("aropen_salescat_id").toInt());
    }

    QString docType = arpopulate.value("aropen_doctype").toString();
    _docType->setCode(docType);

    _cAmount = arpopulate.value("aropen_amount").toDouble();

    if ( (docType == "I") || (docType == "D") )
    {
      arpopulate.prepare( "SELECT arapply_id, arapply_source_aropen_id,"
                 "       CASE WHEN (arapply_source_doctype = 'C') THEN :creditMemo"
                 "            WHEN (arapply_source_doctype = 'R') THEN :cashdeposit"
                 "            ELSE getFundsTypeName(arapply_fundstype)"
                 "       END AS doctype,"
                 "       CASE WHEN (arapply_source_doctype IN ('C','R')) THEN arapply_source_docnumber"
                 "            WHEN (arapply_source_doctype = 'K') THEN arapply_refnumber"
                 "            ELSE :other"
                 "       END AS docnumber, arapply_distdate,"
                 "       arapply_postdate, arapply_applied, "
                 "       currConcat(arapply_curr_id) AS currabbr,"
                 "       currToBase(arapply_curr_id, arapply_applied, arapply_postdate) AS baseapplied,"
                 "       'curr' AS arapply_applied_xtnumericrole,"
                 "       'curr' AS baseapplied_xtnumericrole "
                 "FROM arapply "
                 "WHERE (arapply_target_aropen_id=:aropen_id) "
                 "ORDER BY arapply_postdate;" );

      arpopulate.bindValue(":creditMemo", tr("Credit Memo"));
      arpopulate.bindValue(":cashdeposit", tr("Cash Deposit"));
    }
    else if (docType == "C" || docType == "R")
    {
      arpopulate.prepare( "SELECT arapply_id, arapply_target_aropen_id,"
                 "       CASE WHEN (arapply_target_doctype = 'I') THEN :invoice"
                 "            WHEN (arapply_target_doctype = 'D') THEN :debitMemo"
                 "            WHEN (arapply_target_doctype = 'K') THEN :apcheck"
                 "            WHEN (arapply_target_doctype = 'R') THEN :cashreceipt"
                 "            ELSE :other"
                 "       END AS doctype,"
                 "       arapply_target_docnumber AS docnumber,"
                 "       arapply_distdate, arapply_postdate, arapply_applied,"
                 "       currConcat(arapply_curr_id) AS currabbr,"
                 "       currToBase(arapply_curr_id, arapply_applied, arapply_postdate) AS baseapplied,"
                 "       'curr' AS arapply_applied_xtnumericrole,"
                 "       'curr' AS baseapplied_xtnumericrole "
                 "FROM arapply "
                 "WHERE (arapply_source_aropen_id=:aropen_id) "
                 "ORDER BY arapply_postdate;" );

      arpopulate.bindValue(":invoice", tr("Invoice"));
      arpopulate.bindValue(":debitMemo", tr("Debit Memo"));
      arpopulate.bindValue(":apcheck", tr("A/P Check"));
      arpopulate.bindValue(":cashreceipt", tr("Cash Receipt"));
    }

    arpopulate.bindValue(":error", tr("Error"));
    arpopulate.bindValue(":aropen_id", _aropenid);
    arpopulate.exec();
    _arapply->populate(arpopulate, true);
    ErrorReporter::error(QtCriticalMsg, this, tr("Error Retrieving A/R Information"),
                                  arpopulate, __FILE__, __LINE__);
  }
  else if (ErrorReporter::error(QtCriticalMsg, this, tr("Error Getting Next Period Number"),
                                arpopulate, __FILE__, __LINE__))
  {
    return;
  }
}