Exemplo n.º 1
0
        public FacturaBe ObtenerFactura(int empresaId, int facturaId, bool conCliente = false, bool conDetalle = false)
        {
            FacturaBe item = null;

            try
            {
                cn.Open();
                item = facturaDa.Obtener(empresaId, facturaId, cn);

                if (item != null)
                {
                    if (conCliente)
                    {
                        item.Cliente = clienteDa.Obtener(empresaId, item.ClienteId, cn);
                    }
                    if (conDetalle)
                    {
                        item.ListaFacturaDetalle = facturaDetalleDa.Listar(empresaId, facturaId, cn);
                    }
                }
                cn.Close();
            }
            catch (SqlException ex) { item = null; }
            catch (Exception ex) { item = null; }
            finally { if (cn.State == ConnectionState.Open)
                      {
                          cn.Close();
                      }
            }
            return(item);
        }
Exemplo n.º 2
0
        public bool GuardarRespuestaSunat(FacturaBe registro, SqlConnection cn)
        {
            bool seGuardo = false;

            try
            {
                using (SqlCommand cmd = new SqlCommand("dbo.usp_factura_guardar_respuestasunat", cn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@empresaId", registro.EmpresaId.GetNullable());
                    cmd.Parameters.AddWithValue("@facturaId", registro.FacturaId.GetNullable());
                    cmd.Parameters.AddWithValue("@codigoRespuestaSunat", registro.CodigoRespuestaSunat.GetNullable());
                    cmd.Parameters.AddWithValue("@descripcionRespuestaSunat", registro.DescripcionRespuestaSunat.GetNullable());
                    cmd.Parameters.AddWithValue("@estadoIdRespuestaSunat", registro.EstadoIdRespuestaSunat.GetNullable());
                    cmd.Parameters.AddWithValue("@rutaXml", registro.RutaXml.GetNullable());
                    cmd.Parameters.AddWithValue("@rutaCdr", registro.RutaCdr.GetNullable());
                    cmd.Parameters.AddWithValue("@usuario", registro.Usuario.GetNullable());

                    int filasAfectadas = cmd.ExecuteNonQuery();
                    seGuardo = filasAfectadas > 0;
                }
            }
            catch (Exception ex)
            {
                seGuardo = false;
            }
            return(seGuardo);
        }
Exemplo n.º 3
0
        public List <FacturaBe> Buscar(int empresaId, int ambienteSunatId, string nroDocumentoIdentidadCliente, string razonSocialCliente, DateTime fechaHoraEmisionDesde, DateTime fechaHoraEmisionHasta, int pagina, int cantidadRegistros, string columnaOrden, string ordenMax, SqlConnection cn, out int totalRegistros)
        {
            totalRegistros = 0;
            List <FacturaBe> lista = null;

            using (SqlCommand cmd = new SqlCommand("usp_factura_buscar", cn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@empresaId", empresaId.GetNullable());
                cmd.Parameters.AddWithValue("@ambienteSunatId", ambienteSunatId.GetNullable());
                cmd.Parameters.AddWithValue("@nroDocumentoIdentidadCliente", nroDocumentoIdentidadCliente.GetNullable());
                cmd.Parameters.AddWithValue("@razonSocialCliente", razonSocialCliente.GetNullable());
                cmd.Parameters.AddWithValue("@fechaHoraEmisionDesde", fechaHoraEmisionDesde.GetNullable());
                cmd.Parameters.AddWithValue("@fechaHoraEmisionHasta", fechaHoraEmisionHasta.GetNullable());
                cmd.Parameters.AddWithValue("@pagina", pagina.GetNullable());
                cmd.Parameters.AddWithValue("@cantidadRegistros", cantidadRegistros.GetNullable());
                cmd.Parameters.AddWithValue("@columnaOrden", columnaOrden.GetNullable());
                cmd.Parameters.AddWithValue("@ordenMax", ordenMax.GetNullable());
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        lista = new List <FacturaBe>();

                        while (dr.Read())
                        {
                            FacturaBe item = new FacturaBe();
                            item.Fila             = dr.GetData <int>("Fila");
                            item.FacturaId        = dr.GetData <int>("FacturaId");
                            item.SerieId          = dr.GetData <int>("SerieId");
                            item.Serie            = new SerieBe();
                            item.Serie.SerieId    = dr.GetData <int>("SerieId");
                            item.Serie.Serial     = dr.GetData <string>("SerialSerie");
                            item.NroComprobante   = dr.GetData <int>("NroComprobante");
                            item.FechaHoraEmision = dr.GetData <DateTime>("FechaHoraEmision");
                            item.FechaVencimiento = dr.GetData <DateTime>("FechaVencimiento");
                            item.Cliente          = new ClienteBe();
                            item.Cliente.NroDocumentoIdentidad = dr.GetData <string>("NroDocumentoIdentidadCliente");
                            item.Cliente.RazonSocial           = dr.GetData <string>("RazonSocialCliente");
                            item.ImporteTotal              = dr.GetData <decimal>("ImporteTotal");
                            item.FlagAnulado               = dr.GetData <bool>("FlagAnulado");
                            item.CodigoRespuestaSunat      = dr.GetData <string>("CodigoRespuestaSunat");
                            item.DescripcionRespuestaSunat = dr.GetData <string>("DescripcionRespuestaSunat");
                            item.EstadoIdRespuestaSunat    = dr.GetData <int?>("EstadoIdRespuestaSunat");
                            item.RutaXml = dr.GetData <string>("RutaXml");
                            item.RutaPdf = dr.GetData <string>("RutaPdf");
                            item.RutaCdr = dr.GetData <string>("RutaCdr");
                            lista.Add(item);

                            totalRegistros = dr.GetData <int>("Total");
                        }
                    }
                }
            }
            return(lista);
        }
