Beispiel #1
0
        private static void TestCreateCfdiMultiemisor(FacturamaApiMultiemisor facturama)
        {
            var nameId        = facturama.Catalogs.NameIds.ElementAt(1); //Nombre en el pdf: "Factura"
            var currency      = facturama.Catalogs.Currencies.First(m => m.Value == "MXN");
            var paymentMethod = facturama.Catalogs.PaymentMethods.First(p => p.Name == "Pago en una sola exhibición");
            var paymentForm   = facturama.Catalogs.PaymentForms.First(p => p.Name == "Efectivo");
            var cfdiUse       = facturama.Catalogs.CfdiUses("AAA010101AAA").First();
            var codeProdServ  = facturama.Catalogs.ProductsOrServices("desarrollo").First();
            var unitCode      = facturama.Catalogs.Units("pieza").First();
            var decimals      = (int)currency.Decimals;
            var regimen       = facturama.Catalogs.FiscalRegimens.First();

            var cfdi = new CfdiMulti
            {
                Folio           = "10",
                NameId          = nameId.Value,
                CfdiType        = CfdiType.Ingreso,
                PaymentForm     = paymentForm.Value,
                PaymentMethod   = paymentMethod.Value,
                Currency        = currency.Value,
                Date            = DateTime.Now,
                ExpeditionPlace = "78180",
                Items           = new List <Item>(),
                Issuer          = new Issuer
                {
                    FiscalRegime = regimen.Value,
                    Name         = "Emisor de Ejemplo",
                    Rfc          = "AAA010101AAA"
                },
                Receiver = new Receiver
                {
                    CfdiUse = cfdiUse.Value,
                    Name    = "Receptor de Ejemplo",
                    Rfc     = "ESO1202108R2"
                },
            };

            var price    = 100.00m;
            var quantity = 2m;
            var discount = 10m;
            var subtotal = Math.Round(price * quantity, decimals);

            var item = new Item
            {
                ProductCode          = codeProdServ.Value,
                UnitCode             = unitCode.Value,
                Unit                 = "Libra",
                Description          = "Descripción del Producto",
                IdentificationNumber = "010101-56",
                Quantity             = quantity,
                Discount             = Math.Round(discount, decimals),
                UnitPrice            = Math.Round(price, decimals),
                Subtotal             = subtotal,
                Taxes                = new List <Tax>
                {
                    new Tax
                    {
                        Name        = "IVA",
                        IsQuota     = false,
                        IsRetention = false,

                        Rate  = 0.160000m,
                        Base  = Math.Round(subtotal - discount, decimals),
                        Total = Math.Round((subtotal - discount) * 0.160000m, decimals)
                    }
                }
            };
            var retenciones = item.Taxes?.Where(t => t.IsRetention).Sum(t => t.Total) ?? 0;
            var traslados   = item.Taxes?.Where(t => !t.IsRetention).Sum(t => t.Total) ?? 0;

            item.Total = item.Subtotal - item.Discount + traslados - retenciones;
            cfdi.Items.Add(item);

            try
            {
                var cfdiCreated = facturama.Cfdis.Create(cfdi);
                Console.WriteLine(
                    $"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                facturama.Cfdis.SaveXml($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.xml", cfdiCreated.Id);

                var list = facturama.Cfdis.List("Emisor de Ejemplo");
                Console.WriteLine($"Se encontraron: {list.Length} elementos en la busqueda");
                list = facturama.Cfdis.List(rfc: "ESO1202108R2"); //Atributo en especifico
                Console.WriteLine($"Se encontraron: {list.Length} elementos en la busqueda");

                facturama.Cfdis.Remove(cfdiCreated.Id);
                Console.WriteLine(
                    $"Se eliminó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
            }
            catch (FacturamaException ex)
            {
                Console.WriteLine(ex.Message);
                foreach (var messageDetail in ex.Model.Details)
                {
                    Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inesperado: ", ex.Message);
            }
        }
Beispiel #2
0
        private static void TestCreatePaymentCfdi(FacturamaApiMultiemisor facturama)
        {
            var nameId      = facturama.Catalogs.NameIds[14]; //Nombre en el pdf: "Factura"
            var paymentForm = facturama.Catalogs.PaymentForms.First(p => p.Name == "Efectivo");
            var regimen     = facturama.Catalogs.FiscalRegimens.First();


            var cfdi = new CfdiMulti
            {
                NameId          = nameId.Value,
                CfdiType        = CfdiType.Pago,
                Folio           = "100",
                ExpeditionPlace = "78220",
                Issuer          = new Issuer
                {
                    Rfc          = "AAA010101AAA",
                    Name         = "Expresion en Software SAPI de CV",
                    FiscalRegime = regimen.Value
                },
                Receiver = new Receiver
                {
                    Rfc     = "JAR1106038RA",
                    Name    = "SinDelantal Mexico",
                    CfdiUse = "P01"
                },
                Complement = new Complement
                {
                    Payments = new List <Payment>
                    {
                        new Payment
                        {
                            Date             = "2018-04-04T00:00:00.000Z",
                            PaymentForm      = paymentForm.Value,
                            Currency         = "MXN",
                            Amount           = 1200.00m,
                            RelatedDocuments = new List <RelatedDocument> {
                                new RelatedDocument {
                                    Uuid                  = "F884C787-EEA6-4720-874D-B5048DB8F960",
                                    Folio                 = "100032007",
                                    Currency              = "MXN",
                                    PaymentMethod         = "PUE",
                                    PartialityNumber      = 1,
                                    PreviousBalanceAmount = 1200.00m,
                                    AmountPaid            = 1200.00m
                                }
                            }
                        }
                    }
                }
            };

            try
            {
                var cfdiCreated = facturama.Cfdis.Create(cfdi);
                Console.WriteLine(
                    $"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                facturama.Cfdis.SaveXml($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.xml", cfdiCreated.Id);
                Console.WriteLine($"Se guardo existosamente la factura con el UUID: {cfdiCreated.Complement.TaxStamp.Uuid}.");
                facturama.Cfdis.Remove(cfdiCreated.Id);
                Console.WriteLine(
                    $"Se eliminó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
            }
            catch (FacturamaException ex)
            {
                Console.WriteLine(ex.Message);
                foreach (var messageDetail in ex.Model.Details)
                {
                    Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inesperado: ", ex.Message);
            }
        }
        public void Run()
        {
            Console.WriteLine("----- Inicio del ejemplo WaybillComplementExampleMulti -----");

            var cfdi = new CfdiMulti
            {
                NameId          = "1",                          // Factura
                Folio           = "1342",
                CfdiType        = CfdiType.Ingreso,
                PaymentForm     = "03",                         // Transferencia electrónica de fondos
                PaymentMethod   = "PUE",                        // Pago en una exhibición
                Date            = null,                         // Al especificar null, Facturama asigna la fecha y hora actual, de acuerdo al "ExpeditionPlace"
                ExpeditionPlace = "78000",                      // Codigo postal del la sucursal desde donde se expide el CFDI, (este debe pertenecer al catálogo de sucursales)  https://apisandbox.facturama.mx/guias/perfil-fiscal#lugares-expedicion-series
                Items           = new List <Item>(),
                Issuer          = new Issuer
                {
                    Name         = "Escuela emisora del CFDI",
                    Rfc          = "EKU9003173C9",
                    FiscalRegime = "601"
                },
                Receiver = new Receiver
                {
                    CfdiUse = "P01",
                    Name    = "José Perez Leon",
                    Rfc     = "JUFA7608212V6",
                    Address = new Address                       // El nodo Address es opcional (puedes colocarlo nulo o no colocarlo). En el caso de no colcoarlo, tomará la correspondiente al RFC en el catálogo de clientes
                    {
                        Street         = "Avenida de los pinos",
                        ExteriorNumber = "110",
                        InteriorNumber = "A",
                        Neighborhood   = "Las villerías",
                        ZipCode        = "78000",
                        Municipality   = "San Luis Potosí",
                        State          = "San Luis Potosí",
                        Country        = "México"
                    }
                },
            };

            var item = new Item
            {
                ProductCode          = "78101703",              // Reacionado con institucion educativa
                UnitCode             = "E48",                   // Servicio
                Unit                 = "Unidad de servicio",
                Description          = "Colegiatura del mes de marzo",
                IdentificationNumber = "1234",                  // Numero de identificación interno del producto (opcional)
                Quantity             = 1,
                Discount             = 0,
                UnitPrice            = 2300,
                Subtotal             = 2300,
                Taxes                = new [] { new Tax
                                                {
                                                    Name        = "IVA",
                                                    IsQuota     = false,
                                                    IsRetention = false,

                                                    Rate  = 0.16m,
                                                    Base  = 2300,
                                                    Total = 368
                                                } }.ToList()
            };
            var retenciones = item.Taxes?.Where(t => t.IsRetention).Sum(t => t.Total) ?? 0;
            var traslados   = item.Taxes?.Where(t => !t.IsRetention).Sum(t => t.Total) ?? 0;

            item.Total = item.Subtotal - (item.Discount ?? 0) + traslados - retenciones;
            cfdi.Items.Add(item);

            // Complemento Carta Porte
            cfdi.Complement = new Complement
            {
                CartaPorte20 = new ComplementoCartaPorte20
                {
                    TranspInternac = TranspInternac.No,
                    Ubicaciones    = new[] { new Ubicacion
                                             {
                                                 TipoUbicacion            = TipoUbicacion.Origen,
                                                 RFCRemitenteDestinatario = "EKU9003173C9",
                                                 FechaHoraSalidaLlegada   = DateTime.Now.AddHours(-6),
                                                 DistanciaRecorrida       = 1,
                                                 Domicilio = new Domicilio
                                                 {
                                                     Calle        = "Puebla No.1",
                                                     CodigoPostal = "28239",
                                                     Colonia      = "0342",
                                                     Estado       = "COL",
                                                     Municipio    = "007",
                                                     Localidad    = "02",
                                                     Pais         = "MEX",
                                                 }
                                             },
                                             new Ubicacion
                                             {
                                                 TipoUbicacion            = TipoUbicacion.Destino,
                                                 RFCRemitenteDestinatario = "RIFO990729M66",
                                                 FechaHoraSalidaLlegada   = DateTime.Now.AddHours(+6),
                                                 DistanciaRecorrida       = 100,
                                                 Domicilio = new Domicilio
                                                 {
                                                     Calle        = "Morelos No.1",
                                                     CodigoPostal = "28219",
                                                     Colonia      = "0575",
                                                     Estado       = "COL",
                                                     Municipio    = "007",
                                                     Localidad    = "02",
                                                     Pais         = "MEX",
                                                 }
                                             } },
                    Mercancias = new Mercancias
                    {
                        UnidadPeso = "KGM",
                        Mercancia  = new [] {
                            new Mercancia
                            {
                                Cantidad     = 1,
                                BienesTransp = "10101500",
                                Descripcion  = "Animales vivos de granja",
                                ClaveUnidad  = "KGM",
                                PesoEnKg     = 120,
                            }
                        },
                        Autotransporte = new Autotransporte
                        {
                            PermSCT       = "TPAF01",
                            NumPermisoSCT = "123abc",
                            Seguros       = new Seguros
                            {
                                AseguraRespCivil = "Seguros SA",
                                PolizaRespCivil  = "123123"
                            },
                            IdentificacionVehicular = new IdentificacionVehicular
                            {
                                AnioModeloVM    = 1990,
                                ConfigVehicular = "C2R3",
                                PlacaVM         = "XXX000",
                            },
                            Remolques = new []
                            {
                                new Remolque
                                {
                                    SubTipoRem = "CTR001",
                                    Placa      = "21132H"
                                }
                            }
                        }
                    },
                    FiguraTransporte = new[] { new TiposFigura {
                                                   TipoFigura   = "01",
                                                   RFCFigura    = "MISC491214B86",
                                                   NombreFigura = "Juan",
                                                   NumLicencia  = "000001",
                                               },
                                               new TiposFigura
                                               {
                                                   TipoFigura       = "02",
                                                   RFCFigura        = "XAMA620210DQ5",
                                                   NombreFigura     = "Juan Manuel Perez Lopez",
                                                   PartesTransporte = new [] { new PartesTransporte {
                                                                                   ParteTransporte = "PT01"
                                                                               } },
                                                   Domicilio = new Domicilio
                                                   {
                                                       Calle        = "Morelos No.1",
                                                       CodigoPostal = "28219",
                                                       Colonia      = "0575",
                                                       Estado       = "COL",
                                                       Municipio    = "007",
                                                       Localidad    = "02",
                                                       Pais         = "MEX",
                                                   }
                                               } }
                }
            };


            try
            {
                var cfdiCreated = facturama.Cfdis.Create(cfdi);
                Console.WriteLine(
                    $"Se creó ex la carta porte 2.0 con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                facturama.Cfdis.SavePdf($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.pdf", cfdiCreated.Id);
                facturama.Cfdis.SaveXml($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.xml", cfdiCreated.Id);


                if (facturama.Cfdis.SendByMail(cfdiCreated.Id, "*****@*****.**"))
                {
                    Console.WriteLine("Se envió correctamente la carta porte 2.0");
                }


                var cancelationStatus = facturama.Cfdis.Cancel(cfdiCreated.Id);
                if (cancelationStatus.Status == "canceled")
                {
                    Console.WriteLine($"Se canceló exitosamente el CFDI con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else if (cancelationStatus.Status == "pending")
                {
                    Console.WriteLine($"El CFDI está en proceso de cancelacion, require aprobacion por parte del receptor UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else if (cancelationStatus.Status == "active")
                {
                    Console.WriteLine($"El CFDI no pudo ser cancelado, se deben revisar docuementos relacionados on cancelar directo en el SAT UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else
                {
                    Console.WriteLine($"Estado de cancelacin del CFDI desconocido UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
            }
            catch (FacturamaException ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.Model.Details != null)
                {
                    foreach (var messageDetail in ex.Model.Details)
                    {
                        Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inesperado: ", ex.Message);
            }

            Console.WriteLine("----- Fin del ejemplo WaybillComplementExampleMulti -----");
        }
        private static void TestCreatePaymentCfdi(FacturamaApiMultiemisor facturama)
        {
            var nameId      = facturama.Catalogs.NameIds[14]; //Nombre en el pdf: "Factura"
            var paymentForm = facturama.Catalogs.PaymentForms.First(p => p.Name == "Efectivo");
            var regimen     = facturama.Catalogs.FiscalRegimens.First();


            var cfdi = new CfdiMulti
            {
                NameId          = nameId.Value,
                CfdiType        = CfdiType.Pago,
                Folio           = "100",
                ExpeditionPlace = "78220",
                LogoUrl         = "https://www.ejemplos.co/wp-content/uploads/2015/11/Logo-Chanel.jpg",

                Issuer = new Issuer
                {
                    Rfc          = "EKU9003173C9",
                    Name         = "Kemper Software SAPI de CV",
                    FiscalRegime = regimen.Value
                },
                Receiver = new Receiver
                {
                    Rfc     = "EWE1709045U0",
                    Name    = "Escuela Wilson Esquivel",
                    CfdiUse = "P01"
                },
                Complement = new Complement
                {
                    Payments = new List <Payment>
                    {
                        new Payment
                        {
                            Date             = "2018-04-04T00:00:00.000Z",
                            PaymentForm      = paymentForm.Value,
                            Currency         = "MXN",
                            Amount           = 1200.00m,
                            RelatedDocuments = new List <RelatedDocument> {
                                new RelatedDocument {
                                    Uuid                  = "F884C787-EEA6-4720-874D-B5048DB8F960",
                                    Folio                 = "100032007",
                                    Currency              = "MXN",
                                    PaymentMethod         = "PUE",
                                    PartialityNumber      = 1,
                                    PreviousBalanceAmount = 1200.00m,
                                    AmountPaid            = 1200.00m
                                }
                            }
                        }
                    }
                }
            };

            try
            {
                var cfdiCreated = facturama.Cfdis.Create(cfdi);
                Console.WriteLine(
                    $"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                facturama.Cfdis.SaveXml($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.xml", cfdiCreated.Id);
                Console.WriteLine($"Se guardo existosamente la factura con el UUID: {cfdiCreated.Complement.TaxStamp.Uuid}.");

                Console.WriteLine($"Se intenta cancelar la factura con el UUID: {cfdiCreated.Complement.TaxStamp.Uuid}.");
                var cancelationStatus = facturama.Cfdis.Cancel(cfdiCreated.Id);
                if (cancelationStatus.Status == "canceled")
                {
                    Console.WriteLine($"Se canceló exitosamente el CFDI con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else if (cancelationStatus.Status == "pending")
                {
                    Console.WriteLine($"El CFDI está en proceso de cancelacion, require aprobacion por parte del receptor UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else if (cancelationStatus.Status == "active")
                {
                    Console.WriteLine($"El CFDI no pudo ser cancelado, se deben revisar docuementos relacionados on cancelar directo en el SAT UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else
                {
                    Console.WriteLine($"Estado de cancelacin del CFDI desconocido UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
            }
            catch (FacturamaException ex)
            {
                Console.WriteLine(ex.Message);
                foreach (var messageDetail in ex.Model.Details)
                {
                    Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inesperado: ", ex.Message);
            }
        }
        private static void TestCreateCfdiMultiemisor40(FacturamaApiMultiemisor facturama)
        {
            var cfdi = new CfdiMulti
            {
                Folio           = "10",
                NameId          = "1",
                CfdiType        = CfdiType.Ingreso,
                PaymentForm     = "01",
                PaymentMethod   = "PUE",
                Currency        = "MXN",
                Date            = null,
                ExpeditionPlace = "78140",
                LogoUrl         = "https://www.ejemplos.co/wp-content/uploads/2015/11/Logo-Chanel.jpg",

                Exportation = "01",

                GlobalInformation = new GlobalInformation
                {
                    Periodicity = "04",
                    Months      = "04",
                    Year        = "2022"
                },

                Items  = new List <Item>(),
                Issuer = new Issuer
                {
                    FiscalRegime = "601",
                    Name         = "ESCUELA KEMPER URGATE",
                    Rfc          = "EKU9003173C9"
                },
                Receiver = new Receiver
                {
                    Rfc          = "XAXX010101000",
                    Name         = "PUBLICO GENERAL",
                    CfdiUse      = "S01",
                    FiscalRegime = "616",
                    TaxZipCode   = "78140"
                },
            };

            var price    = 100.00m;
            var quantity = 2m;
            var discount = 10m;
            var subtotal = Math.Round(price * quantity, 2);

            var item = new Item
            {
                ProductCode = "25173108",
                UnitCode    = "E48",
                Description = "GPS estandar pruebas",
                Quantity    = 1.0M,
                UnitPrice   = 100.0M,
                Subtotal    = 100.00M,
                TaxObject   = "02",
                Taxes       = new List <Tax>
                {
                    new Tax
                    {
                        Name        = "IVA",
                        IsQuota     = false,
                        IsRetention = false,

                        Rate  = 0.160000m,
                        Base  = Math.Round(subtotal - discount, 2),
                        Total = Math.Round((subtotal - discount) * 0.160000m, 2)
                    }
                }
            };
            var retenciones = item.Taxes?.Where(t => t.IsRetention).Sum(t => t.Total) ?? 0;
            var traslados   = item.Taxes?.Where(t => !t.IsRetention).Sum(t => t.Total) ?? 0;

            item.Total = item.Subtotal - (item.Discount ?? 0) + traslados - retenciones;
            cfdi.Items.Add(item);

            try
            {
                //var cfdiCreated = facturama.Cfdis.Create(cfdi);
                //Console.WriteLine($"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");

                var cfdiCreated = facturama.Cfdis.Create3(cfdi);// Prueba CFDI 4.0
                Console.WriteLine($"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");

                //facturama.Cfdis.SaveXml($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.xml", cfdiCreated.Id);
                //facturama.Cfdis.SavePdf($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.pdf", cfdiCreated.Id);

                //var list = facturama.Cfdis.List("Emisor de Ejemplo");
                //Console.WriteLine($"Se encontraron: {list.Length} elementos en la busqueda");
                //list = facturama.Cfdis.List(rfc: "EWE1709045U0"); //RFC receptor en especifico
                //Console.WriteLine($"Se encontraron: {list.Length} elementos en la busqueda");

                //var cancelationStatus = facturama.Cfdis.Cancel(cfdiCreated.Id);

                /*
                 *              if(cancelationStatus.Status == "canceled")
                 *              {
                 *                      Console.WriteLine($"Se canceló exitosamente el CFDI con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 *              else if (cancelationStatus.Status == "pending")
                 *              {
                 *                      Console.WriteLine($"El CFDI está en proceso de cancelacion, require aprobacion por parte del receptor UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 *              else if (cancelationStatus.Status == "active")
                 *              {
                 *                      Console.WriteLine($"El CFDI no pudo ser cancelado, se deben revisar docuementos relacionados on cancelar directo en el SAT UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 *              else
                 *              {
                 *                      Console.WriteLine($"Estado de cancelacin del CFDI desconocido UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 */
            }
            catch (FacturamaException ex)
            {
                Console.WriteLine(ex.Message);
                foreach (var messageDetail in ex.Model.Details)
                {
                    Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inesperado: ", ex.Message);
            }
        }
        private static void TestCreateCfdiMultiemisor(FacturamaApiMultiemisor facturama)
        {
            var nameId        = facturama.Catalogs.NameIds.ElementAt(1); //Nombre en el pdf: "Factura"
            var currency      = facturama.Catalogs.Currencies.First(m => m.Value == "MXN");
            var paymentMethod = facturama.Catalogs.PaymentMethods.First(p => p.Name == "Pago en una sola exhibición");
            var paymentForm   = facturama.Catalogs.PaymentForms.First(p => p.Name == "Efectivo");
            var cfdiUse       = facturama.Catalogs.CfdiUses("EKU9003173C9").First();
            var codeProdServ  = facturama.Catalogs.ProductsOrServices("desarrollo").First();
            var unitCode      = facturama.Catalogs.Units("pieza").First();
            var decimals      = (int)currency.Decimals;
            var regimen       = facturama.Catalogs.FiscalRegimens.First();

            var cfdi = new CfdiMulti
            {
                Folio           = "10",
                NameId          = nameId.Value,
                CfdiType        = CfdiType.Ingreso,
                PaymentForm     = paymentForm.Value,
                PaymentMethod   = paymentMethod.Value,
                Currency        = currency.Value,
                Date            = null,
                ExpeditionPlace = "78180",
                LogoUrl         = "https://www.ejemplos.co/wp-content/uploads/2015/11/Logo-Chanel.jpg",
                Items           = new List <Item>(),
                Issuer          = new Issuer
                {
                    FiscalRegime = regimen.Value,
                    Name         = "ESCUELA KEMPER URGATE",
                    Rfc          = "EKU9003173C9"
                },
                Receiver = new Receiver
                {
                    CfdiUse      = "G03",
                    Name         = "UNIVERSIDAD ROBOTICA ESPAÑOLA",
                    Rfc          = "URE180429TM6",
                    FiscalRegime = "601",
                    TaxZipCode   = "65000"
                },
            };

            var price    = 100.00m;
            var quantity = 2m;
            var discount = 10m;
            var subtotal = Math.Round(price * quantity, decimals);

            var item = new Item
            {
                ProductCode = "25173108",
                UnitCode    = "E48",
                Description = "GPS estandar pruebas",
                Quantity    = 1.0M,
                UnitPrice   = 100.0M,
                Subtotal    = 100.00M,
                TaxObject   = "02",
                Taxes       = new List <Tax>
                {
                    new Tax
                    {
                        Name        = "IVA",
                        IsQuota     = false,
                        IsRetention = false,

                        Rate  = 0.160000m,
                        Base  = Math.Round(subtotal - discount, decimals),
                        Total = Math.Round((subtotal - discount) * 0.160000m, decimals)
                    }
                }
            };
            var retenciones = item.Taxes?.Where(t => t.IsRetention).Sum(t => t.Total) ?? 0;
            var traslados   = item.Taxes?.Where(t => !t.IsRetention).Sum(t => t.Total) ?? 0;

            item.Total = item.Subtotal - (item.Discount ?? 0) + traslados - retenciones;
            cfdi.Items.Add(item);

            try
            {
                //var cfdiCreated = facturama.Cfdis.Create(cfdi);
                //Console.WriteLine($"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");

                var cfdiCreated = facturama.Cfdis.Create3(cfdi);// Prueba CFDI 4.0
                Console.WriteLine($"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");

                //facturama.Cfdis.SaveXml($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.xml", cfdiCreated.Id);
                //facturama.Cfdis.SavePdf($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.pdf", cfdiCreated.Id);

                //var list = facturama.Cfdis.List("Emisor de Ejemplo");
                //Console.WriteLine($"Se encontraron: {list.Length} elementos en la busqueda");
                //list = facturama.Cfdis.List(rfc: "EWE1709045U0"); //RFC receptor en especifico
                //Console.WriteLine($"Se encontraron: {list.Length} elementos en la busqueda");

                //var cancelationStatus = facturama.Cfdis.Cancel(cfdiCreated.Id);

                /*
                 *              if(cancelationStatus.Status == "canceled")
                 *              {
                 *                      Console.WriteLine($"Se canceló exitosamente el CFDI con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 *              else if (cancelationStatus.Status == "pending")
                 *              {
                 *                      Console.WriteLine($"El CFDI está en proceso de cancelacion, require aprobacion por parte del receptor UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 *              else if (cancelationStatus.Status == "active")
                 *              {
                 *                      Console.WriteLine($"El CFDI no pudo ser cancelado, se deben revisar docuementos relacionados on cancelar directo en el SAT UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 *              else
                 *              {
                 *                      Console.WriteLine($"Estado de cancelacin del CFDI desconocido UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                 *              }
                 */
            }
            catch (FacturamaException ex)
            {
                Console.WriteLine(ex.Message);
                foreach (var messageDetail in ex.Model.Details)
                {
                    Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inesperado: ", ex.Message);
            }
        }
Beispiel #7
0
        public void Run()
        {
            Console.WriteLine("----- Inicio del ejemplo EducationalInstitutionComplementExampleMultiemisor  -----");

            var cfdi = new CfdiMulti
            {
                NameId          = "1",                          // Factura - Tomado del catálogo de nombres de Facturama https://apisandbox.facturama.mx/guias/catalogos/nombres-cfdi
                Folio           = "1242",
                CfdiType        = CfdiType.Ingreso,
                LogoUrl         = "https://facturama.mx/img/facturama_logo.png", // El logo debe existir en una URL
                PaymentForm     = "03",                                          // Transferencia electrónica de fondos
                PaymentMethod   = "PUE",                                         // Pago en una exhibición
                Date            = null,                                          // Al especificar null, Facturama asigna la fecha y hora actual, de acuerdo al "ExpeditionPlace"
                ExpeditionPlace = "78000",                                       // Codigo postal del la sucursal desde donde se expide el CFDI, (este debe pertenecer al catálogo de sucursales)  https://apisandbox.facturama.mx/guias/perfil-fiscal#lugares-expedicion-series
                Items           = new List <Item>(),
                Issuer          = new Issuer
                {
                    Name         = "Escuela emisora del CFDI",
                    Rfc          = "EKU9003173C9",
                    FiscalRegime = "601"
                },
                Receiver = new Receiver
                {
                    CfdiUse = "P01",
                    Name    = "José Perez Leon",
                    Rfc     = "JUFA7608212V6",
                    Address = new Address                       // El nodo Address es opcional (puedes colocarlo nulo o no colocarlo). En el caso de no colcoarlo, tomará la correspondiente al RFC en el catálogo de clientes
                    {
                        Street         = "Avenida de los pinos",
                        ExteriorNumber = "110",
                        InteriorNumber = "A",
                        Neighborhood   = "Las villerías",
                        ZipCode        = "78000",
                        Municipality   = "San Luis Potosí",
                        State          = "San Luis Potosí",
                        Country        = "México"
                    }
                },
            };

            // Complemento IEDU
            var itemComplement = new Facturama.Models.Complements.ItemComplement();

            itemComplement.EducationalInstitution = new EducationalInstitution
            {
                AutRvoe        = "234",
                Curp           = "POAJ890718HSPMLS05",
                EducationLevel = "Profesional técnico",
                StudentsName   = "Emilio Perez Lopez",
                PaymentRfc     = "XAMA620210DQ5"
            };

            var item = new Item
            {
                ProductCode          = "86121503",              // Reacionado con institucion educativa
                UnitCode             = "E48",                   // Servicio
                Unit                 = "Unidad de servicio",
                Description          = "Colegiatura del mes de marzo",
                IdentificationNumber = "1234",                  // Numero de identificación interno del producto (opcional)
                Quantity             = 1,
                Discount             = 0,
                UnitPrice            = 2300,
                Subtotal             = 2300,
                Taxes                = new [] { new Tax
                                                {
                                                    Name        = "IVA",
                                                    IsQuota     = false,
                                                    IsRetention = false,

                                                    Rate  = 0.16m,
                                                    Base  = 2300,
                                                    Total = 368
                                                } }.ToList(),
                Complement = itemComplement                     // Complemento IEDU
            };
            var retenciones = item.Taxes?.Where(t => t.IsRetention).Sum(t => t.Total) ?? 0;
            var traslados   = item.Taxes?.Where(t => !t.IsRetention).Sum(t => t.Total) ?? 0;

            item.Total = item.Subtotal - (item.Discount ?? 0) + traslados - retenciones;
            cfdi.Items.Add(item);

            try
            {
                var cfdiCreated = facturama.Cfdis.Create(cfdi);
                Console.WriteLine(
                    $"Se creó exitosamente el cfdi con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                facturama.Cfdis.SavePdf($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.pdf", cfdiCreated.Id);
                facturama.Cfdis.SaveXml($"factura{cfdiCreated.Complement.TaxStamp.Uuid}.xml", cfdiCreated.Id);


                if (facturama.Cfdis.SendByMail(cfdiCreated.Id, "*****@*****.**"))
                {
                    Console.WriteLine("Se envió correctamente el CFDI");
                }


                var cancelationStatus = facturama.Cfdis.Cancel(cfdiCreated.Id);
                if (cancelationStatus.Status == "canceled")
                {
                    Console.WriteLine($"Se canceló exitosamente el CFDI con el folio fiscal: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else if (cancelationStatus.Status == "pending")
                {
                    Console.WriteLine($"El CFDI está en proceso de cancelacion, require aprobacion por parte del receptor UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else if (cancelationStatus.Status == "active")
                {
                    Console.WriteLine($"El CFDI no pudo ser cancelado, se deben revisar docuementos relacionados on cancelar directo en el SAT UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
                else
                {
                    Console.WriteLine($"Estado de cancelacin del CFDI desconocido UUID: {cfdiCreated.Complement.TaxStamp.Uuid}");
                }
            }
            catch (FacturamaException ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.Model.Details != null)
                {
                    foreach (var messageDetail in ex.Model.Details)
                    {
                        Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inesperado: ", ex.Message);
            }

            Console.WriteLine("----- Fin del ejemplo EducationalInstitutionComplementExampleMultiemisor  -----");
        }