Esempio n. 1
0
        static void Main(string[] args)
        {
            try
            {
                //CFDI F = new CFDI(@"C:\Users\carlos\Desktop\ZABE701111KR6CFDI0000009356.xml");
                //CFDI F = new CFDI(@"C:\Users\carlos\Desktop\mala.xml");
                CFDI F = new CFDI(@"C:\Users\carlos\Desktop\EjemploAddenda.XML");

                F.InitialzeValidation();

                if (F.Messages != null && F.Messages.Count > 0)
                {
                    foreach (string Message in F.Messages)
                    {
                        Console.WriteLine(Message);
                    }
                }

                if (F.IsValid)
                {
                    F.GenerateObj();
                }
                else
                {
                    Console.WriteLine("No es válido el CFDI");
                }

                Console.WriteLine(F.IsValid);
            }catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.Read();
        }
Esempio n. 2
0
        private void BtnAceptar_Click(object sender, EventArgs e)
        {
            if (!Ambiente.LoggedUser.Facturar)
            {
                Ambiente.Mensaje("Operacion denegada. No tienes permiso para operar esta vista.");
                return;
            }

            if (venta == null)
            {
                Ambiente.Mensaje("Proceso abortado, no se encontró ninguna ticket seleccionado");
                return;
            }

            //Si no seleccionó otro cliente, se recupera el de la venta
            if (cliente == null)
            {
                cliente = clienteController.SelectOne(venta.ClienteId);
            }

            //verificar que no sea pago con puntos
            if (venta.PuntosAplicados || venta.DescXpuntos > 0)
            {
                Ambiente.Mensaje("Proceso abortado, el documento se cobró con puntos.");
                return;
            }

            //valida rfc
            if (Ambiente.RFCvalido(cliente.Rfc))
            {
                //Anula el ticket y crea la venta factura (sin timbrar)
                if (ClonarVenta())
                {
                    var oCFDI = new CFDI();
                    oCFDI.Venta = venta;

                    //Timbra la venta
                    if (oCFDI.Facturar())
                    {
                        //  Ambiente.SaveAndPrintFactura(venta, true, false);
                        Ambiente.SaveAndPrintFactura(venta, true, false);


                        Close();
                    }
                    else
                    {
                        Ambiente.Mensaje("Algo salió mal al facturar la venta");
                    }
                }
                else
                {
                    Ambiente.Mensaje("No se clonó la venta");
                }
            }
            else
            {
                Ambiente.Mensaje("El rfc del cliente está mal formado");
            }
        }
        public void GuardarInformacion(RVCFDI33.GeneraCFDI objCfdi, Clientes Clientes, List <AdeudosInstalaciones> Adeudos, GetPAC_Result PAC, string Ruta, string NombreArchivo,
                                       int Folio, string Moneda, byte[] Logo, double Total, string FormaDePago, string MetodoPago, string CantidadPDF, string ConceptoPDF,
                                       string ValorUnitarioPDF, string ImportePDF, string UnidadPDF)
        {
            Usuarios usuario = db.Usuarios.Where(x => x.Usuario == User.Identity.Name).FirstOrDefault();

            System.IO.File.WriteAllText(Ruta + "\\" + NombreArchivo + ".xml", objCfdi.XmlTimbrado);
            byte[] XML = System.IO.File.ReadAllBytes(Ruta + "\\" + NombreArchivo + ".xml");
            foreach (var adeudo in Adeudos)
            {
                db.InsertCFDIPorOperacion(Guid.NewGuid(), null, adeudo.Id, Guid.Parse(objCfdi.UUID));
            }
            db.InsertCFDI(Guid.Parse(objCfdi.UUID), "Factura", Folio, XML, "~/Facturas/" + PAC.RFC + "/Facturas/" + NombreArchivo, Clientes.IdCliente, null, PAC.Id, false, DateTime.Now, usuario.Id);
            int TimbresUsados = 1;

            TimbresUsados = usuario.TimbresUsados + 1;
            db.UpdateUsuarios(usuario.Id, usuario.Usuario, usuario.Contraseña, usuario.TipoUsuario, usuario.Roles, usuario.Activo, usuario.Timbres, TimbresUsados, usuario.TimbresCancelados, usuario.PrimeraVez);
            string Domicilio = Clientes.Calle + " " + Clientes.NoExterior + " " + Clientes.Colonia + " C.P " + Clientes.CodigoPostal + " " + Clientes.Ciudad + "," + Clientes.Estado + " " + Clientes.Pais;
            double TotalImpuestosRetenidos = Total - (Total / 1.16);

            Tools.PDF.CrearFactura(Ruta + "\\", NombreArchivo, Moneda, Logo, objCfdi, PAC.RFC, PAC.Nombre, PAC.RegimenFiscal, Clientes.RFC, "22210"
                                   , Domicilio, FormaDePago, MetodoPago, Total.ToString("f2"), TotalImpuestosRetenidos.ToString("f2"), float.Parse((Total / 1.16) + "").ToString("f2"),
                                   CantidadPDF, ConceptoPDF, ValorUnitarioPDF, ImportePDF, UnidadPDF);
            if (Adeudos.FirstOrDefault().RequiereEnvio == true && !string.IsNullOrEmpty(Clientes.Email))
            {
                CFDI CFDI = db.GetCFDI(Guid.Parse(objCfdi.UUID), 1).First();
                Helpers.Correo.EnviarFactura(Clientes.Email, NombreArchivo, "http://facturacion.avenzo.mx/Facturas/Descargar", Server.MapPath("~/Tools/plantilla_facturas.html"), CFDI);
            }
        }
Esempio n. 4
0
 private void ValidarPedimento(CFDI pedimento)
 {
     //TODO:Agregar otras validaciones a funcion validar pedimento
     if (pedimento.ArchivoFisico.LongitudArchivo != pedimento.ArchivoFisico.ArchivoBytes.Length)
     {
         throw new ArchivoCorruptoException();
     }
 }
 public FrmFacturas()
 {
     InitializeComponent();
     ventaController    = new VentaController();
     clienteController  = new ClienteController();
     empresaController  = new EmpresaController();
     reporteController  = new ReporteController();
     dymErrorController = new DymErrorController();
     oCFDI   = new CFDI();
     cliente = null;
     empresa = empresaController.SelectTopOne();
     reporte = reporteController.SelectOneByName(empresa.FormatoParaFacturas);
 }
Esempio n. 6
0
        static void Main(string[] args)
        {
            PDF pdf = new PDF();


            string     xml        = @"C:\Users\tonovarela\Desktop\f.XML";
            FacturaXML facturaXML = new FacturaXML(xml, true);
            CFDI       cfdi       = facturaXML.ObtenerData();

            pdf.cfdi = cfdi;
            pdf.obtenerRepresentacionImpresa(new CLRcfdi.models.Cliente()
            {
                NoCliente = "Varela"
            });
        }