Exemplo n.º 4
0
        public bool GuardarRespuestaSunatFactura(FacturaBe registro)
        {
            bool seGuardo = false;

            {
                try
                {
                    cn.Open();
                    seGuardo = facturaDa.GuardarRespuestaSunat(registro, cn);
                    cn.Close();
                }
                catch (Exception ex) { seGuardo = false; }
                finally { if (cn.State == ConnectionState.Open)
                          {
                              cn.Close();
                          }
                }
            }
            return(seGuardo);
        }
Exemplo n.º 5
0
        public bool Anular(FacturaBe registro, SqlConnection cn)
        {
            bool seGuardo = false;

            try
            {
                using (SqlCommand cmd = new SqlCommand("dbo.usp_factura_anular", cn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@empresaId", registro.EmpresaId.GetNullable());
                    cmd.Parameters.AddWithValue("@facturaId", registro.FacturaId.GetNullable());
                    cmd.Parameters.AddWithValue("@usuario", registro.Usuario.GetNullable());

                    int filasAfectadas = cmd.ExecuteNonQuery();
                    seGuardo = filasAfectadas > 0;
                }
            }
            catch (Exception ex)
            {
                seGuardo = false;
            }
            return(seGuardo);
        }
Exemplo n.º 6
0
        public bool GuardarFactura(FacturaBe registro)
        {
            var cookieSS = Request.Headers.GetCookies("ss").FirstOrDefault();
            var user     = JsonConvert.DeserializeObject <dynamic>(cookieSS["ss"].Value);

            int?     facturaId = null, nroComprobante = null;
            DateTime?fechaHoraEmision     = null;
            string   totalImporteEnLetras = null;
            bool     respuesta            = facturaBl.GuardarFactura(registro, out facturaId, out nroComprobante, out fechaHoraEmision, out totalImporteEnLetras);

            if (respuesta)
            {
                try
                {
                    if (facturaId.HasValue)
                    {
                        registro.FacturaId = facturaId.Value;
                    }
                    if (fechaHoraEmision.HasValue)
                    {
                        registro.FechaHoraEmision = fechaHoraEmision.Value;
                    }
                    if (nroComprobante.HasValue)
                    {
                        registro.NroComprobante = nroComprobante.Value;
                    }
                    if (totalImporteEnLetras != null)
                    {
                        registro.ImporteTotalEnLetras = totalImporteEnLetras;
                    }

                    int empresaId = user.Usuario.Empresa.EmpresaId;

                    registro.Empresa = empresaBl.ObtenerEmpresa(empresaId, withUbigeo: true, withConfiguracion: true);

                    List <ColumnasEmpresaImagen> columnasEmpresaImgen = new List <ColumnasEmpresaImagen> {
                        ColumnasEmpresaImagen.LogoFormatoTipoContenido, ColumnasEmpresaImagen.LogoFormato
                    };

                    var empresaImagen = empresaImagenBl.ObtenerDinamico(empresaId, columnasEmpresaImgen);

                    registro.LogoFormatoBase64 = $"data:${empresaImagen.LogoFormatoTipoContenido};base64,{Convert.ToBase64String(empresaImagen.LogoFormato)}";

                    string rucSOL           = registro.Empresa.EmpresaConfiguracion.EmpresaAmbienteSunat.RucSOL;
                    string usuarioSOL       = registro.Empresa.EmpresaConfiguracion.EmpresaAmbienteSunat.UsuarioSOL;
                    string claveSOL         = registro.Empresa.EmpresaConfiguracion.EmpresaAmbienteSunat.ClaveSOL;
                    string rutaCertificado  = registro.Empresa.EmpresaConfiguracion.RutaCertificado.Replace(@"~\", AppDomain.CurrentDomain.BaseDirectory);
                    string claveCertificado = registro.Empresa.EmpresaConfiguracion.ClaveCertificado;

                    //string rucSOL = AppSettings.Get<string>("Sunat.RucSOL");
                    //string usuarioSOL = AppSettings.Get<string>("Sunat.UsuarioSOL");
                    //string claveSOL = AppSettings.Get<string>("Sunat.ClaveSOL");
                    //string rutaCertificado = AppSettings.Get<string>("Sunat.RutaCertificado").Replace(@"~\", AppDomain.CurrentDomain.BaseDirectory);
                    //string claveCertificado = AppSettings.Get<string>("Sunat.ClaveCertificado");

                    InvoiceType invoiceType = ComprobanteSunat.ObtenerComprobante(registro, ComprobanteSunat.VersionUBL._2_1);

                    string contenidoXml        = Generar.GenerarXML(invoiceType);
                    string hash                = null;
                    string contenidoXmlFirmado = Generar.RetornarXmlFirmado("/tns:Invoice", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2", contenidoXml, rutaCertificado, claveCertificado, out hash);
                    registro.Hash = hash;

                    var qr = Generar.GenerarQR(registro.Empresa.Ruc, TipoComprobante.Factura.GetAttributeOfType <DefaultValueAttribute>().Value.ToString(), registro.Serie.Serial, registro.NroComprobante, registro.FechaHoraEmision, registro.Cliente.TipoDocumentoIdentidad.Codigo, registro.Cliente.NroDocumentoIdentidad, registro.TotalIgv, registro.ImporteTotal, registro.Hash);
                    registro.QRBase64 = $"data:image/png;base64,{Convert.ToBase64String(qr)}";

                    var formato = formatoBl.Obtener(registro.FormatoId.Value);

                    string registroJsonString = JsonConvert.SerializeObject(registro);

                    string html = formato.Html
                                  .Replace("[LOGO]", registro.LogoFormatoBase64)
                                  .Replace("[RUC_EMPRESA]", registro.Empresa.Ruc)
                                  .Replace("[SERIE]", registro.Serie.Serial)
                                  .Replace("[NUMERO]", registro.NroComprobante.ToString("00000000"))
                                  .Replace("[RAZON_SOCIAL]", registro.Cliente.RazonSocial)
                                  .Replace("[FECHA_EMISION]", registro.FechaHoraEmision.ToString("dd/MM/yyyy"))
                                  .Replace("[RUC]", registro.Cliente.NroDocumentoIdentidad)
                                  .Replace("[DIRECCION]", registro.Cliente.Direccion)
                                  .Replace("[FECHA_VENCIMIENTO]", registro.FechaVencimiento == null ? "" : registro.FechaVencimiento.Value.ToString("dd/MM/yyyy"))
                                  .Replace("[CONDICION_PAGO]", registro.FormaPago.Descripcion)
                                  .Replace("[ORDEN_COMPRA]", registro.ListaFacturaOrdenCompraStr)
                                  .Replace("[MONEDA]", registro.Moneda.Nombre)
                                  .Replace("[DETALLE]", string.Join(Environment.NewLine, registro.ListaFacturaDetalle.Select(x => $"<li class='data row'><span class='text-center'>{x.Fila}</span><span class='text-right'>{x.Cantidad}</span><span>{x.UnidadMedida.Descripcion}</span><span>{x.Descripcion}</span><span class='text-right'>{x.ValorUnitario:0.00}</span><span class='text-right'>{x.Descuento:0.00}</span><span class='text-right'>{x.ValorVenta:0.00}</span><span class='text-right'>{x.PrecioUnitario:0.00}</span><span class='text-right'>{x.PrecioVenta:0.00}</span></li>").ToArray()))
                                  .Replace("[SIMBOLO_MONEDA]", registro.Moneda.Simbolo)
                                  .Replace("[TOTAL_GRAVADO]", registro.TotalGravado.ToString("0.00"))
                                  .Replace("[TOTAL_INAFECTO]", registro.TotalInafecto.ToString("0.00"))
                                  .Replace("[TOTAL_EXONERADO]", registro.TotalExonerado.ToString("0.00"))
                                  .Replace("[TOTAL_GRATUITO]", registro.TotalGratuito.ToString("0.00"))
                                  .Replace("[TOTAL_DESCUENTO]", registro.TotalDescuentos.ToString("0.00"))
                                  .Replace("[TOTAL_IGV]", registro.TotalIgv.ToString("0.00"))
                                  .Replace("[TOTAL_ISC]", registro.TotalIsc.ToString("0.00"))
                                  .Replace("[TOTAL_OTROSCARGOS]", registro.TotalOtrosCargos.ToString("0.00"))
                                  .Replace("[TOTAL_OTROSTRIBUTOS]", registro.TotalOtrosTributos.ToString("0.00"))
                                  .Replace("[TOTAL_IMPORTETOTAL]", registro.ImporteTotal.ToString("0.00"))
                                  .Replace("[BENEFICIARIO]", registro.Empresa.RazonSocial)
                                  .Replace("[CUENTA_CORRIENTE]", registro.Empresa.EmpresaConfiguracion.CuentaCorriente)
                                  .Replace("[COMENTARIO_LEGAL]", registro.Empresa.EmpresaConfiguracion.ComentarioLegal)
                                  .Replace("[OBSERVACIONES]", registro.Observacion)
                                  .Replace("[LETRAS_MONTOAPAGAR]", registro.ImporteTotalEnLetras)
                                  .Replace("[TOTAL_MONTOAPAGAR]", registro.ImporteTotal.ToString("0.00"))
                                  .Replace("[QR]", registro.QRBase64);
                    //.Replace("[DATA]", registroJsonString);
                    byte[] contenidoPdfBytes = ut.HtmlToPdf.GetSelectPdf(html, PdfPageSize.A4);
                    //byte[] contenidoPdfBytes = ut.HtmlToPdf.GenerarPDF(html);

                    //byte[] contenidoXmlFirmadoBytes = Convert.FromBase64String(contenidoXmlFirmado);
                    //byte[] contenidoXmlFirmadoBytes = Encoding.UTF8.GetBytes(contenidoXmlFirmado);
                    string nombreArchivo    = $"{registro.Empresa.Ruc}-{TipoComprobante.Factura.GetAttributeOfType<DefaultValueAttribute>().Value}-{registro.Serie.Serial}-{registro.NroComprobante}";
                    string nombreArchivoXml = $"{nombreArchivo}.xml";
                    string nombreArchivoPdf = $"{nombreArchivo}.pdf";
                    string nombreArchivoZip = $"{nombreArchivo}.zip";
                    string nombreArchivoCdr = $"R-{nombreArchivo}.zip";
                    //byte[] contenidoZipBytes = Generar.RetornarXmlComprimido(contenidoXmlFirmadoBytes, nombreArchivoXml);
                    byte[] contenidoZipBytes = Generar.RetornarXmlComprimido(contenidoXmlFirmado, nombreArchivoXml);
                    string rutaCarpetaSunatComprobantesBase = AppSettings.Get <string>("Empresa.Almacenamiento.Sunat.Comprobantes");
                    string rutaCarpetaSunatComprobantes     = rutaCarpetaSunatComprobantesBase
                                                              .Replace(@"~\", AppDomain.CurrentDomain.BaseDirectory)
                                                              .Replace("{Ruc}", registro.Empresa.Ruc)
                                                              .Replace("{AmbienteSunat}", registro.Empresa.EmpresaConfiguracion.EmpresaAmbienteSunat.AmbienteSunat.Nombre)
                                                              .Replace("{TipoComprobante}", TipoComprobante.Factura.GetAttributeOfType <DefaultValueAttribute>().Value.ToString())
                                                              .Replace("{Comprobante}", $"{registro.Serie.Serial}-{registro.NroComprobante}");
                    string rutaArchivoXml = Path.Combine(rutaCarpetaSunatComprobantes, nombreArchivoXml);
                    string rutaArchivoCdr = Path.Combine(rutaCarpetaSunatComprobantes, nombreArchivoCdr);
                    string rutaArchivoPdf = Path.Combine(rutaCarpetaSunatComprobantes, nombreArchivoPdf);

                    bool existeCarpeta = Directory.Exists(rutaCarpetaSunatComprobantes);

                    if (!existeCarpeta)
                    {
                        Directory.CreateDirectory(rutaCarpetaSunatComprobantes);
                    }
                    File.WriteAllText(rutaArchivoXml, contenidoXmlFirmado);
                    //File.WriteAllBytes(rutaArchivoXml, contenidoXmlFirmadoBytes);
                    File.WriteAllBytes(rutaArchivoPdf, contenidoPdfBytes);

                    string    codigoCdr = null, descripcionCdr = null;
                    EstadoCdr?estadoCdr = null;
                    byte[]    cdrBytes  = null;
                    bool      seEmitio  = emitir.Venta(registro.Empresa.EmpresaConfiguracion.EmpresaAmbienteSunat.AmbienteSunat.ServicioWebUrlVenta, nombreArchivoZip, contenidoZipBytes, rucSOL, usuarioSOL, claveSOL, out cdrBytes, out codigoCdr, out descripcionCdr, out estadoCdr);

                    if (cdrBytes != null)
                    {
                        File.WriteAllBytes(rutaArchivoCdr, cdrBytes);
                    }

                    registro.CodigoRespuestaSunat      = codigoCdr;
                    registro.DescripcionRespuestaSunat = descripcionCdr;
                    registro.EstadoIdRespuestaSunat    = estadoCdr.HasValue ? (int?)estadoCdr.Value : null;
                    registro.RutaXml = rutaArchivoXml;
                    registro.RutaCdr = rutaArchivoCdr;

                    bool seGuardoRespuestaSunat = facturaBl.GuardarRespuestaSunatFactura(registro);
                }
                catch (Exception ex)
                {
                    string rutaLog = AppSettings.Get <string>("Log.Ruta")
                                     .Replace("~", AppDomain.CurrentDomain.BaseDirectory)
                                     .Replace("{Fecha}", DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"));

                    string[] errors = new string[] { "Message: " + ex.Message, "StackTrace: " + ex.StackTrace };

                    File.WriteAllText(rutaLog, string.Join(Environment.NewLine, errors));
                }
            }
            return(respuesta);
        }
Exemplo n.º 7
0
        public bool AnularFactura(FacturaBe registro)
        {
            bool respuesta = facturaBl.AnularFactura(registro);

            return(respuesta);
        }
Exemplo n.º 8
0
        public FacturaBe Obtener(int empresaId, int facturaId, SqlConnection cn)
        {
            FacturaBe item = null;

            using (SqlCommand cmd = new SqlCommand("usp_factura_obtener", cn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@empresaId", empresaId.GetNullable());
                cmd.Parameters.AddWithValue("@facturaId", facturaId.GetNullable());

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        item = new FacturaBe();

                        if (dr.Read())
                        {
                            item.EmpresaId                  = dr.GetData <int>("EmpresaId");
                            item.FacturaId                  = dr.GetData <int>("FacturaId");
                            item.AmbienteSunatId            = dr.GetData <int>("AmbienteSunatId");
                            item.SedeId                     = dr.GetData <int>("SedeId");
                            item.SerieId                    = dr.GetData <int>("SerieId");
                            item.NroComprobante             = dr.GetData <int>("NroComprobante");
                            item.FechaHoraEmision           = dr.GetData <DateTime>("FechaHoraEmision");
                            item.FechaVencimiento           = dr.GetData <DateTime>("FechaVencimiento");
                            item.MonedaId                   = dr.GetData <int>("MonedaId");
                            item.TipoOperacionVentaId       = dr.GetData <int>("TipoOperacionVentaId");
                            item.ClienteId                  = dr.GetData <int>("ClienteId");
                            item.FormaPagoId                = dr.GetData <int>("FormaPagoId");
                            item.FlagExportacion            = dr.GetData <bool>("FlagExportacion");
                            item.FlagGratuito               = dr.GetData <bool>("FlagGratuito");
                            item.FlagEmisorItinerante       = dr.GetData <bool>("FlagEmisorItinerante");
                            item.FlagAnticipo               = dr.GetData <bool>("FlagAnticipo");
                            item.FlagISC                    = dr.GetData <bool>("FlagISC");
                            item.FlagOtrosCargos            = dr.GetData <bool>("FlagOtrosCargos");
                            item.FlagOtrosTributos          = dr.GetData <bool>("FlagOtrosTributos");
                            item.TotalGravado               = dr.GetData <decimal>("TotalGravado");
                            item.TotalExonerado             = dr.GetData <decimal>("TotalExonerado");
                            item.TipoTributoIdExonerado     = dr.GetData <int?>("TipoTributoIdExonerado");
                            item.TotalInafecto              = dr.GetData <decimal>("TotalInafecto");
                            item.TipoTributoIdInafecto      = dr.GetData <int?>("TipoTributoIdInafecto");
                            item.TotalExportacion           = dr.GetData <decimal>("TotalExportacion");
                            item.TipoTributoIdExportacion   = dr.GetData <int?>("TipoTributoIdExportacion");
                            item.TotalGratuito              = dr.GetData <decimal>("TotalGratuito");
                            item.TipoTributoIdGratuito      = dr.GetData <int?>("TipoTributoIdGratuito");
                            item.TotalVentaArrozPilado      = dr.GetData <decimal>("TotalVentaArrozPilado");
                            item.TotalIgv                   = dr.GetData <decimal>("TotalIgv");
                            item.TipoTributoIdIgv           = dr.GetData <int?>("TipoTributoIdIgv");
                            item.TotalIsc                   = dr.GetData <decimal>("TotalIsc");
                            item.TipoTributoIdIsc           = dr.GetData <int?>("TipoTributoIdIsc");
                            item.TotalOtrosTributos         = dr.GetData <decimal>("TotalOtrosTributos");
                            item.TipoTributoIdOtrosTributos = dr.GetData <int?>("TipoTributoIdOtrosTributos");
                            item.TotalOtrosCargos           = dr.GetData <decimal>("TotalOtrosCargos");
                            item.TotalBaseImponible         = dr.GetData <decimal>("TotalBaseImponible");
                            item.TotalDescuentos            = dr.GetData <decimal>("TotalDescuentos");
                            item.ImporteTotal               = dr.GetData <decimal>("ImporteTotal");
                            item.ImporteTotalEnLetras       = dr.GetData <string>("ImporteTotalEnLetras");
                            item.Observacion                = dr.GetData <string>("Observacion");
                            item.Hash                      = dr.GetData <string>("Hash");
                            item.FlagAnulado               = dr.GetData <bool>("FlagAnulado");
                            item.CodigoRespuestaSunat      = dr.GetData <string>("CodigoRespuestaSunat");
                            item.DescripcionRespuestaSunat = dr.GetData <string>("DescripcionRespuestaSunat");
                            item.EstadoIdRespuestaSunat    = dr.GetData <int?>("EstadoIdRespuestaSunat");
                            item.RutaXml                   = dr.GetData <string>("RutaXml");
                            item.RutaPdf                   = dr.GetData <string>("RutaPdf");
                            item.RutaCdr                   = dr.GetData <string>("RutaCdr");
                            item.FormatoId                 = dr.GetData <int?>("FormatoId");
                            //item.CreadoPor = dr.GetData<string>("CreadoPor");
                            //item.FechaCreacion = dr.GetData<string>("FechaCreacion");
                            //item.ModificadoPor = dr.GetData<string>("ModificadoPor");
                            //item.FechaModificacion = dr.GetData<string>("FechaModificacion");
                        }
                    }
                }
            }

            return(item);
        }
Exemplo n.º 9
0
        public bool Guardar(FacturaBe registro, SqlConnection cn, out int?facturaId, out int?nroComprobante, out DateTime?fechaHoraEmision, out string totalImporteEnLetras)
        {
            facturaId            = null;
            nroComprobante       = null;
            fechaHoraEmision     = null;
            totalImporteEnLetras = null;
            bool seGuardo = false;

            try
            {
                using (SqlCommand cmd = new SqlCommand("dbo.usp_factura_guardar", cn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@empresaId", registro.EmpresaId.GetNullable());
                    cmd.Parameters.Add(new SqlParameter {
                        ParameterName = "@facturaId", SqlDbType = SqlDbType.Int, Value = registro.FacturaId.GetNullable(), Direction = ParameterDirection.InputOutput
                    });
                    cmd.Parameters.AddWithValue("@sedeId", registro.SedeId.GetNullable());
                    cmd.Parameters.AddWithValue("@serieId", registro.SerieId.GetNullable());
                    cmd.Parameters.Add(new SqlParameter {
                        ParameterName = "@nroComprobante", SqlDbType = SqlDbType.Int, Value = registro.NroComprobante.GetNullable(), Direction = ParameterDirection.InputOutput
                    });
                    cmd.Parameters.Add(new SqlParameter {
                        ParameterName = "@fechaHoraEmision", SqlDbType = SqlDbType.DateTime, Value = DBNull.Value, Direction = ParameterDirection.InputOutput
                    });
                    cmd.Parameters.AddWithValue("@fechaVencimiento", registro.FechaVencimiento.GetNullable());
                    cmd.Parameters.AddWithValue("@monedaId", registro.MonedaId.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoOperacionVentaId", registro.TipoOperacionVentaId.GetNullable());
                    cmd.Parameters.AddWithValue("@formaPagoId", registro.FormaPagoId.GetNullable());
                    cmd.Parameters.AddWithValue("@formatoId", registro.FormatoId.GetNullable());
                    cmd.Parameters.AddWithValue("@observacion", registro.Observacion.GetNullable());
                    cmd.Parameters.AddWithValue("@clienteID", registro.ClienteId.GetNullable());
                    cmd.Parameters.AddWithValue("@flagExportacion", registro.FlagExportacion.GetNullable());
                    cmd.Parameters.AddWithValue("@flagGratuito", registro.FlagGratuito.GetNullable());
                    cmd.Parameters.AddWithValue("@flagEmisorItinerante", registro.FlagEmisorItinerante.GetNullable());
                    cmd.Parameters.AddWithValue("@flagAnticipo", registro.FlagAnticipo.GetNullable());
                    cmd.Parameters.AddWithValue("@flagISC", registro.FlagISC.GetNullable());
                    cmd.Parameters.AddWithValue("@flagOtrosCargos", registro.FlagOtrosCargos.GetNullable());
                    cmd.Parameters.AddWithValue("@flagOtrosTributos", registro.FlagOtrosTributos.GetNullable());
                    cmd.Parameters.AddWithValue("@totalGravado", registro.TotalGravado.GetNullable());
                    cmd.Parameters.AddWithValue("@totalExonerado", registro.TotalExonerado.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoTributoIdExonerado", registro.TipoTributoIdExonerado.GetNullable());
                    cmd.Parameters.AddWithValue("@totalInafecto", registro.TotalInafecto.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoTributoIdInafecto", registro.TipoTributoIdInafecto.GetNullable());
                    cmd.Parameters.AddWithValue("@totalExportacion", registro.TotalExportacion.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoTributoIdExportacion", registro.TipoTributoIdExportacion.GetNullable());
                    cmd.Parameters.AddWithValue("@totalGratuito", registro.TotalGratuito.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoTributoIdGratuito", registro.TipoTributoIdGratuito.GetNullable());
                    cmd.Parameters.AddWithValue("@totalVentaArrozPilado", registro.TotalVentaArrozPilado.GetNullable());
                    cmd.Parameters.AddWithValue("@totalIgv", registro.TotalIgv.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoTributoIdIgv", registro.TipoTributoIdIgv.GetNullable());
                    cmd.Parameters.AddWithValue("@totalIsc", registro.TotalIsc.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoTributoIdIsc", registro.TipoTributoIdIsc.GetNullable());
                    cmd.Parameters.AddWithValue("@totalOtrosTributos", registro.TotalOtrosTributos.GetNullable());
                    cmd.Parameters.AddWithValue("@tipoTributoIdOtrosTributos", registro.TipoTributoIdOtrosTributos.GetNullable());
                    cmd.Parameters.AddWithValue("@totalOtrosCargos", registro.TotalOtrosCargos.GetNullable());
                    cmd.Parameters.AddWithValue("@totalBaseImponible", registro.TotalBaseImponible.GetNullable());
                    cmd.Parameters.AddWithValue("@totalDescuentos", registro.TotalDescuentos.GetNullable());
                    cmd.Parameters.AddWithValue("@importeTotal", registro.ImporteTotal.GetNullable());
                    cmd.Parameters.AddWithValue("@ambienteSunatId", registro.AmbienteSunatId.GetNullable());
                    cmd.Parameters.Add(new SqlParameter {
                        ParameterName = "@importeTotalEnLetras", SqlDbType = SqlDbType.VarChar, Size = -1, Value = DBNull.Value, Direction = ParameterDirection.InputOutput
                    });
                    cmd.Parameters.AddWithValue("@usuario", registro.Usuario.GetNullable());

                    int filasAfectadas = cmd.ExecuteNonQuery();
                    seGuardo = filasAfectadas > 0;
                    if (seGuardo)
                    {
                        facturaId            = (int?)cmd.Parameters["@facturaId"].Value;
                        nroComprobante       = (int?)cmd.Parameters["@nroComprobante"].Value;
                        fechaHoraEmision     = (DateTime?)cmd.Parameters["@fechaHoraEmision"].Value;
                        totalImporteEnLetras = (string)cmd.Parameters["@importeTotalEnLetras"].Value;
                    }
                }
            }
            catch (Exception ex)
            {
                seGuardo = false;
            }
            return(seGuardo);
        }
Exemplo n.º 10
0
        public bool GuardarFactura(FacturaBe registro, out int?facturaId, out int?nroComprobante, out DateTime?fechaHoraEmision, out string totalImporteEnLetras)
        {
            facturaId            = null;
            nroComprobante       = null;
            fechaHoraEmision     = null;
            totalImporteEnLetras = null;
            bool seGuardo = false;

            {
                try
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        cn.Open();
                        seGuardo = facturaDa.Guardar(registro, cn, out facturaId, out nroComprobante, out fechaHoraEmision, out totalImporteEnLetras);
                        // Si seGuardo es True entonces
                        if (seGuardo)
                        {
                            //if (registro.ListaFacturaDetalleEliminados != null)
                            //{
                            //    foreach (int facturaDetalleId in registro.ListaFacturaDetalleEliminados)
                            //    {
                            //        FacturaDetalleBe registroDetalleEliminar = new FacturaDetalleBe();
                            //        registroDetalleEliminar.EmpresaId = registro.EmpresaId;
                            //        registroDetalleEliminar.FacturaId = (int)facturaId;
                            //        registroDetalleEliminar.FacturaDetalleId = facturaDetalleId;
                            //        registroDetalleEliminar.Usuario = registro.Usuario;
                            //        seGuardo = facturaDetalleDa.Eliminar(registroDetalleEliminar, cn);

                            //        if (!seGuardo) break;
                            //    }
                            //}

                            // Si la Lista de Detalle es diferente de Null
                            if (registro.ListaFacturaDetalle != null)
                            {
                                //Entonces recorro la misma Lista de detalle con el Item
                                foreach (var item in registro.ListaFacturaDetalle)
                                {
                                    int?facturaDetalleId = null;

                                    item.FacturaId = (int)facturaId;
                                    item.EmpresaId = registro.EmpresaId;
                                    item.Usuario   = registro.Usuario;
                                    seGuardo       = facturaDetalleDa.Guardar(item, cn, out facturaDetalleId);
                                    //seGuardo = new
                                    if (!seGuardo)
                                    {
                                        break;
                                    }
                                }
                            }

                            //if(registro.ListaFacturaGuiaRemision != null)
                            //{
                            //    foreach(var item in registro.ListaFacturaGuiaRemision)
                            //    {
                            //        int? facturaGuiaRemision = null;
                            //        item.FacturaId = (int)facturaId;
                            //        item.EmpresaId = registro.EmpresaId;
                            //        item.Usuario = registro.Usuario;
                            //        seg
                            //    }
                            //}
                        }

                        if (seGuardo)
                        {
                            scope.Complete();
                        }
                        cn.Close();
                    }
                }
                catch (Exception ex) { seGuardo = false; }
                finally { if (cn.State == ConnectionState.Open)
                          {
                              cn.Close();
                          }
                }
            }
            return(seGuardo);
        }