Ejemplo n.º 1
0
        public override object Clone()
        {
            var result = base.Clone() as Shipment;

            result.Price                 = Price?.Clone() as Money;
            result.PriceWithTax          = PriceWithTax?.Clone() as Money;
            result.DiscountAmount        = DiscountAmount?.Clone() as Money;
            result.DiscountAmountWithTax = DiscountAmountWithTax?.Clone() as Money;
            result.Total                 = Total?.Clone() as Money;
            result.TotalWithTax          = TotalWithTax?.Clone() as Money;
            result.TaxTotal              = TaxTotal?.Clone() as Money;


            if (Discounts != null)
            {
                result.Discounts = new List <Discount>(Discounts.Select(x => x.Clone() as Discount));
            }
            if (TaxDetails != null)
            {
                result.TaxDetails = new List <TaxDetail>(TaxDetails.Select(x => x.Clone() as TaxDetail));
            }
            if (Items != null)
            {
                result.Items = new List <CartShipmentItem>(Items.Select(x => x.Clone() as CartShipmentItem));
            }
            if (ValidationErrors != null)
            {
                result.ValidationErrors = new List <ValidationError>(ValidationErrors.Select(x => x.Clone() as ValidationError));
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns true if OrderSummary instances are equal
        /// </summary>
        /// <param name="other">Instance of OrderSummary to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(OrderSummary other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     PartnerOrderNumber == other.PartnerOrderNumber ||
                     PartnerOrderNumber != null &&
                     PartnerOrderNumber.Equals(other.PartnerOrderNumber)
                     ) &&
                 (
                     PlaceOrderTime == other.PlaceOrderTime ||
                     PlaceOrderTime != null &&
                     PlaceOrderTime.Equals(other.PlaceOrderTime)
                 ) &&
                 (
                     Currency == other.Currency ||
                     Currency != null &&
                     Currency.Equals(other.Currency)
                 ) &&
                 (
                     SubTotal == other.SubTotal ||
                     SubTotal != null &&
                     SubTotal.Equals(other.SubTotal)
                 ) &&
                 (
                     TaxTotal == other.TaxTotal ||
                     TaxTotal != null &&
                     TaxTotal.Equals(other.TaxTotal)
                 ) &&
                 (
                     ShippingTotal == other.ShippingTotal ||
                     ShippingTotal != null &&
                     ShippingTotal.Equals(other.ShippingTotal)
                 ) &&
                 (
                     Channel == other.Channel ||
                     Channel != null &&
                     Channel.Equals(other.Channel)
                 ));
        }
