public Decimal guardarAjusteEquipo(String tipo, String idRegional, String idCiudad, int idEmpresa, int idProducto, int idEquipo, String talla, int idLote, int CantidadMod, Decimal costo, String Motivo)
        {
            Decimal idDoc = 0;
            DateTime fecha;
            Decimal idInventario = 0;

            fecha = System.DateTime.Today;
            Conexion _dato = new Conexion(Empresa);
            _dato.IniciarTransaccion();

            documento_temp _doc = new documento_temp(Empresa, Usuario);
            idDoc = _doc.AdicionarAlmDocumentosTemp(0, "AJUSTE", "", fecha, Convert.ToDateTime("01/01/1900"), 0, "POR APROBAR", Motivo, _dato);
            if (idDoc != 0)
            {
                bodega _bodega = new bodega(Empresa, Usuario);
                DataTable tablaBodega = _bodega.ObtenerAlmRegBodegaPorIds(idRegional, idCiudad, idEmpresa);
                DataRow filaBodega = tablaBodega.Rows[0];

                lote _lote = new lote(Empresa, Usuario);
                DataTable tablaLote = _lote.ObtenerAlmLotePorId(idLote);
                DataRow filalote = tablaLote.Rows[0];
                if (tipo.Equals("COSTO"))
                {
                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, idEquipo, talla, CantidadMod, costo, fecha, "MODIFICACION", _dato);
                    if (idInventario == 0)
                    {
                        _dato.DeshacerTransaccion();
                        idDoc = 0;
                    }
                    else
                    {
                        _dato.AceptarTransaccion();
                    }

                }
                else if (tipo.Equals("ENTRADA"))
                {
                    int contenido;
                    contenido = Convert.ToInt32(filalote["ENTRADAS"].ToString()) - Convert.ToInt32(filalote["SALIDAS"].ToString());
                    contenido = CantidadMod - contenido;

                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, idEquipo, talla, contenido, 0, fecha, "ENTRADA", _dato);

                    if (idInventario == 0)
                    {
                        _dato.DeshacerTransaccion();
                        idDoc = 0;
                    }
                    else
                    {

                        _dato.AceptarTransaccion();
                    }
                }
                else
                {
                    int contenido;
                    contenido = Convert.ToInt32(filalote["ENTRADAS"].ToString()) - Convert.ToInt32(filalote["SALIDAS"].ToString());
                    contenido = contenido - CantidadMod;

                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, idEquipo, talla, contenido, 0, fecha, "SALIDA", _dato);
                    if (idInventario == 0)
                    {
                        _dato.DeshacerTransaccion();
                        idDoc = 0;

                    }
                    else
                    {
                        _dato.AceptarTransaccion();
                    }
                }
            }
            else
            {
                _dato.DeshacerTransaccion();
                MensajeError = _doc.MensajeError;
                idDoc = 0;
            }

            return idDoc;
        }
        public Decimal AdicionarDatosFactura(Int32 ID_EMPLEADO,
                                             Int32 DOCUMENTO_ORIGEN,
                                             String TIPO_DOC,
                                             String ORIGEN,
                                             String NUMERO_DOCUMENTO,
                                             DateTime FECHA_DOCUMENTO,
                                             DateTime FECHA_VENCE,
                                             Int32 ID_BODEGA_DESTINO,
                                             Decimal VALOR,
                                             String ESTADO,
                                             String OBSERVACION_JUSTIFICACION,
                                             Int32 ID_PROVEEDOR,
                                             List <documento> listaDetalleFactura)
        {
            Decimal ID_DOCUMENTO  = 0;
            Decimal ID_LOTE       = 0;
            Decimal ID_INVENTARIO = 0;
            Decimal ID_DESCARGUE  = 0;

            Boolean verificador = true;

            List <Decimal> listaDeOrdenesParaDescargadas = new List <Decimal>();

            Conexion conexion = new Conexion(Empresa);

            conexion.IniciarTransaccion();

            try
            {
                ID_DOCUMENTO = AdicionarAlmDocumentosParaFactura(ID_EMPLEADO, DOCUMENTO_ORIGEN, TIPO_DOC, ORIGEN, NUMERO_DOCUMENTO, FECHA_DOCUMENTO, FECHA_VENCE, ID_BODEGA_DESTINO, VALOR, ESTADO, OBSERVACION_JUSTIFICACION, conexion, ID_PROVEEDOR);

                if (ID_DOCUMENTO == 0)
                {
                    conexion.DeshacerTransaccion();
                    MensajeError = MensajeError;
                    verificador  = false;
                }
                else
                {
                    lote                _lote                = new lote(Empresa, Usuario);
                    Inventario          _inventario          = new Inventario(Empresa, Usuario);
                    crtDescargueFactura _crtDescargueFactura = new crtDescargueFactura(Empresa, Usuario);
                    foreach (documento detalleFactura in listaDetalleFactura)
                    {
                        ID_LOTE = _lote.AdicionarAlmLote(Convert.ToInt32(ID_DOCUMENTO), Convert.ToInt32(detalleFactura.ID_PRODUCTO), Convert.ToInt32(detalleFactura.ID_BODEGA), FECHA_DOCUMENTO, detalleFactura.CANTIDAD, 0, detalleFactura.VALOR_UNIDAD, detalleFactura.TALLA, "S", conexion, detalleFactura.REEMBOLSO);

                        if (ID_LOTE == 0)
                        {
                            conexion.DeshacerTransaccion();
                            MensajeError = "ERROR: Ingresando el lote: " + _lote.MensajeError;
                            verificador  = false;
                            break;
                        }
                        else
                        {
                            ID_INVENTARIO = _inventario.AdicionarAlmInventario(Convert.ToInt32(ID_DOCUMENTO), Convert.ToInt32(detalleFactura.ID_PRODUCTO), Convert.ToInt32(detalleFactura.ID_BODEGA), detalleFactura.CANTIDAD, detalleFactura.VALOR_UNIDAD, FECHA_DOCUMENTO, "ENTRADA", conexion, Convert.ToInt32(ID_LOTE), detalleFactura.TALLA, 0, 0, null, detalleFactura.REEMBOLSO);

                            if (ID_INVENTARIO == 0)
                            {
                                conexion.DeshacerTransaccion();
                                MensajeError = "ERROR: Ingresando el inventario: " + _inventario.MensajeError;
                                verificador  = false;
                                break;
                            }
                            else
                            {
                                ID_DESCARGUE = _crtDescargueFactura.AdicionarAlmCrtDescargueInventario(ID_DOCUMENTO, detalleFactura.ID_ORDEN, detalleFactura.ID_PRODUCTO, detalleFactura.ID_DETALLE, detalleFactura.ID_BODEGA, ID_LOTE, detalleFactura.REFERENCIA_PRODUCTO, detalleFactura.TALLA, detalleFactura.CANTIDAD, conexion, detalleFactura.REEMBOLSO);

                                if (ID_DESCARGUE == 0)
                                {
                                    conexion.DeshacerTransaccion();
                                    MensajeError = "ERROR: Ingresando el descargue de inventario: " + _crtDescargueFactura.MensajeError;
                                    verificador  = false;
                                    break;
                                }
                            }
                        }

                        if (listaDeOrdenesParaDescargadas.Contains(detalleFactura.ID_ORDEN) == false)
                        {
                            listaDeOrdenesParaDescargadas.Add(detalleFactura.ID_ORDEN);
                        }
                    }
                }

                if (verificador == true)
                {
                    ordenCompra _ordenCompra = new ordenCompra(Empresa, Usuario);
                    DataTable   tablaDetalleOrden;
                    Int32       CANTIDAD_TOTAL_PRODUCTOS  = 0;
                    Int32       CANTIDAD_TOTAL_DESCARGADA = 0;

                    foreach (Decimal orden in listaDeOrdenesParaDescargadas)
                    {
                        CANTIDAD_TOTAL_PRODUCTOS  = 0;
                        CANTIDAD_TOTAL_DESCARGADA = 0;
                        tablaDetalleOrden         = _ordenCompra.ObtenerDetallesOrdenCompraPorIdOrdenConCantidadDescargada(orden, conexion);

                        foreach (DataRow filaTabla in tablaDetalleOrden.Rows)
                        {
                            try
                            {
                                CANTIDAD_TOTAL_PRODUCTOS  += Convert.ToInt32(filaTabla["CANTIDAD"]);
                                CANTIDAD_TOTAL_DESCARGADA += Convert.ToInt32(filaTabla["CANTIDAD_DESCARGADA"]);
                            }
                            catch (Exception ex)
                            {
                                MensajeError = "ERROR: Al intentar calcular estado de descarga de la orden de compra " + orden.ToString() + ". " + ex.Message;
                                conexion.DeshacerTransaccion();
                                verificador = false;
                                break;
                            }
                        }

                        if (verificador == true)
                        {
                            if ((CANTIDAD_TOTAL_PRODUCTOS - CANTIDAD_TOTAL_DESCARGADA) <= 0)
                            {
                                if (_ordenCompra.ActualizarestadoOrdenCompra(orden, tabla.VAR_ESTADO_ORDEN_COMPRA_FINALIZADA, null) == false)
                                {
                                    MensajeError = _ordenCompra.MensajeError;
                                    conexion.DeshacerTransaccion();
                                    verificador = false;
                                    break;
                                }
                            }
                            else
                            {
                                if (_ordenCompra.ActualizarestadoOrdenCompra(orden, tabla.VAR_ESTADO_ORDEN_COMPRA_ADJUNTADO_FACTURA, null) == false)
                                {
                                    MensajeError = _ordenCompra.MensajeError;
                                    conexion.DeshacerTransaccion();
                                    verificador = false;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (verificador == true)
                    {
                        conexion.AceptarTransaccion();
                    }
                }
            }
            catch (Exception ex)
            {
                conexion.DeshacerTransaccion();
                MensajeError = ex.Message;
                verificador  = false;
            }
            finally
            {
                conexion.Desconectar();
            }

            if (verificador == true)
            {
                return(ID_DOCUMENTO);
            }
            else
            {
                return(0);
            }
        }
    protected DataTable ConsultarInventario(String centroCostos, String subcentroCosto, String ciudad, String[] datos, DataRow fila)
    {
        String id_Ciudad;
        DataTable tablaentregas = new DataTable();
        tablaentregas.Columns.Add("ID_PRODUCTO");
        tablaentregas.Columns.Add("ID_LOTE");
        tablaentregas.Columns.Add("CANTIDAD");
        tablaentregas.Columns.Add("TALLA");

        DataRow entrega = tablaentregas.NewRow();

        if (!(centroCostos.Equals("0")))
        {
            centroCosto _centroC = new centroCosto(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
            DataTable tablaCentro = _centroC.ObtenerCentrosDeCostoPorIdCentroCosto(Convert.ToDecimal(centroCostos));
            DataRow filaCentros = tablaCentro.Rows[0];

            id_Ciudad = filaCentros["ID_CIUDAD"].ToString();
        }
        else if (!(subcentroCosto.Equals("0")))
        {
            subCentroCosto _SubCentroC = new subCentroCosto(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
            DataTable tablaSub = _SubCentroC.ObtenerSubCentrosDeCostoPorIdSubCosto(Convert.ToDecimal(subcentroCosto));
            DataRow filaSubCentro = tablaSub.Rows[0];

            centroCosto _centroC = new centroCosto(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
            DataTable tablaCentro = _centroC.ObtenerCentrosDeCostoPorIdCentroCosto(Convert.ToDecimal(filaSubCentro["ID_CENTRO_C"].ToString()));
            DataRow filaCentros = tablaCentro.Rows[0];

            id_Ciudad = filaCentros["ID_CIUDAD"].ToString();
        }
        else
        {
            id_Ciudad = ciudad;
        }

        int id_empresa = Convert.ToInt32(datos[3].ToString());
        ciudad _ciudad = new ciudad(Session["idEmpresa"].ToString());
        DataTable tablaCiudad = _ciudad.ObtenerCiudadPorIdCiudad(id_Ciudad);
        DataRow filaCiudad = tablaCiudad.Rows[0];

        String id_regional = filaCiudad["ID_REGIONAL"].ToString();
        bodega _bodega = new bodega(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
        DataTable tablabodega = _bodega.ObtenerAlmRegBodegaPorIds(id_regional, id_Ciudad, id_empresa);

        if (tablabodega.Rows.Count <= 0)
        {
            Label_MENSAJE.Text = "ADVERTENCIA: No se encontraron bodegas para la empresa en la ubicación seleccionada. Valide por favor.";
            configurarMensajes(true, System.Drawing.Color.Red, Label_MENSAJE, Panel_MENSAJES);
        }
        else
        {
            DataRow filaBodega = tablabodega.Rows[0];

            lote _lote = new lote(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString());
            HiddenField_idBodega.Value = filaBodega["ID_BODEGA"].ToString();

            DataTable tablaLote = _lote.ObtenerAlmLotePorIdProductoBodega(Convert.ToInt32(fila["ID_PRODUCTO"]), Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()));
            if (tablaLote.Rows.Count <= 0)
            {
                Label_MENSAJE.Text = "ADVERTENCIA: No hay existencias del producto " + fila["NOMBRE"].ToString() + " para la empresa seleccionada. Valide por favor.";
                configurarMensajes(true, System.Drawing.Color.Red, Label_MENSAJE, Panel_MENSAJES);
            }
            else
            {
                int contLote;
                foreach (DataRow filalotes in tablaLote.Rows)
                {
                    entrega = tablaentregas.NewRow();

                    contLote = Convert.ToInt32(filalotes["ENTRADAS"]) - Convert.ToInt32(filalotes["SALIDAS"]);

                    entrega[0] = filalotes["ID_PRODUCTO"];
                    entrega[1] = filalotes["ID_LOTE"];
                    entrega[2] = contLote;
                    entrega[3] = filalotes["TALLA"];

                    tablaentregas.Rows.Add(entrega);
                }
            }
        }
        return tablaentregas;
    }
        public Decimal guardarAjuste(String tipo,
            String idRegional,
            String idCiudad,
            int idEmpresa,
            int idProducto,
            String talla,
            int idLote,
            int CantidadMod,
            Decimal costo,
            String Motivo,
            List<EquipoAjuste> listaEquiposAjuste,
            String NOMBRE_SERVICIO_COMPLEMENTARIO)
        {
            Decimal idDoc = 0;
            DateTime fecha;
            Decimal idInventario = 0;

            Boolean correcto = true;

            fecha = System.DateTime.Today;

            Conexion _dato = new Conexion(Empresa);
            _dato.IniciarTransaccion();

            try
            {
                documento_temp _doc = new documento_temp(Empresa, Usuario);
                idDoc = _doc.AdicionarAlmDocumentosTemp(0, "AJUSTE", "", fecha, new DateTime(), 0, "POR APROBAR", Motivo, _dato);

                if (idDoc <= 0)
                {
                    correcto = false;
                    MensajeError = _doc.MensajeError;
                    _dato.DeshacerTransaccion();
                }
                else
                {
                    bodega _bodega = new bodega(Empresa, Usuario);
                    _bodega.MensajeError = null;
                    DataTable tablaBodega = _bodega.ObtenerAlmRegBodegaPorIds(idRegional, idCiudad, idEmpresa, _dato);

                    if (_bodega.MensajeError != null)
                    {
                        correcto = false;
                        _dato.DeshacerTransaccion();
                        MensajeError = _bodega.MensajeError;
                    }
                    else
                    {
                        DataRow filaBodega = tablaBodega.Rows[0];

                        lote _lote = new lote(Empresa, Usuario);
                        _lote.MensajeError = null;
                        DataTable tablaLote = _lote.ObtenerAlmLotePorId(idLote, _dato);

                        if (_lote.MensajeError != null)
                        {
                            correcto = false;
                            _dato.DeshacerTransaccion();
                            MensajeError = _bodega.MensajeError;
                        }
                        else
                        {
                            DataRow filalote = tablaLote.Rows[0];
                            if (tipo.Equals("COSTO"))
                            {
                                idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, 0, talla, CantidadMod, costo, fecha, "COSTO", _dato);

                                if (idInventario == 0)
                                {
                                    correcto = false;
                                    _dato.DeshacerTransaccion();
                                    MensajeError = _bodega.MensajeError;
                                }
                            }
                            else if (tipo.Equals("ENTRADA"))
                            {
                                if (NOMBRE_SERVICIO_COMPLEMENTARIO != "EQUIPOS")
                                {
                                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, 0, talla, CantidadMod, Convert.ToDecimal(filalote["COSTO"]), fecha, "ENTRADA", _dato);

                                    if (idInventario == 0)
                                    {
                                        correcto = false;
                                        _dato.DeshacerTransaccion();
                                        MensajeError = _bodega.MensajeError;
                                    }
                                }
                                else
                                {
                                    foreach (EquipoAjuste equipo in listaEquiposAjuste)
                                    {
                                        EquipoEntradaTemp _equipoTemp = new EquipoEntradaTemp(Empresa, Usuario);
                                        Decimal ID_EQUIPO_TEMP = _equipoTemp.AdicionarAlmEquipoEntradaTemp(equipo.ID_DOCUMENTO, equipo.MARCA, equipo.MODELO, equipo.SERIE, equipo.IMEI, equipo.NUMERO_CELULAR, fecha, equipo.ID_LOTE, _dato);

                                        if (ID_EQUIPO_TEMP <= 0)
                                        {
                                            correcto = false;
                                            _dato.DeshacerTransaccion();
                                            MensajeError = _bodega.MensajeError;
                                            break;
                                        }
                                        else
                                        {
                                            idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, Convert.ToInt32(ID_EQUIPO_TEMP), talla, 1, Convert.ToDecimal(filalote["COSTO"]), fecha, "ENTRADA", _dato);

                                            if (idInventario == 0)
                                            {
                                                correcto = false;
                                                _dato.DeshacerTransaccion();
                                                MensajeError = _bodega.MensajeError;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (NOMBRE_SERVICIO_COMPLEMENTARIO != "EQUIPOS")
                                {
                                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, 0, talla, CantidadMod, Convert.ToDecimal(filalote["COSTO"]), fecha, "SALIDA", _dato);
                                    if (idInventario == 0)
                                    {
                                        correcto = false;
                                        _dato.DeshacerTransaccion();
                                        MensajeError = _bodega.MensajeError;
                                    }
                                }
                                else
                                {
                                    foreach (EquipoAjuste equipo in listaEquiposAjuste)
                                    {
                                        idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, Convert.ToInt32(equipo.ID_EQUIPO), talla, 1, Convert.ToDecimal(filalote["COSTO"]), fecha, "SALIDA", _dato);
                                        if (idInventario == 0)
                                        {
                                            correcto = false;
                                            _dato.DeshacerTransaccion();
                                            MensajeError = _bodega.MensajeError;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (correcto == true)
                {
                    _dato.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                correcto = false;
                MensajeError = ex.Message;
                _dato.DeshacerTransaccion();
            }
            finally
            {
                _dato.Desconectar();
            }

            if (correcto == true)
            {
                return idDoc;
            }
            else
            {
                return 0;
            }
        }
        public Decimal guardarAjuste(String tipo,
            String idRegional,
            String idCiudad,
            int idEmpresa,
            int idProducto,
            String talla,
            int idLote,
            int CantidadMod,
            Decimal costo,
            String Motivo,
            Decimal idDocTemp,
            List<EquipoAjuste> listaEquiposAjuste,
            String NOMBRE_SERVICIO_COMPLEMENTARIO,
            String OBS_AUTORIZACION)
        {
            Decimal idDoc = 0;
            DateTime fecha;
            Decimal idInventario = 0;

            Boolean correcto = true;

            fecha = System.DateTime.Today;

            Conexion _dato = new Conexion(Empresa);
            _dato.IniciarTransaccion();

            try
            {
                documento _doc = new documento(Empresa, Usuario);
                idDoc = _doc.AdicionarAlmDocumentos(0, Convert.ToInt32(idDocTemp), "AJUSTE", "", "", fecha, new DateTime(), 0, 0, 0, "APROBADO", Motivo, _dato, 0, OBS_AUTORIZACION);

                if (idDoc <= 0)
                {
                    _dato.DeshacerTransaccion();
                    correcto = false;
                    MensajeError = _doc.MensajeError;
                }
                else
                {
                    bodega _bodega = new bodega(Empresa, Usuario);
                    DataTable tablaBodega = _bodega.ObtenerAlmRegBodegaPorIds(idRegional, idCiudad, idEmpresa, _dato);

                    if (_bodega.MensajeError != null)
                    {
                        _dato.DeshacerTransaccion();
                        correcto = false;
                        MensajeError = _bodega.MensajeError;
                    }
                    else
                    {
                        DataRow filaBodega = tablaBodega.Rows[0];

                        lote _lote = new lote(Empresa, Usuario);
                        DataTable tablaLote = _lote.ObtenerAlmLotePorId(idLote, _dato);

                        if (_lote.MensajeError != null)
                        {
                            _dato.DeshacerTransaccion();
                            correcto = false;
                            MensajeError = _bodega.MensajeError;
                        }
                        else
                        {

                            DataRow filalote = tablaLote.Rows[0];

                            if (tipo.Equals("COSTO"))
                            {
                                idInventario = AdicionarAlmInventario(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"]), 0, costo, fecha, "COSTO", _dato, idLote, talla, 0, 0, null, filalote["REEMBOLSO"].ToString());
                                if (idInventario <= 0)
                                {
                                    _dato.DeshacerTransaccion();
                                    correcto = false;
                                }
                                else
                                {
                                    if (_lote.ActualizarAlmLote(idLote, Convert.ToInt32(filalote["ID_DOCUMENTO"]), idProducto, Convert.ToInt32(filalote["ID_BODEGA"]), Convert.ToDateTime(filalote["FECHA_REGISTRO"]), Convert.ToInt32(filalote["ENTRADAS"]), Convert.ToInt32(filalote["SALIDAS"]), costo, filalote["TALLA"].ToString(), filalote["ACTIVO"].ToString(), _dato) == false)
                                    {
                                        _dato.DeshacerTransaccion();
                                        correcto = false;
                                        MensajeError = _lote.MensajeError;
                                    }
                                }
                            }
                            else if (tipo.Equals("ENTRADA"))
                            {
                                int contenido = 0;
                                int entradas = 0;
                                int salidas = 0;

                                if (NOMBRE_SERVICIO_COMPLEMENTARIO != "EQUIPOS")
                                {
                                    entradas = Convert.ToInt32(filalote["ENTRADAS"]) + CantidadMod;
                                    salidas = Convert.ToInt32(filalote["SALIDAS"]);

                                    contenido = entradas - salidas;

                                    String activo = "S";
                                    if (contenido <= 0)
                                    {
                                        activo = "N";
                                    }

                                    idInventario = AdicionarAlmInventario(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"]), CantidadMod, Convert.ToDecimal(filalote["COSTO"]), fecha, "ENTRADA", _dato, idLote, filalote["TALLA"].ToString(), 0, 0, null, filalote["REEMBOLSO"].ToString());

                                    if (idInventario <= 0)
                                    {
                                        _dato.DeshacerTransaccion();
                                        correcto = false;
                                    }
                                    else
                                    {
                                        if (_lote.ActualizarAlmLote(idLote, Convert.ToInt32(filalote["ID_DOCUMENTO"]), idProducto, Convert.ToInt32(filalote["ID_BODEGA"]), Convert.ToDateTime(filalote["FECHA_REGISTRO"]), entradas, salidas, Convert.ToDecimal(filalote["COSTO"]), filalote["TALLA"].ToString(), activo, _dato) == false)
                                        {
                                            _dato.DeshacerTransaccion();
                                            correcto = false;
                                            MensajeError += _lote.MensajeError;
                                        }
                                    }
                                }
                                else
                                {
                                    producto _prod = new producto(Empresa, Usuario);

                                    entradas = Convert.ToInt32(filalote["ENTRADAS"]);
                                    salidas = Convert.ToInt32(filalote["SALIDAS"]);

                                    foreach (EquipoAjuste equipo in listaEquiposAjuste)
                                    {
                                        Decimal ID_NUEVO_EQUIPO = _prod.AdicionarAlmEquipo(Convert.ToInt32(equipo.ID_DOCUMENTO), equipo.MARCA, equipo.MODELO, equipo.SERIE, equipo.IMEI, equipo.NUMERO_CELULAR, "S", fecha, Convert.ToDecimal(idLote), _dato);

                                        if (ID_NUEVO_EQUIPO <= 0)
                                        {
                                            _dato.DeshacerTransaccion();
                                            correcto = false;
                                            MensajeError += _lote.MensajeError;
                                            break;
                                        }
                                        else
                                        {
                                            entradas += 1;
                                            contenido = entradas - salidas;

                                            String activo = "S";
                                            if (contenido <= 0)
                                            {
                                                activo = "N";
                                            }

                                            idInventario = AdicionarAlmInventario(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"]), 1, Convert.ToDecimal(filalote["COSTO"]), fecha, "ENTRADA", _dato, idLote, filalote["TALLA"].ToString(), Convert.ToInt32(ID_NUEVO_EQUIPO), 0, null, filalote["REEMBOLSO"].ToString());

                                            if (idInventario <= 0)
                                            {
                                                _dato.DeshacerTransaccion();
                                                correcto = false;
                                                break;
                                            }
                                            else
                                            {
                                                if (_lote.ActualizarAlmLote(idLote, Convert.ToInt32(filalote["ID_DOCUMENTO"]), idProducto, Convert.ToInt32(filalote["ID_BODEGA"]), Convert.ToDateTime(filalote["FECHA_REGISTRO"]), entradas, salidas, Convert.ToDecimal(filalote["COSTO"]), filalote["TALLA"].ToString(), activo, _dato) == false)
                                                {
                                                    _dato.DeshacerTransaccion();
                                                    correcto = false;
                                                    MensajeError += _lote.MensajeError;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                int contenido = 0;
                                int entradas = 0;
                                int salidas = 0;

                                if (NOMBRE_SERVICIO_COMPLEMENTARIO != "EQUIPOS")
                                {
                                    entradas = Convert.ToInt32(filalote["ENTRADAS"]);
                                    salidas = Convert.ToInt32(filalote["SALIDAS"]) + CantidadMod;

                                    contenido = entradas - salidas;

                                    String activo = "S";
                                    if (contenido <= 0)
                                    {
                                        activo = "N";
                                    }

                                    idInventario = AdicionarAlmInventario(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"]), CantidadMod, Convert.ToDecimal(filalote["COSTO"]), fecha, "SALIDA", _dato, idLote, filalote["TALLA"].ToString(), 0, 0, null, filalote["REEMBOLSO"].ToString());

                                    if (idInventario <= 0)
                                    {
                                        _dato.DeshacerTransaccion();
                                        correcto = false;
                                    }
                                    else
                                    {
                                        if (_lote.ActualizarAlmLote(idLote, Convert.ToInt32(filalote["ID_DOCUMENTO"]), idProducto, Convert.ToInt32(filalote["ID_BODEGA"]), Convert.ToDateTime(filalote["FECHA_REGISTRO"]), entradas, salidas, Convert.ToDecimal(filalote["COSTO"]), filalote["TALLA"].ToString(), activo, _dato) == false)
                                        {
                                            _dato.DeshacerTransaccion();
                                            correcto = false;
                                            MensajeError += _lote.MensajeError;
                                        }
                                    }
                                }
                                else
                                {
                                    producto _prod = new producto(Empresa, Usuario);

                                    entradas = Convert.ToInt32(filalote["ENTRADAS"]);
                                    salidas = Convert.ToInt32(filalote["SALIDAS"]);

                                    foreach (EquipoAjuste equipo in listaEquiposAjuste)
                                    {
                                        if (_prod.ActualizarAlmEquipoIdLoteActualIDocumentoActualParaSalida(equipo.ID_EQUIPO, "N", 0, 0, _dato) == false)
                                        {
                                            _dato.DeshacerTransaccion();
                                            correcto = false;
                                            MensajeError += _prod.MensajeError;
                                            break;
                                        }
                                        else
                                        {
                                            salidas += 1;

                                            contenido = entradas - salidas;

                                            String activo = "S";
                                            if (contenido <= 0)
                                            {
                                                activo = "N";
                                            }

                                            idInventario = AdicionarAlmInventario(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"]), 1, Convert.ToDecimal(filalote["COSTO"]), fecha, "SALIDA", _dato, idLote, filalote["TALLA"].ToString(), Convert.ToInt32(equipo.ID_EQUIPO), 0, null, filalote["REEMBOLSO"].ToString());

                                            if (idInventario <= 0)
                                            {
                                                _dato.DeshacerTransaccion();
                                                correcto = false;
                                                break;
                                            }
                                            else
                                            {
                                                if (_lote.ActualizarAlmLote(idLote, Convert.ToInt32(filalote["ID_DOCUMENTO"]), idProducto, Convert.ToInt32(filalote["ID_BODEGA"]), Convert.ToDateTime(filalote["FECHA_REGISTRO"]), entradas, salidas, Convert.ToDecimal(filalote["COSTO"]), filalote["TALLA"].ToString(), activo, _dato) == false)
                                                {
                                                    _dato.DeshacerTransaccion();
                                                    correcto = false;
                                                    MensajeError += _lote.MensajeError;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (correcto == true)
                {
                    documento_temp _docTemp = new documento_temp(Empresa, Usuario);
                    if (_docTemp.ActualizarAlmDocumentoTemp(Convert.ToInt32(idDocTemp), Convert.ToDateTime(DateTime.Now.ToShortDateString()), "APROBADO", _dato, OBS_AUTORIZACION) == false)
                    {
                        _dato.DeshacerTransaccion();
                        correcto = false;
                        MensajeError = _docTemp.MensajeError;
                    }
                }

                if (correcto == true)
                {
                    _dato.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                _dato.DeshacerTransaccion();
                correcto = false;
                MensajeError = ex.Message;
            }
            finally
            {
                _dato.Desconectar();
            }

            if (correcto == true)
            {
                return idDoc;
            }
            else
            {
                return 0;
            }
        }
        public Decimal guardarDevolucion(List<int> ID_LOTE,
            int ID_BODEGA,
            int ID_EMPLEADO,
            List<int> ID_DOCUMENTO,
            List<int> ID_INVENTARIO,
            List<int> ID_PRODUCTO,
            List<int> cantidad,
            List<String> Estado,
            List<String> motivo,
            List<Decimal> ID_DETALLE_ENTREGAS,
            List<EquipoEntrega> listaEquiposDevueltos)
        {
            Decimal idDocumento = 0;
            Decimal idInventario = 0;
            Decimal idLote = 0;

            DateTime fecha = System.DateTime.Today;
            documento _doc = new documento(Empresa, Usuario);
            Inventario _inventario = new Inventario(Empresa, Usuario);
            Conexion _dato = new Conexion(Empresa);
            lote _lote = new lote(Empresa, Usuario);
            int cuenta = 0;

            Boolean correcto = true;

            _dato.IniciarTransaccion();

            try
            {
                idDocumento = _doc.AdicionarAlmDocumentos(ID_EMPLEADO, 0, "DEVOLUCION", "", "", fecha, new DateTime(), 0, 0, 0, "", "", _dato, 0, null);

                if (idDocumento == 0)
                {
                    correcto = false;
                    MensajeError = _doc.MensajeError;
                    _dato.DeshacerTransaccion();
                }
                else
                {
                    for (int i = 0; i < ID_PRODUCTO.Count; i++)
                    {
                        _lote.MensajeError = null;

                        DataTable tablalote = _lote.ObtenerAlmLotePorId(ID_LOTE[i], _dato);

                        if (_lote.MensajeError != null)
                        {
                            correcto = false;
                            _dato.DeshacerTransaccion();
                            MensajeError = _lote.MensajeError;
                            break;
                        }
                        else
                        {
                            DataRow filalote = tablalote.Rows[0];

                            String activoLote = "S";
                            if (Estado[i] != "BUENO")
                            {
                                activoLote = "N";
                            }

                            idLote = _lote.AdicionarAlmLote(ID_DOCUMENTO[i], ID_PRODUCTO[i], Convert.ToInt32(filalote["ID_BODEGA"]), Convert.ToDateTime(DateTime.Now.ToShortDateString()), cantidad[i], 0, Convert.ToDecimal(filalote["COSTO"]), filalote["TALLA"].ToString().Trim(), activoLote, _dato, filalote["REEMBOLSO"].ToString());

                            if (idLote == 0)
                            {
                                correcto = false;
                                MensajeError = _lote.MensajeError;
                                _dato.DeshacerTransaccion();
                                break;
                            }
                            else
                            {
                                _inventario.MensajeError = null;
                                idInventario = _inventario.AdicionarAlmInventario(Convert.ToInt32(idDocumento), ID_PRODUCTO[i], Convert.ToInt32(filalote["ID_BODEGA"]), cantidad[i], Convert.ToDecimal(filalote["COSTO"]), Convert.ToDateTime(DateTime.Now.ToShortDateString()), "ENTRADA", _dato, Convert.ToInt32(idLote), filalote["TALLA"].ToString(), 0, ID_DETALLE_ENTREGAS[i], motivo[i], filalote["REEMBOLSO"].ToString());

                                if (idInventario <= 0)
                                {
                                    correcto = false;
                                    MensajeError = _inventario.MensajeError;
                                    _dato.DeshacerTransaccion();
                                    break;
                                }
                                else
                                {
                                    cuenta++;
                                }
                            }
                        }
                    }

                    if (correcto == true)
                    {
                        foreach (EquipoEntrega equipo in listaEquiposDevueltos)
                        {
                            _lote.MensajeError = null;

                            DataTable tablalote = _lote.ObtenerAlmLotePorId(Convert.ToInt32(equipo.ID_LOTE), _dato);

                            if (_lote.MensajeError != null)
                            {
                                correcto = false;
                                _dato.DeshacerTransaccion();
                                MensajeError = _lote.MensajeError;
                                break;
                            }
                            else
                            {
                                DataRow filalote = tablalote.Rows[0];

                                String activoLote = "S";
                                if (equipo.ESTADO_DEV != "BUENO")
                                {
                                    activoLote = "N";
                                }

                                idLote = _lote.AdicionarAlmLote(Convert.ToInt32(equipo.ID_DOCUMENTO), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(filalote["ID_BODEGA"]), Convert.ToDateTime(DateTime.Now.ToShortDateString()), 1, 0, Convert.ToDecimal(filalote["COSTO"]), filalote["TALLA"].ToString().Trim(), activoLote, _dato, filalote["REEMBOLSO"].ToString());

                                if (idLote == 0)
                                {
                                    correcto = false;
                                    MensajeError = _lote.MensajeError;
                                    _dato.DeshacerTransaccion();
                                    break;
                                }
                                else
                                {
                                    _inventario.MensajeError = null;
                                    idInventario = _inventario.AdicionarAlmInventario(Convert.ToInt32(idDocumento), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(filalote["ID_BODEGA"]), 1, Convert.ToDecimal(filalote["COSTO"]), Convert.ToDateTime(DateTime.Now.ToShortDateString()), "ENTRADA", _dato, Convert.ToInt32(idLote), filalote["TALLA"].ToString(), Convert.ToInt32(equipo.ID_EQUIPO), equipo.ID_DETALLE_ENTREGAS, equipo.DETALLE_DEV, filalote["REEMBOLSO"].ToString());

                                    if (idInventario <= 0)
                                    {
                                        correcto = false;
                                        MensajeError = _inventario.MensajeError;
                                        _dato.DeshacerTransaccion();
                                        break;
                                    }
                                    else
                                    {
                                        Entrega _entrega = new Entrega(Empresa, Usuario);
                                        if (_entrega.ActualizarAlmEquiposEntregaDevolucion(equipo.ID_EQUIPO_ENTREGA, equipo.ID_EQUIPO, idLote, idDocumento, equipo.ESTADO_DEV, equipo.DETALLE_DEV, _dato) == false)
                                        {
                                            correcto = false;
                                            MensajeError = _entrega.MensajeError;
                                            _dato.DeshacerTransaccion();
                                            break;
                                        }
                                        else
                                        {
                                            cuenta++;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (correcto == true)
                    {
                        if (cuenta != (ID_PRODUCTO.Count + listaEquiposDevueltos.Count))
                        {
                            correcto = false;
                            _dato.DeshacerTransaccion();
                            MensajeError = "Ocurrio un error inesperado, el numero de productos y equipos procesados no corresponde.";
                        }
                    }
                }

                if (correcto == true)
                {
                    _dato.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                _dato.DeshacerTransaccion();
                MensajeError = ex.Message;
                correcto = false;
            }
            finally
            {
                _dato.Desconectar();
            }

            if (correcto == true)
            {
                return idDocumento;
            }
            else
            {
                return 0;
            }
        }
        public Decimal guardarTraslado(Decimal id_bodega_origen,
            List<int> lista_productos,
            List<int> lista_Cantidades,
            List<int> lista_lotes,
            Decimal id_bodega_destino,
            String Observaciones,
            List<String> talla,
            List<EquipoTraslado> listaEquiposTraslado)
        {
            int cantidadRegistrosActualizados = 0;
            int ConteLo;

            DateTime fecha = System.DateTime.Today;
            Decimal idInventario = 0;
            Decimal idDOC = 0;

            Boolean correcto = true;

            Conexion conexion = new Conexion(Empresa);
            conexion.IniciarTransaccion();

            try
            {
                lote _lote = new lote(Empresa, Usuario);

                documento _doc = new documento(Empresa, Usuario);
                idDOC = _doc.AdicionarAlmDocumentos(0, 0, "TRASLADO", "", "", fecha, new DateTime(), Convert.ToInt32(id_bodega_destino), 0, 0, "ELABORADO", Observaciones, conexion, 0, null);

                if (idDOC == 0)
                {
                    conexion.DeshacerTransaccion();
                    correcto = false;
                    MensajeError = _doc.MensajeError;
                }
                else
                {
                    for (int i = 0; i < lista_productos.Count; i++)
                    {
                        _lote.MensajeError = null;
                        DataTable tablalo = _lote.ObtenerAlmLotePorId(lista_lotes[i], conexion);

                        if (_lote.MensajeError != null)
                        {
                            conexion.DeshacerTransaccion();
                            correcto = false;
                            break;
                        }
                        else
                        {
                            DataRow filalo = tablalo.Rows[0];
                            ConteLo = Convert.ToInt32(filalo["ENTRADAS"]) - Convert.ToInt32(filalo["SALIDAS"]);

                            if (lista_Cantidades[i] <= ConteLo)
                            {
                                idInventario = AdicionarAlmInventario(Convert.ToInt32(idDOC), lista_productos[i], Convert.ToInt32(id_bodega_origen), lista_Cantidades[i], Convert.ToDecimal(filalo["COSTO"]), fecha, "SALIDA", conexion, lista_lotes[i], talla[i], 0, 0, null, filalo["REEMBOLSO"].ToString());

                                if (idInventario == 0)
                                {
                                    conexion.DeshacerTransaccion();
                                    MensajeError += "ADVERTENCIA: El registro de inventario no pudo ser creado. Valide Por favor.";
                                    correcto = false;
                                    break;
                                }
                                else
                                {
                                    String activo = "S";
                                    if (ConteLo - lista_Cantidades[i] <= 0)
                                    {
                                        activo = "N";
                                    }

                                    if (_lote.ActualizarAlmLote(lista_lotes[i], Convert.ToInt32(filalo["ID_DOCUMENTO"]), lista_productos[i], Convert.ToInt32(id_bodega_origen), Convert.ToDateTime(filalo["FECHA_REGISTRO"]), Convert.ToInt32(filalo["ENTRADAS"]), Convert.ToInt32(filalo["SALIDAS"]) + lista_Cantidades[i], Convert.ToDecimal(filalo["COSTO"]), filalo["TALLA"].ToString(), activo, conexion) == false)
                                    {
                                        conexion.DeshacerTransaccion();
                                        correcto = false;
                                        MensajeError += "ADVERTENCIA: El registro del lote no pudo ser actualizado. Verifique Por Favor";
                                        break;
                                    }
                                    else
                                    {
                                        cantidadRegistrosActualizados++;
                                    }
                                }
                            }
                            else
                            {
                                conexion.DeshacerTransaccion();
                                correcto = false;
                                MensajeError += "ADVERTENCIA: La cantidad de producto (" + lista_productos[i].ToString() + ") solicitada no puede ser sacada del lote (" + lista_lotes[i].ToString() + ") seleccionado, cambie la cantidad o haga varios registros con cantidades posibles.";
                                break;
                            }
                        }
                    }

                    foreach (EquipoTraslado equipo in listaEquiposTraslado)
                    {
                        _lote.MensajeError = null;
                        DataTable tablalo = _lote.ObtenerAlmLotePorId(Convert.ToInt32(equipo.ID_LOTE), conexion);

                        if (_lote.MensajeError != null)
                        {
                            conexion.DeshacerTransaccion();
                            correcto = false;
                            break;
                        }
                        else
                        {
                            DataRow filalo = tablalo.Rows[0];
                            ConteLo = Convert.ToInt32(filalo["ENTRADAS"]) - Convert.ToInt32(filalo["SALIDAS"]);

                            if (1 <= ConteLo)
                            {
                                idInventario = AdicionarAlmInventario(Convert.ToInt32(idDOC), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(id_bodega_origen), 1, Convert.ToDecimal(filalo["COSTO"]), fecha, "SALIDA", conexion, Convert.ToInt32(equipo.ID_LOTE), filalo["TALLA"].ToString(), Convert.ToInt32(equipo.ID_EQUIPO), 0, null, filalo["REEMBOLSO"].ToString());

                                if (idInventario == 0)
                                {
                                    conexion.DeshacerTransaccion();
                                    MensajeError += "ADVERTENCIA: El registro de inventario no pudo ser creado. Valide Por favor.";
                                    correcto = false;
                                    break;
                                }
                                else
                                {
                                    String activo = "S";
                                    if (ConteLo - 1 <= 0)
                                    {
                                        activo = "N";
                                    }

                                    if (_lote.ActualizarAlmLote(Convert.ToInt32(equipo.ID_LOTE), Convert.ToInt32(filalo["ID_DOCUMENTO"]), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(filalo["ID_BODEGA"]), Convert.ToDateTime(filalo["FECHA_REGISTRO"]), Convert.ToInt32(filalo["ENTRADAS"]), Convert.ToInt32(filalo["SALIDAS"]) + 1, Convert.ToDecimal(filalo["COSTO"]), filalo["TALLA"].ToString(), activo, conexion) == false)
                                    {
                                        conexion.DeshacerTransaccion();
                                        correcto = false;
                                        MensajeError += "ADVERTENCIA: El registro del lote no pudo ser actualizado. Verifique Por Favor";
                                        break;
                                    }
                                    else
                                    {
                                        _lote.MensajeError = null;
                                        if (_lote.ActualizarLoteActualDeUnEquipo(equipo.ID_EQUIPO, 0, 0, conexion) == false)
                                        {
                                            conexion.DeshacerTransaccion();
                                            correcto = false;
                                            MensajeError = _lote.MensajeError;
                                            break;
                                        }
                                        else
                                        {
                                            cantidadRegistrosActualizados++;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                conexion.DeshacerTransaccion();
                                correcto = false;
                                MensajeError += "ADVERTENCIA: La cantidad de (equipo(s)) solicitada no puede ser sacada del lote (" + equipo.ID_LOTE.ToString() + ") seleccionado, cambie la cantidad o haga varios registros con cantidades posibles.";
                                break;
                            }
                        }
                    }
                }

                if (correcto == true)
                {
                    conexion.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                conexion.DeshacerTransaccion();
                correcto = false;
                MensajeError = ex.Message;
            }
            finally
            {
                conexion.Desconectar();
            }

            if (correcto == true)
            {
                return idDOC;
            }
            else
            {
                return 0;
            }
        }
        public Boolean guardarTrasladoIngreso(int idDocumento,
            List<int> listaProductos,
            int idbodegaDest,
            List<int> listacantidad,
            List<int> listalote,
            List<String> listaTallas,
            int falta,
            List<EquipoTraslado> listaEquiposTraslado)
        {
            int transaccion = 0;
            Boolean retorno = true;
            Decimal idLote = 0;
            String estado;
            Decimal id_inventario = 0;

            Conexion conexion = new Conexion(Empresa);
            conexion.IniciarTransaccion();

            lote _lote = new lote(Empresa, Usuario);

            try
            {
                for (int i = 0; i < listaProductos.Count; i++)
                {
                    _lote.MensajeError = null;
                    DataTable tablalote = _lote.ObtenerAlmLotePorId(listalote[i], conexion);

                    if (_lote.MensajeError != null)
                    {
                        retorno = false;
                        MensajeError = _lote.MensajeError;
                        conexion.DeshacerTransaccion();
                        break;
                    }
                    else
                    {
                        DataRow filalote = tablalote.Rows[0];
                        Decimal costo = Convert.ToDecimal(filalote["COSTO"]);
                        DateTime fecha = System.DateTime.Today;

                        idLote = _lote.AdicionarAlmLote(Convert.ToInt32(filalote["ID_DOCUMENTO"]), listaProductos[i], idbodegaDest, fecha, listacantidad[i], 0, costo, listaTallas[i], "S", conexion, filalote["REEMBOLSO"].ToString());
                        if (idLote <= 0)
                        {
                            retorno = false;
                            conexion.DeshacerTransaccion();
                            MensajeError += "No fue posible crear el lote por: " + _lote.MensajeError;
                            break;
                        }
                        else
                        {
                            id_inventario = AdicionarAlmInventario(idDocumento, listaProductos[i], idbodegaDest, listacantidad[i], costo, fecha, "ENTRADA", conexion, Convert.ToInt32(idLote), listaTallas[i], 0, 0, null, filalote["REEMBOLSO"].ToString());

                            if (id_inventario <= 0)
                            {
                                retorno = false;
                                conexion.DeshacerTransaccion();
                                break;
                            }
                            else
                            {
                                transaccion++;
                            }
                        }
                    }
                }

                if (retorno == true)
                {
                    foreach (EquipoTraslado equipo in listaEquiposTraslado)
                    {
                        _lote.MensajeError = null;
                        DataTable tablalote = _lote.ObtenerAlmLotePorId(Convert.ToInt32(equipo.ID_LOTE), conexion);

                        if (_lote.MensajeError != null)
                        {
                            retorno = false;
                            MensajeError = _lote.MensajeError;
                            conexion.DeshacerTransaccion();
                            break;
                        }
                        else
                        {
                            DataRow filalote = tablalote.Rows[0];
                            Decimal costo = Convert.ToDecimal(filalote["COSTO"]);
                            DateTime fecha = System.DateTime.Today;

                            idLote = _lote.AdicionarAlmLote(Convert.ToInt32(filalote["ID_DOCUMENTO"]), Convert.ToInt32(equipo.ID_PRODUCTO), idbodegaDest, fecha, 1, 0, costo, filalote["TALLA"].ToString(), "S", conexion, filalote["REEMBOLSO"].ToString());
                            if (idLote <= 0)
                            {
                                retorno = false;
                                conexion.DeshacerTransaccion();
                                MensajeError += "No fue posible crear el lote por: " + _lote.MensajeError;
                                break;
                            }
                            else
                            {
                                id_inventario = AdicionarAlmInventario(idDocumento, Convert.ToInt32(equipo.ID_PRODUCTO), idbodegaDest, 1, costo, fecha, "ENTRADA", conexion, Convert.ToInt32(idLote), filalote["TALLA"].ToString(), Convert.ToInt32(equipo.ID_EQUIPO), 0, null, filalote["REEMBOLSO"].ToString());

                                if (id_inventario <= 0)
                                {
                                    retorno = false;
                                    conexion.DeshacerTransaccion();
                                    break;
                                }
                                else
                                {
                                    if (_lote.ActualizarLoteActualDeUnEquipo(equipo.ID_EQUIPO, idLote, Convert.ToDecimal(idDocumento), conexion) == false)
                                    {
                                        retorno = false;
                                        conexion.DeshacerTransaccion();
                                        MensajeError = _lote.MensajeError;
                                        break;
                                    }
                                    else
                                    {
                                        transaccion++;
                                    }
                                }
                            }
                        }
                    }
                }

                if (retorno == true)
                {
                    if (falta > 0)
                    {
                        estado = "RECIBIDO";
                    }
                    else
                    {
                        estado = "COMPLETO";
                    }

                    if (transaccion == (listaProductos.Count + listaEquiposTraslado.Count))
                    {
                        documento _doc = new documento(Empresa, Usuario);
                        DataTable tablaDoc = _doc.ObtenerAlmRegDocumentoPorId(idDocumento);
                        DataRow filaDoc = tablaDoc.Rows[0];

                        if (_doc.ActualizarAlmDocumento(idDocumento, 0, 0, "TRASLADO", "", "", Convert.ToDateTime(filaDoc["FECHA_DOCUMENTO"]), new DateTime(), idbodegaDest, 0, 0, estado, filaDoc["OBSERVACION_JUSTIFICACION"].ToString(), 0, conexion) == false)
                        {
                            retorno = false;
                            MensajeError = _doc.MensajeError;
                            conexion.DeshacerTransaccion();
                        }
                    }
                    else
                    {
                        MensajeError = "la transaccion arrojó un resultado inconcistente en cuanto a los productos que se tenian que procesar.";
                        retorno = false;
                        conexion.DeshacerTransaccion();
                    }
                }

                if (retorno == true)
                {
                    conexion.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                retorno = false;
                conexion.DeshacerTransaccion();
                MensajeError = ex.Message;
            }
            finally
            {
                conexion.Desconectar();
            }

            return retorno;
        }
        public Decimal AdicionarEntregaProductos(Decimal id_empleado,
            List<Entrega> listaProductosEntrega,
            List<Equipo> listaEquiposEntrega)
        {
            Conexion conexion = new Conexion(Empresa);
            conexion.IniciarTransaccion();

            Boolean correcto = true;

            Decimal id_documento_entrega = 0;

            try
            {
                documento _documento = new documento(Empresa, Usuario);
                id_documento_entrega = _documento.AdicionarAlmDocumentos(Convert.ToInt32(id_empleado), 0, TiposDeDocumento.ENTREGA.ToString(), null, null, DateTime.Now, new DateTime(), 0, 0, 0, EstadosDocumento.COMPLETO.ToString(), null, conexion, 0, null);

                if (id_documento_entrega <= 0)
                {
                    conexion.DeshacerTransaccion();
                    correcto = false;
                    MensajeError = _documento.MensajeError;
                    id_documento_entrega = 0;
                }
                else
                {
                    lote _lote = new lote(Empresa, Usuario);
                    Inventario _inventario = new Inventario(Empresa, Usuario);

                    Dictionary<Decimal, Decimal> listaIndices = new Dictionary<Decimal, Decimal>();

                    foreach (Entrega productoEntrega in listaProductosEntrega)
                    {
                        DataTable tablaLote = _lote.ObtenerAlmLotePorId(Convert.ToInt32(productoEntrega.ID_LOTE), conexion);
                        DataRow filaLote = tablaLote.Rows[0];

                        Decimal ID_BODEGA = Convert.ToDecimal(filaLote["ID_BODEGA"]);
                        Decimal COSTO_UNIDAD = Convert.ToDecimal(filaLote["COSTO"]);
                        Decimal COSTO_TOTAL = (COSTO_UNIDAD * productoEntrega.CANTIDAD);

                        Decimal ID_INVENTARIO = _inventario.AdicionarAlmInventario(Convert.ToInt32(id_documento_entrega), Convert.ToInt32(productoEntrega.ID_PRODUCTO), Convert.ToInt32(ID_BODEGA), productoEntrega.CANTIDAD, Convert.ToDecimal(filaLote["COSTO"]), DateTime.Now, TiposMovimientos.SALIDA.ToString(), conexion, Convert.ToInt32(productoEntrega.ID_LOTE), productoEntrega.TALLA, 0, 0, null, filaLote["REEMBOLSO"].ToString());

                        if (ID_INVENTARIO <= 0)
                        {
                            conexion.DeshacerTransaccion();
                            correcto = false;
                            MensajeError = _inventario.MensajeError;
                            id_documento_entrega = 0;
                            break;
                        }
                        else
                        {
                            if (_lote.ActualizarCantidadesInventario(productoEntrega.ID_LOTE, productoEntrega.CANTIDAD, TiposMovimientos.SALIDA.ToString(), conexion) == false)
                            {
                                conexion.DeshacerTransaccion();
                                correcto = false;
                                MensajeError = _inventario.MensajeError;
                                id_documento_entrega = 0;
                                break;
                            }
                            else
                            {
                                Decimal ID_ASIGNACION_SC = 0;

                                if (productoEntrega.ID_ASIGNACION_SC == 0)
                                {
                                    if (listaIndices.ContainsKey(productoEntrega.ID_INDEX) == true)
                                    {
                                        ID_ASIGNACION_SC = listaIndices[productoEntrega.ID_INDEX];
                                    }
                                    else
                                    {
                                        ID_ASIGNACION_SC = AdicionarEscAsignacionSC(id_empleado, productoEntrega.ID_PRODUCTO, productoEntrega.CANTIDAD_TOTAL, 0, productoEntrega.FECHA_PROYECTADA_ENTREGA, productoEntrega.TIPO_ENTREGA, EstadosAsignacionSC.ABIERTA.ToString(), conexion);

                                        if (ID_ASIGNACION_SC <= 0)
                                        {
                                            conexion.DeshacerTransaccion();
                                            correcto = false;
                                            id_documento_entrega = 0;
                                            break;
                                        }
                                        else
                                        {
                                            listaIndices.Add(productoEntrega.ID_INDEX, ID_ASIGNACION_SC);
                                        }
                                    }
                                }
                                else
                                {
                                    ID_ASIGNACION_SC = productoEntrega.ID_ASIGNACION_SC;
                                }

                                Decimal ID_DETALLE_ASIGNACION = AdicionarEscDetalleContenidoAsignacion(ID_ASIGNACION_SC, id_documento_entrega, productoEntrega.CANTIDAD, productoEntrega.TALLA, COSTO_UNIDAD, COSTO_TOTAL, productoEntrega.ID_LOTE, conexion, ID_INVENTARIO);

                                if (ID_DETALLE_ASIGNACION <= 0)
                                {
                                    conexion.DeshacerTransaccion();
                                    correcto = false;
                                    id_documento_entrega = 0;
                                    break;
                                }
                                else
                                {
                                    if (ActualizarCantidadesAsignacion(ID_ASIGNACION_SC, productoEntrega.CANTIDAD, conexion) == false)
                                    {
                                        conexion.DeshacerTransaccion();
                                        correcto = false;
                                        id_documento_entrega = 0;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    listaIndices = new Dictionary<Decimal, Decimal>();

                    foreach (Equipo equipo in listaEquiposEntrega)
                    {
                        DataTable tablaLote = _lote.ObtenerAlmLotePorId(Convert.ToInt32(equipo.ID_LOTE), conexion);
                        DataRow filaLote = tablaLote.Rows[0];

                        Decimal ID_BODEGA = Convert.ToDecimal(filaLote["ID_BODEGA"]);
                        Decimal COSTO_UNIDAD = Convert.ToDecimal(filaLote["COSTO"]);

                        Decimal ID_INVENTARIO = _inventario.AdicionarAlmInventario(Convert.ToInt32(id_documento_entrega), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(ID_BODEGA), 1, Convert.ToDecimal(filaLote["COSTO"]), DateTime.Now, TiposMovimientos.SALIDA.ToString(), conexion, Convert.ToInt32(equipo.ID_LOTE), filaLote["TALLA"].ToString(), Convert.ToInt32(equipo.ID_EQUIPO), 0, null, filaLote["REEMBOLSO"].ToString());

                        if (ID_INVENTARIO <= 0)
                        {
                            conexion.DeshacerTransaccion();
                            correcto = false;
                            MensajeError = _inventario.MensajeError;
                            id_documento_entrega = 0;
                            break;
                        }
                        else
                        {
                            if (_lote.ActualizarCantidadesInventario(equipo.ID_LOTE, 1, TiposMovimientos.SALIDA.ToString(), conexion) == false)
                            {
                                conexion.DeshacerTransaccion();
                                correcto = false;
                                MensajeError = _inventario.MensajeError;
                                id_documento_entrega = 0;
                                break;
                            }
                            else
                            {
                                Decimal ID_ASIGNACION_SC = 0;

                                if (equipo.ID_ASIGNACION_SC == 0)
                                {
                                    if (listaIndices.ContainsKey(equipo.ID_INDEX) == true)
                                    {
                                        ID_ASIGNACION_SC = listaIndices[equipo.ID_INDEX];
                                    }
                                    else
                                    {
                                        ID_ASIGNACION_SC = AdicionarEscAsignacionSC(id_empleado, equipo.ID_PRODUCTO, equipo.CANTIDAD_TOTAL, 0, equipo.FECHA_PROYECTADA_ENTREGA, equipo.TIPO_ENTREGA, EstadosAsignacionSC.ABIERTA.ToString(), conexion);

                                        if (ID_ASIGNACION_SC <= 0)
                                        {
                                            conexion.DeshacerTransaccion();
                                            correcto = false;
                                            id_documento_entrega = 0;
                                            break;
                                        }
                                        else
                                        {
                                            listaIndices.Add(equipo.ID_INDEX, ID_ASIGNACION_SC);
                                        }
                                    }
                                }
                                else
                                {
                                    ID_ASIGNACION_SC = equipo.ID_ASIGNACION_SC;
                                }

                                Decimal ID_DETALLE_ASIGNACION = AdicionarEscDetalleContenidoAsignacion(ID_ASIGNACION_SC, id_documento_entrega, 1, filaLote["TALLA"].ToString(), Convert.ToDecimal(filaLote["COSTO"]), Convert.ToDecimal(filaLote["COSTO"]), equipo.ID_LOTE, conexion, ID_INVENTARIO);

                                if (ID_DETALLE_ASIGNACION <= 0)
                                {
                                    conexion.DeshacerTransaccion();
                                    correcto = false;
                                    id_documento_entrega = 0;
                                    break;
                                }
                                else
                                {
                                    if (ActualizarCantidadesAsignacion(ID_ASIGNACION_SC, 1, conexion) == false)
                                    {
                                        conexion.DeshacerTransaccion();
                                        correcto = false;
                                        id_documento_entrega = 0;
                                        break;
                                    }
                                    else
                                    {
                                        Decimal ID_EQUIPO_ENTREGA = AdicionarAlmEquiposEntrega(equipo.ID_EQUIPO, ID_DETALLE_ASIGNACION, DateTime.Now, conexion);

                                        if (ID_EQUIPO_ENTREGA <= 0)
                                        {
                                            conexion.DeshacerTransaccion();
                                            correcto = false;
                                            id_documento_entrega = 0;
                                            break;
                                        }
                                        else
                                        {
                                            if (ActualizarDisponibilidadDeEquipo(equipo.ID_EQUIPO, "N", conexion) == false)
                                            {
                                                conexion.DeshacerTransaccion();
                                                correcto = false;
                                                id_documento_entrega = 0;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (correcto == true)
                {
                    conexion.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                conexion.DeshacerTransaccion();
                correcto = false;
                id_documento_entrega = 0;
                MensajeError = ex.Message;
            }
            finally
            {
                conexion.Desconectar();
            }

            return id_documento_entrega;
        }
        public Decimal guardarGarantia(int idbodega,
            int idLote,
            int idEmpresa,
            int idProducto,
            int Cantidad,
            String idRegional,
            String idCiudad,
            String talla,
            String motivo)
        {
            Boolean correcto = true;

            lote _lote = new lote(Empresa, Usuario);
            documento _doc = new documento(Empresa, Usuario);
            Decimal idDoc = 0;
            Decimal idInventario = 0;
            int idProveedor = 0;

            Conexion _dato = new Conexion(Empresa);
            _dato.IniciarTransaccion();

            try
            {
                _lote.MensajeError = null;
                DataTable tablalote = _lote.ObtenerAlmLotePorId(idLote, _dato);

                if (_lote.MensajeError != null)
                {
                    _dato.DeshacerTransaccion();
                    correcto = false;
                }
                else
                {
                    DataRow filalote = tablalote.Rows[0];
                    Decimal costo = Convert.ToDecimal(filalote["COSTO"]);
                    DateTime fecha = System.DateTime.Today;

                    _doc.MensajeError = null;
                    DataTable tabladoc = _doc.ObtenerAlmRegDocumentoPorId(Convert.ToInt32(filalote["ID_DOCUMENTO"]), _dato);

                    if (_doc.MensajeError != null)
                    {
                        _dato.DeshacerTransaccion();
                        correcto = false;
                    }
                    else
                    {
                        DataRow filaDoc = tabladoc.Rows[0];
                        idProveedor = Convert.ToInt32(filaDoc["ID_PROVEEDOR"]);

                        idDoc = _doc.AdicionarAlmDocumentos(0, 0, "GARANTIA", "", "", fecha, new DateTime(), idbodega, 0, 0, "ELABORADO", motivo, _dato, idProveedor, null);

                        if (idDoc <= 0)
                        {
                            _dato.DeshacerTransaccion();
                            MensajeError += _doc.MensajeError;
                            correcto = false;
                        }
                        else
                        {
                            idInventario = AdicionarAlmInventario(Convert.ToInt32(idDoc), idProducto, idbodega, Cantidad, costo, fecha, "SALIDA", _dato, idLote, talla, 0, 0, null, filalote["REEMBOLSO"].ToString());
                            if (idInventario <= 0)
                            {
                                _dato.DeshacerTransaccion();
                                idDoc = 0;
                                correcto = false;
                            }
                            else
                            {
                                Int32 salidas = Convert.ToInt32(filalote["SALIDAS"]);
                                Int32 entradas = Convert.ToInt32(filalote["ENTRADAS"]);

                                salidas = salidas + Cantidad;

                                String ACTIVO = "S";
                                if (entradas <= salidas)
                                {
                                    ACTIVO = "N";
                                }

                                if (_lote.ActualizarAlmLote(idLote, Convert.ToInt32(filalote["ID_DOCUMENTO"]), idProducto, Convert.ToInt32(idbodega), fecha, entradas, salidas, costo, filalote["TALLA"].ToString(), ACTIVO, _dato) == false)
                                {
                                    _dato.DeshacerTransaccion();
                                    correcto = false;
                                    MensajeError = _lote.MensajeError;
                                }
                            }
                        }
                    }
                }

                if (correcto == true)
                {
                    _dato.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                _dato.DeshacerTransaccion();
                correcto = false;
                MensajeError = ex.Message;
            }
            finally
            {
                _dato.Desconectar();
            }

            if (correcto == true)
            {
                return idDoc;
            }
            else
            {
                return 0;
            }
        }
        public String adicionarEntregasTemp(int idempleado, DateTime fecha, int idBodega, DataTable tablaConfigurados, String[] datos)
        {
            int NumerosEntregas = 0;
            Decimal idDocumento = 0;
            Decimal idOrdenEntrega = 0;

            Brainsbits.LLB.almacen.documento_temp _documento = new almacen.documento_temp(Empresa, Usuario);
            Inventario_temp _inventario = new Inventario_temp(Empresa, Usuario);
            Conexion _dato = new LDA.Conexion(Empresa);
            _dato.IniciarTransaccion();

            #region validaciones
            idDocumento = _documento.AdicionarAlmDocumentosTemp(idempleado, "ENTREGA", "", fecha, Convert.ToDateTime("01/01/1900"), 0, "CONFIGURADO", "", _dato);

            if (idDocumento == 0)
            {
                _dato.DeshacerTransaccion();
                MensajeError += "ADVERTENCIA: No fue posible crear el documento, por la siguiente razón \n" + _documento.MensajeError + "  \ncomuniquese con el administrador";
            }
            else
            {
                foreach (DataRow filaConf in tablaConfigurados.Rows)
                {
                    int idproducto = Convert.ToInt32(filaConf["ID_PRODUCTO"]);
                    int cantidad = Convert.ToInt32(filaConf["CANTIDAD"]);
                    int idlote = Convert.ToInt32(filaConf["ID_LOTE"]);
                    lote _lote = new lote(Empresa, Usuario);
                    DataTable tablalo = _lote.ObtenerAlmLotePorId(idlote);
                    DataRow filalo = tablalo.Rows[0];
                    Decimal costo = Convert.ToInt32(filalo["COSTO"]);
                    String talla = filaConf["TALLA"].ToString();
                    Decimal idinventario = 0;

                    idinventario = _inventario.AdicionarAlmInventarioTemp(Convert.ToInt32(idDocumento), idproducto, idBodega, idlote, 0, talla, cantidad, costo, fecha, "SALIDA", _dato);

                    if (idinventario == 0)
                    {
                        _dato.DeshacerTransaccion();
                        MensajeError += "El registro de inventario no fue posible crearlo por: " + _inventario.MensajeError + " Valide con el Administrador";
                    }
                    else
                    {
                        NumerosEntregas++;
                    }
                }
            }
            if (NumerosEntregas == tablaConfigurados.Rows.Count)
            {
                _dato.AceptarTransaccion();
            }
            else
            {
                _dato.DeshacerTransaccion();
                NumerosEntregas = 0;
            }
            #endregion

            if (NumerosEntregas <= 0) return "";
            return idDocumento.ToString();
        }
        public String adicionarEntregas(int idempleado, DateTime fecha, int idBodega, DataTable tablaConfigurados, DataTable tablalotes, String[] datos, String faltantes)
        {
            int NumerosEntregas = 0;
            Decimal idDocumento = 0;
            Decimal idOrdenEntrega = 0;
            AsignacionServiciosComplementarios _OrdenEntrega = new AsignacionServiciosComplementarios(Empresa, Usuario);
            Brainsbits.LLB.almacen.documento _documento = new almacen.documento(Empresa, Usuario);
            Inventario _inventario = new Inventario(Empresa, Usuario);

            Conexion _dato = new LDA.Conexion(Empresa);
            _dato.IniciarTransaccion();

            #region validaciones
            foreach (DataRow filaConf in tablaConfigurados.Rows)
            {
                foreach (DataRow filaLote in tablalotes.Rows)
                {
                    if (filaConf["ID_PRODUCTO"].Equals(filaLote["ID_PRODUCTO"]) & filaConf["TALLA"].Equals(filaLote["TALLA"]) &
                        Convert.ToInt32(filaConf["CANTIDAD_A_ENTREGAR"]) > Convert.ToInt32(filaLote["CANTIDAD_CONFIGURADA"]))
                    {
                        MensajeError += "La cantidad que se desea entregar es superior a la cantidad que se debe entregar. Valide por favor";
                    }
                    else
                    {
                        idDocumento = _documento.AdicionarAlmDocumentos(idempleado, 0, "ENTREGA", "", "", fecha, new DateTime(), 0, 0, 0, "", "", _dato, 0, null);

                        if (idDocumento == 0)
                        {
                            _dato.DeshacerTransaccion();
                            MensajeError += "ADVERTENCIA: No fue posible crear el documento, por la siguiente razón \n" + _documento.MensajeError + "  \ncomuniquese con el administrador";
                        }
                        else
                        {

                            idOrdenEntrega = _OrdenEntrega.AdicionarAsignacionServiciosComplementarios(Convert.ToInt32(idDocumento), idempleado, fecha, "", _dato);
                            if (idOrdenEntrega == 0)
                            {
                                _dato.DeshacerTransaccion();
                                MensajeError += "ADVERTENCIA: No fue posible crear el documento de Orden de Entrega, por la siguiente razón \n" + _OrdenEntrega.MensajeError + "  \ncomuniquese con el administrador";
                            }
                            else
                            {
                                if (filaConf["ID_PRODUCTO"].Equals(filaLote["ID_PRODUCTO"]) & filaConf["TALLA"].Equals(filaLote["TALLA"]) &
                                    Convert.ToInt32(filaConf["CANTIDAD_A_ENTREGAR"]) <= Convert.ToInt32(filaLote["CONTENIDO_LOTE"]))
                                {
                                    int idproducto = Convert.ToInt32(filaConf["ID_PRODUCTO"]);
                                    int cantidad = Convert.ToInt32(filaConf["CANTIDAD_A_ENTREGAR"]);
                                    int idlote = Convert.ToInt32(filaLote["ID_LOTE"]);
                                    lote _lote = new lote(Empresa, Usuario);
                                    DataTable tablalo = _lote.ObtenerAlmLotePorId(idlote, _dato);
                                    DataRow filalo = tablalo.Rows[0];
                                    Decimal costo = Convert.ToInt32(filalo["COSTO"]);
                                    String talla = filaConf["TALLA"].ToString();
                                    Decimal idinventario = 0;
                                    Decimal idEntrega = 0;

                                    idinventario = _inventario.AdicionarAlmInventario(Convert.ToInt32(idDocumento), idproducto, idBodega, cantidad, costo, fecha, "SALIDA", _dato, idlote, talla, 0, 0, null, filalo["REEMBOLSO"].ToString());

                                    if (idinventario == 0)
                                    {
                                        _dato.DeshacerTransaccion();
                                        MensajeError += "El registro de inventario no fue posible crearlo por: " + _inventario.MensajeError + " Valide con el Administrador";
                                    }
                                    else
                                    {

                                        idEntrega = AdicionarConRegEntregasServiciosComplementarios(Convert.ToInt32(idOrdenEntrega), idproducto, fecha, talla, cantidad, cantidad, "COMPLETA", costo, 0, 0, 0, "N", "", _dato);
                                        if (idEntrega == 0)
                                        {
                                            _dato.DeshacerTransaccion();
                                            MensajeError += "El registro de inventario no fue posible crearlo por: " + MensajeError + " Valide con el Administrador";
                                        }
                                        else
                                        {
                                            NumerosEntregas++;
                                            break;
                                        }

                                    }
                                }
                                else
                                {
                                }
                            }
                        }
                    }
                }
            }
            if (NumerosEntregas == tablaConfigurados.Rows.Count)
            {
                if (faltantes.Equals(""))
                {
                    if (_OrdenEntrega.ActualizarAsignacionServiciosComplementarios(Convert.ToInt32(idOrdenEntrega), Convert.ToInt32(idDocumento), idempleado, fecha, "COMPLETO", _dato))
                    {
                        if (_documento.ActualizarAlmDocumento(Convert.ToInt32(idDocumento), idempleado, 0, "ENTREGA", "", "" + idOrdenEntrega.ToString(), fecha, Convert.ToDateTime("01/01/1900"), 0, 0, 0, "COMPLETO", "", 0, _dato))
                        {
                            _dato.AceptarTransaccion();
                        }
                        else
                        {
                            _dato.DeshacerTransaccion();
                            MensajeError += "No fue posible actualizar el documento por: " + _documento.MensajeError;
                        }
                    }
                    else
                    {
                        _dato.DeshacerTransaccion();
                        MensajeError += "No fue posible actualizar la orden de entrega por: " + _OrdenEntrega.MensajeError;
                    }
                }
                else
                {
                    if (_OrdenEntrega.ActualizarAsignacionServiciosComplementarios(Convert.ToInt32(idOrdenEntrega), Convert.ToInt32(idDocumento), idempleado, fecha, "INCOMPLETO", _dato))
                    {
                        if (_documento.ActualizarAlmDocumento(Convert.ToInt32(idDocumento), idempleado, 0, "ENTREGA", "", "" + idOrdenEntrega.ToString(), fecha, Convert.ToDateTime("01/01/1900"), 0, 0, 0, "INCOMPLETO", faltantes, 0, _dato))
                        {
                            _dato.AceptarTransaccion();
                        }
                        else
                        {
                            _dato.DeshacerTransaccion();
                            MensajeError += "No fue posible actualizar el documento por: " + _documento.MensajeError;
                        }
                    }
                    else
                    {
                        _dato.DeshacerTransaccion();
                        MensajeError += "No fue posible actualizar la orden de entrega por: " + _OrdenEntrega.MensajeError;
                    }
                }
            }
            else
            {
                NumerosEntregas = 0;
            }
            #endregion

            if (NumerosEntregas <= 0) return "";
            return idOrdenEntrega.ToString();
        }
        public Decimal AdicionarDatosFactura(Int32 ID_EMPLEADO,
            Int32 DOCUMENTO_ORIGEN,
            String TIPO_DOC,
            String ORIGEN,
            String NUMERO_DOCUMENTO,
            DateTime FECHA_DOCUMENTO,
            DateTime FECHA_VENCE,
            Int32 ID_BODEGA_DESTINO,
            Decimal VALOR,
            String ESTADO,
            String OBSERVACION_JUSTIFICACION,
            Int32 ID_PROVEEDOR,
            List<documento> listaDetalleFactura)
        {
            Decimal ID_DOCUMENTO = 0;
            Decimal ID_LOTE = 0;
            Decimal ID_INVENTARIO = 0;
            Decimal ID_DESCARGUE = 0;

            Boolean verificador = true;

            List<Decimal> listaDeOrdenesParaDescargadas = new List<Decimal>();

            Conexion conexion = new Conexion(Empresa);
            conexion.IniciarTransaccion();

            try
            {
                ID_DOCUMENTO = AdicionarAlmDocumentosParaFactura(ID_EMPLEADO, DOCUMENTO_ORIGEN, TIPO_DOC, ORIGEN, NUMERO_DOCUMENTO, FECHA_DOCUMENTO, FECHA_VENCE, ID_BODEGA_DESTINO, VALOR, ESTADO, OBSERVACION_JUSTIFICACION, conexion, ID_PROVEEDOR);

                if (ID_DOCUMENTO == 0)
                {
                    conexion.DeshacerTransaccion();
                    MensajeError = MensajeError;
                    verificador = false;
                }
                else
                {
                    lote _lote = new lote(Empresa, Usuario);
                    Inventario _inventario = new Inventario(Empresa, Usuario);
                    crtDescargueFactura _crtDescargueFactura = new crtDescargueFactura(Empresa, Usuario);
                    foreach (documento detalleFactura in listaDetalleFactura)
                    {
                        ID_LOTE = _lote.AdicionarAlmLote(Convert.ToInt32(ID_DOCUMENTO), Convert.ToInt32(detalleFactura.ID_PRODUCTO), Convert.ToInt32(detalleFactura.ID_BODEGA), FECHA_DOCUMENTO, detalleFactura.CANTIDAD, 0, detalleFactura.VALOR_UNIDAD, detalleFactura.TALLA, "S", conexion, detalleFactura.REEMBOLSO);

                        if (ID_LOTE == 0)
                        {
                            conexion.DeshacerTransaccion();
                            MensajeError = "ERROR: Ingresando el lote: " + _lote.MensajeError;
                            verificador = false;
                            break;
                        }
                        else
                        {
                            ID_INVENTARIO = _inventario.AdicionarAlmInventario(Convert.ToInt32(ID_DOCUMENTO), Convert.ToInt32(detalleFactura.ID_PRODUCTO), Convert.ToInt32(detalleFactura.ID_BODEGA), detalleFactura.CANTIDAD, detalleFactura.VALOR_UNIDAD, FECHA_DOCUMENTO, "ENTRADA", conexion, Convert.ToInt32(ID_LOTE), detalleFactura.TALLA, 0, 0, null, detalleFactura.REEMBOLSO);

                            if (ID_INVENTARIO == 0)
                            {
                                conexion.DeshacerTransaccion();
                                MensajeError = "ERROR: Ingresando el inventario: " + _inventario.MensajeError;
                                verificador = false;
                                break;
                            }
                            else
                            {
                                ID_DESCARGUE = _crtDescargueFactura.AdicionarAlmCrtDescargueInventario(ID_DOCUMENTO, detalleFactura.ID_ORDEN, detalleFactura.ID_PRODUCTO, detalleFactura.ID_DETALLE, detalleFactura.ID_BODEGA, ID_LOTE, detalleFactura.REFERENCIA_PRODUCTO, detalleFactura.TALLA, detalleFactura.CANTIDAD, conexion, detalleFactura.REEMBOLSO);

                                if (ID_DESCARGUE == 0)
                                {
                                    conexion.DeshacerTransaccion();
                                    MensajeError = "ERROR: Ingresando el descargue de inventario: " + _crtDescargueFactura.MensajeError;
                                    verificador = false;
                                    break;
                                }
                            }
                        }

                        if (listaDeOrdenesParaDescargadas.Contains(detalleFactura.ID_ORDEN) == false)
                        {
                            listaDeOrdenesParaDescargadas.Add(detalleFactura.ID_ORDEN);
                        }
                    }
                }

                if (verificador == true)
                {
                    ordenCompra _ordenCompra = new ordenCompra(Empresa, Usuario);
                    DataTable tablaDetalleOrden;
                    Int32 CANTIDAD_TOTAL_PRODUCTOS = 0;
                    Int32 CANTIDAD_TOTAL_DESCARGADA = 0;

                    foreach (Decimal orden in listaDeOrdenesParaDescargadas)
                    {
                        CANTIDAD_TOTAL_PRODUCTOS = 0;
                        CANTIDAD_TOTAL_DESCARGADA = 0;
                        tablaDetalleOrden = _ordenCompra.ObtenerDetallesOrdenCompraPorIdOrdenConCantidadDescargada(orden, conexion);

                        foreach (DataRow filaTabla in tablaDetalleOrden.Rows)
                        {
                            try
                            {
                                CANTIDAD_TOTAL_PRODUCTOS += Convert.ToInt32(filaTabla["CANTIDAD"]);
                                CANTIDAD_TOTAL_DESCARGADA += Convert.ToInt32(filaTabla["CANTIDAD_DESCARGADA"]);
                            }
                            catch (Exception ex)
                            {
                                MensajeError = "ERROR: Al intentar calcular estado de descarga de la orden de compra " + orden.ToString() + ". " + ex.Message;
                                conexion.DeshacerTransaccion();
                                verificador = false;
                                break;
                            }
                        }

                        if (verificador == true)
                        {
                            if ((CANTIDAD_TOTAL_PRODUCTOS - CANTIDAD_TOTAL_DESCARGADA) <= 0)
                            {
                                if (_ordenCompra.ActualizarestadoOrdenCompra(orden, tabla.VAR_ESTADO_ORDEN_COMPRA_FINALIZADA, null) == false)
                                {
                                    MensajeError = _ordenCompra.MensajeError;
                                    conexion.DeshacerTransaccion();
                                    verificador = false;
                                    break;
                                }
                            }
                            else
                            {
                                if (_ordenCompra.ActualizarestadoOrdenCompra(orden, tabla.VAR_ESTADO_ORDEN_COMPRA_ADJUNTADO_FACTURA, null) == false)
                                {
                                    MensajeError = _ordenCompra.MensajeError;
                                    conexion.DeshacerTransaccion();
                                    verificador = false;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (verificador == true)
                    {
                        conexion.AceptarTransaccion();
                    }
                }
            }
            catch (Exception ex)
            {
                conexion.DeshacerTransaccion();
                MensajeError = ex.Message;
                verificador = false;
            }
            finally
            {
                conexion.Desconectar();
            }

            if (verificador == true)
            {
                return ID_DOCUMENTO;
            }
            else
            {
                return 0;
            }
        }
Exemple #14
0
        public Decimal guardarAjusteEquipo(String tipo, String idRegional, String idCiudad, int idEmpresa, int idProducto, int idEquipo, String talla, int idLote, int CantidadMod, Decimal costo, String Motivo)
        {
            Decimal  idDoc = 0;
            DateTime fecha;
            Decimal  idInventario = 0;

            fecha = System.DateTime.Today;
            Conexion _dato = new Conexion(Empresa);

            _dato.IniciarTransaccion();

            documento_temp _doc = new documento_temp(Empresa, Usuario);

            idDoc = _doc.AdicionarAlmDocumentosTemp(0, "AJUSTE", "", fecha, Convert.ToDateTime("01/01/1900"), 0, "POR APROBAR", Motivo, _dato);
            if (idDoc != 0)
            {
                bodega    _bodega     = new bodega(Empresa, Usuario);
                DataTable tablaBodega = _bodega.ObtenerAlmRegBodegaPorIds(idRegional, idCiudad, idEmpresa);
                DataRow   filaBodega  = tablaBodega.Rows[0];

                lote      _lote     = new lote(Empresa, Usuario);
                DataTable tablaLote = _lote.ObtenerAlmLotePorId(idLote);
                DataRow   filalote  = tablaLote.Rows[0];
                if (tipo.Equals("COSTO"))
                {
                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, idEquipo, talla, CantidadMod, costo, fecha, "MODIFICACION", _dato);
                    if (idInventario == 0)
                    {
                        _dato.DeshacerTransaccion();
                        idDoc = 0;
                    }
                    else
                    {
                        _dato.AceptarTransaccion();
                    }
                }
                else if (tipo.Equals("ENTRADA"))
                {
                    int contenido;
                    contenido = Convert.ToInt32(filalote["ENTRADAS"].ToString()) - Convert.ToInt32(filalote["SALIDAS"].ToString());
                    contenido = CantidadMod - contenido;

                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, idEquipo, talla, contenido, 0, fecha, "ENTRADA", _dato);

                    if (idInventario == 0)
                    {
                        _dato.DeshacerTransaccion();
                        idDoc = 0;
                    }
                    else
                    {
                        _dato.AceptarTransaccion();
                    }
                }
                else
                {
                    int contenido;
                    contenido = Convert.ToInt32(filalote["ENTRADAS"].ToString()) - Convert.ToInt32(filalote["SALIDAS"].ToString());
                    contenido = contenido - CantidadMod;

                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, idEquipo, talla, contenido, 0, fecha, "SALIDA", _dato);
                    if (idInventario == 0)
                    {
                        _dato.DeshacerTransaccion();
                        idDoc = 0;
                    }
                    else
                    {
                        _dato.AceptarTransaccion();
                    }
                }
            }
            else
            {
                _dato.DeshacerTransaccion();
                MensajeError = _doc.MensajeError;
                idDoc        = 0;
            }

            return(idDoc);
        }
Exemple #15
0
        public Decimal guardarAjuste(String tipo,
                                     String idRegional,
                                     String idCiudad,
                                     int idEmpresa,
                                     int idProducto,
                                     String talla,
                                     int idLote,
                                     int CantidadMod,
                                     Decimal costo,
                                     String Motivo,
                                     List <EquipoAjuste> listaEquiposAjuste,
                                     String NOMBRE_SERVICIO_COMPLEMENTARIO)
        {
            Decimal  idDoc = 0;
            DateTime fecha;
            Decimal  idInventario = 0;

            Boolean correcto = true;

            fecha = System.DateTime.Today;

            Conexion _dato = new Conexion(Empresa);

            _dato.IniciarTransaccion();

            try
            {
                documento_temp _doc = new documento_temp(Empresa, Usuario);
                idDoc = _doc.AdicionarAlmDocumentosTemp(0, "AJUSTE", "", fecha, new DateTime(), 0, "POR APROBAR", Motivo, _dato);

                if (idDoc <= 0)
                {
                    correcto     = false;
                    MensajeError = _doc.MensajeError;
                    _dato.DeshacerTransaccion();
                }
                else
                {
                    bodega _bodega = new bodega(Empresa, Usuario);
                    _bodega.MensajeError = null;
                    DataTable tablaBodega = _bodega.ObtenerAlmRegBodegaPorIds(idRegional, idCiudad, idEmpresa, _dato);

                    if (_bodega.MensajeError != null)
                    {
                        correcto = false;
                        _dato.DeshacerTransaccion();
                        MensajeError = _bodega.MensajeError;
                    }
                    else
                    {
                        DataRow filaBodega = tablaBodega.Rows[0];

                        lote _lote = new lote(Empresa, Usuario);
                        _lote.MensajeError = null;
                        DataTable tablaLote = _lote.ObtenerAlmLotePorId(idLote, _dato);

                        if (_lote.MensajeError != null)
                        {
                            correcto = false;
                            _dato.DeshacerTransaccion();
                            MensajeError = _bodega.MensajeError;
                        }
                        else
                        {
                            DataRow filalote = tablaLote.Rows[0];
                            if (tipo.Equals("COSTO"))
                            {
                                idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, 0, talla, CantidadMod, costo, fecha, "COSTO", _dato);

                                if (idInventario == 0)
                                {
                                    correcto = false;
                                    _dato.DeshacerTransaccion();
                                    MensajeError = _bodega.MensajeError;
                                }
                            }
                            else if (tipo.Equals("ENTRADA"))
                            {
                                if (NOMBRE_SERVICIO_COMPLEMENTARIO != "EQUIPOS")
                                {
                                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, 0, talla, CantidadMod, Convert.ToDecimal(filalote["COSTO"]), fecha, "ENTRADA", _dato);

                                    if (idInventario == 0)
                                    {
                                        correcto = false;
                                        _dato.DeshacerTransaccion();
                                        MensajeError = _bodega.MensajeError;
                                    }
                                }
                                else
                                {
                                    foreach (EquipoAjuste equipo in listaEquiposAjuste)
                                    {
                                        EquipoEntradaTemp _equipoTemp    = new EquipoEntradaTemp(Empresa, Usuario);
                                        Decimal           ID_EQUIPO_TEMP = _equipoTemp.AdicionarAlmEquipoEntradaTemp(equipo.ID_DOCUMENTO, equipo.MARCA, equipo.MODELO, equipo.SERIE, equipo.IMEI, equipo.NUMERO_CELULAR, fecha, equipo.ID_LOTE, _dato);

                                        if (ID_EQUIPO_TEMP <= 0)
                                        {
                                            correcto = false;
                                            _dato.DeshacerTransaccion();
                                            MensajeError = _bodega.MensajeError;
                                            break;
                                        }
                                        else
                                        {
                                            idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, Convert.ToInt32(ID_EQUIPO_TEMP), talla, 1, Convert.ToDecimal(filalote["COSTO"]), fecha, "ENTRADA", _dato);

                                            if (idInventario == 0)
                                            {
                                                correcto = false;
                                                _dato.DeshacerTransaccion();
                                                MensajeError = _bodega.MensajeError;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (NOMBRE_SERVICIO_COMPLEMENTARIO != "EQUIPOS")
                                {
                                    idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), idProducto, Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, 0, talla, CantidadMod, Convert.ToDecimal(filalote["COSTO"]), fecha, "SALIDA", _dato);
                                    if (idInventario == 0)
                                    {
                                        correcto = false;
                                        _dato.DeshacerTransaccion();
                                        MensajeError = _bodega.MensajeError;
                                    }
                                }
                                else
                                {
                                    foreach (EquipoAjuste equipo in listaEquiposAjuste)
                                    {
                                        idInventario = AdicionarAlmInventarioTemp(Convert.ToInt32(idDoc), Convert.ToInt32(equipo.ID_PRODUCTO), Convert.ToInt32(filaBodega["ID_BODEGA"].ToString()), idLote, Convert.ToInt32(equipo.ID_EQUIPO), talla, 1, Convert.ToDecimal(filalote["COSTO"]), fecha, "SALIDA", _dato);
                                        if (idInventario == 0)
                                        {
                                            correcto = false;
                                            _dato.DeshacerTransaccion();
                                            MensajeError = _bodega.MensajeError;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (correcto == true)
                {
                    _dato.AceptarTransaccion();
                }
            }
            catch (Exception ex)
            {
                correcto     = false;
                MensajeError = ex.Message;
                _dato.DeshacerTransaccion();
            }
            finally
            {
                _dato.Desconectar();
            }

            if (correcto == true)
            {
                return(idDoc);
            }
            else
            {
                return(0);
            }
        }