### Initialize Pago 2.0 certificate loading Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/40_cfdi_create_guide.md Demonstrates the initial setup for loading a signing certificate for a payment document. ```python from datetime import date, datetime from decimal import Decimal from satcfdi.models import Signer from satcfdi.create.cfd import cfdi40, pago20 # Load signing certificate signer = Signer.load( certificate=open('csd/xiqb891116qe4_csd.cer', 'rb').read(), key=open('csd/xiqb891116qe4_csd.key', 'rb').read(), password=open('csd/xiqb891116qe4_csd.txt', 'r').read() ) ``` -------------------------------- ### Initial Balance Variable in Auxiliar de Cuentas Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/AuxiliarCtas.html Use this variable to display the Initial Balance (SaldoIni) in the Auxiliar de Cuentas report. This is the balance at the start of the period. ```Python {{ c.SaldoIni }} ``` -------------------------------- ### Render CFDI Invoice to Various Formats Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/readme.rst This snippet shows how to render a processed CFDI invoice into different file formats: XML, JSON, HTML, and PDF. It also includes examples for rendering multiple invoices and extracting only the HTML body. ```python from satcfdi import render from satcfdi.render import BODY_TEMPLATE # XML invoice.xml_write("my_invoice.xml") # JSON render.json_write(invoice, "my_invoice.json", pretty_print=True) # HTML render.html_write(invoice, "my_invoice.html") # PDF render.pdf_write(invoice, "my_invoice.pdf") # Multiple HTML render.html_write([invoice1, invoice2], "my_invoice.html") # Multiple PDF render.pdf_write([invoice1, invoice2], "my_invoice.pdf") # HTML Body only html_body = render.html_str(invoice, template=BODY_TEMPLATE) ``` -------------------------------- ### Retrieve Geolocation Data Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/tests/csf/invalid.html Attempts to get the user's current position using the browser's geolocation API. If geolocation is not supported, it defaults to '0,0'. ```javascript function getVars(){ console.log('este es un mensaje de inicio de ubicacion ::::'); if ("geolocation" in navigator){ navigator.geolocation.getCurrentPosition(onSuccessGeolocating, onErrorGeolocating, { enableHighAccuracy: true, maximumAge: 5000 }); } else { console.log("El Navegador no pudo acceder a la geolocalizacion!, Se mandan datos nulos"); var ubicacion = "0,0"; setHiddenValue(ubicacion); } }; ``` -------------------------------- ### Create a standard CFDI 4.0 invoice Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/40_cfdi_create_guide.md Initializes a Comprobante object with issuer, receiver, and concept details, then signs and processes it. ```python from decimal import Decimal from satcfdi.models import Signer from satcfdi.create.cfd import cfdi40 from satcfdi.create.cfd.catalogos import RegimenFiscal, UsoCFDI, MetodoPago, Impuesto, TipoFactor # Load signing certificate signer = Signer.load( certificate=open('csd/xiqb891116qe4_csd.cer', 'rb').read(), key=open('csd/xiqb891116qe4_csd.key', 'rb').read(), password=open('csd/xiqb891116qe4_csd.txt', 'r').read() ) # create Comprobante invoice = cfdi40.Comprobante( emisor=cfdi40.Emisor( rfc=signer.rfc, nombre=signer.legal_name, regimen_fiscal=RegimenFiscal.GENERAL_DE_LEY_PERSONAS_MORALES ), lugar_expedicion="56820", receptor=cfdi40.Receptor( rfc='KIJ0906199R1', nombre='KIJ, S.A DE C.V.', uso_cfdi=UsoCFDI.GASTOS_EN_GENERAL, domicilio_fiscal_receptor="59820", regimen_fiscal_receptor=RegimenFiscal.GENERAL_DE_LEY_PERSONAS_MORALES ), metodo_pago=MetodoPago.PAGO_EN_PARCIALIDADES_O_DIFERIDO, serie="A", folio="123456", conceptos=[ cfdi40.Concepto( clave_prod_serv='84111506', cantidad=Decimal('1.00'), clave_unidad='E48', descripcion='SERVICIOS DE FACTURACION', valor_unitario=Decimal('1250.30'), impuestos=cfdi40.Impuestos( traslados=cfdi40.Traslado( impuesto=Impuesto.IVA, tipo_factor=TipoFactor.TASA, tasa_o_cuota=Decimal('0.160000'), ), retenciones=[ cfdi40.Retencion( impuesto=Impuesto.ISR, tipo_factor=TipoFactor.TASA, tasa_o_cuota=Decimal('0.100000'), ), cfdi40.Retencion( impuesto=Impuesto.IVA, tipo_factor=TipoFactor.TASA, tasa_o_cuota=Decimal('0.106667'), ) ], ) ) ] ) invoice.sign(signer) invoice = invoice.process() ``` -------------------------------- ### Get User Location on Page Load Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/tests/csf/invalid.html Triggers geolocation retrieval when the page loads if the 'iptRequiereUbicacion' value is '1'. Ensure the 'ubicacionForm:iptRequiereUbicacion' element is correctly set. ```javascript window.onload = function getUbicacion(){ console.log("entrando::::"); var requiereUbicacion = $("#ubicacionForm\\:iptRequiereUbicacion").val(); console.log("Requiere ubicacion ???? " + requiereUbicacion); if(requiereUbicacion === "1"){ console.log('El servicio pertenece a Marbetes'); getVars(); } }; ``` -------------------------------- ### Create and Sign a CFDI Invoice Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/readme.rst This snippet demonstrates how to create a CFDI invoice with detailed concept information, including taxes, and then sign it using a provided signer object. The invoice is then processed. ```python uso_cfdi=UsoCFDI.GASTOS_EN_GENERAL, domicilio_fiscal_receptor="59820", regimen_fiscal_receptor=RegimenFiscal.GENERAL_DE_LEY_PERSONAS_MORALES ), metodo_pago=MetodoPago.PAGO_EN_PARCIALIDADES_O_DIFERIDO, serie="A", folio="123456", conceptos=[ cfdi40.Concepto( clave_prod_serv='84111506', cantidad=Decimal('1.00'), clave_unidad='E48', descripcion='SERVICIOS DE FACTURACION', valor_unitario=Decimal('1250.30'), impuestos=cfdi40.Impuestos( traslados=cfdi40.Traslado( impuesto=Impuesto.IVA, tipo_factor=TipoFactor.TASA, tasa_o_cuota=Decimal('0.160000'), ), retenciones=[ cfdi40.Retencion( impuesto=Impuesto.ISR, tipo_factor=TipoFactor.TASA, tasa_o_cuota=Decimal('0.100000'), ), cfdi40.Retencion( impuesto=Impuesto.IVA, tipo_factor=TipoFactor.TASA, tasa_o_cuota=Decimal('0.106667'), ) ], ) ) ] ) invoice.sign(signer) invoice = invoice.process() ``` -------------------------------- ### Load CFDI from File or String Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/30_cfdi_load_guide.md Use `CFDI.from_file` to load an existing CFDI XML file or `CFDI.from_string` to load from a string or bytes. Ensure the file is opened in binary mode for `from_string`. ```python from satcfdi.cfdi import CFDI # from file invoice = CFDI.from_file('comprobante.xml') ``` ```python # from string/bytes invoice = CFDI.from_string(open('comprobante.xml', 'rb').read()) ``` -------------------------------- ### Request Certificate with FIEL Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/55_certifica_guide.md Load your FIEL (Firma Electrónica Avanzada) and use it to request a new certificate. Ensure the paths to your .cer, .key, and .txt password files are correct. ```python from satcfdi.models import Signer from satcfdi.certifica import Certifica # Load Fiel fiel = Signer.load( certificate=open('csd/xiqb891116qe4.cer', 'rb').read(), key=open('csd/xiqb891116qe4.key', 'rb').read(), password=open('csd/xiqb891116qe4.txt', 'r').read() ) certifica = Certifica(fiel) certifica.solicitud_certificado( sucursal="MiSucursal", password="IsTHisSecure!32?", dirname=None ) ``` -------------------------------- ### Validate RFC and Legal Name with SAT Portal Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/52_portal_facturacion.md Initializes a session with a Fiel certificate to perform RFC validation, legal name verification, and LCO detail retrieval. ```python from satcfdi.models import Signer from satcfdi.portal import SATFacturaElectronica # Load Fiel signer = Signer.load( certificate=open('csd/xiqb891116qe4.cer', 'rb').read(), key=open('csd/xiqb891116qe4.key', 'rb').read(), password=open('csd/xiqb891116qe4.txt', 'r').read() ) sat_session = SATFacturaElectronica(signer) sat_session.login() # Validación RFC res = sat_session.rfc_valid( rfc='XIQB891116QE4' ) print(res) # Validación Razón Social res = sat_session.legal_name_valid( rfc='XIQB891116QE4', legal_name='KIJ, S.A DE C.V.' ) print(res) # LCO Detalles res = sat_session.lco_details(rfc="XIQB891116QE4") print(res) ``` -------------------------------- ### Display Total Taxes (Traslados) Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/Pagos.html Display total taxes (Traslados) for different VAT rates (16%, 8%, 0%) and exempt amounts. ```Python {% if c.Totales %} {% for r in [ ('16.0000%', c.Totales.TotalTrasladosImpuestoIVA16), ('8.0000%', c.Totales.TotalTrasladosImpuestoIVA8), ('0.0000%', c.Totales.TotalTrasladosImpuestoIVA0), ('Exento', c.Totales.TotalTrasladosBaseIVAExento) ] if r[1] %} {% endfor %} **{% if loop.first %}Totales Traslados MXN{% endif %}** IVA {{ r[0] }} {{ r[1] }} ``` -------------------------------- ### Display Payment-Level Taxes (Retenciones) Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/Pagos.html Iterate through and display payment-level tax details (Retenciones), including tax type, rate/quota, and amount. ```Python {% if pago.ImpuestosP.RetencionesP %} {% for v in iterate(pago.ImpuestosP.RetencionesP) %} {% endif %} {% if loop.first %} **Retenciones** {% endif %} {{ v.ImpuestoP | desc }} {{ v.ImporteP }} {% endfor %} ``` -------------------------------- ### Request Retention Download by UUID Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/45_cfdi_descarga_massiva.md This snippet demonstrates how to request the download of retentions associated with a specific UUID. It includes loading the FIEL signer, initializing the SAT service, making the request, and storing the resulting request ID for status checking. ```python import base64 from satcfdi.models import Signer from satcfdi.pacs.sat import SAT, EstadoSolicitud # Load Fiel signer = Signer.load( certificate=open('csd/xiqb891116qe4.cer', 'rb').read(), key=open('csd/xiqb891116qe4.key', 'rb').read(), password=open('csd/xiqb891116qe4.txt', 'r').read() ) sat_service = SAT( signer=signer ) # Retenciones por UUID response = sat_service.recover_retencion_uuid_request( folio="31764278-d091-417f-83aa-063239e7773b" ) # Almacenar el id_solicitud en algún lugar id_solicitud = response['IdSolicitud'] # Revisar estado de descarga response = sat_service.recover_retencion_status(id_solicitud) est = response["EstadoSolicitud"] if est == EstadoSolicitud.TERMINADA: for id_paquete in response['IdsPaquetes']: response, paquete = sat_service.recover_retencion_download( id_paquete=id_paquete ) paquete = base64.b64decode(paquete) with open(f"{id_paquete}.zip", "wb") as f: f.write(paquete) else: # volver a intentar más tarde pass ``` -------------------------------- ### Iterate and display supplier information Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/DIOT.html Loops through the list of suppliers and outputs each entry as a JSON-like dump. ```jinja2 {% for c in c.Proveedores %} {{ c | dump }} {% endfor %} ``` -------------------------------- ### Descargar Retenciones Emitidas Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/45_cfdi_descarga_massiva.md Solicita la descarga masiva de comprobantes de retención emitidos por el contribuyente. Requiere la carga de la FIEL y un rango de fechas. ```python import base64 from datetime import date from satcfdi.models import Signer from satcfdi.pacs.sat import SAT, TipoDescargaMasivaTerceros, EstadoSolicitud # Load Fiel signer = Signer.load( certificate=open('csd/xiqb891116qe4.cer', 'rb').read(), key=open('csd/xiqb891116qe4.key', 'rb').read(), password=open('csd/xiqb891116qe4.txt', 'r').read() ) sat_service = SAT( signer=signer ) # Retenciones Emitidas response = sat_service.recover_retencion_emitted_request( fecha_inicial=date(2020, 1, 1), fecha_final=date(2020, 12, 1), rfc_emisor=sat_service.signer.rfc, tipo_solicitud=TipoDescargaMasivaTerceros.CFDI, ) # Almacenar el id_solicitud en algún lugar id_solicitud = response['IdSolicitud'] ``` -------------------------------- ### Display Total Taxes (Retenciones) Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/Pagos.html Display total retentions for ISR, IVA, and IEPS. ```Python {% for r in [('ISR', c.Totales.TotalRetencionesISR), ('IVA', c.Totales.TotalRetencionesIVA), ('IEPS', c.Totales.TotalRetencionesIEPS)] if r[1] %} {% endfor %} **{% if loop.first %}Totales Retenciónes MXN{% endif %}** {{ r[0] }} {{ r[1] }} ``` -------------------------------- ### Check Download Status and Download Retentions Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/45_cfdi_descarga_massiva.md This snippet shows how to check the status of a mass download request for retentions and then download the resulting zip files if the request is completed. It handles both successful completion and the case where the request needs to be retried later. ```python response = sat_service.recover_retencion_status(id_solicitud) est = response["EstadoSolicitud"] if est == EstadoSolicitud.TERMINADA: for id_paquete in response['IdsPaquetes']: response, paquete = sat_service.recover_retencion_download( id_paquete=id_paquete ) paquete = base64.b64decode(paquete) with open(f"{id_paquete}.zip", "wb") as f: f.write(paquete) else: # volver a intentar más tarde pass ``` -------------------------------- ### Initialize PrimeFaces data tables Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/tests/csf/persona_fisica.html Initializes various PrimeFaces DataTable widgets for displaying fiscal information. ```javascript $(function(){PrimeFaces.cw('DataTable','widget_ubicacionForm_j_idt10_0_j_idt11_j_idt14',{id:'ubicacionForm:j_idt10:0:j_idt11:j_idt14'});}); ``` ```javascript $(function(){PrimeFaces.cw('DataTable','widget_ubicacionForm_j_idt10_0_j_idt11_j_idt22',{id:'ubicacionForm:j_idt10:0:j_idt11:j_idt22'});}); ``` ```javascript $(function(){PrimeFaces.cw('DataTable','widget_ubicacionForm_j_idt10_1_j_idt11_j_idt14',{id:'ubicacionForm:j_idt10:1:j_idt11:j_idt14'});}); ``` ```javascript $(function(){PrimeFaces.cw('DataTable','widget_ubicacionForm_j_idt10_1_j_idt11_j_idt22',{id:'ubicacionForm:j_idt10:1:j_idt11:j_idt22'});}); ``` ```javascript $(function(){PrimeFaces.cw('DataTable','widget_ubicacionForm_j_idt10_2_j_idt11_j_idt14',{id:'ubicacionForm:j_idt10:2:j_idt11:j_idt14'});}); ``` ```javascript $(function(){PrimeFaces.cw('DataTable','widget_ubicacionForm_j_idt10_2_j_idt11_j_idt22',{id:'ubicacionForm:j_idt10:2:j_idt11:j_idt22'});}); ``` -------------------------------- ### Create and Process Aviso ARI Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/70_pld_create.md Use this snippet to create an Aviso ARI object with detailed information about the report, obligated party, alert, person involved, and transaction details. The .process() method prepares the object for XML generation. Ensure all required fields are populated accurately. ```python from datetime import date from satcfdi.create.pld import ari aviso_ari = ari.Archivo( informe=ari.InformeType( mes_reportado='201407', sujeto_obligado=ari.SujetoObligadoType( clave_sujeto_obligado='OGA751212G56', clave_actividad='ARI' ), aviso=ari.AvisoType( referencia_aviso='REF15454FG454', prioridad='1', alerta=ari.AlertaType( tipo_alerta='100' ), persona_aviso=ari.PersonaAvisoType( tipo_domicilio=ari.TipoDomicilioType( extranjero=ari.ExtranjeroType( pais='TG', estado_provincia='TOGUILLITA', ciudad_poblacion='TOGUIS', colonia='NA', calle='TOGA TOGA', numero_exterior='45', codigo_postal='12448' ) ), tipo_persona=ari.TipoPersonaType( persona_fisica=ari.PersonaFisicaType( nombre='NEPOMUCENO', apellido_paterno='ALMONTE', apellido_materno='JUAREZ', fecha_nacimiento=date(1956, 8, 16), pais_nacionalidad='TG', actividad_economica='3130100' ) ) ), detalle_operaciones=ari.DetalleOperacionesType( datos_operacion=ari.DatosOperacionType( fecha_operacion=date(2014, 7, 1), tipo_operacion='1501', caracteristicas=ari.CaracteristicasType( fecha_inicio=date(2014, 1, 1), fecha_termino=date(2015, 1, 1), tipo_inmueble='3', valor_referencia='356825.12', colonia='6920', calle='SAN SIMON TOLNAHUAC', numero_exterior='VIOLANTE', numero_interior='45', codigo_postal='01058', folio_real='BG544-FRR-456B-FRR' ), datos_liquidacion=ari.DatosLiquidacionType( fecha_pago=date(2014, 7, 1), forma_pago='4', instrumento_monetario='4', moneda='2', monto_operacion='757897.55' ) ) ) ) ) ).process() aviso_ari.xml_write("aviso_ari.xml") ``` -------------------------------- ### Display Payment Details Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/Pagos.html Display key payment information such as payment date, method, currency, exchange rate, and amount. ```Python {{ pago.FechaPago }} {{ pago.FormaDePagoP | desc }} {{ pago.MonedaP | desc }} {{ pago.TipoCambioP }} {{ pago.Monto }} ``` -------------------------------- ### Display Taxes for Related Documents (Retenciones) Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/Pagos.html Iterate through and display tax details (Retenciones) for related documents, including base amount, tax type, rate/quota, and amount. ```Python {% if doc.ImpuestosDR.RetencionesDR %} {% for v in iterate(doc.ImpuestosDR.RetencionesDR) %} {% endif %} {% if loop.first %}**Retenciones**{% endif %} {{ v.BaseDR }} {{ v.ImpuestoDR | desc }} {{ tasa_cuota( v.TipoFactorDR, v.TasaOCuotaDR) }} {{ v.ImporteDR }} {% endfor %} ``` -------------------------------- ### Download Constancia de Situación Fiscal PDF Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/48_csf.md Generate and download the Constancia de Situación Fiscal as a PDF. Requires loading FIEL credentials and using the `SATPortalConstancia` class. ```python from satcfdi.models import Signer from satcfdi.portal import SATPortalConstancia # Load Fiel signer = Signer.load( certificate=open('csd/xiqb891116qe4.cer', 'rb').read(), key=open('csd/xiqb891116qe4.key', 'rb').read(), password=open('csd/xiqb891116qe4.txt', 'r').read() ) sp = SATPortalConstancia(signer) res = sp.generar_constancia() with open('constancia.pdf', 'wb') as f: f.write(res) ``` -------------------------------- ### Display DIOT general data Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/DIOT.html Outputs the general information section as a JSON-like dump. ```jinja2 {{ c.DatosGenerales | dump }} ``` -------------------------------- ### Render Concept Details Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/Conceptos.html Renders various details of a concept item, including its description, quantity, unit value, and other attributes. ```html {{ c.Descripcion }} {{ c | simple('ClaveProdServ', 'NoIdentificacion', 'InformacionAduanera', 'CuentaPredial', 'Parte', 'instEducativas', 'ObjetoImp') }} {{ complements(c, c.ComplementoConcepto, level="h6") }} {{ c.Cantidad }} {{ c.ClaveUnidad }} {{ c.Unidad }} {{ c.ValorUnitario }} {{ c.Descuento }} {{ c.Importe }} ``` -------------------------------- ### Render Account Entry Data Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/Polizas.html Displays the financial details for a specific account entry. ```jinja2 {{ c.NumCta }} {{ c.DesCta }} {{ c.Concepto }} {{ c.Debe }} {{ c.Haber }} ``` -------------------------------- ### Generate DIOT with Operations Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/60_diot_create.md This snippet demonstrates how to generate a DIOT package including third-party operations. It supports various types of third-party providers (foreign, global, national) and operation types. The optional `complementaria` field can be used for complementary declarations. A PDF can also be rendered. ```python from datetime import date from satcfdi import render from satcfdi.diot import * diot = DIOT( datos_identificacion=DatosIdentificacion( rfc="OÑO120726RX3", razon_social="ORGANICOS ÑAVEZ OSORIO S.A DE C.V", ejercicio=2021, ), periodo=Periodo.JULIO_SEPTIEMBRE, complementaria=DatosComplementaria( folio_anterior="12313", fecha_presentacion_anterior=date(2021, 5, 10) ), proveedores=[ ProveedorTercero( tipo_tercero=TipoTercero.PROVEEDOR_EXTRANJERO, tipo_operacion=TipoOperacion.OTROS, id_fiscal="1254TAXID", nombre_extranjero="NOMBREEXTRANJERO", pais=Pais.ANTIGUA_Y_BERMUDA, nacionalidad="BERMUDO", iva16=456, iva16_na=752, iva_rfn=782, iva_rfn_na=456, iva_import16=123, iva_import16_na=475, iva_import_exento=7575, iva0=45213, iva_exento=1247, retenido=235, devoluciones=786 ), ProveedorTercero( tipo_tercero=TipoTercero.PROVEEDOR_GLOBAL, tipo_operacion=TipoOperacion.ARRENDAMIENTO_DE_INMUEBLES, iva16=9874, iva16_na=8521, iva_rfn=7632, iva_rfn_na=6541, iva_import16=5241, iva_import16_na=4123, iva_import_exento=3562, iva0=2415, iva_exento=1235, retenido=985, devoluciones=874 ), ProveedorTercero( tipo_tercero=TipoTercero.PROVEEDOR_NACIONAL, tipo_operacion=TipoOperacion.OTROS, rfc="L&O950913MSA", iva16=96208900, iva16_na=85100, iva_rfn=74300, iva_rfn_na=67600, iva0=58900, iva_exento=47700, retenido=36400, devoluciones=24864 ), ProveedorTercero( tipo_tercero=TipoTercero.PROVEEDOR_GLOBAL, tipo_operacion=TipoOperacion.PRESTACION_DE_SERVICIOS_PROFESIONALES, iva16=77757987856, ), ProveedorTercero( tipo_tercero=TipoTercero.PROVEEDOR_NACIONAL, tipo_operacion=TipoOperacion.PRESTACION_DE_SERVICIOS_PROFESIONALES, rfc="IXS7607092R5", iva16_na=500, iva_rfn=0 ) ] ) package = diot.generate_package() print(package) render.pdf_write(diot, 'diot.pdf') ``` -------------------------------- ### Iterate ComprNal Data Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/RepAuxFol.html Iterates through ComprNal data. No specific action is shown within the loop. ```Python {% for c in iterate(c.ComprNal) %} {% endfor %} ``` -------------------------------- ### Create a Nomina 1.2 CFDI Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/40_cfdi_create_guide.md Generates a payroll document including percepciones and deducciones, requiring specific nomina12 structures. ```python from datetime import date from decimal import Decimal from satcfdi.models import Signer from satcfdi.create.cfd import cfdi40, nomina12 # Load signing certificate signer = Signer.load( certificate=open('csd/xiqb891116qe4_csd.cer', 'rb').read(), key=open('csd/xiqb891116qe4_csd.key', 'rb').read(), password=open('csd/xiqb891116qe4_csd.txt', 'r').read() ) # create Comprobante invoice = cfdi40.Comprobante.nomina( emisor=cfdi40.Emisor( rfc=signer.rfc, nombre=signer.legal_name, regimen_fiscal="601" ), receptor=cfdi40.Receptor( rfc='KIJ0906199R1', nombre='KIJ, S.A DE C.V.', uso_cfdi='G03', domicilio_fiscal_receptor="59820", regimen_fiscal_receptor="601" ), lugar_expedicion="56820", complemento_nomina=nomina12.Nomina( emisor=nomina12.Emisor( registro_patronal='Z1234567890' ), receptor=nomina12.Receptor( cuenta_bancaria='0001000200030004', curp='XIQB891116MCHZRL72', clave_ent_fed='MOR', num_empleado='12345678', periodicidad_pago='04', tipo_contrato='01', tipo_regimen='02' ), percepciones=nomina12.Percepciones( percepcion=nomina12.Percepcion( tipo_percepcion='001', clave='001', concepto='SUELDO', importe_gravado=Decimal('1200'), importe_exento=Decimal('400') ) ), deducciones=nomina12.Deducciones( deduccion=nomina12.Deduccion( tipo_deduccion='002', clave='300', concepto='ISR A CARGO', importe=Decimal('1234.73') ) ), tipo_nomina='O', fecha_pago=date(2020, 1, 30), fecha_final_pago=date(2020, 1, 31), fecha_inicial_pago=date(2020, 1, 16), num_dias_pagados=Decimal('16.000') ), serie="A", folio="123456" ) invoice.sign(signer) invoice = invoice.process() ``` -------------------------------- ### Download Opinion de Cumplimiento Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/48_csf.md Generate and download the Opinion de Cumplimiento PDF. This requires loading FIEL credentials and utilizing the `SATPortalOpinionCumplimiento` class. ```python from satcfdi.models import Signer from satcfdi.portal import SATPortalOpinionCumplimiento # Load Fiel signer = Signer.load( certificate=open('csd/xiqb891116qe4.cer', 'rb').read(), key=open('csd/xiqb891116qe4.key', 'rb').read(), password=open('csd/xiqb891116qe4.txt', 'r').read() ) sp = SATPortalOpinionCumplimiento(signer) res = sp.generar_opinion_cumplimiento() with open('opinion_de_cumplimiento.pdf', 'wb') as f: f.write(res) ``` -------------------------------- ### Iterate Transaction Details in Auxiliar de Cuentas Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/AuxiliarCtas.html Iterates through the detailed auxiliary transactions for each account. This loop is essential for listing individual financial movements. ```Python {% for c in iterate(c.DetalleAux) %} {% endfor %} ``` -------------------------------- ### Display Total Amount Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/RepAuxFol.html Displays the Total Amount value. ```HTML/Jinja {{ c.MontoTotal }} ``` -------------------------------- ### Display Currency Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/satcfdi/render/templates/RepAuxFol.html Displays the Currency value. ```HTML/Jinja {{ c.Moneda }} ``` -------------------------------- ### Export CFDI to PDF Source: https://github.com/sat-cfdi/python-satcfdi/blob/main/docs/pages/getting_started/30_cfdi_load_guide.md Obtain the CFDI as PDF bytes using `render.pdf_bytes()` or save it directly to a file or stream using `render.pdf_write()`. ```python # PDF pdf = render.pdf_bytes(invoice) # save to file render.pdf_write(invoice, "_comprobante_.pdf") ``` ```python # .. or alternative with open("_stream_comprobante_.pdf", 'wb') as f: render.pdf_write(invoice, f) ```