Esempio n. 7
0
        public static string createFile(
            string contentXML,
            string NoCliente             = "",
            string LugarYFechaExpedicion = "",
            string Direccion             = "",
            string CP                    = "",
            string Colonia               = "",
            string DelegacionEstado      = "",
            string Contacto              = "",
            string Telefono              = "",
            string Vencimiento           = "",
            string DescripcionMetodoPago = "",
            string DescripcionFormaPago  = "",
            string Referencia            = ""
            )
        {
            Cliente c = new Cliente();

            c.NoCliente             = NoCliente;
            c.LugarYFechaExpedicion = LugarYFechaExpedicion;
            c.Direccion             = Direccion;
            c.CP                    = CP;
            c.Colonia               = Colonia;
            c.DelegacionEstado      = DelegacionEstado;
            c.Contacto              = Contacto;
            c.Telefono              = Telefono;
            c.Vencimiento           = Vencimiento;
            c.DescripcionFormaPago  = DescripcionFormaPago;
            c.DescripcionMetodoPago = DescripcionMetodoPago;
            c.Referencia            = Referencia;


            try
            {
                FacturaXML facturaXML = new FacturaXML(contentXML, false);
                CFDI       cfdi       = facturaXML.ObtenerData();
                PDF        pdf        = new PDF();
                pdf.cfdi = cfdi;
                pdf.obtenerRepresentacionImpresa(c);
            }catch (Exception e)
            {
                return($"Error al crear archivo en la factura ");
            }



            return("Archivo Creado");
        }
Esempio n. 8
0
        private Archivo ConvertirArchivo(CFDI archivo)
        {
            var request = new Archivo()
            {
                ArchivoBytes          = archivo.ArchivoFisico.ArchivoBytes,
                TipoArchivoFiltro     = TipoArchivo.CFDI,
                ExtensionArchivo      = archivo.ArchivoFisico.ExtensionArchivo,
                FechaSubida           = archivo.ArchivoFisico.FechaSubida,
                LongitudArchivo       = archivo.ArchivoFisico.LongitudArchivo,
                NombreCompletoArchivo = archivo.ArchivoFisico.NombreCompletoArchivo,
                Patente       = archivo.ArchivoFisico.Patente,
                ExtensionData = archivo.ArchivoFisico.ExtensionData,
                IdCliente     = archivo.ArchivoFisico.IdCliente
            };

            return(request);
        }
Esempio n. 9
0
        public CuentaGasto ConvertirCfdIaCuentaGasto(CFDI cfdi)
        {
            var listaImpuestosTraslado  = CalcularImpuestoTraslado(cfdi.Comprobante.Impuestos.Traslados);
            var listaImpuestosRetencion = CalcularImpuestoRetencion(cfdi.Comprobante.Impuestos.Retenciones);
            var idMoneda = CatalogosRepositorio.ExtraerIdMonedaXAbreviatura(new BuscarCatalogo()
            {
                Alias = cfdi.Comprobante.Moneda
            });
            var idTipoComprobante = CatalogosRepositorio.ExtraerIdTipoComprobanteXNombreComprobante(new BuscarCatalogo()
            {
                Nombre = Convert.ToString(cfdi.Comprobante.tipoDeComprobante)
            });
            var cuentaGasto = new CuentaGasto()
            {
                IdEmpresa              = cfdi.IdEmpresa,
                IdPedimento            = cfdi.IdPedimento,
                NumeroFactura          = cfdi.Comprobante.noCertificado,
                OtrosDatos             = null,
                TimeStamp              = DateTime.Now,
                IdComplementoFacturaVW = 0,
                XML                 = cfdi.ArchivoFisico.NombreCompletoArchivo,
                PDF                 = null,
                IdMonedaVW          = idMoneda.Id,//método para buscar el tipo de moneda
                MontoTotal          = (double)cfdi.Comprobante.total,
                TipoCambio          = Convert.ToDouble(cfdi.Comprobante.TipoCambio),
                UUID                = cfdi.TimbreFiscalDigital.UUID,
                FechaFactura        = cfdi.Comprobante.fecha,
                Subtotal            = (double)cfdi.Comprobante.subTotal,
                IdTipoComprobanteVW = idTipoComprobante.Id,
                RFCEmisor           = cfdi.Comprobante.Emisor.rfc,
                NombreEmisor        = cfdi.Comprobante.Emisor.nombre,
                TrasladoImpuestos   = CalcularImpuestoTraslado(cfdi.Comprobante.Impuestos.Traslados),
                RetencionImpuestos  = CalcularImpuestoRetencion(cfdi.Comprobante.Impuestos.Retenciones),
                IVA                 = (double)TotalImpuesto(listaImpuestosTraslado, "IVA", true),
                IEPS                = (double)TotalImpuesto(listaImpuestosTraslado, "IEPS", true),
                RetencionIVA        = (double)TotalImpuesto(listaImpuestosRetencion, "", false),
                RetencionISR        = (double)TotalImpuesto(listaImpuestosRetencion, "", false),
                Confirmado          = false
            };

            return(cuentaGasto);
        }
        public ActionResult Descargar(Guid Id)
        {
            CFDI Factura = db.GetCFDI(Id, 1).First();

            byte[] XML;
            PAC    PAC = db.PAC.Where(x => x.Id == Factura.IdProveedor).FirstOrDefault();

            if (Factura.Cancelado == true)
            {
                try {
                    XML = System.IO.File.ReadAllBytes(Server.MapPath("~/Facturas/" + PAC.RFC + "/Cancelaciones") + "/Cancelacion_" + Factura.Folio + ".xml");
                } catch (Exception ex) {
                    XML = Factura.XML;
                }

                MemoryStream xml = new MemoryStream(XML);
                using (ZipFile zip = new ZipFile())
                {
                    MemoryStream memory = new MemoryStream();
                    zip.AddEntry("Factura_Cancelada_" + DateTime.Now.ToString("MM_dd_yyyy") + ".xml", xml);
                    zip.Save(memory);
                    memory.Seek(0, SeekOrigin.Begin);
                    return(File(memory, "application/zip", "Factura.zip"));
                }
            }
            else
            {
                XML = Factura.XML;
                byte[]       PDF = System.IO.File.ReadAllBytes(Server.MapPath(Factura.Ruta) + ".pdf");
                MemoryStream xml = new MemoryStream(XML);
                MemoryStream pdf = new MemoryStream(PDF);
                using (ZipFile zip = new ZipFile())
                {
                    MemoryStream memory = new MemoryStream();
                    zip.AddEntry("Factura_" + Factura.Folio + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".xml", xml);
                    zip.AddEntry("Factura_" + Factura.Folio + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".pdf", pdf);
                    zip.Save(memory);
                    memory.Seek(0, SeekOrigin.Begin);
                    return(File(memory, "application/zip", "Factura.zip"));
                }
            }
        }
