Example #1
0
        private void btnAceptar_Click(object sender, EventArgs e)
        {
            if (!FaltanDatos())
            {
                if (!UsuarioIgualAlEmail())
                {

                    if (!fn.ExisteUsuario(txtUsuario.Text))
                    {

                        Query qr = new Query("UPDATE JJRD.USUARIOS SET USERNAME = '******', CONTRASENIA = '" + txtPasswd.Text + "' WHERE ID_USUARIO =  " + idUsuario);
                        qr.Ejecutar();

                        this.Visible = false;
                        this.Hide();
                        fn.recibirUsuario(idUsuario);

                    }
                    else
                    {
                        MessageBox.Show("Usuario existente.", "Validación al registrar usuario", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtUsuario.Focus();
                    }

                }
                else
                {

                    MessageBox.Show("Usuario invalido." + Environment.NewLine +
                    "El usuario debe ser distinto al asignado por el sistema.  ", "Validación al registrar usuario", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtUsuario.Focus();

                }
            }
        }
Example #2
0
        private void ActualizarFuncionalidades()
        {
            SqlConnection conexion = new SqlConnection();
            conexion.ConnectionString = Settings.Default.CadenaDeConexion;

            string consulta = "SELECT ID_ROL FROM JJRD.ROLES where ROL_NOMBRE = '" + rol + "'";
            Query qr = new Query(consulta);
            qr.pComando = consulta;
            int idRol = (int)qr .ObtenerUnicoCampo();

            for(int i = 0; i < Funcionalidades.Items.Count; i++)
            {
                string sql;
                string Funcionalidad = Funcionalidades.Items[i].ToString().Replace(']', ' ').Substring(Funcionalidades.Items[i].ToString().IndexOf(',') + 1).TrimEnd();
                if(Funcionalidades.GetItemChecked(i))
                {
                    // insertar si no existe
                    sql =   " insert into JJRD.ROL_FUNCIONALIDAD (ID_FUNCIONALIDAD, ID_ROL, HABILITADO)" +
                            " select distinct " + Funcionalidad + ", " + idRol +  ", 1 habilitada" +
                            " from JJRD.FUNCIONALIDAD" +
                            " where " + Funcionalidad + " not in ( select ID_FUNCIONALIDAD from JJRD.ROL_FUNCIONALIDAD where ID_ROL = " + idRol + ")";
                }
                else
                {
                    // borrar el registro en caso que este desmarcado (no es necesario chequear si existe)
                    sql =   " delete from JJRD.ROL_FUNCIONALIDAD" +
                            " where ID_ROL = " + idRol +
                            " and ID_FUNCIONALIDAD = " + Funcionalidad;
                }

                Query qry = new Query();
                qry.pComando = sql;
                qry.Ejecutar();
            }
        }
Example #3
0
        private void FrmOfertar_Load(object sender, EventArgs e)
        {
            if (fn.getTipoDeUsuario(Globales.idUsuarioLogueado) == "A")
            {
                btnGuardar.Enabled = false;
            }

            string montoSQL = "select FLOOR(MAX(MONTO)) " +
                            "from JJRD.OFERTAS " +
                            "where COD_PUBLICACION = " + cod_Publicacion;

            conexion.ConnectionString = Settings.Default.CadenaDeConexion;
            Query qr = new Query(montoSQL);
            string monto = qr.ObtenerUnicoCampo().ToString();

            if (monto == "")
            {
                montoSQL = "select PRECIO " +
                            "from JJRD.PUBLICACION " +
                            "where COD_PUBLICACION = " + cod_Publicacion;

                qr.pComando = montoSQL;
                monto = qr.ObtenerUnicoCampo().ToString();
            }

            lblMontoActual.Text = monto;
        }
Example #4
0
        private int cantidadDeOperacionesSinCalificar()
        {
            int idCliente = fn.ObtenerIdCliente(Globales.idUsuarioLogueado);

            Query qr = new Query("select count(*) from JJRD.PUBLICACION as PU join JJRD.COMPRAS as CO on co.COD_PUBLICACION = Pu.COD_PUBLICACION where CO.ID_CLIENTE = " + idCliente + " and CO.COD_CALIFICACION is null");

            return (Convert.ToInt32(qr.ObtenerUnicoCampo()));
        }
Example #5
0
        private void FrmbnVisibilidad_Alta_Load(object sender, EventArgs e)
        {
            //Llena comboBox Cod_Publicacion

            string codigoPublicacion = "SELECT MAX(COD_VISIBILIDAD+1) FROM JJRD.VISIBILIDAD";
            Query qry = new Query(codigoPublicacion);
            decimal codigo = (decimal)qry.ObtenerUnicoCampo();

            txtCodigo.Text = codigo.ToString();

            txtCodigo.Enabled = false;
        }
Example #6
0
        public FrmDatosVendedor(string codPublicacion)
        {
            InitializeComponent();

            conexion.ConnectionString = Settings.Default.CadenaDeConexion;

            string qTipoUsuario = "select usr.TIPO_DE_USUARIO " +
                                  "from JJRD.PUBLICACION pub " +
                                  "join JJRD.USUARIOS usr " +
                                  "on usr.ID_USUARIO = pub.ID_USUARIO " +
                                  "where pub.COD_PUBLICACION = " + codPublicacion;

            Query qry = new Query(qTipoUsuario);
            string tipoUsuario = (string)qry.ObtenerUnicoCampo();

            string datosContacto = "";

            switch (tipoUsuario)
            {
                case "C":

                    datosContacto = "select cli.NOMBRE + ' ' + cli.APELLIDO, cli.EMAIL,  ISNULL(cli.TELEFONO, -1), cli.CALLE, cli.NUM_CALLE, cli.PISO, cli.DEPARTAMENTO, ISNULL(cli.LOCALIDAD, ''), COD_POSTAL " +
                                    "from JJRD.PUBLICACION pub " +
                                    "join JJRD.CLIENTE cli " +
                                    "on cli.ID_USUARIO = pub.ID_USUARIO " +
                                    "where pub.COD_PUBLICACION = " + codPublicacion;
                    break;
                case "E":
                    datosContacto = "select  emp.NOMBRE_CONTACTO + '(' + emp.RAZON_SOCIAL + ')', emp.EMAIL,ISNULL(emp.TELEFONO, -1), emp.CALLE, emp.NUM_CALLE, emp.PISO, emp.DEPARTAMENTO, ISNULL(emp.CIUDAD, '') + ', ' + ISNULL(emp.LOCALIDAD, ''), emp.COD_POSTAL " +
                                    "from JJRD.PUBLICACION pub " +
                                    "join JJRD.EMPRESA emp " +
                                    "on emp.ID_USUARIO = pub.ID_USUARIO " +
                                    "where pub.COD_PUBLICACION = " + codPublicacion;
                    break;
            }

            DataTable dtContacto = new DataTable();
            qry.pComando = datosContacto;
            dtContacto = qry.ObtenerDataTable();

            lblVendedor.Text = "Vendedor: " + dtContacto.Rows[0][0].ToString();
            lblEmail.Text = "Email: " + dtContacto.Rows[0][1].ToString();
            lblTelefono.Text = "Telefono: " + dtContacto.Rows[0][2].ToString();
            lblCalle.Text = "Calle: " + dtContacto.Rows[0][3].ToString();
            lblNumCalle.Text = "Altura: " + dtContacto.Rows[0][4].ToString();
            lblPiso.Text = "Piso: " + dtContacto.Rows[0][5].ToString();
            lblDepartamento.Text = "Depto: " + dtContacto.Rows[0][6].ToString();
            lblCiudad.Text = "Ciudad: " + dtContacto.Rows[0][7].ToString();
            lblCodPostal.Text = "CP: " + dtContacto.Rows[0][8].ToString();
        }
Example #7
0
        public void cargarRoles()
        {
            string sql = "SELECT r.ROL_NOMBRE rol FROM JJRD.ROLES r, JJRD.ROL_USUARIO ur where ur.ID_ROL = r.ID_ROL and ur.ID_USUARIO = " + idUsuario;

            Query qry = new Query(sql);

            foreach (DataRow dataRow in qry.ObtenerDataTable().AsEnumerable())
            {
                comboBox.Items.Add(dataRow[0]);
            }

            comboBox.DisplayMember = "Key";
            comboBox.ValueMember = "Value";
            comboBox.Text = null;
        }
Example #8
0
        private void btnIngresar_Click(object sender, EventArgs e)
        {
            //SETEO IDROL POR LAS DUDAS, VER SI SE NECESITA PARA DESPUES
            int idRol = (int)new Query("SELECT ID_ROL FROM JJRD.ROLES  " +
                                   " WHERE ROL_NOMBRE = '" + comboBox.SelectedItem.ToString() + "'").ObtenerUnicoCampo();

            //IdRolElegido = idRol;
            Globales.idRolElegido = idRol;

            Query qr = new Query("SELECT distinct(USERNAME) from JJRD.USUARIOS U WHERE ID_USUARIO = " + idUsuario);

            qr.pTipoComando = CommandType.Text;
            string nombreUsuario = qr.ObtenerUnicoCampo().ToString();

            this.Visible = false;
            Funciones fn = new Funciones();
            fn.recibirUsuario(idUsuario);
        }
Example #9
0
        /* El boton guardar insertara todas las funcionalidades chequeadas */
        private void bnGuardar_Click(object sender, EventArgs e)
        {
            conexion.ConnectionString = Settings.Default.CadenaDeConexion;

            if (txtNombre.Text.Trim() != "")
            {
                string Habilitado = "SELECT COUNT(1) FROM JJRD.ROLES where ROL_NOMBRE = '" + txtNombre.Text + "'";
                Query qry = new Query(Habilitado);
                qry.pComando = Habilitado;
                int existeRol = (int)qry.ObtenerUnicoCampo();

                if (existeRol == 1)
                {
                    txtNombre.Text = null;
                    MessageBox.Show("Nombre de rol existente - Ingresar nuevo nombre"
                        , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    string sql = "INSERT INTO JJRD.ROLES (ROL_NOMBRE, ROL_ESTADO) values ('" + txtNombre.Text + "', 1)";
                    qry.pComando = sql;
                    qry.Ejecutar();

                    string consulta = "SELECT ID_ROL FROM JJRD.ROLES where ROL_NOMBRE= '" + txtNombre.Text + "'";
                    Query qr = new Query(consulta);
                    qr.pComando = consulta;
                    idRol = (int)qr.ObtenerUnicoCampo();

                    foreach (var checkedItem in Funcionalidades.CheckedItems)
                    {
                        string sql2 = "insert into JJRD.ROL_FUNCIONALIDAD (ID_FUNCIONALIDAD, ID_ROL, HABILITADO) " +
                                     "select ID_FUNCIONALIDAD, " + idRol + ", 1 habilitado " +
                                     "from JJRD.FUNCIONALIDAD where DESCRIPCION = '" + checkedItem.ToString().Replace('[', ' ').Substring(1, checkedItem.ToString().IndexOf(',') - 1).TrimStart() + "'";

                        Query qry2 = new Query();
                        qry2.pComando = sql2;
                        qry2.Ejecutar();
                    }

                    MessageBox.Show("Rol dado de alta exitosamente!", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Visible = false;
                }
            }
        }
Example #10
0
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            /* insert de monto y fecha */
            if (Convert.ToDouble(txtMontoOferta.Text) > Convert.ToDouble(lblMontoActual.Text))
            {
                string oferta = "insert into JJRD.OFERTAS (COD_PUBLICACION, ID_CLIENTE, MONTO, FECHA) " +
                                "values ( " + cod_Publicacion + ", " + fn.ObtenerIdCliente(Globales.idUsuarioLogueado) + "," + txtMontoOferta.Text + ", '" + Globales.fechaSistema + "')";

                Query qry = new Query(oferta);
                qry.Ejecutar();

                MessageBox.Show("Oferta realizada con éxito!");
                this.Hide();
                frmPrincipal frm = new frmPrincipal();
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("El monto ingresado debe ser superior");
            }
        }
Example #11
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (txtPregunta.Text.Trim().Length > 0)
            {

                string pregunta = "insert into JJRD.PREGUNTAS (COD_PUBLICACION, ID_CLIENTE, PREGUNTA_DESCRIPCION) " +
                "values ( " + codigo + ", " + fn.ObtenerIdCliente(Globales.idUsuarioLogueado) + ",'" + txtPregunta.Text + "')";

                Query qry = new Query(pregunta);
                qry.Ejecutar();

                MessageBox.Show("Pregunta realizada correctamente!");

                frmPrincipal frm = new frmPrincipal();
                this.Hide();
                frm.ShowDialog();

            }
            else
            {
                MessageBox.Show("Por favor ingrese una pregunta.");
            }
        }
Example #12
0
        private void bnGuardar_Click(object sender, EventArgs e)
        {
            conexion.ConnectionString = Settings.Default.CadenaDeConexion;

            if (txtCodigo.Text.Trim() != ""
                && txtDescripcion.Text.Trim() != ""
                && txtPrecio.Text.Trim() != ""
                && txtPorcentaje.Text.Trim() != ""
                && txtVigencia.Text.Trim() != "")
            {
                string codigo = "SELECT COUNT(1) FROM JJRD.Visibilidad where COD_VISIBILIDAD = " + txtCodigo.Text;
                Query qry = new Query(codigo);
                qry.pComando = codigo;
                int existeCodigo = (int)qry.ObtenerUnicoCampo();

                if (existeCodigo == 1)
                {
                    txtCodigo.Text = null;
                    MessageBox.Show("Codigo de visibilidad existente. Ingrese otro.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    string sql = "INSERT INTO JJRD.Visibilidad (COD_VISIBILIDAD, DESCRIPCION, PRECIO, PORCENTAJE_VENTA, DURACION, HABILITADO)"
                                + "values (" + txtCodigo.Text + ", '" + txtDescripcion.Text + "', " + txtPrecio.Text + ", " + txtPorcentaje.Text + ", " + txtVigencia.Text + ", 1)";
                    qry.pComando = sql;
                    qry.Ejecutar();

                    MessageBox.Show("Visibilidad dada de alta exitosamente!", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Visible = false;
                }
            }
            else
            {
                MessageBox.Show("Todos los campos tienen que estar cargados", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #13
0
File: Query.cs Project: JnsCas/gdd
 private CommandType GetCommandType(Query.TipoQuery _TipoQuery)
 {
     if (this.pTipoComando.HasValue)
         return this.pTipoComando.Value;
     if (this.pComando.TrimStart(new char[1] { ' ' }).StartsWith("exec ", StringComparison.InvariantCultureIgnoreCase))
     {
         this.pComando = this.pComando.Remove(0, 5);
         return CommandType.StoredProcedure;
     }
     else
     {
         switch (_TipoQuery)
         {
             case Query.TipoQuery.Ejecutar:
                 return this.pComando.ToLowerInvariant().Contains("update ") || this.pComando.ToLowerInvariant().Contains("insert ")
                     || this.pComando.ToLowerInvariant().Contains("delete ") ? CommandType.Text : CommandType.StoredProcedure;
             default:
                 return this.pComando.ToLowerInvariant().Contains("select ") ? CommandType.Text : CommandType.StoredProcedure;
         }
     }
 }
Example #14
0
        private void cargarRubros()
        {
            string sql = "select DESCRIPCION, COD_RUBRO " +
                         "from JJRD.RUBRO " +
                         "order by DESCRIPCION";

            Query qry = new Query(sql);
            List<KeyValuePair<string, int>> datos = (from x in qry.ObtenerDataTable().AsEnumerable()
                                                     select new
                                                     KeyValuePair<string, int>(x["DESCRIPCION"].ToString(), Convert.ToInt32(x["COD_RUBRO"]))).ToList();

            clbRubros.DataSource = datos;
            clbRubros.DisplayMember = "Key";
            clbRubros.ValueMember = "Value";
        }
Example #15
0
        private bool UsuarioIgualAlEmail()
        {
            string tipo = fn.getTipoDeUsuario(idUsuario);

            if (tipo == "C")
            {
                Query email = new Query("SELECT EMAIL FROM JJRD.CLIENTE WHERE ID_USUARIO = " + idUsuario);
                return (email.ObtenerUnicoCampo().ToString().ToUpper() == txtUsuario.Text.ToUpper());
            }
            else
            {   //TIPO ES "E"
                Query email = new Query("SELECT EMAIL FROM JJRD.EMPRESA WHERE ID_USUARIO = " + idUsuario);
                return (email.ObtenerUnicoCampo().ToString().ToUpper() == txtUsuario.Text.ToUpper());
            }
        }
Example #16
0
        private void bnGuardar_Click(object sender, EventArgs e)
        {
            if((txtRazonSocial.Text.Trim() != "" &&
                txtCuit.Text.Trim() != "" &&
                txtEmail.Text.Trim()!= "" &&

                 txtDireccion.Text.Trim() != "" &&
                 txtLocalidad.Text.Trim() != "" &&
                 txtDepto.Text.Trim() != "" &&
                 txtNomContacto.Text.Trim() != "" &&
                 txtNumCalle.Text.Trim() != "" &&
                 txtTel.Text.Trim() != "" &&
                 txtCodPost.Text.Trim() != "" &&
                 txtDepto.Text.Trim() != "" &&
                 dataFecha.Text !=""))

            {
                //controla que cuit no este repetido= '" + txtEmail.Text + "')";

                string cuit = "SELECT COUNT(1) FROM JJRD.EMPRESA where CUIT = '" + txtCuit.Text + "'";
                Query qry = new Query(cuit);
                int existeCuit = (int)qry.ObtenerUnicoCampo();

                    if (existeCuit == 1)
                    {
                        txtCuit.Text = null;
                        MessageBox.Show("Cuit existente", "Advertencia",MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    else
                    {
                        //controla que razon_social no este repetido
                        string razon_social = "SELECT COUNT(1) FROM JJRD.EMPRESA where RAZON_SOCIAL = '" + txtRazonSocial.Text+"'";
                        Query qry2 = new Query(razon_social);
                        int existeRazonSocial = (int)qry2.ObtenerUnicoCampo();

                            if (existeRazonSocial == 1)
                            {
                                txtRazonSocial.Text = null;
                                MessageBox.Show("Razon Social existente", "Advertencia",MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            { //preguntar por mail
                        string EMAIL = "SELECT COUNT(1) FROM JJRD.EMPRESA WHERE EMAIL = '" + txtEmail.Text + "' ";
                        Query qry3 = new Query(EMAIL);
                        int existeEMAIL = (int)qry3.ObtenerUnicoCampo();

                        if (existeEMAIL == 1)
                        {
                            txtEmail.Text = null;
                            MessageBox.Show("EMAIL existente. Ingrese otro Email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {

                            /* Primero da alta a Usuario */
                            //SI EL ADMINISTRADOR ESTA DANDO DE ALTA, SE SETEA USUARIO Y CONTRASEÑA POR DEFAULT

                            if (tipo_usuario == "A")
                            {

                                //LA CONTRASENIA VA SIN SHA256 ASI PUEDE MATCHEAR EL PRIMERLOGIN
                                string sql = "INSERT INTO JJRD.USUARIOS (USERNAME, CONTRASENIA, HABILITADO, LOGIN_FALLIDOS, TIPO_DE_USUARIO, PRIMER_LOGIN) values ('" + txtRazonSocial.Text + "', '" + txtCuit.Text + "', 1, 0, 'E', 1 )";
                                qry.pComando = sql;
                                qry.Ejecutar();

                                /* Da de alta empresa*/

                                string consulta = "select id_usuario FROM JJRD.USUARIOS where USERNAME=  '******'";
                                Query qr = new Query(consulta);
                                qr.pComando = consulta;
                                idUsuario = (int)qr.ObtenerUnicoCampo();
                            }

                            string sql2 = "INSERT INTO JJRD.EMPRESA (ID_USUARIO,CUIT,RAZON_SOCIAL,CIUDAD,NOMBRE_CONTACTO,EMAIL,CALLE,NUM_CALLE,PISO,DEPARTAMENTO,LOCALIDAD,COD_POSTAL,FECHA_CREACION,TELEFONO)" +
                            " values (" + idUsuario + "," + txtCuit.Text + ",'" + txtRazonSocial.Text + "','" + txtLocalidad.Text + "','" + txtNomContacto.Text + "','" + txtEmail.Text + "','" + txtDireccion.Text + "'," + txtNumCalle.Text + "," + txtPiso.Text + ",'" + txtDepto.Text + "','" + txtLocalidad.Text + "','" + txtCodPost.Text + "','" + dataFecha.Value.ToShortDateString() + "'," + txtTel.Text + ")";
                            qry.pComando = sql2;
                            qry.Ejecutar();

                            // ID_ROL EMPRESA = 2
                            new Query("INSERT INTO JJRD.ROL_USUARIO (ID_ROL, ID_USUARIO, HABILITADO) values (2, " + idUsuario + ", 1)").Ejecutar();

                            this.Visible = false;

                            if (tipo_usuario == "A")
                            {
                                MessageBox.Show("Se dio de alta la Empresa correctamente!", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                FrmEmpresa volver = new FrmEmpresa();
                                this.Hide();
                                volver.ShowDialog();
                                volver = (FrmEmpresa)this.ActiveMdiChild;

                            }
                            else
                            {
                                fn.recibirUsuario(idUsuario);
                            }

                        }

                            }

                    }
            }
            else
                {
                    MessageBox.Show("No puede ingresar campos nulos", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
        }
Example #17
0
        private void bnBuscar_Click(object sender, EventArgs e)
        {
            string rubros = "";

            for (int i = 0; i < clbRubros.Items.Count; i++)
            {
                if (clbRubros.GetItemChecked(i))
                {
                    string item = clbRubros.Items[i].ToString();
                    string unRubro = item.Replace(']', ' ').Substring(item.LastIndexOf(',') + 1).TrimEnd();
                    rubros += unRubro + ",";
                }
            }

            string publicaciones = "";
            if (rubros.Length > 0)
            {
                publicaciones = "select pub.COD_PUBLICACION, pub.DESCRIPCION Publicacion, tpub.DESCRIPCION " +
                                "from JJRD.PUBLICACION pub " +
                                "join JJRD.VISIBILIDAD vis " +
                                "on vis.COD_VISIBILIDAD = pub.COD_VISIBILIDAD " +
                                "join JJRD.PUBLICACION_RUBRO pubrub " +
                                "on pubrub.COD_PUBLICACION = pub.COD_PUBLICACION " +
                                "join JJRD.ESTADO_PUBLICACION epub " +
                                "on epub.ID = pub.ID_ESTADO_PUBLICACION " +
                                "join JJRD.TIPO_PUBLICACION tpub " +
                                "on tpub.ID = pub.ID_TIPO_PUBLICACION " +
                                "where epub.DESCRIPCION = 'Publicada' " +
                                "and pub.Stock > 0 " +
                                "and Fecha_Vencimiento >= '" + Globales.fechaSistema + "' " +
                                "and pub.DESCRIPCION like '%" + txtDescripcion.Text + "%' " +
                                "and pubrub.COD_RUBRO in (" + rubros.Substring(0, rubros.LastIndexOf(",")) + ") " +
                                "order by vis.Precio desc, pub.FECHA_INICIO desc ";
            }
            else
            {
                publicaciones = "select pub.COD_PUBLICACION, pub.DESCRIPCION Publicacion, tpub.DESCRIPCION " +
                                "from JJRD.PUBLICACION pub " +
                                "join JJRD.VISIBILIDAD vis " +
                                "on vis.COD_VISIBILIDAD = pub.COD_VISIBILIDAD " +
                                "join JJRD.PUBLICACION_RUBRO pubrub " +
                                "on pubrub.COD_PUBLICACION = pub.COD_PUBLICACION " +
                                "join JJRD.ESTADO_PUBLICACION epub " +
                                "on epub.ID = pub.ID_ESTADO_PUBLICACION " +
                                "join JJRD.TIPO_PUBLICACION tpub " +
                                "on tpub.ID = pub.ID_TIPO_PUBLICACION " +
                                "where epub.DESCRIPCION = 'Publicada' " +
                                "and pub.Stock > 0 " +
                                "and Fecha_Vencimiento >= '" + Globales.fechaSistema + "' " +
                                "and pub.DESCRIPCION like '%" + txtDescripcion.Text + "%' " +
                                "order by vis.Precio desc, pub.FECHA_INICIO desc ";
            }

            Query qry = new Query(publicaciones);
            dtPublicaciones = qry.ObtenerDataTable();
            qElementos = dtPublicaciones.Rows.Count;
            qPaginas = qElementos / 20 + ((qElementos % 20 >= 1) ? 1 : 0); // esta funcion LOCA a lo PDEP es para que sume uno si el resto de dividir por 20 no es cero :D

            if (qElementos > 0)
            {
                dgvPublicaciones.DataSource = null;
                pagActual = 1;
                mostrarPagina();
            }
            else
            {
                dgvPublicaciones.DataSource = null;
            }
        }
Example #18
0
        /* Se cargan las funcionalidades de la tabla en check list*/
        private void CargarFuncionalidadesEnLista()
        {
            string sql = "select DESCRIPCION, ID_FUNCIONALIDAD from JJRD.FUNCIONALIDAD";
            Query qry = new Query(sql);
            List<KeyValuePair<string, int>> datos = (from x in qry.ObtenerDataTable().AsEnumerable()
                                                     select new
                                                     KeyValuePair<string, int>(x["DESCRIPCION"].ToString(), Convert.ToInt32(x["ID_FUNCIONALIDAD"]))).ToList();

            Funcionalidades.DataSource = datos;
            Funcionalidades.DisplayMember = "Key";
            Funcionalidades.ValueMember = "Value";
        }
 private void comboBoxTipoDoc_SelectedIndexChanged(object sender, EventArgs e)
 {
     Query qr = new Query("SELECT ID FROM JJRD.TIPO_DOCUMENTO WHERE DESCRIPCION = '" + comboBoxTipoDoc.Text + "'");
     IdTipoDni = Convert.ToInt32(qr.ObtenerUnicoCampo());
 }
Example #20
0
        private void bnGuardar_Click(object sender, EventArgs e)
        {
            //Chequea que los datos no sean nulos

            if ((txtNombre.Text.Trim() != "") &&
                (txtApellido.Text.Trim() != "") &&
                (cmbTipoDoc.Text != "") &&
                (txtDocumento.Text.Trim() != "") &&
                (txtTelefono.Text.Trim() != "") &&
                (txtMail.Text.Trim() != "") &&
                (txtLocalidad.Text.Trim() != "") &&
                (txtDireccion.Text.Trim() != ""))
            {
                string telefono = "SELECT COUNT(1) FROM JJRD.CLIENTE where TELEFONO = " + txtTelefono.Text;
                Query qry = new Query(telefono);
                int existeTelefono = (int)qry.ObtenerUnicoCampo();

                if (existeTelefono == 1)
                {
                    txtTelefono.Text = null;
                    MessageBox.Show("Telefono existente. Ingrese otro número", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    // preguntar por DNI y TIPO
                    string DNI = "SELECT COUNT(1) FROM JJRD.CLIENTE where NUMERO_DOC = " + txtDocumento.Text + " AND ID_TIPO_DOC = " + Convert.ToInt32(cmbTipoDoc.SelectedValue);
                    Query qry2 = new Query(DNI);
                    int existeDNI = (int)qry2.ObtenerUnicoCampo();

                    if (existeDNI == 1)
                    {
                        txtDocumento.Text = null;
                        MessageBox.Show("DNI existente. Ingrese otro DNI", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        //preguntar por mail
                        string EMAIL = "SELECT COUNT(1) FROM JJRD.CLIENTE WHERE EMAIL = '" + txtMail.Text + "' ";
                        Query qry3 = new Query(EMAIL);
                        int existeEMAIL = (int)qry.ObtenerUnicoCampo();

                        if (existeEMAIL == 1)
                        {
                            txtMail.Text = null;
                            MessageBox.Show("EMAIL existente. Ingrese otro Email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            /* primero dar de alta usuario */

                            //SI EL ADMINISTRADOR ESTA DANDO DE ALTA, SE SETEA USUARIO Y CONTRASEÑA POR DEFAULT

                            if (tipo_usuario == "A")
                            {
                                string sql = "INSERT INTO JJRD.USUARIOS (USERNAME, CONTRASENIA, HABILITADO, LOGIN_FALLIDOS, TIPO_DE_USUARIO, PRIMER_LOGIN) values ('" + txtMail.Text + "', '" + txtDocumento.Text + "' , 1, 0, 'C', 1 )";
                                qry.pComando = sql;
                                qry.Ejecutar();

                                string consulta = "select id_usuario FROM JJRD.USUARIOS where USERNAME= '******'";
                                Query qr = new Query(consulta);
                                qr.pComando = consulta;
                                idUsuario = (int)qr.ObtenerUnicoCampo();
                            }

                            if (txtNumPiso.Text == "" && txtDpto.Text == "")
                            {
                                string sql2 = "INSERT INTO JJRD.CLIENTE (ID_USUARIO, NOMBRE, APELLIDO, ID_TIPO_DOC, NUMERO_DOC, EMAIL, CALLE, NUM_CALLE, LOCALIDAD, COD_POSTAL,FECHA_NACIMIENTO, TELEFONO) " +
                                          "  values (" + idUsuario + ",'" + txtNombre.Text + "','" + txtApellido.Text + "'," + Convert.ToInt32(cmbTipoDoc.SelectedValue) + "," + txtDocumento.Text + ",'" + txtMail.Text + "','" + txtDireccion.Text + "'," + txtNro_Calle.Text + ",'" + txtLocalidad.Text + "','" + txtCod_Postal.Text + "','" + txtFecha.Value + "'," + txtTelefono.Text + ")";

                                qry.pComando = sql2;
                                qry.Ejecutar();

                            }
                            else
                            {
                                string sql2 = "INSERT INTO JJRD.CLIENTE (ID_USUARIO, NOMBRE, APELLIDO, ID_TIPO_DOC, NUMERO_DOC, EMAIL, CALLE, NUM_CALLE, PISO, DEPARTAMENTO, LOCALIDAD, COD_POSTAL,FECHA_NACIMIENTO, TELEFONO) " +
                                              "  values (" + idUsuario + ",'" + txtNombre.Text + "','" + txtApellido.Text + "'," + Convert.ToInt32(cmbTipoDoc.SelectedValue) + "," + txtDocumento.Text + ",'" + txtMail.Text + "','" + txtDireccion.Text + "'," + txtNro_Calle.Text + "," + txtNumPiso.Text + ",'" + txtDpto.Text + "','" + txtLocalidad.Text + "','" + txtCod_Postal.Text + "','" + txtFecha.Value.ToShortDateString() + "'," + txtTelefono.Text + ")";

                                qry.pComando = sql2;
                                qry.Ejecutar();
                            }

                            // ID_ROL CLIENTE = 3
                            new Query("INSERT INTO JJRD.ROL_USUARIO (ID_ROL, ID_USUARIO, HABILITADO) values (3, " + idUsuario + ", 1)").Ejecutar();

                            this.Visible = false;

                            if (tipo_usuario == "A")
                            {
                                MessageBox.Show("Cliente dado de alta exitosamente!", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                fn.recibirUsuario(idUsuario);
                            }
                        }
                    }
                }
            }
            // Insertar todos los campos
            else
            {
                MessageBox.Show("Nombre, apellido, tipo documento, número y telefóno no pueden ser blancos", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Example #21
0
        private void CargarDatosRol()
        {
            /* Setear el mismo nombre por defecto */
            txtNombreRol.Text = rol;

            CargarFuncionalidadesEnLista();
            string ConsultarFuncionalidades =   " SELECT f.DESCRIPCION Funcionalidad, rf.HABILITADO " +
                                                " FROM JJRD.ROL_FUNCIONALIDAD rf" +
                                                " JOIN JJRD.ROLES r ON r.ID_ROL = rf.ID_ROL" +
                                                " RIGHT JOIN JJRD.FUNCIONALIDAD f on f.ID_FUNCIONALIDAD = rf.ID_FUNCIONALIDAD" +
                                                " where rf.ID_ROL= r.ID_ROL " +
                                                " and r.ROL_NOMBRE = '" + rol + "' ";

            Query qry = new Query(ConsultarFuncionalidades);

            /* Para tildar las funcionalidades habilitadas */
            DataTable funcionalidades = qry.ObtenerDataTable();
            foreach (DataRow funcionalidad in funcionalidades.Rows)
            {
                string descripcionFuncionalidad = funcionalidad["Funcionalidad"].ToString();
                int index = Funcionalidades.FindString(descripcionFuncionalidad, 0);
                Funcionalidades.SetItemChecked(index, true);
            }

            /* Para tildar la casilla de Rol habilitado*/
            string Habilitado = "SELECT ROL_ESTADO FROM JJRD.ROLES where ROL_NOMBRE = '" + rol + "'";
            qry.pComando = Habilitado;
            chkHabilitado.Checked = (bool)qry.ObtenerUnicoCampo();

            /* Para deshabilitar el chequeo del box si el rol está habilitado
             * para dar de baja el rol está el form de baja */
            if (chkHabilitado.Checked == true)
            {
                chkHabilitado.Enabled = false;
            }
        }
Example #22
0
        private void bnVolver_Click(object sender, EventArgs e)
        {
            if (tipo_usuario == "A")
            {
                FrmbnCliente volver = new FrmbnCliente();
                this.Hide();
                volver.ShowDialog();
                volver = (FrmbnCliente)this.ActiveMdiChild;
            }
            else
            {

                Query qr2 = new Query("DELETE FROM JJRD.USUARIOS WHERE ID_USUARIO = " + idUsuario);
                qr2.Ejecutar();

                FrmRegistrarUsuario volver = new FrmRegistrarUsuario();
                this.Hide();
                volver.ShowDialog();
                volver = (FrmRegistrarUsuario)this.ActiveMdiChild;
            }
        }
Example #23
0
        private void FrmbnCliente_Baja_Load(object sender, EventArgs e)
        {
            this.bnDarDeBaja.Enabled = false;

            //CARGAR COMBOBOX
            string sql = "SELECT DESCRIPCION FROM JJRD.TIPO_DOCUMENTO";

            Query qry = new Query(sql);

            foreach (DataRow dataRow in qry.ObtenerDataTable().AsEnumerable())
            {
                comboBoxTipoDoc.Items.Add(dataRow[0]);
            }
        }
        private void comboBoxVisibilidad_SelectedIndexChanged(object sender, EventArgs e)
        {
            string duracionDeLaPublicacion = "SELECT DURACION FROM JJRD.VISIBILIDAD WHERE DESCRIPCION = '" + comboBoxVisibilidad.Text + "'";

            Query qry5 = new Query(duracionDeLaPublicacion);
            int duracion = Convert.ToInt32(qry5.ObtenerUnicoCampo());

            txtFechaVencimiento.Text = (Convert.ToDateTime(Globales.fechaSistema).AddDays(duracion)).ToString();
        }
        private void FrmbnCliente_Baja_Load(object sender, EventArgs e)
        {
            comboBoxTipoDoc.DropDownStyle = ComboBoxStyle.DropDownList;

            //OCULTO BOTONES
            this.bnHabilitar.Visible = false;
            this.bnModificar.Visible = false;
            this.bnDarDeBaja.Visible = false;

            //BLOQUEO BOTONES
            this.bnDarDeBaja.Enabled = false;
            this.bnHabilitar.Enabled = false;
            this.bnModificar.Enabled = false;

            //SI ES 1 ES BAJA, SI ES 2 ES LISTADO, SI ES 3 ES MODIFICACION
            switch (tipo_formulario)
            {
                case 1: this.Text = "Baja de Cliente";
                        this.bnDarDeBaja.Visible = true;
                        break;

                case 2: this.Text = "Listado de Cliente";
                        break;

                case 3: this.Text = "Modificacion de Cliente";
                        this.bnModificar.Visible = true;
                        this.bnHabilitar.Visible = true;
                        break;

            }

            //CARGAR COMBOBOX
            string sql = "SELECT DESCRIPCION FROM JJRD.TIPO_DOCUMENTO";

            Query qry = new Query(sql);

            foreach (DataRow dataRow in qry.ObtenerDataTable().AsEnumerable())
            {
                comboBoxTipoDoc.Items.Add(dataRow[0]);
            }
        }
 private void mostrarResultadoDataGrid(string qr)
 {
     Query resultado = new Query(qr);
     dataResultado.DataSource = resultado.ObtenerDataTable();
     dataResultado.Columns["id_usuario"].Visible = false;  //OCULTO LA COLUMNA
     dataResultado.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
 }
        private void bnGuardar_Click(object sender, EventArgs e)
        {
            //Controlar que los datos no sean nulos

            if ((txtCodigo.Text != "")&&
                (txtDescripcion.Text.Trim() != "" ) &&
                (txtStock.Text.Trim() != "" ) &&

                (txtPrecio.Text.Trim() != "" ) &&
                (txtDescripcion.Text.Trim() != "" ) &&
                (comboBoxVisibilidad.Text != "" ) &&

                (comboBoxEstadoPublicacion.Text != "") &&

                (comboBoxPreguntas.Text != ""))

            {
                //Busca codigo de visibilidad y se lo guarda

                string visibilidad = "SELECT COD_VISIBILIDAD FROM JJRD.VISIBILIDAD WHERE DESCRIPCION = '" + comboBoxVisibilidad.Text + "'";
                Query qr = new Query(visibilidad);

                decimal idVisibilidad = (decimal)qr.ObtenerUnicoCampo();

                //Busca codigo de publicacion y se lo guarda

                string codigoPublicacion = "SELECT MAX(COD_PUBLICACION+1) FROM JJRD.PUBLICACION";
                Query qry = new Query(codigoPublicacion);

                decimal idPublicacion = (decimal)qry.ObtenerUnicoCampo();

                 //Busca codigo de estado y se lo guarda

                string consultaEstado = "SELECT ID FROM JJRD.ESTADO_PUBLICACION WHERE DESCRIPCION = '" + comboBoxEstadoPublicacion.Text + "'";

                Query qry3 = new Query(consultaEstado);

                int idEstado = (int)qry3.ObtenerUnicoCampo();

                //inserta publicacion

                if (comboBoxVisibilidad.Text == "Gratis" && comboBoxEstadoPublicacion.Text == "Publicada")
                {

                    //insertar en tabla usuarios contador publicacion gratis

                    string publicacionesGratisUsuario = "SELECT PUBLICACIONES_GRATIS FROM JJRD.USUARIOS WHERE ID_USUARIO =" + idUsuario;
                    Query qry4 = new Query(publicacionesGratisUsuario);
                    int cantidadPublicacionesGratis = (int)qry4.ObtenerUnicoCampo();

                    if (cantidadPublicacionesGratis >= 3)
                    {
                        //Mensaje de Error, usted ya tiene 3 publicaciones gratis

                        MessageBox.Show("Usted ya tiene 3 Publicaciones Gratis", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        //Volver a llenar el formulario

                        FrmPublicacionCompraInmediata volver = new FrmPublicacionCompraInmediata(idUsuario);
                        this.Hide();
                        volver.ShowDialog();
                        volver = (FrmPublicacionCompraInmediata)this.ActiveMdiChild;

                    }
                    else
                    {

                        //Incrementar y generar publicaciones

                        //incrementa publicaciones gratis
                        cantidadPublicacionesGratis = cantidadPublicacionesGratis + 1;

                        string actualizar = "UPDATE JJRD.USUARIOS SET  PUBLICACIONES_GRATIS = " + cantidadPublicacionesGratis + " WHERE ID_USUARIO = " + idUsuario + "";

                        new Query(actualizar).Ejecutar();

                        //inserta publicacion

                        string generar = "INSERT INTO JJRD.PUBLICACION (COD_PUBLICACION,ID_USUARIO,COD_VISIBILIDAD, DESCRIPCION, STOCK, PRECIO,FECHA_VENCIMIENTO,FECHA_INICIO, ID_ESTADO_PUBLICACION, ID_TIPO_PUBLICACION, PREGUNTAS) " +
                                         "  values (" + idPublicacion + "," + idUsuario + "," + idVisibilidad + ",'" + txtDescripcion.Text + "'," + txtStock.Text + "," + txtPrecio.Text + ",'" + txtFechaVencimiento.Text + "','" + Globales.fechaSistema + "'," + idEstado + ",'" + 1 + "','" + comboBoxPreguntas.Text + "')";

                        Query qry2 = new Query(generar);
                        qry2.Ejecutar();

                         }

                }
                else {

                        //inserta comun

                    string generar = "INSERT INTO JJRD.PUBLICACION (COD_PUBLICACION,ID_USUARIO,COD_VISIBILIDAD, DESCRIPCION, STOCK, PRECIO,FECHA_VENCIMIENTO,FECHA_INICIO, ID_ESTADO_PUBLICACION, ID_TIPO_PUBLICACION, PREGUNTAS) " +
                                          "  values (" + idPublicacion + "," + idUsuario + "," + idVisibilidad + ",'" + txtDescripcion.Text + "'," + txtStock.Text + "," + txtPrecio.Text + ",'" + txtFechaVencimiento.Text + "','" + Globales.fechaSistema + "'," + idEstado + ",'" + 1 + "','" + comboBoxPreguntas.Text + "')";

                    Query qry2 = new Query(generar);
                    qry2.Ejecutar();

                        }

                         //Inserta Publicacion_Rubro

                         for (int i = 0; i < listaRubros.Items.Count; i++)
                         {
                             if (listaRubros.GetItemChecked(i))
                             {
                                 string item = listaRubros.Items[i].ToString();
                                 string unRubro = item.Replace(']', ' ').Substring(item.LastIndexOf(',') + 1).TrimEnd();

                                 string publicacionrubro = "INSERT INTO JJRD.Publicacion_Rubro (COD_RUBRO,COD_PUBLICACION) " +
                                                   "  values (" + unRubro + "," + idPublicacion + ")";

                                 Query qry10 = new Query(publicacionrubro);
                                 qry10.Ejecutar();

                             }
                         }

                         //INCREMENTA CONTADOR EN BONIFICACIONES
                         fn.actualizarBonificaciones(idUsuario, idVisibilidad, idPublicacion);

                         MessageBox.Show("Publicacion Realizada Correctamente", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);

                         //Ir al menu principal

                         frmPrincipal publicacion = new frmPrincipal();
                         this.Hide();
                         publicacion.ShowDialog();
                         publicacion = (frmPrincipal)this.ActiveMdiChild;

            }else

                    {
                        MessageBox.Show("No se pueden Ingresar Campos Vacios", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
        }
Example #28
0
        private void FrmDatosPublicacion_Load(object sender, EventArgs e)
        {
            bnPreguntar.Enabled = false;
            bnOfertarComprar.Enabled = false;
            string datosPub = "select pub.DESCRIPCION, pub.STOCK, pub.FECHA_INICIO, pub.FECHA_VENCIMIENTO, pub.PRECIO, pub.PREGUNTAS, tpub.DESCRIPCION tipoPub, pub.ID_USUARIO " +
            "from JJRD.PUBLICACION pub " +
            "join JJRD.TIPO_PUBLICACION tpub " +
            "on tpub.ID = pub.ID_TIPO_PUBLICACION " +
            "where pub.COD_PUBLICACION = " + cod_Publicacion;

            Query qry = new Query(datosPub);
            DataTable dtPublicacion = new DataTable();
            dtPublicacion = qry.ObtenerDataTable();

            lblDescripcion.Text = dtPublicacion.Rows[0][0].ToString();
            stock = dtPublicacion.Rows[0][1].ToString();
            lblFechaInicio.Text = "Fecha inicio: " + dtPublicacion.Rows[0][2].ToString();
            lblFechaFin.Text = "Fecha fin: " + dtPublicacion.Rows[0][3].ToString();
            lblPrecio.Text = "Precio: $" + dtPublicacion.Rows[0][4].ToString();
            string preguntas = dtPublicacion.Rows[0][5].ToString();
            tipoPublicacion = dtPublicacion.Rows[0][6].ToString();
            int usuarioPublicacicon = Convert.ToInt32(dtPublicacion.Rows[0][7].ToString());

            if (tipoPublicacion == "Compra Inmediata")
            {
                bnOfertarComprar.Text = "Comprar";
                lblStock.Text = "Stock: " + stock;
            }
            else if (tipoPublicacion == "Subasta")
            {
                bnOfertarComprar.Text = "Ofertar";
                lblStock.Text = null;
            }

            if (usuarioPublicacicon != fn.ObtenerIdCliente(Globales.idUsuarioLogueado))
            {
                if (preguntas == "SI")
                {
                    bnPreguntar.Enabled = true;
                }

                bnOfertarComprar.Enabled = true;
            }
        }
        public void FrmPublicacion_Load(object sender, EventArgs e)
        {
            //EL ADMINISTRADOR NO PUEDE GENERAR PUBLICACIONES
            if (fn.getTipoDeUsuario(idUsuario) == "A")
            {
                this.bnGuardar.Enabled = false;
            }

            txtFechaVencimiento.Enabled = false;

                //Llena comboBox Cod_Publicacion

            string codigoPublicacion = "SELECT MAX(COD_PUBLICACION+1) FROM JJRD.PUBLICACION";
            Query qry = new Query(codigoPublicacion);

            decimal idPublicacion = (decimal)qry.ObtenerUnicoCampo();

            SqlConnection conexion = new SqlConnection();
            conexion.ConnectionString = Settings.Default.CadenaDeConexion;

            txtFechaInicio.Text = Globales.fechaSistema;

            //Llenar comboBoxVisibilidad

            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter("select DESCRIPCION from JJRD.Visibilidad where HABILITADO = 1 order by DESCRIPCION", conexion);
            da.Fill(ds, "JJRD.Visibilidad");

            comboBoxVisibilidad.DataSource = ds.Tables[0].DefaultView;
            comboBoxVisibilidad.ValueMember = "DESCRIPCION";
            comboBoxVisibilidad.SelectedItem = null;

            //Llenar comboBoxRubro

            string sql1 = "select DESCRIPCION,COD_RUBRO from JJRD.RUBRO order by DESCRIPCION";
            Query qry1 = new Query(sql1);
            List<KeyValuePair<string, int>> datos = (from x in qry1.ObtenerDataTable().AsEnumerable()
                                                     select new
                                                     KeyValuePair<string, int>(x["DESCRIPCION"].ToString(), Convert.ToInt32(x["COD_RUBRO"]))).ToList();
            listaRubros.DataSource = datos;
            listaRubros.DisplayMember = "Key";
            listaRubros.ValueMember = "Value";

            //Llenar comboBoxEstado

            string sql = "SELECT DESCRIPCION FROM JJRD.ESTADO_PUBLICACION order by DESCRIPCION";

            Query estado = new Query(sql);

            foreach (DataRow dataRow in estado.ObtenerDataTable().AsEnumerable())
            {
                comboBoxEstadoPublicacion.Items.Add(dataRow[0]);
            }

            txtCodigo.Text = idPublicacion.ToString();
            comboBoxEstadoPublicacion.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBoxPreguntas.DropDownStyle = ComboBoxStyle.DropDownList;

            comboBoxVisibilidad.DropDownStyle = ComboBoxStyle.DropDownList;

            this.txtFechaInicio.Enabled = false;
        }
Example #30
0
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            /* insert de cantidad y fecha */
            if (txtStock.Text != "")
            {
                if (Convert.ToInt32(txtStock.Text) == 0)
                {
                    MessageBox.Show("La cantidad a comprar debe ser mayor que 0", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (Convert.ToInt32(txtStock.Text) <= Convert.ToInt32(lblStock.Text))
                {
                    string compra = "insert into JJRD.COMPRAS (COD_PUBLICACION, ID_CLIENTE, FECHA, CANTIDAD) " +
                                    "values ( " + cod_Publicacion + ", " + fn.ObtenerIdCliente(Globales.idUsuarioLogueado) + ",'" + Globales.fechaSistema + "'," + txtStock.Text + ")";

                    Query qry = new Query(compra);
                    qry.Ejecutar();

                    string disminuirStock = "update JJRD.PUBLICACION " +
                                            "set STOCK = STOCK - " + txtStock.Text +
                                            "where cod_Publicacion =  " + cod_Publicacion;

                    qry.pComando = disminuirStock;
                    qry.Ejecutar();

                    /* Cambiar estado de publicacion cuando se agote el stock */
                    if (Convert.ToInt32(lblStock.Text) - Convert.ToInt32(txtStock.Text) == 0)
                    {
                        string cambiarEstado =  "update JJRD.PUBLICACION " +
                                                "set ID_ESTADO_PUBLICACION = (select ID " +
                                                "                             from JJRD.ESTADO_PUBLICACION " +
                                                "                             where DESCRIPCION = 'Finalizada') " +
                                                "where COD_PUBLICACION = " + cod_Publicacion ;

                        qry.pComando = cambiarEstado;
                        qry.Ejecutar();

                        string esGratuita = "select COUNT(1) " +
                                            "from JJRD.PUBLICACION pub " +
                                            "join JJRD.VISIBILIDAD vis " +
                                            "on pub.COD_VISIBILIDAD = vis.COD_VISIBILIDAD " +
                                            "where vis.DESCRIPCION = 'Gratis' " +
                                            "and COD_PUBLICACION =  " + cod_Publicacion;

                        qry.pComando = esGratuita;
                        int gratuita = (int)qry.ObtenerUnicoCampo();

                        if (gratuita > 0)
                        {
                            string disminuirGratis = "update usu " +
                                         "set PUBLICACIONES_GRATIS = PUBLICACIONES_GRATIS -1  " +
                                         "from JJRD.USUARIOS usu " +
                                         "join JJRD.PUBLICACION pub " +
                                         "on pub.ID_USUARIO= usu.ID_USUARIO " +
                                         "where usu.PUBLICACIONES_GRATIS > 0" +
                                         "and pub.COD_PUBLICACION = " + cod_Publicacion;
                            qry.pComando = disminuirGratis;
                            qry.Ejecutar();
                        }
                    }

                    /* insertar en item factura, solo si publicacion no es gratuita */
                    string item = "insert into JJRD.ITEMS (MONTO,CANTIDAD,COD_PUBLICACION) " +
                     "select pub.PRECIO* vis.PORCENTAJE_VENTA*" + txtStock.Text + ", " + txtStock.Text + ", " + cod_Publicacion +
                     " from JJRD.PUBLICACION pub " +
                     "join JJRD.VISIBILIDAD vis " +
                     "on vis.COD_VISIBILIDAD = pub.COD_VISIBILIDAD " +
                     "where pub.COD_PUBLICACION = " + cod_Publicacion +
                     "and vis.DESCRIPCION <> 'Gratis'";

                    qry.pComando = item;
                    qry.Ejecutar();

                    MessageBox.Show("Compra realizada con éxito. A continuación los datos del vendedor.", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    FrmDatosVendedor frm = new FrmDatosVendedor(cod_Publicacion);
                    this.Hide();
                    frm.ShowDialog();
                    frm = (FrmDatosVendedor)this.ActiveMdiChild;
                }
                else
                {
                    MessageBox.Show("No se pueden comprar más unidades que las que se encuentran en stock.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Debe ingresar una cantidad a comprar.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }