Example #1
0
        private DataTable FnTablaEmisor(CreditNoteType ocomprobante)
        {
            DataTable dtEmisor = new DataTable();

            dtEmisor.Columns.Add(new DataColumn("RucEmisor", typeof(string)));
            dtEmisor.Columns.Add(new DataColumn("RazonSocialEmisor", typeof(string)));
            dtEmisor.Columns.Add(new DataColumn("NombreComercialEmisor", typeof(string)));
            dtEmisor.Columns.Add(new DataColumn("DepartamentoEmisor", typeof(string)));
            dtEmisor.Columns.Add(new DataColumn("ProvinciaEmisor", typeof(string)));
            dtEmisor.Columns.Add(new DataColumn("DistritoEmisor", typeof(string)));
            dtEmisor.Columns.Add(new DataColumn("DireccionEmisor", typeof(string)));

            DataRow fila;

            fila = dtEmisor.NewRow();

            if (ocomprobante.AccountingSupplierParty != null)
            {
                fila["RucEmisor"]             = FnValidarNulo(ocomprobante.AccountingSupplierParty.Party.PartyIdentification[0].ID.Value.ToString());
                fila["RazonSocialEmisor"]     = FnValidarNulo(ocomprobante.AccountingSupplierParty.Party.PartyLegalEntity[0].RegistrationName.Value.ToString());
                fila["NombreComercialEmisor"] = FnValidarNulo(ocomprobante.AccountingSupplierParty.Party.PartyName[0].Name.Value.ToString());
                fila["DepartamentoEmisor"]    = FnValidarNulo(ocomprobante.AccountingSupplierParty.Party.PartyLegalEntity[0].RegistrationAddress.CountrySubentity.Value.ToString());
                fila["ProvinciaEmisor"]       = FnValidarNulo(ocomprobante.AccountingSupplierParty.Party.PartyLegalEntity[0].RegistrationAddress.CityName.Value.ToString());
                fila["DistritoEmisor"]        = FnValidarNulo(ocomprobante.AccountingSupplierParty.Party.PartyLegalEntity[0].RegistrationAddress.District.Value.ToString());
                fila["DireccionEmisor"]       = FnValidarNulo(ocomprobante.AccountingSupplierParty.Party.PartyLegalEntity[0].RegistrationAddress.AddressLine[0].Line.Value.ToString());
            }

            dtEmisor.Rows.Add(fila);

            return(dtEmisor);
        }
