IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (DocumentoElectronico)request; documento.MontoEnLetras = Conversion.Enletras(documento.TotalVenta); var invoice = new Invoice { UblExtensions = new UblExtensions { Extension2 = new UblExtension { ExtensionContent = new ExtensionContent { AdditionalInformation = new AdditionalInformation { AdditionalMonetaryTotals = new List <AdditionalMonetaryTotal>() { new AdditionalMonetaryTotal() { Id = "1001", PayableAmount = new PayableAmount() { CurrencyId = documento.Moneda, Value = documento.Gravadas } }, new AdditionalMonetaryTotal { Id = "1002", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Inafectas } }, new AdditionalMonetaryTotal { Id = "1003", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Exoneradas } }, new AdditionalMonetaryTotal { Id = "1004", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Gratuitas } }, new AdditionalMonetaryTotal { Percent = (documento.CalculoIgv * 100) } }, AdditionalProperties = new List <AdditionalProperty>() { new AdditionalProperty { Id = "1000", Value = documento.MontoEnLetras }, new AdditionalProperty { Id = "2006", Value = "OPERACIÓN SUJETA A DETRACCIÓN" } } } } } }, Id = documento.IdDocumento, IssueDate = DateTime.Parse(documento.FechaEmision), IssueTime = documento.IssueTime == "" ? String.Format("{0:HH:mm:ss}", DateTime.Now) : documento.IssueTime, InvoiceTypeCode = documento.TipoDocumento, DocumentCurrencyCode = documento.Moneda, LineCountNumeric = documento.LineCountNumeric, Glosa = documento.Glosa, Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, CodDomicilioFiscal = documento.Emisor.CodDomicilioFiscal, Party = new Party { PartyName = new PartyName { Name = documento.Emisor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Emisor.Ubigeo, StreetName = documento.Emisor.Direccion, CitySubdivisionName = documento.Emisor.Urbanizacion, CountrySubentity = documento.Emisor.Departamento, CityName = documento.Emisor.Provincia, District = documento.Emisor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } }, AccountingCustomerParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Receptor.NroDocumento, AdditionalAccountId = documento.Receptor.TipoDocumento, Party = new Party { PartyName = new PartyName { Name = documento.Receptor.NombreComercial ?? string.Empty }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Receptor.NombreLegal } } }, UblVersionId = "2.1", CustomizationId = "2.0", OrderReference = documento.OrderReference, AdditionalItemProperty = documento.AdditionalItemProperty, PaymentMeans = new Estructuras.CommonAggregateComponents.PaymentMeans { ID = documento.MediosPago.ID, PaymentMeansCode = documento.MediosPago.PaymentMeansCode }, LegalMonetaryTotal = new LegalMonetaryTotal { PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalVenta //Si existe descuento se recalcular monto gravado }, AllowanceTotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal, MultiplierFactorNumeric = documento.MultiplierFactorNumeric }, BaseAmount = new PayableAmount /*DESCUENTO GLOBAL - SI EXISTE DESCUENTO RECALCULAMOS SUMATORIA PARA REALIZAR DESCUENTO*/ { Value = documento.Items.Where(d => d.TipoImpuesto.StartsWith("1")).Sum(d => d.Suma) + documento.Items.Where(d => d.TipoImpuesto.Contains("20")).Sum(d => d.Suma) + documento.Items.Where(d => d.TipoImpuesto.StartsWith("3") || d.TipoImpuesto.Contains("40")).Sum(d => d.Suma) + documento.Items.Where(d => d.TipoImpuesto.Contains("21")).Sum(d => d.Suma) } }, Cargos = new LegalMonetaryTotal { AllowanceTotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Cargos, MultiplierFactorNumeric = documento.MultiplierFactorNumeric }, }, TaxTotals = new List <TaxTotal>(), DeliveryTerms = new DeliveryTerms { Id = "IMCOTERM", Value = documento.Imcoterm } }; if (documento.Gravadas > 0) { invoice.TaxTotals.Add(new TaxTotal { //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Gravadas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal > 0 ? ((documento.Gravadas) * documento.CalculoIgv) : documento.TotalIgv }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal > 0 ? ((documento.Gravadas) * documento.CalculoIgv) : documento.TotalIgv, }, TaxCategory = new TaxCategory { Identifier = "S", //VALOR OBTENIDO DE LA TABLA 5 TaxScheme = new TaxScheme { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Gravadas } }); } if (documento.Exoneradas > 0) { invoice.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Exoneradas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "E", TaxScheme = new TaxScheme { Id = "9997", Name = "EXO", TaxTypeCode = "VAT" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Exoneradas } }); } if (documento.Inafectas > 0) { if (documento.TipoOperacion == "0200") {//EXPORTACION invoice.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Inafectas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "G", TaxScheme = new TaxScheme { Id = "9995", Name = "EXP", TaxTypeCode = "FRE" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Inafectas } }); } else { invoice.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Inafectas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "O", TaxScheme = new TaxScheme { Id = "9998", Name = "INA", TaxTypeCode = "FRE" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Inafectas } }); } } if (documento.TotalIsc > 0) { invoice.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIsc, }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIsc }, TaxCategory = new TaxCategory { Identifier = "S", //VALOR OBTENIDO DE LA TABLA 5 TaxScheme = new TaxScheme { Id = "2000", Name = "ISC", TaxTypeCode = "EXC" } } } }); } if (documento.TotalOtrosTributos > 0) { invoice.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalOtrosTributos, }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalOtrosTributos }, TaxCategory = new TaxCategory { Identifier = "S", //VALOR OBTENIDO DE LA TABLA 5 TaxScheme = new TaxScheme { Id = "9999", Name = "OTROS", TaxTypeCode = "OTH" } } } }); } /* Numero de Placa del Vehiculo - Gastos art.37° Renta */ if (!string.IsNullOrEmpty(documento.PlacaVehiculo)) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.SunatCosts.RoadTransport .LicensePlateId = documento.PlacaVehiculo; } /* Tipo de Operación - Catalogo N° 17 */ if (!string.IsNullOrEmpty(documento.TipoOperacion) && documento.DatosGuiaTransportista == null) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.SunatTransaction.Id = documento.TipoOperacion; // Si es Emisor Itinerante. if (documento.TipoOperacion == "05") { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalProperties.Add(new AdditionalProperty { Id = "3000", // En el catalogo aparece como 2005 pero es 3000 Value = "Venta realizada por emisor itinerante" }); } } foreach (var relacionado in documento.Relacionados) { invoice.DespatchDocumentReferences.Add(new InvoiceDocumentReference { DocumentTypeCode = relacionado.TipoDocumento, Id = relacionado.NroDocumento }); } foreach (var relacionado in documento.OtrosDocumentosRelacionados) { invoice.AdditionalDocumentReferences.Add(new InvoiceDocumentReference { DocumentTypeCode = relacionado.TipoDocumento, Id = relacionado.NroDocumento }); } if (documento.Gratuitas > 0 || documento.Items.Where(a => a.TipoImpuesto.ToString() == "21").Any()) { invoice.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = Convert.ToDecimal(documento.Items.Where(y => y.TipoImpuesto == "21").Select(a => a.PrecioReferencial).Sum()) }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "Z", TaxScheme = new TaxScheme { Id = "9996", Name = "GRA", TaxTypeCode = "FRE" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Gratuitas > 0 ? 0 : documento.Gratuitas } }); invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalProperties.Add(new AdditionalProperty { Id = "1002", Value = "TRANSFERENCIA GRATUITA DE UN BIEN Y/O SERVICIO PRESTADO GRATUITAMENTE" }); } var dctosPorItem = documento.Items.Sum(d => d.Descuento); if (documento.DescuentoGlobal > 0 || dctosPorItem > 0) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalMonetaryTotals.Add(new AdditionalMonetaryTotal { Id = "2005", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal + dctosPorItem } }); } if (documento.MontoPercepcion > 0) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalMonetaryTotals.Add(new AdditionalMonetaryTotal { Id = "2001", ReferenceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalVenta }, PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.MontoPercepcion }, TotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalVenta + documento.MontoPercepcion } }); } if (documento.MontoAnticipo > 0) { invoice.PrepaidPayment = new BillingPayment { Id = new PartyIdentificationId { SchemeId = documento.TipoDocAnticipo, Value = documento.DocAnticipo }, PaidAmount = new PayableAmount { CurrencyId = documento.MonedaAnticipo, Value = documento.MontoAnticipo }, InstructionId = documento.Emisor.NroDocumento }; invoice.LegalMonetaryTotal.PrepaidAmount = new PayableAmount { CurrencyId = documento.MonedaAnticipo, Value = documento.MontoAnticipo }; } // Datos Adicionales a la Factura. foreach (var adicional in documento.DatoAdicionales) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalProperties.Add(new AdditionalProperty { Id = adicional.Codigo, Value = adicional.Contenido }); } if (documento.MontoDetraccion > 0) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalMonetaryTotals.Add(new AdditionalMonetaryTotal { Id = "2003", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.MontoDetraccion }, Percent = documento.CalculoDetraccion * 100 }); } // Para datos de Guia de Remision Transportista. if (!string.IsNullOrEmpty(documento.DatosGuiaTransportista?.RucTransportista)) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.SunatEmbededDespatchAdvice = new SunatEmbededDespatchAdvice { DeliveryAddress = new PostalAddress { Id = documento.DatosGuiaTransportista.DireccionDestino.Ubigeo, StreetName = documento.DatosGuiaTransportista.DireccionDestino.Direccion, CitySubdivisionName = documento.DatosGuiaTransportista.DireccionDestino.Urbanizacion, CityName = documento.DatosGuiaTransportista.DireccionDestino.Departamento, CountrySubentity = documento.DatosGuiaTransportista.DireccionDestino.Provincia, District = documento.DatosGuiaTransportista.DireccionDestino.Distrito, Country = new Country { IdentificationCode = "PE" } }, OriginAddress = new PostalAddress { Id = documento.DatosGuiaTransportista.DireccionOrigen.Ubigeo, StreetName = documento.DatosGuiaTransportista.DireccionOrigen.Direccion, CitySubdivisionName = documento.DatosGuiaTransportista.DireccionOrigen.Urbanizacion, CityName = documento.DatosGuiaTransportista.DireccionOrigen.Departamento, CountrySubentity = documento.DatosGuiaTransportista.DireccionOrigen.Provincia, District = documento.DatosGuiaTransportista.DireccionOrigen.Distrito, Country = new Country { IdentificationCode = "PE" } }, SunatCarrierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.DatosGuiaTransportista.RucTransportista, AdditionalAccountId = "06", Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.DatosGuiaTransportista.NombreTransportista } } }, DriverParty = new AgentParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.DatosGuiaTransportista.NroLicenciaConducir } } }, SunatRoadTransport = new SunatRoadTransport { LicensePlateId = documento.DatosGuiaTransportista.PlacaVehiculo, TransportAuthorizationCode = documento.DatosGuiaTransportista.CodigoAutorizacion, BrandName = documento.DatosGuiaTransportista.MarcaVehiculo }, TransportModeCode = documento.DatosGuiaTransportista.ModoTransporte, GrossWeightMeasure = new InvoicedQuantity { UnitCode = documento.DatosGuiaTransportista.UnidadMedida, Value = documento.DatosGuiaTransportista.PesoBruto } }; } foreach (var detalleDocumento in documento.Items) { var linea = new InvoiceLine { Id = detalleDocumento.Id, ItemClassificationCode = detalleDocumento.ItemClassificationCode, InvoicedQuantity = new InvoicedQuantity { UnitCode = detalleDocumento.UnidadMedida, Value = detalleDocumento.Cantidad }, LineExtensionAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Gratuitas > 0 ? 0 : detalleDocumento.TotalVenta }, PricingReference = new PricingReference { AlternativeConditionPrices = new List <AlternativeConditionPrice>() }, Item = new Item { Description = detalleDocumento.Descripcion, SellersItemIdentification = new SellersItemIdentification { Id = detalleDocumento.CodigoItem }, AdditionalItemIdentification = new AdditionalItemIdentification { Id = detalleDocumento.PlacaVehiculo } }, Price = new Price { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.PrecioUnitario } } }; /*DETRACCION*/ var porcentaje = documento.Items.Select(y => y.PorcentajeDetraccion).Max();// detalleDocumento.PorcentajeDetraccion.Max(); invoice.PaymentMeans.PaymentTerms.Add(new Estructuras.CommonAggregateComponents.PaymentTerms { PaymentMeansID = detalleDocumento.CodDetraccion, PaymentPercent = porcentaje, Amount = (documento.TotalVenta * (Convert.ToDecimal(porcentaje) / 100)) }); /* 17 - Sistema de ISC por ítem */ if (detalleDocumento.ImpuestoSelectivo > 0) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.ImpuestoSelectivo }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.ImpuestoSelectivo }, TaxCategory = new TaxCategory { TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TierRange = "01", TaxScheme = new TaxScheme() { Id = "2000", Name = "ISC", TaxTypeCode = "EXC" } } } }); } linea.PricingReference.AlternativeConditionPrices.Add(new AlternativeConditionPrice { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, // Comprobamos que sea una operacion gratuita. Value = documento.Gratuitas > 0 ? 0 : detalleDocumento.PrecioReferencial }, // Para operaciones no onerosas (gratuitas) PriceTypeCode = detalleDocumento.TipoImpuesto.Contains("21") ? "02" : detalleDocumento.TipoPrecio }); // linea.AditionalItemIdentification.Id = documento.PlacaVehiculo; /* 51 - Descuentos por ítem */ if (detalleDocumento.Descuento > 0) { linea.AllowanceCharge.ChargeIndicator = false; linea.AllowanceCharge.Amount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Descuento }; } /* 16 - Afectación al IGV por ítem */ if (documento.Gravadas > 0 && detalleDocumento.TipoImpuesto.StartsWith("1")) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "S", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } }); invoice.InvoiceLines.Add(linea); continue; } /* Exoneradas */ if (documento.Exoneradas > 0 && detalleDocumento.TipoImpuesto.Contains("20")) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "E", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9997", Name = "EXO", TaxTypeCode = "VAT" } } } }); invoice.InvoiceLines.Add(linea); continue; } /*INAFECTAS*/ if (documento.Inafectas > 0 && (detalleDocumento.TipoImpuesto.StartsWith("3") || detalleDocumento.TipoImpuesto.Contains("40"))) { if (documento.TipoOperacion == "0200") { //EXPORTACION linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "G", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9995", Name = "EXP", TaxTypeCode = "FRE" } } } }); } else { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "O", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9998", Name = "INA", TaxTypeCode = "FRE" } } } }); } invoice.InvoiceLines.Add(linea); continue; } /*GRATUITAS*/ if (documento.Gratuitas > 0 || detalleDocumento.TipoImpuesto.Contains("21")) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = (detalleDocumento.PrecioReferencial * detalleDocumento.Cantidad) }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "Z", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9996", Name = "GRA", TaxTypeCode = "FRE" } } } }); invoice.InvoiceLines.Add(linea); continue; } } return(invoice); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (DocumentoRetencion)request; var retention = new Retention { Id = documento.IdDocumento, IssueDate = documento.FechaEmision, Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AgentParty = new AgentParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { SchemeId = documento.Emisor.TipoDocumento, Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Emisor.Ubigeo, StreetName = documento.Emisor.Direccion, CitySubdivisionName = documento.Emisor.Urbanizacion, CountrySubentity = documento.Emisor.Departamento, CityName = documento.Emisor.Provincia, District = documento.Emisor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } }, ReceiverParty = new AgentParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { SchemeId = documento.Emisor.TipoDocumento, Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Emisor.Ubigeo, StreetName = documento.Emisor.Direccion, CitySubdivisionName = documento.Emisor.Urbanizacion, CountrySubentity = documento.Emisor.Departamento, CityName = documento.Emisor.Provincia, District = documento.Emisor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } }, SunatRetentionSystemCode = documento.RegimenRetencion, SunatRetentionPercent = documento.TasaRetencion, Note = documento.Observaciones, TotalInvoiceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.ImporteTotalRetenido }, TotalPaid = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.ImporteTotalPagado } }; foreach (var relacionado in documento.DocumentosRelacionados) { retention.SunatRetentionDocumentReference.Add(new SunatRetentionDocumentReference { Id = new PartyIdentificationId { SchemeId = relacionado.TipoDocumento, Value = relacionado.NroDocumento }, IssueDate = relacionado.FechaEmision, TotalInvoiceAmount = new PayableAmount { CurrencyId = relacionado.MonedaDocumentoRelacionado, Value = relacionado.ImporteTotal }, Payment = new Payment { IdPayment = relacionado.NumeroPago, PaidAmount = new PayableAmount { CurrencyId = relacionado.MonedaDocumentoRelacionado, Value = relacionado.ImporteSinRetencion }, PaidDate = relacionado.FechaPago }, SunatRetentionInformation = new SunatRetentionInformation { SunatRetentionAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = relacionado.ImporteRetenido }, SunatRetentionDate = relacionado.FechaRetencion, SunatNetTotalPaid = new PayableAmount { CurrencyId = documento.Moneda, Value = relacionado.ImporteTotalNeto }, ExchangeRate = new ExchangeRate { SourceCurrencyCode = relacionado.MonedaDocumentoRelacionado, TargetCurrencyCode = documento.Moneda, CalculationRate = relacionado.TipoCambio, Date = relacionado.FechaTipoCambio } } }); } return(retention); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (DocumentoElectronico)request; documento.MontoEnLetras = Conversion.Enletras(documento.TotalVenta); var invoice = new Invoice { UblExtensions = new UblExtensions { Extension2 = new UblExtension { ExtensionContent = new ExtensionContent { AdditionalInformation = new AdditionalInformation { AdditionalMonetaryTotals = new List <AdditionalMonetaryTotal>() { new AdditionalMonetaryTotal() { Id = "1001", PayableAmount = new PayableAmount() { CurrencyId = documento.Moneda, Value = documento.Gravadas } }, new AdditionalMonetaryTotal { Id = "1002", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Inafectas } }, new AdditionalMonetaryTotal { Id = "1003", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Exoneradas } }, new AdditionalMonetaryTotal { Id = "1004", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Gratuitas } } }, AdditionalProperties = new List <AdditionalProperty>() { new AdditionalProperty { Id = "1000", Value = documento.MontoEnLetras } } } } } }, Id = documento.IdDocumento, IssueDate = DateTime.Parse(documento.FechaEmision), InvoiceTypeCode = documento.TipoDocumento, DocumentCurrencyCode = documento.Moneda, Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, Party = new Party { PartyName = new PartyName { Name = documento.Emisor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Emisor.Ubigeo, StreetName = documento.Emisor.Direccion, CitySubdivisionName = documento.Emisor.Urbanizacion, CountrySubentity = documento.Emisor.Departamento, CityName = documento.Emisor.Provincia, District = documento.Emisor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } }, AccountingCustomerParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Receptor.NroDocumento, AdditionalAccountId = documento.Receptor.TipoDocumento, Party = new Party { PartyName = new PartyName { Name = documento.Receptor.NombreComercial ?? string.Empty }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Receptor.NombreLegal } } }, UblVersionId = "2.0", CustomizationId = "1.0", LegalMonetaryTotal = new LegalMonetaryTotal { PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalVenta }, AllowanceTotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal } }, TaxTotals = new List <TaxTotal> { new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIgv }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIgv, }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } } } }; if (documento.TotalIsc > 0) { invoice.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIsc, }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIsc }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "2000", Name = "ISC", TaxTypeCode = "EXC" } } } }); } if (documento.TotalOtrosTributos > 0) { invoice.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalOtrosTributos, }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalOtrosTributos }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "9999", Name = "OTROS", TaxTypeCode = "OTH" } } } }); } /* Numero de Placa del Vehiculo - Gastos art.37° Renta */ if (!string.IsNullOrEmpty(documento.PlacaVehiculo)) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.SunatCosts.RoadTransport .LicensePlateId = documento.PlacaVehiculo; } /* Tipo de Operación - Catalogo N° 17 */ if (!string.IsNullOrEmpty(documento.TipoOperacion) && documento.DatosGuiaTransportista == null) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.SunatTransaction.Id = documento.TipoOperacion; // Si es Emisor Itinerante. if (documento.TipoOperacion == "05") { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalProperties.Add(new AdditionalProperty { Id = "3000", // En el catalogo aparece como 2005 pero es 3000 Value = "Venta realizada por emisor itinerante" }); } } foreach (var relacionado in documento.Relacionados) { invoice.DespatchDocumentReferences.Add(new InvoiceDocumentReference { DocumentTypeCode = relacionado.TipoDocumento, Id = relacionado.NroDocumento }); } foreach (var relacionado in documento.OtrosDocumentosRelacionados) { invoice.AdditionalDocumentReferences.Add(new InvoiceDocumentReference { DocumentTypeCode = relacionado.TipoDocumento, Id = relacionado.NroDocumento }); } if (documento.Gratuitas > 0) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalProperties.Add(new AdditionalProperty { Id = "1002", Value = "Articulos gratuitos" }); } var dctosPorItem = documento.Items.Sum(d => d.Descuento); if (documento.DescuentoGlobal > 0 || dctosPorItem > 0) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalMonetaryTotals.Add(new AdditionalMonetaryTotal { Id = "2005", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal + dctosPorItem } }); } if (documento.MontoPercepcion > 0) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalMonetaryTotals.Add(new AdditionalMonetaryTotal { Id = "2001", ReferenceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalVenta }, PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.MontoPercepcion }, TotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalVenta + documento.MontoPercepcion } }); } if (documento.MontoAnticipo > 0) { invoice.PrepaidPayment = new BillingPayment { Id = new PartyIdentificationId { SchemeId = documento.TipoDocAnticipo, Value = documento.DocAnticipo }, PaidAmount = new PayableAmount { CurrencyId = documento.MonedaAnticipo, Value = documento.MontoAnticipo }, InstructionId = documento.Emisor.NroDocumento }; invoice.LegalMonetaryTotal.PrepaidAmount = new PayableAmount { CurrencyId = documento.MonedaAnticipo, Value = documento.MontoAnticipo }; } // Datos Adicionales a la Factura. foreach (var adicional in documento.DatoAdicionales) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalProperties.Add(new AdditionalProperty { Id = adicional.Codigo, Value = adicional.Contenido }); } if (documento.MontoDetraccion > 0) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalMonetaryTotals.Add(new AdditionalMonetaryTotal { Id = "2003", PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.MontoDetraccion }, Percent = documento.CalculoDetraccion * 100 }); } // Para datos de Guia de Remision Transportista. if (!string.IsNullOrEmpty(documento.DatosGuiaTransportista?.RucTransportista)) { invoice.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.SunatEmbededDespatchAdvice = new SunatEmbededDespatchAdvice { DeliveryAddress = new PostalAddress { Id = documento.DatosGuiaTransportista.DireccionDestino.Ubigeo, StreetName = documento.DatosGuiaTransportista.DireccionDestino.Direccion, CitySubdivisionName = documento.DatosGuiaTransportista.DireccionDestino.Urbanizacion, CityName = documento.DatosGuiaTransportista.DireccionDestino.Departamento, CountrySubentity = documento.DatosGuiaTransportista.DireccionDestino.Provincia, District = documento.DatosGuiaTransportista.DireccionDestino.Distrito, Country = new Country { IdentificationCode = "PE" } }, OriginAddress = new PostalAddress { Id = documento.DatosGuiaTransportista.DireccionOrigen.Ubigeo, StreetName = documento.DatosGuiaTransportista.DireccionOrigen.Direccion, CitySubdivisionName = documento.DatosGuiaTransportista.DireccionOrigen.Urbanizacion, CityName = documento.DatosGuiaTransportista.DireccionOrigen.Departamento, CountrySubentity = documento.DatosGuiaTransportista.DireccionOrigen.Provincia, District = documento.DatosGuiaTransportista.DireccionOrigen.Distrito, Country = new Country { IdentificationCode = "PE" } }, SunatCarrierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.DatosGuiaTransportista.RucTransportista, AdditionalAccountId = "06", Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.DatosGuiaTransportista.NombreTransportista } } }, DriverParty = new AgentParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.DatosGuiaTransportista.NroLicenciaConducir } } }, SunatRoadTransport = new SunatRoadTransport { LicensePlateId = documento.DatosGuiaTransportista.PlacaVehiculo, TransportAuthorizationCode = documento.DatosGuiaTransportista.CodigoAutorizacion, BrandName = documento.DatosGuiaTransportista.MarcaVehiculo }, TransportModeCode = documento.DatosGuiaTransportista.ModoTransporte, GrossWeightMeasure = new InvoicedQuantity { UnitCode = documento.DatosGuiaTransportista.UnidadMedida, Value = documento.DatosGuiaTransportista.PesoBruto } }; } foreach (var detalleDocumento in documento.Items) { var linea = new InvoiceLine { Id = detalleDocumento.Id, InvoicedQuantity = new InvoicedQuantity { UnitCode = detalleDocumento.UnidadMedida, Value = detalleDocumento.Cantidad }, LineExtensionAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, PricingReference = new PricingReference { AlternativeConditionPrices = new List <AlternativeConditionPrice>() }, Item = new Item { Description = detalleDocumento.Descripcion, SellersItemIdentification = new SellersItemIdentification { Id = detalleDocumento.CodigoItem }, AdditionalItemIdentification = new AdditionalItemIdentification { Id = detalleDocumento.PlacaVehiculo } }, Price = new Price { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.PrecioUnitario } }, }; /* 16 - Afectación al IGV por ítem */ linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } }); /* 17 - Sistema de ISC por ítem */ if (detalleDocumento.ImpuestoSelectivo > 0) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.ImpuestoSelectivo }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.ImpuestoSelectivo }, TaxCategory = new TaxCategory { TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TierRange = "01", TaxScheme = new TaxScheme() { Id = "2000", Name = "ISC", TaxTypeCode = "EXC" } } } }); } linea.PricingReference.AlternativeConditionPrices.Add(new AlternativeConditionPrice { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, // Comprobamos que sea una operacion gratuita. Value = documento.Gratuitas > 0 ? 0 : detalleDocumento.PrecioReferencial }, PriceTypeCode = detalleDocumento.TipoPrecio }); // Para operaciones no onerosas (gratuitas) if (documento.Gratuitas > 0) { linea.PricingReference.AlternativeConditionPrices.Add(new AlternativeConditionPrice { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.PrecioReferencial }, PriceTypeCode = "02" }); } // linea.AditionalItemIdentification.Id = documento.PlacaVehiculo; /* 51 - Descuentos por ítem */ if (detalleDocumento.Descuento > 0) { linea.AllowanceCharge.ChargeIndicator = false; linea.AllowanceCharge.Amount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Descuento }; } invoice.InvoiceLines.Add(linea); } return(invoice); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (ResumenDiarioNuevo)request; var summary = new SummaryDocuments { Id = documento.IdDocumento, IssueDate = Convert.ToDateTime(documento.FechaEmision), ReferenceDate = Convert.ToDateTime(documento.FechaReferencia), CustomizationId = "1.1", UblVersionId = "2.0", Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } } }; foreach (var grupo in documento.Resumenes) { var linea = new VoidedDocumentsLine { LineId = grupo.Id, DocumentTypeCode = grupo.TipoDocumento, Id = grupo.IdDocumento, AccountingCustomerParty = new AccountingSupplierParty { AdditionalAccountId = grupo.TipoDocumentoReceptor, CustomerAssignedAccountId = grupo.NroDocumentoReceptor }, BillingReference = new BillingReference { InvoiceDocumentReference = new InvoiceDocumentReference { Id = grupo.DocumentoRelacionado, DocumentTypeCode = grupo.TipoDocumentoRelacionado } }, ConditionCode = grupo.CodigoEstadoItem, TotalAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalVenta }, BillingPayments = new List <BillingPayment>() { new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Gravadas }, InstructionId = "01" } } , AllowanceCharge = new AllowanceCharge { ChargeIndicator = true, Amount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalDescuentos } } }; if (grupo.Exoneradas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Exoneradas }, InstructionId = "02" }); } if (grupo.Inafectas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Inafectas }, InstructionId = "03" }); } if (grupo.Exportacion > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Exportacion }, InstructionId = "04" }); } if (grupo.Gratuitas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Gratuitas }, InstructionId = "05" }); } if (grupo.TotalIsc > 0) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIsc }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIsc }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "2000", Name = "ISC", TaxTypeCode = "EXC" } } } }); } if (grupo.TotalIgv > 0) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIgv }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIgv }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } }); } if (grupo.TotalOtrosImpuestos > 0) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalOtrosImpuestos }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalOtrosImpuestos }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "9999", Name = "OTROS", TaxTypeCode = "OTH" } } } }); } summary.SummaryDocumentsLines.Add(linea); } return(summary); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (DocumentoElectronico)request; documento.MontoEnLetras = Conversion.Enletras(documento.TotalVenta); var creditNote = new CreditNote { UblExtensions = new UblExtensions { Extension2 = new UblExtension { ExtensionContent = new ExtensionContent { AdditionalInformation = new AdditionalInformation { AdditionalMonetaryTotals = new List <AdditionalMonetaryTotal>() { new AdditionalMonetaryTotal() { Id = "1001", PayableAmount = new PayableAmount() { CurrencyId = documento.Moneda, Value = documento.Gravadas } }, new AdditionalMonetaryTotal { Percent = (documento.CalculoIgv * 100) } }, AdditionalProperties = new List <AdditionalProperty>() { new AdditionalProperty { Id = "1000", Value = documento.MontoEnLetras } } } } } }, Id = documento.IdDocumento, IssueDate = DateTime.Parse(documento.FechaEmision), DocumentCurrencyCode = documento.Moneda, Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, Party = new Party { PartyName = new PartyName { Name = documento.Emisor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Emisor.Ubigeo, StreetName = documento.Emisor.Direccion, CitySubdivisionName = documento.Emisor.Urbanizacion, CountrySubentity = documento.Emisor.Departamento, CityName = documento.Emisor.Provincia, District = documento.Emisor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } }, AccountingCustomerParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Receptor.NroDocumento, AdditionalAccountId = documento.Receptor.TipoDocumento, Party = new Party { PartyName = new PartyName { Name = documento.Receptor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Receptor.Ubigeo, StreetName = documento.Receptor.Direccion, CitySubdivisionName = documento.Receptor.Urbanizacion, CountrySubentity = documento.Receptor.Departamento, CityName = documento.Receptor.Provincia, District = documento.Receptor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Receptor.NombreLegal } } }, UblVersionId = "2.1", CustomizationId = "2.0", LegalMonetaryTotal = new LegalMonetaryTotal { PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalVenta }, AllowanceTotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal } }, TaxTotals = new List <TaxTotal> { new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Gravadas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIgv }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.TotalIgv, }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } } } }; foreach (var discrepancia in documento.Discrepancias) { creditNote.DiscrepancyResponses.Add(new DiscrepancyResponse { ReferenceId = discrepancia.NroReferencia, ResponseCode = discrepancia.Tipo, Description = discrepancia.Descripcion }); } foreach (var relacionado in documento.Relacionados) { creditNote.BillingReferences.Add(new BillingReference { InvoiceDocumentReference = new InvoiceDocumentReference { Id = relacionado.NroDocumento, DocumentTypeCode = relacionado.TipoDocumento } }); } foreach (var relacionado in documento.OtrosDocumentosRelacionados) { creditNote.AdditionalDocumentReferences.Add(new InvoiceDocumentReference { DocumentTypeCode = relacionado.TipoDocumento, Id = relacionado.NroDocumento }); } foreach (var detalleDocumento in documento.Items) { var linea = new InvoiceLine { Id = detalleDocumento.Id, ItemClassificationCode = detalleDocumento.ItemClassificationCode, CreditedQuantity = new InvoicedQuantity { UnitCode = detalleDocumento.UnidadMedida, Value = detalleDocumento.Cantidad }, LineExtensionAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, PricingReference = new PricingReference { AlternativeConditionPrices = new List <AlternativeConditionPrice>(), }, Item = new Item { Description = detalleDocumento.Descripcion, SellersItemIdentification = new SellersItemIdentification { Id = detalleDocumento.CodigoItem } }, Price = new Price { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.PrecioUnitario } }, }; linea.PricingReference.AlternativeConditionPrices.Add(new AlternativeConditionPrice { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, // Comprobamos que sea una operacion gratuita. Value = documento.Gratuitas > 0 ? 0 : detalleDocumento.PrecioReferencial }, PriceTypeCode = detalleDocumento.TipoPrecio }); /* 16 - Afectación al IGV por ítem */ linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } }); creditNote.CreditNoteLines.Add(linea); } return(creditNote); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (DocumentoElectronico)request; var debitNote = new DebitNote { UblVersionId = "2.1", CustomizationId = new CustomizationID() { Value = "2.0" }, IdInvoice = documento.SerieCorrelativo, // Serie y número del comprobante IssueDate = documento.FechaEmision, // Fecha de emisión yyyy-mm-dd IssueTime = documento.HoraEmision, // Hora de emisión hh-mm-ss.0z DiscrepancyResponses = new List <DiscrepancyResponse>(), InvoiceTypeCode = new InvoiceTypeCode() { Value = documento.TipoDocumento, ListID = documento.TipoOperacion }, // Código de tipo de documento DocumentCurrencyCode = new DocumentCurrencyCode() { Value = documento.Moneda }, // Código de tipo de moneda en la cual se emite la factura electrónica OrderReference = new OrderReference() { Id = documento.OrdenCompra ?? string.Empty }, Signature = new Signature { //Id = documento.SerieCorrelativo, Id = documento.Emisor.NroDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.SerieCorrelativo}" } } }, AccountingSupplierParty = new AccountingContributorParty() { // Emisor y Receptor son instancias de la clase Contribuyente, por lo que comparten los mismos atributos Party = new Party() { PartyName = new PartyName() { Name = documento.Emisor.NombreComercial }, // NombreTributo Comercial del emisor PartyIdentification = new PartyIdentification() { // RUC Id = new PartyIdentificationId() { Value = documento.Emisor.NroDocumento, SchemeId = documento.Emisor.TipoDocumento } }, PartyLegalEntity = new PartyLegalEntity() { RegistrationName = documento.Emisor.NombreLegal, // Apellidos y nombres, denominación o razón social RegistrationAddress = new RegistrationAddress() { AddressLine = new AddressLine() { Line = documento.Emisor.Direccion }, CitySubdivisionName = documento.Emisor.Urbanizacion, CityName = documento.Emisor.Provincia, IdUbigeo = new IdUbigeo() { Value = documento.Emisor.Ubigeo }, CountrySubentity = documento.Emisor.Departamento, District = documento.Emisor.Distrito, Country = new Country() { IdentificationCode = new IdentificationCode() { Value = documento.Emisor.Pais } }, AddressTypeCode = new AddressTypeCode() { Value = "0000" } // Por defecto 0000, no se asigna otro valor debido a que no se tiene suficientes especificaciones }, ShareholderParties = new List <ShareholderParty>() // Se implementa líneas mas abajo }, #region PartyTaxScheme PartyTaxScheme = new PartyTaxScheme() { RegistrationName = documento.Emisor.NombreLegal, // NombreTributo o razón social del emisor CompanyID = new CompanyID() { SchemeID = documento.Emisor.TipoDocumento, Value = documento.Emisor.NroDocumento }, // Número de RUC del emisor RegistrationAddress = new RegistrationAddress() { AddressTypeCode = new AddressTypeCode() { Value = "0000" /*documento.Emisor.Ubigeo.ToString()*/ // Cambiar esto !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } } } #endregion PartyTaxScheme }, }, AccountingCustomerParty = new AccountingContributorParty() // AccountingSupplierParty y AccountingCustomerParty son instancias { // de la clase AccountingContributorParty, por lo que comparten los mismos atributos Party = new Party() { PartyName = new PartyName() { Name = documento.Receptor.NombreComercial ?? string.Empty }, // NombreTributo Comercial del Receptor PartyIdentification = new PartyIdentification() { // Número de documento Id = new PartyIdentificationId() { Value = documento.Receptor.NroDocumento, SchemeId = documento.Receptor.TipoDocumento } }, PartyLegalEntity = new PartyLegalEntity() { RegistrationName = documento.Receptor.NombreComercial, RegistrationAddress = new RegistrationAddress() { AddressLine = new AddressLine() { Line = documento.Receptor.Direccion }, CitySubdivisionName = documento.Receptor.Urbanizacion, CityName = documento.Receptor.Provincia, IdUbigeo = new IdUbigeo() { Value = documento.Receptor.Ubigeo }, CountrySubentity = documento.Receptor.Departamento, District = documento.Receptor.Distrito, Country = new Country() { IdentificationCode = new IdentificationCode() { Value = documento.Receptor.Pais } }, AddressTypeCode = new AddressTypeCode() { } // Investigar mas sobre este valor, por ahora no irá } }, #region PartyTaxScheme PartyTaxScheme = new PartyTaxScheme() // Tambien se excluyó, decreto de SUNAT 30/06/2018 { // Número de RUC del Receptor CompanyID = new CompanyID() { SchemeID = documento.Receptor.TipoDocumento, Value = documento.Receptor.NroDocumento } }, #endregion PartyTaxScheme }, }, BillingReferences = new List <BillingReference>(), TaxTotals = new List <TaxTotal>(), RequestedMonetaryTotal = new LegalMonetaryTotal() { LineExtensionAmount = new PayableAmount() { Value = documento.TotalValorVenta, CurrencyId = documento.Moneda }, TaxInclusiveAmount = new PayableAmount() { Value = documento.TotalPrecioVenta, CurrencyId = documento.Moneda }, AllowanceTotalAmount = new PayableAmount() { Value = documento.TotalDescuento, CurrencyId = documento.Moneda }, ChargeTotalAmount = new PayableAmount() { Value = documento.TotalOtrosCargos, CurrencyId = documento.Moneda }, PrepaidAmount = new PayableAmount() { Value = documento.TotalAnticipos, CurrencyId = documento.Moneda }, PayableAmount = new PayableAmount() { Value = documento.ImporteTotalVenta, CurrencyId = documento.Moneda }, PayableRoundingAmount = new PayableAmount() { Value = documento.MontoRedondeo, CurrencyId = documento.Moneda }, } }; foreach (var discrepancia in documento.Discrepancias) { debitNote.DiscrepancyResponses.Add(new DiscrepancyResponse { ResponseCode = new ResponseCode() { Value = discrepancia.Tipo, ListName = "Tipo de nota de debito" }, Description = discrepancia.Descripcion }); } foreach (var relacionado in documento.Relacionados) { debitNote.BillingReferences.Add(new BillingReference { InvoiceDocumentReference = new InvoiceDocumentReference { Id = relacionado.NroDocumento, DocumentTypeCode = new DocumentTypeCode() { Value = relacionado.TipoDocumento ?? string.Empty, ListName = "Tipo de Documento" } } }); } //foreach (var relacionado in documento.OtrosDocumentosRelacionados) //{ // creditNote.AdditionalDocumentReferences.Add(new InvoiceDocumentReference // { // Id = relacionado.NroDocumento, // DocumentTypeCode = new DocumentTypeCode() { Value = relacionado.TipoDocumento ?? string.Empty, ListName = "Documento Relacionado" } // }); //} // TaxTotal o TotalImpuestos foreach (var totalImpuesto in documento.TotalImpuestos) { var lineaTotalImpuestos = new TaxTotal { // Monto total de impuestos TaxAmount = new PayableAmount() { CurrencyId = totalImpuesto.TipoMonedaTotal, Value = totalImpuesto.MontoTotal } }; foreach (var subTotalImpuestos in totalImpuesto.SubTotalesImpuestos) { lineaTotalImpuestos.TaxSubtotals.Add(new TaxSubtotal { TaxableAmount = new PayableAmount { // Monto base CurrencyId = subTotalImpuestos.TipoMonedaBase, // Código de tipo de moneda del monto de las operaciones gravadas/exoneradas/inafectas del impuesto Value = subTotalImpuestos.BaseImponible // Monto las operaciones gravadas/exoneradas/inafectas del impuesto }, TaxAmount = new PayableAmount { CurrencyId = subTotalImpuestos.TipoMonedaTotal, // Código de tipo de moneda del monto total del impuesto Value = subTotalImpuestos.MontoTotal // Monto total del impuesto }, TaxCategory = new TaxCategory { TaxCategoryId = new TaxCategoryId { Value = subTotalImpuestos.CategoriaImpuestos }, // Categoría de impuestos TaxScheme = new TaxScheme { TaxSchemeId = new TaxSchemeId { Value = subTotalImpuestos.CodigoTributo }, // Código de tributo Name = subTotalImpuestos.NombreTributo, // NombreTributo de tributo TaxTypeCode = subTotalImpuestos.CodigoInternacional // Código internacional tributo } } }); } debitNote.TaxTotals.Add(lineaTotalImpuestos); } foreach (var detalleDocumento in documento.DetalleDocumentos) { var linea = new DocumentLine { IdDocumentLine = detalleDocumento.NumeroOrden, DebitedQuantity = new InvoicedQuantity() { UnitCode = detalleDocumento.UnidadMedida, Value = detalleDocumento.Cantidad }, LineExtensionAmount = new PayableAmount() { CurrencyId = detalleDocumento.Moneda, Value = detalleDocumento.TotalVenta }, // Valor de venta por ítem PricingReference = new PricingReference() { AlternativeConditionPrices = new List <AlternativeConditionPrice>() }, Item = new Item() { Descriptions = new List <Description>(), // Se implementa líneas abajo SellersItemIdentification = new SellersItemIdentification() { Id = detalleDocumento.CodigoItem }, // Código de producto CommodityClassification = new CommodityClassification() // No hay una tabla con este listado, debido a inestabilidad de Sunat y por ser demasiado extenso { // Codigo producto de SUNAT | (Catálogo No. 25) | Es excluyente cuando el tipo de operación esta entre 0200 a 0208 ItemClassificationCode = new ItemClassificationCode() { Value = detalleDocumento.CodigoProductoSunat ?? string.Empty } }, // Si tipo de operación es 0112, no debe haber productos con código de Sunat igual a 84121901 o 80131501 // StandardItemIdentification = new StandardItemIdentification() { } Codigo de barras, no se agregará a pedido de Tania AdditionalItemProperties = new List <AdditionalItemProperty>() // Implementado en la región AdditionalItemProperty }, Price = new Price() { PriceAmount = new PayableAmount() { CurrencyId = detalleDocumento.Moneda, Value = detalleDocumento.ValorVenta } }, // Valor unitario por ítem }; #region TaxTotal if (detalleDocumento.TotalImpuestos.Count > 0) { // Monto total de impuestos del ítem foreach (var totalImpuesto in detalleDocumento.TotalImpuestos) { // Total de impuestos para cada ítem var lineaTotalImpuestos = new TaxTotal { // Monto total de impuestos por línea TaxAmount = new PayableAmount() { CurrencyId = totalImpuesto.TipoMonedaTotal, Value = totalImpuesto.MontoTotal } }; foreach (var subTotalImpuestos in totalImpuesto.SubTotalesImpuestos) { // Afectación al IGV por la línea | Afectación IVAP por la línea lineaTotalImpuestos.TaxSubtotals.Add(new TaxSubtotal { TaxableAmount = new PayableAmount { // Monto base CurrencyId = subTotalImpuestos.TipoMonedaBase, // Código de tipo de moneda del monto de las operaciones gravadas/exoneradas/inafectas del impuesto Value = subTotalImpuestos.BaseImponible // Monto las operaciones gravadas/exoneradas/inafectas del impuesto }, TaxAmount = new PayableAmount { // Monto de IGV/IVAP de la línea | Monto total de impuestos por linea CurrencyId = subTotalImpuestos.TipoMonedaTotal, // Código de tipo de moneda del monto total del impuesto Value = subTotalImpuestos.MontoTotal // Monto total del impuesto }, TaxCategory = new TaxCategory { // Tasa del IGV o Tasa del IVAP TaxCategoryId = new TaxCategoryId { Value = subTotalImpuestos.CategoriaImpuestos }, // Categoría de impuestos Percent = subTotalImpuestos.PorcentajeImp, // Tasa del IGV o Tasa del IVAP | Tasa del tributo TaxExemptionReasonCode = new TaxExemptionReasonCode() { Value = subTotalImpuestos.TipoAfectacion }, // Afectación al IGV o IVAP cuando corresponda TierRange = subTotalImpuestos.TipoSistemaISC, TaxScheme = new TaxScheme { TaxSchemeId = new TaxSchemeId { Value = subTotalImpuestos.CodigoTributo }, // Código de tributo por línea | Catálogo No. 05 Name = subTotalImpuestos.NombreTributo, // NombreTributo de tributo TaxTypeCode = subTotalImpuestos.CodigoInternacional // Código internacional tributo } } }); } linea.TaxTotals.Add(lineaTotalImpuestos); // Realizar debug } } #endregion TaxTotal #region Description foreach (var descripcion in detalleDocumento.Descripciones) { // Descripción detallada del servicio prestado, bien vendido o cedido en uso, indicando las características. linea.Item.Descriptions.Add(new Description() { Detail = descripcion.Detalle ?? string.Empty }); } #endregion Description #region AdditionalItemProperty if (detalleDocumento.PropiedadesAdicionales.Count > 0) // validar { foreach (var propiedadAdicional in detalleDocumento.PropiedadesAdicionales) { linea.Item.AdditionalItemProperties.Add(new AdditionalItemProperty() { Name = propiedadAdicional.Nombre, // Sí existe el Tag no debe estar vacío | Catálogo No. 55 NameCode = new NameCode() { Value = propiedadAdicional.Codigo }, Value = propiedadAdicional.ValorPropiedad, // Se le puede poner distintos valores o hubo confusión de Sunat.. // En la documentación vista el 30/06/2018 se observó que el campo ValueQualifier fue removido o no fue considerado en la documentación, ValueQualifier = new ValueQualifier() { Detail = propiedadAdicional.Concepto ?? string.Empty }, UsabilityPeriod = new UsabilityPeriod() { StartDate = propiedadAdicional.FechaInicio, EndDate = propiedadAdicional.FechaFin, DurationMeasure = new DurationMeasure() { Value = propiedadAdicional.Duracion } }, ValueQuantity = new ValueQuantity() { Value = propiedadAdicional.CantidadEspecies }, }); } } #endregion AdditionalItemProperty #region AlternativeConditionPrice foreach (var precioAlternativo in detalleDocumento.PreciosAlternativos) { linea.PricingReference.AlternativeConditionPrices.Add(new AlternativeConditionPrice() { PriceAmount = new PayableAmount() { CurrencyId = precioAlternativo.TipoMoneda, Value = precioAlternativo.Monto }, PriceTypeCode = new PriceTypeCode() { Value = precioAlternativo.TipoPrecio } // Código de precio | Catálogo No. 16 }); } #endregion AlternativeConditionPrice debitNote.DebitNoteLines.Add(linea); } return(debitNote); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (GuiaRemision)request; var despatchAdvice = new DespatchAdvice { Id = documento.IdDocumento, IssueDate = Convert.ToDateTime(documento.FechaEmision), DespatchAdviceTypeCode = documento.TipoDocumento, Note = documento.Glosa, Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Remitente.NroDocumento } }, PartyName = new PartyName { Name = documento.Remitente.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Remitente.NroDocumento}-{documento.IdDocumento}" } } }, DespatchSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Remitente.NroDocumento, AdditionalAccountId = documento.Remitente.TipoDocumento, Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Remitente.NombreLegal } } }, DeliveryCustomerParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Destinatario.NroDocumento, AdditionalAccountId = documento.Destinatario.TipoDocumento, Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Destinatario.NombreLegal } } }, }; if (!string.IsNullOrEmpty(documento.Tercero?.NroDocumento)) { despatchAdvice.SellerSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Tercero.NroDocumento, AdditionalAccountId = documento.Tercero.TipoDocumento, Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Tercero.NombreLegal } } }; } if (documento.DocumentoRelacionado != null) { despatchAdvice.AdditionalDocumentReference = new InvoiceDocumentReference { Id = documento.DocumentoRelacionado.NroDocumento, DocumentTypeCode = documento.DocumentoRelacionado.TipoDocumento }; } if (documento.GuiaBaja != null) { despatchAdvice.OrderReference = new OrderReference { Id = documento.GuiaBaja.NroDocumento, OrderTypeCode = new OrderTypeCode { Name = "Guia de Remision", Value = documento.GuiaBaja.TipoDocumento } }; } despatchAdvice.Shipment = new Shipment { Id = documento.ShipmentId, HandlingCode = documento.CodigoMotivoTraslado, Information = documento.DescripcionMotivo, SplitConsignmentIndicator = documento.Transbordo, GrossWeightMeasure = new InvoicedQuantity { UnitCode = "KGM", Value = documento.PesoBrutoTotal }, TotalTransportHandlingUnitQuantity = documento.NroPallets, ShipmentStages = new List <ShipmentStage> { new ShipmentStage { Id = 1, TransportModeCode = documento.ModalidadTraslado, TransitPeriodStartPeriod = Convert.ToDateTime(documento.FechaInicioTraslado), CarrierParty = new CarrierParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { SchemeId = "6", Value = documento.RucTransportista } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.RazonSocialTransportista } }, DriverPerson = new PartyIdentification { Id = new PartyIdentificationId { SchemeId = "1", Value = documento.NroDocumentoConductor } }, TransportMeans = new SunatRoadTransport { LicensePlateId = documento.NroPlacaVehiculo } } }, DeliveryAddress = new PostalAddress { Id = documento.DireccionLlegada.Ubigeo, StreetName = documento.DireccionLlegada.DireccionCompleta }, OriginAddress = new PostalAddress { Id = documento.DireccionPartida.Ubigeo, StreetName = documento.DireccionPartida.DireccionCompleta }, TransportHandlingUnit = new TransportHandlingUnit { Id = documento.NroPlacaVehiculo, TransportEquipments = new List <TransportEquipment> { new TransportEquipment { Id = documento.NumeroContenedor } } }, FirstArrivalPortLocationId = documento.CodigoPuerto }; foreach (var detalleGuia in documento.BienesATransportar) { despatchAdvice.DespatchLines.Add(new DespatchLine { Id = detalleGuia.Correlativo, DeliveredQuantity = new InvoicedQuantity { UnitCode = detalleGuia.UnidadMedida, Value = detalleGuia.Cantidad }, Item = new DespatchLineItem { Description = detalleGuia.Descripcion, SellersIdentificationId = detalleGuia.CodigoItem }, OrderLineReferenceId = detalleGuia.LineaReferencia }); } return(despatchAdvice); }
public IEstructuraXml Generar(IDocumentoElectronico request) { throw new NotImplementedException(); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (ResumenDiario)request; var summary = new SummaryDocuments { Id = documento.IdDocumento, IssueDate = Convert.ToDateTime(documento.FechaEmision), ReferenceDate = Convert.ToDateTime(documento.FechaReferencia), CustomizationId = "1.0", UblVersionId = "2.0", Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } } }; foreach (var grupo in documento.Resumenes) { var linea = new VoidedDocumentsLine { LineId = grupo.Id, DocumentTypeCode = grupo.TipoDocumento, DocumentSerialId = grupo.Serie, StartDocumentNumberId = grupo.CorrelativoInicio, EndDocumentNumberId = grupo.CorrelativoFin, TotalAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalVenta }, //jcf Sólo agregar este nodo si el monto > 0 //BillingPayments = new List<BillingPayment>() //{ // new BillingPayment // { // PaidAmount = new PayableAmount // { // CurrencyId = grupo.Moneda, // Value = grupo.Gravadas // }, // InstructionId = "01" // }, // new BillingPayment // { // PaidAmount = new PayableAmount // { // CurrencyId = grupo.Moneda, // Value = grupo.Exoneradas // }, // InstructionId = "02" // }, // new BillingPayment // { // PaidAmount = new PayableAmount // { // CurrencyId = grupo.Moneda, // Value = grupo.Inafectas // }, // InstructionId = "03" // }, //}, //AllowanceCharge = new AllowanceCharge //{ // ChargeIndicator = true, // Amount = new PayableAmount // { // CurrencyId = grupo.Moneda, // Value = grupo.TotalDescuentos // } //}, TaxTotals = new List <TaxTotal>() { new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIsc }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIsc }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "2000", Name = "ISC", TaxTypeCode = "EXC" } } } }, new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIgv }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalIgv }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } }, new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalOtrosImpuestos }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalOtrosImpuestos }, TaxCategory = new TaxCategory { TaxScheme = new TaxScheme { Id = "9999", Name = "OTROS", TaxTypeCode = "OTH" } } } }, } }; //jcf Sólo agregar este nodo si el monto > 0 if (grupo.Gravadas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Gravadas }, InstructionId = "01" }); } if (grupo.Exoneradas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Exoneradas }, InstructionId = "02" }); } if (grupo.Inafectas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Inafectas }, InstructionId = "03" }); } if (grupo.TotalDescuentos > 0) { linea.AllowanceCharge = new AllowanceCharge { ChargeIndicator = true, Amount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.TotalDescuentos } }; } //Fin modificación //////////////// if (grupo.Exportacion > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Exportacion }, InstructionId = "04" }); } if (grupo.Gratuitas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = grupo.Moneda, Value = grupo.Gratuitas }, InstructionId = "05" }); } summary.SummaryDocumentsLines.Add(linea); } return(summary); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (ComunicacionBaja)request; var voidedDocument = new VoidedDocuments { Id = documento.IdDocumento, IdInvoice = documento.IdDocumento, IssueDate = Convert.ToDateTime(documento.FechaEmision), ReferenceDate = Convert.ToDateTime(documento.FechaReferencia), CustomizationId = "1.0", UblVersionId = "2.0", Signature = new Signature { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingContributorParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } } }; foreach (var baja in documento.Bajas) { voidedDocument.VoidedDocumentsLines.Add(new VoidedDocumentsLine { LineId = baja.Id, DocumentTypeCode = baja.TipoDocumento, DocumentSerialID = baja.Serie, DocumentNumberID = baja.Correlativo, VoidReasonDescription = baja.MotivoBaja }); } return(voidedDocument); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (DocumentoElectronico)request; documento.MontoEnLetras = Conversion.Enletras(documento.TotalVenta); var creditNote = new CreditNote { UblExtensions = new UblExtensions { Extension2 = new UblExtension { ExtensionContent = new ExtensionContent { AdditionalInformation = new AdditionalInformation { AdditionalMonetaryTotals = new List <AdditionalMonetaryTotal>() { new AdditionalMonetaryTotal() { Id = "1001", PayableAmount = new PayableAmount() { CurrencyId = documento.Moneda, Value = documento.Gravadas } }, new AdditionalMonetaryTotal { Percent = (documento.CalculoIgv * 100) } }, AdditionalProperties = new List <AdditionalProperty>() { new AdditionalProperty { Id = "1000", Value = documento.MontoEnLetras } } } } } }, Id = documento.IdDocumento, IssueDate = DateTime.Parse(documento.FechaEmision), DocumentCurrencyCode = documento.Moneda, Signature = new SignatureCac { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, Party = new Party { PartyName = new PartyName { Name = documento.Emisor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Emisor.Ubigeo, StreetName = documento.Emisor.Direccion, CitySubdivisionName = documento.Emisor.Urbanizacion, CountrySubentity = documento.Emisor.Departamento, CityName = documento.Emisor.Provincia, District = documento.Emisor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } }, AccountingCustomerParty = new AccountingSupplierParty { CustomerAssignedAccountId = documento.Receptor.NroDocumento, AdditionalAccountId = documento.Receptor.TipoDocumento, Party = new Party { PartyName = new PartyName { Name = documento.Receptor.NombreComercial }, PostalAddress = new PostalAddress { Id = documento.Receptor.Ubigeo, StreetName = documento.Receptor.Direccion, CitySubdivisionName = documento.Receptor.Urbanizacion, CountrySubentity = documento.Receptor.Departamento, CityName = documento.Receptor.Provincia, District = documento.Receptor.Distrito, Country = new Country { IdentificationCode = "PE" } }, PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Receptor.NombreLegal } } }, UblVersionId = "2.1", CustomizationId = "2.0", LegalMonetaryTotal = new LegalMonetaryTotal { PayableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Items.Where(d => d.TipoImpuesto.Contains("21")).Any() ? (documento.TotalVenta + documento.Gratuitas) : documento.TotalVenta//Verifica si un item tiene el tipo de impuesto 21, válido para la NC con productos gratuitos }, AllowanceTotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal } }, Cargos = new LegalMonetaryTotal { AllowanceTotalAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Cargos, MultiplierFactorNumeric = documento.MultiplierFactorNumeric }, }, TaxTotals = new List <TaxTotal>() }; /*GRAVADAS*/ if (documento.Gravadas > 0) { creditNote.TaxTotals.Add(new TaxTotal { //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Gravadas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal > 0 ? ((documento.Gravadas - documento.DescuentoGlobal) * documento.CalculoIgv) : documento.TotalIgv }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.DescuentoGlobal > 0 ? ((documento.Gravadas - documento.DescuentoGlobal) * documento.CalculoIgv) : documento.TotalIgv, }, TaxCategory = new TaxCategory { Identifier = "S", //VALOR OBTENIDO DE LA TABLA 5 TaxScheme = new TaxScheme { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } }, BaseAmount = new PayableAmount { Value = documento.Gravadas }, LineExtensionAmount = new PayableAmount { Value = documento.Gravadas } }); } /*EXONERADAS*/ if (documento.Exoneradas > 0) { creditNote.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Exoneradas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "E", TaxScheme = new TaxScheme { Id = "9997", Name = "EXO", TaxTypeCode = "VAT" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Exoneradas } }); } /*INAFECTAS*/ if (documento.Inafectas > 0) { if (documento.TipoOperacion == "0200") {//EXPORTACION creditNote.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Inafectas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "G", TaxScheme = new TaxScheme { Id = "9995", Name = "EXP", TaxTypeCode = "FRE" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Inafectas } }); } else { creditNote.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = documento.Inafectas }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "O", TaxScheme = new TaxScheme { Id = "9998", Name = "INA", TaxTypeCode = "FRE" } } } }); } } /*GRATUITAS*/ if (documento.Gratuitas > 0 || documento.Items.Where(a => a.TipoImpuesto.ToString() == "21").Any()) { creditNote.TaxTotals.Add(new TaxTotal { TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = Convert.ToDecimal(documento.Items.Where(y => y.TipoImpuesto == "21").Select(a => a.PrecioReferencial).Sum()) }, TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = 0.00m, }, TaxCategory = new TaxCategory { Identifier = "Z", TaxScheme = new TaxScheme { Id = "9996", Name = "GRA", TaxTypeCode = "FRE" } } }, LineExtensionAmount = new PayableAmount { Value = documento.Gratuitas > 0 ? 0 : documento.Gratuitas } }); creditNote.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.AdditionalProperties.Add(new AdditionalProperty { Id = "1002", Value = "TRANSFERENCIA GRATUITA DE UN BIEN Y/O SERVICIO PRESTADO GRATUITAMENTE" }); } creditNote.UblExtensions.Extension2.ExtensionContent .AdditionalInformation.SunatTransaction.Id = documento.TipoOperacion; foreach (var discrepancia in documento.Discrepancias) { creditNote.DiscrepancyResponses.Add(new DiscrepancyResponse { ReferenceId = discrepancia.NroReferencia, ResponseCode = discrepancia.Tipo, Description = discrepancia.Descripcion }); } foreach (var relacionado in documento.Relacionados) { creditNote.BillingReferences.Add(new BillingReference { InvoiceDocumentReference = new InvoiceDocumentReference { Id = relacionado.NroDocumento, DocumentTypeCode = relacionado.TipoDocumento } }); } foreach (var relacionado in documento.OtrosDocumentosRelacionados) { creditNote.AdditionalDocumentReferences.Add(new InvoiceDocumentReference { DocumentTypeCode = relacionado.TipoDocumento, Id = relacionado.NroDocumento }); } foreach (var detalleDocumento in documento.Items) { var linea = new InvoiceLine { Id = detalleDocumento.Id, ItemClassificationCode = detalleDocumento.ItemClassificationCode, CreditedQuantity = new InvoicedQuantity { UnitCode = detalleDocumento.UnidadMedida, Value = detalleDocumento.Cantidad }, LineExtensionAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, PricingReference = new PricingReference { AlternativeConditionPrices = new List <AlternativeConditionPrice>(), }, Item = new Item { Description = detalleDocumento.Descripcion, SellersItemIdentification = new SellersItemIdentification { Id = detalleDocumento.CodigoItem } }, Price = new Price { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.PrecioUnitario } }, }; linea.PricingReference.AlternativeConditionPrices.Add(new AlternativeConditionPrice { PriceAmount = new PayableAmount { CurrencyId = documento.Moneda, // Comprobamos que sea una operacion gratuita. Value = /*documento.Gratuitas > 0 ? 0 :*/ detalleDocumento.PrecioReferencial }, PriceTypeCode = detalleDocumento.TipoPrecio }); /* 16 - Afectación al IGV por ítem */ if (documento.Gravadas > 0 && detalleDocumento.TipoImpuesto.StartsWith("1")) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, Identifier = "S", TaxScheme = new TaxScheme() { Id = "1000", Name = "IGV", TaxTypeCode = "VAT" } } } }); creditNote.CreditNoteLines.Add(linea); continue; } /* Exoneradas */ if (documento.Exoneradas > 0 && detalleDocumento.TipoImpuesto.Contains("20")) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "E", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9997", Name = "EXO", TaxTypeCode = "VAT" } } } }); creditNote.CreditNoteLines.Add(linea); continue; } /*INAFECTAS*/ if (documento.Inafectas > 0 && (detalleDocumento.TipoImpuesto.StartsWith("3") || detalleDocumento.TipoImpuesto.Contains("40"))) { if (documento.TipoOperacion == "0200") { //EXPORTACION linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "G", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9995", Name = "EXP", TaxTypeCode = "FRE" } } } }); } else { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.TotalVenta }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "O", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9998", Name = "INA", TaxTypeCode = "FRE" } } } }); } creditNote.CreditNoteLines.Add(linea); continue; } /*GRATUITAS*/ if (documento.Gratuitas > 0 || detalleDocumento.TipoImpuesto.Contains("21")) { linea.TaxTotals.Add(new TaxTotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, //Agregado para la nueva version TaxableAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = (detalleDocumento.PrecioReferencial * detalleDocumento.Cantidad) }, TaxSubtotal = new TaxSubtotal { TaxAmount = new PayableAmount { CurrencyId = documento.Moneda, Value = detalleDocumento.Impuesto }, TaxCategory = new TaxCategory { Identifier = "Z", TaxExemptionReasonCode = detalleDocumento.TipoImpuesto, TaxScheme = new TaxScheme() { Id = "9996", Name = "GRA", TaxTypeCode = "FRE" } } } }); creditNote.CreditNoteLines.Add(linea); continue; } } return(creditNote); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (DocumentoElectronico)request; documento.MontoEnLetras = Conversion.Enletras(documento.ImporteTotalVenta); var invoice = new Invoice { // Falta agregar EXTENSION UblVersionId = "2.1", CustomizationId = new CustomizationID() { Value = "2.0" }, IdInvoice = documento.SerieCorrelativo, // Serie y número del comprobante IssueDate = documento.FechaEmision, // Fecha de emisión yyyy-mm-dd IssueTime = documento.HoraEmision, // Hora de emisión hh-mm-ss.0z DueDate = documento.FechaVencimiento, // Fecha de vencimiento yyyy-mm-dd | Fecha de Pago InvoiceTypeCode = new InvoiceTypeCode() { Value = documento.TipoDocumento, ListID = documento.TipoOperacion }, // Código de tipo de documento // Note DocumentCurrencyCode = new DocumentCurrencyCode() { Value = documento.Moneda }, // Código de tipo de moneda en la cual se emite la factura electrónica LineCountNumeric = documento.CantidadItems, // InvoicePeriod OrderReference = new OrderReference() { Id = documento.OrdenCompra ?? string.Empty }, // DespatchDocumentReference // ContractDocumentReference --> Pertenece a Servicios públicos // AdditionalDocumentReference Signature = new Signature { //Id = documento.SerieCorrelativo, Id = documento.Emisor.NroDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.SerieCorrelativo}" } } }, AccountingSupplierParty = new AccountingContributorParty() { // Emisor y Receptor son instancias de la clase Contribuyente, por lo que comparten los mismos atributos Party = new Party() { PartyName = new PartyName() { Name = documento.Emisor.NombreComercial }, // NombreTributo Comercial del emisor PartyIdentification = new PartyIdentification() { // RUC Id = new PartyIdentificationId() { Value = documento.Emisor.NroDocumento, SchemeId = documento.Emisor.TipoDocumento } }, PartyLegalEntity = new PartyLegalEntity() { RegistrationName = documento.Emisor.NombreLegal, // Apellidos y nombres, denominación o razón social RegistrationAddress = new RegistrationAddress() { AddressLine = new AddressLine() { Line = documento.Emisor.Direccion }, CitySubdivisionName = documento.Emisor.Urbanizacion, CityName = documento.Emisor.Provincia, IdUbigeo = new IdUbigeo() { Value = documento.Emisor.Ubigeo }, CountrySubentity = documento.Emisor.Departamento, District = documento.Emisor.Distrito, Country = new Country() { IdentificationCode = new IdentificationCode() { Value = documento.Emisor.Pais } }, AddressTypeCode = new AddressTypeCode() { Value = "0000" } // Por defecto 0000, no se asigna otro valor debido a que no se tiene suficientes especificaciones }, ShareholderParties = new List <ShareholderParty>() // Se implementa líneas mas abajo }, #region PartyTaxScheme PartyTaxScheme = new PartyTaxScheme() { RegistrationName = documento.Emisor.NombreLegal, // NombreTributo o razón social del emisor CompanyID = new CompanyID() { SchemeID = documento.Emisor.TipoDocumento, Value = documento.Emisor.NroDocumento }, // Número de RUC del emisor RegistrationAddress = new RegistrationAddress() { AddressTypeCode = new AddressTypeCode() { Value = "0000" /*documento.Emisor.Ubigeo.ToString()*/ // Cambiar esto !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } } } #endregion PartyTaxScheme }, }, AccountingCustomerParty = new AccountingContributorParty() // AccountingSupplierParty y AccountingCustomerParty son instancias { // de la clase AccountingContributorParty, por lo que comparten los mismos atributos Party = new Party() { PartyName = new PartyName() { Name = documento.Receptor.NombreComercial ?? string.Empty }, // NombreTributo Comercial del Receptor PartyIdentification = new PartyIdentification() { // Número de documento Id = new PartyIdentificationId() { Value = documento.Receptor.NroDocumento, SchemeId = documento.Receptor.TipoDocumento } }, PartyLegalEntity = new PartyLegalEntity() { RegistrationName = documento.Receptor.NombreComercial, RegistrationAddress = new RegistrationAddress() { AddressLine = new AddressLine() { Line = documento.Receptor.Direccion }, CitySubdivisionName = documento.Receptor.Urbanizacion, CityName = documento.Receptor.Provincia, IdUbigeo = new IdUbigeo() { Value = documento.Receptor.Ubigeo }, CountrySubentity = documento.Receptor.Departamento, District = documento.Receptor.Distrito, Country = new Country() { IdentificationCode = new IdentificationCode() { Value = documento.Receptor.Pais } }, AddressTypeCode = new AddressTypeCode() { } // Investigar mas sobre este valor, por ahora no irá } }, #region PartyTaxScheme PartyTaxScheme = new PartyTaxScheme() // Tambien se excluyó, decreto de SUNAT 30/06/2018 { // Número de RUC del Receptor CompanyID = new CompanyID() { SchemeID = documento.Receptor.TipoDocumento, Value = documento.Receptor.NroDocumento } }, #endregion PartyTaxScheme }, }, // PayeeParty // Delivery, aun por implementar DeliveryTerms = new DeliveryTerms { Id = documento.TerminosEntrega.NumeroRegistro ?? string.Empty, Amount = new Amount { CurrencyID = documento.TerminosEntrega.TipoMoneda, Value = documento.TerminosEntrega.Monto }, DeliveryLocation = new DeliveryLocation() { Address = new Address() { StreetName = documento.TerminosEntrega.Direccion, CitySubdivisionName = documento.TerminosEntrega.Urbanizacion, CityName = documento.TerminosEntrega.Provincia, CountrySubentity = documento.TerminosEntrega.Departamento, CountrySubentityCode = documento.TerminosEntrega.Ubigeo, District = documento.TerminosEntrega.Distrito, Country = new Country() { // Dirección del lugar en el que se entrega el bien (Código de país) IdentificationCode = new IdentificationCode() { // <cbc:IdentificationCode listID="ISO3166-1" listAgencyID="6">DK</cbc:IdentificationCode> Value = documento.TerminosEntrega.Alfa2 } } } } }, PaymentsMeans = new List <PaymentMeans> (), PaymentsTerms = new List <PaymentTerms> (), PrepaidPayments = new List <PrepaidPayment> (), AllowanceCharges = new List <AllowanceCharge> (), TaxTotals = new List <TaxTotal> (), LegalMonetaryTotal = new LegalMonetaryTotal() { LineExtensionAmount = new PayableAmount() { Value = documento.TotalValorVenta, CurrencyId = documento.Moneda }, TaxInclusiveAmount = new PayableAmount() { Value = documento.TotalPrecioVenta, CurrencyId = documento.Moneda }, AllowanceTotalAmount = new PayableAmount() { Value = documento.TotalDescuento, CurrencyId = documento.Moneda }, ChargeTotalAmount = new PayableAmount() { Value = documento.TotalOtrosCargos, CurrencyId = documento.Moneda }, PrepaidAmount = new PayableAmount() { Value = documento.TotalAnticipos, CurrencyId = documento.Moneda }, PayableAmount = new PayableAmount() { Value = documento.ImporteTotalVenta, CurrencyId = documento.Moneda }, PayableRoundingAmount = new PayableAmount() { Value = documento.MontoRedondeo, CurrencyId = documento.Moneda }, } // InvoiceLine }; // Lista de otros participantes asociados a la transacción if (documento.Receptor.OtrosParticipantes.Count > 0) // mejorar validación { foreach (var otroParticipante in documento.Receptor.OtrosParticipantes) { invoice.AccountingCustomerParty.Party.PartyLegalEntity.ShareholderParties.Add(new ShareholderParty { Party = new Party() { PartyIdentification = new PartyIdentification() { Id = new PartyIdentificationId() { SchemeId = otroParticipante.TipoDocumento, Value = otroParticipante.NroDocumento } } } }); } } // Datos en lista if (documento.Notas.Count > 0 && documento.Notas != null) { foreach (var nota in documento.Notas) { if (!string.IsNullOrEmpty(nota.Descripcion.ToString())) { invoice.Notes.Add(new Note // Se agrega al objeto Note { LanguageLocaleID = nota.Codigo, // Código de leyenda Value = nota.Descripcion // Descripcion }); } } } #region Get out InvoicePeriod // Ciclo de facturación //if (documento.PeriodosFactura.Count > 0 && documento.PeriodosFactura != null) //{ // try // { // foreach (var periodoFactura in documento.PeriodosFactura) // { // if (!string.IsNullOrEmpty(periodoFactura.FechaInicio.ToString()) || !string.IsNullOrEmpty(periodoFactura.FechaFin.ToString())) // { // invoice.InvoicePeriods.Add(new InvoicePeriod // { // StartDate = periodoFactura.FechaInicio, // Fecha de inicio de ciclo de facturación // EndDate = periodoFactura.FechaFin // Fecha de fin de ciclo de facturación // }); // } // } // } // catch // { // } //} #endregion Get out InvoicePeriod // documento relacionado o despatchdocumentreferences //if (documento.relacionados.count > 0 && documento.relacionados != null) //{ // foreach (var relacionado in documento.relacionados) // 0..n; relacionados = despatchdocumentreference // { // if (!string.isnullorempty(relacionado.tipodocumento.tostring())) // { // invoice.despatchdocumentreferences.add(new invoicedocumentreference // { // id = relacionado.nrodocumento, // número de guía de remisión relacionada con la operación que se factura // documenttypecode = new documenttypecode() // { // código de tipo de guía de remisión relacionada con la operación que se factura // listname = "tipo de documento", listuri = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo01", value = relacionado.tipodocumento // }, // }); // } // } //} #region Get out ContractDocumentReference // Documento contrato //if (documento.DocumentoContratos.Count > 0 && documento.DocumentoContratos != null) //{ // foreach (var documentoContrato in documento.DocumentoContratos) // { // if (!string.IsNullOrEmpty(documentoContrato.IdNumero)) // { // invoice.ContractDocumentReferences.Add(new ContractDocumentReference // { // Id = documentoContrato.IdNumero, // cbc:ID // DocumentTypeCode = new ContractDocumentReference_DocumentTypeCode() // { // cbc:DocumentTypeCode // Value = documentoContrato.TipoServicioPublico // }, // LocaleCode = new LocaleCode() { Value = documentoContrato.ServicioTelecomunicaciones }, // DocumentStatusCode = new DocumentStatusCode() { Value = documentoContrato.TipoTarifaContratada } // }); // } // } //} #endregion Get out ContractDocumentReference //Otros documentos relacionados //if (documento.OtrosDocumentosRelacionados.Count > 0 && documento.OtrosDocumentosRelacionados != null) //{ // foreach (var relacionado in documento.OtrosDocumentosRelacionados) // { // if (!string.IsNullOrEmpty(relacionado.TipoDocumento.ToString())) // { // var otroDocumentoRelacionado = new InvoiceDocumentReference() // //invoice.AdditionalDocumentReferences.Add(new InvoiceDocumentReference // { // Id = relacionado.NroDocumento, // Número de documento relacionado con la operación que se factura // DocumentTypeCode = new DocumentTypeCode() // { // Código de tipo de documento relacionado con la operación que se factura // ListName = "Documento Relacionado", ListURI = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo12", Value = relacionado.TipoDocumento // }, // DocumentStatusCode = new DocumentStatusCode() { Value = relacionado.IdentificadorPago, ListName = "Anticipo" }, // Identificador del pago // IssuerParty = new IssuerParty() { PartyIdentifications = new List<PartyIdentification>() } // }; // if (relacionado.Identificaciones.Count > 0) // { // foreach (var identificacion in relacionado.Identificaciones) // { // otroDocumentoRelacionado.IssuerParty.PartyIdentifications.Add(new PartyIdentification() // { // Id = new PartyIdentificationId() { SchemeId = identificacion.TipoDocumento, Value = identificacion.NroDocumento } // }); // } // } // invoice.AdditionalDocumentReferences.Add(otroDocumentoRelacionado); // } // } //} // Delivery en la documentación dice que es de 0..n de cero a muchos (FALTA) //if (documento.Entregas.Count > 0 && documento.Entregas != null) // //{ // foreach (var entrega in documento.Entregas) // { // if (!string.IsNullOrEmpty(entrega.Codigo)) // { // var varEntrega = new Delivery() { // DeliveryId = new DeliveryId() { Value = entrega.Codigo }, // Actualizado conforme al documento del 30/06/2018 // Quantity = new Quantity() { Value = entrega.Cantidad }, // MaximumQuantity = new MaximumQuantity() { Value = entrega.MaximaCantidad }, // DeliveryLocation = new DeliveryLocation() // { // Address = new Address() // { // AddressLine = new AddressLine() { Line = entrega.Direccion }, // Dirección completa y detallada // CitySubdivisionName = entrega.Urbanizacion, // Urbanización // CityName = entrega.Provincia, // Id = new IdUbigeo() { Value = entrega.Ubigeo }, // CountrySubentity = entrega.Departamento, // District = entrega.Distrito, // Country = new Country() { IdentificationCode = new IdentificationCode() { Value = entrega.Pais } }, // } // }, // DeliveryParty = new DeliveryParty() { PartyLegalEntities = new List<PartyLegalEntity>() }, // Se rellena en la región DeliveryParty // Shipment = new Shipment() { // Envío // Id = new ShipmentId() { Value = entrega.Envio.CodMotivoTraslado }, // GrossWeightMeasure = new InvoicedQuantity() { UnitCode = entrega.Envio.UnidadMedida, Value = entrega.Envio.PesoBruto }, // ShipmentStages = new List<ShipmentStage>(), // Se rellena en la región ShipmentStage // TransportHandlingUnit = new TransportHandlingUnit() { TransportEquipments = new List<TransportEquipment>() }, // Delivery = new Delivery() { DeliveryAddress = new DeliveryAddress() { // Id = new DeliveryAddressId() { Value = entrega.Envio.PuntoLlegadaUbigeo }, // AddressLine = new AddressLine() { Line = entrega.Envio.PuntoLlegadaDireccion } // } }, // OriginAddress = new OriginAddress() { // Id = new OriginAddressID() { Value = entrega.Envio.PuntoLlegadaUbigeo }, // AddressLine = new AddressLine() { Line = entrega.Envio.PuntoLlegadaDireccion } // }, // } // }; // #region DeliveryParty // if (entrega.EntregaDetalle.NroDocDestinatarios.Count > 0) // { // foreach (var nroDocDestinatario in entrega.EntregaDetalle.NroDocDestinatarios) // { // varEntrega.DeliveryParty.PartyLegalEntities.Add(new PartyLegalEntity() // { // CompanyID = new CompanyID() { SchemeID = nroDocDestinatario.TipoDocumento, Value = nroDocDestinatario.NroDocumento ?? string.Empty } // }); // } // varEntrega.DeliveryParty.MarkAttentionIndicator = entrega.EntregaDetalle.IndSubContratacion; // } // #endregion DeliveryParty // #region ShipmentStage // if (entrega.Envio.EtapaEnvios.Count > 0) // Validación pendiente // { // ShipmentStage // foreach (var etapaEnvio in entrega.Envio.EtapaEnvios) // { // var varEtapaEnvio = new ShipmentStage() { // TransportModeCode = new TransportModeCode() { Value = etapaEnvio.ModalidadTransporte }, // [0..1] // TransitPeriod = new TransitPeriod() { StartDate = etapaEnvio.FechaInicioTraslado }, // [0..1] // CarrierParties = new List<CarrierParty>(), // [0..*] // TransportMeans = new TransportMeans() // { // RegistrationNationalityID = etapaEnvio.Vehiculo.Constancia, // RoadTransport = new RoadTransport() { LicensePlateID = etapaEnvio.Vehiculo.Placa } // }, // DriverPersons = new List<PartyIdentification>() // [0..*] // }; // varEntrega.Shipment.ShipmentStages.Add(varEtapaEnvio); // #region CarrierParties // foreach (var transportista in etapaEnvio.Transportistas) // { // varEtapaEnvio.CarrierParties.Add(new CarrierParty() // { // PartyIdentification = new PartyIdentification() // { // Id = new PartyIdentificationId() { Value = transportista.NroDocumento, SchemeId = transportista.TipoDocumento }, // }, // PartyLegalEntity = new PartyLegalEntity() // { // RegistrationName = transportista.NombreLegal, CompanyID = new CompanyID() { Value = transportista.RegistroMTC } // } // }); // } // #endregion CarrierParties // #region DriverPersons // foreach (var conductor in etapaEnvio.Conductores) // { // // Datos de conductores - Número de documento de identidad | Tipo de documento // varEtapaEnvio.DriverPersons.Add(new PartyIdentification() // { // Id = new PartyIdentificationId() { SchemeId = conductor.TipoDocumento, Value = conductor.NroDocumento ?? string.Empty } // }); // } // #endregion DriverPersons // } // } // #endregion ShipmentStage // #region TransportEquipment // foreach (var vehiculo in entrega.Envio.Vehiculos) // { // varEntrega.Shipment.TransportHandlingUnit.TransportEquipments.Add(new TransportEquipment() { Id = vehiculo.Placa ?? string.Empty }); // } // #endregion TransportEquipment // invoice.Deliveries.Add(varEntrega); // } // } //} // Medio de pago //if (documento.MedioPagos.Count > 0 && documento.MedioPagos != null) //{ // foreach (var medioPago in documento.MedioPagos) // { // if (!string.IsNullOrEmpty(medioPago.NroCuenta.ToString())) // { // invoice.PaymentsMeans.Add(new PaymentMeans() // { // Cuenta del banco de la nacion (detraccion) // PaymentID = medioPago.Autorizacion, // PayeeFinancialAccount = new PayeeFinancialAccount() { Id = medioPago.NroCuenta ?? string.Empty }, // Número de cuenta // PaymentMeansCode = new PaymentMeansCode() { Value = medioPago.CodigoCatalogo ?? string.Empty } // Código de medio de pago // }); // } // } //} // Terminos de pago //if (documento.TerminosPagos.Count > 0 && documento.TerminosPagos != null) //{ // foreach (var terminosPago in documento.TerminosPagos) // { // if (!string.IsNullOrEmpty(terminosPago.Codigo)) // { // Monto y Porcentaje de la detracción // invoice.PaymentsTerms.Add(new PaymentTerms() // { // PaymentTermsId = new PaymentTermsId() { Value = terminosPago.Codigo }, // Catálogo No. 54 // PaymentPercent = terminosPago.Porcentaje, // Tasa o porcentaje de detracción // Amount = terminosPago.Monto // Monto de detraccion // }); // } // } //} // PrepaidPayment if (documento.Anticipos.Count > 0 && documento.Anticipos != null) { foreach (var anticipo in documento.Anticipos) { // Información prepagado o anticipado (Deducción de anticipos) invoice.PrepaidPayments.Add(new PrepaidPayment { PrepaidPaymentId = new PrepaidPaymentId // cbc:ID | Identificador del pago { // Serie y número de comprobante del anticipo (para el caso de reorganización de empresas, incluye el RUC) SchemeID = anticipo.TipoDocumento, Value = anticipo.ComprobanteAnticipo }, PaidAmount = new PaidAmount { CurrencyID = anticipo.Moneda, Value = anticipo.Monto }, // Monto anticipado PaidTime = anticipo.FechaPago }); } } //// AllowanceCharge o Descuentos //if (documento.Descuentos.Count > 0 && documento.Descuentos != null) //{ // foreach (var descuentos in documento.Descuentos) // { // if (!string.IsNullOrEmpty(descuentos.Indicador.ToString())) // { // invoice.AllowanceCharges.Add(new AllowanceCharge // { // ChargeIndicator = descuentos.Indicador, // AllowanceChargeReasonCode = new AllowanceChargeReasonCode() { Value = descuentos.CodigoMotivo }, // MultiplierFactorNumeric = descuentos.Factor, // Amount = new PayableAmount { CurrencyId = descuentos.Moneda, Value = descuentos.Monto }, // BaseAmount = new PayableAmount { CurrencyId = descuentos.MonedaBase, Value = descuentos.MontoBase } // }); // } // } //} // TaxTotal o TotalImpuestos if (documento.TotalImpuestos.Count > 0 && documento.TotalImpuestos != null) { // Total de impuestos para el documento foreach (var totalImpuesto in documento.TotalImpuestos) { var lineaTotalImpuestos = new TaxTotal { // Monto total de impuestos TaxAmount = new PayableAmount() { CurrencyId = totalImpuesto.TipoMonedaTotal, Value = totalImpuesto.MontoTotal } }; foreach (var subTotalImpuestos in totalImpuesto.SubTotalesImpuestos) { lineaTotalImpuestos.TaxSubtotals.Add(new TaxSubtotal { TaxableAmount = new PayableAmount { // Monto base CurrencyId = subTotalImpuestos.TipoMonedaBase, // Código de tipo de moneda del monto de las operaciones gravadas/exoneradas/inafectas del impuesto Value = subTotalImpuestos.BaseImponible // Monto las operaciones gravadas/exoneradas/inafectas del impuesto }, TaxAmount = new PayableAmount { CurrencyId = subTotalImpuestos.TipoMonedaTotal, // Código de tipo de moneda del monto total del impuesto Value = subTotalImpuestos.MontoTotal // Monto total del impuesto }, TaxCategory = new TaxCategory { TaxCategoryId = new TaxCategoryId { Value = subTotalImpuestos.CategoriaImpuestos }, // Categoría de impuestos TaxScheme = new TaxScheme { TaxSchemeId = new TaxSchemeId { Value = subTotalImpuestos.CodigoTributo }, // Código de tributo Name = subTotalImpuestos.NombreTributo, // NombreTributo de tributo TaxTypeCode = subTotalImpuestos.CodigoInternacional // Código internacional tributo } } }); } invoice.TaxTotals.Add(lineaTotalImpuestos); // Realizar debug } } // InvoiceLine o DetalleFactura foreach (var detalleDocumento in documento.DetalleDocumentos) { var linea = new InvoiceLine { IdInvoiceLine = detalleDocumento.NumeroOrden, // Número de orden del Ítem | No debe repetirse InvoicedQuantity = new InvoicedQuantity() { Value = detalleDocumento.Cantidad, // Cantidad de unidades por ítem UnitCode = detalleDocumento.UnidadMedida // Unidad de medida por ítem | (Catálogo No. 03) }, LineExtensionAmount = new PayableAmount() { CurrencyId = detalleDocumento.Moneda, Value = detalleDocumento.ValorVenta }, // Valor de venta por ítem //TaxPointDate = "", // Se omitió esta etiqueta en la documentacion EXCEL de SUNAT PricingReference = new PricingReference() { AlternativeConditionPrices = new List <AlternativeConditionPrice>() }, // La implementación esta dentro de la region AlternativeConditionPrice // AllowanceCharge //TaxTotals = new List<TaxTotal>(), // Implementado en la región TaxTotal Item = new Item() { Descriptions = new List <Description>(), // Se implementa líneas abajo SellersItemIdentification = new SellersItemIdentification() { Id = detalleDocumento.CodigoProducto }, // Código de producto CommodityClassification = new CommodityClassification() // No hay una tabla con este listado, debido a inestabilidad de Sunat y por ser demasiado extenso { // Codigo producto de SUNAT | (Catálogo No. 25) | Es excluyente cuando el tipo de operación esta entre 0200 a 0208 ItemClassificationCode = new ItemClassificationCode() { Value = detalleDocumento.CodigoProductoSunat ?? string.Empty } }, // Si tipo de operación es 0112, no debe haber productos con código de Sunat igual a 84121901 o 80131501 // StandardItemIdentification = new StandardItemIdentification() { } Codigo de barras, no se agregará a pedido de Tania AdditionalItemProperties = new List <AdditionalItemProperty>() // Implementado en la región AdditionalItemProperty }, Price = new Price() { PriceAmount = new PayableAmount() { CurrencyId = detalleDocumento.Moneda, Value = detalleDocumento.ValorVenta } }, // Valor unitario por ítem Deliveries = new List <Delivery>() }; //if (true) Aun no se completa debido a que en la documentación especificada por Tania no se contempla estas etiquetas //{ // foreach (var entrega in detalleDocumento.Entregas) // { // linea.Deliveries.Add(new Delivery() // { // //DeliveryParty = new DeliveryParty() { // // PartyIdentification = new PartyIdentification() { Id = new PartyIdentificationId() { Value = AUN POR COMPLETAR! } } // //}, // Despatch = new Despatch() // { // DespatchAddress = new DespatchAddress() { ID = new DespatchAddressID() { Value = "" } } // } // }); // } //} #region AlternativeConditionPrice if (detalleDocumento.PreciosAlternativos.Count > 0) { foreach (var precioAlternativo in detalleDocumento.PreciosAlternativos) { if (precioAlternativo.Monto != null) { linea.PricingReference.AlternativeConditionPrices.Add(new AlternativeConditionPrice() { PriceAmount = new PayableAmount() { CurrencyId = precioAlternativo.TipoMoneda, Value = precioAlternativo.Monto }, PriceTypeCode = new PriceTypeCode() { Value = precioAlternativo.TipoPrecio } // Código de precio | Catálogo No. 16 }); } } } #endregion AlternativeConditionPrice #region AllowanceCharge if (detalleDocumento.Descuentos.Count > 0) // Validar { foreach (var descuento in detalleDocumento.Descuentos) { // De estar vacio o nulo, este boleano indicara si se debe llenar el nodo o no ya que es nodo requerido para su nodo padre if (!string.IsNullOrEmpty(descuento.Indicador.ToString())) { linea.AllowanceCharges.Add(new AllowanceCharge() { ChargeIndicator = descuento.Indicador, // Indicador de cargo/descuento AllowanceChargeReasonCode = new AllowanceChargeReasonCode() { Value = descuento.CodigoMotivo }, // Código de cargo/descuento MultiplierFactorNumeric = descuento.Factor, // Factor de cargo/descuento Amount = new PayableAmount { CurrencyId = descuento.Moneda, Value = descuento.Monto }, // Monto de cargo/descuento BaseAmount = new PayableAmount { CurrencyId = descuento.MonedaBase, Value = descuento.MontoBase } // Monto base del cargo/descuento }); } } } #endregion AllowanceCharge #region TaxTotal if (detalleDocumento.TotalImpuestos.Count > 0) { // Monto total de impuestos del ítem foreach (var totalImpuesto in detalleDocumento.TotalImpuestos) { // Total de impuestos para cada ítem var lineaTotalImpuestos = new TaxTotal { // Monto total de impuestos por línea TaxAmount = new PayableAmount() { CurrencyId = totalImpuesto.TipoMonedaTotal, Value = totalImpuesto.MontoTotal } }; foreach (var subTotalImpuestos in totalImpuesto.SubTotalesImpuestos) { // Afectación al IGV por la línea | Afectación IVAP por la línea lineaTotalImpuestos.TaxSubtotals.Add(new TaxSubtotal { TaxableAmount = new PayableAmount { // Monto base CurrencyId = subTotalImpuestos.TipoMonedaBase, // Código de tipo de moneda del monto de las operaciones gravadas/exoneradas/inafectas del impuesto Value = subTotalImpuestos.BaseImponible // Monto las operaciones gravadas/exoneradas/inafectas del impuesto }, TaxAmount = new PayableAmount { // Monto de IGV/IVAP de la línea | Monto total de impuestos por linea CurrencyId = subTotalImpuestos.TipoMonedaTotal, // Código de tipo de moneda del monto total del impuesto Value = subTotalImpuestos.MontoTotal // Monto total del impuesto }, TaxCategory = new TaxCategory { // Tasa del IGV o Tasa del IVAP TaxCategoryId = new TaxCategoryId { Value = subTotalImpuestos.CategoriaImpuestos }, // Categoría de impuestos Percent = subTotalImpuestos.PorcentajeImp, // Tasa del IGV o Tasa del IVAP | Tasa del tributo TaxExemptionReasonCode = new TaxExemptionReasonCode() { Value = subTotalImpuestos.TipoAfectacion }, // Afectación al IGV o IVAP cuando corresponda TierRange = subTotalImpuestos.TipoSistemaISC, TaxScheme = new TaxScheme { TaxSchemeId = new TaxSchemeId { Value = subTotalImpuestos.CodigoTributo }, // Código de tributo por línea | Catálogo No. 05 Name = subTotalImpuestos.NombreTributo, // NombreTributo de tributo TaxTypeCode = subTotalImpuestos.CodigoInternacional // Código internacional tributo } } }); } linea.TaxTotals.Add(lineaTotalImpuestos); // Realizar debug } } #endregion TaxTotal #region Description if (detalleDocumento.Descripciones.Count > 0) // Validar { foreach (var descripcion in detalleDocumento.Descripciones) { // Descripción detallada del servicio prestado, bien vendido o cedido en uso, indicando las características. linea.Item.Descriptions.Add(new Description() { Detail = descripcion.Detalle ?? string.Empty }); } } #endregion Description #region AdditionalItemProperty if (detalleDocumento.PropiedadesAdicionales.Count > 0) // validar { foreach (var propiedadAdicional in detalleDocumento.PropiedadesAdicionales) { linea.Item.AdditionalItemProperties.Add(new AdditionalItemProperty() { Name = propiedadAdicional.Nombre, // Sí existe el Tag no debe estar vacío | Catálogo No. 55 NameCode = new NameCode() { Value = propiedadAdicional.Codigo }, Value = propiedadAdicional.ValorPropiedad, // Se le puede poner distintos valores o hubo confusión de Sunat.. // En la documentación vista el 30/06/2018 se observó que el campo ValueQualifier fue removido o no fue considerado en la documentación, ValueQualifier = new ValueQualifier() { Detail = propiedadAdicional.Concepto ?? string.Empty }, UsabilityPeriod = new UsabilityPeriod() { StartDate = propiedadAdicional.FechaInicio, EndDate = propiedadAdicional.FechaFin, DurationMeasure = new DurationMeasure() { Value = propiedadAdicional.Duracion } }, ValueQuantity = new ValueQuantity() { Value = propiedadAdicional.CantidadEspecies }, }); } } #endregion AdditionalItemProperty invoice.InvoiceLines.Add(linea); } return(invoice); }
IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request) { var documento = (ResumenDiario)request; var summary = new SummaryDocuments { Id = documento.IdDocumento, IssueDate = Convert.ToDateTime(documento.FechaEmision), ReferenceDate = Convert.ToDateTime(documento.FechaReferencia), CustomizationId = "1.1", UblVersionId = "2.0", Signature = new Signature { Id = documento.IdDocumento, SignatoryParty = new SignatoryParty { PartyIdentification = new PartyIdentification { Id = new PartyIdentificationId { Value = documento.Emisor.NroDocumento } }, PartyName = new PartyName { Name = documento.Emisor.NombreLegal } }, DigitalSignatureAttachment = new DigitalSignatureAttachment { ExternalReference = new ExternalReference { Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}" } } }, AccountingSupplierParty = new AccountingContributorParty { CustomerAssignedAccountId = documento.Emisor.NroDocumento, AdditionalAccountId = documento.Emisor.TipoDocumento, Party = new Party { PartyLegalEntity = new PartyLegalEntity { RegistrationName = documento.Emisor.NombreLegal } } } }; foreach (var resumen in documento.Resumenes) { var linea = new VoidedDocumentsLine { LineId = resumen.Id, DocumentTypeCode = resumen.TipoDocumento, Id = resumen.Serie, // Serie correlativo AccountingCustomerParty = new AccountingContributorParty { AdditionalAccountId = resumen.Receptor.TipoDocumento, CustomerAssignedAccountId = resumen.Receptor.NroDocumento }, BillingReference = new BillingReference { InvoiceDocumentReference = new InvoiceDocumentReference { Id = resumen.DocumentoRelacionado, DocumentTypeCode = new DocumentTypeCode() { Value = resumen.TipoDocumentoRelacionado } } }, ConditionCode = resumen.CodigoEstadoItem, TotalAmount = new PayableAmount { CurrencyId = resumen.Moneda, Value = resumen.TotalVenta }, BillingPayments = new List <BillingPayment>() { new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = resumen.Moneda, Value = resumen.Gravadas }, InstructionId = "01" } }, AllowanceCharge = new AllowanceCharge { ChargeIndicator = true, Amount = new PayableAmount { CurrencyId = resumen.Moneda, Value = resumen.TotalDescuentos } }, }; #region TaxTotal if (resumen.TotalImpuestos.Count > 0) { // Monto total de impuestos del ítem foreach (var totalImpuesto in resumen.TotalImpuestos) { // Total de impuestos para cada ítem var lineaTotalImpuestos = new TaxTotal { // Monto total de impuestos por línea TaxAmount = new PayableAmount() { CurrencyId = totalImpuesto.TipoMonedaTotal, Value = totalImpuesto.MontoTotal } }; foreach (var subTotalImpuestos in totalImpuesto.SubTotalesImpuestos) { // Afectación al IGV por la línea | Afectación IVAP por la línea lineaTotalImpuestos.TaxSubtotals.Add(new TaxSubtotal { TaxAmount = new PayableAmount { // Monto de IGV/IVAP de la línea | Monto total de impuestos por linea CurrencyId = subTotalImpuestos.TipoMonedaTotal, // Código de tipo de moneda del monto total del impuesto Value = subTotalImpuestos.MontoTotal // Monto total del impuesto }, TaxCategory = new TaxCategory { // Tasa del IGV o Tasa del IVAP TaxCategoryId = new TaxCategoryId { Value = subTotalImpuestos.CategoriaImpuestos }, // Categoría de impuestos Percent = subTotalImpuestos.PorcentajeImp, // Tasa del IGV o Tasa del IVAP | Tasa del tributo TaxExemptionReasonCode = new TaxExemptionReasonCode() { Value = subTotalImpuestos.TipoAfectacion }, // Afectación al IGV o IVAP cuando corresponda TierRange = subTotalImpuestos.TipoSistemaISC, TaxScheme = new TaxScheme { TaxSchemeId = new TaxSchemeId { Value = subTotalImpuestos.CodigoTributo }, // Código de tributo por línea | Catálogo No. 05 Name = subTotalImpuestos.NombreTributo, // NombreTributo de tributo TaxTypeCode = subTotalImpuestos.CodigoInternacional // Código internacional tributo } } }); } linea.TaxTotals.Add(lineaTotalImpuestos); // Realizar debug } } #endregion TaxTotal if (resumen.Exoneradas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = resumen.Moneda, Value = resumen.Exoneradas }, InstructionId = "02" }); } if (resumen.Inafectas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = resumen.Moneda, Value = resumen.Inafectas }, InstructionId = "03" }); } if (resumen.Exportaciones > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = resumen.Moneda, Value = resumen.Exportaciones }, InstructionId = "04" }); } if (resumen.Gratuitas > 0) { linea.BillingPayments.Add(new BillingPayment { PaidAmount = new PayableAmount { CurrencyId = resumen.Moneda, Value = resumen.Gratuitas }, InstructionId = "05" }); } summary.SummaryDocumentsLines.Add(linea); } return(summary); }