Ejemplo n.º 3
0
        public override object Clone()
        {
            var result = base.Clone() as LineItem;

            result.ListPrice             = ListPrice?.Clone() as Money;
            result.SalePrice             = SalePrice?.Clone() as Money;
            result.DiscountAmount        = DiscountAmount?.Clone() as Money;
            result.DiscountAmountWithTax = DiscountAmountWithTax?.Clone() as Money;
            result.DiscountTotal         = DiscountTotal?.Clone() as Money;
            result.DiscountTotalWithTax  = DiscountTotalWithTax?.Clone() as Money;
            result.ListPriceWithTax      = ListPriceWithTax?.Clone() as Money;
            result.SalePriceWithTax      = SalePriceWithTax?.Clone() as Money;
            result.PlacedPrice           = PlacedPrice?.Clone() as Money;
            result.PlacedPriceWithTax    = PlacedPriceWithTax?.Clone() as Money;
            result.ExtendedPrice         = ExtendedPrice?.Clone() as Money;
            result.ExtendedPriceWithTax  = ExtendedPriceWithTax?.Clone() as Money;
            result.TaxTotal = TaxTotal?.Clone() as Money;

            if (Discounts != null)
            {
                result.Discounts = new List <Discount>(Discounts.Select(x => x.Clone() as Discount));
            }
            if (TaxDetails != null)
            {
                result.TaxDetails = new List <TaxDetail>(TaxDetails.Select(x => x.Clone() as TaxDetail));
            }
            if (DynamicProperties != null)
            {
                result.DynamicProperties = new MutablePagedList <DynamicProperty>(DynamicProperties.Select(x => x.Clone() as DynamicProperty));
            }
            if (ValidationErrors != null)
            {
                result.ValidationErrors = new List <ValidationError>(ValidationErrors.Select(x => x.Clone() as ValidationError));
            }

            return(result);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (PartnerOrderNumber != null)
         {
             hashCode = hashCode * 59 + PartnerOrderNumber.GetHashCode();
         }
         if (PlaceOrderTime != null)
         {
             hashCode = hashCode * 59 + PlaceOrderTime.GetHashCode();
         }
         if (Currency != null)
         {
             hashCode = hashCode * 59 + Currency.GetHashCode();
         }
         if (SubTotal != null)
         {
             hashCode = hashCode * 59 + SubTotal.GetHashCode();
         }
         if (TaxTotal != null)
         {
             hashCode = hashCode * 59 + TaxTotal.GetHashCode();
         }
         if (ShippingTotal != null)
         {
             hashCode = hashCode * 59 + ShippingTotal.GetHashCode();
         }
         if (Channel != null)
         {
             hashCode = hashCode * 59 + Channel.GetHashCode();
         }
         return(hashCode);
     }
 }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        public override object Clone()
        {
            var result = base.Clone() as ShoppingCart;

            result.HandlingTotal        = HandlingTotal?.Clone() as Money;
            result.HandlingTotalWithTax = HandlingTotalWithTax?.Clone() as Money;
            result.DiscountAmount       = DiscountAmount?.Clone() as Money;
            result.Total                = Total?.Clone() as Money;
            result.SubTotal             = SubTotal?.Clone() as Money;
            result.SubTotalWithTax      = SubTotalWithTax?.Clone() as Money;
            result.ShippingPrice        = ShippingPrice?.Clone() as Money;
            result.ShippingPriceWithTax = ShippingPriceWithTax?.Clone() as Money;
            result.ShippingTotal        = ShippingTotal?.Clone() as Money;
            result.ShippingTotalWithTax = ShippingTotalWithTax?.Clone() as Money;
            result.PaymentPrice         = PaymentPrice?.Clone() as Money;
            result.PaymentPriceWithTax  = PaymentPriceWithTax?.Clone() as Money;
            result.PaymentTotal         = PaymentTotal?.Clone() as Money;
            result.PaymentTotalWithTax  = PaymentTotalWithTax?.Clone() as Money;
            result.HandlingTotal        = HandlingTotal?.Clone() as Money;
            result.HandlingTotalWithTax = HandlingTotalWithTax?.Clone() as Money;
            result.DiscountTotal        = DiscountTotal?.Clone() as Money;
            result.DiscountTotalWithTax = DiscountTotalWithTax?.Clone() as Money;
            result.TaxTotal             = TaxTotal?.Clone() as Money;

            if (Discounts != null)
            {
                result.Discounts = new List <Discount>(Discounts.Select(x => x.Clone() as Discount));
            }
            if (TaxDetails != null)
            {
                result.TaxDetails = new List <TaxDetail>(TaxDetails.Select(x => x.Clone() as TaxDetail));
            }
            if (DynamicProperties != null)
            {
                result.DynamicProperties = new List <DynamicProperty>(DynamicProperties.Select(x => x.Clone() as DynamicProperty));
            }
            if (ValidationErrors != null)
            {
                result.ValidationErrors = new List <ValidationError>(ValidationErrors.Select(x => x.Clone() as ValidationError));
            }
            if (Addresses != null)
            {
                result.Addresses = new List <Address>(Addresses.Select(x => x.Clone() as Address));
            }
            if (Items != null)
            {
                result.Items = new List <LineItem>(Items.Select(x => x.Clone() as LineItem));
            }
            if (Payments != null)
            {
                result.Payments = new List <Payment>(Payments.Select(x => x.Clone() as Payment));
            }
            if (Shipments != null)
            {
                result.Shipments = new List <Shipment>(Shipments.Select(x => x.Clone() as Shipment));
            }
            if (Coupons != null)
            {
                result.Coupons = new List <Coupon>(Coupons.Select(x => x.Clone() as Coupon));
            }
            if (AvailablePaymentMethods != null)
            {
                result.AvailablePaymentMethods = new List <PaymentMethod>(AvailablePaymentMethods.Select(x => x.Clone() as PaymentMethod));
            }

            return(result);
        }