Example #2
0
        public static string GenerarXML(CreditNoteType item)
        {
            XmlSerializer           serializer = new XmlSerializer(typeof(CreditNoteType));
            XmlSerializerNamespaces oxmlnames  = new XmlSerializerNamespaces();

            oxmlnames.Add("", "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2");
            oxmlnames.Add("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
            oxmlnames.Add("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
            oxmlnames.Add("ccts", "urn:un:unece:uncefact:documentation:2");
            oxmlnames.Add("ds", "http://www.w3.org/2000/09/xmldsig#");
            oxmlnames.Add("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
            oxmlnames.Add("qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
            oxmlnames.Add("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
            oxmlnames.Add("udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
            oxmlnames.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            MemoryStream ms = new MemoryStream();

            serializer.Serialize(ms, item, oxmlnames);
            ms.Position = 0;

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            xmlDocument.Load(ms);

            XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);

            xmlDocument.ReplaceChild(xmlDeclaration, xmlDocument.FirstChild);

            return(xmlDocument.OuterXml);
        }
Example #3
0
        void LlenarMontosIGV(En_ComprobanteElectronico Comprobante, ref CreditNoteType creditNote)
        {
            List <TaxSubtotalType> oListaSubtotal = new List <TaxSubtotalType>();

            if (Comprobante.MontoTotales != null)
            {
                if (Comprobante.MontoTotales.Gravado != null)
                {
                    if (Comprobante.MontoTotales.Gravado.GravadoIGV != null)
                    {
                        TaxSubtotalType oTotalGravado = LlenarSubTotalCabecera(Comprobante.MontoTotales.Gravado.GravadoIGV.MontoBase, Comprobante.MontoTotales.Gravado.GravadoIGV.MontoTotalImpuesto, Comprobante.Moneda, Comprobante.MontoTotales.Gravado.GravadoIGV.Porcentaje, "1000", "IGV", "VAT");
                        oListaSubtotal.Add(oTotalGravado);
                    }
                }
            }


            TaxTotalType oTaxTotal = new TaxTotalType
            {
                TaxAmount = new TaxAmountType
                {
                    Value      = Comprobante.TotalImpuesto,
                    currencyID = Comprobante.Moneda
                },
                TaxSubtotal = oListaSubtotal.ToArray()
            };

            creditNote.TaxTotal = new TaxTotalType[] { oTaxTotal };
        }
Example #4
0
        void LlenarMontosTotales(En_ComprobanteElectronico Comprobante, ref CreditNoteType creditNote)
        {
            MonetaryTotalType oTotal = new MonetaryTotalType
            {
                LineExtensionAmount = new LineExtensionAmountType
                {
                    Value      = Comprobante.TotalValorVenta,
                    currencyID = Comprobante.Moneda.Trim()
                },
                TaxInclusiveAmount = new TaxInclusiveAmountType
                {
                    Value      = Comprobante.TotalPrecioVenta,
                    currencyID = Comprobante.Moneda.Trim()
                },
                PayableAmount = new PayableAmountType
                {
                    Value      = Comprobante.ImporteTotal,
                    currencyID = Comprobante.Moneda.Trim()
                },
                ChargeTotalAmount = new ChargeTotalAmountType
                {
                    Value      = Comprobante.TotalCargo,
                    currencyID = Comprobante.Moneda.Trim()
                },
                AllowanceTotalAmount = new AllowanceTotalAmountType
                {
                    Value      = Comprobante.TotalDescuento,
                    currencyID = Comprobante.Moneda.Trim()
                }
            };

            creditNote.LegalMonetaryTotal = oTotal;
        }
        public CreditNoteType CreateCreditNote(string vknTckn, DateTime tarih1)
        {
            Random rnd        = new Random();
            int    lineNumber = rnd.Next(1, 10);

            eMm = GetCreditHeader(lineNumber, tarih1);
            eMm.AdditionalDocumentReference = GetDocumentReference();
            eMm.Signature = GetSignature();
            switch (vknTckn.Length)
            {
            case 10:
                eMm.AccountingSupplierParty = GetSupplierParty(vknTckn, "VKN");
                eMm.AccountingCustomerParty = GetCustomerParty(vknTckn, "VKN");
                break;

            case 11:
                eMm.AccountingSupplierParty = GetSupplierParty(vknTckn, "TCKN");
                eMm.AccountingCustomerParty = GetCustomerParty(vknTckn, "TCKN");
                break;
            }


            eMm.Delivery           = GetDelivery();
            eMm.CreditNoteLine     = GetCreditNoteLine(lineNumber);
            eMm.LegalMonetaryTotal = LegalMonetaryTotal();
            return(eMm);
        }
Example #6
0
        private DataTable FnTablaDetalle(CreditNoteType ocomprobante)
        {
            DataTable dtDetalle = new DataTable();

            dtDetalle.Columns.Add(new DataColumn("Item", typeof(string)));
            dtDetalle.Columns.Add(new DataColumn("Descripcion", typeof(string)));
            dtDetalle.Columns.Add(new DataColumn("UM", typeof(string)));
            dtDetalle.Columns.Add(new DataColumn("VU", typeof(string)));
            dtDetalle.Columns.Add(new DataColumn("PU", typeof(string)));
            dtDetalle.Columns.Add(new DataColumn("Cantidad", typeof(string)));
            dtDetalle.Columns.Add(new DataColumn("ImporteSinIGV", typeof(string)));

            DataRow fila;

            fila = dtDetalle.NewRow();

            if (ocomprobante.CreditNoteLine != null)
            {
                foreach (CreditNoteLineType detalle in ocomprobante.CreditNoteLine)
                {
                    fila["Item"]          = FnValidarNulo(detalle.ID.Value.ToString());
                    fila["Descripcion"]   = FnValidarNulo(detalle.Item.Description[0].Value.ToString());
                    fila["UM"]            = "UND";
                    fila["VU"]            = FnValidarNulo(detalle.PricingReference.AlternativeConditionPrice[0].PriceAmount.Value.ToString());
                    fila["PU"]            = FnValidarNulo(detalle.PricingReference.AlternativeConditionPrice[0].PriceAmount.Value.ToString());
                    fila["Cantidad"]      = FnValidarNulo(detalle.CreditedQuantity.Value.ToString());
                    fila["ImporteSinIGV"] = FnValidarNulo(detalle.LineExtensionAmount.Value.ToString());
                }
            }

            dtDetalle.Rows.Add(fila);

            return(dtDetalle);
        }
Example #7
0
        void CrearXML(ref CreditNoteType creditNote, En_ComprobanteElectronico Comprobante, ref string codigoHASH, ref byte[] archivoXML, ref string firma)
        {
            XmlSerializer oxmlSerializer  = new XmlSerializer(typeof(CreditNoteType));
            var           xmlNameSpaceNom = new XmlSerializerNamespaces();

            xmlNameSpaceNom.Add("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
            xmlNameSpaceNom.Add("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
            xmlNameSpaceNom.Add("ccts", "urn:un:unece:uncefact:documentation:2");
            xmlNameSpaceNom.Add("ds", "http://www.w3.org/2000/09/xmldsig#");
            xmlNameSpaceNom.Add("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
            xmlNameSpaceNom.Add("qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
            xmlNameSpaceNom.Add("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
            xmlNameSpaceNom.Add("udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
            xmlNameSpaceNom.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            string carpetaTemp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temporal");
            string nombreXml   = string.Format("{0}-{1}-{2}.xml", Comprobante.Emisor.NumeroDocumentoIdentidad, Comprobante.TipoComprobante, Comprobante.SerieNumero);
            string ruta        = Path.Combine(carpetaTemp, nombreXml);

            string            sxml      = "";
            Encoding          utf8noBOM = new UTF8Encoding(false);
            XmlWriterSettings settings  = new XmlWriterSettings
            {
                Indent   = true,
                Encoding = utf8noBOM
            };

            // Se ha creado una nueva clase llamada StringWriterWithEncoding que grabaen formato UTF-8
            // Por defecto la clase StringWriter graba con UTF-16 y no se podía firmar, con UTF-8 ya se puede
            using (var sw = new StringWriterWithEncoding())
            {
                using (XmlWriter writter = XmlWriter.Create(sw, settings))
                {
                    oxmlSerializer.Serialize(writter, creditNote, xmlNameSpaceNom);
                    sxml = sw.ToString();
                }
            }

            // Se elimina el tag temporal creado dentro de ext:ExtensionContent y en su lugar se colocará la firma
            string cadena  = "<Borrar xmlns=\"\" />";
            int    tamanio = cadena.Length;
            int    indice  = sxml.IndexOf(cadena);

            sxml = sxml.Remove(indice, tamanio);

            // Se sigue grabando el archivo como siempre
            File.WriteAllText(ruta, sxml, Encoding.UTF8);

            // Firma del comprobante
            var objFirma = new Firma.FirmaComprobante();
            var document = new XmlDocument();

            document.Load(ruta);
            // Enviamos el RUC de la empresa, para ello el certificado debe estar registrado
            objFirma.FirmarXml(document, Comprobante.Emisor.NumeroDocumentoIdentidad, ref codigoHASH, ref firma);
            document.Save(ruta);

            archivoXML = File.ReadAllBytes(ruta);
        }
Example #8
0
        public async Task create_creditnote()
        {
            const CreditNoteType expected = CreditNoteType.AccountsReceivable;

            var type = (await Given_a_creditnote(type: expected)).Type;

            Assert.AreEqual(expected, type);
        }
Example #9
0
        public void create_creditnote()
        {
            const CreditNoteType expected = CreditNoteType.AccountsReceivable;

            var type = Given_a_creditnote(type: expected).Type;

            Assert.AreEqual(expected, type);
        }
        private CreditNoteType GetCreditHeader(int lineNumber, DateTime tarih1)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<xml />");
            var eMM = new CreditNoteType
            {
                UBLExtensions = new[]  //UBL Dijital İmza Düğümü
                {
                    new UBLExtensionType
                    {
                        ExtensionContent = doc.DocumentElement
                    }
                },
                UBLVersionID = new UBLVersionIDType {
                    Value = "2.1"
                },
                CustomizationID = new CustomizationIDType {
                    Value = "TR1.2.1"
                },
                ProfileID = new ProfileIDType {
                    Value = "EARSIVBELGE"
                },
                ID = new IDType {
                    Value = "FM02020000000001"
                },                                             //Eğer Sovos Foriba tarafından otomatik üretilmeyecekse Fatura ID generate edilecek şekilde düzenlenmelidir.
                CopyIndicator = new CopyIndicatorType {
                    Value = false
                },
                UUID = new UUIDType {
                    Value = Guid.NewGuid().ToString()
                },
                IssueDate = new IssueDateType {
                    Value = tarih1
                },
                IssueTime = new IssueTimeType {
                    Value = default(DateTime).AddHours(11).AddMinutes(20)
                },
                CreditNoteTypeCode = new CreditNoteTypeCodeType {
                    Value = "MUSTAHSILMAKBUZ"
                },
                DocumentCurrencyCode = new DocumentCurrencyCodeType {
                    Value = "TRY"
                },
                Note = new[]
                {
                    new NoteType {
                        Value = "MÜSTAHSİL MAKBUZU"
                    }
                },
                LineCountNumeric = new LineCountNumericType {
                    Value = lineNumber
                }
            };

            return(eMM);
        }
Example #11
0
        public void ReadNorwegianCreditNote()
        {
            string         filename = "BII05 T14 0 gyldig kreditnota med alle elementer.xml";
            CreditNoteType doc      = UblDoc <CreditNoteType> .Create(filename);

            Assert.AreEqual("5645342123", doc.AccountingCustomerParty.Party.PartyLegalEntity[0].CompanyID.Value);
            bool areEqual = UblXmlComparer.IsCopyEqual <CreditNoteType>(filename, doc);

            Assert.IsTrue(areEqual, "Written UBL doc differs from original");
        }
Example #12
0
        public void ReadCreditNote()
        {
            string         filename = "UBL-CreditNote-2.0-Example.xml";
            CreditNoteType doc      = UblDoc <CreditNoteType> .Create(filename);

            string value = doc.AccountingCustomerParty.Party.PartyName[0].Name;

            Assert.AreEqual("IYT Corporation", value);

            bool areEqual = UblXmlComparer.IsCopyEqual <CreditNoteType>(filename, doc);

            Assert.IsTrue(areEqual, "Written UBL doc differs from original");
        }
Example #13
0
        private DataTable FnTablaReferenciadoCreditNote(CreditNoteType ocomprobante)
        {
            DataTable dtSustento = new DataTable();

            dtSustento.Columns.Add(new DataColumn("DocumentoReferenciado", typeof(string)));
            dtSustento.Columns.Add(new DataColumn("TipoDocumentoReferenciado", typeof(string)));
            dtSustento.Columns.Add(new DataColumn("Sustento", typeof(string)));


            DataRow fila;

            fila = dtSustento.NewRow();


            if (ocomprobante.BillingReference != null)
            {
                foreach (BillingReferenceType oreferencia in ocomprobante.BillingReference)
                {
                    DocumentReferenceType oDocument = oreferencia.InvoiceDocumentReference;

                    fila["DocumentoReferenciado"] = FnValidarNulo(oDocument.ID.Value.ToString());

                    if (oDocument.DocumentTypeCode.Value.ToString() == "01")
                    {
                        fila["TipoDocumentoReferenciado"] = "Factura";
                    }
                    else if (oDocument.DocumentTypeCode.Value.ToString() == "03")
                    {
                        fila["TipoDocumentoReferenciado"] = "Boleta";
                    }
                }
            }

            if (ocomprobante.DiscrepancyResponse != null)
            {
                foreach (ResponseType oreferencia in ocomprobante.DiscrepancyResponse)
                {
                    DescriptionType[] oDocument = oreferencia.Description;
                    string            sustento  = "";
                    foreach (DescriptionType valor in oDocument)
                    {
                        sustento += valor.Value.ToString() + Environment.NewLine;
                    }
                    fila["Sustento"] = sustento;
                }
            }

            dtSustento.Rows.Add(fila);

            return(dtSustento);
        }
Example #14
0
        public En_Respuesta RegistroComprobante(En_ComprobanteElectronico Comprobante)
        {
            log.Info("Invocación al método RegistroComprobante");
            En_Respuesta oRespuesta = new En_Respuesta();
            string       rutaXML    = "";

            try
            {
                CreditNoteType creditNote = new CreditNoteType();
                LlenarCabecera(Comprobante, ref creditNote);
                LlenarDocumentoRefenciado(Comprobante, ref creditNote);
                LlenarEmisor(Comprobante.Emisor, ref creditNote);
                LlenarReceptor(Comprobante.Receptor, ref creditNote);
                LlenarDescuentoCargo(Comprobante, ref creditNote);
                LlenarMontosIGV(Comprobante, ref creditNote);
                LlenarMontosTotales(Comprobante, ref creditNote);
                LlenarDetalle(Comprobante, ref creditNote);

                string codigoHASH = "", nombreXML = "", firma = "";
                byte[] archivoXML = null;
                nombreXML = string.Format("{0}-{1}-{2}.xml", Comprobante.Emisor.NumeroDocumentoIdentidad, Comprobante.TipoComprobante, Comprobante.SerieNumero);
                CrearXML(ref creditNote, Comprobante, ref codigoHASH, ref archivoXML, ref firma);

                string         mensajeRetorno = "";
                Lp_Comprobante lpComprobante  = new Lp_Comprobante();
                bool           resultado      = lpComprobante.InsertarComprobante(Comprobante, nombreXML, archivoXML, codigoHASH, firma, ref mensajeRetorno);

                oRespuesta.Codigo      = (resultado) ? "0" : "99";
                oRespuesta.Descripcion = mensajeRetorno;

                string carpetaTemp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temporal");
                rutaXML = Path.Combine(carpetaTemp, nombreXML);
                if (File.Exists(rutaXML))
                {
                    File.Delete(rutaXML);
                }
            }
            catch (Exception ex)
            {
                oRespuesta.Codigo      = "99";
                oRespuesta.Descripcion = "Ocurrió un error general, mensaje: " + ex.Message.ToString();
                if (rutaXML != "" && File.Exists(rutaXML))
                {
                    File.Delete(rutaXML);
                }
            }
            return(oRespuesta);
        }
Example #15
0
 public CreditNote Given_a_creditnote(CreditNoteType type = CreditNoteType.AccountsPayable)
 {
     return Api.CreditNotes.Create(new CreditNote
     {
         Contact = new Contact { Name = "Apple Computers Ltd" },
         Type = type,
         Date = DateTime.UtcNow,
         LineAmountTypes = LineAmountType.Exclusive,
         LineItems = new List<LineItem>
         {
             new LineItem
             {
                 AccountCode = "720",
                 Description = "MacBook - White",
                 UnitAmount = 1995.00m
             }
         }
     });
 }
Example #16
0
 public Task<CreditNote> Given_a_creditnote(string contactName = "Apple Computers Ltd", CreditNoteType type = CreditNoteType.AccountsPayable, InvoiceStatus status = InvoiceStatus.Draft)
 {
     return Api.CreditNotes.CreateAsync(new CreditNote
     {
         Contact = new Contact { Name = contactName },
         Type = type,
         Date = DateTime.UtcNow,
         LineAmountTypes = LineAmountType.Exclusive,
         Status = status,
         LineItems = new List<LineItem>
         {
             new LineItem
             {
                 AccountCode = "720",
                 Description = "MacBook - White",
                 UnitAmount = 1995.00m
             }
         }
     });
 }
Example #17
0
        void LlenarDescuentoCargo(En_ComprobanteElectronico Comprobante, ref CreditNoteType creditNote)
        {
            List <AllowanceChargeType> oListaDescuentoCargo = new List <AllowanceChargeType>();

            foreach (En_DescuentoCargo oDescar in Comprobante.DescuentoCargo)
            {
                AllowanceChargeType oDescuentoCargo = new AllowanceChargeType
                {
                    ChargeIndicator = new ChargeIndicatorType
                    {
                        Value = oDescar.Indicador
                    },
                    AllowanceChargeReasonCode = new AllowanceChargeReasonCodeType
                    {
                        listAgencyName = "PE:SUNAT",
                        listName       = "Cargo/descuento",
                        listURI        = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo53",
                        Value          = oDescar.CodigoMotivo
                    },
                    MultiplierFactorNumeric = new MultiplierFactorNumericType
                    {
                        Value = oDescar.Factor
                    },
                    Amount = new AmountType2
                    {
                        Value      = oDescar.MontoTotal,
                        currencyID = Comprobante.Moneda.Trim()
                    },
                    BaseAmount = new BaseAmountType
                    {
                        Value      = oDescar.MontoBase,
                        currencyID = Comprobante.Moneda.Trim()
                    }
                };
                oListaDescuentoCargo.Add(oDescuentoCargo);
            }
            creditNote.AllowanceCharge = oListaDescuentoCargo.ToArray();
        }
Example #18
0
        void LlenarCabecera(En_ComprobanteElectronico Comprobante, ref CreditNoteType creditNote)
        {
            UBLExtensionType uBLExtensionType = new UBLExtensionType()
            {
                // Se crea un tag temporal llamado "Borrar", esto porque no he conseguido crear el tag
                // ext:ExtensionContent con un valor vacío
                ExtensionContent = new XmlDocument().CreateElement("Borrar")
            };

            UBLExtensionType[] ublExtensions = { uBLExtensionType };
            creditNote.UBLExtensions = ublExtensions;
            //Serie y Numero
            creditNote.ID = new IDType
            {
                Value = Comprobante.SerieNumero.Trim()
            };

            creditNote.UBLVersionID = new UBLVersionIDType
            {
                Value = "2.1"
            };

            creditNote.IssueDate = new IssueDateType
            {
                Value = Comprobante.FechaEmision
            };
            creditNote.IssueTime = new IssueTimeType
            {
                Value = Comprobante.HoraEmision
            };



            creditNote.DocumentCurrencyCode = new DocumentCurrencyCodeType
            {
                listAgencyName = "United Nations Economic Commission for Europe",
                listID         = "ISO 4217 Alpha",
                listName       = "Currency",
                Value          = Comprobante.Moneda.Trim()
            };

            List <NoteType> oListaNota = new List <NoteType>();

            foreach (En_Leyenda oNote in Comprobante.Leyenda)
            {
                NoteType oNota = new NoteType
                {
                    Value            = oNote.Valor,
                    languageLocaleID = oNote.Codigo
                };
                oListaNota.Add(oNota);
            }
            ;

            creditNote.Note = oListaNota.ToArray();

            creditNote.CustomizationID = new CustomizationIDType
            {
                Value = "2.0"
            };



            List <DocumentReferenceType> oListadocumento = new List <DocumentReferenceType>();

            foreach (En_DocumentoReferencia oreferen in Comprobante.DocumentoReferenciaDespacho)
            {
                DocumentReferenceType odocumento = new DocumentReferenceType
                {
                    ID = new IDType
                    {
                        Value = oreferen.SerieNumero.Trim()
                    },
                    IssueDate = new IssueDateType
                    {
                        Value = oreferen.Fecha.Trim()
                    },
                    DocumentTypeCode = new DocumentTypeCodeType
                    {
                        Value          = oreferen.TipoDocumento.Trim(),
                        listAgencyName = "PE:SUNAT",
                        listName       = "SUNAT:Identificador de guía relacionada",
                        listURI        = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo12"
                    }
                };
                oListadocumento.Add(odocumento);
            }
            ;
            creditNote.DespatchDocumentReference = oListadocumento.ToArray();
        }
Example #19
0
        void LlenarDocumentoRefenciado(En_ComprobanteElectronico Comprobante, ref CreditNoteType creditNote)
        {
            if (Comprobante.DocumentoSustentoNota != null)
            {
                creditNote.DiscrepancyResponse = new ResponseType[]
                {
                    new ResponseType {
                        Description = new DescriptionType[] {
                            new DescriptionType
                            {
                                Value = Comprobante.DocumentoSustentoNota.MotivoAnulacion
                            }
                        },
                        ResponseCode = new ResponseCodeType
                        {
                            listName       = "Tipo de nota de credito",
                            listAgencyName = "PE:SUNAT",
                            listURI        = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo09",
                            Value          = Comprobante.DocumentoSustentoNota.CodigoMotivoAnulacion
                        },
                        ReferenceID = new ReferenceIDType {
                            Value = Comprobante.DocumentoSustentoNota.SerieNumero
                        }
                    }
                };
            }

            if (Comprobante.DocumentoReferenciaNota != null)
            {
                List <BillingReferenceType> oListaReferencia = new List <BillingReferenceType>();

                foreach (En_DocumentoReferenciaNota oDoc in Comprobante.DocumentoReferenciaNota)
                {
                    BillingReferenceType oreferencia = new BillingReferenceType();
                    oreferencia.InvoiceDocumentReference = new DocumentReferenceType
                    {
                        ID = new IDType
                        {
                            Value = oDoc.SerieNumero
                        },
                        IssueDate = new IssueDateType
                        {
                            Value = oDoc.Fecha
                        },
                        DocumentTypeCode = new DocumentTypeCodeType
                        {
                            listName       = "Tipo de Documento",
                            listAgencyName = "PE:SUNAT",
                            listURI        = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo01",
                            Value          = oDoc.TipoDocumento
                        }
                    };

                    oListaReferencia.Add(oreferencia);
                }

                if (oListaReferencia.Count > 0)
                {
                    creditNote.BillingReference = oListaReferencia.ToArray();
                }
            }
        }
Example #20
0
 public CreditNote Given_a_draft_creditnote(CreditNoteType type = CreditNoteType.AccountsPayable)
 {
     return Given_a_creditnote(type: type);
 }
Example #21
0
 public CreditNote Given_an_authorised_creditnote(CreditNoteType type = CreditNoteType.AccountsPayable)
 {
     return Given_a_creditnote(type: type, status: InvoiceStatus.Authorised);
 }
Example #22
0
        void LlenarReceptor(En_Receptor Receptor, ref CreditNoteType creditNote)
        {
            WebsiteURIType EmisorPaginaWeb = new WebsiteURIType
            {
                Value = Receptor.PaginaWeb.Trim()
            };

            List <PartyNameType> oListaNombreComercial = new List <PartyNameType>();
            PartyNameType        PartyName             = new PartyNameType
            {
                Name = new NameType1
                {
                    Value = Receptor.NombreComercial.Trim()
                }
            };

            oListaNombreComercial.Add(PartyName);


            PartyIdentificationType        EmisorIdentificacion      = new PartyIdentificationType();
            List <PartyIdentificationType> EmisorListaIdentificacion = new List <PartyIdentificationType>();

            EmisorIdentificacion.ID = new IDType
            {
                Value          = Receptor.NumeroDocumentoIdentidad.Trim(),
                schemeAgencyID = "PE:SUNAT",
                schemeID       = Receptor.TipoDocumentoIdentidad.Trim(),
                schemeName     = "Documento de Identidad",
                schemeURI      = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06"
            };
            EmisorListaIdentificacion.Add(EmisorIdentificacion);

            //Razon social
            PartyLegalEntityType oRazonSocial = new PartyLegalEntityType
            {
                RegistrationName = new RegistrationNameType
                {
                    Value = Receptor.RazonSocial,
                },

                RegistrationAddress = new AddressType
                {
                    ID = new IDType
                    {
                        Value            = Receptor.CodigoUbigeo.Trim(),
                        schemeAgencyName = "PE:INEI",
                        schemeName       = "Ubigeos"
                    },
                    AddressTypeCode = new AddressTypeCodeType
                    {
                        Value          = Receptor.CodigoDomicilioFiscal.Trim(),
                        listAgencyName = "PE:SUNAT",
                        listName       = "Establecimientos anexos"
                    },
                    CitySubdivisionName = new CitySubdivisionNameType
                    {
                        Value = Receptor.Urbanizacion.Trim()
                    },
                    CityName = new CityNameType
                    {
                        Value = Receptor.Provincia.Trim()
                    },
                    CountrySubentity = new CountrySubentityType
                    {
                        Value = Receptor.Departamento.Trim()
                    },
                    District = new DistrictType
                    {
                        Value = Receptor.Distrito.Trim()
                    },
                    AddressLine = new AddressLineType[] {
                        new AddressLineType {
                            Line = new LineType {
                                Value = Receptor.Direccion.Trim()
                            }
                        }
                    },
                    Country = new CountryType
                    {
                        IdentificationCode = new IdentificationCodeType
                        {
                            listAgencyName = "United Nations Economic Commission for Europe",
                            listID         = "ISO 3166-1",
                            listName       = "Country",
                            Value          = Receptor.CodigoPais.Trim()
                        }
                    }
                }
            };

            ContactType oContacto = new ContactType
            {
                ElectronicMail = new ElectronicMailType()
                {
                    Value = Receptor.Contacto.Correo.Trim()
                },
                Name = new NameType1
                {
                    Value = Receptor.Contacto.Nombre.Trim()
                },
                Telephone = new TelephoneType
                {
                    Value = Receptor.Contacto.Telefono.Trim()
                }
            };

            CustomerPartyType oReceptor = new CustomerPartyType
            {
                Party = new PartyType
                {
                    WebsiteURI          = EmisorPaginaWeb,
                    PartyIdentification = EmisorListaIdentificacion.ToArray(),
                    PartyName           = oListaNombreComercial.ToArray(),
                    PartyLegalEntity    = new PartyLegalEntityType[] { oRazonSocial },
                    Contact             = oContacto
                }
            };

            creditNote.AccountingCustomerParty = oReceptor;
        }
Example #23
0
        public bool GenerateXML()
        {
            bool isGenerated = false;

            try
            {
                MS.GeneraLog.GeneracionXML("-----  Inicio de Generación de Archivo: " + MS.XMLIFileLocation);
                XmlSerializer           mySerializer = new XmlSerializer(typeof(CreditNoteType));
                XmlSerializerNamespaces ns           = getNamespaces();
                XmlWriterSettings       setting      = getSettings();

                CreditNoteType cre = new CreditNoteType();
                cre.AccountingSupplierParty = getSupplierPartyType();
                cre.AccountingCustomerParty = getAccountingCustomerParty();
                cre.Signature       = getSignatureType();
                cre.UBLVersionID    = getUBLVersionID();
                cre.CustomizationID = getCustomizationID();
                cre.ID                   = getID();
                cre.IssueDate            = getIssueDate();
                cre.DiscrepancyResponse  = getDiscrepancyResponseType();
                cre.BillingReference     = getBillingReferenceType();
                cre.DocumentCurrencyCode = getDocumentCurrencyCode();
                cre.LegalMonetaryTotal   = getLegalMonetaryTotal();
                cre.CreditNoteLine       = getCreditNoteLine();
                cre.UBLExtensions        = getUBLExtensions();

                if (VD.Taxes.Count > 0)
                {
                    cre.TaxTotal = getTaxTotal();
                }

                cre.AdditionalDocumentReference = getAdditionalDocumentReferenceType();
                cre.DespatchDocumentReference   = getDespatchDocumentReferenceType();
                cre.OrderReference = getOrderReferenceType();

                XMLI = ObjectToXml(cre, ns);

                XMLI = XMLI.Replace("&lt;", "<");
                XMLI = XMLI.Replace("&gt;", ">");
                XMLI = XMLI.Replace("encoding=\"utf-16\"", "encoding=\"ISO-8859-1\"");
                XMLI = XMLI.Replace("q1:CreditNote", "CreditNote");
                XMLI = XMLI.Replace("q1", "CreditNote");
                XMLI = XMLI.Replace("xmlns=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\"", "");
                XMLI = XMLI.Replace("xmlns:CreditNote", "xmlns");

                XMLI = XMLI.Replace("&amp;", "&");

                using (StreamWriter sw = new StreamWriter(MS.XMLIFileLocation, false, ISO_8859_1))
                {
                    sw.Write(XMLI);
                }

                SXMLI = GenerateStreamFromString(XMLI);

                isGenerated = true;
            }
            catch (Exception ex)
            {
                MS.GeneraLog.GeneracionXML("Ocurrió un error al momento de general el XML Inicial");
                MS.GeneraLog.GeneracionXML("Error: " + ex.Message);
            }
            return(isGenerated);
        }
Example #24
0
 public void ReadWrongDocTypeByMistake()
 {
     string         filename = "UBL-Invoice-2.0-Example.xml"; // This is not a credit note, next codeline must fail
     CreditNoteType doc      = UblDoc <CreditNoteType> .Create(filename);
 }
Example #25
0
 public async Task <CreditNote> Given_a_draft_creditnote(CreditNoteType type = CreditNoteType.AccountsPayable)
 {
     return(await Given_a_creditnote(type : type));
 }
Example #26
0
 public async Task <CreditNote> Given_an_authorised_creditnote(CreditNoteType type = CreditNoteType.AccountsPayable)
 {
     return(await Given_a_creditnote(type : type, status : InvoiceStatus.Authorised));
 }
        public void SaveImplicitCreatedNorwegianCreditNote()
        {
            Func <decimal, AmountType> newAmountType = v => new AmountType {
                Value = v, currencyID = "NOK"
            };

            // Set global defaults for Ubl documents that get created
            var customizationID = "urn:www.cenbii.eu:transaction:BiiCoreTrdm001:ver1.0:extentionId";
            var profileID       = "urn:www.cenbii.eu:profile:bii05:ver1.0";

            // Set thread local default for all amounts types decending from AmountType
            //Ubl2.Udt.AmountType.TlsDefaultCurrencyID = "NOK";

            // Create a serializable CreditNote instance.
            CreditNoteType doc = new CreditNoteType();

            doc.CustomizationID = customizationID;
            doc.ProfileID       = profileID;
            doc.ID                   = "654321";
            doc.UBLVersionID         = "2.0";
            doc.DocumentCurrencyCode = "NOK";
            doc.IssueDate            = new DateTime(2009, 11, 12, 0, 0, 0, DateTimeKind.Utc);

            // <cac:BillingReference>
            //   <cac:InvoiceDocumentReference>
            //     <cbc:ID>123456</cbc:ID>
            //   </cac:InvoiceDocumentReference>
            // </cac:BillingReference>
            // Becomes:
            doc.BillingReference = new BillingReferenceType[]
            {
                new BillingReferenceType {
                    InvoiceDocumentReference = new DocumentReferenceType {
                        ID = "123456"
                    }
                }
            };

            doc.AccountingSupplierParty = new SupplierPartyType
            {
                Party = new PartyType
                {
                    PartyName = new [] { new PartyNameType {
                                             Name = "Leverandør"
                                         } },
                    PostalAddress = new AddressType
                    {
                        Postbox        = "Postboks 123",
                        StreetName     = "Oslogate",
                        BuildingNumber = "1",
                        CityName       = "Oslo",
                        PostalZone     = "0612",
                        Country        = new CountryType {
                            IdentificationCode = "NO"
                        }
                    },
                    PartyLegalEntity = new PartyLegalEntityType[] { new PartyLegalEntityType {
                                                                        CompanyID = "NO999999999MVA"
                                                                    } },
                    Contact = new ContactType {
                        ID = "O Hansen"
                    },
                }
            };

            // Populating class instance the old way but are still using implicit operator assingnment functions
            doc.AccountingCustomerParty = new CustomerPartyType();
            PartyType p = new PartyType();

            doc.AccountingCustomerParty.Party = p;
            p.PartyIdentification             = new [] { new PartyIdentificationType {
                                                             ID = "456789"
                                                         } };
            p.PartyName    = new PartyNameType[1];
            p.PartyName[0] = new PartyNameType {
                Name = "Kjøper"
            };
            p.PostalAddress                            = new AddressType();
            p.PostalAddress.StreetName                 = "Testveien";
            p.PostalAddress.BuildingNumber             = "1";
            p.PostalAddress.CityName                   = "Frogner";
            p.PostalAddress.PostalZone                 = "2012";
            p.PostalAddress.Country                    = new CountryType();
            p.PostalAddress.Country.IdentificationCode = "NO"; // implicit operator called behind the scenes here
            //p.PostalAddress.Country.IdentificationCode = new CodeType { Value = "NO" };
            p.PartyLegalEntity = new PartyLegalEntityType[] { new PartyLegalEntityType() };
            p.PartyLegalEntity[0].CompanyID = "NO888888888MVA";
            p.Contact = new ContactType {
                ID = "3150bdn"
            };

            TaxTotalType tax = new TaxTotalType();

            doc.TaxTotal = new TaxTotalType[1] {
                tax
            };
            tax.TaxAmount   = newAmountType(112.0M);
            tax.TaxSubtotal = new TaxSubtotalType[1] {
                new TaxSubtotalType()
            };
            tax.TaxSubtotal[0].TaxableAmount = newAmountType(800.0M);
            tax.TaxSubtotal[0].TaxAmount     = newAmountType(112.0M);
            tax.TaxSubtotal[0].TaxCategory   = new TaxCategoryType
            {
                ID        = "AA",
                Percent   = 14.0M,
                TaxScheme = new TaxSchemeType {
                    ID = "VAT"
                }
            };

            doc.LegalMonetaryTotal = new MonetaryTotalType();
            doc.LegalMonetaryTotal.LineExtensionAmount = new AmountType {
                Value = 800.0M, currencyID = "AED"
            };                                                                                                  // Note difi.no doc use "AED" instead of DocumentCurrency code. QA slip.
            doc.LegalMonetaryTotal.TaxExclusiveAmount = new AmountType {
                Value = 800.0M, currencyID = "AED"
            };
            doc.LegalMonetaryTotal.TaxInclusiveAmount = new AmountType {
                Value = 912.0M, currencyID = "AED"
            };
            doc.LegalMonetaryTotal.PayableAmount = new AmountType {
                Value = 912.0M, currencyID = "AED"
            };

            doc.CreditNoteLine    = new CreditNoteLineType[1];
            doc.CreditNoteLine[0] = new CreditNoteLineType
            {
                ID = "1",
                CreditedQuantity = new QuantityType {
                    Value = 8, unitCode = "KGM"
                },
                LineExtensionAmount = newAmountType(800.0M),
                TaxTotal            = new TaxTotalType[] { new TaxTotalType {
                                                               TaxAmount = newAmountType(112.0M)
                                                           } },
                Item = new ItemType
                {
                    Name = "Matprodukt-1",
                    SellersItemIdentification = new ItemIdentificationType {
                        ID = "23456785"
                    },
                    ClassifiedTaxCategory = new TaxCategoryType[]
                    {
                        new TaxCategoryType
                        {
                            ID        = "S",
                            Percent   = 14.0M,
                            TaxScheme = new TaxSchemeType {
                                ID = "VAT"
                            }
                        }
                    }
                },
                Price = new PriceType {
                    PriceAmount = newAmountType(100.0M)
                }
            };

            // save the creditnote to xml
            string filename = "ImplicitCreatedNorwegianCreditNote.xml";

            UblDoc <CreditNoteType> .Save(filename, doc);

            // Compare it with a local copy grabbed from difi.no doc
            bool areEqual = UblXmlComparer.IsCopyEqual <CreditNoteType>("NorwegianCreditNoteFromDifiPdfDoc.xml", doc);

            Assert.AreEqual(areEqual, true, "Written UBL doc differs from original");
        }
Example #28
0
 public CreditNote Given_a_creditnote(string contactName = "Apple Computers Ltd", CreditNoteType type = CreditNoteType.AccountsPayable, InvoiceStatus status = InvoiceStatus.Draft)
 {
     return(Api.CreditNotes.Create(new CreditNote
     {
         Contact = new Contact {
             Name = contactName
         },
         Type = type,
         Date = DateTime.UtcNow,
         LineAmountTypes = LineAmountType.Exclusive,
         Status = status,
         LineItems = new List <LineItem>
         {
             new LineItem
             {
                 AccountCode = "720",
                 Description = "MacBook - White",
                 UnitAmount = 1995.00m
             }
         }
     }));
 }
Example #29
0
 public CreditNote Given_an_authorised_creditnote(CreditNoteType type = CreditNoteType.AccountsPayable)
 {
     return(Given_a_creditnote(type: type, status: InvoiceStatus.Authorised));
 }
Example #30
0
        public bool GuardarNotaCredito(NotaCreditoBe registro)
        {
            var cookieSS = Request.Headers.GetCookies("ss").FirstOrDefault();
            var user     = JsonConvert.DeserializeObject <dynamic>(cookieSS["ss"].Value);

            int?     notaCreditoId = null, nroComprobante = null;
            DateTime?fechaHoraEmision     = null;
            string   totalImporteEnLetras = null;
            bool     respuesta            = notaCreditoBl.GuardarNotaCredito(registro, out notaCreditoId, out nroComprobante, out fechaHoraEmision, out totalImporteEnLetras);

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

                    int empresaId = user.Usuario.Empresa.EmpresaId;

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

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

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

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

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

                    CreditNoteType creditNoteType = ComprobanteSunat.ObtenerComprobante(registro, ComprobanteSunat.VersionUBL._2_1);

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

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

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

                    string registroJsonString = JsonConvert.SerializeObject(registro);

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

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

                    bool existeCarpeta = Directory.Exists(rutaCarpetaSunatComprobantes);

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

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

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

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

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

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

                    File.WriteAllText(rutaLog, string.Join(Environment.NewLine, errors));
                }
            }
            return(respuesta);
        }
Example #31
0
 public CreditNote Given_a_draft_creditnote(CreditNoteType type = CreditNoteType.AccountsPayable)
 {
     return(Given_a_creditnote(type: type));
 }
Example #32
0
        /// <summary>
        /// Genera un documento XML para Notas de Credito.
        /// </summary>
        /// <param name="creditHeaderEntity">Entidad de Nota de Credito</param>
        /// <returns>Retorna el XML generado.</returns>
        public XmlFileResult GenerarDocumentoCreditNote(CreditNoteHeader creditHeaderEntity)
        {
            try
            {
                #region FileName
                string xmlFilename =
                    $"{creditHeaderEntity.RucEmisor}-07-{creditHeaderEntity.SerieDocumento}-{creditHeaderEntity.CorrelativoDocumento}";
                #endregion

                #region Gen CreditNote
                AmountType.TlsDefaultCurrencyID = creditHeaderEntity.CodigoMoneda;
                var creditDoc = new CreditNoteType
                {
                    ID                          = string.Concat(creditHeaderEntity.SerieDocumento, "-", creditHeaderEntity.CorrelativoDocumento),
                    IssueDate                   = creditHeaderEntity.FechaEmision,
                    DocumentCurrencyCode        = creditHeaderEntity.CodigoMoneda,
                    CustomizationID             = "1.0",
                    DespatchDocumentReference   = UtilsXmlDoc.DevuelveGuiasRemisionReferenciadas(creditHeaderEntity.GuiaRemisionReferencia),
                    AdditionalDocumentReference = UtilsXmlDoc.DevuelveDocumentosReferenciaNote(creditHeaderEntity),
                    DiscrepancyResponse         = new[]
                    {
                        new ResponseType
                        {
                            ReferenceID  = creditHeaderEntity.DocumentoRef,
                            ResponseCode = ((int)creditHeaderEntity.TipoNota).ToString("00"),
                            Description  = new TextType[]
                            {
                                creditHeaderEntity.Motivo
                            }
                        }
                    },
                    BillingReference = new[]
                    {
                        new BillingReferenceType
                        {
                            InvoiceDocumentReference = new DocumentReferenceType
                            {
                                ID = creditHeaderEntity.DocumentoRef,
                                DocumentTypeCode = ((int)creditHeaderEntity.TipoDocRef).ToString("00")
                            }
                        }
                    },
                    Signature = UtilsXmlDoc.GetSignature(creditHeaderEntity),
                    AccountingSupplierParty = UtilsXmlDoc.GetInfoEmisor(creditHeaderEntity),
                    AccountingCustomerParty = new CustomerPartyType
                    {
                        CustomerAssignedAccountID = creditHeaderEntity.NroDocCliente,
                        AdditionalAccountID       =
                            new IdentifierType[] { ((int)creditHeaderEntity.TipoDocumentoIdentidadCliente).ToString() },
                        Party = new PartyType
                        {
                            PostalAddress = string.IsNullOrWhiteSpace(creditHeaderEntity.DireccionCliente) ? null : new AddressType
                            {
                                StreetName = creditHeaderEntity.DireccionCliente
                            },
                            PartyLegalEntity = new[]
                            {
                                new PartyLegalEntityType
                                {
                                    RegistrationName = creditHeaderEntity.NombreRazonSocialCliente,
                                }
                            }
                        },
                    },
                    TaxTotal           = UtilsXmlDoc.DevuelveSubTotalImpuestos(creditHeaderEntity.Impuesto),
                    LegalMonetaryTotal = new MonetaryTotalType
                    {
                        ChargeTotalAmount = creditHeaderEntity.TotalCargos > 0 ? new AmountType {
                            Value = creditHeaderEntity.TotalCargos
                        } : null,
                        AllowanceTotalAmount = creditHeaderEntity.DescuentoGlobal > 0 ? new AmountType {
                            Value = creditHeaderEntity.DescuentoGlobal
                        } : null,
                        PayableAmount = creditHeaderEntity.Total
                    },
                    CreditNoteLine = UtilsXmlDoc.ToCredit(UtilsXmlDoc.DevuelveDetallesDelComprobante(creditHeaderEntity.DetallesDocumento)),
                };
                #region Ext
                var lisExt = new List <UBLExtensionType>(2);
                if (creditHeaderEntity.TotalTributosAdicionales != null)
                {
                    lisExt.Add(new UBLExtensionType
                    {
                        ExtensionContent = new AdditionalsInformationType //(mas informacion en el catalogo no 14 del manual.)
                        {
                            AdditionalInformation = new AdditionalInformationType {
                                AdditionalMonetaryTotal = UtilsXmlDoc.DevuelveTributosAdicionales(creditHeaderEntity.TotalTributosAdicionales),
                            }
                        }
                    });
                }
                lisExt.Add(new UBLExtensionType {
                    ExtensionContent = new AdditionalsInformationType()
                });
                creditDoc.UBLExtensions = lisExt.ToArray();
                #endregion
                creditDoc.AccountingSupplierParty.Party.PostalAddress = UtilsXmlDoc.ObtenerDireccion(creditHeaderEntity.DireccionEmisor);
                #endregion |

                return(FromDocument(creditDoc, xmlFilename));
            }
            catch (Exception ex)
            {
                return(FromException(ex));
            }
        }
Example #33
0
        public static CreditNoteType Create()
        {
            var doc = new CreditNoteType
            {
                UBLVersionID    = "2.0",
                CustomizationID = "urn:oasis:names:specification:ubl:xpath:CreditNote-2.0:sbs-1.0-draft",
                ProfileID       = "bpid:urn:oasis:names:draft:bpss:ubl-2-sbs-credit-notification-draft",
                ID            = "CN758494",
                CopyIndicator = false,
                UUID          = "349ABBAE-DF9D-40B4-849F-94C5FF9D1AF4",
                IssueDate     = "2005-06-25",
                TaxPointDate  = "2005-06-21",
                Note          = new List <TextType>()
                {
                    new TextType
                    {
                        Value = "sample"
                    }
                },
                AccountingSupplierParty = new SupplierPartyType
                {
                    CustomerAssignedAccountID = "CO001",
                    Party = new PartyType
                    {
                        PartyName = new List <PartyNameType>()
                        {
                            new PartyNameType
                            {
                                Name = "Consortial"
                            }
                        },
                        PostalAddress = new AddressType
                        {
                            StreetName       = "Busy Street",
                            BuildingName     = "Thereabouts",
                            BuildingNumber   = "56A",
                            CityName         = "Farthing",
                            PostalZone       = "AA99 1BB",
                            CountrySubentity = "Heremouthshire",
                            AddressLine      = new List <AddressLineType>()
                            {
                                new AddressLineType
                                {
                                    Line = "The Roundabout"
                                }
                            },
                            Country = new CountryType
                            {
                                IdentificationCode = "GB"
                            }
                        },
                        PartyTaxScheme = new List <PartyTaxSchemeType>()
                        {
                            new PartyTaxSchemeType
                            {
                                RegistrationName = "Farthing Purchasing Consortium",
                                CompanyID        = "175 269 2355",
                                ExemptionReason  = new List <TextType>()
                                {
                                    new TextType
                                    {
                                        Value = "N/A"
                                    }
                                },
                                TaxScheme = new TaxSchemeType
                                {
                                    ID          = "VAT",
                                    TaxTypeCode = "VAT"
                                }
                            }
                        },
                        Contact = new ContactType
                        {
                            Name           = "Mrs Bouquet",
                            Telephone      = "0158 1233714",
                            Telefax        = "0158 1233856",
                            ElectronicMail = "*****@*****.**"
                        }
                    }
                },
                AccountingCustomerParty = new CustomerPartyType
                {
                    CustomerAssignedAccountID = "XFB01",
                    SupplierAssignedAccountID = "GT00978567",
                    Party = new PartyType
                    {
                        PartyName = new List <PartyNameType>()
                        {
                            new PartyNameType
                            {
                                Name = "IYT Corporation"
                            }
                        },
                        PostalAddress = new AddressType
                        {
                            StreetName       = "Avon Way",
                            BuildingName     = "Thereabouts",
                            BuildingNumber   = "56A",
                            CityName         = "Bridgtow",
                            PostalZone       = "ZZ99 1ZZ",
                            CountrySubentity = "Avon",
                            AddressLine      = new List <AddressLineType>()
                            {
                                new AddressLineType
                                {
                                    Line = "3rd Floor, Room 5"
                                }
                            },
                            Country = new CountryType
                            {
                                IdentificationCode = "GB"
                            }
                        },
                        PartyTaxScheme = new List <PartyTaxSchemeType>()
                        {
                            new PartyTaxSchemeType
                            {
                                RegistrationName = "Bridgtow District Council",
                                CompanyID        = "12356478",
                                ExemptionReason  = new List <TextType>()
                                {
                                    new TextType
                                    {
                                        Value = "Local Authority"
                                    }
                                },
                                TaxScheme = new TaxSchemeType
                                {
                                    ID          = "UK VAT",
                                    TaxTypeCode = "VAT"
                                }
                            }
                        },
                        Contact = new ContactType
                        {
                            Name           = "Mr Fred Churchill",
                            Telephone      = "0127 2653214",
                            Telefax        = "0127 2653215",
                            ElectronicMail = "*****@*****.**"
                        }
                    }
                },
                TaxTotal = new List <TaxTotalType>()
                {
                    new TaxTotalType
                    {
                        TaxAmount = new AmountType
                        {
                            currencyID = "GBP",
                            Value      = 17.50M
                        },
                        TaxEvidenceIndicator = true,
                        TaxSubtotal          = new List <TaxSubtotalType>()
                        {
                            new TaxSubtotalType
                            {
                                TaxableAmount = new AmountType
                                {
                                    currencyID = "GBP",
                                    Value      = 100.00M
                                },
                                TaxAmount = new AmountType
                                {
                                    currencyID = "GBP",
                                    Value      = 17.50M
                                },
                                TaxCategory = new TaxCategoryType
                                {
                                    ID        = "A",
                                    TaxScheme = new TaxSchemeType
                                    {
                                        ID          = "UK VAT",
                                        TaxTypeCode = "VAT"
                                    }
                                }
                            }
                        },
                    }
                },
                LegalMonetaryTotal = new MonetaryTotalType
                {
                    LineExtensionAmount = new AmountType
                    {
                        currencyID = "GBP",
                        Value      = 100.00M
                    },
                    TaxExclusiveAmount = new AmountType
                    {
                        currencyID = "GBP",
                        Value      = 90.00M
                    },
                    PayableAmount = new AmountType
                    {
                        currencyID = "GBP",
                        Value      = 107.50M
                    }
                },
                CreditNoteLine = new List <CreditNoteLineType>()
                {
                    new CreditNoteLineType
                    {
                        ID   = "1",
                        Note = new List <TextType>()
                        {
                            new TextType
                            {
                                Value = "as agreed on phone, the invoice should have been cancelled earlier, apologies"
                            }
                        },
                        CreditedQuantity = new QuantityType
                        {
                            unitCode = "KGM",
                            Value    = 100M
                        },
                        LineExtensionAmount = new AmountType
                        {
                            currencyID = "GBP",
                            Value      = 100.00M
                        },
                        TaxPointDate        = "2005-06-21",
                        DiscrepancyResponse = new List <ResponseType>()
                        {
                            new ResponseType
                            {
                                ReferenceID = "A00095678",
                                Description = new List <TextType>()
                                {
                                    new TextType
                                    {
                                        Value = "invoice cancelation"
                                    }
                                },
                            }
                        },
                        BillingReference = new List <BillingReferenceType>()
                        {
                            new BillingReferenceType
                            {
                                InvoiceDocumentReference = new DocumentReferenceType
                                {
                                    ID        = "A00095678",
                                    UUID      = "849FBBCE-E081-40B4-906C-94C5FF9D1AC3",
                                    IssueDate = "2005-06-21"
                                }
                            }
                        },
                        TaxTotal = new List <TaxTotalType>()
                        {
                            new TaxTotalType
                            {
                                TaxAmount = new AmountType
                                {
                                    currencyID = "GBP",
                                    Value      = 17.50M
                                },
                                TaxEvidenceIndicator = true,
                                TaxSubtotal          = new List <TaxSubtotalType>()
                                {
                                    new TaxSubtotalType
                                    {
                                        TaxableAmount = new AmountType
                                        {
                                            currencyID = "GBP",
                                            Value      = 100.00M
                                        },
                                        TaxAmount = new AmountType
                                        {
                                            currencyID = "GBP",
                                            Value      = 17.50M
                                        },
                                        TaxCategory = new TaxCategoryType
                                        {
                                            ID        = "A",
                                            TaxScheme = new TaxSchemeType
                                            {
                                                ID          = "UK VAT",
                                                TaxTypeCode = "VAT"
                                            }
                                        }
                                    }
                                },
                            }
                        },
                        Item = new ItemType
                        {
                            Description = new List <TextType>()
                            {
                                new TextType
                                {
                                    Value = "Acme beeswax"
                                }
                            },
                            Name = "beeswax",
                            BuyersItemIdentification = new ItemIdentificationType
                            {
                                ID = "6578489"
                            },
                            SellersItemIdentification = new ItemIdentificationType
                            {
                                ID = "17589683"
                            },
                            ItemInstance = new List <ItemInstanceType>()
                            {
                                new ItemInstanceType
                                {
                                    LotIdentification = new LotIdentificationType
                                    {
                                        LotNumberID = "546378239",
                                        ExpiryDate  = "2010-01-01"
                                    }
                                }
                            },
                        },
                        Price = new PriceType
                        {
                            PriceAmount = new AmountType
                            {
                                currencyID = "GBP",
                                Value      = 1.00M
                            },
                            BaseQuantity = new QuantityType
                            {
                                unitCode = "KGM",
                                Value    = 1M
                            }
                        }
                    }
                },
            };

            doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[]
            {
                new XmlQualifiedName("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"),
                new XmlQualifiedName("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"),
            });
            return(doc);
        }
Example #34
0
        private DataTable FnTablaCabeceraInvoice(CreditNoteType ocomprobante)
        {
            DataTable dtCabecera = new DataTable();

            dtCabecera.Columns.Add(new DataColumn("SerieNumero", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("FechaEmision", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("FechaVencimiento", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("TipoComprobante", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("Moneda", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("MontoLetras", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("QR", typeof(Byte[])));
            dtCabecera.Columns.Add(new DataColumn("TotalValorVentaGravada", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("IGV", typeof(string)));
            dtCabecera.Columns.Add(new DataColumn("ImporteTotal", typeof(string)));

            DataRow fila;

            fila = dtCabecera.NewRow();
            fila["SerieNumero"]      = FnValidarNulo(ocomprobante.ID.Value.ToString());
            fila["FechaEmision"]     = FnValidarNulo(ocomprobante.IssueDate.Value.ToString());
            fila["FechaVencimiento"] = "";


            fila["TipoComprobante"] = "CREDITO ELECTRÓNICA";

            if (ocomprobante.DocumentCurrencyCode.Value.ToString() == "PEN")
            {
                fila["Moneda"] = "NUEVO SOL";
            }
            if (ocomprobante.DocumentCurrencyCode.Value.ToString() == "USD")
            {
                fila["Moneda"] = "DOLAR AMERICANO";
            }


            fila["MontoLetras"] = "";
            if (ocomprobante.Note != null)
            {
                if (ocomprobante.Note.Length > 0)
                {
                    foreach (NoteType nota in ocomprobante.Note)
                    {
                        if (nota.languageLocaleID == "1000")
                        {
                            fila["MontoLetras"] = nota.Value.ToString();
                        }
                    }
                }
            }

            fila["QR"] = FnCodigoQR("Luchito");

            if (ocomprobante.TaxTotal != null)
            {
                foreach (TaxTotalType total in ocomprobante.TaxTotal)
                {
                    foreach (TaxSubtotalType subTotal in total.TaxSubtotal)
                    {
                        if (subTotal.TaxCategory.TaxScheme.Name.Value.ToString() == "IGV")
                        {
                            fila["IGV"] = FnValidarNulo(subTotal.TaxAmount.Value.ToString());
                        }
                    }
                }
            }

            if (ocomprobante.LegalMonetaryTotal != null)
            {
                fila["TotalValorVentaGravada"] = FnValidarNulo(ocomprobante.LegalMonetaryTotal.LineExtensionAmount.Value.ToString());
                fila["ImporteTotal"]           = FnValidarNulo(ocomprobante.LegalMonetaryTotal.PayableAmount.Value.ToString());
            }


            dtCabecera.Rows.Add(fila);

            return(dtCabecera);
        }