Example #1
0
        private iva CargaDatos()
        {
            iva iva = new iva();

            try
            {
                progressBar1.Value = 40;

                cp_codigo_SRI_Bus         dat_ti             = new cp_codigo_SRI_Bus();
                List <cp_codigo_SRI_Info> ListCodigoSRI      = new List <cp_codigo_SRI_Info>();
                List <cp_codigo_SRI_Info> ListCodigoSustento = new List <cp_codigo_SRI_Info>();
                ListCodigoSRI = dat_ti.Get_List_codigo_SRI_(param.IdEmpresa);

                ListCodigoSustento = ListCodigoSRI.FindAll(c => c.co_estado == "A" && c.IdTipoSRI == "COD_IDCREDITO");

                List <cp_TipoDocumento_Info> LstTipDoc = new List <cp_TipoDocumento_Info>();
                cp_TipoDocumento_Bus         TipDoc_B  = new cp_TipoDocumento_Bus();
                LstTipDoc = TipDoc_B.Get_List_TipoDocumento();


                cp_orden_giro_pagos_sri_Bus   formasPago_B   = new cp_orden_giro_pagos_sri_Bus();
                cp_orden_giro_Bus             OGB            = new cp_orden_giro_Bus();
                cp_proveedor_Autorizacion_Bus Autorizacion_B = new cp_proveedor_Autorizacion_Bus();
                cp_proveedor_Bus Proveedor_B = new cp_proveedor_Bus();
                tb_persona_bus   Persona_B   = new tb_persona_bus();

                List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleCompras> lstDetalleCompras = new List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleCompras>();
                List <cp_orden_giro_Info> listaOG = new List <cp_orden_giro_Info>();
                listaOG = OGB.Get_List_orden_giro_SRI(param.IdEmpresa, Convert.ToInt32(cmb_anio.Text), Convert.ToInt32(cmb_periodo.SelectedValue));



                iva.IdInformante = Empresa_I.em_ruc;
                iva.razonSocial  = Empresa_I.RazonSocial.Replace(".", " ").Replace("ñ", "n").Replace("Ñ", "N");
                iva.Anio         = cmb_anio.Text;
                iva.Mes          = (cmb_periodo.SelectedValue.ToString().Length == 1) ? "0" + cmb_periodo.SelectedValue.ToString() : cmb_periodo.SelectedValue.ToString();

                tb_Sucursal_Bus bus_sucursal       = new tb_Sucursal_Bus();
                int             numEstablecimiento = bus_sucursal.Get_numEstablecimiento_x_empresa_SRI(param.IdEmpresa);
                iva.numEstabRuc = numEstablecimiento.ToString("000");


                iva.TipoIDInformante = ivaTypeTipoIDInformante.R;
                iva.codigoOperativo  = codigoOperativoType.IVA;
                iva.totalVentas      = 0;



                foreach (cp_orden_giro_Info item in listaOG)
                {
                    try
                    {
                        Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleCompras itemDetalleCompras = new Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleCompras();
                        if (item.IdCbteCble_Ogiro == 9)
                        {
                        }
                        info_Retencion_x_RF   = Retencion_B.Get_Info_retencion_X_Retecion_FT(param.IdEmpresa, item.IdCbteCble_Ogiro, item.IdTipoCbte_Ogiro);
                        info_Retencion_x_RIVA = Retencion_B.Get_Info_retencion_X_Retecion_RTIVA(param.IdEmpresa, item.IdCbteCble_Ogiro, item.IdTipoCbte_Ogiro);

                        string secuenci_numReten = "";
                        List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAir> LstdetalleAir = new List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAir>();
                        string fecRet = info_Retencion_x_RF.fecha.ToString("dd/MM/yyyy");


                        if (info_Retencion_x_RF.ListDetalle.Count != 0)
                        {
                            foreach (var item2 in info_Retencion_x_RF.ListDetalle)
                            {
                                Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAir detalleAir = new Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAir();
                                detalleAir.codRetAir = item2.CodigoSRI.Trim();

                                detalleAir.porcentajeAir = Convert.ToDecimal(item2.re_Porcen_retencion).ToString();
                                detalleAir.baseImpAir    = Convert.ToDecimal(item2.re_baseRetencion).ToString();

                                fecRet = info_Retencion_x_RF.fecha.ToString("dd/MM/yyyy");
                                detalleAir.valRetAir = Convert.ToDecimal(item2.re_valor_retencion).ToString();
                                LstdetalleAir.Add(detalleAir);
                            }
                        }


                        itemDetalleCompras.valRetBien10      = "0";
                        itemDetalleCompras.valRetServ20      = "0";
                        itemDetalleCompras.valRetServ50      = "0";
                        itemDetalleCompras.valRetServ100     = "0";
                        itemDetalleCompras.valorRetBienes    = "0";
                        itemDetalleCompras.valorRetServicios = "0";
                        itemDetalleCompras.totbasesImpReemb  = "0";


                        if (info_Retencion_x_RIVA.ListDetalle.Count != 0)
                        {
                            foreach (var item_iva in info_Retencion_x_RIVA.ListDetalle)
                            {
                                if (item_iva.re_Porcen_retencion == 10)
                                {
                                    itemDetalleCompras.valRetBien10 = Convert.ToDecimal(item_iva.re_valor_retencion).ToString();
                                }

                                if (item_iva.re_Porcen_retencion == 20)
                                {
                                    itemDetalleCompras.valRetServ20 = Convert.ToDecimal(item_iva.re_valor_retencion).ToString();
                                }

                                if (item_iva.re_Porcen_retencion == 30)
                                {
                                    itemDetalleCompras.valorRetBienes = Convert.ToDecimal(item_iva.re_valor_retencion).ToString();
                                }

                                if (item_iva.re_Porcen_retencion == 50)
                                {
                                    itemDetalleCompras.valRetServ50 = Convert.ToDecimal(item_iva.re_valor_retencion).ToString();
                                }

                                if (item_iva.re_Porcen_retencion == 70)
                                {
                                    itemDetalleCompras.valorRetServicios = Convert.ToDecimal(item_iva.re_valor_retencion).ToString();
                                }


                                if (item_iva.re_Porcen_retencion == 100)
                                {
                                    itemDetalleCompras.valRetServ100 = Convert.ToDecimal(item_iva.re_valor_retencion).ToString();
                                }
                            }
                        }



                        if (item.IdIden_credito != 0)
                        {
                            var sustento = ListCodigoSustento.First(c => c.IdCodigo_SRI == item.IdIden_credito);
                            itemDetalleCompras.codSustento = sustento.codigoSRI;
                        }


                        if (!String.IsNullOrEmpty(item.co_serie))
                        {
                            string[] serie = Convert.ToString(item.co_serie).Split('-');

                            itemDetalleCompras.establecimiento = serie[0];
                            itemDetalleCompras.puntoEmision    = serie[1];
                        }


                        itemDetalleCompras.secuencial = item.co_factura;

                        //if (item.co_factura == "000002133") { MessageBox.Show(""); }



                        itemDetalleCompras.fechaRegistro = Convert.ToDateTime(item.co_FechaContabilizacion).ToString("dd/MM/yyyy");
                        itemDetalleCompras.idProv        = item.InfoProveedor.Persona_Info.pe_cedulaRuc.Trim();
                        itemDetalleCompras.tpIdProv      = (item.InfoProveedor.Persona_Info.IdTipoDocumento.Trim() == "RUC") ? "01" : ((item.InfoProveedor.Persona_Info.IdTipoDocumento.Trim() == "CED") ? "02" : "03");
                        itemDetalleCompras.parteRel      = (item.InfoProveedor.es_empresa_relacionada == true) ? parteRelType.SI : parteRelType.NO;
                        itemDetalleCompras.autorizacion  = (item.Num_Autorizacion == null) ? "" : item.Num_Autorizacion;



                        if (itemDetalleCompras.tpIdProv == "03")
                        {
                            itemDetalleCompras.tipoProv = (item.InfoProveedor.Persona_Info.pe_Naturaleza == "NATUR") ? "01" : "02";

                            if (item.InfoProveedor.es_empresa_relacionada == true)
                            {
                                itemDetalleCompras.parteRel = parteRelType.SI;
                            }
                            else
                            {
                                itemDetalleCompras.parteRel = parteRelType.NO;
                            }
                        }


                        var tipD = LstTipDoc.First(c => c.CodTipoDocumento == item.IdOrden_giro_Tipo);
                        itemDetalleCompras.tipoComprobante = tipD.CodSRI;
                        itemDetalleCompras.fechaEmision    = item.co_FechaFactura.ToString("dd/MM/yyyy");
                        itemDetalleCompras.autorizacion    = item.Num_Autorizacion;

                        itemDetalleCompras.baseNoGraIva  = "0";                                                                                                 //base NO objeto de IVA
                        itemDetalleCompras.baseImponible = Math.Round(Convert.ToDecimal(item.co_subtotal_siniva), 2, MidpointRounding.AwayFromZero).ToString(); // sin iva
                        itemDetalleCompras.baseImpGrav   = Math.Round(Convert.ToDecimal(item.co_subtotal_iva), 2, MidpointRounding.AwayFromZero).ToString();    //con iva
                        itemDetalleCompras.baseImpExe    = "0";

                        itemDetalleCompras.montoIce = Math.Round(Convert.ToDecimal(item.co_Ice_valor), 2, MidpointRounding.AwayFromZero).ToString();
                        itemDetalleCompras.montoIva = Math.Round(Convert.ToDecimal(item.co_valoriva), 2, MidpointRounding.AwayFromZero).ToString();

                        itemDetalleCompras.valRetBien10Specified     = true;
                        itemDetalleCompras.valRetServ20Specified     = true;
                        itemDetalleCompras.valRetServ50Specified     = true;
                        itemDetalleCompras.totbasesImpReembSpecified = true;

                        if (tipD.CodSRI == "05")
                        {
                            itemDetalleCompras.docModificado    = item.Tipodoc_a_Modificar;
                            itemDetalleCompras.estabModificado  = item.estable_a_Modificar;
                            itemDetalleCompras.ptoEmiModificado = item.ptoEmi_a_Modificar;
                            itemDetalleCompras.secModificado    = item.num_docu_Modificar;
                            itemDetalleCompras.autModificado    = item.aut_doc_Modificar;
                        }

                        if (LstdetalleAir.Count > 0)
                        {
                            itemDetalleCompras.air = LstdetalleAir;     //AREGLAR
                        }
                        if (!string.IsNullOrEmpty(info_Retencion_x_RF.NAutorizacion))
                        {
                            secuenci_numReten = info_Retencion_x_RF.NumRetencion.ToString();
                            string sSerieRetencion = "";
                            sSerieRetencion = info_Retencion_x_RF.serie1 + '-' + info_Retencion_x_RF.serie2;
                            if (!string.IsNullOrEmpty(sSerieRetencion))
                            {
                                itemDetalleCompras.estabRetencion1  = info_Retencion_x_RF.serie1;
                                itemDetalleCompras.ptoEmiRetencion1 = info_Retencion_x_RF.serie2;
                            }
                            itemDetalleCompras.secRetencion1 = secuenci_numReten;
                            itemDetalleCompras.autRetencion1 = info_Retencion_x_RF.NAutorizacion;
                            itemDetalleCompras.fechaEmiRet1  = fecRet;
                        }

                        lstDetalleCompras.Add(itemDetalleCompras);

                        pagoExterior Item_pagoExterior = new pagoExterior();

                        if (item.PagoLocExt == "LOC")
                        {
                            Item_pagoExterior.pagoLocExt = pagoLocExtType.Item01;
                        }
                        else
                        {
                            Item_pagoExterior.pagoLocExt = pagoLocExtType.Item02;
                        }


                        Item_pagoExterior.paisEfecPago = (Item_pagoExterior.pagoLocExt == pagoLocExtType.Item01) ? "NA" : (item.PaisPago != null || item.PaisPago != "") ? item.PaisPago : "NA";

                        Item_pagoExterior.aplicConvDobTrib   = (item.ConvenioTributacion == "S") ? aplicConvDobTribType.SI : (item.ConvenioTributacion == "N") ? aplicConvDobTribType.NO :aplicConvDobTribType.NA;
                        Item_pagoExterior.pagExtSujRetNorLeg = (item.PagoSujetoRetencion == "S") ? aplicConvDobTribType.SI : (item.PagoSujetoRetencion == "N") ? aplicConvDobTribType.NO : aplicConvDobTribType.NA;



                        itemDetalleCompras.pagoExterior = Item_pagoExterior;



                        List <cp_orden_giro_pagos_sri_Info> formasDePagoOG = new List <cp_orden_giro_pagos_sri_Info>();
                        formasDePagoOG = formasPago_B.Get_List_orden_giro_pagos_sri(item.IdEmpresa, item.IdCbteCble_Ogiro, item.IdTipoCbte_Ogiro);

                        string  cadena = "";
                        string  coma   = "";
                        Boolean Hay_registros_de_pagos = false;


                        if (formasDePagoOG.Count > 0)
                        {
                            foreach (var itemfp in formasDePagoOG)
                            {
                                if (itemfp.check == true)
                                {
                                    cadena = cadena + coma + itemfp.codigo_pago_sri;
                                    coma   = ",";
                                    Hay_registros_de_pagos = true;
                                }
                            }
                            if (Hay_registros_de_pagos)
                            {
                                itemDetalleCompras.formasDePago = cadena.Split(',');
                            }
                        }


                        if (Hay_registros_de_pagos == false)
                        {
                            decimal Total = 0;
                            Total = Convert.ToDecimal(itemDetalleCompras.baseNoGraIva) + Convert.ToDecimal(itemDetalleCompras.baseImpGrav);

                            if (Total >= 1000)
                            {
                                string[] arr1 = new string[] { "01" };
                                itemDetalleCompras.formasDePago = arr1;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }

// Para las notas de debito y credito cxp
//*************************************

                cp_nota_DebCre_Bus         nota_B      = new cp_nota_DebCre_Bus();
                List <cp_nota_DebCre_Info> listaNotaDC = new List <cp_nota_DebCre_Info>();
                listaNotaDC = nota_B.Get_List_nota_DebCre(param.IdEmpresa, Convert.ToInt32(cmb_anio.Text), Convert.ToInt32(cmb_periodo.SelectedValue));



                progressBar1.Value = 70;
                foreach (cp_nota_DebCre_Info item in listaNotaDC)
                {
                    Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleCompras itemDetalleCompras = new Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleCompras();



                    List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAir> LstdetalleAir = new List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAir>();

                    cp_proveedor_Autorizacion_Info Autorizacion_I = new cp_proveedor_Autorizacion_Info();

                    var sustento = ListCodigoSustento.First(c => c.IdCodigo_SRI == item.IdIden_credito);
                    itemDetalleCompras.codSustento = sustento.codigoSRI;

                    itemDetalleCompras.establecimiento = item.cn_serie1;
                    itemDetalleCompras.puntoEmision    = item.cn_serie2;
                    itemDetalleCompras.secuencial      = item.cn_Nota;
                    itemDetalleCompras.autorizacion    = item.cn_Autorizacion;



                    //if ("000002133" == item.cn_Nota) { MessageBox.Show(""); }

                    if (item.Fecha_contable != null)
                    {
                        itemDetalleCompras.fechaRegistro = Convert.ToDateTime(item.Fecha_contable).ToString("dd/MM/yyyy");
                        itemDetalleCompras.fechaEmision  = Convert.ToDateTime(item.Fecha_contable).ToString("dd/MM/yyyy");
                    }

                    if (String.IsNullOrEmpty(itemDetalleCompras.fechaRegistro))
                    {
                        itemDetalleCompras.fechaRegistro = Convert.ToDateTime(item.cn_fecha).ToString("dd/MM/yyyy");
                        itemDetalleCompras.fechaEmision  = Convert.ToDateTime(item.cn_fecha).ToString("dd/MM/yyyy");
                    }



                    itemDetalleCompras.idProv   = item.InfoProveedor.Persona_Info.pe_cedulaRuc.Trim();
                    itemDetalleCompras.tpIdProv = (item.InfoProveedor.Persona_Info.IdTipoDocumento.Trim() == "RUC") ? "01" : ((item.InfoProveedor.Persona_Info.IdTipoDocumento.Trim() == "CED") ? "02" : "03");

                    if (itemDetalleCompras.tpIdProv == "03")
                    {
                        itemDetalleCompras.tipoProv = (item.InfoProveedor.Persona_Info.pe_Naturaleza == "NATUR") ? "01" : "02";
                        if (item.InfoProveedor.es_empresa_relacionada == true)
                        {
                            itemDetalleCompras.parteRel = parteRelType.SI;
                        }
                        else
                        {
                            itemDetalleCompras.parteRel = parteRelType.NO;
                        }
                    }



                    itemDetalleCompras.tipoComprobante = (item.DebCre == "C" || item.DebCre == "Credito") ? "04" : "05";
                    if (item.Fecha_contable != null)
                    {
                        itemDetalleCompras.fechaEmision = Convert.ToString(item.Fecha_contable);
                    }

                    itemDetalleCompras.baseNoGraIva  = "0";
                    itemDetalleCompras.baseImponible = Math.Round(Convert.ToDecimal(item.cn_subtotal_siniva), 2, MidpointRounding.AwayFromZero).ToString();    //sin iva
                    itemDetalleCompras.baseImpGrav   = Math.Round(Convert.ToDecimal(item.cn_subtotal_iva), 2, MidpointRounding.AwayFromZero).ToString();
                    itemDetalleCompras.baseImpExe    = "0";


                    itemDetalleCompras.montoIce = Math.Round(Convert.ToDecimal(item.cn_Ice_valor), 2, MidpointRounding.AwayFromZero).ToString();
                    itemDetalleCompras.montoIva = Math.Round(Convert.ToDecimal(item.cn_valoriva), 2, MidpointRounding.AwayFromZero).ToString();


                    itemDetalleCompras.valRetBien10      = "0.00";
                    itemDetalleCompras.valRetServ20      = "0.00";
                    itemDetalleCompras.valorRetBienes    = "0.00";
                    itemDetalleCompras.valRetServ50      = "0.00";
                    itemDetalleCompras.valorRetServicios = "0.00";
                    itemDetalleCompras.valRetServ100     = "0.00";
                    itemDetalleCompras.totbasesImpReemb  = "0.00";

                    itemDetalleCompras.valRetBien10Specified     = true;
                    itemDetalleCompras.valRetServ20Specified     = true;
                    itemDetalleCompras.valRetServ50Specified     = true;
                    itemDetalleCompras.totbasesImpReembSpecified = true;


                    if (LstdetalleAir.Count > 0)
                    {
                        itemDetalleCompras.air = LstdetalleAir;
                    }


                    itemDetalleCompras.docModificado    = item.docModificado;
                    itemDetalleCompras.estabModificado  = item.estabModificado;
                    itemDetalleCompras.ptoEmiModificado = item.ptoEmiModificado;
                    itemDetalleCompras.secModificado    = item.secModificado;
                    itemDetalleCompras.autModificado    = item.autModificado;

                    lstDetalleCompras.Add(itemDetalleCompras);

                    pagoExterior Item_pagoExterior = new pagoExterior();
                    Item_pagoExterior.pagoLocExt   = (item.PagoLocExt == "LOC") ? pagoLocExtType.Item01 : pagoLocExtType.Item02;
                    Item_pagoExterior.paisEfecPago = (Item_pagoExterior.pagoLocExt == pagoLocExtType.Item01) ? "NA"  : (item.PaisPago != null || item.PaisPago != "") ? item.PaisPago : "NA";

                    Item_pagoExterior.aplicConvDobTrib   = (item.ConvenioTributacion == "S") ? aplicConvDobTribType.SI : (item.ConvenioTributacion == "N") ? aplicConvDobTribType.NO :aplicConvDobTribType.NA;
                    Item_pagoExterior.pagExtSujRetNorLeg = (item.PagoSujetoRetencion == "S") ? aplicConvDobTribType.SI : (item.PagoSujetoRetencion == "N") ? aplicConvDobTribType.NO : aplicConvDobTribType.NA;

                    itemDetalleCompras.pagoExterior = Item_pagoExterior;
                }

                iva.compras        = lstDetalleCompras;
                progressBar1.Value = 85;

//*****ANULADOS*******
//********************

                tb_sis_Documento_Tipo_x_Empresa_Anulados_Bus         DocAnu_B  = new tb_sis_Documento_Tipo_x_Empresa_Anulados_Bus();
                List <tb_sis_Documento_Tipo_x_Empresa_Anulados_Info> LstDocAnu = new List <tb_sis_Documento_Tipo_x_Empresa_Anulados_Info>();

                LstDocAnu = DocAnu_B.ConsultaPorMesAnio(param.IdEmpresa, Convert.ToInt32(cmb_anio.Text), Convert.ToInt32(cmb_periodo.SelectedValue));

                List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAnulados> lstDetalleDocAnu = new List <Core.Erp.Info.CuentasxPagar.xmlATS_V_1_1_4.detalleAnulados>();
                foreach (var itemDA in LstDocAnu)
                {
                    if (itemDA.Autorizacion != null)
                    {
                        detalleAnulados info = new detalleAnulados();
                        info.autorizacion     = itemDA.Autorizacion;
                        info.establecimiento  = itemDA.Serie1;
                        info.puntoEmision     = itemDA.Serie2;
                        info.secuencialInicio = itemDA.Documento;
                        info.secuencialFin    = itemDA.DocumentoFin;
                        var tipD = LstTipDoc.First(c => c.CodTipoDocumento == itemDA.codDocumentoTipo);
                        info.tipoComprobante = tipD.CodSRI;
                        lstDetalleDocAnu.Add(info);
                    }
                }

                if (lstDetalleDocAnu.Count > 0)
                {
                    iva.anulados = lstDetalleDocAnu;
                }

                //// FACTURAS

                fa_factura_Bus fac_B = new fa_factura_Bus();

                List <detalleVentas> LstDV = new List <detalleVentas>();
                LstDV = fac_B.Get_List_VentasParaATS(param.IdEmpresa, Convert.ToInt32(cmb_anio.Text), Convert.ToInt32(cmb_periodo.SelectedValue));

                int IdPeriodo = (Convert.ToInt32(iva.Anio) * 100) + Convert.ToInt32(iva.Mes);

                foreach (var item in LstDV)
                {
                    item.montoIce          = 0;
                    item.montoIceSpecified = true;

                    #region Personalizacion de cliente Grafinpren

                    /// el cliente nos pide q enceremos el valor de la retencion de estos meses junio y julio 2016
                    if (param.IdCliente_Ven_x_Default == Cl_Enumeradores.eCliente_Vzen.GRAFINPRENT)
                    {
                        if (IdPeriodo >= 201606 && IdPeriodo <= 201611)
                        {
                            item.valorRetIva   = "0.00";
                            item.valorRetRenta = "0.00";
                        }
                    }
                    #endregion
                }



                if (LstDV.Count() > 0)
                {
                    iva.ventas = LstDV;
                }

                List <ventaEst> LstVenSum = new List <ventaEst>();
                LstVenSum = fac_B.Get_List_VentasXEstablecimientoParaATS(param.IdEmpresa, Convert.ToInt32(cmb_anio.Text), Convert.ToInt32(cmb_periodo.SelectedValue));

                foreach (var item in LstVenSum)
                {
                }
                if (LstVenSum.Count > 0)
                {
                    iva.ventasEstablecimiento = LstVenSum;
                    iva.totalVentas           = Math.Round(Math.Abs(LstVenSum.Sum(c => c.ventasEstab)), 2, MidpointRounding.AwayFromZero);
                }
                else
                {
                    iva.totalVentas = 0;
                }


                iva.totalVentasSpecified = true;

                return(iva);
            }
            catch (Exception ex)
            {
                Log_Error_bus.Log_Error(ex.ToString());
                MessageBox.Show(ex.ToString());
                return(iva);
            }
        }
Example #2
0
        Boolean GuardarDatos()
        {
            try
            {
                Boolean         bolResult    = true;
                tb_Sucursal_Bus bus_sucursal = new tb_Sucursal_Bus();
                string          msg          = "";
                int             id           = 0;

                if (validarDatos())
                {
                    get_Sucursal();
                    switch (_Accion)
                    {
                    case Cl_Enumeradores.eTipo_action.grabar:

                        //if (bus_sucursal.ValidarCodigoExiste(param.IdEmpresa, info.Su_Ruc, info.Su_CodigoEstablecimiento) != false)
                        //{
                        if (bus_sucursal.GrabarDB(info, ref id, ref msg))
                        {
                            this.lbl_id_sucursal.Text = id.ToString();
                            //this.lbl_title_id_sucursal.Visible = true;
                            //this.lbl_id_sucursal.Visible = true;

                            MessageBox.Show(msg, "SISTEMA", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            //ucGe_Menu.Visible_bntGuardar_y_Salir = false;
                            //ucGe_Menu.Visible_btnGuardar = false;
                            LimpiarDatos();
                            bolResult = true;
                        }
                        else
                        {
                            this.lbl_title_id_sucursal.Visible = false;
                            this.lbl_id_sucursal.Visible       = false;
                            bolResult = false;
                            MessageBox.Show(msg, "SISTEMA", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        this.txt_vendedor.Enabled = true;
                        this.chk_estado.Enabled   = true;
                        //}
                        //else
                        //{
                        //    MessageBox.Show("El codigo Ingresado Ya existe \nPor favor ingrese uno diferente");
                        //    bolResult = false;
                        //}
                        break;

                    case Cl_Enumeradores.eTipo_action.actualizar:

                        if (bus_sucursal.ModificarDB(info, ref msg))
                        {
                            MessageBox.Show(msg, "SISTEMA", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            //ucGe_Menu.Visible_bntGuardar_y_Salir = false;
                            //ucGe_Menu.Visible_btnGuardar = false;
                            LimpiarDatos();
                            bolResult = true;
                        }
                        else
                        {
                            bolResult = false;
                            MessageBox.Show(msg, "SISTEMA", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        this.txt_vendedor.Enabled = false;
                        this.chk_estado.Enabled   = false;

                        break;
                    }
                }

                else
                {
                    bolResult = false;
                }
                return(bolResult);
            }
            catch (Exception ex)
            {
                Log_Error_bus.Log_Error(ex.ToString());
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
        public Boolean ValidarObjeto(ct_Cbtecble_Info Info_CbteCble, ref string MensajeError)
        {
            try
            {
                Boolean res = true;


                if (Info_CbteCble.IdEmpresa == 0 || Info_CbteCble.IdTipoCbte == 0)
                {
                    MensajeError = "el objeto esta errado los PK IdEmpresa , IdTipoCbte no pueden estar en cero";
                    res          = false;
                    return(res);
                }

                if (Info_CbteCble._cbteCble_det_lista_info == null)
                {
                    MensajeError = "El Comprobante no tiene detalle";
                    res          = false;
                    return(res);
                }

                try
                {
                    Info_CbteCble.cb_Valor = Info_CbteCble._cbteCble_det_lista_info.FindAll(q => q.dc_Valor > 0).Sum(q => q.dc_Valor);
                }
                catch (Exception ex)
                {
                    oLog.Log_Error(ex.ToString());
                    Info_CbteCble.cb_Valor = 0;
                }
                if (Info_CbteCble.cb_Valor == 0)
                {
                    MensajeError = "El Valor del Comprobante contable no puede ser 0.";
                    return(false);
                }

                if (Info_CbteCble.IdPeriodo == 0)
                {
                    MensajeError = "Periodo Fiscal es invalido, por favor verifique.";
                    res          = false;
                }


                if (Info_CbteCble.IdSucursal == 0)
                {
                    tb_Sucursal_Bus busSucu = new tb_Sucursal_Bus();
                    Info_CbteCble.IdSucursal = busSucu.Get_List_Sucursal(Info_CbteCble.IdEmpresa).FirstOrDefault().IdSucursal;
                }



                if (Info_CbteCble.cb_Fecha == (new DateTime()))
                {
                    MensajeError = "Fecha de comprobante es invalida, por favor verifique.";
                    res          = false;
                }



                foreach (var item in Info_CbteCble._cbteCble_det_lista_info)
                {
                    item.IdEmpresa  = Info_CbteCble.IdEmpresa;
                    item.IdCbteCble = Info_CbteCble.IdCbteCble;
                    item.dc_Valor   = Math.Round(item.dc_Valor, 2, MidpointRounding.AwayFromZero);
                }
                // realizo una sumatoria del debe y haber para obtener la diferencia
                Info_CbteCble._cbteCble_det_lista_info.ForEach(x => x.dc_Valor = Math.Round(x.dc_Valor, 3));



                var Sum_Total_debito = (from tb in Info_CbteCble._cbteCble_det_lista_info where tb.dc_Valor > 0
                                        select tb.dc_Valor).Sum();

                var Sum_Total_credito = (from tb in Info_CbteCble._cbteCble_det_lista_info
                                         where tb.dc_Valor < 0
                                         select tb.dc_Valor).Sum();


                double Total_Debito  = Math.Round(Convert.ToDouble(Convert.ToString(Sum_Total_debito)), 2, MidpointRounding.AwayFromZero);
                double Total_Credito = Math.Round(Convert.ToDouble(Convert.ToString(Sum_Total_credito)), 2, MidpointRounding.AwayFromZero);

                double Diferencia = Total_Debito + Total_Credito;
                Diferencia = Math.Round(Diferencia, 2, MidpointRounding.AwayFromZero);
                if (Diferencia >= -0.02 || Diferencia <= 0.02)                                                             //Se cambio a 2 ctvs porque
                {
                    if (Diferencia > 0)                                                                                    // 1 ctv de mas
                    {
                        Info_CbteCble._cbteCble_det_lista_info.FirstOrDefault(v => v.dc_Valor > 0).dc_Valor -= Diferencia; // le resto 1
                    }
                    else
                    {
                        Info_CbteCble._cbteCble_det_lista_info.FirstOrDefault(v => v.dc_Valor < 0).dc_Valor -= Diferencia;// le resto a los negativos
                    }
                    Diferencia = 0;
                }

                if (Convert.ToDouble(Convert.ToString(Diferencia)) != 0)  // si es diferente de 0 quiere decir q no esta cuadrado el CBTE CBLE
                {
                    MensajeError = "El Diaro no esta cuadrado Hay difencias entre el debito y el credito:  Total Debito:" + Total_Debito + " Total Credito:" + Total_Credito + " Diferencia:" + Diferencia;
                    res          = false;
                    return(res);
                }

                double TotalCbte = 0;


                foreach (var item in Info_CbteCble._cbteCble_det_lista_info)
                {
                    if (item.IdCtaCble == null || item.IdCtaCble == "")
                    {
                        MensajeError = "Falta Cuenta Contable en detalle " + item.dc_Observacion;
                        res          = false;
                        return(res);
                    }
                    if (item.dc_Valor == 0)
                    {
                        MensajeError = "Existen detalles con valor 0, verifique por favor.";
                        res          = false;
                        return(res);
                    }
                    if (item.dc_Valor > 0)
                    {
                        TotalCbte = TotalCbte + item.dc_Valor;
                    }
                }

                Info_CbteCble.cb_Fecha = Convert.ToDateTime(Info_CbteCble.cb_Fecha.ToShortDateString());
                if (Info_CbteCble.cb_Valor == 0)
                {
                    Info_CbteCble.cb_Valor = Math.Round(TotalCbte, 2);
                }
                ;



                if (res == false)
                {
                    oLog.Log_Error(MensajeError);
                }

                return(res);
            }
            catch (Exception ex)
            {
                Core.Erp.Info.Log_Exception.LoggingManager.Logger.Log(Core.Erp.Info.Log_Exception.LoggingCategory.Error, ex.Message);
                throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "ValidarObjeto", ex.Message), ex)
                      {
                          EntityType = typeof(ct_Cbtecble_Bus)
                      };
            }
        }
Example #4
0
        public rdep setInfoXML(List <ro_Rdep_Info> info, string ruc, int idPeriodo)
        {
            try
            {
                //CAMBIAR LA CULTURA REGIONAL PARA SETEAR EL PUNTO DECIMAL
                System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

                //DATOS DE LA EMPRESA
                rdep oRdep = new rdep();
                oRdep.anio   = idPeriodo.ToString();
                oRdep.numRuc = ruc;

                oRdep.retRelDep = new List <rdepRetRelDepDatRetRelDep>();


                foreach (ro_Rdep_Info item in info)
                {
                    rdepRetRelDepDatRetRelDep detalleRDEP = new rdepRetRelDepDatRetRelDep();

                    detalleRDEP.empleado = new List <rdepRetRelDepDatRetRelDepEmpleado>();
                    rdepRetRelDepDatRetRelDepEmpleado datosEmpleado = new rdepRetRelDepDatRetRelDepEmpleado();


                    //CONSULTAR DATOS DEL EMPLEADO
                    ro_Empleado_Info ro_Empleado_Info = new ro_Empleado_Info();
                    ro_Empleado_Info = oRo_Empleado_Bus.Get_Info_Empleado(item.IdEmpresa, item.IdEmpleado);

                    #region Empleado

                    //Tipo de identificación del trabajador
                    switch (ro_Empleado_Info.InfoPersona.IdTipoDocumento)
                    {
                    case "CED":
                        datosEmpleado.tipIdRet = "C";

                        break;

                    case "PAS":
                        datosEmpleado.tipIdRet = "P";
                        break;

                    default:
                        //Identificación Tributaria del Exterior
                        datosEmpleado.tipIdRet = "E";
                        break;
                    }

                    //Número de identificación del trabajador
                    datosEmpleado.idRet = ro_Empleado_Info.InfoPersona.pe_cedulaRuc;

                    //Apellidos del trabajador
                    datosEmpleado.apellidoTrab = ro_Empleado_Info.InfoPersona.pe_apellido;

                    //Nombres del trabajador
                    datosEmpleado.nombreTrab = ro_Empleado_Info.InfoPersona.pe_nombre;

                    //Código del establecimiento
                    tb_Sucursal_Bus  oTb_Sucursal_Bus  = new tb_Sucursal_Bus();
                    tb_Sucursal_Info oTb_Sucursal_Info = new Info.General.tb_Sucursal_Info();
                    oTb_Sucursal_Info   = oTb_Sucursal_Bus.Get_Info_Sucursal(param.IdEmpresa, param.IdSucursal);
                    datosEmpleado.estab = oTb_Sucursal_Info.Su_CodigoEstablecimiento;

                    //Residencia del trabajador
                    datosEmpleado.residenciaTrab = pu_Right(ro_Empleado_Info.IdTipoResidenciaSRI, 2);

                    //País de residencia del trabajador
                    datosEmpleado.paisResidencia = "593";

                    //Aplica convenio para evitar doble imposición
                    datosEmpleado.aplicaConvenio = pu_Right(ro_Empleado_Info.IdAplicaConvenioDobleImposicionSRI, 2);

                    //Condición del trabajador respecto a discapacidades
                    //if (item.em_empEspecial == "S") {datosEmpleado.tipoTrabajDiscap = "02"; } else {datosEmpleado.tipoTrabajDiscap = "01"; }
                    datosEmpleado.tipoTrabajDiscap = "NO";//= pu_Right(ro_Empleado_Info.IdCondicionDiscapacidadSRI, 2);

                    //Porcentaje de discapacidad
                    datosEmpleado.porcentajeDiscap = ro_Empleado_Info.por_discapacidad.ToString();

                    //Tipo de identificación de la persona con discapacidad a quien sustituye o representa
                    datosEmpleado.tipIdDiscap = pu_Right(ro_Empleado_Info.IdTipoIdentDiscapacitadoSustitutoSRI, 1);

                    //Número de identificación de la persona con discapacidad a quien sustituye o representa
                    datosEmpleado.idDiscap = ro_Empleado_Info.IdentDiscapacitadoSustitutoSRI;

                    //AGREGAR DATOS DEL DETALLE DE EMPLEADOS
                    detalleRDEP.empleado.Add(datosEmpleado);


                    #endregion

                    #region detalle

                    //Sueldos y salarios
                    detalleRDEP.suelSal = item.suelSal;

                    //Sobresueldos, comisiones, bonos y otros ingresos gravados
                    detalleRDEP.sobSuelComRemu = item.sobSuelComRemu;

                    //Participación de utilidades
                    detalleRDEP.partUtil = item.partUtil;

                    //Ingresos gravados generados con otros empleadores
                    detalleRDEP.intGrabGen = item.intGrabGen;

                    //Impuesto a la renta asumido por este empleador
                    detalleRDEP.impRentEmpl = item.impRentEmpl;

                    //Décimo tercer sueldo
                    detalleRDEP.decimTer = item.decimTer;

                    //Décimo cuarto sueldo
                    detalleRDEP.decimCuar = item.decimCuar;

                    //Fondo de reserva
                    detalleRDEP.fondoReserva = item.fondoReserva;

                    //Compensación Económica Salario Digno
                    detalleRDEP.salarioDigno = item.salarioDigno;

                    //Otros ingresos en relación de dependencia que no constituyen renta gravada
                    detalleRDEP.otrosIngRenGrav = item.otrosIngRenGrav;

                    //Ingresos gravados con este empleador (Informativo)
                    detalleRDEP.ingGravConEsteEmpl = item.ingGravConEsteEmpl;

                    //Sistema de salario neto
                    detalleRDEP.sisSalNet = item.sisSalNet;

                    //Aporte personal al IESS con este empleador (únicamente pagado por el trabajador)
                    detalleRDEP.apoPerIess = item.apoPerIess;

                    //Aporte personal al IESS con otros empleadores (únicamente pagado por el trabajador)
                    detalleRDEP.aporPerIessConOtrosEmpls = item.aporPerIessConOtrosEmpls;


                    //*****************DEDUCCION POR GASTOS PERSONALES***********************

                    //Deducción de gastos personales por Vivienda
                    detalleRDEP.deducVivienda = item.deducVivienda;

                    //Deducción de gastos personales por Salud
                    detalleRDEP.deducSalud = item.deducSalud;

                    //Deducción de gastos personales por Educación
                    detalleRDEP.deducEduca = item.deducEduca;

                    //Deducción de gastos personales por Alimentación
                    detalleRDEP.deducAliement = item.deducAliement;

                    //Deducción de gastos personales por Vestimenta
                    //detalleRDEP. = "0.00";

                    //*************************************************************************


                    //Exoneración por Discapacidad
                    detalleRDEP.exoDiscap = item.exoDiscap;

                    //Exoneración por Tercera Edad
                    detalleRDEP.exoTerEd = item.exoTerEd;

                    //Base imponible gravada
                    detalleRDEP.basImp = item.basImp;

                    //Impuesto a la renta causado
                    detalleRDEP.impRentCaus = item.impRentCaus;

                    //Valor del impuesto retenido y asumido por otros empleadores durante el período declarado
                    detalleRDEP.valRetAsuOtrosEmpls = item.valRetAsuOtrosEmpls;

                    //Valor del impuesto asumido por este empleador
                    detalleRDEP.valImpAsuEsteEmpl = item.valImpAsuEsteEmpl;

                    //Valor del impuesto retenido al trabajador por este empleador
                    detalleRDEP.valRet = item.valRet;

                    #endregion

                    oRdep.retRelDep.Add(detalleRDEP);
                }

                return(oRdep);
            }
            catch (Exception ex)
            {
                Core.Erp.Info.Log_Exception.LoggingManager.Logger.Log(Core.Erp.Info.Log_Exception.LoggingCategory.Error, ex.Message);
                throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "setInfoXML", ex.Message), ex)
                      {
                          EntityType = typeof(ro_Rdep_Bus)
                      };
            }
        }
        public Boolean Modificar_Num_Retencion(cp_retencion_Info Info_Retencion, ref string mensajeError)
        {
            try
            {
                Boolean res = false;


                tb_sis_Documento_Tipo_Talonario_Bus  busTalonario  = new tb_sis_Documento_Tipo_Talonario_Bus();
                tb_sis_Documento_Tipo_Talonario_Info infoTalonario = new tb_sis_Documento_Tipo_Talonario_Info();
                tb_Sucursal_Bus Bus_Sucu   = new tb_Sucursal_Bus();
                tb_Bodega_Bus   Bus_bodega = new tb_Bodega_Bus();

                string mensajeDocumentoDupli = "";
                string cod_estable           = "";
                string cod_pto_emision       = "";

                Info_Retencion.CodDocumentoTipo = string.IsNullOrEmpty(Info_Retencion.CodDocumentoTipo) ? "RETEN" : Info_Retencion.CodDocumentoTipo;


                // el objeto viene sin serie o sin # factura tomo el ultimo num de factura del talonario
                if (Info_Retencion.serie1 == "" || Info_Retencion.serie1 == null || Info_Retencion.serie2 == "" || Info_Retencion.serie2 == null ||
                    Info_Retencion.NumRetencion == "" || Info_Retencion.NumRetencion == null)
                {
                    cod_estable     = Bus_Sucu.Get_Cod_Establecimiento_x_Sucursal(Info_Retencion.IdEmpresa, param.IdSucursal);
                    cod_pto_emision = Bus_bodega.Get_cod_pto_emision_x_Bodega(Info_Retencion.IdEmpresa, param.IdSucursal, 1);

                    infoTalonario = busTalonario.Get_Info_Primer_Documento_no_usado(Info_Retencion.IdEmpresa, cod_estable, cod_pto_emision, Info_Retencion.CodDocumentoTipo
                                                                                    , Info_Retencion.EsDocumentoElectronico);


                    if (infoTalonario.NumDocumento == null)
                    {
                        mensajeError = "No hay talonarios para Establecimiento=" + cod_estable + " y punto de emision=" + cod_pto_emision;
                        throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "no hay talonario activos", mensajeError))
                              {
                                  EntityType = typeof(cp_retencion_Bus)
                              };
                    }

                    Info_Retencion.serie1       = infoTalonario.Establecimiento;
                    Info_Retencion.serie2       = infoTalonario.PuntoEmision;
                    Info_Retencion.NumRetencion = infoTalonario.NumDocumento;
                }
                else
                {
                    // se puede dar si mas de un usario estan haciendo la factura y tienen en memoria o en la pantalla el mismo talonario
                    //verifico el numero de factura si esta usado
                    infoTalonario.Establecimiento          = Info_Retencion.serie1;
                    infoTalonario.PuntoEmision             = Info_Retencion.serie2;
                    infoTalonario.NumDocumento             = Info_Retencion.NumRetencion;
                    infoTalonario.IdEmpresa                = Info_Retencion.IdEmpresa;
                    infoTalonario.CodDocumentoTipo         = Info_Retencion.CodDocumentoTipo;
                    infoTalonario.es_Documento_electronico = Info_Retencion.EsDocumentoElectronico;


                    if (busTalonario.Documento_talonario_esta_Usado(infoTalonario, ref mensajeError, ref mensajeDocumentoDupli))
                    {
                        //si esta en usado busco el siguiente
                        cod_estable     = Bus_Sucu.Get_Cod_Establecimiento_x_Sucursal(Info_Retencion.IdEmpresa, param.IdSucursal);
                        cod_pto_emision = Bus_bodega.Get_cod_pto_emision_x_Bodega(Info_Retencion.IdEmpresa, param.IdSucursal, 1);

                        infoTalonario = busTalonario.Get_Info_Primer_Documento_no_usado(Info_Retencion.IdEmpresa, cod_estable,
                                                                                        cod_pto_emision, Info_Retencion.CodDocumentoTipo, Info_Retencion.EsDocumentoElectronico);

                        if (infoTalonario.NumDocumento == null)
                        {
                            throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "no hay talonario activos", mensajeError))
                                  {
                                      EntityType = typeof(cp_retencion_Bus)
                                  };
                        }

                        Info_Retencion.serie1       = infoTalonario.Establecimiento;
                        Info_Retencion.serie2       = infoTalonario.PuntoEmision;
                        Info_Retencion.NumRetencion = infoTalonario.NumDocumento;

                        if (!infoTalonario.es_Documento_electronico)
                        {
                            //si no es documento electronico le actualizo el numero de autorizacion y la fecha de autorizacion
                            Info_Retencion.NAutorizacion      = infoTalonario.NumAutorizacion;
                            Info_Retencion.Fecha_Autorizacion = DateTime.Now.Date;
                        }
                    }
                    else
                    {
                        if (!infoTalonario.es_Documento_electronico)
                        {
                            //Si no esta siendo usado, si no es documento electronico le actualizo el numero de autorizacion y la fecha de autorizacion
                            infoTalonario = busTalonario.Get_Info_Documento_Tipo_Talonario(Info_Retencion.IdEmpresa, Info_Retencion.CodDocumentoTipo, cod_estable, cod_pto_emision, Info_Retencion.NumRetencion);


                            Info_Retencion.NAutorizacion      = infoTalonario.NumAutorizacion;
                            Info_Retencion.Fecha_Autorizacion = DateTime.Now.Date;
                        }
                    }
                }

                res = data_retencion.Modificar_Num_Retencion(Info_Retencion, ref mensajeError);
                busTalonario.Modificar_Estado_Usado(infoTalonario, ref mensajeError);

                return(res);
            }
            catch (Exception ex)
            {
                Core.Erp.Info.Log_Exception.LoggingManager.Logger.Log(Core.Erp.Info.Log_Exception.LoggingCategory.Error, ex.Message);
                throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "ModificarNRetencion", ex.Message), ex)
                      {
                          EntityType = typeof(cp_retencion_Bus)
                      };
            }
        }
        Boolean Validar_y_corregir_objeto(ref in_Guia_x_traspaso_bodega_Info Info_Guia, ref string msg)
        {
            try
            {
                #region 'Validaciones'
                /*--- validaciones */



                if (Info_Guia.IdEmpresa == 0)
                {
                    msg = "La variable estan en cero... IdEmpresa == 0  ";
                    return(false);
                }



                foreach (var item in Info_Guia.list_detalle_Guia)
                {
                    if (item.Cantidad_enviar == 0 || item.Cantidad_enviar == null)
                    {
                        msg = "Ingrese la cantidad de traspaso para el item : " + item.pr_descripcion + "  ";
                        return(false);
                    }
                }



                foreach (var item in Info_Guia.list_detalle_Guia_Sin_OC)
                {
                    if (item.Cantidad_enviar == 0 || item.Cantidad_enviar == null)
                    {
                        msg = "Ingrese la cantidad de traspaso para el item : " + item.nom_producto + "  ";
                        return(false);
                    }
                }


                if (Info_Guia.IdEmpresa <= 0 && Info_Guia.IdSucursal_Partida <= 0 && Info_Guia.IdSucursal_Llegada <= 0)
                {
                    msg = "Error en la cabecera de fact uno de los PK es <=0";
                    throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "Validaciones", msg))
                          {
                              EntityType = typeof(in_Guia_x_traspaso_bodega_Bus)
                          };
                }


                if (Info_Guia.IdTransportista <= 0)
                {
                    msg = "Erro en la cabecera de guia IdTransportista es <=0";
                    throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "Validaciones", msg))
                          {
                              EntityType = typeof(in_Guia_x_traspaso_bodega_Bus)
                          };
                }


                if (Info_Guia.IdMotivo_Traslado == "")
                {
                    msg = "Erro en la cabecera de IdMotivo_Traslado esta en blanco";
                    throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "Validaciones", msg))
                          {
                              EntityType = typeof(in_Guia_x_traspaso_bodega_Bus)
                          };
                }


                if (Info_Guia.list_detalle_Guia.Count == 0 && Info_Guia.list_detalle_Guia_Sin_OC.Count == 0)
                {
                    msg = "la guia  no tiene detalle ";
                    throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "Validaciones", msg))
                          {
                              EntityType = typeof(in_Guia_x_traspaso_bodega_Bus)
                          };
                }



                /*--- Fin validaciones */


                /*--- corrigiendo data */

                Info_Guia.Estado = (string.IsNullOrEmpty(Info_Guia.Estado) == true) ? "A" : Info_Guia.Estado;
                Info_Guia.Fecha  = Convert.ToDateTime(Info_Guia.Fecha).Date;



                tb_sis_Documento_Tipo_Talonario_Bus  busTalonario  = new tb_sis_Documento_Tipo_Talonario_Bus();
                tb_sis_Documento_Tipo_Talonario_Info infoTalonario = new tb_sis_Documento_Tipo_Talonario_Info();
                tb_Sucursal_Bus Bus_Sucu   = new tb_Sucursal_Bus();
                tb_Bodega_Bus   Bus_bodega = new tb_Bodega_Bus();

                string mensajeDocumentoDupli = "";
                string cod_estable           = "";
                string cod_pto_emision       = "";

                Info_Guia.CodDocumentoTipo = Cl_Enumeradores.eTipoDocumento_Talonario.GUIA.ToString();


                // el objeto viene sin serie o sin # factura tomo el ultimo num de factura del talonario
                if (Info_Guia.IdEstablecimiento == "" || Info_Guia.IdEstablecimiento == null || Info_Guia.IdPuntoEmision == "" || Info_Guia.IdPuntoEmision == null ||
                    Info_Guia.NumDocumento_Guia == "" || Info_Guia.NumDocumento_Guia == null)
                {
                    cod_estable     = Bus_Sucu.Get_Cod_Establecimiento_x_Sucursal(Info_Guia.IdEmpresa, Convert.ToInt32(Info_Guia.IdSucursal_Partida));
                    cod_pto_emision = Bus_bodega.Get_cod_pto_emision_x_Bodega(Info_Guia.IdEmpresa, Convert.ToInt32(Info_Guia.IdSucursal_Partida), 1); // la tabla no tiene bodega
                    infoTalonario   = busTalonario.Get_Info_Primer_Documento_no_usado(Info_Guia.IdEmpresa, cod_pto_emision, cod_estable, Info_Guia.CodDocumentoTipo, Info_Guia.Es_electronica);

                    if (infoTalonario.NumDocumento == null)
                    {
                        msg = "No hay talonarios para Establecimiento=" + cod_estable + " y punto de emision=" + cod_pto_emision;
                        throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "no hay talonario activos", msg))
                              {
                                  EntityType = typeof(in_Guia_x_traspaso_bodega_Bus)
                              };
                    }

                    Info_Guia.IdEstablecimiento = infoTalonario.Establecimiento;
                    Info_Guia.IdPuntoEmision    = infoTalonario.PuntoEmision;
                    Info_Guia.NumDocumento_Guia = infoTalonario.NumDocumento;
                }
                else
                {
                    // se puede dar si mas de un usario estan haciendo la factura y tienen en memoria o en la pantalla el mismo talonario
                    //verifico el numero de factura si esta usado
                    infoTalonario.Establecimiento          = Info_Guia.IdEstablecimiento;
                    infoTalonario.PuntoEmision             = Info_Guia.IdPuntoEmision;
                    infoTalonario.NumDocumento             = Info_Guia.NumDocumento_Guia;
                    infoTalonario.IdEmpresa                = Info_Guia.IdEmpresa;
                    infoTalonario.CodDocumentoTipo         = Info_Guia.CodDocumentoTipo;
                    infoTalonario.es_Documento_electronico = Info_Guia.Es_electronica;


                    if (Info_Guia.IdGuia == 0 && busTalonario.Documento_talonario_esta_Usado(infoTalonario, ref msg, ref mensajeDocumentoDupli))
                    {
                        //si esta en usado busco el siguiente
                        cod_estable     = Bus_Sucu.Get_Cod_Establecimiento_x_Sucursal(Info_Guia.IdEmpresa, Convert.ToInt32(Info_Guia.IdSucursal_Partida));
                        cod_pto_emision = Bus_bodega.Get_cod_pto_emision_x_Bodega(Info_Guia.IdEmpresa, Convert.ToInt32(Info_Guia.IdPuntoEmision), 1);

                        infoTalonario = busTalonario.Get_Info_Primer_Documento_no_usado(Info_Guia.IdEmpresa, cod_pto_emision, cod_estable, Info_Guia.CodDocumentoTipo, Info_Guia.Es_electronica);

                        if (infoTalonario.NumDocumento == null)
                        {
                            throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "no hay talonario activos", msg))
                                  {
                                      EntityType = typeof(in_Guia_x_traspaso_bodega_Bus)
                                  };
                        }

                        Info_Guia.IdEstablecimiento = infoTalonario.Establecimiento;
                        Info_Guia.IdPuntoEmision    = infoTalonario.PuntoEmision;
                        Info_Guia.NumDocumento_Guia = infoTalonario.NumDocumento;
                    }
                }


                /*--- corrigiendo data */

                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                Core.Erp.Info.Log_Exception.LoggingManager.Logger.Log(Core.Erp.Info.Log_Exception.LoggingCategory.Error, ex.Message);
                throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "Validar_y_corregir_objeto", ex.Message), ex)
                      {
                          EntityType = typeof(in_Guia_x_traspaso_bodega_Bus)
                      };
            }
        }