Esempio n. 11
0
        private void ResetPDV()
        {
            venta            = new Venta();
            partidas         = new List <Ventap>();
            cliente          = null;
            producto         = null;
            SigPartida       = 0;
            datosCliente     = "PUBLICO EN GENERAL";
            TxtSubtotal.Text = "";
            TxtTotal.Text    = "";
            TxtCliente.Text  = "";

            ventaController    = new VentaController();
            ventapController   = new VentapController();
            productoController = new ProductoController();
            clienteController  = new ClienteController();

            ImpuestoController   = new ImpuestoController();
            empresaController    = new EmpresaController();
            loteController       = new LoteController();
            movInvController     = new MovInvController();
            flujoController      = new FlujoController();
            reporteController    = new ReporteController();
            dymErrorController   = new DymErrorController();
            formaPagoController  = new FormaPagoController();
            loteVentapController = new LoteVentapController();
            oCFDI = new CFDI();
            lote  = null;
            TxtProductoId.Focus();


            //Reset malla
            Malla.Rows.Clear();
            for (int i = 0; i < NPARTIDAS; i++)
            {
                Malla.Rows.Add();
                Malla.Rows[i].Cells[2].Style.BackColor = Color.Yellow;
                Malla.Rows[i].Cells[8].Style.BackColor = Color.Yellow;
            }
            CreaVenta();
        }
        private void Inicializa()
        {
            //Controladores
            ventaController  = new VentaController();
            ventapController = new VentapController();

            //Listas
            ventas   = new List <Venta>();
            partidas = new List <Ventap>();

            //Objetos
            venta   = null;
            partida = null;
            moneda  = new Moneda();
            oCFDI   = new CFDI();

            //Variables
            subtotal  = 0;
            impuestos = 0;
            total     = 0;
        }
        private void BtnGenerar_Click(object sender, EventArgs e)
        {
            if (!Venta.Consultar(ref _venta))
            {
                return;
            }

            Text = "Facturando....";

            CFDI cfdi = new CFDI();

            int res = cfdi.GenerarYTimbrar(ref _factura, _venta);

            if (res == CFDI.RESULT_ERROR_GENERAL)
            {
                MessageBox.Show("Error al crear la Factura", "Facturar", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Text = "Facturación";
                return;
            }
            else if (res == CFDI.RESULT_ERROR_TIMBRADO)
            {
                MessageBox.Show("Error al timbrar la Factura", "Facturar", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Text = "Facturación";
                return;
            }
            MessageBox.Show("Factura Realizada Correctamente", "Facturar", MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (!Factura.Guardar(ref _factura))
            {
                MessageBox.Show("Error al guardar la Factura", "Facturar", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Text = "Facturación";
                return;
            }
            MessageBox.Show("Factura Guardada Correctamente", "Guardar", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Text = "Facturación";
            BtnGenerar.Visible    = false;
            BtnGuardarXML.Visible = true;
            BtnGuardarPDF.Visible = true;
        }
 public ActionResult Cancelar(Guid Id)
 {
     try {
         CFDI          Factura = db.GetCFDI(Id, 1).FirstOrDefault();
         GetPAC_Result PAC     = db.GetPAC(null, 0).Where(x => x.Id == Factura.IdProveedor).First();
         RVCFDI33.RVCancelacion.Cancelacion Cancelar = new RVCFDI33.RVCancelacion.Cancelacion();
         string Certificado       = Server.MapPath("~/Certificados/" + PAC.RFC + "/" + PAC.RFC + ".cer"),
                Llave             = Server.MapPath("~/Certificados/" + PAC.RFC + "/" + PAC.RFC + ".key"),
                Cancelacion       = Server.MapPath("~/Facturas/" + PAC.RFC + "/Cancelaciones");
         string cadenaCancelacion = Cancelar.crearXMLCancelacionCadena(Certificado, Llave, PAC.ContrasenaLlave, Factura.Id.ToString());
         if (Cancelar.MensajeDeError == "")
         {
             //Cancelar.enviarCancelacionCadena(cadenaCancelacion, PAC.RFC, PAC.Contrasena, "http://generacfdi.com.mx/rvltimbrado/service1.asmx");
             if (Cancelar.CodigoDeError == 0)
             {
                 if (!System.IO.Directory.Exists(Cancelacion))
                 {
                     System.IO.Directory.CreateDirectory(Cancelacion);
                 }
                 System.IO.File.WriteAllText(Cancelacion + "\\Cancelacion_" + Factura.Folio + ".xml", cadenaCancelacion);
                 db.UpdateCFDI(Id, Factura.Tipo, Factura.Folio, Factura.XML, Factura.Ruta, Factura.IdCliente, Factura.IdEmpleado, Factura.IdProveedor, true);
                 return(Json(new { error = false }, JsonRequestBehavior.AllowGet));
             }
             else
             {
                 return(Json(new { error = "Error Al enviar la Cadena De Cancelacion", Message = Cancelar.MensajeDeError }, JsonRequestBehavior.AllowGet));
             }
         }
         else
         {
             return(Json(new { error = "Error Al hacer la Cadena De Cancelacion", Message = Cancelar.MensajeDeError }, JsonRequestBehavior.AllowGet));
         }
     }
     catch (Exception ex) {
         return(Json(new { error = "error", Message = ex.Message }, JsonRequestBehavior.AllowGet));
     }
 }
Esempio n. 15
0
 /// <summary>
 /// Esta función inserta en la base de datos, los datos del CFDI además que
 /// envía al servidor FTP el archivo físico
 /// </summary>
 /// <param name="cfdi">Contiene el archivo físico y los datos del CFDI</param>
 /// <returns></returns>
 public CuentaGasto InsertaFactura(CFDI cfdi)
 {
     ValidarPedimento(cfdi);
     using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required))
     {
         var idMoneda = CatalogosRepositorio.ExtraerIdMonedaXAbreviatura(new BuscarCatalogo()
         {
             Alias = "MXP"
         });
         //var cuentaGasto = ConvertirCfdIaCuentaGasto(cfdi);
         var idTipoComprobante = CatalogosRepositorio.ExtraerIdTipoComprobanteXNombreComprobante(new BuscarCatalogo()
         {
             Nombre = "ingreso"
         });                                                 //Borrar
         var crearImpuestoTraslado  = CrearImpuestosDemo();  //Borrar
         var crearImpuestoRetencion = CrearImpuestosDemo2(); //Borrar
         var cuentaGasto            = new CuentaGasto()      //Borrar
         {
             IdEmpresa              = 2,
             IdPedimento            = 1,
             NumeroFactura          = "1234ASDF1234ASDF",
             OtrosDatos             = null,
             TimeStamp              = DateTime.Now,
             IdComplementoFacturaVW = 0,
             XML                 = "PathXML",
             PDF                 = null,
             IdMonedaVW          = idMoneda.Id,
             MontoTotal          = 10000,
             TipoCambio          = 15,
             UUID                = "1234ASDFASDFQER12334",
             FechaFactura        = DateTime.Now,
             Subtotal            = 9000,
             IdTipoComprobanteVW = idTipoComprobante.Id,
             RFCEmisor           = "RFC123456DFF",
             NombreEmisor        = "Nombre Emisor",
             TrasladoImpuestos   = CalcularImpuestoTraslado(crearImpuestoTraslado),
             RetencionImpuestos  = CalcularImpuestoRetencion(crearImpuestoRetencion),
             IVA                 = (double)TotalImpuesto(CalcularImpuestoTraslado(crearImpuestoTraslado), "IVA", true),
             IEPS                = (double)TotalImpuesto(CalcularImpuestoTraslado(crearImpuestoTraslado), "IEPS", true),
             RetencionIVA        = (double)TotalImpuesto(CalcularImpuestoTraslado(crearImpuestoTraslado), "", false),
             RetencionISR        = (double)TotalImpuesto(CalcularImpuestoTraslado(crearImpuestoTraslado), "", false),
             Confirmado          = false
         };
         //Inserta a la base de datos la cuenta de gasto y regresa una entidad cuenta gasto con el id
         var cuentaGastoResponse = CuentaGastoRepositorio.InsertaFactura(cuentaGasto);
         //se envía uno por uno los impuestos a la base de datos
         foreach (var VARIABLE in cuentaGasto.RetencionImpuestos)
         {
             CuentaGastoRepositorio.InsertaImpuestosRetencion(VARIABLE, cuentaGasto.IdCuentaGasto);
         }
         //Se crea el request del NAS para enviarlo al Servicio FTP
         var request = new RecibeArchivoRequest()
         {
             EjecucionValida  = false,
             Item             = ConvertirArchivo(cfdi),
             MensajeError     = "",
             UsuarioEjecucion = ""
         };
         //hago llamado a NAS
         var ftp      = ServicioFTPSoftrade();
         var response = ftp.OperacionArchivo(request);
         transaction.Complete();
         return(cuentaGastoResponse);
     }
 }
        public ActionResult Complemento(string Folios, string Complemento, string FechaPago, string FormaPago)
        {
            try {
                RVCFDI33.GeneraCFDI objCfdi     = new RVCFDI33.GeneraCFDI();
                RVCFDI33.GeneraCFDI LeerObjCfdi = new RVCFDI33.GeneraCFDI();
                int           PrimerFolio       = int.Parse(Folios.Split(',')[0]);
                CFDI          Factura           = db.CFDI.Where(x => x.Folio == PrimerFolio).First();
                GetPAC_Result Proveedor         = db.GetPAC(Factura.IdProveedor, 1).First();
                Clientes      cliente           = db.Clientes.Where(x => x.IdCliente == Factura.IdCliente).First();
                Usuarios      usuario           = db.Usuarios.Where(x => x.Usuario == User.Identity.Name).FirstOrDefault();
                string        Certificado       = Server.MapPath("~/Certificados/" + Proveedor.RFC + "/" + Proveedor.RFC + ".cer");
                string        Llave             = Server.MapPath("~/Certificados/" + Proveedor.RFC + "/" + Proveedor.RFC + ".key");
                string        Domicilio         = cliente.Calle + " " + cliente.NoExterior + " " + cliente.Colonia + " C.P " + cliente.CodigoPostal + " " + cliente.Ciudad + "," + cliente.Estado + " " + cliente.Pais;
                System.IO.File.WriteAllBytes(Server.MapPath(Factura.Ruta) + ".xml", Factura.XML);
                objCfdi.agregarCertificado(Certificado);
                int    Folio      = 0;
                double total      = 0;
                string Moneda     = "";
                double TipoCambio = 1;

                objCfdi.agregarComprobante33("P", Folio.ToString(), System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"), "", "", 0, 0, "XXX", "", 0, "P", "", "22230", "");
                objCfdi.agregarEmisor(Proveedor.RFC, Proveedor.Nombre.Trim(), Proveedor.RegimenFiscal);
                objCfdi.agregarReceptor(cliente.RFC, cliente.Nombres + " " + cliente.ApellidoPaterno + " " + cliente.ApellidoMaterno, "", "", "P01");                //
                objCfdi.agregarConcepto("84111506", "", 1, "ACT", "", "Pago", 0, 0, 0);

                foreach (string folioStr in Folios.Split(','))
                {
                    Folio   = int.Parse(folioStr);
                    Factura = db.CFDI.Where(x => x.Folio == Folio).First();
                    string XMLTimbrado = System.IO.File.ReadAllText(Server.MapPath(Factura.Ruta) + ".xml");

                    Moneda = LeerObjCfdi.LeerValorXML(XMLTimbrado, "Moneda", "Comprobante");

                    if (LeerObjCfdi.LeerValorXML(XMLTimbrado, "TipoCambio", "Comprobante") != "")
                    {
                        double.TryParse(LeerObjCfdi.LeerValorXML(XMLTimbrado, "TipoCambio", "Comprobante"), out TipoCambio);
                    }
                    total = total + double.Parse(objCfdi.LeerValorXML(XMLTimbrado, "Total", "Comprobante"));
                    double totalIndividual = double.Parse(objCfdi.LeerValorXML(XMLTimbrado, "Total", "Comprobante"));
                    objCfdi.agregarPago10(FechaPago, FormaPago, Moneda, TipoCambio, totalIndividual, "01", "", "", "", "", "", "", "", "", "");
                    objCfdi.agregarPago10DoctoRelacionado(Factura.Id.ToString(), "B", folioStr, objCfdi.LeerValorXML(XMLTimbrado, "Moneda", "Comprobante"), 0, "PPD", 1, totalIndividual, totalIndividual, 0);
                }

                string path = Server.MapPath("~/Facturas/" + Proveedor.RFC + "/Complementos");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                Folio = ((int)db.CFDI.Where(x => x.Tipo == Complemento).Max(x => x.Folio)) + 1;

                switch (Complemento)
                {
                case "Pago10":


                    //"2018-09-11T12:42:47"
                    break;
                }
                string NombreArchivo = Proveedor.RFC + "_" + Folio + "_" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year;

                objCfdi.GeneraXML(Llave, Proveedor.ContrasenaLlave);
                System.IO.File.WriteAllText(path + "//" + NombreArchivo + "_SinTimbrar.xml", objCfdi.Xml);
                objCfdi.TimbrarCfdiArchivo(path + "\\" + NombreArchivo + "_SinTimbrar.xml", Proveedor.Usuario, Proveedor.Contrasena, "http://generacfdi.com.mx/rvltimbrado/service1.asmx", path, NombreArchivo, true);
                if (objCfdi.MensajeError == "")
                {
                    byte[] Logo = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Avenzo_Logo_Header.png"));
                    System.IO.File.WriteAllText(path + "\\" + NombreArchivo + ".xml", objCfdi.XmlTimbrado);
                    db.InsertCFDI(Guid.Parse(objCfdi.UUID), "Pago10", Folio, System.IO.File.ReadAllBytes(path + "//" + NombreArchivo + ".xml"), "~/Facturas/" + Proveedor.RFC + "/Complementos/" + NombreArchivo + ".xml", cliente.IdCliente, null, Proveedor.Id, false, DateTime.Now, Guid.Parse("8BEAD89F-B0CA-4CA9-9268-4DE6C727E3A2"));

                    Tools.PDF.ComplementoPago10(path + "\\", NombreArchivo, "XXX", Logo, objCfdi, Proveedor.RFC, Proveedor.Nombre, Proveedor.RegimenFiscal, cliente.RFC, "22210"
                                                , Domicilio, FechaPago, FormaPago, Moneda, TipoCambio.ToString("f2"), total.ToString("f2"), "01", Factura.Id.ToString(), "B", Factura.Folio.ToString(), Moneda, "PPD", "1", total.ToString("f2"), total.ToString("f2"), "0");


                    return(Json(new { error = false }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new { error = true, Message = objCfdi.MensajeError }, JsonRequestBehavior.AllowGet));
                }
            } catch (Exception ex) {
                return(Json(new { error = true, Message = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 17
0
        public void TestUno()
        {
            var cfdi = new CFDI();

            Assert.IsFalse(cfdi.GetStatus());
        }
Esempio n. 18
0
        public bool GetCFDI(string user, string password, CFDI.Comprobante comprobante)
        {
            //throw new NotImplementedException();

            string invoiceFileName = DateTime.Now.ToString("yyyyMMddHHmmss_" + comprobante.PublicKey.ToString("N"));
            byte[] sendFileBytes;
            byte[] responseFileBytes;

            CloudStorageAccount account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureDefaultStorageConnectionString"]);
            CloudBlobClient client = account.CreateCloudBlobClient();
            CloudBlobContainer container = client.GetContainerReference(ConfigurationManager.AppSettings["AzureDefaultStorage"]);

            try {

                using (MemoryStream ms = new MemoryStream()) {
                    using (MemoryStream zipMs = new MemoryStream()) {
                        CFDIXmlTextWriter writer =
                            new CFDIXmlTextWriter(comprobante, ms, System.Text.Encoding.UTF8);
                        writer.WriteXml();
                        ms.Position = 0;

                        using (ZipArchive zip = new ZipArchive(zipMs, ZipArchiveMode.Create, true)) {
                            var entry = zip.CreateEntry(invoiceFileName + "_send.xml");
                            using (Stream s = entry.Open()) {
                                ms.CopyTo(s);
                            }
                            zipMs.Flush();
                        } // zip.Dispose() => Close();

                        // container.CreateIfNotExists();
                        CloudBlockBlob blob = container.GetBlockBlobReference(invoiceFileName + "_send.zip");
                        zipMs.Position = 0;

                        blob.UploadFromStream(zipMs);
                        blob.Properties.ContentType = "application/x-zip-compressed";
                        blob.SetMetadata();
                        blob.SetProperties();

                        zipMs.Position = 0;
                        sendFileBytes = zipMs.ToArray();
                    } // zipMs.Dispose() => Close();
                } // ms.Dispose() => Close();

                //CFDI.EDICOM.TestCFDI.CFDiService webService = new CFDI.EDICOM.TestCFDI.CFDiService();
                //responseFileBytes = webService.getCfdiTest(user, password, sendFileBytes);
                ICFDIService webService = CFDiServiceFactory.Create();
                responseFileBytes = webService.GetCFDI(user, password, sendFileBytes);

                CloudBlockBlob blob2 = container.GetBlockBlobReference(invoiceFileName + "_response.zip");
                //zipMs.Position = 0;

                blob2.UploadFromByteArray(responseFileBytes, 0, responseFileBytes.Length); // .UploadFromStream(zipMs);
                blob2.Properties.ContentType = "application/x-zip-compressed";
                blob2.SetMetadata();
                blob2.SetProperties();

                using (var responseStream = new MemoryStream(responseFileBytes)) {
                    using (var archive = new ZipArchive(responseStream, ZipArchiveMode.Read, true)) {
                        var fileInArchive = archive.Entries[0]; //
                        using (var entryStream = fileInArchive.Open()) {
                            using (var reader = new StreamReader(entryStream)) {
                                string output = reader.ReadToEnd();

                                System.Xml.XmlDocument invoice = new System.Xml.XmlDocument();
                                invoice.LoadXml(output);

                                System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(invoice.NameTable);
                                nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3");
                                nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital");
                                System.Xml.XmlNode timbre = invoice.SelectSingleNode("//tfd:TimbreFiscalDigital", nsmgr);

                                TimbreFiscalDigital complemento = new TimbreFiscalDigital();

                                complemento.Version = timbre.Attributes.GetNamedItem("version").Value.ToString();
                                complemento.UUID = timbre.Attributes.GetNamedItem("UUID").Value.ToString();
                                complemento.FechaTimbrado = DateTime.Parse(timbre.Attributes.GetNamedItem("FechaTimbrado").Value);
                                complemento.SelloCFD = timbre.Attributes.GetNamedItem("selloCFD").Value.ToString();
                                complemento.NoCertificadoSAT = timbre.Attributes.GetNamedItem("noCertificadoSAT").Value.ToString();
                                complemento.SelloSAT = timbre.Attributes.GetNamedItem("selloSAT").Value.ToString();

                                if (comprobante.Complementos == null)
                                    comprobante.Complementos = new List<Complemento>();
                                comprobante.Complementos.Add(complemento);
                                //Complemento complemento = new Complemento();
                                //complemento.

                                //           //    Sistrategia.Server.SAT.CFDI.Comprobante comprobante2 = Sistrategia.Server.SAT.SATManager.GetComprobante(Guid.Parse(post["comprobanteId"]));
                                //           //    comprobante2.Complemento = new Sistrategia.Server.SAT.CFDI.ComprobanteComplemento();
                                //           //    comprobante2.Complemento.TimbreFiscalDigitalSpecified = true;
                                //           //    comprobante2.Complemento.TimbreFiscalDigital = new Sistrategia.Server.SAT.CFDI.ComprobanteTimbre();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.SatTimbreId = Guid.NewGuid();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.Version = timbre.Attributes.GetNamedItem("version").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.UUID = timbre.Attributes.GetNamedItem("UUID").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.FechaTimbrado = DateTime.Parse(timbre.Attributes.GetNamedItem("FechaTimbrado").Value);
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.SelloCFD = timbre.Attributes.GetNamedItem("selloCFD").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.NoCertificadoSAT = timbre.Attributes.GetNamedItem("noCertificadoSAT").Value.ToString();
                                //           //    comprobante2.Complemento.TimbreFiscalDigital.SelloSAT = timbre.Attributes.GetNamedItem("selloSAT").Value.ToString();

                                // entryStream.Position = 0;
                              //  entryStream.Position

                                // SAVE final xml:
                                 Sistrategia.SAT.CFDiWebSite.CloudStorage.CloudStorageMananger manager =
                                     new Sistrategia.SAT.CFDiWebSite.CloudStorage.CloudStorageMananger();
                            //manager.UploadFromStream(ConfigurationManager.AppSettings["AzureAccountName"],
                                manager.UploadFromString(ConfigurationManager.AppSettings["AzureAccountName"],
                                ConfigurationManager.AppSettings["AzureAccountKey"],
                                comprobante.Emisor.PublicKey.ToString("N"),
                                comprobante.PublicKey.ToString("N") + ".xml",
                                comprobante.Serie + comprobante.Folio + ".xml", //model.ComprobanteArchivo.FileName,
                                "text/xml", //model.ComprobanteArchivo.ContentType,
                                output); // model.ComprobanteArchivo.InputStream);

                                comprobante.GeneratedCadenaOriginal = comprobante.GetCadenaOriginal();
                                comprobante.GeneratedXmlUrl = string.Format(@"https://sistrategiacfdi1.blob.core.windows.net/{0}/{1}.xml",
                                comprobante.Emisor.PublicKey.ToString("N"),
                                comprobante.PublicKey.ToString("N"));
                                comprobante.Status = "A";
                            }
                        }
                        //using (var fileToCompressStream = new MemoryStream(fileBytes)) {
                        //    fileToCompressStream.CopyTo(entryStream);
                        //}
                    }
                }

            }
            catch (Exception ex){
                CloudBlockBlob blob2 = container.GetBlockBlobReference(invoiceFileName + "_exception.txt");
                //zipMs.Position = 0;
                blob2.UploadText(ex.ToString());
                blob2.Properties.ContentType = "text/plain";
                blob2.SetMetadata();
                blob2.SetProperties();

                throw;
            }

            return true;
        }
Esempio n. 19
0
        public CFDI ObtenerData()
        {
            CFDI cfdi = new CFDI();

            cfdi.uuid = this.obtenerInfo("TIMBREFISCALDIGITAL", "UUID");
            //cfdi.id_invoice = this._idInvoice;

            cfdi.folio        = this.obtenerInfo("", "FOLIO", 1, true);
            cfdi.fechaEmision = castToDate(this.obtenerInfo("", "FECHA", 1, true));
            cfdi.descuento    = 0;
            string descuento = String.Empty;

            descuento = this.obtenerInfo("", "DESCUENTO", 1, true);
            if (!descuento.Equals(""))
            {
                cfdi.descuento = castToDecimal(descuento);
            }
            cfdi.fechaTimbrado       = castToDate(this.obtenerInfo("TIMBREFISCALDIGITAL", "FECHATIMBRADO"));
            cfdi.condicionesPago     = this.obtenerInfo("", "CONDICIONESDEPAGO", 1, true);
            cfdi.metodoPago          = this.obtenerInfo("", "METODOPAGO", 1, true);
            cfdi.moneda              = this.obtenerInfo("", "MONEDA", 1, true);
            cfdi.tipoCambio          = castToDecimal(obtenerInfo("", "TIPOCAMBIO", 1, true));
            cfdi.lugarExpedicion     = this.obtenerInfo("", "LUGAREXPEDICION", 1, true);
            cfdi.regimenFiscalEmisor = this.obtenerInfo("EMISOR", "REGIMENFISCAL");
            cfdi.nombreEmisor        = this.obtenerInfo("EMISOR", "NOMBRE");
            cfdi.rfcEmisor           = this.obtenerInfo("EMISOR", "RFC");
            cfdi.rfcReceptor         = this.obtenerInfo("RECEPTOR", "RFC");
            cfdi.nombreReceptor      = this.obtenerInfo("RECEPTOR", "NOMBRE");
            cfdi.tipo = this.obtenerInfo("", "TIPODECOMPROBANTE", 1, true);
            cfdi.totalImpuestosTrasladados = Decimal.Parse(obtenerUltimoNodo("IMPUESTOS", "TOTALIMPUESTOSTRASLADADOS"));
            cfdi.ivaTrasladado             = Decimal.Parse(obtenerUltimoNodo("IMPUESTOS", "TOTALIMPUESTOSTRASLADADOS"));
            cfdi.usoCFDI = this.obtenerInfo("RECEPTOR", "USOCFDI");

            cfdi.serie            = this.obtenerInfo("", "SERIE", 1, true);
            cfdi.subTotal         = castToDecimal(this.obtenerInfo("", "SUBTOTAL", 1, true));
            cfdi.numRegIdTrib     = this.obtenerInfo("RECEPTOR", "NUMREGIDTRIB");
            cfdi.residenciaFiscal = this.obtenerInfo("RECEPTOR", "RESIDENCIAFISCAL");
            cfdi.total            = castToDecimal(this.obtenerInfo("", "TOTAL", 1, true));
            //cfdi.baseIvaTasaCero = obtenerTasaCero();
            cfdi.ivaTasaCero         = cfdi.baseIvaTasaCero > 0 ? true : false;
            cfdi.formaPago           = this.obtenerInfo("", "FORMAPAGO", 1, true);
            cfdi.certificadoSerieSAT = this.obtenerInfo("", "", 1, true);
            cfdi.selloDigital        = this.obtenerInfo("TIMBREFISCALDIGITAL", "SELLOCFD");;
            cfdi.selloSAT            = this.obtenerInfo("TIMBREFISCALDIGITAL", "SELLOSAT");
            cfdi.certificadoSerieSAT = this.obtenerInfo("TIMBREFISCALDIGITAL", "NOCERTIFICADOSAT");
            cfdi.certificadoCSD      = this.obtenerInfo("", "NOCERTIFICADO", 1, true);
            cfdi.rfcProvCertif       = this.obtenerInfo("TIMBREFISCALDIGITAL", "RFCPROVCERTIF");



            #region Propiedades no identificadas hasta ahora en el XML
            //cxc.iepsRetenidoTasa = "0";
            //cxc.iepsTrasladadoTasa = "0";
            //cxc.iepsRetenidoCuota = 0;
            //cxc.iepsTrasladadoCuota = 0;
            //cxc.totalImpuestosRetenidos = 0;
            //cxc.isrRetenido = 0;
            //cxc.isrTraslado = 0;
            //cxc.ivaRetenido = 0;
            //cxc.ivaTrasladado = 0;
            //cxc.baseIvaExento = 0;
            //cxc.ivaExento = false;
            //cxc.totalRetencionesLocales = 0;
            //cxc.totalTrasladosLocales = 0;
            //cxc.impuestoLocalRetenido = 0;
            //cxc.tasaRetencionLocal = "";
            //cxc.importeRetencionLocal = 0;
            //cxc.impuestoLocalTrasladado = 0;
            //cxc.tasaTrasladoLocal = "";
            //cxc.importeTrasladoLocal = 0;
            //cxc.confirmacion=''
            #endregion
            cfdi.CFDIRelacionado = this.obtenerCFDIRelacionados();
            cfdi.ComplementoPago = this.obtenerComplementoPago();
            if (cfdi.CFDIRelacionado.Count > 0)
            {
                cfdi.cfdiRelacionados = $"{cfdi.CFDIRelacionado.First().tipoRelacion}," +
                                        $"{String.Join(",", cfdi.CFDIRelacionado.Select(x => x.uuidRelacionado).ToArray())}";
            }
            cfdi.Concepto = this.obtenerConceptos();



            //Console.WriteLine(cfdi.Concepto.ToList().Sum(x=>x.importe));


            return(cfdi);
        }
Esempio n. 20
0
        //9.-Funcion para llenar los datos utilizando las label posteriormente llamo a la funcion timbrar()
        private void llenarDatosEmisorReceptor()
        {
            try
            {
                //establecemos el numero de serie de la licencia del SDK para poder hacer uso de ella.
                //En caso de no asignara, el SDK funcionará con las restricciones de version DEMO,
                //las cuales permite hacer unicamente CFDI con el RFC Genérico XAXX010101000
                LicenciasBuildCFDI lic1 = new LicenciasBuildCFDI();
                DateTime FechTimbre=DateTime.Now;
                lic1.Licencia(liccenciaBuildCFDI);
                
                
                if (cbFechTimb.Checked == true && cbFechTimb.Visible == true)
                {   
                    //Timbro con la fecha actual no con la que se genero la carta porte
                    FechTimbre = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy H:mm:ss"));
                    
                }else 
                {
                    //Timbrar con la fecha en la que se genera la carta porte el dato es tomado desde la base de datos
                    FechTimbre = Convert.ToDateTime(label[33]);                    
                }
                
                CFDI.Comprobante c = new CFDI.Comprobante(FechTimbre, Convert.ToString(label[44])/*lblMetodoPago.Text*/, CFDI.Comprobante.opTipoDeComprobante.ingreso, Convert.ToDouble(label[37]/*lblSubtotal.Text*/), Convert.ToDouble(label[28]/*lblTotal.Text*/), Convert.ToString(label[45])/*lblMetodoPago.Text*/, Convert.ToString(label[42])/*lblDireccion.Text*/ + "  Tels.:" + Convert.ToString(label[47])/*lblTelefono1.Text*/ + ", " + Convert.ToString(label[48])/*lblTelefono2.Text*/, Convert.ToString(label[1])/*lblNumero.Text*/, Convert.ToString(label[0])/*lblSerie.Text*/, "", default(DateTime),-1 /*lblTotal.Text*/, "PESOS MEXICANOS", "1", Convert.ToString(label[46])/*lblTerminacion.Text*/, Convert.ToString(label[44])/*lblLeyenda.Text*/, -1, "");    
                      
                //Establecemos datos del Emisor
                //esta variable con esta funcion nos dejará indicar el regimen fiscal de la empresa emisora
                CFDI.Emisor.RegimenFiscal reg = new CFDI.Emisor.RegimenFiscal();
                reg.AgregarRegimen(leyenda);

                //esta funcion nos permite indicar la información obligatoria para el emisor
                CFDI.Emisor em = new CFDI.Emisor(rfcE, reg, razonSocial);

                //con esta variable establecemos los datos del emisor
                CFDI.Emisor.DomicilioFiscal df = new CFDI.Emisor.DomicilioFiscal(direccion,municipioE , estadoE, paisE, cpE, numeroExterior, "N/A", coloniaE);

                //con esta funcion agregamos los datos fiscales del emisor
                em.EstablecerDomicilioFiscal(df);                

                //Establecemos datos del Receptor
                //esta funcion nos permite indicar la información obligatoria para el emisor
                CFDI.Receptor r = new CFDI.Receptor(rfc, nombre);

                //con esta variable establecemos los datos del receptor
                CFDI.Receptor.Domicilio d = new CFDI.Receptor.Domicilio(pais, direcc,numExt ,numInt, colonia, ciudad, "", null, estado, cp);
                r.EstablecerDomicilio(d);
                                
                //Establecemos Conceptos
                //Podemos crear un ciclo for ó cualquier otro tipo de ciclo para agregar la cantidad de conceptos necesarios.
                //Aquí solo aclaramos un poco la idea de como hay que hacerlo.
                CFDI.Conceptos co = new CFDI.Conceptos();         
                                               
                for (int fila = 0; fila <gridConceptos.RowCount-1; fila++)
                {
                    if (gridConceptos[1, fila].Value.ToString() != "0.00")
                        {                          
                            co.AgregarConcepto(1, "N/A", gridConceptos[0, fila].Value.ToString(), Convert.ToDouble(gridConceptos[1, fila].Value.ToString()), Convert.ToDouble(gridConceptos[1, fila].Value.ToString()));
                        }                   
                }               
                
                //Establecemos Impuestos
                //aquí declaramos un impuesto IVA trasladado con tasa de 16%
                CFDI.Impuestos im = new CFDI.Impuestos();
                
                if (Convert.ToDouble(label[39])/*lblRetIva.Text*/ >0)
                {
                    im.AgregarImpuestosTrasladados(CFDI.Impuestos.opTraslado.IVA, Convert.ToDouble(label[38]/*lblIvaActual.Text*/), Convert.ToDouble(label[39]/*lblIva.Text*/));
                }
                if (Convert.ToDouble(label[41])/*lblRetIva.Text*/>0)
                {
                    im.AgregarImpuestosRetenidos(CFDI.Impuestos.opRetencion.IVA, Convert.ToDouble(label[41]/*lblRetIva.Text*/));
                }
                /*******************************TOMAR LA RUTA DE .CER Y .KEY DE LA BASE DE DATOS**********************************/

                //ubicacion para guardar el XML en la aplicacion de masteredi y posteriormente timbrarla 
                SqlDataReader ResConsul;
                string consulta = "select * from Certifcado where Id_cer=(SELECT MAX(Id_cer) from Certifcado);";
                metodos BD = new metodos();
                ResConsul = BD.Buscar(consulta, this.conn);

                if (ResConsul.Read())
                {   
                    //Tomando la Ruta de los archivo .cer y .key y la clave privada desde la base de datos  
                    if (File.Exists(CerFileLocal))
                    {
                        CertFile = CerFileLocal;
                    }
                    else
                    {
                        CertFile = @ResConsul.GetString(1).ToString();
                    }

                    if (File.Exists(KeyPassLocal))
                    {
                        keyFile = KeyPassLocal;
                    }
                    else
                    {
                        keyFile = @ResConsul.GetString(2).ToString();
                    }

                    keyPass = ResConsul.GetString(3).ToString();
                }

                //Creamos el XML con todos los datos llenados especificando certificado, llave privada, contraseña y ruta de destino
                CFDI sellar = new CFDI();
                                     
                //Tambien lo guardo en un archivo TXT de manera local en la carperta temporal para despues timbrarlo. 
                sellar.CrearXML(CertFile, keyFile, keyPass, c, em, r, co, im, @temp + nomenclatura + c.serie + c.folio + ".txt");
                sellar.CrearXML(CertFile, keyFile, keyPass, c, em, r, co, im, @temp + nomenclatura + c.serie + c.folio + ".xml");

                //OBTENER CADENA ORIGINAL DEL CFD
                /*XslCompiledTransform transformador = new XslCompiledTransform();
                transformador.Load(@"C:\Users\Admin\Desktop\Factura CFDI Visual 2010\XSLT\cadenaoriginal_3_2.xslt");
                transformador.Transform(temp + label[0] + label[1] + ".xml", temp + label[0] + label[1] + "CO.txt");
                */
                   
                //Enviamos un mensaje al usuario para informar que se ha creado el xml
                //MessageBox.Show("¡Se ha creado el XML con éxito!");
                Timbrar();
                        
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error para sellar el xml\n" + ex);
            }


        }
Esempio n. 21
0
        public static void CrearFactura()
        {
            //Aquí configuramos el rfc con el cliente, como vamos a hacer pruebas utilizaremos el rfc de pruebas
            // Para cambiar a produción simplemente haga cambie de NO a SI. cuando esta configurado en NO estamos en prueba
            pac = new PAC("DEMO700101XXX", "DEMO700101XXX", "NO");
            //Configuración de certificados.
            conf = new Conf(@"C:\multifacturas_sdk\pruebas\CSD01_AAA010101AAA.cer",
                            @"C:\multifacturas_sdk\pruebas\CSD01_AAA010101AAA.key",
                            "12345678a");
            //Configuramos el sdk para el timbrado
            sdkconf = new SDKConfig(pac, conf, @"C:\multifacturas_sdk\");
            sdk     = new SDK(sdkconf);

            //Datos del emisor.
            emisor = new Emisor();

            //Domicilio
            emisor.Nombre = "Soluciones Integrales en Tecnologías de la Información del Maya S.A de C.V";
            emisor.RFC    = "AAA010101AAA";

            //Creamos el domicilio fiscal del emisor

            DomicilioFiscal domiciliofiscal = new DomicilioFiscal();

            domiciliofiscal.Calle        = " 41";
            domiciliofiscal.NoExterior   = "318";
            domiciliofiscal.Colonia      = "Montealban";
            domiciliofiscal.CodigoPostal = "97114";
            domiciliofiscal.Localidad    = "Mérida";
            domiciliofiscal.Municipio    = "Mérida";
            domiciliofiscal.Pais         = "México";
            domiciliofiscal.Estado       = "Yucatán";



            //En caso de que la expedisión sea en otra sucursal.
            ExpedidoEn expedidoen = new ExpedidoEn();

            expedidoen.Calle        = "Andador Potasio";
            expedidoen.NoExterior   = "279";
            expedidoen.NoInterior   = "3A";
            expedidoen.Colonia      = "11 de Julio";
            expedidoen.CodigoPostal = "60954";
            expedidoen.Localidad    = "Lázaro Cárdenas";
            expedidoen.Municipio    = "Lázaro Cárdenas";
            expedidoen.Pais         = "México";
            expedidoen.Estado       = "Michoacán";

            emisor.Domicilio  = domiciliofiscal;
            emisor.ExpedidoEn = expedidoen;

            ///Creamos el receptor
            receptor        = new Receptor();
            receptor.Nombre = "Francisco Javier Guerrero";
            receptor.RFC    = "XAXX010101000"; //aquí publico gneral.

            Domicilio domicilioreceptor = new Domicilio();

            domicilioreceptor.Calle     = "Domicilio Conocido";
            domicilioreceptor.Localidad = "Lazaro Cárdenas";


            receptor.Domicilio = domicilioreceptor;



            //No es necesario llenar todos los campos.

            //Creamos la venta
            List <Concepto> conceptos = new List <Concepto>();

            conceptos.Add(new Concepto("1", "Pieza", "COD1", "Producto Prueba", "120", "120"));
            Impuestos impuestos = new Impuestos();

            impuestos.AgregaTraslado(new Translado("IVA", "19.2", "16"));

            //Creamos un nuevo objeto de tipo factura


            factura = new CFDI();
            //Datos básicos de la factura
            //factura.Emisor = emisor;
            //factura.Receptor = receptor;
            factura.Emisor    = emisor;
            factura.Receptor  = receptor;
            factura.Conceptos = conceptos;
            factura.Impuestos = impuestos;
            //Configuramos la serie y el folio
            factura.Serie             = "AA";
            factura.Folio             = "1";
            factura.FechaDeExpedicion = "2016-12-02 19:00:00";
            //Consultar los cambios a la miscelanea fiscal Agosto 2016.
            factura.MetodoDePago = "01";
            //Los 4 digitos si pagó con tarjeta o cheque...
            factura.NumCtaPAgo = "";
            //Esto se configura según las reglas del negocio;
            factura.FormaDePago = "Pago en una sola exhibición";
            //Peso mexicano... cambiar al tipo de cambio en caso de cobrar en USD o en otra moneda.
            factura.TipoDeCambio = "1.0";
            //Consultar el Anexo 20.
            factura.TipoDeComprobante = "ingreso"; //ingreso, egreso, traslado [Escribir en minúsculas]
            factura.LugarDeExpedicion = "Lázaro Cárdenas, Michoacan";
            factura.RegimenFiscal     = "De las personas fisicas con actividad empresarial";
            factura.SubTotal          = "120";
            factura.Descuento         = "0";
            factura.Total             = "139.2"; //El total con el iva NETO
            var x = AppDomain.CurrentDomain.BaseDirectory;

            sdk.CreaINI(factura, AppDomain.CurrentDomain.BaseDirectory + "Factura01"); //Esta cadena se cambia por la de tu archivo a generar.

            //Ahora creamos el tmbrado con el archivo INI ya generado (generamos el XML)
            //factura, directorio y el archivo .ini generado
            sdk.Timbrar(factura, AppDomain.CurrentDomain.BaseDirectory, "Factura01");
        }