Ejemplo n.º 7
0
        public List<TaxTotal> TotalsGetTaxTotals(DateTime StartDate, DateTime EndDate)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("TotalsGetTaxTotals", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@StartDate", StartDate);
            cmd.Parameters.AddWithValue("@EndDate", EndDate);

            try
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
                TaxTotal currentitem;
                List<TaxTotal> items = new List<TaxTotal>();
                while (reader.Read())
                {
                    currentitem = new TaxTotal(
                        DateTime.Parse(reader["StartDate"].ToString()),
                        DateTime.Parse(reader["EndDate"].ToString()),
                        reader["TaxLine"].ToString(),
                        Decimal.Parse(reader["Amount"].ToString())
                        );
                    items.Add(currentitem);
                }
                return items;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
Ejemplo n.º 8
0
        protected override List <TaxTotal> GetTaxesTotales(XDocument xdoc)
        {
            var taxes = xdoc.Root.Elements().Where(e => e.Name.LocalName == "TaxTotal").ToArray();

            List <TaxTotal> _taxesTotales = new List <TaxTotal>();
            bool            error         = false;

            foreach (var tax in taxes)
            {
                List <TaxSubtotal> _subtotals = new List <TaxSubtotal>();
                string             _taxAmount = string.Empty;

                var subtotals = tax.Elements().Where(e => e.Name.LocalName == "TaxSubtotal").ToArray();

                foreach (var subtotal in subtotals)
                {
                    //TaxCategory _categories
                    string _schemeId = string.Empty;
                    string _percent  = string.Empty;

                    var category = subtotal.Elements().Where(e => e.Name.LocalName == "TaxCategory").SingleOrDefault();

                    if (category == null)
                    {
                        error = true;
                        break;
                    }

                    var schemeId = category.Elements().Where(e => e.Name.LocalName == "TaxScheme").SingleOrDefault()?
                                   .Elements().Where(e => e.Name.LocalName == "ID").SingleOrDefault();

                    if (schemeId == null || schemeId.Value == string.Empty)
                    {
                        error = true;
                        break;
                    }

                    var percent = category.Elements().Where(e => e.Name.LocalName == "Percent").SingleOrDefault();

                    if (percent == null || percent.Value == string.Empty)
                    {
                        error = true;
                        break;
                    }

                    _schemeId = schemeId.Value;
                    _percent  = percent.Value;

                    TaxCategory c = new TaxCategory
                    {
                        SchemeID = _schemeId,
                        Percent  = _percent
                    };

                    string _subtotalTaxAmount = string.Empty;
                    var    subTotaltaxAmount  = subtotal.Elements().Where(e => e.Name.LocalName == "TaxAmount").SingleOrDefault();

                    if (subTotaltaxAmount == null || subTotaltaxAmount.Value == string.Empty)
                    {
                        error = true;
                        break;
                    }

                    _subtotalTaxAmount = subTotaltaxAmount.Value;

                    TaxSubtotal s = new TaxSubtotal
                    {
                        TaxCategory = c,
                        TaxAmount   = _subtotalTaxAmount
                    };

                    _subtotals.Add(s);
                }

                if (error)
                {
                    break;
                }

                var taxAmount = tax.Elements().Where(e => e.Name.LocalName == "TaxAmount").SingleOrDefault();

                if (taxAmount == null || taxAmount.Value == string.Empty)
                {
                    error = true;
                    break;
                }

                _taxAmount = taxAmount.Value;

                TaxTotal t = new TaxTotal
                {
                    TaxesSubtotals = _subtotals,
                    TaxAmount      = _taxAmount
                };

                _taxesTotales.Add(t);
            }

            if (error)
            {
                _taxesTotales.Clear();
            }

            return(_taxesTotales);
            //TaxesTotales = new List<TaxTotal>(_taxesTotales);
        }
Ejemplo n.º 9
0
        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);
        }