Ejemplo n.º 1
0
/*!
  Inserts new record into the database, based on the current properties
  of the object.
*/
bool TSqlObject::create()
{
    // Sets the values of 'created_at', 'updated_at' or 'modified_at' properties
    for (int i = metaObject()->propertyOffset(); i < metaObject()->propertyCount(); ++i) {
        const char *propName = metaObject()->property(i).name();
        QByteArray prop = QByteArray(propName).toLower();

        if (prop == CreatedAt || prop == UpdatedAt || prop == ModifiedAt) {
            setProperty(propName, QDateTime::currentDateTime());
        } else if (prop == LockRevision) {
            // Sets the default value of 'revision' property
            setProperty(propName, 1);  // 1 : default value
        } else {
            // do nothing
        }
    }

    syncToSqlRecord();

    QString autoValName;
    QSqlRecord record = *this;
    if (autoValueIndex() >= 0) {
        autoValName = field(autoValueIndex()).name();
        record.remove(autoValueIndex()); // not insert the value of auto-value field
    }

    QSqlDatabase &database = Tf::currentSqlDatabase(databaseId());
    QString ins = database.driver()->sqlStatement(QSqlDriver::InsertStatement, tableName(), record, false);
    if (Q_UNLIKELY(ins.isEmpty())) {
        sqlError = QSqlError(QLatin1String("No fields to insert"),
                             QString(), QSqlError::StatementError);
        tWarn("SQL statement error, no fields to insert");
        return false;
    }

    TSqlQuery query(database);
    bool ret = query.exec(ins);
    sqlError = query.lastError();
    if (Q_LIKELY(ret)) {
        // Gets the last inserted value of auto-value field
        if (autoValueIndex() >= 0) {
            QVariant lastid = query.lastInsertId();

            if (!lastid.isValid() && database.driverName().toUpper() == QLatin1String("QPSQL")) {
                // For PostgreSQL without OIDS
                ret = query.exec("SELECT LASTVAL()");
                sqlError = query.lastError();
                if (Q_LIKELY(ret)) {
                    lastid = query.getNextValue();
                }
            }

            if (lastid.isValid()) {
                QObject::setProperty(autoValName.toLatin1().constData(), lastid);
                QSqlRecord::setValue(autoValueIndex(), lastid);
            }
        }
    }
    return ret;
}
Ejemplo n.º 2
0
/*!
    \fn MGasto::agregarGasto( QString descripcion, double costo, QDate Fecha, int categoria )
 */
bool MGasto::agregarGasto( QString descripcion, double costo, QDate Fecha, int categoria )
{
 QSqlTableModel::EditStrategy modo = this->editStrategy();
 this->setEditStrategy( QSqlTableModel::OnManualSubmit );
 QSqlRecord registro = this->record();
 registro.setValue( "descripcion", descripcion );
 registro.setValue( "costo", costo );
 registro.setValue( "fecha", Fecha );
 registro.setValue( "id_categoria", categoria );
 registro.remove( 0 );
 if( this->insertRecord( -1, registro ) == false )
 {
  qDebug( "Error al insertar registro de gasto" );
  qDebug() << "Detalles: tipo: " << lastError().type() << ", errno:" << lastError().number() << ", descripcion: " << lastError().text();
  this->setEditStrategy( modo );
  return false;
 }
 else
 {
     if( submitAll() )
     {
         qDebug( "Gasto agregado correctamente" );
         this->setEditStrategy( modo );
         return true;
     }
     else
     {
         qDebug( "Error al insertar registro de gasto" );
         qDebug() << "Detalles: tipo: " << lastError().type() << ", errno:" << lastError().number() << ", descripcion: " << lastError().text();
         this->setEditStrategy( modo );
         return false;
     }

 }
}
Ejemplo n.º 3
0
/*!
    \fn VDuenos::antes_de_insertar( int row, QSqlRecord & record )
	Este metodo llamado antes de insertar los datos de un registro que setea los valores predeterminados.
	@param row Numero de registro
	@param record Objeto de registro
 */
void VDuenos::antes_de_insertar( int row, QSqlRecord & record )
{
  record.remove( 0 );
  for( int i = 0; i<record.count(); i++ )
  {
   record.setValue( i, QVariant( " " ) );
  }
}
Ejemplo n.º 4
0
/*!
    \fn EVLista::agregar()
	Agrega un nuevo registro mediante la vista al modelo
 */
void EVLista::agregar()
{
 QSqlRecord registro = modelo->record();
 registro.remove( 0 );
 if( !modelo->insertRecord( -1, registro ) )
 {
  qDebug( "Error al insertar el registro" );
  qDebug( QString( "Detalles: tipo: %1, errno: %2, descripcion: %3" ).arg( modelo->lastError().type() ).arg( modelo->lastError().number() ).arg( modelo->lastError().text() ).toLocal8Bit() );
 }
}
Ejemplo n.º 5
0
/*!
    \fn MRecargos::agregarRecargo()
    Agrega un tipo de recargo a la lista de recargos para un servicio.
 */
void MRecargos::agregarRecargo()
{
 if( _servicio_actual <= 0 ) {
   qDebug( "Error, no hay un id de servicio seteado ( id <= 0 )" );
   return;
 } else { qDebug( QString( "id_servicio = %1" ).arg( _servicio_actual ).toLocal8Bit() ); }
 QSqlRecord registro = this->record();
 registro.remove( 0 );
 registro.setValue( "id_servicio", _servicio_actual );
 registro.setValue( "cant_dias", 1 );
 registro.setGenerated( 3, true );
 /*for( int i = 0; i < registro.count(); i++ ) {
     qDebug( QString( "%1: %2 - %3" ).arg( i ).arg( registro.fieldName( i ) ).arg( registro.value( i ).toString() ).toLocal8Bit() );
 }*/
 if( !this->insertRecord( -1, registro ) ) {
     qDebug( "No se pudo agregar el registro" );
 }
}
/*
    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 && (_metrics->boolean("MultiWhs")))
    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"); //returns 14, based on #define value in header, fixes problem with poitem_pohead_id not being assigned
  if (record.field(index).value() == 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;
}
void QSqlRecordProto::remove(int pos)
{
  QSqlRecord *item = qscriptvalue_cast<QSqlRecord*>(thisObject());
  if (item)
    item->remove(pos);
}