private static void TestValidationsClient(FacturamaApi facturama) { try { var cliente = facturama.Clients.Create(new Client { Address = new Address { Country = "MEXICO", ExteriorNumber = "1230", InteriorNumber = "B", Locality = "San Luis", Municipality = "San Luis Potosí", Neighborhood = "Lomas 4ta", State = "San Luis Potosí", Street = "Cañada de Gomez", ZipCode = "7822015" }, CfdiUse = "P0001", Email = "diego@@facturama.com.mx", Rfc = "ESO1202108R245", Name = "Expresion en Software" }); } catch (FacturamaException ex) { Console.WriteLine(ex.Message); foreach (var messageDetail in ex.Model.Details) { Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}"); } } Console.ReadKey(); }
/** * Llenado del modelo de CFDI, de una forma general * - Se especifica: la moneda, método de pago, forma de pago, cliente, y lugar de expedición */ private static Facturama.Models.Request.Cfdi CreateModelCfdiGeneral(FacturamaApi facturama) { var products = facturama.Products.List().Where(p => p.Taxes.Any()).ToList(); var nameId = facturama.Catalogs.NameIds.First(); //Nombre en el pdf: "Factura" var currency = facturama.Catalogs.Currencies.First(m => m.Value == "MXN"); var paymentMethod = facturama.Catalogs.PaymentMethods.First(p => p.Value == "PUE"); var paymentForm = facturama.Catalogs.PaymentForms.First(p => p.Name == "Efectivo"); var cliente = facturama.Clients.List().First(c => c.Rfc == "ESO1202108R2"); var branchOffice = facturama.BranchOffices.List().First(); var cfdi = new Cfdi { NameId = nameId.Value, CfdiType = CfdiType.Ingreso, PaymentForm = paymentForm.Value, PaymentMethod = paymentMethod.Value, Currency = currency.Value, Date = DateTime.Now, ExpeditionPlace = branchOffice.Address.ZipCode, //Items = new List<Item>(), Receiver = new Receiver { CfdiUse = cliente.CfdiUse, Name = cliente.Name, Rfc = cliente.Rfc }, }; return(cfdi); }
public void BranchOffice() { var facturama = new FacturamaApi("pruebas", "pruebas2011"); var Cont = facturama.BranchOffices.List(); var ContUno = Cont.Count; var sucursal = facturama.BranchOffices.Create(new BranchOffice { Address = new Address { Country = "MEXICO", ExteriorNumber = "1230", InteriorNumber = "B", Locality = "Aguascalientes", Municipality = "Aguascalientes", Neighborhood = "ojo caliente", State = "Aguascalientes", Street = "Cañada de Gomez", ZipCode = "78000" }, Name = "La Ofi", Description = "un lugar bonito pa trabajar", }); Assert.IsNotNull(sucursal.Id); sucursal.Name = "Rancho La Chingada"; facturama.BranchOffices.Update(sucursal, sucursal.Id); sucursal = facturama.BranchOffices.Retrieve(sucursal.Id); Assert.AreEqual(sucursal.Name = "Rancho La Chingada", sucursal.Name); facturama.BranchOffices.Remove(sucursal.Id); var Conta = facturama.BranchOffices.List(); var ContDos = Conta.Count; Assert.AreEqual(ContUno, ContDos); }
/** * Llenado del modelo de CFDI, de una forma general * - Se especifica: la moneda, método de pago, forma de pago, cliente, y lugar de expedición */ private static Facturama.Models.Request.Cfdi CreateModelCfdiGeneral(FacturamaApi facturama) { var products = facturama.Products.List().Where(p => p.Taxes.Any()).ToList(); var nameId = facturama.Catalogs.NameIds.First(); //Nombre en el pdf: "Factura" var currency = facturama.Catalogs.Currencies.First(m => m.Value == "MXN"); var paymentMethod = facturama.Catalogs.PaymentMethods.First(p => p.Value == "PUE"); var paymentForm = facturama.Catalogs.PaymentForms.First(p => p.Name == "Efectivo"); var cliente = facturama.Clients.List().First(); var branchOffice = facturama.BranchOffices.List().First(); var cfdi = new Cfdi { NameId = nameId.Value, CfdiType = CfdiType.Ingreso, PaymentForm = paymentForm.Value, PaymentMethod = paymentMethod.Value, Currency = currency.Value, Date = null, ExpeditionPlace = "83170", //Items = new List<Item>(), Receiver = new Receiver { CfdiUse = "P01", Name = "Público en general", Rfc = "XAXX010101000" }, }; return(cfdi); }
static void Main(string[] args) { var facturama = new FacturamaApi("pruebas", "pruebas2011"); TestCrudClient(facturama); //TestValidationsClient(facturama); //TestCreateProduct(facturama); //TestCreateCfdi(facturama); }
private static void TestCreateProduct(FacturamaApi facturama) { var unit = facturama.Catalogs.Units("servicio")[0]; var prod = facturama.Catalogs.ProductsOrServices("desarrollo")[0]; var product = new Product { Unit = "Servicio", UnitCode = unit.Value, IdentificationNumber = "WEB003", Name = "Sitio Web CMS", Description = "Desarrollo e implementación de sitio web empleando un CMS", Price = 6500.0m, CodeProdServ = prod.Value, CuentaPredial = "123", Taxes = new[] { new Tax { Name = "IVA", Rate = 0.16m, IsRetention = false, }, new Tax { Name = "ISR", IsRetention = true, Total = 0.1m }, new Tax { Name = "IVA", IsRetention = true, Total = 0.106667m } } }; try { product = facturama.Products.Create(product); Console.WriteLine("Se creo exitosamente un producto con el id: " + product.Id); facturama.Products.Remove(product.Id); Console.WriteLine("Se elimino exitosamente un producto con el id: " + product.Id); } catch (FacturamaException ex) { Console.WriteLine(ex.Message); foreach (var messageDetail in ex.Model.Details) { Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}"); } } }
private static Facturama.Models.Request.Cfdi AddItemsToCfdi(FacturamaApi facturama, Cfdi cfdi) { // Lista de todos los productos List <Product> lstProducts = facturama.Products.List(); Random random = new Random(); var currency = facturama.Catalogs.Currencies.First(m => m.Value == "MXN"); int nItems = random.Next(lstProducts.Count) % 10 + 1; int decimals = (int)currency.Decimals; // Lista de Items en el cfdi (los articulos a facturar) List <Item> lstItems = new List <Item>(); // Creacion del CFDI for (int i = lstProducts.Count - nItems; i < lstProducts.Count && i > 0; i++) { Product product = lstProducts.ElementAt(i); // Un producto cualquiera int quantity = random.Next(1, 5) + 1; // una cantidad aleatoria de elementos de este producto Double discount = Decimal.ToDouble(product.Price % (product.Price == 0 ? 1 : random.Next(1, Decimal.ToInt32(product.Price)))); // Redondeo del precio del producto, de acuerdo a la moneda Double numberOfDecimals = Math.Pow(10, decimals); Double subTotal = Math.Round((Decimal.ToDouble(product.Price) * quantity) * numberOfDecimals) / numberOfDecimals; // Llenado del item (que va en el cfdi) Item item = new Item { ProductCode = product.CodeProdServ, UnitCode = product.UnitCode, Unit = product.Unit, Description = $"Item{i}: product.Description", IdentificationNumber = product.IdentificationNumber, Quantity = quantity, Discount = Convert.ToDecimal(Math.Round(discount * numberOfDecimals) / numberOfDecimals), UnitPrice = Convert.ToDecimal(Math.Round(Decimal.ToDouble(product.Price) * numberOfDecimals) / numberOfDecimals), Subtotal = Convert.ToDecimal(subTotal) }; // ---- Llenado de los impuestos del item ---- item = AddTaxesToItem(item, product, numberOfDecimals); if (item.UnitPrice > 0m) { lstItems.Add(item); } } cfdi.Items = lstItems; return(cfdi); }
public CDPaymentComplement() { //Api _facturamaWeb = new FacturamaApi("pruebas", "pruebas2011"); /*// Ejemplo de la creación de un complemento de pago * SamplePaymentComplement(facturama); */ //Api Multiemisor _facturamaMultiEmisor = new FacturamaApiMultiemisor("pruebas", "pruebas2011"); // Ejemplo de la creación de un complemento de pago Multiemeisor //SampleCreatePaymentCfdiMultiemisor(facturamaMultiEmisor); }
/// <summary> /// CRUD de ejemplo para productos /// </summary> /// <param name="facturama"></param> private void CrudProductExample(FacturamaApi facturama) { Console.WriteLine("----- CatalogsExample > CrudProductExample - Inicio -----"); var unit = facturama.Catalogs.Units("servicio")[0]; var prod = facturama.Catalogs.ProductsOrServices("desarrollo")[0]; var product = new Product { Unit = "Servicio", UnitCode = unit.Value, IdentificationNumber = "WEB003", Name = "Sitio Web CMS", Description = "Desarrollo e implementación de sitio web empleando un CMS", Price = 6500.0m, CodeProdServ = prod.Value, CuentaPredial = "123", Taxes = new[] { new Tax { Name = "IVA", Rate = 0.16m, IsRetention = false, }, new Tax { Name = "ISR", IsRetention = true, Total = 0.1m }, new Tax { Name = "IVA", IsRetention = true, Total = 0.106667m } } }; product = facturama.Products.Create(product); Console.WriteLine("Se creo exitosamente un producto con el id: " + product.Id); facturama.Products.Remove(product.Id); Console.WriteLine("Se elimino exitosamente un producto con el id: " + product.Id); Console.WriteLine("----- CatalogsExample > CrudProductExample - Fin -----"); }
public void SerieTest() { var facturama = new FacturamaApi("pruebas", "pruebas2011"); var serie = (new Serie { IdBranchOffice = "G8H81UGPAcqAXVXxtfhGyw2", Name = "Trabajo", Description = "A Nice Place to Work", Folio = 100 }); serie = facturama.Series.Create(serie); Assert.IsNull(serie.IdBranchOffice); serie.Folio = 105; serie.IdBranchOffice = "G8H81UGPAcqAXVXxtfhGyw2"; serie = facturama.Series.Retrieve(serie.IdBranchOffice, serie.Name); Assert.AreEqual(serie.Folio = 99, serie.Folio); }
/// <summary> /// CRUD de ejemplo para clientes /// </summary> /// <param name="facturama"></param> private void CrudClientExample(FacturamaApi facturama) { Console.WriteLine("----- CatalogsExample > CrudClientExample - Inicio -----"); var clientes = facturama.Clients.List(); // Obtiene el listado de clientes var clientesBefore = clientes.Count; var cliente = facturama.Clients.Create(new Client // Agrega un nuevo cliente { Address = new Address { Country = "MEXICO", ExteriorNumber = "1230", InteriorNumber = "B", Locality = "San Luis", Municipality = "San Luis Potosí", Neighborhood = "Lomas 4ta", State = "San Luis Potosí", Street = "Cañada de Gomez", ZipCode = "78220" }, CfdiUse = "P01", Email = "*****@*****.**", Rfc = "EWE1709045U0", Name = "Expresion en Software" }); cliente = facturama.Clients.Retrieve(cliente.Id); // Detalle de cliente cliente.Rfc = "XAXX010101000"; facturama.Clients.Update(cliente, cliente.Id); // Actualizar datos cliente = facturama.Clients.Retrieve(cliente.Id); Console.WriteLine(cliente.Rfc == "XAXX010101000" ? "Cliente Editado" : "Error al editar cliente"); facturama.Clients.Remove(cliente.Id); // Eliminar cliente clientes = facturama.Clients.List(); var clientesAfter = clientes.Count; Console.WriteLine(clientesAfter == clientesBefore ? "Test Passed!" : "Test Failed!"); Console.WriteLine("----- CatalogsExample > CrudClientExample - Fin -----"); }
public void SerieTest() { var facturama = new FacturamaApi("pruebas", "pruebas2011"); var serie = (new Serie { IdBranchOffice = "yzBJZx7uYQiX8FhGN_WIOQ2", Name = "TR" + DateTime.Now.ToString("MMddmmss"), Description = "A Nice Place to Work", Folio = 100 }); serie = facturama.Series.Create(serie); Assert.IsNull(serie.IdBranchOffice); serie.IdBranchOffice = "yzBJZx7uYQiX8FhGN_WIOQ2"; serie.Description = "Serie Editada"; //Solo la descripcion es editable facturama.Series.Update(serie); serie = facturama.Series.Retrieve(serie.IdBranchOffice, serie.Name); Assert.AreEqual("Serie Editada", serie.Description); Assert.AreEqual(serie.Folio = 99, serie.Folio); }
public void CrudCliente() { var facturama = new FacturamaApi("pruebas", "pruebas2011"); var clientes = facturama.Clients.List(); var clientesBefore = clientes.Count; var cliente = facturama.Clients.Create(new Client { Address = new Address { Country = "MEXICO", ExteriorNumber = "1230", InteriorNumber = "B", Locality = "San Luis", Municipality = "San Luis Potosí", Neighborhood = "Lomas 4ta", State = "San Luis Potosí", Street = "Cañada de Gomez", ZipCode = "78220" }, CfdiUse = "P01", Email = "*****@*****.**", Rfc = "JES900109Q90", Name = "Expresion en Software" }); cliente = facturama.Clients.Retrieve(cliente.Id); cliente.Rfc = "XAXX010101000"; facturama.Clients.Update(cliente, cliente.Id); cliente = facturama.Clients.Retrieve(cliente.Id); Assert.AreEqual(cliente.Rfc = "XAXX010101000", cliente.Rfc); facturama.Clients.Remove(cliente.Id); clientes = facturama.Clients.List(); var clientesAfter = clientes.Count; Assert.AreEqual(clientesAfter, clientesBefore); }
private static void TestCrudClient(FacturamaApi facturama) { var clientes = facturama.Clients.List(); var clientesBefore = clientes.Count; var cliente = facturama.Clients.Create(new Client { Address = new Address { Country = "MEXICO", ExteriorNumber = "1230", InteriorNumber = "B", Locality = "San Luis", Municipality = "San Luis Potosí", Neighborhood = "Lomas 4ta", State = "San Luis Potosí", Street = "Cañada de Gomez", ZipCode = "78220" }, CfdiUse = "P01", Email = "*****@*****.**", Rfc = "ESO1202108R2", Name = "Expresion en Software" }); cliente = facturama.Clients.Retrieve(cliente.Id); cliente.Rfc = "XAXX010101000"; facturama.Clients.Update(cliente, cliente.Id); cliente = facturama.Clients.Retrieve(cliente.Id); Console.WriteLine(cliente.Rfc == "XAXX010101000" ? "Cliente Editado" : "Error al editar cliente"); facturama.Clients.Remove(cliente.Id); clientes = facturama.Clients.List(); var clientesAfter = clientes.Count; Console.WriteLine(clientesAfter == clientesBefore ? "Test Passed!" : "Test Failed!"); }
public void CreaYBorraProducto() { var facturama = new FacturamaApi("pruebas", "pruebas2011"); var productOs = facturama.Clients.List(); var productOsAntes = productOs.Count; var unit = facturama.Catalogs.Units("servicio")[0]; var prod = facturama.Catalogs.ProductsOrServices("desarrollo")[0]; var product = facturama.Products.Create(new Product { Unit = "Servicio", UnitCode = unit.Value, IdentificationNumber = "WEB003", Name = "Sitio Web CMS", Description = "Desarrollo e implementación de sitio web empleando un CMS", Price = 6500.0m, CodeProdServ = prod.Value, CuentaPredial = "123", Taxes = new[] { new Tax { Name = "IVA", Rate = 0.16m, IsRetention = false, }, new Tax { Name = "ISR", IsRetention = true, Total = 0.1m }, new Tax { Name = "IVA", IsRetention = true, Total = 0.106667m } } }); try { Assert.IsNotNull(product.Id); //<-------------------update and retrive----------------------------------->> product.CuentaPredial = "420"; product = facturama.Products.Update(product, product.Id); Assert.AreEqual(product.CuentaPredial = "420", product.CuentaPredial); product = facturama.Products.Retrieve(product.Id); Assert.IsNotNull(product.Id); facturama.Products.Remove(product.Id); productOs = facturama.Clients.List(); var productOsFinales = productOs.Count; Assert.AreEqual(productOsFinales, productOsAntes); } catch (FacturamaException ex) { Console.WriteLine(ex.Message); foreach (var messageDetail in ex.Model.Details) { Console.WriteLine($"{messageDetail.Key}: {string.Join(",", messageDetail.Value)}"); } } }
/** * Modelo "Complemento de pago" * - Se especifica: la moneda, método de pago, forma de pago, cliente, y lugar de expedición */ private static Facturama.Models.Request.Cfdi CreateModelCfdiPaymentComplement(FacturamaApi facturama, Facturama.Models.Response.Cfdi cfdiInicial) { Cfdi cfdi = new Cfdi(); // Lista del catálogo de nombres en el PDF var nameForPdf = facturama.Catalogs.NameIds.First(m => m.Value == "14"); // Nombre en el pdf: "Complemento de pago" cfdi.NameId = nameForPdf.Value; // Receptor de comprobante (se toma como cliente el mismo a quien se emitió el CFDI Inicial), String clientRfc = cfdiInicial.Receiver.Rfc; Client client = facturama.Clients.List().Where(p => p.Rfc.Equals(clientRfc)).First(); Receiver receiver = new Receiver { CfdiUse = "P01", Name = client.Name, Rfc = client.Rfc }; cfdi.Receiver = receiver; // Lugar de expedición (es necesario por lo menos tener una sucursal) BranchOffice branchOffice = facturama.BranchOffices.List().First(); cfdi.ExpeditionPlace = "78240"; // Fecha y hora de expecidión del comprobante //DateTime bindingDate; //DateTime.TryParse(cfdiBinding.Date, null, DateTimeStyles.RoundtripKind, out bindingDate); cfdi.Date = null; // Puedes especificar una fecha por ejemplo: DateTime.Now cfdi.CfdiType = CfdiType.Pago; // Complemento de pago --- Complement complement = new Complement(); // Pueden representarse más de un pago en un solo CFDI List <Facturama.Models.Complements.Payment> lstPagos = new List <Facturama.Models.Complements.Payment>(); Facturama.Models.Complements.Payment pago = new Facturama.Models.Complements.Payment(); // Fecha y hora en que se registró el pago en el formato: "yyyy-MM-ddTHH:mm:ss" // (la fecha del pago debe ser menor que la fecha en que se emite el CFDI) // Para este ejemplo, se considera que el pago se realizó hace una hora pago.Date = DateTime.Now.AddHours(-6).ToString("yyyy-MM-dd HH:mm:ss"); // Forma de pago (Efectivo, Tarjeta, etc) Facturama.Models.Response.Catalogs.CatalogViewModel paymentForm = facturama.Catalogs.PaymentForms.Where(p => p.Name.Equals("Efectivo")).First(); pago.PaymentForm = paymentForm.Value; // Selección de la moneda del catálogo // La Moneda, puede ser diferente a la del documento inicial // (En el caso de que sea diferente, se debe colocar el tipo de cambio) List <CurrencyCatalog> lstCurrencies = facturama.Catalogs.Currencies.ToList(); CurrencyCatalog currency = lstCurrencies.Where(p => p.Value.Equals("MXN")).First(); pago.Currency = currency.Value; // Monto del pago // Este monto se puede distribuir entre los documentos relacionados al pago pago.Amount = 100.00m; // Documentos relacionados con el pago // En este ejemplo, los datos se obtiene el cfdiInicial, pero puedes colocar solo los datos // aun sin tener el "Objeto" del cfdi Inicial, ya que los valores son del tipo "String" List <Facturama.Models.Complements.RelatedDocument> lstRelatedDocuments = new List <Facturama.Models.Complements.RelatedDocument>(); Facturama.Models.Complements.RelatedDocument relatedDocument = new Facturama.Models.Complements.RelatedDocument { Uuid = cfdiInicial.Complement.TaxStamp.Uuid, // "27568D31-E579-442F-BA77-798CBF30BD7D" Serie = "A", //cfdiInicial.Serie, // "EA" Folio = cfdiInicial.Folio, // 34853 Currency = currency.Value, PaymentMethod = "PUE", // En el complemento de pago tiene que ser PUE PartialityNumber = 1, PreviousBalanceAmount = 100.00m, AmountPaid = 100.00m }; lstRelatedDocuments.Add(relatedDocument); pago.RelatedDocuments = lstRelatedDocuments; lstPagos.Add(pago); complement.Payments = lstPagos; cfdi.Complement = complement; return(cfdi); }
public PaymentComplementExample(FacturamaApi facturama) { this.facturama = facturama; }
public EducationalInstitutionComplementExample(FacturamaApi facturama) { this.facturama = facturama; }
public void Test() { var facturama = new FacturamaApi("pruebas", "pruebas2011"); var cfdi = new Cfdi { Serie = "R", Currency = "MXN", ExpeditionPlace = "78116", PaymentConditions = "CREDITO A SIETE DIAS", CfdiType = CfdiType.Ingreso, PaymentForm = "03", PaymentMethod = "PUE", Receiver = new Receiver { Rfc = "EKU9003173C9", Name = "RADIAL SOFTWARE SOLUTIONS", CfdiUse = "P01" }, Items = new List <Item> { new Item { ProductCode = "10101504", IdentificationNumber = "EDL", Description = "Estudios de viabilidad", Unit = "NO APLICA", UnitCode = "MTS", UnitPrice = 50.00m, Quantity = 2.00m, Subtotal = 100.00m, Taxes = new List <Tax> { new Tax { Total = 16.00m, Name = "IVA", Base = 100.00m, Rate = 0.160000m, IsRetention = false } }, Total = 116.0m, Complement = new ItemComplement { ThirdPartyAccount = new ThirdPartyAccount { Rfc = "JES900109Q90", Name = "Expresión en Software", Taxes = new List <ThirdPartyAccountTax> { new ThirdPartyAccountTax { Name = "IVA", Rate = 0.16m, Amount = 1000.00m } } } } } } }; var cfdiCreated = facturama.Cfdis.Create(cfdi); Assert.IsTrue(Guid.TryParse(cfdiCreated.Complement.TaxStamp.Uuid, out _)); }
/** * Ejemplo de creación de un CFDI "complemento de pago" * Referencia: https://apisandbox.facturama.mx/guias/api-web/cfdi/complemento-pago * * En virtud de que el complemento de pago, requiere ser asociado a un CFDI con el campo "PaymentMethod" = "PPD" * En este ejemplo se incluye la creacón de este CFDI, para posteriormente realizar el "Complemento de pago" = "PUE" */ private static void SamplePaymentComplement(FacturamaApi facturama) { try { Console.WriteLine("----- Inicio del ejemplo samplePaymentComplement -----"); // Cfdi Incial (debe ser "PPD") // -------- Creacion del cfdi en su forma general (sin items / productos) asociados -------- Facturama.Models.Request.Cfdi cfdi = CreateModelCfdiGeneral(facturama); // -------- Agregar los items que lleva el cfdi ( para este ejemplo, se agregan con datos aleatorios) -------- cfdi = AddItemsToCfdi(facturama, cfdi); cfdi.PaymentMethod = "PPD"; // El método de pago del documento inicial debe ser "PPD" // Se manda timbrar mediante Facturama Facturama.Models.Response.Cfdi cfdiInicial = facturama.Cfdis.Create(cfdi); Console.WriteLine("Se creó exitosamente el cfdi Inicial (PPD) con el folio fiscal: " + cfdiInicial.Complement.TaxStamp.Uuid); // Descarga de los archivos del documento inicial String filePath = "factura" + cfdiInicial.Complement.TaxStamp.Uuid; facturama.Cfdis.SavePdf(filePath + ".pdf", cfdiInicial.Id); facturama.Cfdis.SaveXml(filePath + ".xml", cfdiInicial.Id); // Complemento de pago (debe ser "PUE") // Y no lleva "Items" solo especifica el "Complemento" Facturama.Models.Request.Cfdi paymentComplementModel = CreateModelCfdiPaymentComplement(facturama, cfdiInicial); // Se manda timbrar el complemento de pago mediante Facturama Facturama.Models.Response.Cfdi paymentComplement = facturama.Cfdis.Create(paymentComplementModel); Console.WriteLine("Se creó exitosamente el complemento de pago con el folio fiscal: " + cfdiInicial.Complement.TaxStamp.Uuid); // Descarga de los archivos del documento inicial String filePathPayment = "factura" + paymentComplement.Complement.TaxStamp.Uuid; facturama.Cfdis.SavePdf(filePath + ".pdf", paymentComplement.Id); facturama.Cfdis.SaveXml(filePath + ".xml", paymentComplement.Id); // Posibilidad de mandar los cfdis por coreo ( el cfdiInical y complemento de pago) Console.WriteLine(facturama.Cfdis.SendByMail(cfdiInicial.Id, "*****@*****.**")); Console.WriteLine(facturama.Cfdis.SendByMail(paymentComplement.Id, "*****@*****.**")); Console.WriteLine("----- Fin del ejemplo de samplePaymentComplement -----"); } 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 CatalogsExample(FacturamaApi facturama) { this.facturama = facturama; }
public WaybillComplementExample(FacturamaApi facturama) { this.facturama = facturama; }
public PayrollExample(FacturamaApi facturama) { this.facturama = facturama; }
public InvoiceExample(FacturamaApi facturama) { this.facturama = facturama; }
/** * Llenado del modelo de CFDI para Nóminas */ private static Cfdi CreatePayrollModel(FacturamaApi facturama) { var products = facturama.Products.List().Where(p => p.Taxes.Any()).ToList(); var nameId = "16"; // "Nomina" de acuerdo al catálogo de nombres https://apisandbox.facturama.mx/guias/catalogos/nombres-cfdi var currency = facturama.Catalogs.Currencies.First(m => m.Value == "MXN"); var paymentMethod = facturama.Catalogs.PaymentMethods.First(p => p.Value == "PUE"); var paymentForm = "99"; // 99 = por definir var cliente = facturama.Clients.List().First(); // Puedes seleccionar el cliente de tu catálogo de clientes var branchOffice = facturama.BranchOffices.List().First(); var lstPerceptions = new List <PerceptionsDetail>(); lstPerceptions.Add(new PerceptionsDetail { PerceptionType = "046", Code = "046", Description = "ASIMILIADOS A SALARIOS", TaxedAmount = 3621.18m, ExemptAmount = 0m }); var lstDeductions = new List <DeductionsDetail>(); lstDeductions.Add(new DeductionsDetail { DeduccionType = "002", Code = "002", Description = "ISR", Amount = 172.60M }); var lstOtherPayments = new List <OtherPayment>(); lstOtherPayments.Add(new OtherPayment { EmploymentSubsidy = new EmploymentSubsidy { Amount = 10 }, OtherPaymentType = "002", Code = "000", Description = "Subsidio", Amount = 10 }); var payroll = new Cfdi { NameId = nameId, CfdiType = CfdiType.Nomina, PaymentForm = paymentForm, PaymentMethod = "PUE", // Pago en una exhibicion Currency = currency.Value, Date = null, ExpeditionPlace = "78220", Receiver = new Receiver // En este caso pudimos poner los datos de cliente tomado del catálogo, o colocar los datos de otra fuente { CfdiUse = "P01", Name = "ADRIANA GARCIA MORALES", Rfc = "CACX7605101P8" }, Complement = new Complement { Payroll = new Payroll { Type = "O", // Tipo de nomina [O = ordinaria, E = exenta] DailySalary = 0m, BaseSalary = 0m, PaymentDate = Convert.ToDateTime("2020-10-06"), InitialPaymentDate = Convert.ToDateTime("2020-10-06"), FinalPaymentDate = Convert.ToDateTime("2020-10-06"), DaysPaid = 15, Issuer = new PayrollIssuer { EmployerRegistration = "SampleRegistration" }, Employee = new Employee { Curp = "GAMA800912MSPRRD05", SocialSecurityNumber = "92919084431", PositionRisk = "1", ContractType = "01", RegimeType = "02", Unionized = false, TypeOfJourney = "01", EmployeeNumber = "006", Department = null, Position = null, FrequencyPayment = "04", FederalEntityKey = "SLP", DailySalary = 50, StartDateLaborRelations = Convert.ToDateTime("2019-10-06"), }, Perceptions = new Perceptions { Details = lstPerceptions.ToArray() }, Deductions = new Deductions { Details = lstDeductions.ToArray() }, OtherPayments = lstOtherPayments.ToArray() } } }; return(payroll); }
private static void TestCreateCfdi(FacturamaApi facturama) { var products = facturama.Products.List().Where(p => p.Taxes.Any()).ToList(); 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 cliente = facturama.Clients.List().First(c => c.Rfc == "XAXX010101000"); var branchOffice = facturama.BranchOffices.List().First(); var random = new Random(); var nitems = random.Next(1, products.Count) % 10; // Cantidad de items para la factura var decimals = (int)currency.Decimals; var cfdi = new Cfdi { NameId = nameId.Value, CfdiType = CfdiType.Ingreso, PaymentForm = paymentForm.Value, PaymentMethod = paymentMethod.Value, Currency = currency.Value, Date = DateTime.Now, ExpeditionPlace = branchOffice.Address.ZipCode, Items = new List <Item>(), Receiver = new Receiver { CfdiUse = cliente.CfdiUse, Name = cliente.Name, Rfc = cliente.Rfc }, }; for (var i = products.Count - nitems; i < products.Count && i > 0; i++) { var product = products[i]; var quantity = random.Next(1, 5); //Una cantidad aleatoria var discount = product.Price % (product.Price == 0 ? 1 : random.Next(0, (int)product.Price)); //Un descuento aleatorio var subtotal = Math.Round(product.Price * quantity, decimals); var item = new Item { ProductCode = product.CodeProdServ, UnitCode = product.UnitCode, Unit = product.Unit, Description = product.Description, IdentificationNumber = product.IdentificationNumber, Quantity = quantity, Discount = Math.Round(discount, decimals), UnitPrice = Math.Round(product.Price, decimals), Subtotal = subtotal, Taxes = product.Taxes?.Select( t => { var baseAmount = Math.Round(subtotal - discount, decimals); return(new Tax { Name = t.Name, IsQuota = t.IsQuota, IsRetention = t.IsRetention, Rate = Math.Round(t.Rate, 6), Base = Math.Round(subtotal - discount, decimals), Total = Math.Round(baseAmount * t.Rate, decimals) }); }).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 + 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); var list = facturama.Cfdis.List("Expresion en Software"); 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); } Console.ReadKey(); }