openapi: 3.1.0
servers:
  - url: https://www.facturapi.io/v2
info:
  title: Facturapi
  version: '2.0'
  contact:
    name: Facturapi
    url: https://www.facturapi.io
    email: soporte@facturapi.io
  x-logo:
    url: https://www.facturapi.io/img/logo.svg
    altText: Facturapi
  description: |
    <br />
    <br />

    En esta página enlistamos todos los métodos
    disponibles en la API de Facturapi, así como
    la referencia completa de los parámetros
    que acepta cada uno. Para ver las propiedades
    anidadas de un objeto o arreglo de objetos,
    puedes hacer clic sobre el nombre del campo y
    expandirlo.

    La API de Facturapi está diseñada con el
    estándar [REST](https://developer.mozilla.org/en-US/docs/Glossary/REST)
    en mente. Los endpoints de la API están agrupados
    por recursos, tienen URLs predecibles, las respuestas
    tienen formato JSON y usamos códigos HTTP de respuesta,
    autenticación y verbos estándar.

    Durante el desarrollo, puedes usar la API de Facturapi en
    ambiente Test y las facturas que emitas no se enviarán al SAT ni
    tendrán validez fiscal.

    La llave secreta que utilices para autenticarte
    determinará tanto el ambiente en el que se creará la factura
    (Test o Live), así como la organización a utilizar como emisor
    de tu factura, o bien como dueña del recurso que solicites crear.
tags:
  - name: tools
    x-displayName: Herramientas
  - name: customer
    x-displayName: Clientes
  - name: product
    x-displayName: Productos
  - name: invoice
    x-displayName: Facturas
  - name: receipt
    x-displayName: Recibos
  - name: retention
    x-displayName: Retenciones
  - name: organization
    x-displayName: Organizaciones
  - name: organization_access
    x-displayName: Usuarios y permisos
  - name: webhooks
    x-displayName: Webhooks
  - name: events
    x-displayName: Eventos
    description: >
      Los eventos ocurren cuando Facturapi realiza una operación

      de manera asíncrona, es decir, fuera del ciclo de vida de

      una petición a la API.


      Para recibir estos eventos en tu servidor, puedes registrar una URL de
      escucha

      creando un **Webhook** desde tu dashboard:
      https://dashboard.facturapi.io/integration/webhooks
  - name: sat_keys
    x-displayName: Claves de catálogos
    description: "Principales catálogos del SAT, incluídos aquí por conveniencia. Puedes consultar estos y más catálogos desde el portal oficial del SAT: http://omawww.sat.gob.mx/tramitesyservicios/Paginas/anexo_20_version3-3.htm\n\n### Forma de pago\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Efectivo\n\"02\" | Cheque nominativo\n\"03\" | Transferencia electrónica de fondos\n\"04\" | Tarjeta de crédito\n\"05\" | Monedero electrónico\n\"06\" | Dinero electrónico\n\"08\" | Vales de despensa\n\"12\" | Dación en pago\n\"13\" | Pago por subrogación\n\"14\" | Pago por consignación\n\"15\" | Condonación\n\"17\" | Compensación\n\"23\" | Novación\n\"24\" | Confusión\n\"25\" | Remisión de deuda\n\"26\" | Prescripción o caducidad\n\"27\" | A satisfacción del acreedor\n\"28\" | Tarjeta de débito\n\"29\" | Tarjeta de servicios\n\"30\" | Aplicación de anticipos\n\"31\" | Intermediario pagos\n\"99\" | Por definir\n\n### Método de pago\n\nClave | Descripción\n:-----:| -----------\n\"PUE\" | Pago en una sola exhibición (de contado).\n\"PPD\" | Pago en parcialidades o diferido (total o parcialmente a crédito). Requiere expedir un comprobante de pago cuando se reciba un pago subsecuente.\n\n### Uso CFDI\n\nClave | Descripción | Régimen Fiscal \n:-----:| ----------- | -----------\n\"G01\" | Adquisición de mercancías. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625,626\n\"G02\" | Devoluciones, descuentos o bonificaciones. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625,626\n\"G03\" | Gastos en general. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I01\" | Construcciones. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I02\" | Mobiliario y equipo de oficina por inversiones. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I03\" | Equipo de transporte. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I04\" | Equipo de computo y accesorios. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I05\" | Dados, troqueles, moldes, matrices y herramental. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I06\" | Comunicaciones telefónicas. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I07\" | Comunicaciones satelitales. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"I08\" | Otra maquinaria y equipo. | 601, 603, 606, 612, 620, 621, 622, 623, 624, 625, 626\n\"D01\" | Honorarios médicos, dentales y gastos hospitalarios. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D02\" | Gastos médicos por incapacidad o discapacidad. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D03\" | Gastos funerales. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D04\" | Donativos. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D05\" | Intereses reales efectivamente pagados por créditos hipotecarios (casa habitación). | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D06\" | Aportaciones voluntarias al SAR. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D07\" | Primas por seguros de gastos médicos. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D08\" | Gastos de transportación escolar obligatoria. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D09\" | Depósitos en cuentas para el ahorro, primas que tengan como base planes de pensiones. | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"D10\" | Pagos por servicios educativos (colegiaturas). | 605, 606, 608, 611, 612, 614, 607, 615, 625\n\"S01\" | Sin efectos fiscales.  | 601, 603, 605, 606, 608, 610, 611, 612, 614, 616, 620, 621, 622, 623, 624, 607, 615, 625, 626\n\"CP01\" | Pagos |  601, 603, 605, 606, 608, 610, 611, 612, 614, 616, 620, 621, 622, 623, 624, 607, 615, 625, 626\n\"CN01\" | Nómina | 605\n\n### Catálogos Hidrocarburos Petrolíferos\n\nClave de permiso | Descripción\n:-----:| -----------\n\"PER01\" | Expendio en estaciones de servicio de petrolíferos\n\"PER02\" | Comercialización\n\"PER03\" | Distribución por otros medios distintos a ducto\n\"PER04\" | Expendio en estaciones de servicio multimodal de petrolíferos\n\"PER05\" | Expendio en estaciones de servicio de petrolíferos\n\"PER06\" | Comercialización\n\"PER07\" | Distribución por otros medios distintos a ducto\n\"PER08\" | Expendio en estaciones de servicio multimodal de petrolíferos\n\"PER09\" | Comercialización\n\"PER10\" | Comercialización\n\"PER11\" | Comercialización\n\nClave HYP | Descripción\n:-----:| -----------\n\"15101514\" | Gasolina\n\"15101515\" | Diesel\n\"15101505\" | Combustibles para barco\n\nSubproducto HYP | Descripción\n:-----:| -----------\n\"SP16\" | Gasolina regular menor a 91 octanos\n\"SP17\" | Gasolina premium mayor o igual a 91 octanos\n\"SP18\" | Diésel automotriz\n\"SP19\" | Diésel marino\n\"SP22\" | IFO380\n\"SP23\" | Diésel industrial\n\"SP24\" | Diésel de Ultra Bajo Azufre (DUBA)\n\"SP25\" | Diésel agrícola\n\"SP48\" | Gasóleo doméstico\n\n### Relación entre facturas\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Nota de crédito de los documentos relacionados\n\"02\" | Nota de débito de los documentos relacionados\n\"03\" | Devolución de mercancía sobre facturas o traslados previos\n\"04\" | Sustitución de los CFDI previos\n\"05\" | Traslados de mercancias facturados previamente\n\"06\" | Factura generada por los traslados previos\n\"07\" | CFDI por aplicación de anticipo\n\"08\" | Factura generada por pagos en parcialidades\n\"09\" | Factura generada por pagos diferidos\n\n### Régimen Fiscal\n\nClave | Descripción\n:-----:| -----------\n\"601\" |\tGeneral de Ley Personas Morales\n\"603\" |\tPersonas Morales con Fines no Lucrativos\n\"605\" |\tSueldos y Salarios e Ingresos Asimilados a Salarios\n\"606\" |\tArrendamiento\n\"608\" |\tDemás ingresos\n\"609\" |\tConsolidación\n\"610\" |\tResidentes en el Extranjero sin Establecimiento Permanente en México\n\"611\" |\tIngresos por Dividendos (socios y accionistas)\n\"612\" |\tPersonas Físicas con Actividades Empresariales y Profesionales\n\"614\" |\tIngresos por intereses\n\"616\" |\tSin obligaciones fiscales\n\"620\" |\tSociedades Cooperativas de Producción que optan por diferir sus ingresos\n\"621\" |\tIncorporación Fiscal\n\"622\" |\tActividades Agrícolas, Ganaderas, Silvícolas y Pesqueras\n\"623\" |\tOpcional para Grupos de Sociedades\n\"624\" |\tCoordinados\n\"628\" |\tHidrocarburos\n\"607\" |\tRégimen de Enajenación o Adquisición de Bienes\n\"629\" |\tDe los Regímenes Fiscales Preferentes y de las Empresas Multinacionales\n\"630\" |\tEnajenación de acciones en bolsa de valores\n\"615\" |\tRégimen de los ingresos por obtención de premios\n\"625\" |\tRégimen de las Actividades Empresariales con ingresos a través de Plataformas Tecnológicas\n\"626\" | Régimen Simplificado de Confianza\n\n### Meses y bimestres\n\nClave | Descripción\n:-----:| -----------\n01 | Enero\n02 | Febrero\n03 | Marzo\n04 | Abril\n05 | Mayo\n06 | Junio\n07 | Julio\n08 | Agosto\n09 | Septiembre\n10 | Octubre\n11 | Noviembre\n12 | Diciembre\n13 | Enero-Febrero\n14 | Marzo-Abril\n15 | Mayo-Junio\n16 | Julio-Agosto\n17 | Septiembre-Octubre\n18 | Noviembre-Diciembre\n\n### Tipo de Contrato\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Contrato de trabajo por tiempo indeterminado\n\"02\" | Contrato de trabajo para obra determinada\n\"03\" | Contrato de trabajo por tiempo determinado\n\"04\" | Contrato de trabajo por temporada\n\"05\" | Contrato de trabajo sujeto a prueba\n\"06\" | Contrato de trabajo con capacitación inicial\n\"07\" | Modalidad de contratación por pago de hora laborada\n\"08\" | Modalidad de trabajo por comisión laboral\n\"09\" | Modalidades de contratación donde no existe relación de trabajo\n\"10\" | Jubilación, pensión, retiro.\n\"99\" | Otro contrato\n\n### Tipo de Jornada\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Diurna\n\"02\" | Nocturna\n\"03\" | Mixta\n\"04\" | Por hora\n\"05\" | Reducida\n\"06\" | Continuada\n\"07\" | Partida\n\"08\" | Por turnos\n\"99\" | Otra Jornada\n\n### Tipo de Régimen\n\nClave | Descripción\n:-----:| -----------\n\"02\" | Sueldos (Incluye ingresos señalados en la fracción I del artículo 94 de LISR)\n\"03\" | Jubilados\n\"04\" | Pensionados\n\"05\" | Asimilados Miembros Sociedades Cooperativas Produccion\n\"06\" | Asimilados Integrantes Sociedades Asociaciones Civiles\n\"07\" | Asimilados Miembros consejos\n\"08\" | Asimilados comisionistas\n\"09\" | Asimilados Honorarios\n\"10\" | Asimilados acciones\n\"11\" | Asimilados otros\n\"12\" | Jubilados o Pensionados\n\"13\" | Indemnización o Separación\n\"99\" | Otro Regimen\n\n### Riesgo del Puesto\n\nClave | Descripción\n:-----:| -----------\n\"1\" | Clase I\n\"2\" | Clase II\n\"3\" | Clase III\n\"4\" | Clase IV\n\"5\" | Clase V\n\"99\" | No aplica\n\n### Periodicidad del Pago\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Diario\n\"02\" | Semanal\n\"03\" | Catorcenal\n\"04\" | Quincenal\n\"05\" | Mensual\n\"06\" | Bimestral\n\"07\" | Unidad obra\n\"08\" | Comisión\n\"09\" | Precio alzado\n\"10\" | Decenal\n\"99\" | Otra Periodicidad\n\n### Tipo de Percepción\n\nClave | Descripción\n:-----:| -----------\n\"001\" | Sueldos, Salarios  Rayas y Jornales\n\"002\" | Gratificación Anual (Aguinaldo)\n\"003\" | Participación de los Trabajadores en las Utilidades PTU\n\"004\" | Reembolso de Gastos Médicos Dentales y Hospitalarios\n\"005\" | Fondo de Ahorro\n\"006\" | Caja de ahorro\n\"009\" | Contribuciones a Cargo del Trabajador Pagadas por el Patrón\n\"010\" | Premios por puntualidad\n\"011\" | Prima de Seguro de vida\n\"012\" | Seguro de Gastos Médicos Mayores\n\"013\" | Cuotas Sindicales Pagadas por el Patrón\n\"014\" | Subsidios por incapacidad\n\"015\" | Becas para trabajadores y/o hijos\n\"019\" | Horas extra\n\"020\" | Prima dominical\n\"021\" | Prima vacacional\n\"022\" | Prima por antigüedad\n\"023\" | Pagos por separación\n\"024\" | Seguro de retiro\n\"025\" | Indemnizaciones\n\"026\" | Reembolso por funeral\n\"027\" | Cuotas de seguridad social pagadas por el patrón\n\"028\" | Comisiones\n\"029\" | Vales de despensa\n\"030\" | Vales de restaurante\n\"031\" | Vales de gasolina\n\"032\" | Vales de ropa\n\"033\" | Ayuda para renta\n\"034\" | Ayuda para artículos escolares\n\"035\" | Ayuda para anteojos\n\"036\" | Ayuda para transporte\n\"037\" | Ayuda para gastos de funeral\n\"038\" | Otros ingresos por salarios\n\"039\" | Jubilaciones, pensiones o haberes de retiro\n\"044\" | Jubilaciones, pensiones o haberes de retiro en parcialidades\n\"045\" | Ingresos en acciones o títulos valor que representan bienes\n\"046\" | Ingresos asimilados a salarios\n\"047\" | Alimentación diferentes a los establecidos en el Art 94 último párrafo LISR\n\"048\" | Habitación\n\"049\" | Premios por asistencia\n\"050\" | Viáticos\n\"051\" | Pagos por gratificaciones, primas, compensaciones, recompensas u otros en parcialidades\n\"052\" | Pagos por jubilación en parcialidades derivados de una resolución judicial\n\"053\" | Pagos por jubilación en una sola exhibición derivados de la ejecución de una resolución judicial\n\n### Tipo de Horas\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Dobles\n\"02\" | Triples\n\"03\" | Simples\n\n### Tipo de Deducción\n\nClave | Descripción\n:-----:| -----------\n\"001\" | Seguridad social\n\"002\" | ISR\n\"003\" | Aportaciones a retiro, cesantía en edad avanzada y vejez.\n\"004\" | Otros\n\"005\" | Aportaciones a Fondo de vivienda\n\"006\" | Descuento por incapacidad\n\"007\" | Pensión alimenticia\n\"008\" | Renta\n\"009\" | Préstamos provenientes del Fondo Nacional de la Vivienda para los Trabajadores\n\"010\" | Pago por crédito de vivienda\n\"011\" | Pago de abonos INFONACOT\n\"012\" | Anticipo de salarios\n\"013\" | Pagos hechos con exceso al trabajador\n\"014\" | Errores\n\"015\" | Pérdidas\n\"016\" | Averías\n\"017\" | Adquisición de artículos producidos por la empresa o establecimiento\n\"018\" | Cuotas para la constitución y fomento de sociedades cooperativas y de cajas de ahorro\n\"019\" | Cuotas sindicales\n\"020\" | Ausencia (Ausentismo)\n\"021\" | Cuotas obrero patronales\n\"022\" | Impuestos Locales\n\"023\" | Aportaciones voluntarias\n\"024\" | Ajuste en Gratificación Anual (Aguinaldo) Exento\n\"025\" | Ajuste en Gratificación Anual (Aguinaldo) Gravado\n\"026\" | Ajuste en Participación de los Trabajadores en las Utilidades PTU Exento\n\"027\" | Ajuste en Participación de los Trabajadores en las Utilidades PTU Gravado\n\"028\" | Ajuste en Reembolso de Gastos Médicos Dentales y Hospitalarios Exento\n\"029\" | Ajuste en Fondo de ahorro Exento\n\"030\" | Ajuste en Caja de ahorro Exento\n\"031\" | Ajuste en Contribuciones a Cargo del Trabajador Pagadas por el Patrón Exento\n\"032\" | Ajuste en Premios por puntualidad Gravado\n\"033\" | Ajuste en Prima de Seguro de vida Exento\n\"034\" | Ajuste en Seguro de Gastos Médicos Mayores Exento\n\"035\" | Ajuste en Cuotas Sindicales Pagadas por el Patrón Exento\n\"036\" | Ajuste en Subsidios por incapacidad Exento\n\"037\" | Ajuste en Becas para trabajadores y/o hijos Exento\n\"038\" | Ajuste en Horas extra Exento\n\"039\" | Ajuste en Horas extra Gravado\n\"040\" | Ajuste en Prima dominical Exento\n\"041\" | Ajuste en Prima dominical Gravado\n\"042\" | Ajuste en Prima vacacional Exento\n\"043\" | Ajuste en Prima vacacional Gravado\n\"044\" | Ajuste en Prima por antigüedad Exento\n\"045\" | Ajuste en Prima por antigüedad Gravado\n\"046\" | Ajuste en Pagos por separación Exento\n\"047\" | Ajuste en Pagos por separación Gravado\n\"048\" | Ajuste en Seguro de retiro Exento\n\"049\" | Ajuste en Indemnizaciones Exento\n\"050\" | Ajuste en Indemnizaciones Gravado\n\"051\" | Ajuste en Reembolso por funeral Exento\n\"052\" | Ajuste en Cuotas de seguridad social pagadas por el patrón Exento\n\"053\" | Ajuste en Comisiones Gravado\n\"054\" | Ajuste en Vales de despensa Exento\n\"055\" | Ajuste en Vales de restaurante Exento\n\"056\" | Ajuste en Vales de gasolina Exento\n\"057\" | Ajuste en Vales de ropa Exento\n\"058\" | Ajuste en Ayuda para renta Exento\n\"059\" | Ajuste en Ayuda para artículos escolares Exento\n\"060\" | Ajuste en Ayuda para anteojos Exento\n\"061\" | Ajuste en Ayuda para transporte Exento\n\"062\" | Ajuste en Ayuda para gastos de funeral Exento\n\"063\" | Ajuste en Otros ingresos por salarios Exento\n\"064\" | Ajuste en Otros ingresos por salarios Gravado\n\"065\" | Ajuste en Jubilaciones, pensiones o haberes de retiro en una sola exhibición Exento\n\"066\" | Ajuste en Jubilaciones, pensiones o haberes de retiro en una sola exhibición Gravado\n\"067\" | Ajuste en Pagos por separación Acumulable\n\"068\" | Ajuste en Pagos por separación No acumulable\n\"069\" | Ajuste en Jubilaciones, pensiones o haberes de retiro en parcialidades Exento\n\"070\" | Ajuste en Jubilaciones, pensiones o haberes de retiro en parcialidades Gravado\n\"071\" | Ajuste en Subsidio para el empleo (efectivamente entregado al trabajador)\n\"072\" | Ajuste en Ingresos en acciones o títulos valor que representan bienes Exento\n\"073\" | Ajuste en Ingresos en acciones o títulos valor que representan bienes Gravado\n\"074\" | Ajuste en Alimentación Exento\n\"075\" | Ajuste en Alimentación Gravado\n\"076\" | Ajuste en Habitación Exento\n\"077\" | Ajuste en Habitación Gravado\n\"078\" | Ajuste en Premios por asistencia\n\"079\" | Ajuste en Pagos distintos a los listados\n\"080\" | Ajuste en Viáticos gravados\n\"081\" | Ajuste en Viáticos (entregados al trabajador)\n\"082\" | Ajuste en Fondo de ahorro Gravado\n\"083\" | Ajuste en Caja de ahorro Gravado\n\"084\" | Ajuste en Prima de Seguro de vida Gravado\n\"085\" | Ajuste en Seguro de Gastos Médicos Mayores Gravado\n\"086\" | Ajuste en Subsidios por incapacidad Gravado\n\"087\" | Ajuste en Becas para trabajadores y/o hijos Gravado\n\"088\" | Ajuste en Seguro de retiro Gravado\n\"089\" | Ajuste en Vales de despensa Gravado\n\"090\" | Ajuste en Vales de restaurante Gravado\n\"091\" | Ajuste en Vales de gasolina Gravado\n\"092\" | Ajuste en Vales de ropa Gravado\n\"093\" | Ajuste en Ayuda para renta Gravado\n\"094\" | Ajuste en Ayuda para artículos escolares Gravado\n\"095\" | Ajuste en Ayuda para anteojos Gravado\n\"096\" | Ajuste en Ayuda para transporte Gravado\n\"097\" | Ajuste en Ayuda para gastos de funeral Gravado\n\"098\" | Ajuste a ingresos asimilados a salarios gravados\n\"099\" | Ajuste a ingresos por sueldos y salarios gravados\n\"100\" | Ajuste en Viáticos exentos\n\"101\" | ISR Retenido de ejercicio anterior\n\"102\" | Ajuste a pagos por gratificaciones, primas, compensaciones, recompensas u otros\n\"103\" | Ajuste a pagos en parcialidades derivados de una resolución judicial gravados\n\"104\" | Ajuste a pagos en parcialidades derivados de una resolución judicial exentos\n\"105\" | Ajuste a pagos en una sola exhibición derivados de una resolución judicial gravados\n\"106\" | Ajuste a pagos en una sola exhibición derivados de una resolución judicial exentos\n\"107\" | Ajuste al Subsidio Causado\n\n### Tipo de Otro Pago\n\nClave | Descripción\n:-----:| -----------\n\"001\" | Reintegro de ISR pagado en exceso.\n\"002\" | Subsidio para el empleo (efectivamente entregado al trabajador).\n\"003\" | Viáticos (entregados al trabajador).\n\"004\" | Aplicación de saldo a favor por compensación anual.\n\"005\" | Reintegro de ISR retenido en exceso de ejercicio anterior\n\"006\" | Alimentos en bienes (Servicios de comedor y comida).\n\"007\" | ISR ajustado por subsidio.\n\"008\" | Subsidio efectivamente entregado que no correspondía.\n\"009\" | Reembolso de descuentos efectuados para el crédito de vivienda.\n\"999\" | Pagos distintos a los listados.\n\n### Tipo de Incapacidad\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Riesgo de trabajo.\n\"02\" | Enfermedad en general.\n\"03\" | Maternidad.\n\"04\" | Licencia por cuidados médicos de hijos diagnosticados con cáncer.\n\n### Clave de retención\n\nClave | Descripción\n:-----:| -----------\n\"01\" | Servicios profesionales.\n\"02\" | Regalías por derechos de autor.\n\"03\" | Autotransporte terrestre de carga.\n\"04\" | Servicios prestados por comisionistas.\n\"05\" | Arrendamiento.\n\"06\" | Enajenación de acciones.\n\"07\" | Enajenación de bienes objeto de la LIEPS, a través de mediadores, agentes, representantes, corredores, consignatarios o distribuidores.\n\"08\" | Enajenación de bienes inmuebles consignada en escritura pública.\n\"09\" | Enajenación de otros bienes, no consignada en escritura pública.\n\"10\" | Adquisición de desperdicios industriales.\n\"11\" | Adquisición de bienes consignada en escritura pública.\n\"12\" | Adquisición de otros bienes, no consignada en escritura pública.\n\"13\" | Otros retiros de AFORE.\n\"14\" | Dividendos o utilidades distribuidas.\n\"15\" | Remanente distribuible.\n\"16\" | Intereses.\n\"17\" | Arrendamiento en fideicomiso.\n\"18\" | Pagos realizados a favor de residentes en el extranjero.\n\"19\" | Enajenación de acciones u operaciones en bolsa de valores.\n\"20\" | Obtención de premios.\n\"21\" | Fideicomisos que no realizan actividades empresariales.\n\"22\" | Planes personales de retiro.\n\"23\" | Intereses reales deducibles por créditos hipotecarios.\n\"24\" | Operaciones Financieras Derivadas de Capital.\n\"25\" | Otro tipo de retenciones.\n\"26\" | Servicios mediante Plataformas Tecnológicas\n\n### Validez de obligaciones\n\n| Validez | IVA Exento | Tasa 0% | Tasa 8% Fronteriza Norte | Tasa 8% Fronteriza Sur | Tasa 16%\n|:-------:|:----------:|:-------:|:------------------------:|:----------------------:|:--------\n| \"0\" | El contribuyente no está autorizado para emitir facturas | El contribuyente no está autorizado para emitir facturas | El contribuyente no está autorizado para emitir facturas | El contribuyente no está autorizado para emitir facturas | El contribuyente no está autorizado para emitir facturas\n| \"1\" | Sí | Sí | No | No | Sí\n| \"2\" | Sí | Sí | Sí | No | Sí\n| \"3\" | Sí | Sí | No | Sí | Sí\n| \"4\" | Sí | Sí | Sí | Sí | Sí\n\n#### Situación del contribuyente\n\n| Valor | Explicación\n|:-----:|:-----------\n| \"Previsto\" | Vía buzón tributario o notificaciones por estrados, el contribuyente recibe un oficio en el que se establece su situación y se le solicita que demuestre la materialidad de las operaciones facturadas.\n| \"Presunto\" | El contribuyente notificado se considera presunto cuando, en su página web, la autoridad emite sus datos dentro de la relación de los EFOS, es decir, en las listas negras del SAT.\n| \"Desvirtuado\" | En este caso, el contribuyente acusado de operaciones inexistentes ya aportó a la autoridad la documentación e información pertinente para desvirtuar los hechos que llevaron a notificarlo.\n| \"Definitivo\" | En este caso, el EFO no atendió el llamado de la autoridad en el plazo de 15 días, a partir de la última notificación; o bien, no pudo desvirtuar los hechos imputados.\n| \"Sentencia favorable\" | Los contribuyentes EFOS “definitivos” que se inconforman e interponen algún medio de defensa, el cual concluye a su favor, son clasificados en la lista de “sentencia favorable”.\n| \"EFOS de información suprimida\" | En esta categoría, se encuentran los EFOS “presuntos” y “definitivos” que presentaron algún medio de defensa (amparo, juicio de nulidad) y, por lo tanto, un juez ordenó suprimir sus datos de la lista, sin ser eliminados.\n"
  - name: carta_porte_keys
    x-displayName: Catálogos Carta Porte
    description: >
      Catálogos específicos del complemento Carta Porte 3.1. Útiles para validar
      y construir correctamente los valores del complemento.


      Cada tabla incluye: Clave | Descripción (Español oficial)


      ### Régimenes Aduaneros (c_RegimenAduanero)


      Clave | Descripción

      :-----:| -----------

      IMD | Importación definitiva

      EXD | Exportación definitiva

      ITR | Tránsito interno de mercancías

      ITE | Tránsito interno de mercancías para exportación

      ETR | Tránsito externo de mercancías

      ETE | Tránsito externo de mercancías para exportación

      DFI | Depósito fiscal

      RFE | Recinto fiscalizado estratégico

      RFS | Recinto fiscalizado

      TRA | Tránsito aduanero


      ### Medio de Transporte (c_MedioTransporte)


      Clave | Descripción

      :-----:| -----------

      01 | Autotransporte

      02 | Transporte Marítimo

      03 | Transporte Aéreo

      04 | Transporte Ferroviario

      05 | Otro


      ### Tipo de Estación (c_TipoEstacion)


      Clave | Descripción

      :-----:| -----------

      01 | Origen Nacional

      02 | Intermedia

      03 | Destino Final Nacional


      ### Permisos SCT (c_PermisoSCT)


      Clave | Descripción

      :-----:| -----------

      TPAF01 | Autotransporte Federal de carga general

      TPAF02 | Transporte privado de carga

      TPAF03 | Autotransporte Federal de Carga Especializada de materiales y
      residuos peligrosos

      TPAF04 | Transporte de automóviles sin rodar en vehículo tipo góndola

      TPAF05 | Transporte de carga de gran peso y/o volumen de hasta 90
      toneladas

      TPAF06 | Transporte de carga especializada de gran peso y/o volumen de más
      90 toneladas

      TPAF07 | Transporte Privado de materiales y residuos peligrosos

      TPAF08 | Autotransporte internacional de carga de largo recorrido

      TPAF09 | Autotransporte internacional de carga especializada de materiales
      y residuos peligrosos de largo recorrido

      TPAF10 | Autotransporte Federal de Carga General cuyo ámbito de aplicación
      comprende la franja fronteriza con Estados Unidos

      TPAF11 | Autotransporte Federal de Carga Especializada cuyo ámbito de
      aplicación comprende la franja fronteriza con Estados Unidos

      TPAF12 | Servicio auxiliar de arrastre en las vías generales de
      comunicación

      TPAF13 | Servicio auxiliar de arrastre, arrastre y salvamento, y depósito
      de vehículos

      TPAF14 | Servicio de paquetería y mensajería en las vías generales de
      comunicación

      TPAF15 | Transporte especial para tránsito de grúas industriales hasta 90
      toneladas

      TPAF16 | Servicio federal para empresas arrendadoras servicio público
      federal

      TPAF17 | Empresas trasladistas de vehículos nuevos

      TPAF18 | Empresas fabricantes o distribuidoras de vehículos nuevos

      TPAF19 | Autorización para circular con tractocamión doblemente articulado

      TPAF20 | Autotransporte Federal de Carga Especializada de fondos y valores

      TPTM01 | Permiso temporal para navegación de cabotaje

      TPTA01 | Concesión/ autorización servicio regular nacional/internacional
      (empresas mexicanas)

      TPTA02 | Permiso servicio aéreo regular empresas extranjeras

      TPTA03 | Permiso servicio no regular de fletamento nacional/internacional

      TPTA04 | Permiso servicio no regular de taxi aéreo nacional/internacional

      TPXX00 | Permiso no contemplado en el catálogo


      ### Sector COFEPRIS (c_SectorCOFEPRIS)


      Clave | Descripción

      :-----:| -----------

      01 | Medicamento

      02 | Precursores y químicos de uso dual

      03 | Psicotrópicos y estupefacientes

      04 | Sustancias tóxicas

      05 | Plaguicidas y fertilizantes


      ### Forma Farmacéutica (c_FormaFarmacéutica)


      Clave | Descripción

      :-----:| -----------

      01 | Tableta

      02 | Cápsulas

      03 | Comprimidos

      04 | Grageas

      05 | Suspensión

      06 | Solución

      07 | Emulsión

      08 | Jarabe

      09 | Inyectable

      10 | Crema

      11 | Ungüento

      12 | Aerosol

      13 | Gas medicinal

      14 | Gel

      15 | Implante

      16 | Óvulo

      17 | Parche

      18 | Pasta

      19 | Polvo

      20 | Supositorio


      ### Condiciones Especiales (c_CondicionesEspeciales)


      Clave | Descripción

      :-----:| -----------

      01 | Congelados

      02 | Refrigerados

      03 | Temperatura controlada

      04 | Temperatura ambiente


      ### Tipo de Materia (c_TipoMateria)


      Clave | Descripción

      :-----:| -----------

      01 | Materia prima

      02 | Materia procesada

      03 | Materia terminada (producto terminado)

      04 | Materia para la industria manufacturera

      05 | Otra


      ### Tipo de Documento de Aduana (c_TipoDocumentoAduanero)


      Clave | Descripción

      :-----:| -----------

      01 | Pedimento

      02 | Autorización de importación temporal

      03 | Autorización de importación temporal de embarcaciones

      04 | Autorización de importación temporal de mercancías para
      mantenimiento/reparación

      05 | Autorización para importación de vehículos especializados

      06 | Aviso de exportación temporal

      07 | Aviso traslado (IMMEX/RFE/Operador Económico Autorizado)

      08 | Aviso traslado autopartes franja fronteriza

      09 | Constancia importación/retorno/transferencia contenedores

      10 | Constancia de transferencia de mercancías

      11 | Autorización de donación de mercancías (extranjero)

      12 | Cuaderno ATA

      13 | Listas de intercambio

      14 | Permiso de Importación Temporal

      15 | Permiso importación temporal casa rodante

      16 | Permiso importación temporal embarcaciones

      17 | Solicitud donación (emergencias/desastres)

      18 | Aviso de consolidado

      19 | Aviso de cruce de mercancias

      20 | Otro


      ### Tipo de Transporte (c_ParteTransporte)


      Clave | Descripción

      :-----:| -----------

      PT01 | Camión unitario

      PT02 | Camión

      PT03 | Tractocamión

      PT04 | Remolque

      PT05 | Semirremolque

      PT06 | Vehículo ligero de carga

      PT07 | Grúa

      PT08 | Aeronave

      PT09 | Barco o buque

      PT10 | Carro o vagón

      PT11 | Contenedor

      PT12 | Locomotora


      ### Figuras de Transporte (c_FiguraTransporte)


      Clave | Descripción

      :-----:| -----------

      01 | Operador

      02 | Propietario

      03 | Arrendador

      04 | Notificado

      05 | Integrante de Coordinados


      ### Registro ISTMO (c_RegistroISTMO)


      Clave | Descripción

      :-----:| -----------

      01 | Coatzacoalcos I

      02 | Coatzacoalcos II

      03 | Texistepec

      04 | San Juan Evangelista

      05 | Salina Cruz

      06 | San Blas Atempa


      ### Clave de Tipo de Carga (c_ClaveTipoCarga)


      Clave | Descripción

      :-----:| -----------

      CGS | Carga General Suelta

      CGC | Carga General Contenerizada

      GMN | Gran Mineral

      GAG | Granel Agrícola

      OFL | Otros Fluidos

      PYD | Petróleo y Derivados


      ### Configuración Marítima (c_ConfiguracionMaritima)


      Clave | Descripción

      :-----:| -----------

      B01 | Abastecedor

      B02 | Barcaza

      B03 | Granelero

      B04 | Porta Contenedor

      B05 | Draga

      B06 | Pesquero

      B07 | Carga General

      B08 | Quimiqueros

      B09 | Transbordadores

      B10 | Carga RoRo

      B11 | Investigación

      B12 | Tanquero

      B13 | Gasero

      B14 | Remolcador

      B15 | Extraordinaria especialización


      ### Tipo de Tráfico Ferroviario (c_TraficoFerroviario)


      Clave | Descripción

      :-----:| -----------

      TT01 | Tráfico local

      TT02 | Tráfico interlineal remitido

      TT03 | Tráfico interlineal recibido

      TT04 | Tráfico interlineal en tránsito


      ### Tipo de Contenedor (c_TipoContenedor)


      Clave | Descripción

      :-----:| -----------

      TC01 | Contenedor de 6.1 Mts de longitud

      TC02 | Contenedor de 12.2 Mts de longitud

      TC03 | Contenedor de 13.7 Mts de longitud

      TC04 | Contenedor de 14.6 Mts de longitud

      TC05 | Contenedor de 16.1 Mts de longitud


      ### Tipo de Contenedor Marítimo (c_TipoContenedorMaritimo)


      Clave | Descripción

      :-----:| -----------

      CM001 | Contenedores refrigerados de 20FT

      CM002 | Contenedores refrigerados de 40FT

      CM003 | Contenedores estándar de 8FT

      CM004 | Contenedores estándar de 10FT

      CM005 | Contenedores estándar de 20FT

      CM006 | Contenedores estándar de 40FT

      CM007 | Contenedores Open Side

      CM008 | Contenedor Isotanque

      CM009 | Contenedor flat racks

      CM010 | Buque tanque

      CM011 | Ferri

      CM012 | Ferri – Turístico y vacíos


      ### Tipo de Carro Ferroviario (c_TipoCarroFerroviario)


      Clave | Descripción

      :-----:| -----------

      TC01 | Furgón

      TC02 | Góndola

      TC03 | Tolva

      TC04 | Tanque

      TC05 | Plataforma Intermodal

      TC06 | Plataforma de Uso General

      TC07 | Plataforma Automotriz

      TC08 | Locomotora

      TC09 | Carro Especial

      TC10 | Pasajeros

      TC11 | Mantenimiento de Vía


      ### Tipo de Servicio Ferroviario (c_TipoServicioFerroviario)


      Clave | Descripción

      :-----:| -----------

      TS01 | Carros Ferroviarios

      TS02 | Carros Ferroviarios intermodal

      TS03 | Tren unitario de carros ferroviarios

      TS04 | Tren unitario Intermodal
  - name: comercio_exterior_keys
    x-displayName: Catálogos Comercio Exterior
    description: >
      Catálogos específicos del complemento Comercio Exterior 2.0. Útiles para
      validar y construir correctamente los valores del complemento.


      Cada tabla incluye: Clave | Descripción (Español oficial)


      ### Motivo de traslado (c_MotivoTraslado)


      Clave | Descripción

      :-----:| -----------

      01 | Envío de mercancías facturadas con anterioridad

      02 | Reubicación de mercancías propias

      03 | Envío de mercancías objeto de contrato de consignación

      04 | Envío de mercancías para posterior enajenación

      05 | Envío de mercancías propiedad de terceros

      99 | Otros


      ### Incoterm (c_INCOTERM)


      Clave | Descripción

      :-----:| -----------

      CFR | Coste y flete (puerto de destino convenido).

      CIF | Coste, seguro y flete (puerto de destino convenido).

      CPT | Transporte pagado hasta (el lugar de destino convenido).

      CIP | Transporte y seguro pagados hasta (lugar de destino convenido).

      DAP | Entregada en lugar.

      DDP | Entregada derechos pagados (lugar de destino convenido).

      DPU | Entregada y descargada en lugar acordado.

      EXW | En fabrica (lugar convenido).

      FCA | Franco transportista (lugar designado).

      FAS | Franco al costado del buque (puerto de carga convenido).

      FOB | Franco a bordo (puerto de carga convenido).


      ### Unidad de Aduana (c_UnidadAduana)


      Clave | Descripción

      :-----:| -----------

      01 | KILO

      02 | GRAMO

      03 | METRO LINEAL

      04 | METRO CUADRADO

      05 | METRO CUBICO

      06 | PIEZA

      07 | CABEZA

      08 | LITRO

      09 | PAR

      10 | KILOWATT

      11 | MILLAR

      12 | JUEGO

      13 | KILOWATT/HORA

      14 | TONELADA

      15 | BARRIL

      16 | GRAMO NETO

      17 | DECENAS

      18 | CIENTOS

      19 | DOCENAS

      20 | CAJA

      21 | BOTELLA

      22 | CARAT

      99 | SERVICIO
  - name: customer_model
    x-displayName: Objeto Customer
    description: |
      <SchemaDefinition schemaRef="#/components/schemas/Customer" />
  - name: product_model
    x-displayName: Objeto Product
    description: |
      <SchemaDefinition schemaRef="#/components/schemas/Product" />
  - name: invoice_model
    x-displayName: Objeto Invoice
    description: |
      <SchemaDefinition schemaRef="#/components/schemas/Invoice" />
  - name: receipt_model
    x-displayName: Objeto Receipt
    description: |
      <SchemaDefinition schemaRef="#/components/schemas/Receipt" />
  - name: retention_model
    x-displayName: Objeto Retention
    description: |
      <SchemaDefinition schemaRef="#/components/schemas/Retention" />
  - name: organization_model
    x-displayName: Objeto Organización
    description: |
      <SchemaDefinition schemaRef="#/components/schemas/Organization" />
x-tagGroups:
  - name: Recursos
    tags:
      - customer
      - product
      - invoice
      - receipt
      - retention
      - organization
      - organization_access
  - name: Herramientas
    tags:
      - tools
      - sat_keys
      - carta_porte_keys
      - comercio_exterior_keys
  - name: Webhooks
    tags:
      - events
      - webhooks
  - name: Modelos
    tags:
      - customer_model
      - product_model
      - invoice_model
      - receipt_model
      - retention_model
      - organization_model
paths:
  /catalogs/cartaporte/3.1/air-transport-codes:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar códigos de transporte aéreo
      description: >
        Devuelve entradas del catálogo de aerolíneas que coinciden con la
        consulta. Usado para el complemento Carta Porte.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/air-transport-codes"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=AMX" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchAirTransportCodes({ q: 'AMX',
            page: 0, limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchAirTransportCodes(
                  Map.of(
                      "q", "llantas",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchAirTransportCodes([
              "q" => "AMX",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchAirTransportCodes(new
            Dictionary<string, object>

            {
              ["q"] = "AMX",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key`, `airline_name` o `icao_designator`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/comercioexterior/2.0/tariff-fractions:
    get:
      tags:
        - comercio_exterior_keys
      summary: Buscar fracciones arancelarias
      description: Devuelve fracciones arancelarias que coinciden con la consulta.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/comercioexterior/2.0/tariff-fractions"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=0101" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.comercioExteriorCatalogs.searchTariffFractions({ q:
            '0101', page: 0, limit: 10 })
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var result =
            facturapi.comercioExteriorCatalogs().searchTariffFractions(
                  Map.of(
                      "q", "0101",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $result =
            $facturapi->ComercioExteriorCatalogs->searchTariffFractions([
              "q" => "0101",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.ComercioExteriorCatalog.SearchTariffFractions(new
            Dictionary<string, object>

            {
              ["q"] = "0101",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key` o `description`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/transport-configs:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar configuraciones de autotransporte
      description: Devuelve configuraciones de transporte (p. ej., camión/semirremolque).
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/transport-configs"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=llantas" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchTransportConfigs({ q: 'CC', page:
            0, limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchTransportConfigs(
                  Map.of(
                      "q", "llantas",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchTransportConfigs([
              "q" => "llantas",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchTransportConfigs(new
            Dictionary<string, object>

            {
              ["q"] = "llantas",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key` o `description`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/rights-of-passage:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar derechos de paso
      description: Devuelve derechos de paso ferroviarios que coinciden con la consulta.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/rights-of-passage"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=CDP001" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchRightsOfPassage({ q: 'CDP001',
            page: 0, limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchRightsOfPassage(
                  Map.of(
                      "q", "CDP001",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchRightsOfPassage([
              "q" => "CDP001",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchRightsOfPassage(new
            Dictionary<string, object>

            {
              ["q"] = "CDP001",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key`, `right_of_passage` o `concessionaire`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/customs-documents:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar documentos aduaneros
      description: Devuelve tipos de documentos aduaneros.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/customs-documents"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=PEDIMENTO" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchCustomsDocuments({ q:
            'PEDIMENTO', page: 0, limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchCustomsDocuments(
                  Map.of(
                      "q", "AMX",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchCustomsDocuments([
              "q" => "PEDIMENTO",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchCustomsDocuments(new
            Dictionary<string, object>

            {
              ["q"] = "PEDIMENTO",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key` o `description`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/packaging-types:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar tipos de empaque
      description: Devuelve tipos de empaque para mercancías.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/packaging-types"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=CAJA" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchPackagingTypes({ q: 'CAJA', page:
            0, limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchPackagingTypes(
                  Map.of(
                      "q", "AMX",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchPackagingTypes([
              "q" => "CAJA",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchPackagingTypes(new
            Dictionary<string, object>

            {
              ["q"] = "CAJA",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key` o `description`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/trailer-types:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar tipos de remolque
      description: Devuelve tipos de remolque/semirremolque.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/trailer-types"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=CTR001" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchTrailerTypes({ q: 'CTR001', page:
            0, limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchTrailerTypes(
                  Map.of(
                      "q", "AMX",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchTrailerTypes([
              "q" => "CTR001",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchTrailerTypes(new
            Dictionary<string, object>

            {
              ["q"] = "CTR001",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key` o `description`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/hazardous-materials:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar materiales peligrosos
      description: Devuelve entradas del catálogo de materiales peligrosos.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/hazardous-materials"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=solido" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchHazardousMaterials({ q: 'solido',
            page: 0, limit: 10 })
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var result =
            facturapi.cartaPorteCatalogs().searchHazardousMaterials(
                  Map.of(
                      "q", "AMX",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchHazardousMaterials([
              "q" => "solido",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchHazardousMaterials(new
            Dictionary<string, object>

            {
              ["q"] = "solido",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key`, `description` o `class_division`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/naval-authorizations:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar autorizaciones navales
      description: Devuelve códigos de autorización naval (solo `key`).
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/naval-authorizations"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=SCT418/069/2018" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchNavalAuthorizations({ q:
            'SCT418/069/2018', page: 0, limit: 10 })
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var result =
            facturapi.cartaPorteCatalogs().searchNavalAuthorizations(
                  Map.of(
                      "q", "AMX",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $result =
            $facturapi->CartaPorteCatalogs->searchNavalAuthorizations([
              "q" => "SCT418/069/2018",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchNavalAuthorizations(new
            Dictionary<string, object>

            {
              ["q"] = "SCT418/069/2018",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                type: object
                properties:
                  page:
                    type: integer
                  total_pages:
                    type: integer
                  total_results:
                    type: integer
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        key:
                          type: string
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/port-stations:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar estaciones/puertos
      description: Devuelve entradas de estaciones aéreas/marítimas/terrestres.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/port-stations"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=MEX" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchPortStations({ q: 'MEX', page: 0,
            limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchPortStations(
                  Map.of(
                      "q", "AMX",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchPortStations([
              "q" => "MEX",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchPortStations(new
            Dictionary<string, object>

            {
              ["q"] = "MEX",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key`, `description` o `iata_designator`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /catalogs/cartaporte/3.1/marine-containers:
    get:
      tags:
        - carta_porte_keys
      summary: Buscar contenedores marítimos
      description: Devuelve tipos de contenedores marítimos.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/catalogs/cartaporte/3.1/marine-containers"
            \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=FERRI" \
              -d "page=0" \
              -d "limit=10"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.cartaPorteCatalogs.searchMarineContainers({ q: 'FERRI',
            page: 0, limit: 10 })
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.cartaPorteCatalogs().searchMarineContainers(
                  Map.of(
                      "q", "AMX",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $result = $facturapi->CartaPorteCatalogs->searchMarineContainers([
              "q" => "FERRI",
              "page" => 0,
              "limit" => 10
            ]);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.CartaporteCatalog.SearchMarineContainers(new
            Dictionary<string, object>

            {
              ["q"] = "FERRI",
              ["page"] = 0,
              ["limit"] = 10
            });
      parameters:
        - in: query
          name: q
          schema:
            type: string
          required: true
          description: Prefijo para buscar en `key` o `description`.
        - in: query
          name: page
          schema:
            type: integer
            minimum: 0
        - in: query
          name: limit
          schema:
            type: integer
            minimum: 1
      responses:
        '200':
          description: Búsqueda exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchKeyDescriptionResult'
        '400':
          description: Error en parámetros de la petición
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '401':
          description: Error de autenticación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '404':
          description: No se encontró el recurso especificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          description: Error inesperado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorMessage'
  /customers:
    post:
      operationId: createCustomer
      tags:
        - customer
      summary: Crear cliente
      description: >
        Registra un nuevo cliente en Facturapi.


        Esta llamada valida que los datos fiscales coincidan con

        los registros del SAT para ese RFC, de lo contrario, la llamada

        devolverá un error indicando el problema.


        Una vez creado el cliente y obtenido un objeto de respuesta,

        te recomendamos guardar el ID en tu base de datos junto a la información

        de tu cliente. Posteriormente, puedes llamar al encpoint de Crear
        Factura

        pasando el ID del cliente en lugar de repetir la información.


        Por último, ten en cuenta que los clientes que crees en ambiente _Test_
        **no se

        comparten** con el ambiente _Live_.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/customers \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "legal_name": "Dunder Mifflin",
                    "email": "email@example.com",
                    "tax_id": "ABC101010111",
                    "tax_system": "601",
                    "address": {
                      "zip": "01234"
                    }
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const customer = await facturapi.customers.create({
              legal_name: 'Dunder Mifflin',
              email: 'email@example.com',
              tax_id: 'ABC101010111',
              tax_system: '601',
              address: {
                zip: '01234'
              }
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await facturapi.Customer.CreateAsync(new
            Dictionary<string, object>

            {
              ["legal_name"] = "Dunder Mifflin",
              ["email"] = "email@example.com",
              ["tax_id"] = "ABC101010111",
              ["tax_system"] = "601",
              ["address"] = new Dictionary<string, object>
              {
                ["zip"] = "01234"
              }
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var customer = facturapi.customers().create(
                Map.of(
                    "legal_name", "Mi Empresa SA de CV",
                    "tax_id", "XAXX010101000",
                    "tax_system", "601",
                    "email", "cliente@example.com"
                ),
                null
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $customer = $facturapi->Customers->create([
              "email" => "email@example.com",
              "legal_name" => "Dunder Mifflin",
              "tax_id" => "ABC101010111",
              "tax_system" => "601",
              "address" => [
                "zip" => "01234"
              ]
            ]);
      requestBody:
        $ref: '#/components/requestBodies/CustomerCreate'
      parameters:
        - in: query
          name: createEditLink
          schema:
            type: boolean
          required: false
          description: >
            Si pasas el valor `true`, se generará un enlace para que el cliente
            pueda editar

            su información fiscal. Este enlace estará disponible en el campo
            "edit_link", será

            válido por 7 días y sólo se podrá usar una vez.

            Además, pasar el valor `true` desactivará la validación de
            información fiscal con el SAT,

            permitiendo crear clientes con información incompleta.
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Un objeto `Customer` con la misma información ya existía
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Customer'
        '201':
          description: Nuevo objeto `Customer` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Customer'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listCustomers
      tags:
        - customer
      summary: Listar clientes
      description: >-
        Regresa una lista paginada de todos los clientes de una organización o
        realiza una búsqueda de acuerdo a parámetros
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/customers \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -G \
              -d 'q=Dunder' \
              -d 'date[gt]=2021-07-14T06:00:00.000Z' \
              -d 'date[lt]=2021-08-14T06:00:00.000Z' \
              -d 'page=1'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const searchResult = await facturapi.customers.list({
              q: 'Dunder',
              date: {
                gt: new Date('2021-07-14T06:00:00.000Z'),
                lt: new Date('2021-08-14T06:00:00.000Z')
              },
              page: 1
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var searchResult = await facturapi.Customer.ListAsync(new
            Dictionary<string, object>

            {
              ["q"] = "Dunder",
              ["date"] = new Dictionary<string, object>
                {
                  ["gt"] = new DateTime("2021-07-14T06:00:00.000Z"),
                  ["lt"] = new DateTime("2021-08-14T06:00:00.000Z")
                },
              ["page"] = 1
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var searchResult = facturapi.customers().list(
                  Map.of(
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $searchResult = $facturapi->Customers->all([
              "q" => "Dunder",
              "date" => [
                "gt" => new DateTime("2021-07-14T06:00:00.000Z"),
                "lt" => new DateTime("2021-08-14T06:00:00.000Z")
              ],
              "page" => 1
            ]);
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: >-
            Consulta. Texto a buscar en `legal_name` (nombre fiscal) o en
            `tax_id` (RFC).
        - $ref: '#/components/parameters/SearchDate'
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CustomerSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /customers/{customer_id}:
    get:
      operationId: getCustomer
      tags:
        - customer
      summary: Obtener cliente por ID
      description: Regresa el objeto 'Customer' relacionado al `id` especificado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl https://www.facturapi.io/v2/customers/590ce6c56d04f840aa8438af
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const customer = await
            facturapi.customers.retrieve('590ce6c56d04f840aa8438af');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await
            facturapi.Customer.RetrieveAsync("590ce6c56d04f840aa8438af");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var customer = facturapi.customers().retrieve(
                  "cus_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $customer = $facturapi->Customers->retrieve(
            "5a3ee743f508333611ad6b3c" );
      parameters:
        - in: path
          name: customer_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Customer`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Customer'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: editCustomer
      tags:
        - customer
      summary: Editar cliente
      description: >-
        Actualiza la información de un cliente existente, asignando los valores
        de los parámetros enviados. Los parámetros que no se envíen en la
        petición no se modificarán.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl https://www.facturapi.io/v2/customers/590ce6c56d04f840aa8438af
            \
              -X PUT \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "email": "jdoe@example.com",
                    "address": {
                      "street": "Santa Monica Ave."
                    }
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const customer = await facturapi.customers.update(
              '590ce6c56d04f840aa8438af',
              {
                email: 'jdoe@example.com',
                address: {
                  street: 'Santa Monica Ave.'
                }
              }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
            var customer = await facturapi.Customer.UpdateAsync(
              "590ce6c56d04f840aa8438af",
              new Dictionary<string, object>
              {
                ["email"] = "jdoe@example.com",
                ["address"] = new Dictionary<string, object>
                {
                  ["street"] = "Santa Monica Ave."
                }
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var customer = facturapi.customers().update(
                "cus_123",
                Map.of(
                    "legal_name", "Mi Empresa SA de CV",
                    "email", "cliente@example.com"
                ),
                null
            );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $customer =
            $facturapi->Customers->update("590ce6c56d04f840aa8438af", [
              "email" => "jdoe@example.com",
              "legal_name" => "Dunder Mifflin",
              "address" => [
                "street" => "Santa Monica Ave."
              ]
            ]);
      parameters:
        - in: path
          name: customer_id
          schema:
            type: string
          required: true
          description: ID del objeto a editar
        - in: query
          name: createEditLink
          schema:
            type: boolean
          required: false
          description: >
            Si pasas el valor `true`, se generará un enlace para que el cliente
            pueda editar

            su información fiscal. Este enlace estará disponible en el campo
            "edit_link", será

            válido por 7 días y sólo se podrá usar una vez. Pasar el valor
            `true` al editar

            **no** desactivará la validación de información fiscal con el SAT.
      requestBody:
        $ref: '#/components/requestBodies/CustomerEdit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Customer` editado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Customer'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: deleteCustomer
      tags:
        - customer
      summary: Eliminar cliente
      description: >-
        Elimina el cliente de tu organización. Las facturas asociadas al cliente
        **no** se eliminarán.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl https://www.facturapi.io/v2/customers/590ce6c56d04f840aa8438af
            \
              -X DELETE \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const removedCustomer = await
            facturapi.customers.del('590ce6c56d04f840aa8438af');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await
            facturapi.Customer.DeleteAsync("590ce6c56d04f840aa8438af");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var customer = facturapi.customers().delete(
                  "cus_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $facturapi->Customers->delete( "5a3fefd9f508333611ad6b43" );
      parameters:
        - in: path
          name: customer_id
          schema:
            type: string
          required: true
          description: ID del objeto a eliminar
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Customer` eliminado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Customer'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /customers/{customer_id}/email-edit-link:
    post:
      operationId: sendEditLinkByEmail
      tags:
        - customer
      summary: Enviar enlace de edición por correo electrónico
      description: >
        Envía un enlace para que el cliente pueda editar su información fiscal.


        Este enlace estará disponible en el campo `edit_link`, será válido por 7
        días y sólo se podrá usar una vez.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/customers/590ce6c56d04f840aa8438af/email-edit-link
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X POST
              -d '{
                "email": "email@example.com"
              }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            await
            facturapi.customers.sendEditLinkByEmail('67bf1239b15b44fb9269e6a8',
            {
              email: 'email@example.com' // Opcional, si no se proporciona, se usará el correo electrónico del cliente
            });
        - lang: csharp
          label: C#
          source: >
            await
            facturapi.Customer.SendEditLinkByEmailAsync("67bf1239b15b44fb9269e6a8",
            new Dictionary<string, object>

            {
              ["email"] = "email@example.com" // Opcional, si no se proporciona, se usará el correo electrónico del cliente
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.customers().sendEditLinkByEmail(
                  "cus_123",
                  "cliente@example.com"
                );
        - lang: PHP
          label: PHP
          source: >
            $customer =
            $facturapi->Customers->sendEditLinkByEmail("67bf1239b15b44fb9269e6a8",
            [
              "email" => "email@example.com" // Opcional, si no se proporciona, se usará el correo electrónico del cliente
            ]);
      parameters:
        - in: path
          name: customer_id
          schema:
            type: string
          required: true
          description: ID del objeto `Customer` a editar
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                email:
                  type: string
                  description: >-
                    Correo electrónico del cliente. Si no se proporciona, se
                    usará el correo electrónico del cliente.
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Enlace de edición enviado correctamente
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:
                    type: boolean
                    description: Indica si el enlace se envió correctamente
                    example: true
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /customers/{customer_id}/tax-info-validation:
    get:
      operationId: validateCustomerTaxInfo
      tags:
        - customer
      summary: Validar información fiscal
      description: >
        Valida que la información fiscal del cliente coincida con los registros
        del SAT.


        Su función principal es validar que los datos del cliente registraado
        siguen cumpliendo la validación del SAT.


        :::tip
          Las operaciones de crear cliente, editar cliente y crear factura ya realizan una
          validación de la información del cliente, por lo que **no** es necesario llamar a este endpoint
          antes de realizar dichas operaciones.
        :::
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/customers/590ce6c56d04f840aa8438af/tax-info-validation
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const customer = await
            facturapi.customers.validateTaxInfo('590ce6c56d04f840aa8438af');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await
            facturapi.Customer.ValidateTaxInfoAsync("590ce6c56d04f840aa8438af");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var validation = facturapi.customers().validateTaxInfo(
                  "cus_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $customer = $facturapi->Customers->validateTaxInfo(
            "5a3ee743f508333611ad6b3c" );
      parameters:
        - in: path
          name: customer_id
          schema:
            type: string
          required: true
          description: ID del objeto `Customer` a validar
      security:
        - SecretLiveKey: []
      responses:
        '200':
          description: Resultado de la validación
          content:
            application/json:
              schema:
                type: object
                properties:
                  is_valid:
                    type: boolean
                    description: >-
                      Indica si la información fiscal del cliente coincide con
                      los registros del SAT
                    example: true
                  errors:
                    type: array
                    description: Lista de errores encontrados
                    items:
                      type: object
                      properties:
                        path:
                          type: string
                          description: >-
                            Nombre del campo que no coincide con los registros
                            del SAT
                          example: tax_system
                        message:
                          type: string
                          description: Mensaje de error
                          example: >-
                            El RégimenFiscal no coincide con el registrado para
                            el RFC en la lista de contribuyentes obligados del
                            SAT.
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /products:
    post:
      operationId: createProduct
      tags:
        - product
      summary: Crear producto
      description: >
        Registra un nuevo producto o servicio en tu catálogo de Facturapi.


        Puedes usar el ID del producto para crear facturas sin tener que enviar
        todos los datos del producto cada vez.


        Te en cuenta que los productos que crees en ambiente _Test_ **no se

        comparten** con el ambiente _Live_.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/products \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "description": "Ukelele",
                    "product_key": "60131324",
                    "price": 345.60,
                    "sku": "ABC1234"
                }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const product = await facturapi.products.create({
              description: 'Ukelele',
              product_key: '60131324',
              price: 345.60,
              sku: 'ABC1234'
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var product = await facturapi.Product.CreateAsync(new
            Dictionary<string, object>

            {
              ["description"] = "Ukelele",
              ["product_key"] = "60131324",
              ["price"] = 345.60,
              ["sku"] = "ABC1234"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var product = facturapi.products().create(
                Map.of(
                    "description", "Producto de ejemplo",
                    "product_key", "01010101",
                    "price", 100.0,
                    "tax_included", false
                  ));
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $product = $facturapi->Products->create([
              "description" => "Ukelele",
              "product_key" => "60131324",
              "price" => 345.60,
              "sku" => "ABC1234"
            ]);
      requestBody:
        $ref: '#/components/requestBodies/ProductCreate'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Nuevo objeto `Product` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listProducts
      tags:
        - product
      summary: Listar productos
      description: >-
        Regresa una lista paginada de todos los productos de una organización o
        realiza una búsqueda de acuerdo a parámetros
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/products \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -G \
              -d 'q=ukelele' \
              -d 'page=1'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const searchResult = await facturapi.products.list({
              q: 'ukelele',
              page: 1
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var searchResult = await facturapi.Product.ListAsync(new
            Dictionary<string, object>

            {
              ["q"] = "ukelele",
              ["date"] = new Dictionary<string, object>
                {
                  ["gt"] = new DateTime("2021-07-14T06:00:00.000Z"),
                  ["lt"] = new DateTime("2021-08-14T06:00:00.000Z")
                },
              ["page"] = 1
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var searchResult = facturapi.products().list(
                  Map.of(
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $searchResult = $facturapi->Products->all([
              "q" => "ukelele",
              "page" => 1
            ]);
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: Consulta. Texto a buscar en la descripción del producto o SKU.
        - in: query
          name: sku
          schema:
            type: string
          description: SKU del producto.
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProductSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /products/{product_id}:
    get:
      operationId: getProduct
      tags:
        - product
      summary: Obtener producto por ID
      description: Regresa el objeto `Product` relacionado al `id` especificado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/products/590e22c26d04f840aa8438b2 \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const product = await
            facturapi.products.retrieve('590e22c26d04f840aa8438b2');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var product = await
            facturapi.Product.RetrieveAsync("590e22c26d04f840aa8438b2");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var product = facturapi.products().retrieve(
                  "prod_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $product = $facturapi->Product->retrieve( "590e22c26d04f840aa8438b2"
            );
      parameters:
        - in: path
          name: product_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Product`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: editProduct
      tags:
        - product
      summary: Editar producto
      description: >-
        Actualiza la información de un producto existente, asignando los valores
        de los parámetros enviados. Los parámetros que no se envíen en la
        petición no se modificarán.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/products/590e22c26d04f840aa8438b2 \
              -X PUT \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "price": 456.70
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const product = await facturapi.products.update(
              '590e22c26d04f840aa8438b2',
              {
                email: 'jdoe@example.com',
                address: {
                  street: 'Santa Monica Ave.'
                }
              }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
            var product = await facturapi.Product.UpdateAsync(
              "590e22c26d04f840aa8438b2",
              new Dictionary<string, object>
              {
                ["price"] = 456.70
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var product = facturapi.products().update("prod_123", Map.of(
                    "description", "Producto actualizado",
                    "price", 120.0
                  ));
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $product = $facturapi->Products->update("590e22c26d04f840aa8438b2",
            [
              "price" => 456.70
            ]);
      parameters:
        - in: path
          name: product_id
          schema:
            type: string
          required: true
          description: ID del objeto a editar
      requestBody:
        $ref: '#/components/requestBodies/ProductEdit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Product` editado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: deleteProduct
      tags:
        - product
      summary: Eliminar producto
      description: >-
        Elimina el producto de tu organización. Las facturas asociadas al
        producto **no** se eliminarán.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/products/590e22c26d04f840aa8438b2 \
              -X DELETE \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const removedProduct = await
            facturapi.products.del('590e22c26d04f840aa8438b2');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var product = await
            facturapi.Product.DeleteAsync("590e22c26d04f840aa8438b2");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var product = facturapi.products().delete(
                  "prod_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $facturapi->Products->delete( "590e22c26d04f840aa8438b2" );
      parameters:
        - in: path
          name: product_id
          schema:
            type: string
          required: true
          description: ID del objeto a eliminar
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Product` eliminado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices:
    post:
      operationId: createInvoice
      tags:
        - invoice
      summary: Crear factura (CFDI 4.0)
      description: >
        Crea una nueva Factura. Si la factura es creada en ambiente Live, ésta
        será **timbrada y enviada al SAT**.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/invoices \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "customer": {
                  "legal_name": "Dunder Mifflin",
                  "email": "email@example.com",
                  "tax_id": "ABC101010111",
                  "tax_system": "601",
                  "address": {
                    "zip": "85900"
                  }
                },
                "items": [{
                  "quantity": 2,
                  "product": {
                    "description": "Ukelele",
                    "product_key": "60131324",
                    "price": 345.60
                  }
                }],
                "payment_form": "06",
                "folio_number": 914,
                "series": "F"
              }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const invoice = await facturapi.invoices.create({
              customer: {
                legal_name: 'Dunder Mifflin',
                email: 'email@example.com',
                tax_id: 'ABC101010111',
                tax_system: '601',
                address: {
                  zip: '85900'
                }
              },
              items: [{
                quantity: 2,
                product: {
                  description: 'Ukelele',
                  product_key: '60131324',
                  price: 345.60
                }
              }],
              payment_form: Facturapi.PaymentForm.DINERO_ELECTRONICO,
              folio_number: 914,
              series: 'F'
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var invoice = await facturapi.Invoice.CreateAsync(new
            Dictionary<string, object>

            {
              ["customer"] = new Dictionary<string, object>
              {
                ["legal_name"] = "Dunder Mifflin",
                ["email"] = "email@example.com",
                ["tax_id"] = "ABC101010111",
                ["tax_system"] = "601",
                ["address"] = new Dictionary<string, object>
                {
                  ["zip"] = "85900"
                }
              },
              ["items"] = new Dictionary<string, object>[]
              {
                new Dictionary<string, object>
                {
                  ["product"] = new Dictionary<string, object>
                  {
                    ["description"] = "Ukelele",
                    ["product_key"] = "60131324",
                    ["price"] = 345.60
                  }
                }
              },
              ["payment_form"] = Facturapi.PaymentForm.DINERO_ELECTRONICO,
              ["folio_number"] = 914,
              ["series"] = "F"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.invoices().create(
                Map.of(
                    "customer", "cus_123",
                    "items", List.of(
                        Map.of(
                            "quantity", 1,
                            "product", "prod_123"
                        )
                    )
                ),
                null
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $invoice = $facturapi->Invoices->create([
              "customer" => [
                "legal_name" => "Dunder Mifflin",
                "email" => "email@example.com",
                "tax_id" => "ABC101010111",
                "tax_system" => "601",
                "address" => [
                  "zip" => "85900"
                ]
              ],
              "items" => [
                [
                  "quantity" => 2,
                  "product" => [
                    "description" => "Ukelele",
                    "product_key" => "60131324",
                    "price" => 420.69,
                    "sku" => "ABC4567"
                  ]
                ] // Add as many products as you want to include in your invoice
              ],
              "payment_form" => \Facturapi\PaymentForm::EFECTIVO,
              "folio_number" => 581,
              "series" => "F"
            ]);
      requestBody:
        $ref: '#/components/requestBodies/InvoiceCreate'
      parameters:
        - in: query
          name: async
          schema:
            type: boolean
          required: false
          description: >
            Útil para facturas de gran tamaño. Si se envía `false` o no se
            envía, la llamada esperará a que el SAT responda timbrando la
            factura.

            Si se envía `true`, la llamada regresará inmediatamente con el
            objeto `invoice` en status `pending`, y podrá consultarse su cambio
            de status

            a `valid`` en un momento posterior.
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Nuevo objeto `Invoice` creado
          content:
            application/json:
              schema:
                type: object
                discriminator:
                  propertyName: status
                  mapping:
                    pending: '#/components/schemas/Invoice'
                    draft: '#/components/schemas/InvoiceDraft'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listInvoices
      tags:
        - invoice
      summary: Listar facturas
      description: >-
        Regresa una lista paginada de todas las facturas de una organización o
        realiza una búsqueda de acuerdo a parámetros
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            # Todas las facturas de la organización
            curl "https://www.facturapi.io/v2/invoices" \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY"

            # Todas las facturas emitidas para cierto cliente
            curl "https://www.facturapi.io/v2/invoices" \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "customer=58e93bd8e86eb318b0197456"

            # Página 3 de los resultados de búsqueda de texto libre
            # de facturas emitidas por cierto cliente entre 2017 y 2019
            curl "https://www.facturapi.io/v2/invoices" \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=Aspiradora+Robot&customer=58e93bd8e86eb318b0197456&date[gte]=2017-01-01T00:00:00.000Z&date[lt]=2020-01-01T00:00:00.000Z&page=3&limit=10"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            // Todas las facturas de la organización
            const invoiceSearch = await facturapi.invoices.list();

            // Todas las facturas emitidas para cierto cliente
            const invoiceSearch = await facturapi.invoices.list({
              customer: '590ce6c56d04f840aa8438af'
            });

            // Página 3 de los resultados de búsqueda de texto libre
            // de facturas emitidas por cierto cliente entre 2017 y 2019
            const invoiceSearch = await facturapi.invoices.list({
              q: 'Aspiradora Robot',
              customer: '590ce6c56d04f840aa8438af',
              date: {
                gte: new Date('2017-01-01T00:00:00.000Z'),
                lt: new Date('2020-01-01T00:00:00.000Z')
              },
              page: 3,
              limit: 10,
            });
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            // Todas las facturas de la organización
            var searchResult = await facturapi.Invoice.ListAsync();

            // Todas las facturas emitidas para cierto cliente
            var searchResult = await facturapi.Invoice.ListAsync(
              new Dictionary<string, object>
              {
                ["customer"] = "590ce6c56d04f840aa8438af"
              }
            );

            // Página 3 de los resultados de búsqueda de texto libre
            // de facturas emitidas por cierto cliente entre 2017 y 2019
            var searchResult = await facturapi.Invoice.ListAsync(
              new Dictionary<string, object>
              {
                ["q"] = "Aspiradora Robot",
                ["customer"] = "590ce6c56d04f840aa8438af",  
                ["date"] = new Dictionary<string, object>
                  {
                    ["gte"] = new DateTime("2017-01-01T00:00:00.000Z"),
                    ["lt"] = new DateTime("2020-01-01T00:00:00.000Z")
                  },
                ["page"] = 3,
                ["limit"] = 10,
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var searchResult = facturapi.invoices().list(
                  Map.of(
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            // Todas las facturas de la organización
            $invoices = $facturapi->Invoices->all();

            // Todas las facturas emitidas para cierto cliente
            $invoices = $facturapi->Invoices->all([
              customer => "590ce6c56d04f840aa8438af"
            ]);

            // Página 3 de los resultados de búsqueda de texto libre
            // de facturas emitidas por cierto cliente entre 2017 y 2019
            $invoices = $facturapi->Invoices->all([
              q => "Aspiradora Robot",
              customer => "590ce6c56d04f840aa8438af"
              date => [
                gte => new DateTime("2017-01-01T00:00:00.000Z"),
                lt => new DateTime("2020-01-01T00:00:00.000Z")
              ],
              page => 3,
              limit => 10,
            ]);
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: >
            Consulta. Texto a buscar en la factura.


            La búsqueda se realizará por coincidencias **parciales** en los
            campos:


            - `items[].product.description`

            - `customer.legal_name`


            Y por coincidencias **exactas** en los campos:


            - `id`

            - `uuid`

            - `customer.tax_id`

            - `folio_number`

            - `total`
        - in: query
          name: customer
          schema:
            type: string
          description: >-
            Identificador del cliente. Útil para obtener las facturas emitidas a
            un sólo cliente.
        - in: query
          name: type
          schema:
            type: string
            enum:
              - I
              - E
              - P
              - 'N'
              - T
          description: >-
            Tipo de factura. Búsqueda por tipo de factura con las claves
            exactas.
        - in: query
          name: payment_method
          schema:
            type: string
            enum:
              - PUE
              - PPD
          description: Método de pago. Búsqueda exacta por método de pago.
        - in: query
          name: folio_number
          schema:
            type: integer
            minimum: 1
          description: Filtrar por folio de la factura. Coincidencia exacta.
        - in: query
          name: series
          schema:
            type: string
            maxLength: 25
          description: Filtrar por serie de la factura. Coincidencia exacta.
        - in: query
          name: external_id
          schema:
            type: string
            maxLength: 100
          description: Filtrar por identificador externo. Coincidencia exacta.
        - in: query
          name: issuer_type
          schema:
            $ref: '#/components/schemas/IssuingType'
          description: Filtrar por tipo de emisión.
        - in: query
          name: cancellation_status
          schema:
            type: array
            items:
              $ref: '#/components/schemas/CancellationStatus'
          description: Filtrar por uno o más estados de cancelación.
        - in: query
          name: uuid
          schema:
            type: string
            format: uuid
          description: Filtrar por el UUID del CFDI. Coincidencia exacta.
        - in: query
          name: payment_status
          schema:
            type: string
            enum:
              - paid
              - unpaid
          description: Filtrar por estado de pago. Coincidencia exacta.
        - $ref: '#/components/parameters/SearchDate'
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvoiceSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/preview/pdf:
    post:
      operationId: previewInvoicePdf
      tags:
        - invoice
      summary: Vista previa de factura en PDF
      description: >-
        Genera una vista previa en PDF de una factura sin timbrar ni guardar en
        la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/invoices/preview/pdf \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "customer": {
                  "legal_name": "Dunder Mifflin",
                  "email": "email@example.com",
                  "tax_id": "ABC101010111",
                  "tax_system": "601",
                  "address": {
                    "zip": "85900"
                  }
                },
                "items": [{
                  "quantity": 2,
                  "product": {
                    "description": "Ukelele",
                    "product_key": "60131324",
                    "price": 345.60
                  }
                }],
                "payment_form": "06",
                "folio_number": 914,
                "series": "F"
              }'
        - lang: JavaScript
          label: Node.js
          source: |
            const Facturapi = require('facturapi');
            const facturapi = new Facturapi('sk_test_API_KEY');
            const pdfStream = await facturapi.invoices.previewPdf({
              customer: {
                legal_name: 'Dunder Mifflin',
                email: 'email@example.com',
                tax_id: 'ABC101010111',
                tax_system: '601',
                address: {
                  zip: '85900'
                }
              },
              items: [{
                quantity: 2,
                product: {
                  description: 'Ukelele',
                  product_key: '60131324',
                  price: 345.60
                }
              }],
              payment_form: Facturapi.PaymentForm.DINERO_ELECTRONICO,
              folio_number: 914,
              series: 'F'
            });
            // Save PDF stream to a file
            const fs = require('fs');
            const file = fs.createWriteStream('invoice_preview.pdf');
            pdfStream.pipe(file);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var pdfStream = await facturapi.Invoice.PreviewPdfAsync(new
            Dictionary<string, object>

            {
              ["customer"] = new Dictionary<string, object>
              {
                ["legal_name"] = "Dunder Mifflin",
                ["email"] = "email@example.com",
                ["tax_id"] = "ABC101010111",
                ["tax_system"] = "601",
                ["address"] = new Dictionary<string, object>
                {
                  ["zip"] = "85900"
                }
              },
              ["items"] = new Dictionary<string, object>[]
              {
                new Dictionary<string, object>
                {
                  ["product"] = new Dictionary<string, object>
                  {
                    ["description"] = "Ukelele",
                    ["product_key"] = "60131324",
                    ["price"] = 345.60
                  }
                }
              },
              ["payment_form"] = Facturapi.PaymentForm.DINERO_ELECTRONICO,
              ["folio_number"] = 914,
              ["series"] = "F"
            });

            // Save PDF stream to a file

            var file = new System.IO.FileStream("invoice_preview.pdf",
            System.IO.FileMode.Create, System.IO.FileAccess.Write);

            pdfStream.CopyTo(file);

            file.Close();
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var pdf = facturapi.invoices().previewPdf(
                Map.of(
                    "customer", "cus_123",
                    "items", List.of(
                        Map.of(
                            "quantity", 1,
                            "product", "prod_123"
                        )
                    )
                  ));
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $pdfBytes = $facturapi->Invoices->previewPdf([
              "customer" => [
                "legal_name" => "Dunder Mifflin",
                "email" => "email@example.com",
                "tax_id" => "ABC101010111",
                "tax_system" => "601",
                "address" => [
                  "zip" => "85900"
                ]
              ],
              "items" => [
                [
                  "quantity" => 2,
                  "product" => [
                    "description" => "Ukelele",
                    "product_key" => "60131324",
                    "price" => 345.60,
                    "sku" => "ABC4567"
                  ]
                ]
              ],
              "payment_form" => \Facturapi\PaymentForm::EFECTIVO,
              "folio_number" => 914,
              "series" => "F"
            ]);
      requestBody:
        $ref: '#/components/requestBodies/InvoiceCreate'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: El archivo PDF de la factura
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/{invoice_id}:
    get:
      operationId: getInvoice
      tags:
        - invoice
      summary: Obtener factura por ID
      description: Regresa el objeto 'Invoice' relacionado al `id` especificado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const invoice = await
            facturapi.invoices.retrieve('58e93bd8e86eb318b019743d');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var invoice = await
            facturapi.Invoice.RetrieveAsync("58e93bd8e86eb318b019743d");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.invoices().retrieve(
                  "inv_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $invoice = $facturapi->Invoices->retrieve(
            "58e93bd8e86eb318b019743d" );
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Invoice`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: updateDraftInvoice
      tags:
        - invoice
      summary: Editar borrador de factura
      description: |
        Actualiza la información de una factura con status `draft`, asignando
        los valores de los parámetros enviados. Los parámetros que no se envíen
        en la petición no se modificarán.

        En el objeto `invoice` de respuesta, Facturapi asignará automáticamente
        el campo `is_ready_to_stamp` con el valor `true` si la factura pasa la
        validación mínima requerida para ser timbrada; de lo contrario, el campo
        `is_ready_to_stamp` será `false`.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d \
              -X PUT \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "payment_form": "06"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const invoice = await facturapi.invoices.updateDraft(
              '58e93bd8e86eb318b019743d',
              {
                payment_form: Facturapi.PaymentForm.DINERO_ELECTRONICO
              }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new Facturapi("sk_test_API_KEY");
            var invoice = await facturapi.Invoice.UpdateDraftAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["payment_form"] = Facturapi.PaymentForm.DINERO_ELECTRONICO
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.invoices().updateDraft("inv_123", Map.of(
                    "items", List.of(
                        Map.of(
                            "quantity", 1,
                            "product", "prod_123"
                        )
                    )
                  ));
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $invoice =
            $facturapi->Invoices->updateDraft("58e93bd8e86eb318b019743d", [
              "payment_form" => \Facturapi\PaymentForm::EFECTIVO
            ]);
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID del objeto a editar
      requestBody:
        $ref: '#/components/requestBodies/InvoiceEdit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Invoice` editado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvoiceDraft'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: cancelInvoice
      tags:
        - invoice
      summary: Cancelar factura
      description: >
        Realiza una solicitud de cancelación de factura ante el SAT, soportando
        el esquema de cancelación 2022.


        Al usar este método pueden ocurrir 3 posibles resultados:


        - Que la llamada regrese un error con la explicación de por qué no se
        pudo cancelar.

        - Que la llamada sea satisfactoria y regrese un objeto `invoice` con la
        propiedad `status: "canceled"`.

        - Que la llamada sea satisfactoria, pero que la cancelación requiera de
        confirmación de parte de tu cliente, en cuyo caso se obtendrá como
        respuesta el objeto `invoice` con las propiedades `status: "valid"` y
        `cancellation_status: "pending"`.


        En el tercer escenario, el valor de `cancellation_status` será
        actualizado automáticamente por Facturapi cuando tu cliente acepte,
        rechace o deje expirar la solicitud, de tal manera que al consultar una
        factura (usando [Obtener Factura](#tag/invoice/operation/getInvoice)),
        la propiedad `cancellation_status` reflejará el estado más reciente de
        la soliitud.


        Consulta los valores posibles de `cancellation_status` más abajo.


        Después de la cancelación la factura ya no tendrá validez, el objeto
        cambiará su `status` a `"canceled"` y seguirá estando disponible para
        futuras consultas.


        Si el status de la factura es `draft`, este método la eliminará de la
        base de datos.


        Si el status de la factura es `canceled`, este método regresará un
        error.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d?motive=02
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X DELETE
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const invoice = await facturapi.invoices.cancel(
              '58e93bd8e86eb318b019743d',
              { motive: '02' }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
            var invoice = await facturapi.Invoice.CancelAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["motive"] = "02"
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.invoices().cancel(
                  "inv_123",
                  Map.of(
                      "motive", "02"
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $canceled_invoice = $facturapi->Invoices->cancel(
              "58e93bd8e86eb318b019743d",
              [
                "motive" => "02"
              ]
            );
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID de la factura a cancelar
        - in: query
          name: motive
          required: true
          schema:
            type: string
            enum:
              - '01'
              - '02'
              - '03'
              - '04'
          description: >
            Clave que representa el motivo de la cancelación de la factura.


            - `01`: **Comprobante emitido con errores con relación**. Cuando la
              factura contiene algún error en las cantidades, claves o cualquier otro dato y ya
              se ha emitido el comprobante que la sustituye, el cual deberá indicarse por medio
              del atributo `substitution`.
            - `02`: **Comprobante emitido con errores sin relación**. Cuando la
              factura contiene algún error en las cantidades, claves o cualquier otro dato y no
              se requiere relacionar con otra factura.
            - `03`: **No se llevó a cabo la operación**. Cuando la venta o
            transacción no se concretó.

            - `04`: **Operación nominativa relacionada en la factura global**.
            Cuando se requiere cancelar
              una factura al público en general porque el cliente solicita su comprobante.
        - in: query
          name: substitution
          required: false
          schema:
            type: string
          description: |
            ID de la factura que sustituye a la factura que se está cancelando.

            Puedes usar el ID de Facturapi o el folio fiscal (UUID).
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Solicitud de cancelación exitosa
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/{invoice_id}/copy:
    post:
      operationId: copyToDraftInvoice
      tags:
        - invoice
      summary: Copiar a borrador
      description: |
        Crea una copia en borrador de la factura especificada.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/copy \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X POST
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const invoice = await
            facturapi.invoices.copyToDraft('58e93bd8e86eb318b019743d');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var invoice = await
            facturapi.Invoice.CopyToDraftAsync("58e93bd8e86eb318b019743d");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var draft = facturapi.invoices().copyToDraft(
                  "inv_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $invoice =
            $facturapi->Invoices->copyToDraft("58e93bd8e86eb318b019743d");
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID de la factura a copiar
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Nuevo objeto `Invoice` con status `draft`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvoiceDraft'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/{invoice_id}/stamp:
    post:
      operationId: stampDraftInvoice
      tags:
        - invoice
      summary: Timbrar borrador de factura
      description: >
        Timbra una factura con status `draft` y la envía al SAT para su
        validación.


        Al usar este método, el valor del campo `is_ready_to_stamp` (asignado
        por Facturapi)

        deberá ser `true`. De otra forma, la llamada regresará un error.


        Este método no permite editar la factura, sólo timbrarla. Si necesitas
        editar información

        en la factura antes de timbrarla, usa el método [Editar Borrador de
        Factura](#tag/invoice/operation/editDraftInvoice).
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/stamp
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X POST
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const stampedInvoice = await
            facturapi.invoices.stampDraft('58e93bd8e86eb318b019743d');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var stampedInvoice = await
            facturapi.Invoice.StampDraftAsync("58e93bd8e86eb318b019743d");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.invoices().stampDraft(
                  "inv_123",
                  Map.of(
                  )
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $stamped_invoice =
            $facturapi->Invoices->stampDraft("58e93bd8e86eb318b019743d");
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID del objeto a timbrar
        - in: query
          name: async
          schema:
            type: boolean
          required: false
          description: >
            Útil para facturas de gran tamaño. Si se envía `false` o no se
            envía, la llamada esperará a que el SAT responda timbrando la
            factura.

            Si se envía `true`, la llamada regresará inmediatamente con el
            objeto `invoice` en status `pending`, y podrá consultarse su cambio
            de status

            a `valid`` en un momento posterior.
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Invoice` timbrado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/{invoice_id}/cancellation_receipt/{format}:
    get:
      operationId: downloadCancellationReceiptXml
      tags:
        - invoice
      summary: Descargar acuse de cancelación
      description: >-
        Descarga acuse de recibo de cancelación de una factura en un archivo xml
        o pdf.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            # Acuse de factura cancelada

            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/cancellation_receipt/{format}
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X GET
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            // Acuse de factura cancelada xml

            await
            facturapi.invoices.downloadCancellationReceiptXml('58e93bd8e86eb318b019743d');


            // Acuse de factura cancelada pdf

            await
            facturapi.invoices.downloadCancellationReceiptPdf('58e93bd8e86eb318b019743d');
        - lang: csharp
          label: C#
          source: >
            // Acuse de factura cancelada

            await
            facturapi.Invoice.DownloadCancellationReceiptXmlAsync("58e93bd8e86eb318b019743d");
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            byte[] cancellationReceiptXml =
            facturapi.invoices().downloadCancellationReceiptXml(
                  "58e93bd8e86eb318b019743d"
                );
            byte[] cancellationReceiptPdf =
            facturapi.invoices().downloadCancellationReceiptPdf(
                  "58e93bd8e86eb318b019743d"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");


            // Acuse de factura cancelada xml

            $facturapi->Invoices->downloadCancellationReceiptXml("58e93bd8e86eb318b019743d");


            // Acuse de factura cancelada pdf

            $facturapi->Invoices->downloadCancellationReceiptPdf("58e93bd8e86eb318b019743d");
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
        - in: path
          name: format
          schema:
            type: string
            enum:
              - xml
              - pdf
          required: true
          description: Formato del archivo de descarga
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Archivo del acuse de recibo de cancelación
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/{invoice_id}/{format}:
    get:
      operationId: downloadInvoice
      tags:
        - invoice
      summary: Descargar factura
      description: Descarga tu Factura en PDF, XML o ambos en un archivo comprimido ZIP.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            ## Descargar PDF y XML comprimidos en archivo ZIP

            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/zip \
              -H "Authorization: Bearer sk_test_API_KEY"

            ## Descargar sólo el PDF

            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/pdf \
              -H "Authorization: Bearer sk_test_API_KEY"

            ## Descargar sólo el XML

            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/xml \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import fs from 'fs';

            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            // Descargar PDF y XML comprimidos en archivo ZIP

            const zipStream = await
            facturapi.invoices.downloadZip('58e93bd8e86eb318b019743d');

            const zipFile = fs.createWriteStream('./factura.zip');

            zipStream.pipe(zipFile);


            // Descargar sólo el PDF

            const pdfStream = await
            facturapi.invoices.downloadPdf('58e93bd8e86eb318b019743d');

            const pdfFile = fs.createWriteStream('./factura.pdf');

            pdfStream.pipe(pdfFile);


            // Descargar sólo el XML

            const xmlStream = await
            facturapi.invoices.downloadXml('58e93bd8e86eb318b019743d');

            const xmlFile = fs.createWriteStream('./factura.xml');

            xmlStream.pipe(xmlFile);
        - lang: csharp
          label: C#
          source: >
            // Descargar PDF y XML comprimidos en archivo ZIP

            var zipStream = await
            facturapi.Invoice.DownloadZipAsync("58e93bd8e86eb318b019743d");

            // Descargar sólo el XML

            var xmlStream = await
            facturapi.Invoice.DownloadXmlAsync("58e93bd8e86eb318b019743d");

            // Descargar sólo el PDF

            var pdfStream = await
            facturapi.Invoice.DownloadPdfAsync("58e93bd8e86eb318b019743d");


            // Para guardar la descarga en un archivo

            var file = new
            System.IO.FileStream("C:\\route\\to\\save\\invoice.zip",
            FileMode.Create);

            zipStream.CopyTo(file);

            file.Close();
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.io.InputStream;

            import java.nio.file.Files;

            import java.nio.file.Path;

            import java.nio.file.StandardCopyOption;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            try (InputStream zipStream =
            facturapi.invoices().downloadZip("58e93bd8e86eb318b019743d")) {
              Files.copy(zipStream, Path.of("./factura.zip"), StandardCopyOption.REPLACE_EXISTING);
            }


            try (InputStream pdfStream =
            facturapi.invoices().downloadPdf("58e93bd8e86eb318b019743d")) {
              Files.copy(pdfStream, Path.of("./factura.pdf"), StandardCopyOption.REPLACE_EXISTING);
            }


            try (InputStream xmlStream =
            facturapi.invoices().downloadXml("58e93bd8e86eb318b019743d")) {
              Files.copy(xmlStream, Path.of("./factura.xml"), StandardCopyOption.REPLACE_EXISTING);
            }
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");


            // stream containing the PDF and XML as a ZIP file

            $zip =
            $facturapi->Invoices->downloadZip("58e93bd8e86eb318b019743d");

            // stream containing the PDF file

            $pdf =
            $facturapi->Invoices->downloadPdf("58e93bd8e86eb318b019743d"); 

            // stream containing the XML file

            $xml =
            $facturapi->Invoices->downloadXml("58e93bd8e86eb318b019743d");
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID del objeto a descargar
        - in: path
          name: format
          schema:
            type: string
            enum:
              - xml
              - pdf
              - zip
          required: true
          description: Formato del archivo de descarga
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Archivo del comprobante CFDI en el formato solicitado
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/{invoice_id}/email:
    post:
      operationId: sendInvoiceByEmail
      tags:
        - invoice
      summary: Enviar factura por correo electrónico
      description: >-
        Envía un correo electrónico a la dirección de tu cliente, con los
        archivos XML y PDF adjuntos al mensaje.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            # Enviar al correo del cliente

            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/email
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X POST

            # Enviar a otro correo

            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/email
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X POST \
              -H "Content-Type: application/json" \
              -d '{
                    "email": "another_email@example.com"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            // Enviar al correo del cliente
            await facturapi.invoices.sendByEmail('58e93bd8e86eb318b019743d');

            // Enviar a otro correo
            await facturapi.invoices.sendByEmail(
              '58e93bd8e86eb318b019743d',
              { email: 'otro@correo.com' }
            );

            // Enviar a más de un correo (máx. 10)
            await facturapi.invoices.sendByEmail(
              '58e93bd8e86eb318b019743d',
              { 
                email: [
                  'primer@correo.com',
                  'segundo@correo.com'
                ]
              }
            );
        - lang: csharp
          label: C#
          source: >
            // Enviar al correo del cliente

            await
            facturapi.Invoice.SendByEmailAsync("58e93bd8e86eb318b019743d");


            // Enviar a otro correo

            await facturapi.Invoice.SendByEmailAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["email"] = "otro@correo.com"
              }
            );


            // Enviar a más de un correo

            await facturapi.Invoice.SendByEmailAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["email"] = new String[]
                {
                  "primer@correo.com",
                  "segundo@correo.com"
                }
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.invoices().sendByEmail(
                  "inv_123",
                  Map.of(
                      "to", "cliente@example.com"
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            // Enviar al correo del cliente
            $facturapi->Invoices->sendByEmail("58e93bd8e86eb318b019743d");

            // Enviar a otro correo
            $facturapi->Invoices->sendByEmail(
              "58e93bd8e86eb318b019743d",
              "otro@correo.com"
            );

            // Enviar a más de un correo (máx 10)
            $facturapi->Invoices->sendByEmail(
              "58e93bd8e86eb318b019743d",
              [
                "primer@correo.com",
                "segundo@correo.com"
              ]
            );
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                email:
                  description: >-
                    Dirección de correo electrónico a enviar la factura. Si no
                    se envía este parámetro, la factura será enviada al correo
                    que el cliente tenga registrado.
                  oneOf:
                    - type: string
                      format: email
                      description: Dirección de correo eletrónico
                      example: otro@correo.com
                    - type: array
                      example:
                        - primer@correo.com
                        - segundo@correo.com
                      description: Lista de direcciones de correo que recibirán la factura.
                      maxLength: 10
                      items:
                        type: string
                        format: email
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto genérico de respuesta
          content:
            application/json:
              schema:
                type: object
                required:
                  - ok
                properties:
                  ok:
                    type: boolean
                    description: Indica si el correo fue enviado exitosamente
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /invoices/{invoice_id}/status:
    put:
      operationId: updateInvoiceStatus
      tags:
        - invoice
      summary: |
        Actualizar status de factura
      description: >
        Consulta el status de una factura timbrada en el SAT y actualiza el
        objeto invoice

        con La información más reciente.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/invoices/58e93bd8e86eb318b019743d/status
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X PUT
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const invoice = await
            facturapi.invoices.updateStatus('58e93bd8e86eb318b019743d');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new Facturapi

            var invoice = await
            facturapi.Invoice.UpdateStatusAsync("58e93bd8e86eb318b019743d");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.invoices().updateStatus(
                  "inv_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $invoice =
            $facturapi->Invoices->updateStatus("58e93bd8e86eb318b019743d");
      parameters:
        - in: path
          name: invoice_id
          schema:
            type: string
          required: true
          description: ID del objeto invoice a actualizar
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Invoice` actualizado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts:
    post:
      operationId: createReceipt
      tags:
        - receipt
      summary: Crear recibo
      description: |
        Crea un nuevo Recibo, el cual funge como nota de venta.

        Todos los recibos generan una URL de autofactura que cliente puede
        visitar para llenar sus datos fiscales en un micrositio con el branding
        de la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/receipts \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "folio_number": 1234,
                    "payment_form": "03",
                    "items": [{
                      "quantity": 1,
                      "product": {
                        "description": "Ukelele",
                        "product_key": "60131324",
                        "price": 345.60,
                        "sku": "ABC1234"
                      }
                    }]
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const receipt = await facturapi.receipts.create({
              folio_number: 1234,
              payment_form: Facturapi.PaymentForm.DINERO_ELECTRONICO,
              items: [{
                quantity: 1,
                product: {
                  description: 'Ukelele',
                  product_key: '60131324',
                  price: 345.60,
                  sku: 'ABC1234'
                }
              }]
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var receipt = await facturapi.Receipt.CreateAsync(new
            Dictionary<string, object>

            {
              ["folio_number"] = 1234,
              ["payment_form"] = Facturapi.PaymentForm.DINERO_ELECTRONICO,
              ["items"] = new Dictionary<string, object>[]
              {
                new Dictionary<string, object> {
                  ["description"] = "Ukelele",
                  ["product_key"] = "60131324",
                  ["price"] = 345.60,
                  ["sku"] = "ABC1234"
                }
              }
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var receipt = facturapi.receipts().create(
                Map.of(
                    "customer", "cus_123",
                    "items", List.of(
                        Map.of(
                            "quantity", 1,
                            "product", "prod_123"
                        )
                    )
                  ));
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $receipt = $facturapi->Receipts->create([
              "folio_number" => 1234,
              "payment_form" => "03",
              "items" => [
                [
                  "product" => [
                    "description" => "Ukelele",
                    "product_key" => "60131324",
                    "price" => 345.60,
                    "sku" => "ABC1234"
                  ]
                ]
              ]
            ]);
      requestBody:
        $ref: '#/components/requestBodies/ReceiptCreate'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Nuevo objeto `Receipt` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Receipt'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listReceipts
      tags:
        - receipt
      summary: Listar recibos
      description: >-
        Regresa una lista paginada de todos los recibos de una organización o
        realiza una búsqueda de acuerdo a parámetros
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            # Todos los recibos de la organización
            curl "https://www.facturapi.io/v2/receipts" \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY"

            # Página 3 de los resultados de búsqueda de texto libre
            # de recibos creados entre 2017 y 2019
            curl "https://www.facturapi.io/v2/receipts" \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=Aspiradora+Robot&date[gte]=2017-01-01T00:00:00.000Z&date[lt]=2020-01-01T00:00:00.000Z&page=3&limit=10"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            // Todos los recibos de la organización
            const receiptSearch = await facturapi.receipts.list();

            // Página 3 de los resultados de búsqueda de texto libre
            // de recibos creados entre 2017 y 2019
            const receiptSearch = await facturapi.receipts.list({
              q: 'Aspiradora Robot',
              date: {
                gte: new Date('2017-01-01T00:00:00.000Z'),
                lt: new Date('2020-01-01T00:00:00.000Z')
              },
              page: 3,
              limit: 10,
            });
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            // Todos los recibos de la organización
            var searchResult = await facturapi.Receipt.ListAsync();

            // Página 3 de los resultados de búsqueda de texto libre
            // de recibos creados entre 2017 y 2019
            var searchResult = await facturapi.Receipt.ListAsync(
              new Dictionary<string, object>
              {
                ["q"] = "Aspiradora Robot",
                ["date"] = new Dictionary<string, object>
                  {
                    ["gte"] = new DateTime("2017-01-01T00:00:00.000Z"),
                    ["lt"] = new DateTime("2020-01-01T00:00:00.000Z")
                  },
                ["page"] = 3,
                ["limit"] = 10,
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var searchResult = facturapi.receipts().list(
                  Map.of(
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            // Todos los recibos de la organización
            $searchResult = $facturapi->Receipts->all();

            // Página 3 de los resultados de búsqueda de texto libre
            // de recibos creados entre 2017 y 2019
            $searchResult = $facturapi->Receipts->all([
              q => "Aspiradora Robot",
              date => [
                gte => new DateTime("2017-01-01T00:00:00.000Z"),
                lt => new DateTime("2020-01-01T00:00:00.000Z")
              ],
              page => 3,
              limit => 10,
            ]);
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: >
            Consulta. Texto a buscar en la descripción de los conceptos del
            recibo o el SKU.
        - in: query
          name: customer
          schema:
            type: string
            minLength: 24
            maxLength: 24
          description: |
            ID del cliente asociado al recibo.
          example: 58e93bd8e86eb318b0197456
        - in: query
          name: payment_form
          schema:
            type: string
            minLength: 2
            maxLength: 2
          example: '02'
          description: >
            Código que representa la forma de pago, de acuerdo al [catálogo del
            SAT](#forma-de-pago). Si se incluye, los recibos se agruparán y se
            listarán de acuerdo a la forma de pago.
        - in: query
          name: date[gte]
          schema:
            type: string
            format: date-time
            example: '2017-01-01T00:00:00.000Z'
          description: Fecha de creación mayor o igual a la especificada.
        - in: query
          name: date[lte]
          schema:
            type: string
            format: date-time
            example: '2020-01-01T00:00:00.000Z'
          description: Fecha de creación menor o igual a la especificada.
        - in: query
          name: invoice
          schema:
            type: string
          description: |
            ID de la factura relacionada al recibo.
          example: 58e93bd8e86eb318b019743d
        - $ref: '#/components/parameters/SearchDate'
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReceiptSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts/{receipt_id}:
    get:
      operationId: getReceipt
      tags:
        - receipt
      summary: Obtener recibo por ID
      description: Regresa el objeto 'Receipt' relacionado al `id` especificado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/receipts/58e93bd8e86eb318b019743d \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const receipt = await
            facturapi.receipts.retrieve('58e93bd8e86eb318b019743d');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var receipt = await
            facturapi.Receipt.RetrieveAsync("58e93bd8e86eb318b019743d");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var receipt = facturapi.receipts().retrieve(
                  "rec_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $receipt = $facturapi->Receipts->retrieve(
            "58e93bd8e86eb318b019743d" );
      parameters:
        - in: path
          name: receipt_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Receipt`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Receipt'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: assignReceiptCustomer
      tags:
        - receipt
      summary: Asignar o reasignar cliente a recibo
      description: >
        Asigna o reasigna un cliente existente (por ID) a un recibo, o crea uno
        nuevo enviando el objeto del cliente.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/receipts/58e93bd8e86eb318b019743d \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -X PUT \
              -d '{
                    "customer": "58e93bd8e86eb318b0197456"
                  }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            // Asignar un cliente existente por ID

            const receipt = await facturapi.receipts.assignCustomer(
              '58e93bd8e86eb318b019743d',
              { customer: '58e93bd8e86eb318b0197456' }
            );


            // O crear el cliente desde payload y asignarlo al recibo

            const receiptWithNewCustomer = await
            facturapi.receipts.assignCustomer(
              '58e93bd8e86eb318b019743d',
              {
                customer: {
                  legal_name: 'Dunder Mifflin',
                  tax_id: 'XAXX010101000',
                  tax_system: '616',
                  email: 'billing@dundermifflin.com',
                  address: { zip: '01234', country: 'MEX' }
                }
              }
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");


            // Asignar un cliente existente por ID

            var receipt = await facturapi.Receipt.AssignCustomerAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["customer"] = "58e93bd8e86eb318b0197456"
              }
            );


            // O crear el cliente desde payload y asignarlo al recibo

            var receiptWithNewCustomer = await
            facturapi.Receipt.AssignCustomerAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["customer"] = new Dictionary<string, object>
                {
                  ["legal_name"] = "Dunder Mifflin",
                  ["tax_id"] = "XAXX010101000",
                  ["tax_system"] = "616",
                  ["email"] = "billing@dundermifflin.com",
                  ["address"] = new Dictionary<string, object>
                  {
                    ["zip"] = "01234",
                    ["country"] = "MEX"
                  }
                }
              }
            );
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            // This endpoint is available in the API, but the Java SDK helper is
            not exposed yet.
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");


            // Asignar un cliente existente por ID

            $receipt =
            $facturapi->Receipts->assignCustomer("58e93bd8e86eb318b019743d", [
              "customer" => "58e93bd8e86eb318b0197456"
            ]);


            // O crear el cliente desde payload y asignarlo al recibo

            $receiptWithNewCustomer =
            $facturapi->Receipts->assignCustomer("58e93bd8e86eb318b019743d", [
              "customer" => [
                "legal_name" => "Dunder Mifflin",
                "tax_id" => "XAXX010101000",
                "tax_system" => "616",
                "email" => "billing@dundermifflin.com",
                "address" => [
                  "zip" => "01234",
                  "country" => "MEX"
                ]
              ]
            ]);
      parameters:
        - in: path
          name: receipt_id
          schema:
            type: string
          required: true
          description: ID del recibo a actualizar
      requestBody:
        $ref: '#/components/requestBodies/ReceiptAssignCustomer'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Receipt` actualizado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Receipt'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: cancelReceipt
      tags:
        - receipt
      summary: Cancelar recibo
      description: >
        Marca un recibo como cancelado, cambiando su propiedad `status` a
        `"canceled"`.


        Una vez cancelado, el recibo no podrá ser facturado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/receipts/5ebd8e56f5687a013ca0df46 \
              -X DELETE \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const receipt = await
            facturapi.receipts.cancel('5ebd8e56f5687a013ca0df46');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var receipt = await
            facturapi.Receipt.CancelAsync("5ebd8e56f5687a013ca0df46");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var receipt = facturapi.receipts().cancel(
                  "rec_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $facturapi->Receipts->cancel("5ebd8e56f5687a013ca0df46");
      parameters:
        - in: path
          name: receipt_id
          schema:
            type: string
          required: true
          description: ID del recibo a cancelar
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto 'Receipt' cancelado exitosamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Receipt'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts/{receipt_id}/pdf:
    get:
      operationId: downloadReceiptPdf
      tags:
        - receipt
      summary: Descargar PDF
      description: Descarga el recibo digital en formato PDF.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/receipts/58e93bd8e86eb318b019743d/pdf \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import fs from 'fs';

            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            // Descargar recibo en formato PDF

            const pdfStream = await
            facturapi.receipts.downloadPdf('58e93bd8e86eb318b019743d');

            const pdfFile = fs.createWriteStream('./recibo.pdf');

            pdfStream.pipe(pdfFile);
        - lang: csharp
          label: C#
          source: >
            // Descargar recibo en formato PDF

            var pdfStream = await
            facturapi.Receipt.DownloadPdfAsync("58e93bd8e86eb318b019743d");


            // Para guardar la descarga en un archivo

            var file = new
            System.IO.FileStream("C:\\route\\to\\save\\receipt.pdf",
            FileMode.Create);

            pdfStream.CopyTo(file);

            file.Close();
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");
            byte[] pdf = facturapi.receipts().downloadPdf(
                  "rec_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");


            // stream containing the PDF file

            $pdf =
            $facturapi->Receipts->downloadPdf("58e93bd8e86eb318b019743d");
      parameters:
        - in: path
          name: receipt_id
          schema:
            type: string
          required: true
          description: ID del objeto a descargar
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Archivo del recibo digital en formato PDF
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts/{receipt_id}/email:
    post:
      operationId: sendReceiptByEmail
      tags:
        - receipt
      summary: Enviar recibo por correo electrónico
      description: >
        Envía un correo electrónico a la dirección de tu cliente.


        El correo enviado estará personalizado con el logotipo y los colores de
        la organización que lo creó,

        e incluirá un botón para facturar el recibo, así con el recibo en
        formato PDF adjunto al mensaje.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            # Enviar recibo por correo electrónico

            curl
            https://www.facturapi.io/v2/receipts/58e93bd8e86eb318b019743d/email
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X POST \
              -H "Content-Type: application/json" \
              -d '{
                    "email": "another_email@example.com"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            // Enviar recibo por correo electrónico
            await facturapi.receipts.sendByEmail(
              '58e93bd8e86eb318b019743d',
              { email: 'ejemplo@correo.com' }
            );

            // Enviar a más de un correo (máx. 10)
            await facturapi.receipts.sendByEmail(
              '58e93bd8e86eb318b019743d',
              { 
                email: [
                  'primer@correo.com',
                  'segundo@correo.com'
                ]
              }
            );
        - lang: csharp
          label: C#
          source: |
            // Enviar recibo por correo electrónico
            await facturapi.Receipt.SendByEmailAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["email"] = "ejemplo@correo.com"
              }
            );

            // Enviar a más de un correo
            await facturapi.Receipt.SendByEmailAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["email"] = new String[]
                {
                  "primer@correo.com",
                  "segundo@correo.com"
                }
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.receipts().sendByEmail(
                  "rec_123",
                  Map.of(
                      "to", "cliente@example.com"
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            // Enviar recibo por correo electrónico
            $facturapi->Receipts->sendByEmail(
              "58e93bd8e86eb318b019743d",
              "ejemplo@correo.com"
            );

            // Enviar a más de un correo (máx 10)
            $facturapi->Receipts->sendByEmail(
              "58e93bd8e86eb318b019743d",
              [
                "primer@correo.com",
                "segundo@correo.com"
              ]
            );
      parameters:
        - in: path
          name: receipt_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              required:
                - email
              properties:
                email:
                  description: Dirección de correo electrónico a enviar el recibo digital.
                  oneOf:
                    - type: string
                      format: email
                      description: Dirección de correo eletrónico
                      example: otro@correo.com
                    - type: array
                      example:
                        - primer@correo.com
                        - segundo@correo.com
                      description: >-
                        Lista de direcciones de correo que recibirán el recibo
                        digital.
                      maxLength: 10
                      items:
                        type: string
                        format: email
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto genérico de respuesta
          content:
            application/json:
              schema:
                type: object
                required:
                  - ok
                properties:
                  ok:
                    type: boolean
                    description: Indica si el correo fue enviado exitosamente
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts/{receipt_id}/invoice:
    post:
      operationId: invoiceReceipt
      tags:
        - receipt
      summary: Facturar recibo
      description: >
        Crea una factura a partir de un recibo.


        Sólo pueden facturarse recibos abiertos (`status = "open"`)


        Si envías `customer`, ese cliente se usará como receptor de la factura y

        sobrescribirá el cliente asignado al recibo. Si omites `customer`, el

        recibo debe tener un cliente asignado previamente.


        Una vez facturado, el `status` del recibo cambiará a
        `"invoiced_to_customer"`.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/receipts/5ebd8e56f5687a013ca0df46/invoice
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "customer": "58e93bd8e86eb318b0197456",
                    "folio_number": 914,
                    "series": "F"
                }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            const invoice = await
            facturapi.receipts.invoice('5ebd8e56f5687a013ca0df46', {
              customer: '58e93bd8e86eb318b0197456',
              folio_number: 914,
              series: 'F'
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var invoice = await
            facturapi.Receipt.InvoiceAsync("5ebd8e56f5687a013ca0df46", new
            Dictionary<string, object>

            {
              ["customer"] = "58e93bd8e86eb318b0197456",
              ["folio_number"] = 914,
              ["series"] = "F"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.receipts().invoice(
                  "rec_123",
                  Map.of(
                      "customer", "cus_123"
                  )
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");


            $invoice = $facturapi->Receipts->invoice("5a3f3e35f508333611ad6b3e",
            [
              "customer" => "58e93bd8e86eb318b0197456",
              "folio_number" => 914,
              "series" => "F"
            ]);
      parameters:
        - in: path
          name: receipt_id
          schema:
            type: string
          required: true
          description: ID del recibo a facturar
      requestBody:
        $ref: '#/components/requestBodies/ReceiptInvoice'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Nuevo objeto `Invoice` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts/to-invoice:
    post:
      operationId: createToInvoiceFromReceipts
      tags:
        - receipt
      summary: Facturar múltiples recibos
      description: >
        Crea una sola factura a partir de múltiples recibos seleccionados por su
        `key`.


        Si envías `customer`, ese cliente se usará como receptor de la factura y

        sobrescribirá el cliente asignado a los recibos incluidos. Si omites

        `customer`, todos los recibos deben tener asignado el mismo cliente.


        Si `dry_run` es `true`, no crea la factura y regresa un resumen de vista
        previa.

        El `dry_run` valida las mismas reglas que la creación real, pero no
        persiste cambios.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/receipts/to-invoice \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "keys": ["ticket_1001", "ticket_1002"],
                    "customer": {
                      "legal_name": "Dunder Mifflin",
                      "tax_id": "ABC101010111",
                      "tax_system": "601",
                      "email": "email@example.com",
                      "address": {
                        "zip": "85900"
                      }
                    },
                    "use": "G03",
                    "payment_form": "03"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const invoice = await facturapi.receipts.toInvoice({
              keys: ['ticket_1001', 'ticket_1002'],
              customer: {
                legal_name: 'Dunder Mifflin',
                tax_id: 'ABC101010111',
                tax_system: '601',
                email: 'email@example.com',
                address: {
                  zip: '85900'
                }
              },
              use: 'G03',
              payment_form: Facturapi.PaymentForm.TRANSFERENCIA_ELECTRONICA_DE_FONDOS
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var invoice = await facturapi.Receipt.ToInvoiceAsync(new
            Dictionary<string, object>

            {
              ["keys"] = new[] { "ticket_1001", "ticket_1002" },
              ["customer"] = new Dictionary<string, object>
              {
                ["legal_name"] = "Dunder Mifflin",
                ["tax_id"] = "ABC101010111",
                ["tax_system"] = "601",
                ["email"] = "email@example.com",
                ["address"] = new Dictionary<string, object>
                {
                  ["zip"] = "85900"
                }
              },
              ["use"] = "G03",
              ["payment_form"] = Facturapi.PaymentForm.TRANSFERENCIA_ELECTRONICA_DE_FONDOS
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.receipts().toInvoice(
                Map.of(
                    "keys", List.of("ticket_1001", "ticket_1002"),
                    "customer", Map.of(
                        "legal_name", "Dunder Mifflin",
                        "tax_id", "ABC101010111",
                        "tax_system", "601",
                        "address", Map.of("zip", "85900")
                    ),
                    "use", "G03",
                    "payment_form", "03"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $invoice = $facturapi->Receipts->toInvoice([
              "keys" => ["ticket_1001", "ticket_1002"],
              "customer" => [
                "legal_name" => "Dunder Mifflin",
                "tax_id" => "ABC101010111",
                "tax_system" => "601",
                "email" => "email@example.com",
                "address" => [
                  "zip" => "85900"
                ]
              ],
              "use" => "G03",
              "payment_form" => \Facturapi\PaymentForm::TRANSFERENCIA_ELECTRONICA_DE_FONDOS
            ]);
      requestBody:
        $ref: '#/components/requestBodies/ReceiptCreateToInvoice'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Invoice` creado u objeto resumen cuando `dry_run=true`
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/Invoice'
                  - $ref: '#/components/schemas/ToInvoiceSummary'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          description: No se encontraron recibos elegibles para las keys enviadas
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ToInvoiceNotFoundResponse'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts/to-invoice/preview:
    post:
      operationId: previewToInvoiceFromReceipts
      tags:
        - receipt
      summary: Vista previa PDF de factura múltiple
      description: >
        Genera una vista previa en PDF para una factura construida a partir de
        múltiples recibos seleccionados por `key`.


        La vista previa valida las mismas reglas de cliente que la creación
        real:

        si omites `customer`, todos los recibos deben tener asignado el mismo
        cliente.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/receipts/to-invoice/preview \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "keys": ["ticket_1001", "ticket_1002"],
                    "customer": {
                      "legal_name": "Dunder Mifflin",
                      "tax_id": "ABC101010111",
                      "tax_system": "601",
                      "address": {
                        "zip": "85900"
                      }
                    },
                    "use": "G03"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            import fs from 'fs'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const pdfStream = await facturapi.receipts.previewToInvoicePdf({
              keys: ['ticket_1001', 'ticket_1002'],
              customer: {
                legal_name: 'Dunder Mifflin',
                tax_id: 'ABC101010111',
                tax_system: '601',
                address: {
                  zip: '85900'
                }
              },
              use: 'G03'
            });

            const file = fs.createWriteStream('to_invoice_preview.pdf');
            pdfStream.pipe(file);
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var pdfStream = await facturapi.Receipt.PreviewToInvoicePdfAsync(new
            Dictionary<string, object>

            {
              ["keys"] = new[] { "ticket_1001", "ticket_1002" },
              ["customer"] = new Dictionary<string, object>
              {
                ["legal_name"] = "Dunder Mifflin",
                ["tax_id"] = "ABC101010111",
                ["tax_system"] = "601",
                ["address"] = new Dictionary<string, object>
                {
                  ["zip"] = "85900"
                }
              },
              ["use"] = "G03"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var pdf = facturapi.receipts().previewToInvoicePdf(
                Map.of(
                    "keys", List.of("ticket_1001", "ticket_1002"),
                    "customer", Map.of(
                        "legal_name", "Dunder Mifflin",
                        "tax_id", "ABC101010111",
                        "tax_system", "601",
                        "address", Map.of("zip", "85900")
                    ),
                    "use", "G03"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $pdfBytes = $facturapi->Receipts->previewToInvoicePdf([
              "keys" => ["ticket_1001", "ticket_1002"],
              "customer" => [
                "legal_name" => "Dunder Mifflin",
                "tax_id" => "ABC101010111",
                "tax_system" => "601",
                "address" => [
                  "zip" => "85900"
                ]
              ],
              "use" => "G03"
            ]);
      requestBody:
        $ref: '#/components/requestBodies/ReceiptPreviewToInvoice'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Contenido binario del PDF
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '204':
          description: No se encontraron recibos elegibles para las keys enviadas
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /receipts/global-invoice:
    post:
      operationId: createGlobalInvoice
      tags:
        - receipt
      summary: Crear factura global
      description: >
        Crea una factura global que incluirá todos los recibos con `status =
        “open”` de un cierto periodo.


        La factura global se emite al cliente genérico `PUBLICO EN GENERAL`.

        Los recibos incluidos quedan asociados a ese cliente y su `status`

        cambia a `"invoiced_globally"`.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/receipts/global-invoice \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "from": "2021-01-01T05:00:00.000Z",
                    "to": "2021-01-31T04:59:59.999Z",
                    "periodicity": "month",
                    "months": "01",
                    "year": 2021,
                    "folio_number": 1234,
                    "series": "G"
                }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const invoice = await facturapi.receipts.createGlobalInvoice({
              from: '2020-12-01T05:00:00.000Z',
              to: '2020-12-31T04:59:59.999Z',
              periodicity: 'month',
              months: '01',
              year: 2021
              folio_number: 1234,
              series: 'G'
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var invoice = await facturapi.Receipt.CreateGlobalInvoiceAsync(new
            Dictionary<string, object>

            {
              ["from"] = "2020-12-01T05:00:00.000Z",
              ["to"] = "2020-12-31T04:59:59.999Z",
              ["periodicity"] = "month",
              ["months"] = "01",
              ["year"] = 2021,
              ["folio_number"] = 1234,
              ["series"] = "G"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invoice = facturapi.receipts().createGlobalInvoice(
                  Map.of(
                      "month", 5,
                      "year", 2024
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $invoice = $facturapi->Receipts->createGlobalInvoice([
              "from" => "2020-12-01T05:00:00.000Z",
              "to" => "2020-12-31T04:59:59.999Z",
              "periodicity" => "month",
              "months" => "01",
              "year" => 2021,
              "folio_number" => 1234,
              "series" => "G"
            ]);
      requestBody:
        $ref: '#/components/requestBodies/ReceiptCreateGlobalInvoice'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Nuevo objeto `Invoice` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /retentions:
    post:
      operationId: createRetention
      tags:
        - retention
      summary: Crear retención
      description: >
        Crea una nueva Retención. Si el comprobante es creado en ambiente Live,
        ésta será **timbrado y enviado al SAT**.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/retentions \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "customer": "58e93bd8e86eb318b0197456",
                    "cve_retenc": "26",
                    "periodo": {
                      "mes_ini": 1,
                      "mes_fin": 12,
                      "ejerc": 2020
                    },
                    "totales": {
                      "monto_tot_operacion": 244.654321,
                      "monto_tot_exent": 145.123456,
                      "imp_retenidos": [
                        {
                          "monto_ret": 40,
                          "base_ret": 250
                        }
                      ]
                    }
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const retention = await facturapi.retentions.create({
              customer: '58e93bd8e86eb318b0197456',
              cve_retenc: '26',
              periodo: {
                mes_ini: 1,
                mes_fin: 12,
                ejerc: 2020
              },
              totales: {
                monto_tot_operacion: 244.654321,
                monto_tot_exent: 145.123456,
                imp_retenidos: [
                  {
                    monto_ret: 40,
                    base_ret: 250
                  }
                ]
              }
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var retention = await facturapi.Retention.CreateAsync(new
            Dictionary<string, object>

            {
              ["customer"] = "58e93bd8e86eb318b0197456",
              ["cve_retenc"] = "26",
              ["periodo"] = new Dictionary<string, object>
              {
                ["mes_ini"] = 1,
                ["mes_fin"] = 12,
                ["ejerc"] = 2020
              },
              ["totales"] = new Dictionary<string, object>
              {
                ["monto_tot_operacion"] = 244.654321,
                ["monto_tot_exent"] = 145.123456,
                ["imp_retenidos"] = new Dictionary<string, object>[]
                {
                  new Dictionary<string, object>
                  {
                    ["]
                    ["monto_ret"] = 40,
                    ["base_ret"] = 250
                  }
                }
              }
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var retention = facturapi.retentions().create(
                Map.of(
                    "receiver", Map.of(
                        "name", "Cliente ejemplo"
                    ),
                    "items", List.of(
                        Map.of(
                            "quantity", 1,
                            "product", "prod_123"
                        )
                    )
                  ));
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $retention = $facturapi->Retentions->create([
              "customer" => "58e93bd8e86eb318b0197456",
              "cve_retenc" => "26",
              "periodo" => [
                "mes_ini" => 1,
                "mes_fin" => 12,
                "ejerc" => 2020
              ],
              "totales" => [
                "monto_tot_operacion" => 244.654321,
                "monto_tot_exent" => 145.123456,
                "imp_retenidos" => [
                  [
                    "impuesto" => "ISR",
                    "monto_ret" => 40,
                    "base_ret" => 250
                  ]
                ]
              ]
            ]);
      requestBody:
        $ref: '#/components/requestBodies/RetentionCreate'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Nuevo objeto `Retention` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Retention'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listRetentions
      tags:
        - retention
      summary: Listar retenciones
      description: >-
        Regresa una lista paginada de todas las retenciones de una organización
        o realiza una búsqueda de acuerdo a parámetros
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            # Todas las retenciones de la organización
            curl https://www.facturapi.io/v2/retentions \
              -H "Authorization: Bearer sk_test_API_KEY"

            # Todas las retenciones emitidas para cierto cliente
            curl "https://www.facturapi.io/v2/retentions" \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "customer=58e93bd8e86eb318b0197456"

            # Página 3 de los resultados de búsqueda de texto libre
            # de retenciones emitidas entre 2017 y 2019
            curl "https://www.facturapi.io/v2/retentions" \
              -G \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -d "q=John+Doe6&date[gte]=2017-01-01T00:00:00.000Z&date[lt]=2020-01-01T00:00:00.000Z&page=3&limit=10"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            // Todas las retenciones de la organización
            const retentionSearch = await facturapi.retentions.list();

            // Todas las retenciones emitidas para cierto cliente
            const retentionSearch = await facturapi.retentions.list({
              customer: '590ce6c56d04f840aa8438af'
            });

            // Página 3 de los resultados de búsqueda de texto libre
            // de retenciones emitidas entre 2017 y 2019
            const retentionSearch = await facturapi.retentions.list({
              q: 'John Doe',
              date: {
                gte: new Date('2017-01-01T00:00:00.000Z'),
                lt: new Date('2020-01-01T00:00:00.000Z')
              },
              page: 3,
              limit: 10,
            });
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            // Todas las retenciones de la organización
            var searchResult = await facturapi.Retention.ListAsync();

            // Todas las retenciones emitidas para cierto cliente
            var searchResult = await facturapi.Retention.ListAsync(
              new Dictionary<string, object>
              {
                ["customer"] = "590ce6c56d04f840aa8438af"
              }
            );

            // Página 3 de los resultados de búsqueda de texto libre
            // de retenciones emitidas entre 2017 y 2019
            var searchResult = await facturapi.Retention.ListAsync(
              new Dictionary<string, object>
              {
                ["q"] = "John Doe",
                ["date"] = new Dictionary<string, object>
                  {
                    ["gte"] = new DateTime("2017-01-01T00:00:00.000Z"),
                    ["lt"] = new DateTime("2020-01-01T00:00:00.000Z")
                  },
                ["page"] = 3,
                ["limit"] = 10,
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var searchResult = facturapi.retentions().list(
                  Map.of(
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            // Todas las retenciones de la organización
            $retentions = $facturapi->Retentions->all();

            // Todas las retenciones emitidas para cierto cliente
            $retentions = $facturapi->Retentions->all([
              customer => "590ce6c56d04f840aa8438af"
            ]);

            // Página 3 de los resultados de búsqueda de texto libre
            // de retenciones emitidas entre 2017 y 2019
            $retentions = $facturapi->Retentions->all([
              q => "John Doe",
              date => [
                gte => new DateTime("2017-01-01T00:00:00.000Z"),
                lt => new DateTime("2020-01-01T00:00:00.000Z")
              ],
              page => 3,
              limit => 10,
            ]);
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: Consulta. Texto a buscar en el nombre fiscal del cliente o su RFC.
        - in: query
          name: customer
          schema:
            type: string
          description: >-
            Identificador del cliente. Útil para obtener las retenciones
            emitidas a un sólo cliente.
        - $ref: '#/components/parameters/SearchDate'
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetentionSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /retentions/{retention_id}:
    get:
      operationId: getRetention
      tags:
        - retention
      summary: Obtener retención por ID
      description: Regresa el objeto 'Retention' relacionado al `id` especificado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl https://www.facturapi.io/v2/retentions/6062d9fb226600001cd22f71
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const retention = await
            facturapi.retentions.retrieve('6062d9fb226600001cd22f71');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var retention = await
            facturapi.Retention.RetrieveAsync("6062d9fb226600001cd22f71");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var retention = facturapi.retentions().retrieve(
                  "ret_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $retention = $facturapi->Retentions->retrieve(
            "6062d9fb226600001cd22f71" );
      parameters:
        - in: path
          name: retention_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Retention`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Retention'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: cancelRetention
      tags:
        - retention
      summary: Cancelar retención
      description: >
        Realiza una solicitud de cancelación de retención ante el SAT.


        A diferencia de las facturas comúnes, la cancelación de la retención es
        inmediata y no requiere autorización de parte del receptor.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl https://www.facturapi.io/v2/retentions/6062d9fb226600001cd22f71
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X DELETE
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
                const canceledRetention = await facturapi.retentions.cancel('6062d9fb226600001cd22f71', {
                  motive: '01',
                  substitution: 'UUID_O_ID_DE_RETENCION'
                });
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
                var canceledRetention = await facturapi.Retention.CancelAsync("6062d9fb226600001cd22f71", new {
                    motive = "01",
                    substitution = "UUID_O_ID_DE_RETENCION"
                });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var retention = facturapi.retentions().cancel(
                  "ret_123",
                  Map.of(
                      "motive", "02"
                  )
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $canceledRetention =
            $facturapi->Retentions->cancel("6062d9fb226600001cd22f71", [
              "motive" => "01",
              "substitution" => "UUID_O_ID_DE_RETENCION"
            ]);
      parameters:
        - in: path
          name: retention_id
          schema:
            type: string
          required: true
          description: ID de la retención a cancelar
        - in: query
          name: motive
          required: true
          schema:
            type: string
            enum:
              - '01'
              - '02'
              - '03'
              - '04'
          description: >
            Clave que representa el motivo de la cancelación de la retención

            - `01`: **Comprobante emitido con errores con relación**. Cuando la
              retención contiene algún error en las cantidades, claves o cualquier otro dato y ya
              se ha emitido el comprobante que la sustituye, el cual deberá indicarse por medio
              del atributo `substitution`.
            - `02`: **Comprobante emitido con errores sin relación**. Cuando la
              retención contiene algún error en las cantidades, claves o cualquier otro dato y no
              se requiere relacionar con otra retención.
            - `03`: **No se llevó a cabo la operación**. Cuando la operación o
            transacción no se concretó.

            - `04`: **Operación nominativa relacionada en la retención global**.
            Cuando se requiere cancelar
              una retención al público en general porque el cliente solicita su comprobante.
        - in: query
          name: substitution
          required: false
          schema:
            type: string
          description: >
            ID de la retención que sustituye a la retención que se está
            cancelando

            Puedes usar el ID de Facturapi o el folio fiscal (UUID).
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Retention` cancelado exitosamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Retention'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /retentions/{retention_id}/{format}:
    get:
      operationId: downloadRetention
      tags:
        - retention
      summary: Descargar retención
      description: Descarga una retención en PDF, XML o ambos en un archivo comprimido ZIP.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            ## Descargar PDF y XML comprimidos en archivo ZIP

            curl
            https://www.facturapi.io/v2/retentions/58e93bd8e86eb318b019743d/zip
            \
              -H "Authorization: Bearer sk_test_API_KEY"

            ## Descargar sólo el PDF

            curl
            https://www.facturapi.io/v2/retentions/58e93bd8e86eb318b019743d/pdf
            \
              -H "Authorization: Bearer sk_test_API_KEY"

            ## Descargar sólo el XML

            curl
            https://www.facturapi.io/v2/retentions/58e93bd8e86eb318b019743d/xml
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import fs from 'fs';

            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            // Descargar PDF y XML comprimidos en archivo ZIP

            const zipStream = await
            facturapi.retentions.downloadZip('58e93bd8e86eb318b019743d');

            const zipFile = fs.createWriteStream('./retencion.zip');

            zipStream.pipe(zipFile);


            // Descargar sólo el PDF

            const pdfStream = await
            facturapi.retentions.downloadPdf('58e93bd8e86eb318b019743d');

            const pdfFile = fs.createWriteStream('./retencion.pdf');

            pdfStream.pipe(pdfFile);


            // Descargar sólo el XML

            const xmlStream = await
            facturapi.retentions.downloadXml('58e93bd8e86eb318b019743d');

            const xmlFile = fs.createWriteStream('./retencion.xml');

            xmlStream.pipe(xmlFile);
        - lang: csharp
          label: C#
          source: >
            // Descargar PDF y XML comprimidos en archivo ZIP

            var zipStream = await
            facturapi.Retention.DownloadZipAsync("58e93bd8e86eb318b019743d");

            // Descargar sólo el XML

            var xmlStream = await
            facturapi.Retention.DownloadXmlAsync("58e93bd8e86eb318b019743d");

            // Descargar sólo el PDF

            var pdfStream = await
            facturapi.Retention.DownloadPdfAsync("58e93bd8e86eb318b019743d");


            // Para guardar la descarga en un archivo

            var file = new
            System.IO.FileStream("C:\\route\\to\\save\\retention.zip",
            FileMode.Create);

            zipStream.CopyTo(file);

            file.Close();
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");
            byte[] pdf = facturapi.retentions().downloadPdf(
                  "ret_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");


            // stream containing the PDF and XML as a ZIP file

            $zip =
            $facturapi->Retentions->downloadZip("58e93bd8e86eb318b019743d");

            // stream containing the PDF file

            $pdf =
            $facturapi->Retentions->downloadPdf("58e93bd8e86eb318b019743d"); 

            // stream containing the XML file

            $xml =
            $facturapi->Retentions->downloadXml("58e93bd8e86eb318b019743d");
      parameters:
        - in: path
          name: retention_id
          schema:
            type: string
          required: true
          description: ID del objeto a descargar
        - in: path
          name: format
          schema:
            type: string
            enum:
              - xml
              - pdf
              - zip
          required: true
          description: Formato del archivo de descarga
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Archivo del comprobante CFDI en el formato solicitado
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /retentions/{retention_id}/email:
    post:
      operationId: sendRetentionByEmail
      tags:
        - retention
      summary: Enviar retención por correo electrónico
      description: >-
        Envía un correo electrónico a la dirección de tu cliente, con los
        archivos XML y PDF adjuntos al mensaje.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            # Enviar al correo del cliente

            curl
            https://www.facturapi.io/v2/retentions/58e93bd8e86eb318b019743d/email
            \
              -H "Authorization: Bearer sk_test_API_KEY"
              -X POST

            # Enviar a otro correo

            curl
            https://www.facturapi.io/v2/retentions/58e93bd8e86eb318b019743d/email
            \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -X POST \
              -H "Content-Type: application/json" \
              -d '{
                    "email": "another_email@example.com"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            // Enviar al correo del cliente
            await facturapi.retentions.sendByEmail('58e93bd8e86eb318b019743d');

            // Enviar a otro correo
            await facturapi.retentions.sendByEmail(
              '58e93bd8e86eb318b019743d',
              { email: 'otro@correo.com' }
            );

            // Enviar a más de un correo (máx. 10)
            await facturapi.retentions.sendByEmail(
              '58e93bd8e86eb318b019743d',
              { 
                email: [
                  'primer@correo.com',
                  'segundo@correo.com'
                ]
              }
            );
        - lang: csharp
          label: C#
          source: >
            // Enviar al correo del cliente

            await
            facturapi.Retention.SendByEmailAsync("58e93bd8e86eb318b019743d");


            // Enviar a otro correo

            await facturapi.Retention.SendByEmailAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["email"] = "otro@correo.com"
              }
            );


            // Enviar a más de un correo

            await facturapi.Retention.SendByEmailAsync(
              "58e93bd8e86eb318b019743d",
              new Dictionary<string, object>
              {
                ["email"] = new String[]
                {
                  "primer@correo.com",
                  "segundo@correo.com"
                }
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.retentions().sendByEmail(
                  "ret_123",
                  Map.of(
                      "to", "cliente@example.com"
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            // Enviar al correo del cliente
            $facturapi->Retentions->sendByEmail("58e93bd8e86eb318b019743d");

            // Enviar a otro correo
            $facturapi->Retentions->sendByEmail(
              "58e93bd8e86eb318b019743d",
              "otro@correo.com"
            );

            // Enviar a más de un correo (máx 10)
            $facturapi->Retentions->sendByEmail(
              "58e93bd8e86eb318b019743d",
              [
                "primer@correo.com",
                "segundo@correo.com"
              ]
            );
      parameters:
        - in: path
          name: retention_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                email:
                  description: >-
                    Dirección de correo electrónico a enviar la retención. Si no
                    se envía este parámetro, la retención será enviada al correo
                    que el cliente tenga registrado.
                  oneOf:
                    - type: string
                      format: email
                      description: Dirección de correo eletrónico
                      example: otro@correo.com
                    - type: array
                      example:
                        - primer@correo.com
                        - segundo@correo.com
                      description: >-
                        Lista de direcciones de correo que recibirán la
                        retención.
                      maxLength: 10
                      items:
                        type: string
                        format: email
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto genérico de respuesta
          content:
            application/json:
              schema:
                type: object
                required:
                  - ok
                properties:
                  ok:
                    type: boolean
                    description: Indica si el correo fue enviado exitosamente
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations:
    post:
      operationId: createOrganization
      tags:
        - organization
      summary: Crear organización
      description: >
        Crea una nueva Organización que pertenecerá a tu cuenta de usuario.


        Después de crear la organización y antes de poder emitir facturas con

        la organización, deberás de terminar de configurarla llamando a los

        métodos de [Actualizar datos
        fiscales](#tag/organization/operation/editOrganizationLegal) y

        [Subir certificados
        (CSD)](#tag/organization/operation/uploadOrganizationCertificate)



        Después de crear la organización y antes de poder emitir facturas con

        la organización, deberás de terminar de configurarla llamando a los

        métodos de [Actualizar datos
        fiscales](#tag/organization/operation/editOrganizationLegal) y

        [Subir certificados
        (CSD)](#tag/organization/operation/uploadOrganizationCertificate), 

        además de firmar la Carta Manifiesto que autoriza a nuestro PAC a
        timbrar facturas; 

        puedes hacerlo en [tu
        dashboard](https://dashboard.facturapi.io/settings/manifiesto) 

        o en [nuestro portal público](https://www.facturapi.io/manifiesto).
        También puedes incrustar 

        en tu solución el módulo de firma de la carta (sin logos, listo para
        iframe): https://www.facturapi.io/embedded/manifiesto


        Recuerda que los folios de tu suscripción podrán ser consumidos por

        cualquiera de las organizaaciones registradas bajo tu cuenta.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/organizations \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                  "name": "Skynet"
                }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');
            const organization = await facturapi.organizations.create({
              name: 'Skynet'
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var organization = await facturapi.Organization.CreateAsync(new
            Dictionary<string, object>

            {
              ["name"] = "Skynet"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().create(
                Map.of(
                    "legal_name", "Mi Empresa SA de CV",
                    "tax_id", "XAXX010101000",
                    "tax_system", "601",
                    "email", "cliente@example.com"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $organization = $facturapi->Organizations->create([
              "name" => "Skynet"
            ]);
      requestBody:
        $ref: '#/components/requestBodies/OrganizationCreate'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Nuevo objeto `Organization` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listOrganizations
      tags:
        - organization
      summary: Listar organizaciones
      description: >-
        Regresa una lista paginada de todas las organizationes registradas bajo
        tu cuenta, o realiza una búsqueda de acuerdo a parámetros.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/organizations \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const organizationResults = await facturapi.organizations.list();
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var searchResult = await facturapi.Organization.ListAsync();
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var searchResult = facturapi.organizations().list(
                  Map.of(
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $organizations = $facturapi->Organizations->all()
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: >-
            Consulta. Texto a buscar en `name` (nombre comercial), `legal_name`
            (nombre fiscal) o en `tax_id` (RFC).
        - $ref: '#/components/parameters/SearchDate'
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/me:
    get:
      operationId: meOrganization
      tags:
        - organization
      summary: Detalle de organización
      description: |
        Retorna el detalle de la organización actualmente autenticada.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/organizations/me \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const organizationResults = await facturapi.organizations.me();
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var searchResult = await facturapi.Organization.MeAsync();
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().me(
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $organizations = $facturapi->Organizations->me()
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Organization`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/legal:
    put:
      operationId: editOrganizationLegal
      tags:
        - organization
      summary: Editar datos fiscales
      description: |
        Actualiza los datos fiscales de la organización.

        Si estás buscando cómo editar el RFC, recuerda que la propiedad
        `tax_id` se asigna automáticamente al subir los Certificados de Sello
        Digital.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/legal
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "name": "Skynet",
                    "legal_name": "Skynet",
                    "tax_system": "601",
                    "website": "www.sky.net",
                    "phone": "555-555-5555",
                    "address": {
                      "exterior": "1414",
                      "interior": "12",
                      "zip": "44940",
                      "neighborhood": "Villa Toscana",
                      "city": "Guadalajara",
                      "municipality": "Guadalajara",
                      "state": "Jalisco",
                      "country": "México"
                    }
                }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');
            const organization = await facturapi.organizations.updateLegal(
              '5a2a307be93a2f00129ea035',
              {
                name: 'Skynet',
                legal_name: 'Skynet',
                tax_system: Facturapi.TaxSystem.GENERAL_LEY_DE_PERSONAS_MORALES,
                website: 'www.sky.net',
                phone: '555-555-5555',
                address: {
                  exterior: '1414',
                  interior: '12',
                  zip: '44940',
                  neighborhood: 'Villa Toscana',
                  city: 'Guadalajara',
                  municipality: 'Guadalajara',
                  state: 'Jalisco',
                  country: 'México'
                }
              }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var organization = await facturapi.Organization.UpdateLegalAsync(
              "5a2a307be93a2f00129ea035",
              new Dictionary<string, object>
              {
                ["name"] = "Skynet",
                ["legal_name"] = "Skynet",
                ["tax_system"] = "601",
                ["website"] = "www.sky.net",
                ["phone"] = "555-555-5555",
                ["address"] = new Dictionary<string, object>
                {
                  ["exterior"] = "1414",
                  ["interior"] = "12",
                  ["zip"] = "44940",
                  ["neighborhood"] = "Villa Toscana",
                  ["city"] = "Guadalajara",
                  ["municipality"] = "Guadalajara",
                  ["state"] = "Jalisco",
                  ["country"] = "México"
                }
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().updateLegal(
                "org_123",
                Map.of(
                    "legal_name", "Mi Empresa SA de CV",
                    "tax_id", "XAXX010101000"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $organization = $facturapi->Organizations->updateLegal(
              "5a2a307be93a2f00129ea035", [
                "name" => "Skynet",
                "legal_name" => "Skynet",
                "tax_system" => "601",
                "website" => "www.sky.net",
                "phone" => "555-555-5555",
                "address" => [
                  "exterior" => "1414",
                  "interior" => "12",
                  "zip" => "44940",
                  "neighborhood" => "Villa Toscana",
                  "city" => "Guadalajara",
                  "municipality" => "Guadalajara",
                  "state" => "Jalisco",
                  "country" => "México"
                )
              ]
            ];
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationEditLegal'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/certificate:
    put:
      operationId: uploadOrganizationCertificate
      tags:
        - organization
      summary: Subir certificados (CSD)
      description: |
        Sube los archivos del Certificado de Sello Digital (CSD) proporcionado
        por el SAT. Esta llamada también debe usarse para reemplazar los
        certificados existentes en caso de solicitar nuevos.

        Al actualizar tus certificados se leerá el RFC y asignará
        automáticamente a `legal.tax_id`.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/certificate
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: multipart/form-data" \
              -F 'cer=@/path/to/your/CSD.cer' \
              -F 'key=@/path/to/your/CSD.key' \
              -F 'password=CONTRASEÑA_DEL_CERTIFICADO'
        - lang: JavaScript
          label: Node.js
          source: >
            import fs from 'fs';

            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY');


            const cerFileStream = fs.createReadStream('/path/to/your/CSD.cer');

            const keyFileStream = fs.createReadStream('/path/to/your/CSD.key');


            const organization = await
            facturapi.organizations.uploadCertificate(
              '5a2a307be93a2f00129ea035',
              cerFileStream,
              keyFileStream,
              'CONTRASEÑA_DEL_CERTIFICADO'
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");


            var cerFileStream = File.OpenRead(@"C:\path\to\your\CSD.cer");

            var keyFileStream = File.OpenRead(@"C:\path\to\your\CSD.key");


            var organization = await
            facturapi.Organization.UploadCertificateAsync(
              "5a2a307be93a2f00129ea035",
              cerFileStream,
              keyFileStream,
              "CONTRASEÑA_DEL_CERTIFICADO"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.io.File;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().uploadCertificate(
                    "org_123",
              new File("certificate.cer"),
              new File("certificate.key"),
                    "secret"
                  );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");

            $organization = $facturapi->Organizations->uploadCertificate(
              "5a2a307be93a2f00129ea035",
              [
                "cer" => "/path/to/CSD.cer",
                "key" => "/path/to/CSD.key",
                "password" => "mYp455w0rD1553cUr3!"
              ]
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationUploadCerts'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: deleteOrganizationCertificate
      tags:
        - organization
      summary: Eliminar certificados (CSD)
      description: >
        Elimina los certificados (CSD) de tu organización. 


        Esto no afecta a las facturas ya emitidas, pero no podrás emitir nuevas
        facturas hasta que subas nuevos certificados.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/certificate
            \
              -X DELETE \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY');


            const organization = await
            facturapi.organizations.deleteCertificate(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var organization = await
            facturapi.Organization.DeleteCertificateAsync("5a2a307be93a2f00129ea035");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().deleteCertificate(
                  "org_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_user_API_KEY");


            $organization =
            $facturapi->Organizations->deleteCertificate("5a2a307be93a2f00129ea035");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationDeleteCerts'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/fiel:
    put:
      operationId: uploadOrganizationFiel
      tags:
        - organization
      summary: Subir certificado FIEL
      description: |
        Sube los archivos de la e.firma (FIEL) de la organización.

        La e.firma (FIEL) no es necesaria para crear CFDI. Para timbrar CFDI
        solo necesitas cargar el Certificado de Sello Digital (CSD). La FIEL es
        necesaria para utilizar la descarga masiva de CFDI.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/organizations/me/fiel \
              -X PUT \
              -H "Authorization: Bearer sk_live_API_KEY" \
              -H "Content-Type: multipart/form-data" \
              -F 'cer=@/path/to/your/FIEL.cer' \
              -F 'key=@/path/to/your/FIEL.key' \
              -F 'password=CONTRASEÑA_DEL_CERTIFICADO'
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: >-
            ID de la organización. También puedes usar `me` con la Live Secret
            Key de la organización.
      requestBody:
        $ref: '#/components/requestBodies/OrganizationUploadFiel'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/logo:
    put:
      operationId: uploadOrganizationLogo
      tags:
        - organization
      summary: Subir logotipo
      description: |
        Sube el logotipo de la organización que será colocado en el PDF y en
        los correos que se envían al cliente con la factura adjunta.

        El archivo debe ser una imagen en formato JPG o PNG y tener un tamaño
        no mayor a 500 KB. Las dimensiones recomendadas son 800 × 500px.

        Si la organización ya tiene un logotipo, esta llamada reemplaza el
        logotipo anterior.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/logo
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: multipart/form-data" \
              -F 'file=@/path/to/your/logo.jpg'
        - lang: JavaScript
          label: Node.js
          source: |
            import fs from 'fs';
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const fileStream = fs.createReadStream('/path/to/your/logo.jpg');
            const organization = await facturapi.organizations.uploadLogo(
              '5a2a307be93a2f00129ea035',
              fileStream
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var fileStream = File.OpenRead(@"C:\path\to\your\logo.jpg");

            var organization = await facturapi.Organization.UploadLogoAsync(
              "5a2a307be93a2f00129ea035",
              fileStream
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.io.File;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().uploadLogo(
                  "org_123",
            new File("logo.png")
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");

            $organization = $facturapi->Organizations->uploadLogo(
              "5a2a307be93a2f00129ea035",
              "/path/to/logo.jpg"
            ));
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationUploadLogo'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/customization:
    put:
      operationId: editOrganizationCustomization
      tags:
        - organization
      summary: Editar personalización
      description: >
        Actualiza la información relacionada con la identidad o branding de la
        organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/customization
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "color": "#BADA55",
                    "pdf_extra": {
                      "codes": false,
                      "product_key": true
                    }
                }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY');


            const organization = await
            facturapi.organizations.updateCustomization(
              '5a2a307be93a2f00129ea035',
              {
                color: '#BADA55',
                pdf_extra: {
                  codes: false,
                  product_key: true
                }
              }
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");


            var organization = await
            facturapi.Organization.UpdateCustomizationAsync(
              "5a2a307be93a2f00129ea035",
              new Dictionary<string, object>
              {
                ["color"] = "#BADA55",
                ["pdf_extra"] = new Dictionary<string, object>
                {
                  ["codes"] = false,
                  ["product_key"] = true
                }
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().updateCustomization(
                "org_123",
                Map.of(
                    "website", "https://facturapi.io"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");

            $organization = $facturapi->Organizations->updateCustomization(
              "5a2a307be93a2f00129ea035",
              [
                "color" => "#BADA55",
                "pdf_extra" => [
                  "codes" => false,
                  "product_key" => true
                ]
              ]
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationEditCustomization'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/receipts:
    put:
      operationId: editOrganizationReceiptsSettings
      tags:
        - organization
      summary: Editar config. recibos
      description: |
        Actualiza la configuración de recibos de la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/receipts
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "invoicing_period": "month",
                    "duration_days": 14,
                    "next_folio_number": 100
                }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY');


            const organization = await
            facturapi.organizations.updateReceiptSettings(
              '5a2a307be93a2f00129ea035',
              {
                invoicing_period: "month",
                duration_days: 14,
                next_folio_number: 100
              }
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");


            var organization = await
            facturapi.Organization.UpdateReceiptSettingsAsync(
              "5a2a307be93a2f00129ea035",
              new Dictionary<string, object>
              {
                ["invoicing_period"] = "month",
                ["duration_days"] = 14,
                ["next_folio_number"] = 100
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().updateReceiptSettings(
                "org_123",
                Map.of(
                    "color", "#4786FF"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");

            $organization = $facturapi->Organizations->updateReceiptSettings(
              "5a2a307be93a2f00129ea035",
              [
                "invoicing_period" => "month",
                "duration_days" => 14,
                "next_folio_number" => 100
              ]
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationEditReceiptsSettings'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/self-invoice:
    put:
      operationId: editOrganizationSelfInvoiceSettings
      tags:
        - organization
      summary: Editar config. autofactura
      description: |
        Actualiza la configuración del portal de autofactura de la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/self-invoice
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "allowed_cfdi_uses": ["G01", "G03"],
                    "apply_resico_isr": false,
                    "support_email": "support@dundermifflin.com"
                }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY');


            const organization = await
            facturapi.organizations.updateSelfInvoiceSettings(
              '5a2a307be93a2f00129ea035',
              {
                allowed_cfdi_uses: ["G01", "G03"],
                apply_resico_isr: false,
                support_email: "support@dundermifflin.com"
              }
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");


            var organization = await
            facturapi.Organization.UpdateSelfInvoiceSettingsAsync(
              "5a2a307be93a2f00129ea035",
              new Dictionary<string, object>
              {
                ["allowed_cfdi_uses"] = new List<string> { "G01", "G03" },
                ["apply_resico_isr"] = false,
                ["support_email"] = "support@dundermifflin.com"
              }
            );
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var organization =
            facturapi.organizations().updateSelfInvoiceSettings("org_123",
            Map.of(
                    "enabled", true
                  ));
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_user_API_KEY");


            $organization =
            $facturapi->Organizations->updateSelfInvoiceSettings(
              "5a2a307be93a2f00129ea035",
              [
                "allowed_cfdi_uses" => ["G01", "G03"],
                "apply_resico_isr" => false,
                "support_email" => "support@dundermifflin.com"
              ]
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationEditSelfInvoiceSettings'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/domain-check:
    get:
      operationId: checkDomainAvailability
      tags:
        - organization
      summary: Revisar dominio disponible
      description: >-
        Revisa si un identificador está disponible para elegir como dominio para
        el portal de autofactura.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/domain-check?domain=empresa-demo
            \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY');


            const organization = await
            facturapi.organizations.checkDomainIsAvailable({
              domain: 'empresa-demo'
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var organization = await
            facturapi.Organization.CheckDomainIsAvailableAsync(
              new Dictionary<string, object>
              {
                ["domain"] = "empresa-demo"
              }
            );
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var availability =
            facturapi.organizations().checkDomainAvailability(
                  Map.of(
                      "domain", "facturapi"
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $organization = $facturapi->Organizations->checkDomainAvailability(
              ["domain" => "empresa-demo"]
            );
      parameters:
        - in: query
          name: domain
          required: true
          schema:
            $ref: '#/components/schemas/DomainField'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Información de disponibilidad de dominio
          content:
            application/json:
              schema:
                type: object
                required:
                  - available
                properties:
                  available:
                    type: boolean
                    example: true
                    description: Indica si el dominio está diponible
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/domain:
    put:
      operationId: editOrganizationDomain
      tags:
        - organization
      summary: Elegir dominio de autofactura
      description: |
        Elige el dominio que utilizará esta organización en su micrositio de
        autofactura. Una vez elegido el dominio, deberás ponerte en contacto
        con nosotros si necesitas cambiarlo.

        El dominio que elijas será el que aparecerá en el campo
        `self_invoice_url` al crear un nuevo recibo, de la siguiente manera:

        `https://factura.space/{DOMAIN}/{RECEIPT_KEY}`
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/domain
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "domain": "empresa-demo"
                }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const organization = await facturapi.organizations.updateDomain(
              '5a2a307be93a2f00129ea035',
              { domain: 'empresa-demo' }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var organization = await facturapi.Organization.UpdateDomainAsync(
              "5a2a307be93a2f00129ea035",
              new Dictionary<string, object>
              {
                ["domain"] = "empresa-demo"
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().updateDomain(
                "org_123",
                Map.of(
                    "domain", "facturapi"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");

            $organization = $facturapi->Organizations->updateDomain(
              "5a2a307be93a2f00129ea035",
              [ "domain" => "empresa-demo" ]
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationEditDomain'
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` modificado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}:
    get:
      operationId: getOrganization
      tags:
        - organization
      summary: Obtener organización por ID
      description: Regresa el objeto 'Organization' relacionado al `id` especificado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035 \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');
            const organization = await facturapi.organizations.retrieve(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var organization = await facturapi.Organization.RetrieveAsync(
              "5a2a307be93a2f00129ea035"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().retrieve(
                  "org_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_user_API_KEY");

            $organization =
            $facturapi->Organizations->retrieve("5a2a307be93a2f00129ea035");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: deleteOrganization
      tags:
        - organization
      summary: Eliminar organización
      description: |
        Elimina la organización de tu cuenta de Facturapi. Una vez eliminada,
        ya no podrás acceder a sus recursos, tales como clientes, productos,
        facturas, recibos o retenciones.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035 \
              -X DELETE \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');
            const organization = await facturapi.organizations.del(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var organization = await facturapi.Organization.DeleteAsync(
              "5a2a307be93a2f00129ea035"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().delete(
                  "org_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $organization = $facturapi->Organizations->delete(
              "5a2a307be93a2f00129ea035"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID del objeto a eliminar
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Organization` eliminado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/apikeys/test:
    get:
      operationId: getTestApiKey
      tags:
        - organization
      summary: Obtener Test Api Key
      description: Obtiene la llave secreta de ambiente Test de la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/apikeys/test
            \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const apiKeys = await facturapi.organizations.getTestApiKey(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var apiKeys = await facturapi.Organization.GetTestApiKeyAsync(
              "5a2a307be93a2f00129ea035"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var apiKey = facturapi.organizations().getTestApiKey(
                  "org_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $organization = $facturapi->Organizations->getTestApiKey(
              "5a2a307be93a2f00129ea035"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Test API Key
          content:
            application/json:
              schema:
                type: string
                example: sk_test_API_KEY
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: renewTestApiKey
      tags:
        - organization
      summary: Renovar Test API Key
      description: >
        Renueva la llave secreta de ambiente Test de la organización e invalida
        inmediatamente la anterior.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/apikeys/test
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const newTestApiKey = await facturapi.organizations.renewTestApiKey(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var newTestApiKey = await
            facturapi.Organization.RenewTestApiKeyAsync(
              "5a2a307be93a2f00129ea035"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var apiKey = facturapi.organizations().renewTestApiKey(
                  "org_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $new_test_api_key = $facturapi->Organizations->renewTestApiKey(
              "5a2a307be93a2f00129ea035"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Test API Key
          content:
            application/json:
              schema:
                type: string
                example: sk_test_API_KEY
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/apikeys/live:
    get:
      operationId: listLiveApiKeys
      tags:
        - organization
      summary: Listar Live API Keys
      description: |
        Listar llaves secretas de ambiente Live de la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/apikeys/live
            \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY');


            const listLiveApiKeys = await
            facturapi.organizations.listLiveApiKeys(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var listLiveApiKeys = await
            facturapi.Organization.ListLiveApiKeysAsync(
              "5a2a307be93a2f00129ea035"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var apiKeys = facturapi.organizations().listLiveApiKeys(
                  "org_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $list_live_api_keys = $facturapi->Organizations->listLiveApiKeys(
              "5a2a307be93a2f00129ea035"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Live API Key
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    first_12:
                      type: string
                      description: Primeros 12 caracteres de la llave secreta
                    created_at:
                      type: string
                      format: date-time
                      description: Fecha de creación de la llave secreta
                    id:
                      type: string
                      description: ID de la llave secreta
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: renewLiveApiKey
      tags:
        - organization
      summary: Crear Live API Key
      description: >
        Genera una nueva llave secreta de ambiente Live de la organización.

        Esta operación no invalida las llaves generadas previamente. El endpoint
        usa `PUT`

        por compatibilidad histórica, pero su comportamiento es crear una nueva
        llave.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/apikeys/live
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const newLiveApiKey = await facturapi.organizations.renewLiveApiKey(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var newLiveApiKey = await
            facturapi.Organization.RenewLiveApiKeyAsync(
              "5a2a307be93a2f00129ea035"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var apiKey = facturapi.organizations().renewLiveApiKey(
                  "org_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $new_live_api_key = $facturapi->Organizations->renewLiveApiKey(
              "5a2a307be93a2f00129ea035"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Live API Key
          content:
            application/json:
              schema:
                type: string
                example: sk_live_API_KEY
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/apikeys/live/{id}:
    delete:
      operationId: deleteLiveApiKey
      tags:
        - organization
      summary: Revocar Live API Key
      description: |
        Revocar Live Api Key de tu organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/apikeys/live/66f2ec798ca5a9b80c97db71
            \
              -X DELETE \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const hasDeleted = await facturapi.organizations.deleteLiveApiKey(
              '5a2a307be93a2f00129ea035',
              '66f2ec798ca5a9b80c97db71'
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var hasDeleted = await facturapi.Organization.DeleteLiveApiKeyAsync(
              "5a2a307be93a2f00129ea035",
              "66f2ec798ca5a9b80c97db71"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var apiKeys = facturapi.organizations().deleteLiveApiKey(
                  "org_123",
                  "key_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $has_deleted = $facturapi->Organizations->deleteLiveApiKey(
              "5a2a307be93a2f00129ea035",
              "66f2ec798ca5a9b80c97db71"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: id
          schema:
            type: string
          required: true
          description: ID de la llave secreta a eliminar
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Live API Key
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    first_12:
                      type: string
                      description: Primeros 12 caracteres de la llave secreta
                    created_at:
                      type: string
                      format: date-time
                      description: Fecha de creación de la llave secreta
                    id:
                      type: string
                      description: ID de la llave secreta
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/series-group:
    get:
      operationId: getSeriesGroup
      tags:
        - organization
      summary: Listado de series
      description: >
        Listado de series creadas para la personalización de organización. La
        cual lleva control de foliaje para cada tipo de factura si está asignada
        en las personalización de organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/series-group
            \
              -X GET \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const seriesList = await facturapi.organizations.getSeries(
              '5a2a307be93a2f00129ea035'
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var seriesList = await facturapi.Organization.ListSeriesAsync(
              "5a2a307be93a2f00129ea035"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var series = facturapi.organizations().listSeriesGroup(
                  "org_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $seriesList = $facturapi->Organizations->getSeries(
              "5a2a307be93a2f00129ea035"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Listado de objetos `Series` creadas previamente
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/OrganizationSeriesGroup'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    post:
      operationId: createSeriesGroup
      tags:
        - organization
      summary: Crear serie
      description: >
        Crea una nueva serie de folios para la organización.

        Las series son útiles para llevar un control de los folios emitidos para
        cada tipo de factura.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/series-group
            \
              -X POST \
              -H "Content-Type: application/json" \
              -d '{
                    "series": "New",
                    "next_folio": 1,
                    "next_folio_test": 1
                  }'
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const newSeries = await facturapi.organizations.createSeries(
              '5a2a307be93a2f00129ea035',
              {
                series: 'New',
                next_folio: 1,
                next_folio_test: 1
              }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var newSeries = await facturapi.Organization.CreateSeriesAsync(
              "5a2a307be93a2f00129ea035",
              [
                "series" => "New",
                "next_folio" => 1,
                "next_folio_test" => 1
              ]
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var series = facturapi.organizations().createSeriesGroup(
                "org_123",
                Map.of(
                    "name", "A"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $newSeries = $facturapi->Organizations->createSeries(
              "5a2a307be93a2f00129ea035",
              {
                    "series": "New",
                    "next_folio": 1,
                    "next_folio_test": 1
              }
            );
      requestBody:
        $ref: '#/components/requestBodies/OrganizationSeriesCreate'
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Nuevo objeto de la `Serie` creada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationSeriesGroup'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/series-group/default-series:
    put:
      operationId: updateDefaultSeries
      tags:
        - organization
      summary: Establecer serie predeterminada
      description: |
        Asigna una serie predeterminada para el tipo de comprobante indicado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/series-group/default-series
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "type": "I",
                    "series": "A"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const result = await facturapi.organizations.updateDefaultSeries(
              '5a2a307be93a2f00129ea035',
              {
                type: 'I',
                series: 'A'
              }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var result = await facturapi.Organization.UpdateDefaultSeriesAsync(
              "5a2a307be93a2f00129ea035",
              new Dictionary<string, object>
              {
                ["type"] = "I",
                ["series"] = "A"
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.organizations().updateDefaultSeries(
                "org_123",
                Map.of(
                    "type", "I",
                    "series", "A"
                )
            );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $result = $facturapi->Organizations->updateDefaultSeries(
              "5a2a307be93a2f00129ea035",
              [
                "type" => "I",
                "series" => "A"
              ]
            );
      requestBody:
        $ref: '#/components/requestBodies/OrganizationSeriesDefault'
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Serie predeterminada actualizada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OkResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/series-group/{series_name}:
    put:
      operationId: updateSeriesGroup
      tags:
        - organization
      summary: Editar serie
      description: >
        Edita el número de foliaje de la serie en ambientes Test y Live de la
        organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/series-group/New
            \
              -X PUT \
              -H "Authorization: Bearer sk_user_API_KEY"
              -H "Content-Type: application/json" \
              -d '{
                  "next_folio": 1,
                  "next_folio_test": 1
                }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const updatedSeries = await facturapi.organizations.updateSeries(
              '5a2a307be93a2f00129ea035',
              'New',
              [
                "next_folio" => 1,
                "next_folio_test" => 1
              ]
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var updatedSeries = await facturapi.Organization.UpdateSeriesAsync(
              "5a2a307be93a2f00129ea035",
              "New",
              {
                "next_folio": 1,
                "next_folio_test": 1
              }
            );
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var series = facturapi.organizations().updateSeriesGroup("org_123",
            "A", Map.of(
                    "next_folio", 1
                  ));
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $updatedSeries = $facturapi->Organizations->updateSeries(
            "5a2a307be93a2f00129ea035",
              "New",
              {
                "next_folio": 1,
                "next_folio_test": 1
              }
            );
      requestBody:
        $ref: '#/components/requestBodies/OrganizationSeriesUpdate'
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: series_name
          schema:
            type: string
          required: true
          description: Nombre de la serie
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Serie` editada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationSeriesGroup'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: deleteSeriesGroup
      tags:
        - organization
      summary: Eliminar serie
      description: |
        Elimina la serie previamente creada
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/organizations/5a2a307be93a2f00129ea035/series-group/New
            \
              -X DELETE \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_user_API_KEY');

            const deletedSeries = await facturapi.organizations.deleteSeries(
              '5a2a307be93a2f00129ea035',
              'New'
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var deletedSeries = await facturapi.Organization.DeleteSeriesAsync(
              "5a2a307be93a2f00129ea035",
              "New"
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var series = facturapi.organizations().deleteSeriesGroup(
                  "org_123",
                  "A"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_user_API_KEY");
            $deletedSeries = $facturapi->Organizations->deleteSeries(
            "5a2a307be93a2f00129ea035",
            "New"
            );
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: series_name
          schema:
            type: string
          required: true
          description: Nombre de la serie
      security:
        - SecretLiveKey: []
        - SecretUserKey: []
      responses:
        '200':
          description: Objeto `Serie` eliminado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationSeriesGroup'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team:
    get:
      operationId: getOrganizationTeam
      tags:
        - organization_access
      summary: Listar usuarios con acceso a organización
      description: >-
        Regresa un arreglo con los usuarios que actualmente tienen acceso a la
        organización, incluyendo al propietario. Este endpoint no está paginado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl "https://www.facturapi.io/v2/organizations/ORG_ID/team" \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi';

            const facturapi = new Facturapi('sk_test_API_KEY');

            const accessList = await
            facturapi.organizations.listTeamAccess('ORG_ID');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var accessList = await
            facturapi.Organization.ListTeamAccessAsync("ORG_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var team = facturapi.organizations().listTeamAccess(
                  "org_123"
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $accessList = $facturapi->Organizations->listTeamAccess("ORG_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: >-
            Lista de accesos de usuarios dentro de la organización, incluyendo
            accesos implícitos como el del propietario
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationUserAccessList'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/invites:
    post:
      operationId: createOrganizationTeamInvite
      tags:
        - organization_access
      summary: Invitar usuario a organización
      description: >
        Crea o actualiza una invitación de usuario. Por defecto, el acceso es de
        administrador con permisos completos; para limitarlo, crea un rol y
        envía su ID en `role`.


        Cada organización puede invitar a un usuario sin costo adicional. A
        partir del segundo usuario invitado, cada usuario adicional tendrá un
        costo mensual. Este cargo se aplica automáticamente cuando el usuario
        acepta la invitación.

        Puedes consultar el precio vigente en nuestra [página de
        precios](https://www.facturapi.io/pricing).
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl "https://www.facturapi.io/v2/organizations/ORG_ID/team/invites"
            \
              -X POST \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "email": "alex@example.com",
                "role": "ROLE_ID"
              }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const invite = await
            facturapi.organizations.inviteUserToTeam('ORG_ID', {
              email: 'alex@example.com',
              role: 'ROLE_ID',
            })
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
            var invite = await facturapi.Organization.InviteUserToTeamAsync(
              "ORG_ID",
              new Dictionary<string, object>
              {
                ["email"] = "alex@example.com",
                ["role"] = "ROLE_ID"
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invite = facturapi.organizations().inviteUserToTeam(
                "org_123",
                Map.of(
                    "email", "new.user@example.com",
                    "role", "admin"
                )
            );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $invite = $facturapi->Organizations->inviteUserToTeam("ORG_ID", [
              "email" => "alex@example.com",
              "role" => "ROLE_ID"
            ]);
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationInviteCreate'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Invitación creada o actualizada para el correo solicitado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationInvite'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listOrganizationTeamInvites
      tags:
        - organization_access
      summary: Listar invitaciones enviadas
      description: Regresa invitaciones enviadas desde la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl "https://www.facturapi.io/v2/organizations/ORG_ID/team/invites"
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const invites = await
            facturapi.organizations.listSentTeamInvites('ORG_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var invites = await
            facturapi.Organization.ListSentTeamInvitesAsync("ORG_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var invites = facturapi.organizations().listSentTeamInvites(
                  "org_123"
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $invites = $facturapi->Organizations->listSentTeamInvites("ORG_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Lista de invitaciones enviadas y aún vigentes para la organización
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationInviteList'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/{access_id}:
    get:
      operationId: getOrganizationTeamUser
      tags:
        - organization_access
      summary: Obtener acceso de usuario
      description: >-
        Regresa el detalle del acceso del usuario dentro de la organización
        usando su `access_id`, incluyendo accesos implícitos como el del
        propietario.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/ACCESS_ID" \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const access = await
            facturapi.organizations.retrieveTeamAccess('ORG_ID', 'ACCESS_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var access = await
            facturapi.Organization.RetrieveTeamAccessAsync("ORG_ID",
            "ACCESS_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var access = facturapi.organizations().retrieveTeamAccess(
                  "org_123",
                  "access_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $access = $facturapi->Organizations->retrieveTeamAccess("ORG_ID",
            "ACCESS_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: access_id
          schema:
            type: string
          required: true
          description: ID del acceso
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: >-
            Detalle del acceso del usuario dentro de la organización, incluyendo
            accesos implícitos como el del propietario
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationUserAccess'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: removeOrganizationUserAccess
      tags:
        - organization_access
      summary: Eliminar usuario con acceso
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/ACCESS_ID" \
              -X DELETE \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.organizations.removeTeamAccess('ORG_ID', 'ACCESS_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.Organization.RemoveTeamAccessAsync("ORG_ID", "ACCESS_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.organizations().removeTeamAccess(
                  "org_123",
                  "access_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $result = $facturapi->Organizations->removeTeamAccess("ORG_ID",
            "ACCESS_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: access_id
          schema:
            type: string
          required: true
          description: ID del acceso
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Usuario removido de la organización
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OkResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/invites/{invite_key}:
    delete:
      operationId: deleteOrganizationTeamInvite
      tags:
        - organization_access
      summary: Cancelar invitación enviada
      description: Elimina una invitación pendiente de la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/invites/INVITE_ID"
            \
              -X DELETE \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.organizations.cancelTeamInvite('ORG_ID', 'INVITE_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.Organization.CancelTeamInviteAsync("ORG_ID", "INVITE_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.organizations().cancelTeamInvite(
                  "org_123",
                  "invite_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $result = $facturapi->Organizations->cancelTeamInvite("ORG_ID",
            "INVITE_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: invite_key
          schema:
            type: string
          required: true
          description: Clave pública de la invitación.
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Invitación cancelada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OkResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/invites/pending:
    get:
      operationId: listPendingOrganizationInvites
      tags:
        - organization_access
      summary: Listar invitaciones recibidas
      description: Regresa las invitaciones recibidas para el usuario autenticado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl "https://www.facturapi.io/v2/organizations/invites/pending" \
              -H "Authorization: Bearer sk_user_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY')

            const pendingInvites = await
            facturapi.organizations.listReceivedTeamInvites()
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_user_API_KEY");

            var pendingInvites = await
            facturapi.Organization.ListReceivedTeamInvitesAsync();
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var organization = facturapi.organizations().retrieve(
                  "org_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_user_API_KEY");

            $pendingInvites =
            $facturapi->Organizations->listReceivedTeamInvites();
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Lista de invitaciones recibidas por el usuario autenticado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationInviteList'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/invites/{invite_key}/response:
    post:
      operationId: respondOrganizationInvite
      tags:
        - organization_access
      summary: Responder invitación
      description: Acepta o rechaza una invitación usando su `invite_key`.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/invites/INVITE_ID/response"
            \
              -X POST \
              -H "Authorization: Bearer sk_user_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "accept": true
              }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_user_API_KEY')

            const result = await
            facturapi.organizations.respondTeamInvite('INVITE_ID', {
              accept: true,
            })
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_user_API_KEY");
            var result = await facturapi.Organization.RespondTeamInviteAsync(
              "INVITE_ID",
              new Dictionary<string, object>
              {
                ["accept"] = true
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.organizations().respondTeamInvite(
                "invite_123",
                Map.of(
                    "response", "accepted"
                )
            );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_user_API_KEY");

            $result = $facturapi->Organizations->respondTeamInvite("INVITE_ID",
            [
              "accept" => true
            ]);
      parameters:
        - in: path
          name: invite_key
          schema:
            type: string
          required: true
          description: Clave pública de la invitación.
      requestBody:
        $ref: '#/components/requestBodies/OrganizationInviteRespond'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Invitación aceptada o rechazada exitosamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OkResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/roles:
    get:
      operationId: listOrganizationPermissionRoles
      tags:
        - organization_access
      summary: Listar roles de organización
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl "https://www.facturapi.io/v2/organizations/ORG_ID/team/roles" \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY')
            const roles = await facturapi.organizations.listTeamRoles('ORG_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var roles = await
            facturapi.Organization.ListTeamRolesAsync("ORG_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var roles = facturapi.organizations().listTeamRoles(
                  "org_123"
                );
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $roles = $facturapi->Organizations->listTeamRoles("ORG_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Lista de roles
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationPermissionRoleList'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    post:
      operationId: createOrganizationPermissionRole
      tags:
        - organization_access
      summary: Crear rol de organización
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl "https://www.facturapi.io/v2/organizations/ORG_ID/team/roles" \
              -X POST \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "name": "Billing analyst"
              }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const role = await facturapi.organizations.createTeamRole('ORG_ID',
            {
              name: 'Billing analyst',
            })
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
            var role = await facturapi.Organization.CreateTeamRoleAsync(
              "ORG_ID",
              new Dictionary<string, object>
              {
                ["name"] = "Billing analyst"
              }
            );
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var role = facturapi.organizations().createTeamRole("org_123",
            Map.of(
                    "name", "Contabilidad",
                    "operations", List.of("createInvoice", "cancelInvoice")
                  ));
        - lang: PHP
          label: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $role = $facturapi->Organizations->createTeamRole("ORG_ID", [
              "name" => "Billing analyst"
            ]);
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      requestBody:
        $ref: '#/components/requestBodies/OrganizationPermissionRoleCreate'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Rol creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationPermissionRole'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/roles/templates:
    get:
      operationId: listOrganizationPermissionRoleTemplates
      tags:
        - organization_access
      summary: Listar plantillas de roles
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/roles/templates"
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const templates = await
            facturapi.organizations.listTeamRoleTemplates('ORG_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var templates = await
            facturapi.Organization.ListTeamRoleTemplatesAsync("ORG_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var templates = facturapi.organizations().listTeamRoleTemplates(
                  "org_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $templates =
            $facturapi->Organizations->listTeamRoleTemplates("ORG_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Plantillas disponibles
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationPermissionRoleTemplateList'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/roles/operations:
    get:
      operationId: listOrganizationPermissionOperations
      tags:
        - organization_access
      summary: Listar operaciones de permisos
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/roles/operations"
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const operations = await
            facturapi.organizations.listTeamRoleOperations('ORG_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var operations = await
            facturapi.Organization.ListTeamRoleOperationsAsync("ORG_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var operations = facturapi.organizations().listTeamRoleOperations(
                  "org_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $operations =
            $facturapi->Organizations->listTeamRoleOperations("ORG_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Lista de códigos de operación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationPermissionOperationList'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/roles/{role_id}:
    get:
      operationId: getOrganizationPermissionRole
      tags:
        - organization_access
      summary: Obtener rol de organización
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/roles/ROLE_ID"
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const role = await
            facturapi.organizations.retrieveTeamRole('ORG_ID', 'ROLE_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var role = await
            facturapi.Organization.RetrieveTeamRoleAsync("ORG_ID", "ROLE_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var role = facturapi.organizations().retrieveTeamRole(
                  "org_123",
                  "role_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $role = $facturapi->Organizations->retrieveTeamRole("ORG_ID",
            "ROLE_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: role_id
          schema:
            type: string
          required: true
          description: ID del rol
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Detalle del rol
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationPermissionRole'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: updateOrganizationPermissionRole
      tags:
        - organization_access
      summary: Actualizar rol de organización
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/roles/ROLE_ID"
            \
              -X PUT \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "name": "Senior billing analyst"
              }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const role = await facturapi.organizations.updateTeamRole('ORG_ID',
            'ROLE_ID', {
              name: 'Senior billing analyst',
            })
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
            var role = await facturapi.Organization.UpdateTeamRoleAsync(
              "ORG_ID",
              "ROLE_ID",
              new Dictionary<string, object>
              {
                ["name"] = "Senior billing analyst"
              }
            );
        - lang: Java
          label: Java
          source: >
            import io.facturapi.Facturapi;

            import java.util.List;

            import java.util.Map;


            Facturapi facturapi = new Facturapi("sk_test_API_KEY");


            var role = facturapi.organizations().updateTeamRole("org_123",
            "role_123", Map.of(
                    "name", "Contabilidad",
                    "operations", List.of("createInvoice", "cancelInvoice")
                  ));
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $role = $facturapi->Organizations->updateTeamRole("ORG_ID",
            "ROLE_ID", [
              "name" => "Senior billing analyst"
            ]);
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: role_id
          schema:
            type: string
          required: true
          description: ID del rol
      requestBody:
        $ref: '#/components/requestBodies/OrganizationPermissionRoleUpdate'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Rol actualizado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationPermissionRole'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: deleteOrganizationPermissionRole
      tags:
        - organization_access
      summary: Eliminar rol de organización
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/roles/ROLE_ID"
            \
              -X DELETE \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const result = await
            facturapi.organizations.deleteTeamRole('ORG_ID', 'ROLE_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var result = await
            facturapi.Organization.DeleteTeamRoleAsync("ORG_ID", "ROLE_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var response = facturapi.organizations().deleteTeamRole(
                  "org_123",
                  "role_123"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $result = $facturapi->Organizations->deleteTeamRole("ORG_ID",
            "ROLE_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: role_id
          schema:
            type: string
          required: true
          description: ID del rol
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Rol eliminado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OkResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /organizations/{organization_id}/team/{access_id}/role:
    put:
      operationId: updateOrganizationTeamUserRole
      tags:
        - organization_access
      summary: Reasignar rol a usuario
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            "https://www.facturapi.io/v2/organizations/ORG_ID/team/ACCESS_ID/role"
            \
              -X PUT \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "role": "ROLE_ID"
              }'
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY')

            const access = await
            facturapi.organizations.updateTeamAccessRole('ORG_ID', 'ACCESS_ID',
            'ROLE_ID')
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var access = await
            facturapi.Organization.UpdateTeamAccessRoleAsync("ORG_ID",
            "ACCESS_ID", "ROLE_ID");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var access = facturapi.organizations().updateTeamAccessRole(
                  "org_123",
                  "access_123",
                  "admin"
                );
        - lang: PHP
          label: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $access = $facturapi->Organizations->updateTeamAccessRole("ORG_ID",
            "ACCESS_ID", "ROLE_ID");
      parameters:
        - in: path
          name: organization_id
          schema:
            type: string
          required: true
          description: ID de la organización
        - in: path
          name: access_id
          schema:
            type: string
          required: true
          description: ID del acceso
      requestBody:
        $ref: '#/components/requestBodies/OrganizationUserAccessRoleUpdate'
      security:
        - SecretUserKey: []
      responses:
        '200':
          description: Acceso del usuario actualizado con el nuevo rol
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrganizationUserAccess'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /webhooks:
    post:
      operationId: createWebhook
      tags:
        - webhooks
      summary: Crear Webhook
      description: >
        Registra un nuevo webhook en tu organización de Facturapi.

        Utiliza esta llamada para recibir notificaciones de eventos asíncronos a
        la API. 

        Los webhooks de ambiente test y ambiente live son independientes.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/webhooks \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "enabled_events": ["receipt.self_invoice_complete"],
                    "url": "http://my-website.com/my/webhook"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const customer = await facturapi.webhooks.create({
                    "enabled_events": ["receipt.self_invoice_complete"],
                    "url": "http://my-website.com/my/webhook"
                  });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await facturapi.Webhook.CreateAsync(new
            Dictionary<string, object>

            {
              ["enabled_events"] = new Dictionary<string, object>["receipt.self_invoice_complete"],
              ["url"] = "http://my-website.com/my/webhook"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var webhook = facturapi.webhooks().create(
                Map.of(
                    "url", "https://example.com/webhooks",
                    "triggers", List.of("invoice.created")
                  ));
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $customer = $facturapi->Webhooks->create([
              "enabled_events" => ["receipt.self_invoice_complete"],
              "url" => "http://my-website.com/my/webhook"
            ]);
      requestBody:
        $ref: '#/components/requestBodies/WebhookCreate'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Un objeto `Webhook` con la misma información ya existía
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Webhook'
        '201':
          description: Nuevo objeto `Webhook` creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Webhook'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    get:
      operationId: listWebhooks
      tags:
        - webhooks
      summary: Listar webhooks
      description: Retorna una lista de webhooks creados previamente para la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/webhooks \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -G \
              -d 'page=1'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const searchResult = await facturapi.webhooks.list({
              limit: 0,
              page: 1
            });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var searchResult = await facturapi.Webhook.ListAsync(new
            Dictionary<string, object>

            {
              ["page"] = 1
              ["limit"] = 0,
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var searchResult = facturapi.webhooks().list(
                  Map.of(
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $searchResult = $facturapi->Webhooks->all([
              "page" => 1
            ]);
      parameters:
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /webhooks/{webhook_id}:
    get:
      operationId: getWebhook
      tags:
        - webhooks
      summary: Obtener webhook por ID
      description: Regresa el objeto "Webhook" relacionado al `id` especificado.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/webhooks/590ce6c56d04f840aa8438af \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const customer = await
            facturapi.webhooks.retrieve('590ce6c56d04f840aa8438af');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await
            facturapi.Webhook.RetrieveAsync("590ce6c56d04f840aa8438af");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var webhook = facturapi.webhooks().retrieve(
                  "whk_123"
                );
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $customer = $facturapi->Webhooks->retrieve(
            "5a3ee743f508333611ad6b3c" );
      parameters:
        - in: path
          name: webhook_id
          schema:
            type: string
          required: true
          description: ID del objeto a obtener
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Webhook`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Webhook'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    put:
      operationId: editWebhook
      tags:
        - webhooks
      summary: Editar webhook
      description: >-
        Actualiza la información de un Webhook existente con los parámetros que
        envíes en la petición.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/webhooks/590ce6c56d04f840aa8438af \
              -X PUT \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "status": "disabled",
                    "enabled_events": ["receipt.self_invoice_complete"]
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const customer = await facturapi.webhooks.update(
              '590ce6c56d04f840aa8438af',
              {
                "status": "disabled",
                "enabled_events": ["receipt.self_invoice_complete"]
              }
            );
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");
            var customer = await facturapi.Webhook.UpdateAsync(
              "590ce6c56d04f840aa8438af",
              new Dictionary<string, object>
              {
                ["status"] = "disabled",
                ["address"] = new Dictionary<string>["receipt.self_invoice_complete"]
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var webhook = facturapi.webhooks().update("whk_123", Map.of(
                    "url", "https://example.com/webhooks",
                    "triggers", List.of("invoice.created")
                  ));
        - lang: PHP
          source: >
            $facturapi = new Facturapi("sk_test_API_KEY");

            $customer = $facturapi->Webhooks->update("590ce6c56d04f840aa8438af",
            [
                "status" => "disabled",
                "address" => ["receipt.self_invoice_complete"]
              ]
            ]);
      parameters:
        - in: path
          name: webhook_id
          schema:
            type: string
          required: true
          description: ID del objeto a editar
      requestBody:
        $ref: '#/components/requestBodies/WebhookEdit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Webhook` editado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Webhook'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
    delete:
      operationId: deleteWebhook
      tags:
        - webhooks
      summary: Eliminar Webhook
      description: Elimina el webhook pertenciente a la organización.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/webhooks/590ce6c56d04f840aa8438af \
              -X DELETE \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');

            const removedCustomer = await
            facturapi.webhooks.del('590ce6c56d04f840aa8438af');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await
            facturapi.Webhook.DeleteAsync("590ce6c56d04f840aa8438af");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var webhook = facturapi.webhooks().delete(
                  "whk_123"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $facturapi->Webhooks->delete( "5a3fefd9f508333611ad6b43" );
      parameters:
        - in: path
          name: webhook_id
          schema:
            type: string
          required: true
          description: ID del objeto a eliminar
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto `Webhook` eliminado correctamente
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Webhook'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /webhooks/validate-signature:
    post:
      operationId: validateWebhookSignature
      tags:
        - webhooks
      summary: Validar evento de webhook
      description: >
        Valida la firma de un evento recibido mediante un Webhook.

        Utiliza esta operación para verificar la autenticidad e integridad de

        un evento recibido, comparando la firma recibida con la generada por
        Facturapi.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/webhooks/valdate-signature \
              -H "Authorization: Bearer sk_test_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                    "secret": "wh_sec...",
                    "payload": "Object Response",
                    "signature": "Signature_FROM_HEADER"
                  }'
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');
            const customer = await facturapi.webhooks.validateSignature({
                    secret: "wh_sec...",
                    payload: "Object Response",
                    signature: "Signature_FROM_HEADER"
                  });
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var customer = await facturapi.Webhook.ValidateSignatureAsync(new
            Dictionary<string, object>

            {
              ["secret"] = "wh_sec...",
              ["payload"] = new Dictionary<string>["Object Response"],
              ["signature"] = "Signature_FROM_HEADER"
            });
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var event = facturapi.webhooks().validateSignature(
                    "webhook_secret",
                    "signature_hex",
                    "{\"id\":\"evt_123\"}"
                  );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");
            $customer = $facturapi->Webhooks->validateSignature([
              "secret" => "wh_sec...",
              "payload" => "Object Response",
              "signature" => "Signature_FROM_HEADER"
            ]);
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                secret:
                  type: string
                  description: >-
                    Llave secreta del webhook. Se obtiene al crear un webhook o
                    desde el dashboard de Facturapi.
                payload:
                  type: object
                  description: Objeto ApiEvent recibido mediante el webhook
                signature:
                  type: string
                  description: >-
                    Firma del webhook recibida en el header
                    `Facturapi-Signature`
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Objeto del evento validado
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/EventBase'
                  - type: object
                    properties:
                      type:
                        type: string
                        description: Tipo de evento
                        example: invoice.status_updated
                        enum:
                          - invoice.status_updated
                      data:
                        type: object
                        properties:
                          type:
                            type: string
                            description: Tipo de objeto asociado al evento
                            enum:
                              - invoice
                          object:
                            $ref: '#/components/schemas/Invoice'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /check:
    get:
      tags:
        - tools
      summary: Health check (Pulso)
      description: Indica el estatus de disponibilidad de la API.
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: La API está operando con normalidad.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:
                    type: boolean
                    example: true
        '401':
          description: Error de autenticación. Asegúrate de estar usando tu llave secreta.
        '502':
          description: Servicio temporalmente no disponible.
  /tools/tax_id_validation:
    get:
      tags:
        - tools
      summary: Validar RFC
      description: >
        Consulta el estado de un RFC en la lista de **EFOS** (Empresas que

        Facturan Operaciones Simuladas). Al aparecer en esta lista, el RFC es o

        fue sospechoso de incurrir en simulación de operaciones fiscales

        (empresas factureras).


        La respuesta (detallada más abajo) incluye los resultados de esta

        validación. Se incluye la propiedad

        booleana `is_valid`, que Facturapi resuelve interpretando la respuesta.

        Un valor de `true` para esta propiedad indica que el RFC no tiene
        asuntos

        por resolver y está libre de problemas; y lo contrario para `false`.


        Adicionalmente puedes consultar la propiedad data para ver los valores

        en bruto de la consulta al SAT.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: >
            curl
            https://www.facturapi.io/v2/tools/tax_id_validation?tax_id=BBA830831LJ2
            \
              -H "Authorization: Bearer sk_test_API_KEY"
        - lang: JavaScript
          label: Node.js
          source: >
            import Facturapi from 'facturapi'

            const facturapi = new Facturapi('sk_test_API_KEY');


            const validation = await
            facturapi.tools.validateTaxId('BBA830831LJ2');
        - lang: csharp
          label: C#
          source: >
            var facturapi = new FacturapiClient("sk_test_API_KEY");


            var customer = await
            facturapi.Tool.ValidateTaxIdAsync("BBA830831LJ2");
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var validation = facturapi.tools().validateTaxId(
                  "XAXX010101000"
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $customer = $facturapi->Tools->validateTaxId("BBA830831LJ2");
      parameters:
        - in: query
          name: tax_id
          required: true
          schema:
            type: string
            description: RFC a validar
            example: BBA830831LJ2
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la validación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TaxIdValidationResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /catalogs/products:
    get:
      tags:
        - sat_keys
      summary: Clave Producto/Servicio
      description: >-
        Busca en el catálogo Productos/Servicios del SAT, el cual contiene la
        clave a incluir en la factura.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/catalogs/products?q=ukelele \
              -H "Authorization: Bearer sk_test_API_KEY" 
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const searchResult = await facturapi.catalogs.searchProducts({
              q: 'ukelele'
            });
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var searchResult = await facturapi.Catalog.SearchProducts(
              new Dictionary<string, object>
              {
                ["q"] = "ukelele"
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.catalogs().searchProducts(
                  Map.of(
                      "q", "0101",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $result = $facturapi->Catalogs->searchProducts([
              "q" => "ukelele"
            ]);
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: Consulta. Texto a buscar en la descripción de la clasificación.
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProductCatalogSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
  /catalogs/units:
    get:
      tags:
        - sat_keys
      summary: Unidades de medida
      description: Busca en el catálogo de Unidades de Medida del SAT.
      x-codeSamples:
        - lang: Bash
          label: cURL
          source: |
            curl https://www.facturapi.io/v2/catalogs/units?q=pulgada \
              -H "Authorization: Bearer sk_test_API_KEY" 
        - lang: JavaScript
          label: Node.js
          source: |
            import Facturapi from 'facturapi'
            const facturapi = new Facturapi('sk_test_API_KEY');

            const searchResult = await facturapi.catalogs.searchUnits({
              q: 'pulgada'
            });
        - lang: csharp
          label: C#
          source: |
            var facturapi = new FacturapiClient("sk_test_API_KEY");

            var searchResult = await facturapi.Catalog.SearchUnits(
              new Dictionary<string, object>
              {
                ["q"] = "pulgada"
              }
            );
        - lang: Java
          label: Java
          source: |
            import io.facturapi.Facturapi;
            import java.util.List;
            import java.util.Map;

            Facturapi facturapi = new Facturapi("sk_test_API_KEY");

            var result = facturapi.catalogs().searchUnits(
                  Map.of(
                      "q", "H87",
                      "page", 0,
                      "limit", 10
                  )
                );
        - lang: PHP
          source: |
            $facturapi = new Facturapi("sk_test_API_KEY");

            $result = $facturapi->Catalogs->searchUnits([
              "q" => "pulgada"
            ]);
      parameters:
        - in: query
          name: q
          schema:
            type: string
          description: Consulta. Texto a buscar en la descripción de la unidad de medida.
        - $ref: '#/components/parameters/SearchPage'
        - $ref: '#/components/parameters/SearchLimit'
      security:
        - SecretLiveKey: []
        - SecretTestKey: []
      responses:
        '200':
          description: Resultado de la búsqueda
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UnitCatalogSearchResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/UnexpectedError'
x-webhooks:
  Factura global creada:
    post:
      summary: Factura global creada
      description: >
        Notifica acerca de la creación de una factura global a partir de
        e-Receipts.
      tags:
        - events
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/EventBase'
                - type: object
                  properties:
                    type:
                      type: string
                      description: Tipo de evento
                      example: invoice.global_invoice_created
                      enum:
                        - invoice.global_invoice_created
                    data:
                      type: object
                      properties:
                        type:
                          type: string
                          description: Tipo de objeto asociado al evento
                          enum:
                            - invoice
                        object:
                          $ref: '#/components/schemas/Invoice'
  Estatus de factura actualizado:
    post:
      summary: Estatus de factura actualizado
      description: |
        Notifica acerca del cambio del campo `status` de una factura.

        Se utiliza en el caso de haber creado la factura de manera asíncrona.
      tags:
        - events
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/EventBase'
                - type: object
                  properties:
                    type:
                      type: string
                      description: Tipo de evento
                      example: invoice.status_updated
                      enum:
                        - invoice.status_updated
                    data:
                      type: object
                      properties:
                        type:
                          type: string
                          description: Tipo de objeto asociado al evento
                          enum:
                            - invoice
                        object:
                          $ref: '#/components/schemas/Invoice'
  Creación de factura desde dashboard:
    post:
      summary: Creación de factura desde dashboard
      description: |
        Notifica cuandos se crea una factura desde dashboard de Facturapi.
      tags:
        - events
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/EventBase'
                - type: object
                  properties:
                    type:
                      type: string
                      description: Tipo de evento
                      example: invoice.created_from_dashboard
                      enum:
                        - invoice.created_from_dashboard
                    data:
                      type: object
                      properties:
                        type:
                          type: string
                          description: Tipo de objeto asociado al evento
                          enum:
                            - invoice
                        object:
                          $ref: '#/components/schemas/Invoice'
  Estatus de cancelación actualizado:
    post:
      tags:
        - events
      summary: Estatus de cancelación actualizado
      description: >
        Notifica acerca de cambios en el campo `cancellation_status` de una
        factura.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/EventBase'
                - type: object
                  properties:
                    type:
                      type: string
                      description: Tipo de evento
                      enum:
                        - invoice.cancellation_status_updated
                    data:
                      type: object
                      properties:
                        type:
                          type: string
                          description: Tipo de objeto asociado al evento
                          enum:
                            - invoice
                        object:
                          $ref: '#/components/schemas/Invoice'
  Autofactura completada:
    post:
      tags:
        - events
      summary: Autofactura completada
      description: >
        Notifica acerca de la creación de una autofactura a partir de un
        e-Receipt.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/EventBase'
                - type: object
                  properties:
                    type:
                      type: string
                      description: Tipo de evento
                      example: receipt.self_invoice_complete
                      enum:
                        - receipt.self_invoice_complete
                    data:
                      type: object
                      properties:
                        type:
                          type: string
                          description: Tipo de objeto asociado al evento
                          enum:
                            - receipt
                        object:
                          $ref: '#/components/schemas/Receipt'
  Estatus de recibo actualizado:
    post:
      tags:
        - events
      summary: Estatus de recibo actualizado
      description: |
        Notifica acerca de cambios en el campo `status` de un recibo.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/EventBase'
                - type: object
                  properties:
                    type:
                      type: string
                      description: Tipo de evento
                      enum:
                        - receipt.status_updated
                    data:
                      type: object
                      properties:
                        type:
                          type: string
                          description: Tipo de objeto asociado al evento
                          enum:
                            - receipt
                        object:
                          $ref: '#/components/schemas/Receipt'
components:
  responses:
    BadRequest:
      description: Error en parámetros de la petición
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GenericError'
    Unauthenticated:
      description: Error de autenticación
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GenericError'
    Conflict:
      description: >
        Conflicto en la petición. La operación que se intenta realizar no puede
        completarse debido a conflictos en el estado actual del recurso.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GenericError'
    NotFound:
      description: No se encontró el recurso especificado.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GenericError'
    RateLimited:
      description: Demasiadas solicitudes en una ventana de tiempo corta.
      headers:
        Retry-After:
          description: Segundos recomendados antes de reintentar.
          schema:
            type: integer
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GenericError'
          example:
            message: Too many requests. Please retry shortly.
            status: 429
            ok: false
            code: rate_limit_exceeded
    UnexpectedError:
      description: Error inesperado
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GenericError'
  requestBodies:
    CustomerCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/CustomerCreateInput'
    CustomerEdit:
      required: true
      content:
        application/json:
          schema:
            allOf:
              - $ref: '#/components/schemas/CustomerProperties'
    ProductCreate:
      required: true
      content:
        application/json:
          schema:
            allOf:
              - $ref: '#/components/schemas/ProductProperties'
    ProductEdit:
      required: true
      content:
        application/json:
          schema:
            allOf:
              - $ref: '#/components/schemas/ProductProperties'
    InvoiceCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/InvoiceCreateInput'
    InvoiceCreatePending:
      required: true
      content:
        application/json:
          schema:
            oneOf:
              - $ref: '#/components/schemas/InvoiceIngresoInput'
              - $ref: '#/components/schemas/InvoiceEgresoInput'
              - $ref: '#/components/schemas/InvoicePagoInput'
              - $ref: '#/components/schemas/InvoiceNominaInput'
              - $ref: '#/components/schemas/InvoiceTrasladoInput'
    InvoiceEdit:
      required: true
      content:
        application/json:
          schema:
            oneOf:
              - $ref: '#/components/schemas/InvoiceIngresoEditInput'
              - $ref: '#/components/schemas/InvoiceEgresoEditInput'
              - $ref: '#/components/schemas/InvoicePagoEditInput'
              - $ref: '#/components/schemas/InvoiceNominaEditInput'
              - $ref: '#/components/schemas/InvoiceTrasladoEditInput'
    ReceiptCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ReceiptInput'
    ReceiptAssignCustomer:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ReceiptAssignCustomerInput'
    ReceiptInvoice:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/InvoiceReceiptInput'
    ReceiptCreateGlobalInvoice:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GlobalInvoiceInput'
    ReceiptCreateToInvoice:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ToInvoiceInput'
    ReceiptPreviewToInvoice:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ToInvoicePreviewInput'
    RetentionCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/RetentionInput'
    OrganizationCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationCreateInput'
    OrganizationEditLegal:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationLegalInput'
    OrganizationUploadCerts:
      required: true
      content:
        multipart/form-data:
          schema:
            $ref: '#/components/schemas/OrganizationCertsInput'
    OrganizationUploadFiel:
      required: true
      content:
        multipart/form-data:
          schema:
            $ref: '#/components/schemas/OrganizationFielInput'
    OrganizationUploadLogo:
      required: true
      content:
        multipart/form-data:
          schema:
            $ref: '#/components/schemas/OrganizationLogoInput'
    OrganizationEditCustomization:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationCustomizationInput'
    OrganizationEditReceiptsSettings:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationReceiptsInput'
    OrganizationEditSelfInvoiceSettings:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationSelfInvoiceInput'
    OrganizationEditDomain:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationDomainInput'
    OrganizationSeriesCreate:
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationSeriesCreateInput'
    OrganizationSeriesUpdate:
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationSeriesUpdateInput'
    OrganizationSeriesDefault:
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationSeriesDefaultInput'
    OrganizationInviteCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationInviteCreateInput'
    OrganizationInviteRespond:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationInviteRespondInput'
    OrganizationPermissionRoleCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationPermissionRoleCreateInput'
    OrganizationPermissionRoleUpdate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationPermissionRoleUpdateInput'
    OrganizationUserAccessRoleUpdate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/OrganizationUserAccessRoleUpdateInput'
    WebhookCreate:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/WebhookCreateInput'
    WebhookEdit:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/WebhookCreateEdit'
  parameters:
    SearchDate:
      in: query
      name: date
      style: deepObject
      schema:
        $ref: '#/components/schemas/DateRange'
      description: Objeto con rango de fechas solicitado.
    SearchPage:
      in: query
      name: page
      schema:
        type: integer
        minimum: 1
      description: Página de resultados a regresar, empezando desde la página 1.
    SearchLimit:
      in: query
      name: limit
      schema:
        type: integer
        minimum: 1
        default: 50
        maximum: 100
      description: >-
        Número del 1 al 100 que representa la cantidad máxima de resultados a
        regresar con motivos de paginación.
  schemas:
    SearchKeyDescriptionResult:
      type: object
      properties:
        page:
          type: integer
          description: Número de página actual (base 0).
        total_pages:
          type: integer
          description: Total de páginas disponibles.
        total_results:
          type: integer
          description: Total de resultados encontrados.
        data:
          type: array
          items:
            type: object
            properties:
              key:
                type: string
              description:
                type: string
    ErrorMessage:
      type: object
      required:
        - message
      properties:
        message:
          type: string
          description: Descripción del error y posible sugerencia.
    EventBase:
      type: object
      properties:
        id:
          type: string
          description: ID del evento
          example: 61f81a81bd4661b11b9b404e
        created_at:
          type: string
          format: date-time
          description: Fecha y hora de creación del evento
          example: '2022-03-30T00:00:00Z'
        livemode:
          type: boolean
          description: >-
            Indica si el evento se generó en modo test (false) o en modo
            producción (true).
          example: false
        organization:
          type: string
          description: ID de la organización a la que pertenece el evento
          example: 61f81a7fbd4661b11b9b3f27
    DateRange:
      type: object
      properties:
        gt:
          type: string
          format: date-time
          title: Greater than
          description: Límite inferior exclusivo del rango de fechas a solicitar.
        gte:
          type: string
          format: date-time
          title: Greater than or equals
          description: Límite inferior inclusivo del rango de fechas a solicitar.
        lt:
          type: string
          format: date-time
          title: Lesser than
          description: Límite superior exclusivo del rango de fechas a solicitar.
        lte:
          type: string
          format: date-time
          title: Lesser than or equals
          description: Límite superior inclusivo del rango de fechas a solicitar.
    GenericError:
      type: object
      properties:
        message:
          type: string
          title: Descripción del error
          description: >-
            Indica qué salió mal y puede incluir una sugerencia sobre cómo
            solucionar el error.
        status:
          type: integer
          format: int32
          title: Código de estado HTTP
          description: Código de estado HTTP de esta respuesta de error.
          example: 400
        ok:
          type: boolean
          description: >-
            Indica si la petición fue exitosa. Siempre `false` en respuestas de
            error.
          example: false
        code:
          type: string
          description: >-
            Código de error estable para manejar el error de forma programática.
            Consulta la guía de manejo de errores para ver la lista de códigos
            documentados.
          example: invalid_request
        location:
          type: string
          description: Ubicación opcional del dato relacionado con el error.
          enum:
            - body
            - query
            - params
            - headers
            - files
        path:
          type: string
          description: Ruta opcional del campo relacionado con el error.
        errors:
          type: array
          description: >-
            Detalles adicionales del error. Sólo se incluye cuando hay errores
            de validación o detalles externos relevantes.
          items:
            $ref: '#/components/schemas/ErrorDetail'
    ErrorDetail:
      type: object
      properties:
        message:
          type: string
          description: Mensaje legible del detalle.
        code:
          type: string
          description: >-
            Subcódigo del detalle. En validaciones usa códigos como `required` o
            `invalid_type`; en errores externos puede contener el código
            original del proveedor.
          example: required
        location:
          type: string
          description: Ubicación opcional del dato relacionado con este detalle.
          enum:
            - body
            - query
            - params
            - headers
            - files
        path:
          type: string
          description: Ruta opcional del campo relacionado con este detalle.
        source:
          type: string
          description: Fuente opcional para detalles externos, por ejemplo `sat`.
    IssuingType:
      type: string
      description: >-
        Indica si la factura fue emitida por tu organización o recibida de un
        tercero.
      enum:
        - issuing
        - receiving
    CancellationStatus:
      type: string
      description: Estado de la solicitud de cancelación de la factura.
      enum:
        - none
        - accepted
        - pending
        - rejected
        - expired
    SearchResult:
      type: object
      properties:
        page:
          type: integer
          example: 1
          title: Página
          description: Número de página de resultados
        total_pages:
          type: integer
          example: 1
          title: Páginas totales
          description: Número total de páginas de resultados
        total_results:
          type: integer
          example: 1
          title: Resultados totales
          description: Número de elementos individuales en todas las páginas de resultados
    ResourceAutoGeneratedProps:
      type: object
      required:
        - id
        - created_at
        - livemode
      properties:
        id:
          type: string
          description: ID del objeto
          example: 590ce6c56d04f840aa8438af
        created_at:
          type: string
          format: date-time
          description: Fecha de registro
          example: '2017-05-05T20:55:33.468Z'
        livemode:
          type: boolean
          description: >-
            Si el valor es `true`, indica que el objeto fue creado en ambiente
            Live; o si es `false`, en ambiente Test.
          example: false
    TaxIdValidationResult:
      type: object
      properties:
        efos:
          type: object
          description: |
            Resultado de la validación en la lista de Empresas que
            Facturan Operaciones Simuladas del SAT.
          properties:
            is_valid:
              type: boolean
              example: true
              description: >
                Indica si el RFC tiene algún asunto relacionado con esta lista.

                `true`: El RFC no está en la lista de EFOS o su situación fue

                apelada y resultó favorable. `false`: El RFC está registrado
                como

                “Presunto” o “Definitivo” en la lista de EFOS.
            data:
              type: object
              description: |
                Objeto con el resultado de la búqueda ante el SAT.
                Toda la información contenida en este objeto proviene del SAT.
              properties:
                mensaje:
                  type: string
                  description: |
                    Disponible sólo cuando el RFC no fue encontrado en la lista,
                    lo cual es bueno.
                fechaLista:
                  type: string
                  example: Información actualizada al 17 de septiembre de 2021
                  description: Texto que indica la fecha de actualización de la lista.
                detalles:
                  type: array
                  description: >-
                    Arreglo con los resultados de la búsqueda en la lista de
                    EFOS.
                  items:
                    type: object
                    properties:
                      rfc:
                        type: string
                        example: NOR170627727
                        description: El RFC consultado, a manera de confirmación.
                      razonSocial:
                        type: string
                        example: NORMANDIA FERRE,
                        description: Razón social del contribuyente.
                      situacionContribuyente:
                        type: string
                        example: Definitivo
                        description: |
                          Texto que indica la situación actual. Consulta
                          [esta tabla](#situación-del-contribuyente) para ver
                          el detalle de los distintos valores.
                      numFechaPresuncion:
                        type: string
                        example: 500-05-2020-23758 de fecha 03 de noviembre de 2020
                        description: >-
                          Texto con identificador y fecha del reporte de
                          presunción.
                      pubFechaSatPresuntos:
                        type: string
                        format: DD/MM/YYYY
                        example: 03/11/2020
                        description: Fecha de publicación de presunción.
                      numGlobalPresuncion:
                        type: string
                        example: 500-05-2020-23758 de fecha 03 de noviembre de 2020
                        description: >-
                          Texto con identificador y fecha de publicación en el
                          listado global de presunción.
                      pubFechaDofPresuntos:
                        type: string
                        format: DD/MM/YYYY
                        example: 18/11/2020
                        description: >-
                          Fecha de publicación en el Diario Oficial de la
                          Federación (DOF).
                      pubSatDefinitivos:
                        type: string
                        example: 500-05-2021-151
                        description: >-
                          Identificador de la publicación de estado
                          “Definitivo”.
                      pubDofDefinitivos:
                        type: string
                        format: DD/MM/YYYY
                        example: 25/05/2021
                        description: >-
                          Fecha de la publicación de estado “Definitivo” en el
                          DOF.
                      numFechaSentFav:
                        type: string
                        example: 500-05-2021-15156 de fecha 25 de mayo de 2021
                        description: >-
                          Texto con identificador y fecha de sentencia
                          favorable.
                      pubSatSentFav:
                        type: string
                        example: 08/06/2021
                        format: DD/MM/YYYY
                        description: Fecha de sentencia favorable
    ProductCatalogResult:
      type: object
      properties:
        key:
          type: string
          description: Clave del catálogo
          example: 60131324
        description:
          type: string
          description: Descripción
          example: Ukelele
        score:
          type: number
          description: |
            Número del 0 al 1 que representa el nivel de coincidencia del
            resultado con respecto a la consulta de búsqueda.
          example: 0.8
    UnitCatalogResult:
      type: object
      properties:
        key:
          type: string
          description: Clave del catálogo
          example: INH
        description:
          type: string
          description: Descripción
          example: Pulgada
        score:
          type: number
          description: |
            Número del 0 al 1 que representa el nivel de coincidencia del
            resultado con respecto a la consulta de búsqueda.
          example: 0.9
    ProductCatalogSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/ProductCatalogResult'
    UnitCatalogSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/UnitCatalogResult'
    LocalTax:
      type: object
      required:
        - rate
        - type
      properties:
        rate:
          type: number
          example: 0.1
          description: Tasa del impuesto en fracción decimal.
        base:
          type: number
          default: 100% del subtotal
          description: Base del impuesto
        type:
          type: string
          description: Nombre del impuesto. Texto libre.
        withholding:
          type: boolean
          default: false
          description: >-
            Indica si se trata de un impuesto retenido (`true`), o un impuesto
            trasladado (`false`)
    BaseTax:
      title: Tax
      type: object
      required:
        - rate
      discriminator:
        propertyName: type
        mapping:
          IVA: '#/components/schemas/BaseTax'
          ISR: '#/components/schemas/BaseTax'
          IEPS: '#/components/schemas/IepsTax'
      properties:
        rate:
          type: number
          example: 0.16
          description: Tasa del impuesto en fracción decimal.
        base:
          type: number
          default: 100% del subtotal
          description: Base del impuesto.
        type:
          type: string
          default: IVA
          description: Tipo de impuesto.
          enum:
            - IVA
            - ISR
            - IEPS
        factor:
          type: string
          default: Tasa
          enum:
            - Tasa
            - Cuota
            - Exento
          description: Tipo factor
        withholding:
          type: boolean
          default: false
          description: >-
            Indica si se trata de un impuesto retenido (`true`), o un impuesto
            trasladado (`false`)
    IepsTax:
      type: object
      allOf:
        - $ref: '#/components/schemas/BaseTax'
        - type: object
          properties:
            ieps_mode:
              type: string
              default: sum_before_taxes
              enum:
                - sum_before_taxes
                - break_down
                - unit
                - subtract_before_break_down
              description: >
                Indica la manera de cobrar el impuesto, y puede tener los
                valores:


                `"sum_before_taxes"`: Aplica primero el IEPS al subtotal y usa
                el resultado como base del resto de impuestos en el producto.


                `"break_down"`: Cobra y desgloza el IEPS al mismo nivel que el
                resto de los impuestos en el producto.


                `"unit"`: Aplica el IEPS antes del precio unitario, y usa el
                precio unitario original como base para el resto de impuestos.


                `"subtract_before_break_down"`: Aplica el IEPS solo para
                calcular impuestos como IVA de traslado y retenciones, y usa el
                precio unitario original como base para el resto de impuestos.


                Consulta con tu contador qué caso aplica para tu giro de empresa
                y producto.
    Stamp:
      type: object
      description: Información sobre el timbre fiscal digital agregado por el PAC.
      properties:
        signature:
          type: string
          description: Sello digital del comprobante fiscal.
        date:
          type: string
          format: date-time
          description: Fecha de timbrado en formato ISO8601 (UTC String).
        sat_cert_number:
          type: string
          description: Número de serie del certificado del SAT usado para timbrar.
        sat_signature:
          type: string
          description: Sello digital del timbre fiscal digital.
    LineItem:
      type: object
      properties:
        quantity:
          type: number
          description: Cantidad de unidades incluídas del mismo concepto.
          example: 1
        discount:
          type: number
          description: Monto total de descuento aplicado a este concepto.
          example: 0
        product:
          $ref: '#/components/schemas/LineItemProduct'
          description: Objeto con información del producto o servicio facturado.
        parts:
          $ref: '#/components/schemas/Parts'
          description: Objeto con información de las partes de la factura.
    ThirdParty:
      type: object
      description: >
        Objeto con información del contribuyente tercero, a cuenta del que se
        realiza la operación.


        Corresponde al campo "ACuentaTerceros" en el CFDI.
      properties:
        legal_name:
          type: string
          description: Nombre o razón social del tercero.
          example: The Michael Scott Paper Company
        tax_id:
          type: string
          description: RFC del tercero.
          example: MIC920101HN7
        tax_system:
          type: string
          maxLength: 3
          minLength: 3
          description: Régimen fiscal del tercero.
          example: '601'
        zip:
          type: string
          description: Código postal del tercero.
          example: '01234'
    LineItemInput:
      title: LineItem
      required:
        - product
      type: object
      description: Conceptos incluidos en el documento
      properties:
        quantity:
          type: number
          default: 1
          description: Cantidad de unidades incluídas del mismo concepto.
          example: 1
        discount:
          type: number
          description: Monto total de descuento aplicado a este concepto.
          default: 0
          example: 0
        product:
          description: Objeto con información del producto o servicio facturado.
          oneOf:
            - $ref: '#/components/schemas/LineItemProductInput'
            - type: string
              title: product_id
              description: ID de un producto previamente registrado en Facturapi
        parts:
          type: array
          items:
            $ref: '#/components/schemas/PartInput'
        customs_keys:
          type: array
          items:
            type: string
          description: Números de pedimento asociados a este concepto.
        complement:
          description: >-
            Código XML de tu complemento concepto, el complemento Hidrocarburos
            y Petrolíferos o el complemento Instituciones Educativas Privadas.
          oneOf:
            - type: string
              format: xml
              description: Código XML de tu complemento concepto.
            - $ref: '#/components/schemas/HidroYPetroComplementInput'
            - $ref: '#/components/schemas/IeduComplementInput'
        third_party:
          allOf:
            - type: object
              required:
                - legal_name
                - tax_id
                - tax_system
                - zip
            - $ref: '#/components/schemas/ThirdParty'
        property_tax_account:
          type: string
          description: Número de cuenta para el impuesto predial.
          example: '0102030405'
    LineItemEgresoInput:
      title: LineItem
      required:
        - product
      type: object
      description: Conceptos incluidos en el documento
      properties:
        quantity:
          type: number
          default: 1
          description: Cantidad de unidades incluídas del mismo concepto.
          example: 1
        discount:
          type: number
          description: Monto total de descuento aplicado a este concepto.
          default: 0
          example: 0
        product:
          description: Objeto con información del producto o servicio facturado.
          oneOf:
            - $ref: '#/components/schemas/LineItemProductEgresoInput'
            - type: string
              title: product_id
              description: ID de un producto previamente registrado en Facturapi
        parts:
          type: array
          items:
            $ref: '#/components/schemas/PartInput'
        customs_keys:
          type: array
          items:
            type: string
          description: Números de pedimento asociados a este concepto.
        complement:
          description: >-
            Código XML de tu complemento concepto, el complemento Hidrocarburos
            y Petrolíferos o el complemento Instituciones Educativas Privadas.
          oneOf:
            - type: string
              format: xml
              description: Código XML de tu complemento concepto.
            - $ref: '#/components/schemas/HidroYPetroComplementInput'
            - $ref: '#/components/schemas/IeduComplementInput'
        third_party:
          allOf:
            - type: object
              required:
                - legal_name
                - tax_id
                - tax_system
                - zip
            - $ref: '#/components/schemas/ThirdParty'
    LineItemTrasladoInput:
      title: LineItem
      required:
        - product
      type: object
      description: Conceptos incluidos en el documento
      properties:
        quantity:
          type: number
          default: 1
          description: Cantidad de unidades incluídas del mismo concepto.
          example: 1
        product:
          description: Objeto con información del producto o servicio facturado.
          oneOf:
            - $ref: '#/components/schemas/LineItemTrasladoProductInput'
            - type: string
              title: product_id
              description: ID de un producto previamente registrado en Facturapi
        customs_keys:
          type: array
          items:
            type: string
          description: Números de pedimento asociados a este concepto.
        complement:
          type: string
          format: xml
          description: Código XML de tu complemento concepto.
        parts:
          type: array
          items:
            $ref: '#/components/schemas/PartInput'
        third_party:
          type: object
          required:
            - legal_name
            - tax_id
            - tax_system
            - zip
          properties:
            legal_name:
              type: string
              description: Nombre o razón social del tercero.
              example: The Michael Scott Paper Company
            tax_id:
              type: string
              description: RFC del tercero.
              example: STA920101HN7
            tax_system:
              type: string
              maxLength: 3
              minLength: 3
              description: Régimen fiscal del tercero.
              example: '601'
            zip:
              type: string
              description: Código postal del tercero.
              example: '01234'
    HidroYPetroComplementInput:
      title: HidroYPetroComplement
      type: object
      required:
        - tipo_permiso
        - numero_permiso
        - sub_producto_hyp
      properties:
        tipo_permiso:
          type: string
          enum:
            - PER01
            - PER02
            - PER03
            - PER04
            - PER05
            - PER06
            - PER07
            - PER08
            - PER09
            - PER10
            - PER11
          example: PER01
          description: >-
            Tipo de permiso otorgado por la autoridad competente, conforme al
            [Catálogo Hidrocarburos
            Petrolíferos](#cat%C3%A1logos-hidrocarburos-petrol%C3%ADferos).
          x-enum-descriptions:
            - Expendio en estaciones de servicio de petroliferos
            - Comercializacion
            - Distribucion por otros medios distintos a ducto
            - Expendio en estaciones de servicio multimodal de petroliferos
            - Expendio en estaciones de servicio de petroliferos
            - Comercializacion
            - Distribucion por otros medios distintos a ducto
            - Expendio en estaciones de servicio multimodal de petroliferos
            - Comercializacion
            - Comercializacion
            - Comercializacion
        numero_permiso:
          type: string
          minLength: 15
          maxLength: 35
          description: >-
            Número de permiso otorgado por la autoridad competente, conforme a
            la nomenclatura del catálogo c_TipoPermiso.
        sub_producto_hyp:
          type: string
          enum:
            - SP16
            - SP17
            - SP18
            - SP19
            - SP22
            - SP23
            - SP24
            - SP25
            - SP48
          example: SP16
          description: >-
            Subtipo del hidrocarburo o petrolífero, conforme al [Catálogo
            Hidrocarburos
            Petrolíferos](#cat%C3%A1logos-hidrocarburos-petrol%C3%ADferos).
          x-enum-descriptions:
            - Gasolina regular menor a 91 octanos
            - Gasolina premium mayor o igual a 91 octanos
            - Diésel automotriz
            - Diésel marino
            - IFO380
            - Diésel industrial
            - Diésel de Ultra Bajo Azufre (DUBA)
            - Diésel agrícola
            - Gasóleo doméstico
        clave_hyp:
          type: string
          enum:
            - '15101514'
            - '15101515'
            - '15101505'
          example: '15101514'
          description: >
            Clave correspondiente a hidrocarburos y petrolíferos, conforme al
            [Catálogo Hidrocarburos
            Petrolíferos](#cat%C3%A1logos-hidrocarburos-petrol%C3%ADferos).


            Puedes enviarla explícitamente o dejar que Facturapi la derive desde
            el `product_key` del concepto cuando aplique.
          x-enum-descriptions:
            - Gasolina
            - Diesel
            - Combustibles para barco
    IeduComplementInput:
      title: IeduComplement
      type: object
      description: |
        Complemento concepto de Instituciones Educativas Privadas versión 1.0.

        Se incluye a nivel concepto dentro de `items[].complement`.
      required:
        - nombreAlumno
        - CURP
        - nivelEducativo
        - autRVOE
      properties:
        nombreAlumno:
          type: string
          description: Nombre del alumno.
          example: Juan Perez Lopez
        CURP:
          type: string
          minLength: 18
          maxLength: 18
          pattern: >-
            ^[A-Z][AEIOUX][A-Z]{2}[0-9]{2}[0-1][0-9][0-3][0-9][MHX][A-Z]{2}[BCDFGHJKLMNÑPQRSTVWXYZ]{3}[0-9A-Z][0-9]$
          description: CURP del alumno de la institución educativa.
          example: PELJ010101HDFRPN09
        nivelEducativo:
          type: string
          enum:
            - Preescolar
            - Primaria
            - Secundaria
            - Profesional técnico
            - Bachillerato o su equivalente
          example: Primaria
          description: Nivel educativo que cursa el alumno.
        autRVOE:
          type: string
          minLength: 1
          description: >-
            Clave del centro de trabajo o reconocimiento de validez oficial de
            estudios de la institución educativa privada donde se realiza el
            pago.
          example: 15PPR1234A
        rfcPago:
          type: string
          pattern: >-
            ^[A-ZÑ&]{3,4}[0-9]{2}[0-1][0-9][0-3][0-9][A-Z0-9]?[A-Z0-9]?[0-9A-Z]?$
          description: >-
            RFC de quien realiza el pago cuando sea diferente a quien recibe el
            servicio.
          example: PELJ800101ABC
    CustomComplementData:
      title: string
      type: string
      format: xml
      description: >-
        Código XML de tu complemento tal cual como quieres que se inserte en el
        XML. Debe contener sólamente un nodo XML raíz.
    CustomComplementProperties:
      title: CustomComplement
      type: object
      properties:
        type:
          type: string
          enum:
            - custom
          description: Tipo de complemento.
        data:
          $ref: '#/components/schemas/CustomComplementData'
    CustomComplementInput:
      title: CustomComplement
      allOf:
        - type: object
          required:
            - type
            - data
        - $ref: '#/components/schemas/CustomComplementProperties'
    NominaComplementDataInput:
      title: NominaComplementData
      description: Objeto con la información del complemento de nómina.
      allOf:
        - type: object
          required:
            - fecha_inicial_pago
            - fecha_final_pago
            - num_dias_pagados
            - receptor
            - percepciones
        - $ref: '#/components/schemas/NominaComplementDataDirectProperties'
        - $ref: '#/components/schemas/NominaComplementDataNestedInput'
    NominaComplementDataProperties:
      description: Complemento de Nómina.
      allOf:
        - $ref: '#/components/schemas/NominaComplementDataDirectProperties'
        - $ref: '#/components/schemas/NominaComplementDataNestedProperties'
    NominaComplementDataDirectProperties:
      type: object
      properties:
        tipo_nomina:
          type: string
          default: O
          enum:
            - O
            - E
          description: >
            Tipo de nómina.

            - `“O”` (Ordinaria): Cuando corresponde a un pago que se realiza de
            manera habitual, como sueldos.

            - `“E”` (Extraordinaria): Para pagos fuera de lo habitual, como
            liquidaciones, aguinaldos o bonos.
        fecha_pago:
          type: string
          format: date
          default: now
          description: Fecha de pago de la nómina al trabajador.
        fecha_inicial_pago:
          type: string
          format: date
          description: Fecha inicial del periodo de pago.
        fecha_final_pago:
          type: string
          format: date
          description: Fecha final del periodo de pago.
        num_dias_pagados:
          type: number
          exclusiveMinimum: 0
          description: Número de días pagados. Puede ser entero o fracción.
    NominaComplementDataNestedInput:
      type: object
      properties:
        emisor:
          $ref: '#/components/schemas/NominaEmisorProperties'
        receptor:
          $ref: '#/components/schemas/NominaReceptorInput'
        percepciones:
          $ref: '#/components/schemas/NominaPercepcionesInput'
        deducciones:
          type: array
          description: Arreglo de objetos donde se expresan las deducciones aplicables.
          items:
            $ref: '#/components/schemas/NominaDeduccionInput'
        otros_pagos:
          type: array
          description: Arreglo de objetos para expresar otros pagos aplicables.
          items:
            title: OtroPago
            allOf:
              - $ref: '#/components/schemas/NominaOtroPagoInput'
              - type: object
                properties:
                  compensacion_saldos_a_favor:
                    $ref: '#/components/schemas/NominaCompensacionInput'
        incapacidades:
          type: array
          description: Arreglo de objetos con información de incapacidades.
          items:
            $ref: '#/components/schemas/NominaIncapacidadInput'
    NominaComplementDataNestedProperties:
      type: object
      properties:
        emisor:
          $ref: '#/components/schemas/NominaEmisorProperties'
        receptor:
          $ref: '#/components/schemas/NominaReceptorProperties'
        percepciones:
          $ref: '#/components/schemas/NominaPercepcionesProperties'
        deducciones:
          type: array
          description: Arreglo de objetos donde se expresan las deducciones aplicables.
          items:
            $ref: '#/components/schemas/NominaDeduccionProperties'
        otros_pagos:
          type: array
          description: Arreglo de objetos para expresar otros pagos aplicables.
          items:
            allOf:
              - $ref: '#/components/schemas/NominaOtroPagoDirectProperties'
              - type: object
                properties:
                  compensacion_saldos_a_favor:
                    $ref: '#/components/schemas/NominaCompensacionProperties'
        incapacidades:
          type: array
          description: Arreglo de objetos con información de incapacidades.
          items:
            $ref: '#/components/schemas/NominaIncapacidadProperties'
    NominaIncapacidadInput:
      title: Incapacidad
      allOf:
        - type: object
          required:
            - dias_incapacidad
            - tipo_incapacidad
        - $ref: '#/components/schemas/NominaIncapacidadProperties'
    NominaIncapacidadProperties:
      type: object
      properties:
        dias_incapacidad:
          type: integer
          description: >-
            Número de días enteros que el trabajador se incapacitó en el
            periodo.
        tipo_incapacidad:
          type: string
          description: Clave del catálogo [Tipo de Incapacidad](#tipo-de-incapacidad).
        importe_monetario:
          type: number
          description: Monto del importe monetario de la incapacidad.
    NominaOtroPagoInput:
      title: OtroPago
      allOf:
        - type: object
          required:
            - tipo_otro_pago
            - clave
            - importe
        - $ref: '#/components/schemas/NominaOtroPagoDirectProperties'
        - type: object
          properties:
            compensacion_saldos_a_favor:
              $ref: '#/components/schemas/NominaCompensacionInput'
    NominaOtroPagoDirectProperties:
      type: object
      properties:
        tipo_otro_pago:
          type: string
          description: Clave del catálogo [Tipo de Otro Pago](#tipo-de-otro-pago).
        clave:
          type: string
          minLength: 3
          maxLength: 15
          description: >-
            Clave de otro pago de nómina propia de la contabilidad de cada
            patrón.
        concepto:
          type: string
          description: Descripción alternativa correspondiente a la clave utilizada.
        importe:
          type: number
          description: Importe por concepto de otro pago.
        subsidio_causado:
          type: number
          description: |
            Subsidio causado conforme a la tabla del subsidio para el empleo
            publicada en el Anexo 8 de la Resolución Miscelánea Fiscal vigente.

            Este valor será insertado dentro del nodo `SubsidioAlEmpleo`, y es
            requerido cuando el valor de `tipo_otro_pago` es `"002"`.
    NominaCompensacionInput:
      allOf:
        - type: object
          required:
            - saldo_a_favor
            - ano
            - remanente_sal_fav
        - $ref: '#/components/schemas/NominaCompensacionProperties'
    NominaCompensacionProperties:
      type: object
      description: >-
        Objeto con información referente a la compensación de saldos a favor de
        un trabajador.
      properties:
        saldo_a_favor:
          type: number
          description: >-
            Monto por saldo a favor determinado por el patrón al trabajador en
            periodos o ejercicios anteriores.
        ano:
          type: integer
          description: Año en que se determinó el saldo a favor del trabajador.
        remanente_sal_fav:
          type: number
          description: Remanente del saldo a favor del trabajador.
    NominaDeduccionInput:
      title: Deduccion
      allOf:
        - type: object
          required:
            - tipo_deduccion
            - clave
            - importe
        - $ref: '#/components/schemas/NominaDeduccionProperties'
    NominaDeduccionProperties:
      type: object
      properties:
        tipo_deduccion:
          type: string
          description: Clave del catálogo [Tipo de deducción](#tipo-de-deducción).
        concepto:
          type: string
          description: >-
            Concepto de la deducción. Si no se envía, se utilizará la
            descripción del catálogo del tipo de deducción.
        clave:
          type: string
          minLength: 3
          maxLength: 15
          description: >-
            Clave de control interno que asigna el patrón a cada deducción
            (descuento) de nómina propia de su contabilidad.
        importe:
          type: number
          description: Importe del concepto de deducción.
    NominaPercepcionesInput:
      type: object
      title: Percepciones
      description: Objeto para indicar las percepciones aplicables.
      required:
        - percepcion
      properties:
        percepcion:
          type: array
          description: Objeto con información detallada de cada percepción.
          items:
            $ref: '#/components/schemas/NominaPercepcionInput'
        jubilacion_pension_retiro:
          $ref: '#/components/schemas/NominaJubilacionInput'
        separacion_indemnizacion:
          $ref: '#/components/schemas/NominaSeparacionInput'
    NominaPercepcionesProperties:
      type: object
      title: Percepciones
      description: Objeto para indicar las percepciones aplicables.
      properties:
        percepcion:
          type: array
          description: Objeto con información detallada de cada percepción.
          items:
            $ref: '#/components/schemas/NominaPercepcionProperties'
        jubilacion_pension_retiro:
          $ref: '#/components/schemas/NominaJubilacionProperties'
        separacion_indemnizacion:
          $ref: '#/components/schemas/NominaSeparacionProperties'
    NominaSeparacionInput:
      title: Separacion
      allOf:
        - type: object
          required:
            - total_pagado
            - num_anos_servicio
            - ultimo_sueldo_mens_ord
            - ingreso_acumulable
            - ingreso_no_acumulable
        - $ref: '#/components/schemas/NominaSeparacionProperties'
    NominaSeparacionProperties:
      type: object
      title: Jubilacion
      description: >-
        Objeto con información detallada de pagos por separación (despido) o
        indemnización.
      properties:
        total_pagado:
          type: number
          description: Monto total pagado por concepto de separación o indemnización.
        num_anos_servicio:
          type: integer
          description: >-
            Años de servicio que laboró el trabajador, redondeado al entero
            inmediato superior.
        ultimo_sueldo_mens_ord:
          type: number
          description: Último sueldo mensual ordinario percibido por el trabajador.
        ingreso_acumulable:
          type: number
          description: Monto por ingresos acumulables.
        ingreso_no_acumulable:
          type: number
          description: Monto por ingresos no acumulables.
    NominaJubilacionInput:
      title: Jubilacion
      allOf:
        - type: object
          required:
            - ingreso_acumulable
            - ingreso_no_acumulable
        - $ref: '#/components/schemas/NominaJubilacionProperties'
    NominaJubilacionProperties:
      type: object
      description: >-
        Objeto con información detallada de pagos por jubilación, pensiones o
        haberes de retiro.
      properties:
        total_una_exhibicion:
          type: number
          description: Monto total del pago entregado en una sola exhibición.
        total_parcialidad:
          type: number
          description: Monto total del pago entregado en parcialidades.
        monto_diario:
          type: number
          description: >-
            Monto diario percibido por el trabajador cuando el pago se realiza
            en parcialidades.
        ingreso_acumulable:
          type: number
          description: Ingresos acumulables percibidos por el trabajador.
        ingreso_no_acumulable:
          type: number
          description: Ingresos no acumulables percibidos por el trabajador.
    NominaPercepcionProperties:
      title: Percepcion
      allOf:
        - $ref: '#/components/schemas/NominaPercepcionDirectProperties'
        - $ref: '#/components/schemas/NominaPercepcionNestedProperties'
    NominaPercepcionInput:
      title: Percepcion
      allOf:
        - type: object
          required:
            - tipo_percepcion
            - clave
            - importe_gravado
            - importe_exento
        - $ref: '#/components/schemas/NominaPercepcionDirectProperties'
        - $ref: '#/components/schemas/NominaPercepcionNestedInput'
    NominaPercepcionDirectProperties:
      type: object
      properties:
        tipo_percepcion:
          type: string
          description: Clave del catálogo [Tipo de percepción](#tipo-de-percepcion).
        concepto:
          type: string
          description: >-
            Concepto de la percepción. Si no se envía, se utilizará la
            descripción del catálogo del tipo de percepción.
        clave:
          type: string
          minLength: 3
          maxLength: 15
          description: >-
            Clave de control interno que asigna el patrón a cada percepción de
            nómina propia de su contabilidad.
        importe_gravado:
          type: number
          description: Importe gravado por el concepto indicado en el tipo de percepción.
        importe_exento:
          type: number
          description: Importe exento por el concepto indicado en el tipo de percepción.
    NominaPercepcionNestedInput:
      type: object
      properties:
        acciones_o_titulos:
          $ref: '#/components/schemas/NominaAccionesInput'
        horas_extra:
          type: array
          description: >-
            Arreglo de objetos para expresar las horas extra aplicables.
            Requerido cuando el tipo de percepción es “019” (Horas extras).
          items:
            $ref: '#/components/schemas/NominaHorasExtraInput'
    NominaPercepcionNestedProperties:
      type: object
      properties:
        acciones_o_titulos:
          $ref: '#/components/schemas/NominaAccionesProperties'
        horas_extra:
          type: array
          description: >-
            Arreglo de objetos para expresar las horas extra aplicables.
            Requerido cuando el tipo de percepción es “019” (Horas extras).
          items:
            $ref: '#/components/schemas/NominaHorasExtraProperties'
    NominaHorasExtraInput:
      title: HorasExtra
      allOf:
        - type: object
          required:
            - dias
            - tipo_horas
            - horas_extra
            - importe_pagado
        - $ref: '#/components/schemas/NominaHorasExtraProperties'
    NominaHorasExtraProperties:
      type: object
      title: HorasExtra
      properties:
        dias:
          type: integer
          description: >-
            Número de días en que el trabajador laboró horas extra adicionales a
            su jornada normal de trabajo.
        tipo_horas:
          type: string
          description: Clave del catálogo [Tipo de Horas](#tipo-de-Horas).
        horas_extra:
          type: integer
          description: Número de horas extra trabajadas en el periodo.
        importe_pagado:
          type: number
          description: Importe pagado por las horas extra.
    NominaAccionesInput:
      title: Accion
      allOf:
        - type: object
          required:
            - valor_mercado
            - precio_al_otorgarse
        - $ref: '#/components/schemas/NominaAccionesProperties'
    NominaAccionesProperties:
      type: object
      title: Accion
      description: >-
        Objeto para expresar ingresos por acciones o títulos valor que
        representan bienes. Es requerido cuando existan ingresos por sueldos
        derivados de adquisición de acciones o títulos.
      properties:
        valor_mercado:
          type: number
          description: >-
            Valor de mercado de las Acciones o Títulos valor al ejercer la
            opción.
        precio_al_otorgarse:
          type: number
          description: >-
            Precio establecido al otorgarse la opción de ingresos en acciones o
            títulos valor.
    NominaReceptorProperties:
      type: object
      title: Receptor
      description: Información del trabajador.
      allOf:
        - $ref: '#/components/schemas/NominaReceptorDirectProperties'
        - $ref: '#/components/schemas/NominaReceptorNestedProperties'
    NominaReceptorInput:
      type: object
      title: Receptor
      description: Información del trabajador.
      allOf:
        - type: object
          required:
            - curp
            - tipo_contrato
            - tipo_regimen
            - num_empleado
            - periodicidad_pago
            - clave_ent_fed
        - $ref: '#/components/schemas/NominaReceptorDirectProperties'
        - $ref: '#/components/schemas/NominaReceptorNestedInput'
    NominaReceptorDirectProperties:
      type: object
      properties:
        curp:
          type: string
          description: CURP del trabajador.
        num_seguridad_social:
          type: string
          description: Número de seguridad social.
        fecha_inicio_rel_laboral:
          type: string
          format: date
          description: >-
            Fecha de inicio de la relación laboral entre el empleador y el
            empleado.
        antiguedad:
          oneOf:
            - type: string
            - type: boolean
          default: true
          description: >-
            Antigüedad del empleado en el formato especificado por el SAT. Si se
            envía un `string`, se espera que éste contenga la antigüedad en el
            formato que especifica el SAT. Si se envía el valor booleano
            `false`, este campo no se incluirá en la factura. Si se envía el
            valor booleano `true` y `fecha_inicio_rel_laboral` existe, este
            valor se calculará con la diferencia entre la fecha de inicio de
            relación laboral y la fecha de pago.
        tipo_contrato:
          type: string
          description: Clave del catálogo del SAT [Tipo de Contrato](#tipo-de-contrato).
        sindicalizado:
          type: boolean
          default: false
          description: Indica si el trabajador está asociado a un sindicato.
        tipo_jornada:
          type: string
          description: Clave del catálogo del SAT [Tipo de Jornada](#tipo-de-jornada).
        tipo_regimen:
          type: string
          description: Clave del catálogo del SAT [Tipo de Régimen](#régimen-fiscal).
        num_empleado:
          type: string
          minLength: 1
          maxLength: 15
          description: Número interno de empleado, asignado por el empleador.
        departamento:
          type: string
          description: Nombre del departamento o área a la que pertenece el trabajador.
        puesto:
          type: string
          description: >-
            Nombre del puesto asignado al empleado o el nombre de la actividad
            que realiza.
        riesgo_puesto:
          type: string
          description: Clave del catálogo del SAT [Riesgo del Puesto](#riesgo-del-puesto).
        periodicidad_pago:
          type: string
          description: >-
            Clave del catálogo del SAT [Periodicidad de
            Pago](#periodicidad-del-pago).
        banco:
          type: string
          description: >-
            Clave del banco de acuerdo al catálogo del SAT “Bancos” que puedes
            consultar utilizando nuestra [herramienta de
            búsqueda](https://dashboard.facturapi.io/catalogs/bank).
        cuenta_bancaria:
          type: string
          description: >
            Número de cuenta bancaria (11 caracteres) o número de teléfono
            celular (10 caracteres) o número de tarjeta (15 ó 16 caracteres) o
            la CLABE (18 caracteres) o número de monedero electrónico donde se
            realiza el depósito de nómina.
        salario_base_cot_apor:
          type: number
          description: >-
            Importe de la retribución en efectivo por cuota diaria,
            gratificaciones, percepciones, alimentación, habitación, primas,
            comisiones, prestaciones en especie, etc.
        salario_diario_integrado:
          type: number
          description: >-
            Salario que se integra con los pagos hechos en efectivo por cuota
            diaria, gratificaciones, percepciones, habitación, primas,
            comisiones, prestaciones en especie y cualquier otra cantidad o
            prestación que se entregue al trabajador por su trabajo.
        clave_ent_fed:
          type: string
          description: >-
            Clave de la entidad federativa en donde el trabajador prestó sus
            servicios al empleador, que puedes consultar utilizando nuestra
            [herramienta de
            búsqueda](https://dashboard.facturapi.io/catalogs/state).
    NominaReceptorNestedProperties:
      type: object
      properties:
        sub_contratacion:
          type: array
          description: >-
            Arreglo de objetos para expresar información sobre la empresa que se
            beneficia del trabajo del empleado, en casos donde el emisor preste
            servicios de subcontratación.
          items:
            $ref: '#/components/schemas/NominaSubContratacionProperties'
    NominaReceptorNestedInput:
      type: object
      properties:
        sub_contratacion:
          type: array
          description: >-
            Arreglo de objetos para expresar información sobre la empresa que se
            beneficia del trabajo del empleado, en casos donde el emisor preste
            servicios de subcontratación.
          items:
            allOf:
              - $ref: '#/components/schemas/NominaSubContratacionRequiredProperties'
              - $ref: '#/components/schemas/NominaSubContratacionProperties'
    NominaSubContratacionRequiredProperties:
      type: object
      required:
        - rfc_labora
        - porcentaje_tiempo
    NominaSubContratacionProperties:
      type: object
      properties:
        rfc_labora:
          type: string
          description: >-
            RFC de la persona o empresa que subcontrata, es decir, de la persona
            o empresa en donde el trabajador prestó directamente sus servicios.
        porcentaje_tiempo:
          type: number
          minimum: 0.001
          maximum: 100
          description: >-
            Porcentaje de tiempo en que el trabajador prestó sus servicios a la
            persona o empresa que lo subcontrató.
    NominaEmisorProperties:
      type: object
      title: Emisor
      description: Información del emisor, en caso de ser requerida.
      properties:
        curp:
          type: string
          minLength: 18
          maxLength: 18
          description: Requerido cuando el empleador es persona física. CURP del empleador.
        registro_patronal:
          type: string
          description: >-
            Clave de registro patronal asignada por la institución de seguridad
            social al patrón.
        rfc_patron_origen:
          minLength: 12
          maxLength: 13
          type: string
          description: >-
            RFC de la persona que fungió como patrón. Se usa cuando el pago se
            realiza a través de un tercero.
        entidad_sncf:
          type: object
          description: >-
            Información para que las entidades adheridas al Sistema Nacional de
            Coordinación Fiscal realicen la identificación del origen de los
            recursos.
          properties:
            origen_recurso:
              type: string
              enum:
                - IP
                - IF
                - IM
              description: |
                Clave de origen de recurso.

                - `“IP”`: Ingresos Propios
                - `“IF”`: Ingresos Federales
                - `“IM”`: Ingresos mixtos.
            monto_recurso_propio:
              type: number
              description: >
                Importe de recursos propios. Requerido cuando el origen del
                recurso es por ingresos mixtos.
    PagoOrCustomComplementProperties:
      title: Complement
      type: object
      discriminator:
        propertyName: type
        mapping:
          pago: '#/components/schemas/PagoComplementProperties'
          custom: '#/components/schemas/CustomComplementProperties'
      properties:
        type:
          type: string
          enum:
            - pago
            - custom
          description: Tipo de complemento.
    PagoOrCustomComplementInput:
      type: object
      title: Complement
      discriminator:
        propertyName: type
        mapping:
          pago: '#/components/schemas/PagoComplementInput'
          custom: '#/components/schemas/CustomComplementInput'
      required:
        - type
        - data
      properties:
        type:
          type: string
          enum:
            - nomina
            - custom
          description: Tipo de complemento.
    PagoComplementProperties:
      allOf:
        - $ref: '#/components/schemas/NominaOrCustomComplementProperties'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/NominaComplementDataProperties'
    PagoComplementInput:
      allOf:
        - $ref: '#/components/schemas/PagoOrCustomComplementInput'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/PagoComplementDataInput'
    PagoComplementDataInput:
      type: array
      title: PagoComplementData
      description: >-
        Pagos a incluir en este comprobante. Lo más común es incluir un sólo
        pago. Un caso en el que se debe de agregar más de uno es cuando el pago
        se realiza con 2 formas de pago distintas; por ejemplo, cuando se paga
        una parte con tarjeta y otra en efectivo.
      items:
        $ref: '#/components/schemas/PaymentInput'
    NominaOrCustomComplementProperties:
      title: Complement
      type: object
      discriminator:
        propertyName: type
        mapping:
          nomina: '#/components/schemas/NominaComplementProperties'
          custom: '#/components/schemas/CustomComplementProperties'
      properties:
        type:
          type: string
          enum:
            - nomina
            - custom
          description: Tipo de complemento.
    NominaOrCustomComplementInput:
      type: object
      title: Complement
      discriminator:
        propertyName: type
        mapping:
          nomina: '#/components/schemas/NominaComplementInput'
          custom: '#/components/schemas/CustomComplementInput'
      required:
        - type
        - data
      properties:
        type:
          type: string
          enum:
            - nomina
            - custom
          description: Tipo de complemento.
    NominaComplementProperties:
      allOf:
        - $ref: '#/components/schemas/NominaOrCustomComplementProperties'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/NominaComplementDataProperties'
    NominaComplementInput:
      allOf:
        - $ref: '#/components/schemas/NominaOrCustomComplementInput'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/NominaComplementDataInput'
    CartaPorteProperties:
      allOf:
        - $ref: '#/components/schemas/CartaPorteOrCustomComplementProperties'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/CartaPorteDataProperties'
    CartaPorteInput:
      allOf:
        - $ref: '#/components/schemas/CartaPorteOrCustomComplementInput'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/CartaPorteDataInput'
    ComercioExteriorProperties:
      allOf:
        - $ref: '#/components/schemas/CartaPorteOrCustomComplementProperties'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ComercioExteriorDataProperties'
    ComercioExteriorInput:
      allOf:
        - $ref: '#/components/schemas/CartaPorteOrCustomComplementInput'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ComercioExteriorDataInput'
    CartaPorteOrCustomComplementProperties:
      title: Complement
      type: object
      discriminator:
        propertyName: type
        mapping:
          carta_porte: '#/components/schemas/CartaPorteProperties'
          comercio_exterior: '#/components/schemas/ComercioExteriorProperties'
          custom: '#/components/schemas/CustomComplementProperties'
      properties:
        type:
          type: string
          enum:
            - carta_porte
            - comercio_exterior
            - custom
          description: Tipo de complemento.
    CartaPorteOrCustomComplementInput:
      title: Complement
      type: object
      discriminator:
        propertyName: type
        mapping:
          custom: '#/components/schemas/CustomComplementInput'
          carta_porte: '#/components/schemas/CartaPorteInput'
          comercio_exterior: '#/components/schemas/ComercioExteriorInput'
      required:
        - type
        - data
      properties:
        type:
          type: string
          enum:
            - carta_porte
            - comercio_exterior
            - custom
          description: Tipo de complemento.
    CartaPorteDataProperties:
      type: object
      title: CartaPorte
      description: Complemento Carta Porte versión 3.1. (Beta)
      required:
        - IdCCP
        - TranspInternac
        - Ubicaciones
        - Mercancias
      properties:
        IdCCP:
          type: string
          description: Identificador único de la Carta Porte.
        TranspInternac:
          type: string
          description: Indica si el transporte es internacional.
        EntradaSalidaMerc:
          type: string
          description: Entrada o salida de mercancías.
        PaisOrigenDestino:
          type: string
          description: País de origen o destino.
        ViaEntradaSalida:
          type: string
          description: Vía de entrada o salida.
        TotalDistRec:
          type: number
          description: Distancia total recorrida.
        RegistroISTMO:
          type: string
          description: Registro del programa ISTMO.
        UbicacionPoloOrigen:
          type: string
          description: Polo origen.
        UbicacionPoloDestino:
          type: string
          description: Polo destino.
        RegimenesAduaneros:
          type: object
          description: Objeto con los regímenes aduaneros aplicables.
        Ubicaciones:
          type: array
          description: Arreglo de ubicaciones.
          items:
            type: object
            description: Ubicación origen/destino.
            required:
              - TipoUbicacion
              - RFCRemitenteDestinatario
              - FechaHoraSalidaLlegada
            properties:
              TipoUbicacion:
                type: string
                description: >-
                  Atributo requerido para precisar si el tipo de ubicación
                  corresponde al origen o destino de las ubicaciones para el
                  traslado de los bienes y/o mercancías en los distintos medios
                  de transporte. Valores: "Origen" | "Destino".
              IDUbicacion:
                type: string
                description: >-
                  Atributo condicional para registrar una clave que identifique
                  el punto de salida o entrada de los bienes y/o mercancías.
                  Formato: "OR" o "DE" seguido de 6 dígitos numéricos (expresión
                  regular (OR|DE)[0-9]{6}).
              RFCRemitenteDestinatario:
                type: string
                description: >-
                  Atributo requerido para registrar el RFC del remitente o
                  destinatario de los bienes y/o mercancías que se trasladan.
              NombreRemitenteDestinatario:
                type: string
                description: >-
                  Atributo opcional para registrar el nombre del remitente o
                  destinatario de los bienes y/o mercancías (longitud 1 a 254
                  caracteres).
              NumRegIdTrib:
                type: string
                description: >-
                  Atributo condicional para el número de identificación o
                  registro fiscal del país de residencia del remitente o
                  destinatario cuando se trate de residentes en el extranjero
                  (longitud 6 a 40 caracteres).
              ResidenciaFiscal:
                type: string
                description: >-
                  Atributo condicional para registrar la clave del país de
                  residencia fiscal conforme al catálogo c_Pais (ISO 3166-1).
              NumEstacion:
                type: string
                description: >-
                  Atributo condicional para la clave de la estación de origen o
                  destino conforme al catálogo c_Estaciones del complemento
                  Carta Porte y al tipo de transporte.
              NombreEstacion:
                type: string
                description: >-
                  Atributo condicional para el nombre de la estación de origen o
                  destino conforme al catálogo c_Estaciones (longitud 1 a 50
                  caracteres).
              NavegacionTrafico:
                type: string
                description: >-
                  Atributo condicional para registrar el tipo de puerto de
                  origen o destino en transporte marítimo. Valores: "Altura" |
                  "Cabotaje".
              FechaHoraSalidaLlegada:
                type: string
                description: >-
                  Atributo requerido para registrar la fecha y hora estimada de
                  salida o llegada en formato AAAA-MM-DDThh:mm:ss.
              TipoEstacion:
                type: string
                description: >-
                  Atributo condicional para registrar el tipo de estación por la
                  que pasan las mercancías conforme al catálogo c_TipoEstacion.
              DistanciaRecorrida:
                type: number
                description: >-
                  Atributo condicional para registrar en kilómetros la distancia
                  recorrida entre la ubicación de origen y la de destino parcial
                  o final.
              Domicilio:
                $ref: '#/components/schemas/CartaPorteDomicilio'
        Mercancias:
          $ref: '#/components/schemas/CartaPorteMercancias'
        FiguraTransporte:
          type: array
          description: Figuras de transporte.
          items:
            type: object
            description: >-
              Figura de transporte (operador, propietario, arrendatario,
              notificado, etc.).
            required:
              - TipoFigura
              - NombreFigura
            properties:
              TipoFigura:
                type: string
                description: >-
                  Atributo requerido. Clave que identifica el tipo de figura de
                  transporte conforme al catálogo correspondiente (operador,
                  propietario, arrendatario, notificado). Debe coincidir con
                  c_TipoFigura.
              RFCFigura:
                type: string
                description: >-
                  RFC del operador/propietario/arrendatario o figura
                  interveniente.
              NumLicencia:
                type: string
                description: >-
                  Número de licencia del operador cuando TipoFigura corresponde
                  a operador.
              NombreFigura:
                type: string
                description: Nombre o razón social de la figura de transporte (requerido).
              NumRegIdTribFigura:
                type: string
                description: >-
                  Número de registro fiscal en el extranjero de la figura cuando
                  aplica.
              ResidenciaFiscalFigura:
                type: string
                description: >-
                  Clave del país de residencia fiscal de la figura (c_Pais)
                  cuando es extranjero.
              PartesTransporte:
                type: array
                description: >-
                  Arreglo opcional con las partes del transporte que se
                  relacionan a la figura.
                items:
                  type: object
                  required:
                    - ParteTransporte
                  properties:
                    ParteTransporte:
                      type: string
                      description: >-
                        Clave de la parte del transporte conforme al catálogo
                        c_ParteTransporte.
              Domicilio:
                $ref: '#/components/schemas/CartaPorteDomicilio'
                description: Domicilio asociado a la figura del transporte.
    CartaPorteDataInput:
      allOf:
        - $ref: '#/components/schemas/CartaPorteDataProperties'
    ComercioExteriorDataProperties:
      type: object
      title: ComercioExterior
      description: Complemento Comercio Exterior versión 2.0.
      required:
        - ClaveDePedimento
        - CertificadoOrigen
        - TipoCambioUSD
        - TotalUSD
        - Mercancias
      properties:
        Version:
          type: string
          default: '2.0'
          enum:
            - '2.0'
        MotivoTraslado:
          type: string
          description: Clave del catálogo c_MotivoTraslado.
        ClaveDePedimento:
          type: string
          description: Clave del pedimento (catálogo c_ClavePedimento).
        CertificadoOrigen:
          type: integer
          enum:
            - 0
            - 1
          description: Indica si existe certificado de origen.
        NumCertificadoOrigen:
          type: string
          minLength: 6
          maxLength: 40
          description: Número de certificado de origen.
        NumeroExportadorConfiable:
          type: string
          minLength: 1
          maxLength: 50
          description: Número de exportador confiable.
        Incoterm:
          type: string
          description: Clave del INCOTERM (catálogo c_INCOTERM).
        Observaciones:
          type: string
          minLength: 1
          maxLength: 300
        TipoCambioUSD:
          type: number
          minimum: 0
          description: Tipo de cambio USD.
        TotalUSD:
          type: number
          minimum: 0
          description: Total en USD.
        Emisor:
          description: >-
            Objeto con información del emisor del complemento. Requerido cuando
            el domicilio y CURP del emisor no se toman de la organización que
            emite el complemento.
          oneOf:
            - $ref: '#/components/schemas/ComercioExteriorEmisor'
            - type: boolean
              default: true
              description: >-
                Cuando es `true`, se utiliza el domicilio y CURP del emisor de
                la organización que emite el complemento. Por default es `true`.
        Propietario:
          type: array
          items:
            oneOf:
              - $ref: '#/components/schemas/ComercioExteriorPropietario'
              - $ref: '#/components/schemas/CustomerComercioExterior'
        Receptor:
          oneOf:
            - $ref: '#/components/schemas/ComercioExteriorReceptor'
            - $ref: '#/components/schemas/CustomerComercioExterior'
        Destinatario:
          type: array
          items:
            oneOf:
              - $ref: '#/components/schemas/ComercioExteriorDestinatario'
              - $ref: '#/components/schemas/CustomerComercioExterior'
        Mercancias:
          $ref: '#/components/schemas/ComercioExteriorMercancias'
    ComercioExteriorDataInput:
      allOf:
        - $ref: '#/components/schemas/ComercioExteriorDataProperties'
    ComercioExteriorDomicilio:
      type: object
      required:
        - Calle
        - Estado
        - Pais
        - CodigoPostal
      properties:
        Calle:
          type: string
          maxLength: 100
        NumeroExterior:
          type: string
          maxLength: 20
        NumeroInterior:
          type: string
          maxLength: 20
        Colonia:
          type: string
        Localidad:
          type: string
        Referencia:
          type: string
          maxLength: 150
        Municipio:
          type: string
        Estado:
          type: string
          minLength: 1
          maxLength: 30
        Pais:
          type: string
          description: Clave del catálogo c_Pais.
        CodigoPostal:
          type: string
          minLength: 1
          maxLength: 12
    ComercioExteriorEmisor:
      type: object
      required:
        - Domicilio
      properties:
        Domicilio:
          $ref: '#/components/schemas/ComercioExteriorDomicilio'
        Curp:
          type: string
          minLength: 18
          maxLength: 18
    ComercioExteriorPropietario:
      type: object
      required:
        - NumRegIdTrib
        - ResidenciaFiscal
      properties:
        NumRegIdTrib:
          type: string
          minLength: 6
          maxLength: 40
        ResidenciaFiscal:
          type: string
          description: Clave del catálogo c_Pais.
    ComercioExteriorReceptor:
      type: object
      properties:
        Domicilio:
          $ref: '#/components/schemas/ComercioExteriorDomicilio'
        NumRegIdTrib:
          type: string
          minLength: 6
          maxLength: 40
    ComercioExteriorDestinatario:
      type: object
      required:
        - Domicilio
      properties:
        Domicilio:
          type: array
          minItems: 1
          items:
            $ref: '#/components/schemas/ComercioExteriorDomicilio'
        NumRegIdTrib:
          type: string
          minLength: 6
          maxLength: 40
        Nombre:
          type: string
          minLength: 1
          maxLength: 300
    ComercioExteriorDescripcionesEspecificas:
      type: object
      required:
        - Marca
      properties:
        Marca:
          type: string
          minLength: 1
          maxLength: 35
        Modelo:
          type: string
          minLength: 1
          maxLength: 80
        SubModelo:
          type: string
          minLength: 1
          maxLength: 50
        NumeroSerie:
          type: string
          minLength: 1
          maxLength: 40
    ComercioExteriorMercancia:
      type: object
      required:
        - NoIdentificacion
        - ValorDolares
      properties:
        DescripcionesEspecificas:
          type: array
          items:
            $ref: '#/components/schemas/ComercioExteriorDescripcionesEspecificas'
        NoIdentificacion:
          type: string
          minLength: 1
          maxLength: 100
        FraccionArancelaria:
          type: string
          description: Clave del catálogo c_FraccionArancelaria.
        CantidadAduana:
          type: number
          minimum: 0.001
        UnidadAduana:
          type: string
          description: Clave del catálogo c_UnidadAduana.
        ValorUnitarioAduana:
          type: number
          minimum: 0
        ValorDolares:
          type: number
          minimum: 0
    ComercioExteriorMercancias:
      type: object
      required:
        - Mercancia
      properties:
        Mercancia:
          type: array
          minItems: 1
          items:
            $ref: '#/components/schemas/ComercioExteriorMercancia'
    CartaPorteCantidadTransporta:
      type: object
      required:
        - Cantidad
        - IDOrigen
        - IDDestino
      properties:
        Cantidad:
          type: number
        IDOrigen:
          type: string
        IDDestino:
          type: string
        CvesTransporte:
          type: string
          description: Clave del medio de transporte.
    CartaPorteDetalleMercancia:
      type: object
      required:
        - UnidadPesoMerc
        - PesoBruto
        - PesoNeto
        - PesoTara
      properties:
        UnidadPesoMerc:
          type: string
          description: >-
            Clave de la unidad de peso de la mercancía conforme al catálogo
            correspondiente.
        PesoBruto:
          type: number
          description: Peso bruto de la mercancía incluyendo embalajes y tare.
        PesoNeto:
          type: number
          description: Peso neto de la mercancía sin incluir embalajes ni tara.
        PesoTara:
          type: number
          description: Peso de la tara (contenedores, embalajes) asociado a la mercancía.
        NumPiezas:
          type: number
          description: Número de piezas que conforman la mercancía detallada.
    CartaPorteDocumentacionAduanera:
      type: object
      properties:
        TipoDocumento:
          type: string
          description: >-
            Tipo de documento aduanero (pedimento, guía, conocimiento)
            relacionado.
        NumPedimento:
          type: string
          description: Número de pedimento de importación/exportación.
        IdentDocAduanero:
          type: string
          description: Identificador alterno del documento aduanero.
        RFCImpo:
          type: string
      description: RFC del importador cuando aplica.
    CartaPorteGuiaIdentificacion:
      type: object
      properties:
        NumeroGuiaIdentificacion:
          type: string
          description: Número de la guía de identificación asociada a la mercancía.
        DescripGuiaIdentificacion:
          type: string
          description: Descripción detallada de la guía de identificación.
        PesoGuiaIdentificacion:
          type: number
          description: Peso amparado por la guía de identificación.
    CartaPorteMercancia:
      type: object
      required:
        - BienesTransp
        - Descripcion
        - Cantidad
        - ClaveUnidad
        - PesoEnKg
      properties:
        BienesTransp:
          type: string
          description: >-
            Clave del bien o producto transportado
            (catCartaPorte:c_BienesTransp).
        ClaveSTCC:
          type: string
          description: Clave STCC para transporte ferroviario cuando corresponda.
        Descripcion:
          type: string
          description: Descripción comercial del bien transportado.
        Cantidad:
          type: number
          description: Cantidad total de unidades del bien.
        ClaveUnidad:
          type: string
          description: Clave de unidad (c_ClaveUnidad) aplicable a la cantidad.
        Unidad:
          type: string
          description: Texto descriptivo de la unidad de medida.
        Dimensiones:
          type: string
          description: >-
            Dimensiones físicas de la mercancía (largo x ancho x alto) si
            aplica.
        MaterialPeligroso:
          type: string
          description: Indicador de si la mercancía es material peligroso ("Sí" / "No").
        CveMaterialPeligroso:
          type: string
          description: >-
            Clave del material peligroso (c_MaterialPeligroso) cuando
            MaterialPeligroso es Sí.
        Embalaje:
          type: string
          description: Clave del tipo de embalaje utilizado (c_TipoEmbalaje).
        DescripEmbalaje:
          type: string
          description: Descripción adicional del embalaje.
        SectorCOFEPRIS:
          type: string
          description: Sector regulado por COFEPRIS al que pertenece el producto.
        NombreIngredienteActivo:
          type: string
          description: Nombre del ingrediente activo (productos regulados).
        NomQuimico:
          type: string
          description: Nombre químico del producto cuando aplica.
        DenominacionGenericaProd:
          type: string
          description: Denominación genérica del producto farmacéutico.
        DenominacionDistintivaProd:
          type: string
          description: Denominación distintiva (marca) del producto farmacéutico.
        Fabricante:
          type: string
          description: Nombre o razón social del fabricante.
        FechaCaducidad:
          type: string
          description: Fecha de caducidad del producto (AAAAMMDD o formato aplicable).
        LoteMedicamento:
          type: string
          description: Número de lote del medicamento.
        FormaFarmaceutica:
          type: string
          description: Forma farmacéutica (tableta, cápsula, solución, etc.).
        CondicionesEspTransp:
          type: string
          description: Condiciones especiales de transporte (refrigeración, frágil, etc.).
        RegistroSanitarioFolioAutorizacion:
          type: string
          description: Registro sanitario o folio de autorización.
        PermisoImportacion:
          type: string
          description: Número de permiso de importación.
        FolioImpoVUCEM:
          type: string
          description: Folio VUCEM de importación.
        NumCAS:
          type: string
          description: Número CAS para sustancias químicas.
        RazonSocialEmpImp:
          type: string
          description: Razón social de la empresa importadora.
        NumRegSanPlagCOFEPRIS:
          type: string
          description: Número de registro sanitario o plaguicida COFEPRIS.
        DatosFabricante:
          type: string
          description: Información adicional del fabricante.
        DatosFormulador:
          type: string
          description: Información del formulador del producto.
        DatosMaquilador:
          type: string
          description: Información del maquilador (si aplica).
        UsoAutorizado:
          type: string
          description: Uso autorizado del producto.
        PesoEnKg:
          type: number
          description: >-
            Peso en kilogramos de la mercancía (puede ser peso neto o bruto
            según contexto).
        ValorMercancia:
          type: number
          description: Valor monetario de la mercancía.
        Moneda:
          type: string
          description: Clave de moneda (c_Moneda) del valor de la mercancía.
        FraccionArancelaria:
          type: string
          description: Fracción arancelaria aplicable (c_FraccionArancelaria).
        UUIDComercioExt:
          type: string
          description: UUID asociado al complemento de Comercio Exterior relacionado.
        TipoMateria:
          type: string
          description: Tipo de materia prima (si aplica para minerales, sustancias, etc.).
        DescripcionMateria:
          type: string
          description: Descripción de la materia prima.
        DocumentacionAduanera:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteDocumentacionAduanera'
          description: Documentos aduaneros asociados a la mercancía.
        GuiasIdentificacion:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteGuiaIdentificacion'
          description: Guías de identificación asociadas.
        CantidadTransporta:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteCantidadTransporta'
          description: Detalle de cantidades transportadas por origen/destino.
        DetalleMercancia:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteDetalleMercancia'
          description: Detalle de pesos y piezas de la mercancía.
    CartaPorteIdentificacionVehicular:
      type: object
      properties:
        ConfigVehicular:
          type: string
          description: >-
            Configuración vehicular (catCartaPorte:c_ConfigAutotransporte) del
            vehículo primario.
        PesoBrutoVehicular:
          type: number
          description: Peso bruto vehicular máximo permitido.
        PlacaVM:
          type: string
          description: Placa del vehículo motor.
        AnioModeloVM:
          type: string
          description: Año modelo del vehículo motor.
    CartaPorteSeguros:
      type: object
      properties:
        AseguraRespCivil:
          type: string
          description: Nombre de la aseguradora de responsabilidad civil.
        PolizaRespCivil:
          type: string
          description: Número de póliza de responsabilidad civil.
        AseguraMedAmbiente:
          type: string
          description: Aseguradora contra daños al medio ambiente.
        PolizaMedAmbiente:
          type: string
          description: Número de póliza de medio ambiente.
        AseguraCarga:
          type: string
          description: Aseguradora de la carga.
        PolizaCarga:
          type: string
          description: Número de póliza de la carga.
        PrimaSeguro:
          type: number
          description: Prima total de los seguros contratados.
    CartaPorteRemolque:
      type: object
      properties:
        SubTipoRem:
          type: string
          description: Subtipo de remolque (catCartaPorte:c_SubTipoRem).
        Placa:
          type: string
          description: Placa del remolque.
    CartaPorteAutotransporte:
      type: object
      properties:
        PermSCT:
          type: string
          description: Clave del permiso SCT del autotransporte.
        NumPermisoSCT:
          type: string
          description: Número del permiso SCT.
        IdentificacionVehicular:
          $ref: '#/components/schemas/CartaPorteIdentificacionVehicular'
          description: Datos de identificación del vehículo principal.
        Seguros:
          $ref: '#/components/schemas/CartaPorteSeguros'
          description: Información de seguros aplicables.
        Remolques:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteRemolque'
          description: Lista de remolques acoplados.
    CartaPorteContenedorMaritimo:
      type: object
      properties:
        TipoContenedor:
          type: string
          description: Tipo de contenedor marítimo (ISO / catálogo SAT).
        MatriculaContenedor:
          type: string
          description: Matrícula o número identificador del contenedor.
        NumPrecinto:
          type: string
          description: Número de precinto o sello de seguridad.
        IdCCPRelacionado:
          type: string
          description: Identificador CCP relacionado cuando se reutiliza información.
        PlacaVMCCP:
          type: string
          description: Placa del vehículo motor asociado (si aplica en transbordo).
        FechaCertificacionCCP:
          type: string
          description: Fecha de certificación CCP del contenedor.
        RemolquesCCP:
          type: array
          items:
            type: object
            properties:
              SubTipoRemCCP:
                type: string
                description: Subtipo de remolque relacionado (CCP).
              PlacaCCP:
                type: string
                description: Placa del remolque relacionado (CCP).
    CartaPorteTransporteMaritimo:
      type: object
      required:
        - PermSCT
        - NumPermisoSCT
      properties:
        PermSCT:
          type: string
          description: Clave del permiso SCT de la embarcación.
        NumPermisoSCT:
          type: string
          description: Número de permiso SCT de la embarcación.
        NombreAseg:
          type: string
          description: Nombre de la aseguradora marítima.
        NumPolizaSeguro:
          type: string
          description: Número de póliza de seguro marítimo.
        TipoEmbarcacion:
          type: string
          description: Tipo de embarcación (catCartaPorte:c_TipoEmbarcacion).
        Matricula:
          type: string
          description: Matrícula de la embarcación.
        NumeroOMI:
          type: string
          description: Número OMI (IMO number) de la embarcación.
        AnioEmbarcacion:
          type: string
          description: Año de construcción de la embarcación.
        NombreEmbarc:
          type: string
          description: Nombre propio de la embarcación.
        NacionalidadEmbarc:
          type: string
          description: Nacionalidad o bandera de la embarcación.
        UnidadesDeArqBruto:
          type: number
          description: Toneladas de arqueo bruto.
        TipoCarga:
          type: string
          description: Tipo de carga (granel, contenedores, líquidos, etc.).
        Eslora:
          type: number
          description: Longitud total de la embarcación (eslora).
        Manga:
          type: number
          description: Ancho máximo de la embarcación (manga).
        Calado:
          type: number
          description: Calado máximo.
        Puntal:
          type: number
          description: Altura del puntal.
        LineaNaviera:
          type: string
          description: Nombre de la línea naviera.
        NombreAgenteNaviero:
          type: string
          description: Nombre del agente naviero.
        NumAutorizacionNaviero:
          type: string
          description: Número de autorización del agente naviero.
        NumViaje:
          type: string
          description: Número de viaje o rotación.
        NumConocEmbarc:
          type: string
          description: Número de conocimiento de embarque.
        PermisoTempNavegacion:
          type: string
          description: Permiso temporal de navegación.
        Contenedor:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteContenedorMaritimo'
          description: Lista de contenedores asociados al embarque.
    CartaPorteTransporteAereo:
      type: object
      properties:
        PermSCT:
          type: string
          description: Clave del permiso SCT para transporte aéreo.
        NumPermisoSCT:
          type: string
          description: Número de permiso SCT.
        MatriculaAeronave:
          type: string
          description: Matrícula de la aeronave.
        NombreAseg:
          type: string
          description: Nombre de la aseguradora aérea.
        NumPolizaSeguro:
          type: string
          description: Número de póliza de seguro de la aeronave.
        NumeroGuia:
          type: string
          description: Número de guía aérea (Air Waybill).
        LugarContrato:
          type: string
          description: Lugar donde se celebró el contrato de transporte.
        CodigoTransportista:
          type: string
          description: Código del transportista aéreo.
        RFCEmbarcador:
          type: string
          description: RFC del embarcador.
        NumRegIdTribEmbarc:
          type: string
          description: Número de registro tributario extranjero del embarcador.
        ResidenciaFiscalEmbarc:
          type: string
          description: País de residencia fiscal del embarcador.
        NombreEmbarcador:
          type: string
          description: Nombre o razón social del embarcador.
    CartaPorteDerechosDePaso:
      type: object
      properties:
        TipoDerechoDePaso:
          type: string
          description: Tipo de derecho de paso ferroviario.
        KilometrajePagado:
          type: number
          description: Kilometraje cubierto/pagado en el derecho de paso.
    CartaPorteContenedorFerroviario:
      type: object
      properties:
        TipoContenedor:
          type: string
          description: Tipo de contenedor ferroviario.
        PesoContenedorVacio:
          type: number
          description: Peso del contenedor vacío.
        PesoNetoMercancia:
          type: number
          description: Peso neto de la mercancía contenida.
    CartaPorteCarroFerroviario:
      type: object
      properties:
        TipoCarro:
          type: string
          description: Tipo de carro ferroviario.
        MatriculaCarro:
          type: string
          description: Matrícula o número identificador del carro.
        GuiaCarro:
          type: string
          description: Número de guía asociado al carro.
        ToneladasNetasCarro:
          type: number
          description: Toneladas netas transportadas en el carro.
        Contenedor:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteContenedorFerroviario'
          description: Contenedores asociados al carro.
    CartaPorteTransporteFerroviario:
      type: object
      properties:
        TipoDeServicio:
          type: string
          description: Tipo de servicio ferroviario (regular, intermodal, etc.).
        TipoDeTrafico:
          type: string
          description: Tipo de tráfico (nacional, internacional, etc.).
        NombreAseg:
          type: string
          description: Nombre de la aseguradora ferroviaria.
        NumPolizaSeguro:
          type: string
          description: Número de póliza de seguro ferroviario.
        DerechosDePaso:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteDerechosDePaso'
          description: Lista de derechos de paso aplicados.
        Carro:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteCarroFerroviario'
          description: Lista de carros ferroviarios involucrados.
    CartaPorteDomicilio:
      type: object
      description: Domicilio relacionado a la ubicación en el complemento Carta Porte.
      required:
        - Estado
        - Pais
        - CodigoPostal
      properties:
        Calle:
          type: string
          description: Calle del domicilio de origen y/o destino (requerida en XSD).
        NumeroExterior:
          type: string
          description: Número exterior donde se ubica el domicilio.
        NumeroInterior:
          type: string
          description: Número interior del domicilio, si existe.
        Colonia:
          type: string
          description: Colonia o dato análogo del domicilio.
        Localidad:
          type: string
          description: Ciudad, población o distrito del domicilio.
        Referencia:
          type: string
          description: Referencia geográfica adicional (ej. coordenadas GPS).
        Municipio:
          type: string
          description: Municipio, delegación, alcaldía o análogo del domicilio.
        Estado:
          type: string
          description: >-
            Clave de estado, entidad o región (ISO 3166-2 conforme catálogo
            SAT).
        Pais:
          type: string
          description: Clave del país (catálogo c_Pais, ISO 3166-1).
        CodigoPostal:
          type: string
          description: Código postal del domicilio.
    CartaPorteMercancias:
      type: object
      required:
        - PesoBrutoTotal
        - UnidadPeso
        - NumTotalMercancias
        - Mercancia
      properties:
        PesoBrutoTotal:
          type: number
          description: Suma del peso bruto total de las mercancías (aéreo y ferroviario).
        UnidadPeso:
          type: string
          description: >-
            Clave de unidad de medida estandarizada del peso
            (catCartaPorte:c_ClaveUnidadPeso).
        PesoNetoTotal:
          type: number
          description: Suma de los valores PesoNeto de cada DetalleMercancia.
        NumTotalMercancias:
          type: number
          description: Número total de mercancías (cantidad de nodos Mercancia).
        CargoPorTasacion:
          type: number
          description: Importe pagado por la tasación de las mercancías (vía aérea).
        LogisticaInversaRecoleccionDevolucion:
          type: string
          description: Indica si aplica logística inversa, recolección o devolución.
        Mercancia:
          type: array
          items:
            $ref: '#/components/schemas/CartaPorteMercancia'
          description: Arreglo requerido con las mercancías transportadas.
        Autotransporte:
          $ref: '#/components/schemas/CartaPorteAutotransporte'
          description: Datos del autotransporte de carga federal.
        TransporteMaritimo:
          $ref: '#/components/schemas/CartaPorteTransporteMaritimo'
          description: Datos de la embarcación para transporte marítimo.
        TransporteAereo:
          $ref: '#/components/schemas/CartaPorteTransporteAereo'
          description: Datos del transporte aéreo utilizado.
        TransporteFerroviario:
          $ref: '#/components/schemas/CartaPorteTransporteFerroviario'
          description: Datos del transporte ferroviario utilizado.
    NamespaceRequiredProperties:
      type: object
      required:
        - prefix
        - uri
        - schema_location
    NamespaceProperties:
      type: object
      title: Namespace
      properties:
        prefix:
          type: string
          description: Prefijo o nombre del namespace.
          example: iedu
        uri:
          type: string
          format: url
          description: Dirección URL asociada al namespace.
          example: http://www.sat.gob.mx/iedu
        schema_location:
          type: string
          format: url
          example: http://www.sat.gob.mx/sitio_interet/cfd/iedu/iedu.xsd
          description: Dirección URL del esquema de validación XSD.
    CommonAddressProperties:
      type: object
      properties:
        street:
          type: string
          description: Nombre de la calle
          example: Blvd. Atardecer
        exterior:
          type: string
          description: Número exterior.
          example: 142
        interior:
          type: string
          description: Número interior.
          example: 4
        neighborhood:
          type: string
          description: Colonia
          example: Centro
        city:
          type: string
          description: Ciudad
          example: Huatabampo
        municipality:
          type: string
          description: Municipio o delegación
          example: Huatabampo
        zip:
          type: string
          description: Código postal
          example: 86500
    Webhook:
      title: Objeto Webhook
      allOf:
        - $ref: '#/components/schemas/ResourceAutoGeneratedProps'
        - $ref: '#/components/schemas/WebhookProperties'
    WebhookSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Webhook'
    WebhookProperties:
      properties:
        organization:
          type: string
          description: |
            Id de la organización la cual se está dando de alta el webhook.
        livemode:
          type: boolean
          example: false
          description: Ambiente en el cual se está dando de alta el webhook.
        enabled_events:
          type: string
          example:
            - receipt.cancellation_status
          description: Eventos dados de alta para el webhook.
        url:
          type: string
          format: email
          description: Http ruta para el webhook
          example: http://my-website.com/my/webhook
        status:
          type: string
          description: Status del webhook
          enum:
            - enabled
            - disabled
          example: enabled
    WebhookCreateInput:
      title: Webhook
      allOf:
        - type: object
          required:
            - enabled_events
            - url
          properties:
            url:
              type: string
              description: URL del webhook a dar de alta para recibir notificaciones.
              example: http://my-website.com/my/webhook
            enabled_events:
              type: array
              items:
                type: string
                enum:
                  - invoice.global_invoice_created
                  - invoice.status_updated
                  - invoice.created_from_dashboard
                  - invoice.cancellation_status_updated
                  - receipt.self_invoice_complete
                  - receipt.status_updated
                  - receipt.cancellation_status_updated
              description: Los eventos a los que el webhook se suscribirá.
              example:
                - receipt.self_invoice_complete
    WebhookCreateEdit:
      title: Webhook
      allOf:
        - type: object
          required:
            - enabled_events
          properties:
            status:
              type: string
              description: Estatus del webhook
              enum:
                - disabled
                - enabled
              example: disabled
            enabled_events:
              type: array
              items:
                type: string
                enum:
                  - invoice.global_invoice_created
                  - invoice.status_updated
                  - invoice.cancellation_status_updated
                  - invoice.created_from_dashboard
                  - receipt.self_invoice_complete
                  - receipt.cancellation_status_updated
                  - receipt.status_updated
              description: Los eventos a los que el webhook se suscribirá.
              example:
                - receipt.self_invoice_complete
    Customer:
      title: Objeto Customer
      allOf:
        - $ref: '#/components/schemas/ResourceAutoGeneratedProps'
        - $ref: '#/components/schemas/CustomerNonEditableProperties'
        - $ref: '#/components/schemas/CustomerProperties'
    CustomerSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Customer'
    CustomerNonEditableProperties:
      type: object
      properties:
        edit_link:
          type: string
          description: >
            Enlace a una página alojada donde el cliente puede editar su
            información una vez.

            Ejemplo: https://auto.facturapi.io/tax-info/abcdWXYZ1234
          example: https://auto.facturapi.io/tax-info/abcdWXYZ1234
        edit_link_expires_at:
          type: string
          format: date-time
          description: |
            Fecha de expiración del enlace de edición.
          example: '2022-12-31T23:59:59Z'
        sat_validated_at:
          type: string
          format: date-time
          description: |
            Fecha en la que la información fiscal fue validado por el SAT.
          example: '2022-12-31T23:59:59Z'
    CustomerProperties:
      allOf:
        - $ref: '#/components/schemas/CustomerCommonProperties'
        - type: object
          properties:
            address:
              allOf:
                - $ref: '#/components/schemas/CommonAddressProperties'
                - type: object
                  description: Domicilio fiscal.
                  properties:
                    state:
                      type: string
                      description: >-
                        Si el país es México ("MEX"), contiene el nombre del
                        Estado o Entidad Federativa. Para extranjeros contiene
                        el código de Estado de acuerdo al estándar [ISO
                        3166-2](https://en.wikipedia.org/wiki/ISO_3166-2), que
                        puedes consultar en nuestro [Catálogo de
                        Estados](https://dashboard.facturapi.io/catalogs/state).
                      example: Sonora
                    country:
                      type: string
                      description: >-
                        Código de país acorde al estándar [ISO 3166-1
                        alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3),
                        del [Catálogo de
                        Países](https://dashboard.facturapi.io/catalogs/country).
                      example: MEX
                      default: MEX
    CustomerCommonProperties:
      type: object
      properties:
        legal_name:
          type: string
          description: >
            Nombre Fiscal o Razón Social del cliente. *sin* el régimen
            societario (ej.: S.A. de C.V.).
          example: Dunder Mifflin
        tax_id:
          type: string
          example: ABC101010111
          description: >-
            En clientes de México contiene el RFC del cliente. Para extranjeros
            es opcional y representa el número de registro de identificacón
            tributaria, es decir, el equivalente al RFC en el país del cliente.
        tax_system:
          type: string
          example: '601'
          maxLength: 3
          minLength: 3
          description: >-
            Requerido para clientes nacionales. Clave del régimen fiscal del
            cliente, del catálogo de [Regímenes Fiscales](#r%C3%A9gimen-fiscal).
        email:
          type: string
          format: email
          description: >-
            Dirección de correo electrónico al cual enviar las facturas
            generadas.
          example: email@example.com
        phone:
          type: string
          description: Teléfono del cliente.
          example: 6474010101
        default_invoice_use:
          type: string
          description: Uso de CFDI por defecto.
          example: G01
    CustomerCreateInput:
      title: Customer
      allOf:
        - $ref: '#/components/schemas/CustomerCommonProperties'
        - type: object
          required:
            - legal_name
            - tax_id
            - tax_system
            - address
          properties:
            address:
              allOf:
                - $ref: '#/components/schemas/CommonAddressProperties'
                - type: object
                  description: Domicilio fiscal.
                  required:
                    - zip
                  properties:
                    state:
                      type: string
                      description: >-
                        Si el país es México ("MEX"), contiene el nombre del
                        Estado o Entidad Federativa. Para extranjeros contiene
                        el código de Estado de acuerdo al estándar [ISO
                        3166-2](https://en.wikipedia.org/wiki/ISO_3166-2), que
                        puedes consultar en nuestro [Catálogo de
                        Estados](https://dashboard.facturapi.io/catalogs/state).
                      example: Sonora
                    country:
                      type: string
                      description: >-
                        Código de país acorde al estándar [ISO 3166-1
                        alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3),
                        del [Catálogo de
                        Países](https://dashboard.facturapi.io/catalogs/country).
                      example: MEX
                      default: MEX
    LineItemProductInput:
      title: Product
      allOf:
        - $ref: '#/components/schemas/ProductProperties'
    LineItemProductEgresoInput:
      title: Product
      allOf:
        - $ref: '#/components/schemas/ProductEgresoProperties'
    LineItemTrasladoProductInput:
      title: Product
      required:
        - description
      type: object
      properties:
        description:
          type: string
          description: Descripción del bien o servicio como aparecerá en la factura.
          example: Ukelele
        product_key:
          type: string
          description: >-
            Clave de producto/servicio, del catálogo del SAT. Nosotros te
            proporcionamos una manera más conveniente de encontrarlo utilizando
            nuestra [herramienta de búsqueda de
            claves](https://dashboard.facturapi.io/catalogs/productKey).
          example: 60131324
        unit_key:
          type: string
          default: H87
          description: >
            Clave de unidad de medida, del catálogo del SAT. El valor por
            default `"H87"` (elemento) es la clave para representar una pieza o
            unidad de venta (lápiz, cuaderno, televisión, etc).

            Si la unidad de tu producto es kilogramos, litros, horas u otra
            unidad, te proporcionamos una manera conveniente de encontrar la
            clave utilizando nuestra [herramienta de búsqueda de
            claves](https://dashboard.facturapi.io/catalogs/unit).
        unit_name:
          type: string
          default: Elemento
          description: >-
            Palabra que representa la unidad de medida de tu producto. Debe
            estar relacionada con la clave de unidad `unit_key`.
        sku:
          type: string
          description: >-
            Identificador de uso interno designado por la empresa. Puede tener
            cualquier valor.
    LineItemProduct:
      allOf:
        - type: object
          properties:
            id:
              type: string
              description: >-
                ID del producto base. Sólo presente si se utilizó como base un
                objeto `Product` guardado previamente.
              example: 58e93bd8e86eb318b0197454
        - $ref: '#/components/schemas/ProductProperties'
    Parts:
      type: object
      properties:
        description:
          type: string
          description: Descripción del producto o servicio.
        product_key:
          type: string
          description: >-
            Clave de producto/servicio, del catálogo del SAT. Nosotros te
            proporcionamos una manera más conveniente de encontrarlo utilizando
            nuestra herramienta de búsqueda de claves.
        quantity:
          type: number
          description: Cantidad
          example: 1
        sku:
          type: string
          description: >-
            Identificador de uso interno designado por la empresa. Puede tener
            cualquier valor.
        unit_price:
          type: number
          description: Precio unitario
        unit_name:
          type: string
          description: Nombre de la unidad de medida que expresa la cantidad.
        customs_keys:
          type: array
          items:
            type: string
          description: Números de pedimento aduanal asociados a esta parte.
    PartInput:
      allOf:
        - type: object
          required:
            - description
            - product_key
        - $ref: '#/components/schemas/Parts'
    Product:
      title: Objeto Product
      allOf:
        - $ref: '#/components/schemas/ResourceAutoGeneratedProps'
        - $ref: '#/components/schemas/ProductProperties'
    ProductSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Product'
    ProductProperties:
      type: object
      required:
        - description
        - product_key
        - unit_key
        - price
      properties:
        description:
          type: string
          description: Descripción del bien o servicio como aparecerá en la factura.
          example: Ukelele
        product_key:
          type: string
          description: >-
            Clave de producto/servicio, del catálogo del SAT. Nosotros te
            proporcionamos una manera más conveniente de encontrarlo utilizando
            nuestra [herramienta de búsqueda de
            claves](https://dashboard.facturapi.io/catalogs/productKey).
          example: 60131324
        price:
          type: number
          description: >-
            Precio por unidad del bien o servicio. Este valor representará el
            precio con IVA incluído o sin él, dependiendo del valor de
            `tax_included`.
          example: 345.6
        tax_included:
          type: boolean
          default: true
          description: >
            - `true`: Indica que todos los impuestos aplicables están incluídos
            en el precio (atributo price) y se desglosarán automáticamente al
            emitir la factura.

            - `false`: Indica que el atributo price no incluye impuestos, por lo
            que aquellos impuestos a aplicar se sumarán en el precio final.
        taxability:
          type: string
          default: '02'
          enum:
            - '01'
            - '02'
            - '03'
            - '04'
            - '05'
            - '06'
            - '07'
            - '08'
          description: >
            Código que representa si el bien o servicio es objeto de impuesto o
            no. Este atributo corresponde al campo "ObjetoImp" en el CFDI.


            - `01`: No objeto de impuesto.

            - `02`: Sí objeto de impuesto.

            - `03`: Sí objeto de impuesto, pero no obligado a desglose.

            - `04`: Sí objeto de impuesto, y no causa impuesto.

            - `05`: Sí objeto de impuesto, IVA crédito PODEBI.

            - `06`: Sí objeto de impuesto, no IVA trasladado.

            - `07`: No traslado de IVA, pero desglose de IEPS.

            - `08`: No traslado de IVA sin desglose de IEPS.
        taxes:
          type: array
          default:
            - type: IVA
              rate: 0.16
          example:
            - type: IVA
              rate: 0.16
          description: >
            Lista de impuestos que deberán aplicarse a este producto.


            Resolución cuando `taxes` se omite o es `null`:

            - `taxability` omitido o `"02"`: se agrega IVA trasladado 16%.

            - `taxability` en `"01"`, `"03"`, `"04"`, `"05"`, `"06"` o `"08"`:
            se guarda `[]`.

            - `taxability = "07"`: la solicitud es inválida; debes enviar al
            menos un IEPS de traslado y no incluir IVA.


            Si envías `taxes` explícitamente, se usa el arreglo enviado.
          items:
            $ref: '#/components/schemas/BaseTax'
        local_taxes:
          type: array
          description: >-
            Arreglo de impuestos locales (estatales o municipales), en caso de
            haberlos.
          default: []
          items:
            $ref: '#/components/schemas/LocalTax'
        unit_key:
          type: string
          default: H87
          description: >
            Clave de unidad de medida, del catálogo del SAT. El valor por
            default `"H87"` (elemento) es la clave para representar una pieza o
            unidad de venta (lápiz, cuaderno, televisión, etc).

            Si la unidad de tu producto es kilogramos, litros, horas u otra
            unidad, puedes encontrar la clave utilizando nuestra [herramienta de
            búsqueda de claves](https://dashboard.facturapi.io/catalogs/unit).
        unit_name:
          type: string
          default: Elemento
          description: >-
            Palabra que representa la unidad de medida de tu producto. Debe
            estar relacionada con la clave de unidad `unit_key`.
        sku:
          type: string
          description: >-
            Identificador de uso interno designado por la empresa. Puede tener
            cualquier valor.
    ProductEgresoProperties:
      type: object
      properties:
        description:
          type: string
          description: >-
            Resumen de la operación en una sola descripción. Deben mencionarse
            cada uno de los productos que contempla el descuento, devolución o
            bonificación aplicada y que contienen las facturas relacionadas. Si
            el egreso está basado en un pocentaje (como al aplicar un 30% de
            descuento), dicho porcentaje debe incluirse en la descripción junto
            al nombre del producto que corresponda.
          example: Ukelele
        product_key:
          type: string
          default: 84111506
          description: >-
            Clave de producto/servicio, del catálogo del SAT. Nosotros te
            proporcionamos una manera más conveniente de encontrarlo utilizando
            nuestra [herramienta de búsqueda de
            claves](https://dashboard.facturapi.io/catalogs/productKey).
          example: 84111506
        price:
          type: number
          description: Suma total de la cantidad devuelta, descontada o bonificada.
          example: 345.6
        tax_included:
          type: boolean
          default: true
          description: >
            - `true`: Indica que todos los impuestos aplicables están incluídos
            en el precio (atributo price) y se desglosarán automáticamente al
            emitir la factura.

            - `false`: Indica que el atributo price no incluye impuestos, por lo
            que aquellos impuestos a aplicar se sumarán en el precio final.
        taxability:
          type: string
          default: '02'
          enum:
            - '01'
            - '02'
            - '03'
            - '04'
            - '05'
            - '06'
            - '07'
            - '08'
          description: >
            Código que representa si el bien o servicio es objeto de impuesto o
            no. Este atributo corresponde al campo "ObjetoImp" en el CFDI.


            - `01`: No objeto de impuesto.

            - `02`: Sí objeto de impuesto.

            - `03`: Sí objeto de impuesto, pero no obligado a desglose.

            - `04`: Sí objeto de impuesto, y no causa impuesto.

            - `05`: Sí objeto de impuesto, IVA crédito PODEBI.
        taxes:
          type: array
          default:
            - type: IVA
              rate: 0.16
          description: >
            Lista de impuestos que deberán aplicarse a este producto.


            Resolución cuando `taxes` se omite o es `null`:

            - `taxability` omitido o `"02"`: se agrega IVA trasladado 16%.

            - `taxability` en `"01"`, `"03"`, `"04"`, `"05"`, `"06"` o `"08"`:
            se guarda `[]`.

            - `taxability = "07"`: la solicitud es inválida; debes enviar al
            menos un IEPS de traslado y no incluir IVA.


            Si envías `taxes` explícitamente, se usa el arreglo enviado.
          items:
            $ref: '#/components/schemas/BaseTax'
        local_taxes:
          type: array
          description: >-
            Arreglo de impuestos locales (estatales o municipales), en caso de
            haberlos.
          default: []
          items:
            $ref: '#/components/schemas/LocalTax'
        unit_key:
          type: string
          default: ACT
          description: >
            Clave de unidad de medida, del catálogo del SAT.

            Puedes encontrar la clave utilizando nuestra [herramienta de
            búsqueda de claves](https://dashboard.facturapi.io/catalogs/unit).
        unit_name:
          type: string
          default: Actividad
          description: >-
            Palabra que representa la unidad de medida de tu producto. Debe
            estar relacionada con la clave de unidad `unit_key`.
      required:
        - description
        - price
    PaymentInput:
      title: Payment
      required:
        - payment_form
        - related_documents
      type: object
      properties:
        payment_form:
          type: string
          example: '03'
          description: >-
            Código de la forma de pago según el [catálogo del
            SAT](#forma-de-pago). También puedes utilizar la constante
            `PaymentForm` incluída en nuestras librerías.
        related_documents:
          type: array
          description: >-
            Arreglo que incluye un elemento por cada comprobante de ingreso
            relacionado a este pago. Lo más común es que el pago esté
            relacionado a un sólo comprobante de ingreso. Un caso en el que se
            agrega más de un elemento es cuando se recibe (por ejemplo) un sólo
            depósito que ampara el pago de 2 facturas relacionadas. En lugar de
            expedir un comprobante de recepción de pago por cada factura, debes
            expedir sólo uno relacionando los 2 comprobantes.
          items:
            type: object
            required:
              - uuid
              - amount
              - taxes
              - installment
              - last_balance
            properties:
              uuid:
                type: string
                format: uuid
                description: Folio fiscal ó UUID del comprobante de ingreso relacionado.
              amount:
                type: number
                description: |
                  Cantidad del pago correspondiente al comprobante relacionado,
                  usando el método de pago indicado en este elemento del arreglo
                  de pagos. Este valor debe ser expresado en la moneda definida
                  en `related_documents[].currency`.
              taxes:
                type: array
                description: >
                  Arreglo con impuestos del documento relacionado que aplican al
                  pago realizado.
                items:
                  type: object
                  required:
                    - base
                    - type
                    - rate
                  properties:
                    base:
                      type: number
                      description: |
                        Base utilizada para el cálculo del impuestos.
                    type:
                      type: string
                      enum:
                        - IVA
                        - ISR
                        - IEPS
                      description: |
                        Tipo de impuesto.
                    rate:
                      type: number
                      example: 0.16
                      description: |
                        Tasa o cuota del impuesto
                    factor:
                      type: string
                      default: Tasa
                      enum:
                        - Tasa
                        - Cuota
                        - Exento
                      description: Tipo factor.
                    withholding:
                      type: boolean
                      default: false
                      description: >-
                        Indica si el impuesto es una retención (`true`) o un
                        traslado (`false`).
              taxability:
                type: string
                default: >
                  '01' si el array `taxes` está vacío; '02' si el array `taxes`
                  tiene por lo menos un elemento.
                enum:
                  - '01'
                  - '02'
                  - '03'
                  - '04'
                  - '05'
                description: >
                  Código que representa si el bien o servicio es objeto de
                  impuesto o no. Este atributo corresponde al campo "ObjetoImp"
                  en el CFDI.


                  - `01`: No objeto de impuesto.

                  - `02`: Sí objeto de impuesto.

                  - `03`: Sí objeto de impuesto, pero no obligado a desglose.

                  - `04`: Sí objeto de impuesto, y no causa impuesto.

                  - `05`: Sí objeto de impuesto, IVA crédito PODEBI.
              installment:
                type: integer
                description: Número de parcialidad del pago.
              last_balance:
                type: number
                description: >-
                  Cantidad que estaba pendiente por pagar antes de recibir este
                  pago. Este valor se expresa en la moneda definida en
                  `related_documents[].currency`.
              currency:
                type: string
                minLength: 3
                maxLength: 3
                default: MXN
                description: >-
                  Si la moneda utilizada en la factura relacionada no es moneda
                  nacional (MXN), debe especificarse su valor acorde al estándar
                  [ISO 4217](https://es.wikipedia.org/wiki/ISO_4217).
              exchange:
                type: number
                description: >
                  Obligatorio cuando la moneda del documento relacionado es
                  distinta a la moneda de pago. Tipo de cambio entre las dos
                  monedas al momento del pago. Ejemplo: La factura de iingreso
                  relacionada se registra en USD, mientras que el pago actual se
                  realiza en MXN, este atributo debería registrarse como `0.45`
                  (USD/MXN).
              folio_number:
                type: integer
                description: >-
                  Opcionalmente se puede incluir el número de folio del
                  documento relacionado.
              series:
                type: string
                description: >-
                  Opcionalmente se puede incluir la serie del documento
                  relacionado.
        currency:
          type: string
          minLength: 3
          maxLength: 3
          default: MXN
          description: >-
            Código de la moneda, acorde al estándar [ISO
            4217](https://es.wikipedia.org/wiki/ISO_4217).
        exchange:
          type: number
          default: 1
          description: >-
            Tipo de cambio conforme a la moneda usada. Representa el número de
            pesos mexicanos que equivalen a una unidad de la divisa señalada en
            el atributo `currency`.
        date:
          type: string
          format: date-time
          default: now
          description: >-
            Fecha en que se recibió el pago. Sólo es necesario incluirla si el
            pago se efectuó en una fecha anterior a la emisión de este
            comprobante. No se permiten fechas futuras.
        numOperacion:
          type: string
          description: >-
            Número de cheque, de autorización, de referencia, clave de rastreo
            SPEI, línea de captura o algún número de referencia que permita
            identificar la operación correspondiente al pago efectuado.
        rfcEmisorCtaOrd:
          type: string
          description: >-
            RFC de la entidad emisora de la cuenta de origen, es decir, la
            operadora, banco, institución financiera, emisor de monedero
            electrónico, etc.
        nomBancoOrdExt:
          type: string
          description: Nombre del banco ordenante.
        ctaOrdenante:
          type: string
          description: Número de cuenta con la que se realizó el pago.
        rfcEmisorCtaBen:
          type: string
          description: >-
            RFC de la entidad de la cuenta operadora destino, es decir, la
            operadora, banco, institución financiera, emisor de monedero
            electrónico, etc.
        ctaBeneficiario:
          type: string
          description: Número de cuenta donde se recibió el pago.
        tipoCadPago:
          type: string
          enum:
            - 1
          description: >
            Clave del tipo de cadena de pago que genera la entidad receptora del
            pago.

            Si existe este campo, es obligatorio registrar los campos
            `certPago`, `cadPago` y `selloPago`.
        certPago:
          type: string
          format: base64
          description: >-
            Certificado que corresponde al pago, como una cadena de texto en
            formato base 64.
        cadPago:
          type: string
          description: >-
            Cadena original del comprobante de pago generado por la entidad
            emisora de la cuenta beneficiaria.
        selloPago:
          type: string
          format: base64
          description: >-
            Sello digital que se asocie al pago expresado como una cadena de
            texto en formato base 64.
    CustomerInfo:
      type: object
      description: >-
        Objeto con información parcial del cliente receptor del comprobante.
        Para obtener el objeto `Customer` completo, deberás consultarlo con el
        método de [Obtener Cliente]('#/operation/getCustomer').
      properties:
        id:
          type: string
          description: >-
            ID del objeto `customer` relacionado a la factura, en caso de no
            haber sido eliminado
          example: 58e93bd8e86eb318b0197456
        legal_name:
          type: string
          description: >
            Nombre Fiscal o Razón Social del cliente, *sin* incluir el régimen
            societario (ej.: S.A. de C.V.).
          example: Dunder Mifflin
        tax_id:
          type: string
          description: RFC del cliente.
          example: ABC101010111
        address:
          type: object
          properties:
            country:
              type: string
              format: ISO 3166-1 alpha-3
              description: >-
                Código de País acorde al estándar ISO 3166-1 alpha-3, del
                Catálogo de Países.
              example: MEX
    CustomerComercioExterior:
      type: object
      description: >-
        Objeto con información parcial del cliente receptor del comprobante.
        Para obtener el objeto `Customer` completo, deberás consultarlo con el
        método de [Obtener Cliente]('#/operation/getCustomer').
      properties:
        id:
          type: string
          description: >-
            ID del objeto `customer` relacionado a la factura, en caso de no
            haber sido eliminado
          example: 58e93bd8e86eb318b0197456
    RelatedDocumentInput:
      allOf:
        - type: object
          required:
            - relationship
            - related
        - $ref: '#/components/schemas/RelatedDocument'
    RelatedDocument:
      type: object
      properties:
        relationship:
          type: string
          description: >-
            Clave de relación del catálogo del SAT que puedes consultar en [esta
            tabla](#relacion-entre-facturas). Es requerido cuando se envíe el
            parámetro `related_documents`.
        documents:
          type: array
          default: []
          items:
            type: string
          description: Folios fiscales (UUID) de facturas relacionadas.
    Invoice:
      title: Objeto Invoice
      allOf:
        - $ref: '#/components/schemas/ResourceAutoGeneratedProps'
        - $ref: '#/components/schemas/InvoiceProperties'
    InvoiceDraft:
      title: Objeto Invoice con status draft
      allOf:
        - $ref: '#/components/schemas/ResourceAutoGeneratedProps'
        - $ref: '#/components/schemas/InvoiceDraftProperties'
    InvoiceSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Invoice'
    InvoiceRequiredProperties:
      type: object
      required:
        - description
        - invoice_key
        - price
    InvoiceProperties:
      type: object
      properties:
        status:
          type: string
          enum:
            - pending
            - valid
            - canceled
            - draft
          description: |
            Estado actual de la factura.
          example: valid
        cancellation_status:
          type: string
          enum:
            - none
            - pending
            - accepted
            - rejected
            - expired
          description: >
            Estado actual de la solicitud de cancelación, en caso de haberla
            realizado. Puedes leer más a detalle en la sección de [Cancelar
            Factura](#tag/invoice/operation/deleteInvoice)).
          example: none
        canceled_at:
          type: string
          format: date-time
          description: Fecha en la que se canceló el CFDI con hora aproximada.
        verification_url:
          type: string
          format: uri
          description: >-
            Dirección URL para verificar el estado del CFDI en el portal del
            SAT. Este link es el mismo que aparece en el código QR, en el PDF de
            la factura.
          example: >-
            https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx?id=45BEC0CA-5F1E-491E-9417-698EA48C382A&re=AAA010101AAA&rr=ABC101010111&tt=345.600000&fe=bWApPw==
        date:
          type: string
          format: date-time
          default: now
          description: Fecha de expedición del comprobante en formato ISO8601 (UTC String).
        address:
          allOf:
            - $ref: '#/components/schemas/CommonAddressProperties'
            - type: object
              description: Domicilio de expedición de la factura.
              properties:
                state:
                  type: string
                  description: Nombre del Estado o Entidad Federativa.
                  example: Sonora
        type:
          type: string
          enum:
            - I
            - E
            - P
            - 'N'
            - T
          description: >
            Tipo de comprobante. Puede tener los valores `"I"`: Ingreso, `"P"`:
            Pago, `"E"`: Egreso, `"N"`: Nómina, `"T"`: Traslado.
        customer:
          $ref: '#/components/schemas/CustomerInfo'
        total:
          type: number
          description: Monto total facturado.
          example: 10944.82
        uuid:
          type: string
          format: uuid
          description: Folio fiscal de la factura, asignado por el SAT.
          example: 39c85a3f-275b-4341-b259-e8971d9f8a94
        folio_number:
          type: integer
          description: >-
            Número de folio autoincremental para control interno y sin validez
            fiscal.
          example: 914
        series:
          type: string
          description: >-
            Serie. Caracteres designados por la empresa para control interno y
            sin validez fiscal. En el PDF se imprime junto al número de folio.
          example: F
        external_id:
          type: string
          description: >-
            Identificador que puedes usar para relacionar esta factura con tus
            registros para después buscar por este número.
        idempotency_key:
          type: string
          description: >-
            Identificador único que puedes usar para evitar duplicados al
            reintentar una petición. Puede ser cualquier cadena de texto,
            mientras sea única para cada documento.
        payment_form:
          type: string
          description: >-
            Código que representa la forma de pago, de acuerdo al [catálogo del
            SAT](#forma-de-pago).
          example: 6
        total_payment_amount:
          type: number
          description: Total del complemento de Pago cuando la factura es tipo P.
        total_payment_amount_converted:
          type: number
          description: >-
            Total del monto pagado convertido de la moneda de pago a Pesos
            Mexicanos.
        is_ready_to_stamp:
          type: boolean
          description: >
            Este campo es asignado automáticamente por Facturapi. Indica si una
            factura

            con status `draft` está completa y lista para intentar timbrarse. Si
            el valor es `true`, puedes

            intentar timbrar la factura con el método [Timbrar
            Factura]('#/operation/stampInvoice').

            Si el valor es `false`, debes usar el método [Actualizar
            Factura]('#/operation/updateDraftInvoice')

            para completar los campos faltantes.


            En una factura con status diferente a `draft`, este campo siempre
            será `false`.
        items:
          type: array
          description: Conceptos incluidos en el comprobante
          items:
            $ref: '#/components/schemas/LineItem'
        related_documents:
          type: array
          description: Documentos relacionados con la factura.
          items:
            $ref: '#/components/schemas/RelatedDocument'
        received_payment_ids:
          type: array
          items:
            type: string
          description: >
            En facturas con tipo I (Ingreso) y método de pago PPD, este campo
            lista los

            IDs de los comprobantes de pago cuyo arreglo de documentos
            relacionados incluye el UUID

            de esta factura. Este campo es llenado por Facturapi en el momento
            en que se crea o importa

            el comprobante de pago (tipo P), siempre y cuando pertenezca a la
            misma organización.
          default: []
        target_invoice_ids:
          type: array
          items:
            type: string
          description: >
            En facturas con tipo P (Pago), este arreglo lista los IDs de los
            comprobantes de ingreso

            listados en el arreglo de documentos relacionados. Este campo es
            llenado por Facturapi siempre

            y cuando el comprobante relacionado también esté registrado en
            Facturapi y pertenezca a la misma organización.
          default: []
        currency:
          type: string
          example: MXN
          description: >-
            Código de la moneda, acorde al estándar [ISO
            4217](https://es.wikipedia.org/wiki/ISO_4217).
        exchange:
          type: number
          minimum: 0
          example: 1
          description: >-
            Tipo de cambio conforme a la moneda usada. Representa el número de
            pesos mexicanos que equivalen a una unidad de la divisa señalada en
            el atributo `currency`.
        complements:
          type: array
          default: []
          items:
            $ref: '#/components/schemas/NominaOrCustomComplementProperties'
          description: Complementos a incluir en la factura.
        pdf_custom_section:
          type: string
          format: html
          description: >-
            En caso de que necesites incluir más información en el PDF, este
            campo te permite insertar código HTML con tu propio contenido.
        addenda:
          type: string
          format: xml
          description: Código XML con la Addenda que se necesite agregar a la factura.
        namespaces:
          type: array
          description: >-
            Namespaces a insertar en el nodo raíz de la factura. Requerido en
            `addenda`.
          items:
            $ref: '#/components/schemas/NamespaceProperties'
        stamp:
          $ref: '#/components/schemas/Stamp'
    InvoiceDraftProperties:
      type: object
      properties:
        status:
          type: string
          enum:
            - pending
            - valid
            - canceled
            - draft
          description: |
            Estado actual de la factura.
          example: draft
        cancellation_status:
          type: string
          enum:
            - none
            - pending
            - accepted
            - rejected
            - expired
          description: >
            Estado actual de la solicitud de cancelación, en caso de haberla
            realizado. Puedes leer más a detalle en la sección de [Cancelar
            Factura](#tag/invoice/operation/deleteInvoice)).
          example: none
        verification_url:
          type: string
          format: uri
          description: >-
            Dirección URL para verificar el estado del CFDI en el portal del
            SAT. Este link es el mismo que aparece en el código QR, en el PDF de
            la factura.
          example: null
        date:
          type: string
          format: date-time
          example: null
          description: >-
            Fecha de timbrado del comprobante en formato ISO8601 (UTC String).
            Si el estado es `draft`, este campo es nulo.
        address:
          allOf:
            - $ref: '#/components/schemas/CommonAddressProperties'
            - type: object
              description: Domicilio de expedición de la factura.
              properties:
                state:
                  type: string
                  description: Nombre del Estado o Entidad Federativa.
                  example: Sonora
        type:
          type: string
          enum:
            - I
            - E
            - P
            - 'N'
            - T
          description: >
            Tipo de comprobante. Puede tener los valores `"I"`: Ingreso, `"P"`:
            Pago, `"E"`: Egreso, `"N"`: Nómina, `"T"`: Traslado.
        customer:
          $ref: '#/components/schemas/CustomerInfo'
        total:
          type: number
          description: Monto total facturado.
          example: 0
        uuid:
          type: string
          format: uuid
          description: >-
            Folio fiscal de la factura, asignado por el SAT, en caso de haber
            sido timbrada.
          example: 0
        folio_number:
          type: integer
          description: >-
            Número de folio autoincremental para control interno y sin validez
            fiscal.
          example: 914
        series:
          type: string
          description: >-
            Serie. Caracteres designados por la empresa para control interno y
            sin validez fiscal. En el PDF se imprime junto al número de folio.
          example: F
        external_id:
          type: string
          description: >-
            Identificador que puedes usar para relacionar esta factura con tus
            registros para después buscar por este número.
        idempotency_key:
          type: string
          description: >-
            Identificador único que puedes usar para evitar duplicados al
            reintentar una petición. Puede ser cualquier cadena de texto,
            mientras sea única para cada documento.
        payment_form:
          type: string
          description: >-
            Código que representa la forma de pago, de acuerdo al [catálogo del
            SAT](#forma-de-pago).
          example: 6
        items:
          type: array
          description: Conceptos incluidos en el comprobante
          items:
            $ref: '#/components/schemas/LineItem'
        related_documents:
          type: array
          description: Documentos relacionados con la factura.
          items:
            $ref: '#/components/schemas/RelatedDocument'
        currency:
          type: string
          example: MXN
          description: >-
            Código de la moneda, acorde al estándar [ISO
            4217](https://es.wikipedia.org/wiki/ISO_4217).
        exchange:
          type: number
          minimum: 0
          example: 1
          description: >-
            Tipo de cambio conforme a la moneda usada. Representa el número de
            pesos mexicanos que equivalen a una unidad de la divisa señalada en
            el atributo `currency`.
        complements:
          type: array
          default: []
          items:
            $ref: '#/components/schemas/NominaOrCustomComplementProperties'
          description: Complementos a incluir en la factura.
        pdf_custom_section:
          type: string
          format: html
          description: >-
            En caso de que necesites incluir más información en el PDF, este
            campo te permite insertar código HTML con tu propio contenido.
        addenda:
          type: string
          format: xml
          description: Código XML con la Addenda que se necesite agregar a la factura.
        namespaces:
          type: array
          description: >-
            Namespaces a insertar en el nodo raíz de la factura. Requerido en
            `addenda`.
          items:
            $ref: '#/components/schemas/NamespaceProperties'
        is_ready_to_stamp:
          type: boolean
          description: >
            Este campo es asignado automáticamente por Facturapi. Indica si una
            factura

            con status `draft` está completa y lista para intentar timbrarse. Si
            el valor es `true`, puedes

            intentar timbrar la factura con el método [Timbrar
            Factura]('#/operation/stampInvoice').

            Si el valor es `false`, debes usar el método [Actualizar
            Factura]('#/operation/updateDraftInvoice')

            para completar los campos faltantes.


            En una factura con status diferente a `draft`, este campo siempre
            será `false`.
        stamp:
          allOf:
            - $ref: '#/components/schemas/Stamp'
            - type: object
              example: null
    InvoiceableCommonInput:
      type: object
      properties:
        folio_number:
          type: integer
          default: autoincremental
          description: >-
            Número de folio asignado por la empresa para control interno. Si se
            omite, se asignará el valor autoincremental de la organización.
        series:
          type: string
          maxLength: 25
          description: >-
            Serie. Caracteres designados por la empresa para control interno y
            sin validez fiscal.
        pdf_custom_section:
          type: string
          format: xml
          description: >
            En caso de que necesites incluir más información en el PDF, este
            campo te permite enviar código HTML con tu propio contenido.


            Por seguridad, el código que puedes enviar está limitado a las
            siguientes etiquetas: `h1`, `h2`, `h3`, `h4`, `h5`, `h6`, `div`,
            `p`, `span`, `small`, `br`, `b`, `i`, `ul`, `ol`, `li`, `strong`,
            `table`, `thead`, `tbody`, `tfoot`, `tr`, `th` y `td`. No se
            permiten atributos ni estilos.
        addenda:
          type: string
          format: xml
          description: Código XML con la Addenda que se necesite agregar a la factura.
        namespaces:
          type: array
          default: []
          description: >-
            Si incluiste el parámetro `complements`, este campo es opcional; en
            cambio si inclusite el parámetro `addenda`, debes enviar la
            información necesaria para incluir estos namespaces en el documento
            XML.
          items:
            allOf:
              - $ref: '#/components/schemas/NamespaceRequiredProperties'
              - $ref: '#/components/schemas/NamespaceProperties'
        pdf_options:
          type: object
          description: >-
            Configura qué campos opcionales se queiren mostrar en el PDF. El SAT
            no obliga a mostrar estos campos, pero pueden activarse según la
            preferencia del cliente para la factura en curso. Utiliza este campo
            para peticiones de generación de facturas en las cuales necesites
            utilizar una configuración distinta al campo pdf_extra de la
            organización.
          properties:
            codes:
              type: boolean
              default: true
              description: >
                Mostrar códigos de catálogos del SAT junto a sus descripciones.
                Ejemplo: “KGM Kilogramo”.
            product_key:
              type: boolean
              default: true
              description: |
                Mostrar la clave de producto-servicio.
            address_codes:
              type: boolean
              default: true
              description: >
                Mostrar los códigos estandarizados de estado y de país en el
                PDF.
            export_key:
              type: boolean
              default: false
              description: |
                Mostrar la clave de exportación en el PDF.
            round_unit_price:
              type: boolean
              default: false
              description: >
                Redondear el precio unitario en el PDF a 2 decimales, pero
                conservar los 6 decimales en el XML.
            tax_breakdown:
              type: boolean
              default: true
              description: >
                Mostrar el desglose de impuestos en el PDF. Si se desactiva,
                sólo se mostratán los impuestos en los totales, pero no en el
                detalle de cada concepto.
            ieps_breakdown:
              type: boolean
              default: true
              description: >
                Mostrar el desglose de IEPS en el PDF. Si se desactiva, solo se
                mostrarán los impuestos relacionados al IVA en el subtotal.    
            combine_ieps_with_subtotal:
              type: boolean
              default: false
              description: |
                Suma IEPS con subtotal sin desglosarlo en el PDF.
            render_carta_porte:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de Carta Porte 3.1 en el PDF sólo si
                el complemento de carta porte está incluido en la factura.
            render_iedu:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de Instituciones Educativas Privadas
                en el PDF.
            render_hyp_complement:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de hidrocarburos y petrolíferos en el
                PDF.
            render_comercio_exterior:
              type: boolean
              default: false
              description: |
                Renderizar el complemento de comercio exterior en el PDF.
            repeat_signature:
              type: boolean
              default: false
              description: |
                Repetir la firma electrónica en cada página del PDF.
            payroll_options:
              type: object
              properties:
                tipo_contrato:
                  type: boolean
                  default: false
                puesto:
                  type: boolean
                  default: false
                riesgo_puesto:
                  type: boolean
                  default: false
                antiguedad:
                  type: boolean
                  default: false
    InvoiceableCommonEditInput:
      type: object
      properties:
        folio_number:
          type: integer
          description: >-
            Número de folio asignado por la empresa para control interno. Si se
            omite, se asignará el valor autoincremental de la organización.
        series:
          type: string
          maxLength: 25
          description: >-
            Serie. Caracteres designados por la empresa para control interno y
            sin validez fiscal.
        pdf_custom_section:
          type: string
          format: xml
          description: >
            En caso de que necesites incluir más información en el PDF, este
            campo te permite enviar código HTML con tu propio contenido.


            Por seguridad, el código que puedes enviar está limitado a las
            siguientes etiquetas: `h1`, `h2`, `h3`, `h4`, `h5`, `h6`, `div`,
            `p`, `span`, `small`, `br`, `b`, `i`, `ul`, `ol`, `li`, `strong`,
            `table`, `thead`, `tbody`, `tfoot`, `tr`, `th` y `td`. No se
            permiten atributos ni estilos.
        addenda:
          type: string
          format: xml
          description: Código XML con la Addenda que se necesite agregar a la factura.
        namespaces:
          type: array
          description: >-
            Si incluiste el parámetro `complements`, este campo es opcional; en
            cambio si inclusite el parámetro `addenda`, debes enviar la
            información necesaria para incluir estos namespaces en el documento
            XML.
          items:
            allOf:
              - $ref: '#/components/schemas/NamespaceRequiredProperties'
              - $ref: '#/components/schemas/NamespaceProperties'
        pdf_options:
          type: object
          description: >-
            Configura qué campos opcionales se queiren mostrar en el PDF. El SAT
            no obliga a mostrar estos campos, pero pueden activarse según la
            preferencia del cliente para la factura en curso. Utiliza este campo
            para peticiones de generación de facturas en las cuales necesites
            utilizar una configuración distinta al campo pdf_extra de la
            organización.
          properties:
            codes:
              type: boolean
              default: true
              description: >
                Mostrar códigos de catálogos del SAT junto a sus descripciones.
                Ejemplo: “KGM Kilogramo”.
            product_key:
              type: boolean
              default: true
              description: |
                Mostrar la clave de producto-servicio.
            address_codes:
              type: boolean
              default: true
              description: >
                Mostrar los códigos estandarizados de estado y de país en el
                PDF.
            export_key:
              type: boolean
              default: false
              description: |
                Mostrar la clave de exportación en el PDF.
            round_unit_price:
              type: boolean
              default: false
              description: >
                Redondear el precio unitario en el PDF a 2 decimales, pero
                conservar los 6 decimales en el XML.
            tax_breakdown:
              type: boolean
              default: true
              description: >
                Mostrar el desglose de impuestos en el PDF. Si se desactiva,
                sólo se mostratán los impuestos en los totales, pero no en el
                detalle de cada concepto.
            ieps_breakdown:
              type: boolean
              default: true
              description: >
                Mostrar el desglose de IEPS en el PDF. Si se desactiva, solo se
                mostrarán los impuestos relacionados al IVA en el subtotal.   
            combine_ieps_with_subtotal:
              type: boolean
              default: false
              description: |
                Suma IEPS con subtotal sin desglosarlo en el PDF.
            render_carta_porte:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de Carta Porte 3.1 en el PDF sólo si
                el complemento de carta porte está incluido en la factura.
            render_iedu:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de Instituciones Educativas Privadas
                en el PDF.
            render_hyp_complement:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de hidrocarburos y petrolíferos en el
                PDF.
            render_comercio_exterior:
              type: boolean
              default: false
              description: |
                Renderizar el complemento de comercio exterior en el PDF.
            repeat_signature:
              type: boolean
              default: false
              description: |
                Repetir la firma electrónica en cada página del PDF.
            payroll_options:
              type: object
              properties:
                tipo_contrato:
                  type: boolean
                  default: false
                puesto:
                  type: boolean
                  default: false
                riesgo_puesto:
                  type: boolean
                  default: false
                antiguedad:
                  type: boolean
                  default: false
    InvoiceCommonInputProperties:
      allOf:
        - type: object
          properties:
            customer:
              description: Cliente receptor de la factura.
              oneOf:
                - $ref: '#/components/schemas/CustomerCreateInput'
                - type: string
                  title: customer_id
                  description: >-
                    ID del objeto 'customer' previamente registrado en
                    Facturapi.
                  example: 58e93bd8e86eb318b0197456
            status:
              type: string
              enum:
                - pending
                - draft
              default: pending
              description: >
                Estado inicial de la factura. Si se envía `draft`, la factura se
                guardará como borrador y no se timbrará ni se

                enviará al SAT. También al enviar `draft`, todos los campos
                requeridos se vuelven

                opcionales. Si se omite, el estado por default es `pending` y
                una vez timbrada (en la respuesta) este

                campo se actualizará a `valid`. Para facturas asíncronas, este
                campo se quedará en `pending` hasta que

                se timbre la factura.
              example: draft
            date:
              type: string
              format: date-time
              default: now
              description: >-
                Fecha de expedición del comprobante en formato ISO8601 (UTC
                String). No puede ser anterior a 72 horas en el pasado, ni
                posterior al presente.
            address:
              allOf:
                - $ref: '#/components/schemas/CommonAddressProperties'
                - type: object
                  description: >
                    Puedes usar este parámetro para especificar el domicilio de
                    expedición de la factura.

                    Este campo es opcional y si no se envía, la factura se
                    expedirá con el domicilio de

                    la organización.
                  required:
                    - zip
                  properties:
                    state:
                      type: string
                      description: Nombre del Estado o Entidad Federativa.
                      example: Sonora
            external_id:
              type: string
              description: >-
                Identificador opcional que puedes usar para relacionar esta
                factura con tus registros y poder hacer búsquedas usando este
                identificador. Facturapi no valida que este campo sea único.
            idempotency_key:
              type: string
              description: >
                Identificador único que puedes usar para evitar duplicados al
                reintentar una petición. Puede ser cualquier cadena de texto,
                mientras sea única para cada documento.

                Si se deja en blanco, no se tomará en cuenta.
        - $ref: '#/components/schemas/InvoiceableCommonInput'
    InvoiceCommonEditInputProperties:
      allOf:
        - type: object
          properties:
            customer:
              description: Cliente receptor de la factura.
              oneOf:
                - $ref: '#/components/schemas/CustomerCreateInput'
                - type: string
                  title: customer_id
                  description: >-
                    ID del objeto 'customer' previamente registrado en
                    Facturapi.
                  example: 58e93bd8e86eb318b0197456
            status:
              type: string
              enum:
                - draft
              description: >
                Estado inicial de la factura. Sólo es posible editar una factura
                con status `draft`,

                y no es posible cambiar el status al editar, por lo que el único
                valor permitido es `draft`.
              example: draft
            date:
              type: string
              format: date-time
              description: >-
                Fecha de expedición del comprobante en formato ISO8601 (UTC
                String). No puede ser anterior a 72 horas en el pasado, ni
                posterior al presente.
            address:
              allOf:
                - $ref: '#/components/schemas/CommonAddressProperties'
                - type: object
                  description: >
                    Puedes usar este parámetro para especificar el domicilio de
                    expedición de la factura.

                    Este campo es opcional y si no se envía, la factura se
                    expedirá con el domicilio de

                    la organización.
                  required:
                    - zip
                  properties:
                    state:
                      type: string
                      description: Nombre del Estado o Entidad Federativa.
                      example: Sonora
            external_id:
              type: string
              description: >-
                Identificador opcional que puedes usar para relacionar esta
                factura con tus registros y poder hacer búsquedas usando este
                identificador. Facturapi no valida que este campo sea único.
            idempotency_key:
              type: string
              description: >
                Identificador único que puedes usar para evitar duplicados al
                reintentar una petición. Puede ser cualquier cadena de texto,
                mientras sea única para cada documento.

                Si se deja en blanco, no se tomará en cuenta.
        - $ref: '#/components/schemas/InvoiceableCommonEditInput'
    InvoiceCreateInput:
      type: object
      oneOf:
        - title: Ingreso
          discriminator:
            propertyName: status
            mapping:
              pending: '#/components/schemas/InvoiceIngresoInput'
              draft: '#/components/schemas/InvoiceIngresoEditInput'
          properties:
            status:
              type: string
              enum:
                - pending
                - draft
              default: pending
              description: >
                Estado inicial de la factura. Si se envía `draft`, la factura se
                guardará como borrador y no se timbrará ni se

                enviará al SAT. También al enviar `draft`, todos los campos
                requeridos se vuelven

                opcionales. Si se omite, el estado por default es `pending` y
                una vez timbrada (en la respuesta) este

                campo se actualizará a `valid`. Para facturas asíncronas, este
                campo se quedará en `pending` hasta que

                se timbre la factura.
              example: draft
        - title: Egreso
          discriminator:
            propertyName: status
            mapping:
              pending: '#/components/schemas/InvoiceEgresoInput'
              draft: '#/components/schemas/InvoiceEgresoEditInput'
          properties:
            status:
              type: string
              enum:
                - pending
                - draft
              default: pending
              description: >
                Estado inicial de la factura. Si se envía `draft`, la factura se
                guardará como borrador y no se timbrará ni se

                enviará al SAT. También al enviar `draft`, todos los campos
                requeridos se vuelven

                opcionales. Si se omite, el estado por default es `pending` y
                una vez timbrada (en la respuesta) este

                campo se actualizará a `valid`. Para facturas asíncronas, este
                campo se quedará en `pending` hasta que

                se timbre la factura.
              example: draft
        - title: Pago
          discriminator:
            propertyName: status
            mapping:
              pending: '#/components/schemas/InvoicePagoInput'
              draft: '#/components/schemas/InvoicePagoEditInput'
          properties:
            status:
              type: string
              enum:
                - pending
                - draft
              default: pending
              description: >
                Estado inicial de la factura. Si se envía `draft`, la factura se
                guardará como borrador y no se timbrará ni se

                enviará al SAT. También al enviar `draft`, todos los campos
                requeridos se vuelven

                opcionales. Si se omite, el estado por default es `pending` y
                una vez timbrada (en la respuesta) este

                campo se actualizará a `valid`. Para facturas asíncronas, este
                campo se quedará en `pending` hasta que

                se timbre la factura.
              example: draft
        - title: Nómina
          discriminator:
            propertyName: status
            mapping:
              pending: '#/components/schemas/InvoiceNominaInput'
              draft: '#/components/schemas/InvoiceNominaEditInput'
          properties:
            status:
              type: string
              enum:
                - pending
                - draft
              default: pending
              description: >
                Estado inicial de la factura. Si se envía `draft`, la factura se
                guardará como borrador y no se timbrará ni se

                enviará al SAT. También al enviar `draft`, todos los campos
                requeridos se vuelven

                opcionales. Si se omite, el estado por default es `pending` y
                una vez timbrada (en la respuesta) este

                campo se actualizará a `valid`. Para facturas asíncronas, este
                campo se quedará en `pending` hasta que

                se timbre la factura.
              example: draft
        - title: Traslado
          discriminator:
            propertyName: status
            mapping:
              pending: '#/components/schemas/InvoiceTrasladoInput'
              draft: '#/components/schemas/InvoiceTrasladoEditInput'
          properties:
            status:
              type: string
              enum:
                - pending
                - draft
              default: pending
              description: >
                Estado inicial de la factura. Si se envía `draft`, la factura se
                guardará como borrador y no se timbrará ni se

                enviará al SAT. También al enviar `draft`, todos los campos
                requeridos se vuelven

                opcionales. Si se omite, el estado por default es `pending` y
                una vez timbrada (en la respuesta) este

                campo se actualizará a `valid`. Para facturas asíncronas, este
                campo se quedará en `pending` hasta que

                se timbre la factura.
              example: draft
    InvoiceIngresoInput:
      title: Ingreso
      required:
        - customer
        - items
        - payment_form
        - use
      allOf:
        - type: object
          properties:
            type:
              type: string
              enum:
                - I
              default: I
              description: Tipo de comprobante. El valor default es `“I”` (Ingreso).
            items:
              type: array
              maxItems: 5000
              description: >
                Conceptos a incluir en la factura.


                El número máximo de elementos que puedes incluir en una factura
                es de 5,000. Si necesitas

                emitir una factura con más de 5,000 conceptos, puedes dividir la
                transacción en varias facturas.
              items:
                $ref: '#/components/schemas/LineItemInput'
            payment_form:
              type: string
              minLength: 2
              maxLength: 2
              example: '03'
              description: >-
                Código que representa la forma de pago, de acuerdo al [catálogo
                del SAT](#forma-de-pago).
            payment_method:
              type: string
              default: PUE
              enum:
                - PUE
                - PPD
              description: |
                Código del método de pago según el catálogo del SAT.

                - `PUE`: Pago en Una sola Exhibición
                - `PPD`: Pago en Parcialidades o Diferido
            use:
              type: string
              default: G01
              description: >
                Código de Uso CFDI según el catálogo del SAT. Puedes ver los
                códigos

                en [esta tabla](#uso-cfdi), o utilizar las constantes incluídas
                en

                nuestras librerías.


                Para factura global debe ingresarse la clave `S01`.
            currency:
              type: string
              default: MXN
              description: >-
                Código de la moneda, acorde al estándar [ISO
                4217](https://es.wikipedia.org/wiki/ISO_4217).
            exchange:
              type: number
              default: 1
              description: >
                Tipo de cambio conforme a la moneda usada. Representa el número
                de pesos

                mexicanos (MXN) que equivalen a una unidad de la divisa señalada
                en el atributo `currency`.
            conditions:
              type: string
              minLength: 1
              maxLength: 1000
              description: Condiciones de pago
            related_documents:
              type: array
              description: Documentos relacionados con la factura.
              default: []
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
            global:
              type: object
              required:
                - periodicity
                - months
                - year
              description: |
                Objeto requerido al crear una factura global.
              properties:
                periodicity:
                  type: string
                  description: |
                    Periodicidad que abarca la factura global.

                    - `day`: Diario
                    - `week`: Semanal
                    - `fortnight`: Quincenal
                    - `month`: Mensual
                    - `two_months`: Bimestral
                  enum:
                    - day
                    - week
                    - fortnight
                    - month
                    - two_months
                months:
                  type: string
                  description: >
                    Clave que representa el mes o bimestre de la factura.
                    Consulta

                    los posibles valores en el [catálogo de Meses y
                    Bimestres](#meses-y-bimestres).
                  example: '01'
                year:
                  type: integer
                  description: Año de la factura.
                  example: 2022
            export:
              type: string
              default: '01'
              enum:
                - '01'
                - '02'
                - '03'
                - '04'
              description: >
                Indica si el comprobante ampara una operación de exportación.


                - `01`: No aplica

                - `02`: Definitiva con clave A1

                - `03`: Temporal

                - `04`: Definitiva con clave distinta a A1 o cuando no existe
                enajenación en términos del CFF
            complements:
              type: array
              default: []
              items:
                $ref: '#/components/schemas/CartaPorteOrCustomComplementInput'
              description: >
                Complementos a incluir en la factura. Puedes incluir cualquier
                complemento en la

                factura si tú mismo construyes el nodo XML del complemento y
                usas el tipo `custom`.

                Es necesario agregar la información del complemento al PDF por
                separado usando el

                parámetro `pdf_custom_section`.
        - $ref: '#/components/schemas/InvoiceCommonInputProperties'
    InvoiceEgresoInput:
      title: Egreso
      allOf:
        - type: object
          required:
            - type
            - customer
            - payment_form
            - items
          properties:
            type:
              type: string
              enum:
                - E
            payment_form:
              type: string
              minLength: 2
              maxLength: 2
              example: '03'
              description: >-
                Código que representa la forma de pago, de acuerdo al [catálogo
                del SAT](#forma-de-pago).
            related_documents:
              type: array
              description: Documentos relacionados con la nota de crédito.
              default: []
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
            items:
              type: array
              maxItems: 5000
              description: >
                Conceptos a incluir en la nota de crédito.


                El número máximo de elementos que puedes incluir en el
                comprobante es de 5,000. Si necesitas

                emitir un comprobante con más de 5,000 conceptos, puedes dividir
                la transacción en varios comprobantes.
              items:
                $ref: '#/components/schemas/LineItemEgresoInput'
            use:
              type: string
              default: G01
              description: >-
                Código de Uso CFDI según el catálogo del SAT. Puedes ver los
                códigos en [esta tabla](#uso-cfdi), o utilizar las constantes
                incluídas en nuestras librerías.
            currency:
              type: string
              default: MXN
              description: >-
                Código de la moneda, acorde al estándar [ISO
                4217](https://es.wikipedia.org/wiki/ISO_4217).
            exchange:
              type: number
              default: 1
              description: >-
                Tipo de cambio conforme a la moneda usada. Representa el número
                de pesos mexicanos (MXN) que equivalen a una unidad de la divisa
                señalada en el atributo `currency`.
            complements:
              type: array
              default: []
              items:
                $ref: '#/components/schemas/CustomComplementInput'
              description: >
                Complementos a incluir en el comprobante. Puedes incluir
                cualquier

                complemento en el comprobante si tú mismo construyes el nodo XML
                del

                complemento y usas el tipo `custom`. Es necesario agregar la
                información

                del complemento al PDF por separado usando el parámetro
                `pdf_custom_section`.
        - $ref: '#/components/schemas/InvoiceCommonInputProperties'
    InvoicePagoInput:
      title: Pago
      allOf:
        - type: object
          required:
            - type
            - customer
            - complements
          properties:
            type:
              type: string
              enum:
                - P
            related_documents:
              type: array
              description: Documentos relacionados con la factura.
              default: []
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
            third_party:
              allOf:
                - type: object
                  required:
                    - legal_name
                    - tax_id
                    - tax_system
                    - zip
                - $ref: '#/components/schemas/ThirdParty'
            complements:
              type: array
              default: []
              items:
                $ref: '#/components/schemas/PagoOrCustomComplementInput'
              description: Complementos a incluir en la factura.
        - $ref: '#/components/schemas/InvoiceCommonInputProperties'
    InvoiceNominaInput:
      title: Nómina
      allOf:
        - type: object
          required:
            - type
            - customer
            - complements
          properties:
            type:
              type: string
              enum:
                - 'N'
            complements:
              type: array
              default: []
              items:
                $ref: '#/components/schemas/NominaOrCustomComplementInput'
              description: Complementos a incluir en la factura.
            related_documents:
              type: array
              description: Documentos relacionados con la factura.
              default: []
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
        - $ref: '#/components/schemas/InvoiceCommonInputProperties'
    InvoiceTrasladoInput:
      title: Traslado
      allOf:
        - type: object
          required:
            - type
            - items
            - customer
          properties:
            type:
              type: string
              enum:
                - T
            items:
              type: array
              maxItems: 5000
              description: >
                Conceptos a incluir en el comprobante de Traslado.


                El número máximo de elementos que puedes incluir en un
                comprobante es de 5,000. Si necesitas

                emitir un comprobante con más de 5,000 conceptos, puedes dividir
                la transacción en varios comprobantes.
              items:
                $ref: '#/components/schemas/LineItemTrasladoInput'
            complements:
              type: array
              default: []
              items:
                $ref: '#/components/schemas/CartaPorteOrCustomComplementInput'
              description: >
                Complementos a incluir en el comprobante. Puedes incluir
                cualquier complemento en

                el comprobante si tú mismo construyes el nodo XML del
                complemento y usas el tipo

                `custom`. Es necesario agregar la información del complemento al
                PDF por separado

                usando el parámetro `pdf_custom_section`.
            use:
              type: string
              default: G01
              description: >
                Código de Uso CFDI según el catálogo del SAT. Puedes ver los
                códigos en

                [esta tabla](#uso-cfdi), o utilizar las constantes incluídas en
                nuestras librerías.
            currency:
              type: string
              default: MXN
              description: >-
                Código de la moneda, acorde al estándar [ISO
                4217](https://es.wikipedia.org/wiki/ISO_4217).
            exchange:
              type: number
              default: 1
              description: >
                Tipo de cambio conforme a la moneda usada. Representa el número
                de pesos mexicanos

                (MXN) que equivalen a una unidad de la divisa señalada en el
                atributo `currency`.
            related_documents:
              type: array
              description: Documentos relacionados con el comprobante.
              default: []
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
        - $ref: '#/components/schemas/InvoiceCommonInputProperties'
    InvoiceIngresoEditInput:
      title: Ingreso
      allOf:
        - type: object
          properties:
            type:
              type: string
              enum:
                - I
                - E
                - P
                - 'N'
                - T
              description: >
                Tipo de comprobante. Puede tener los valores `"I"`: Ingreso,
                `"P"`: Pago, `"E"`: Egreso, `"N"`: Nómina, `"T"`: Traslado.
            items:
              type: array
              maxItems: 5000
              description: >
                Conceptos a incluir en la factura.


                El número máximo de elementos que puedes incluir en una factura
                es de 5,000. Si necesitas

                emitir una factura con más de 5,000 conceptos, puedes dividir la
                transacción en varias facturas.
              items:
                $ref: '#/components/schemas/LineItemInput'
            payment_form:
              type: string
              minLength: 2
              maxLength: 2
              example: '03'
              description: >-
                Código que representa la forma de pago, de acuerdo al [catálogo
                del SAT](#forma-de-pago).
            payment_method:
              type: string
              enum:
                - PUE
                - PPD
              description: |
                Código del método de pago según el catálogo del SAT.

                - `PUE`: Pago en Una sola Exhibición
                - `PPD`: Pago en Parcialidades o Diferido
            use:
              type: string
              example: G01
              description: >
                Código de Uso CFDI según el catálogo del SAT. Puedes ver los
                códigos

                en [esta tabla](#uso-cfdi), o utilizar las constantes incluídas
                en

                nuestras librerías.


                Para factura global debe ingresarse la clave `S01`.
            currency:
              type: string
              example: MXN
              description: >-
                Código de la moneda, acorde al estándar [ISO
                4217](https://es.wikipedia.org/wiki/ISO_4217).
            exchange:
              type: number
              description: >
                Tipo de cambio conforme a la moneda usada. Representa el número
                de pesos

                mexicanos (MXN) que equivalen a una unidad de la divisa señalada
                en el atributo `currency`.
            conditions:
              type: string
              minLength: 1
              maxLength: 1000
              description: Condiciones de pago
            related_documents:
              type: array
              description: Documentos relacionados con la factura.
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
            global:
              type: object
              required:
                - periodicity
                - months
                - year
              description: |
                Objeto requerido al crear una factura global.
              properties:
                periodicity:
                  type: string
                  description: |
                    Periodicidad que abarca la factura global.

                    - `day`: Diario
                    - `week`: Semanal
                    - `fortnight`: Quincenal
                    - `month`: Mensual
                    - `two_months`: Bimestral
                  enum:
                    - day
                    - week
                    - fortnight
                    - month
                    - two_months
                months:
                  type: string
                  description: >
                    Clave que representa el mes o bimestre de la factura.
                    Consulta

                    los posibles valores en el [catálogo de Meses y
                    Bimestres](#meses-y-bimestres).
                  example: '01'
                year:
                  type: integer
                  description: Año de la factura.
                  example: 2022
            export:
              type: string
              enum:
                - '01'
                - '02'
                - '03'
                - '04'
              description: >
                Indica si el comprobante ampara una operación de exportación.


                - `01`: No aplica

                - `02`: Definitiva con clave A1

                - `03`: Temporal

                - `04`: Definitiva con clave distinta a A1 o cuando no existe
                enajenación en términos del CFF
            complements:
              type: array
              items:
                $ref: '#/components/schemas/CustomComplementInput'
              description: >
                Complementos a incluir en la factura. Puedes incluir cualquier
                complemento en la

                factura si tú mismo construyes el nodo XML del complemento y
                usas el tipo `custom`.

                Es necesario agregar la información del complemento al PDF por
                separado usando el

                parámetro `pdf_custom_section`.
        - $ref: '#/components/schemas/InvoiceCommonEditInputProperties'
    InvoiceEgresoEditInput:
      title: Egreso
      allOf:
        - type: object
          properties:
            type:
              type: string
              enum:
                - I
                - E
                - P
                - 'N'
                - T
              description: >
                Tipo de comprobante. Puede tener los valores `"I"`: Ingreso,
                `"P"`: Pago, `"E"`: Egreso, `"N"`: Nómina, `"T"`: Traslado.
            payment_form:
              type: string
              minLength: 2
              maxLength: 2
              example: '03'
              description: >-
                Código que representa la forma de pago, de acuerdo al [catálogo
                del SAT](#forma-de-pago).
            related_documents:
              type: array
              description: Documentos relacionados con la nota de crédito.
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
            items:
              type: array
              maxItems: 5000
              description: >
                Conceptos a incluir en la nota de crédito.


                El número máximo de elementos que puedes incluir en el
                comprobante es de 5,000. Si necesitas

                emitir un comprobante con más de 5,000 conceptos, puedes dividir
                la transacción en varios comprobantes.
              items:
                $ref: '#/components/schemas/LineItemEgresoInput'
            use:
              type: string
              example: G01
              description: >-
                Código de Uso CFDI según el catálogo del SAT. Puedes ver los
                códigos en [esta tabla](#uso-cfdi), o utilizar las constantes
                incluídas en nuestras librerías.
            currency:
              type: string
              example: MXN
              description: >-
                Código de la moneda, acorde al estándar [ISO
                4217](https://es.wikipedia.org/wiki/ISO_4217).
            exchange:
              type: number
              description: >-
                Tipo de cambio conforme a la moneda usada. Representa el número
                de pesos mexicanos (MXN) que equivalen a una unidad de la divisa
                señalada en el atributo `currency`.
            complements:
              type: array
              items:
                $ref: '#/components/schemas/CustomComplementInput'
              description: >
                Complementos a incluir en el comprobante. Puedes incluir
                cualquier

                complemento en el comprobante si tú mismo construyes el nodo XML
                del

                complemento y usas el tipo `custom`. Es necesario agregar la
                información

                del complemento al PDF por separado usando el parámetro
                `pdf_custom_section`.
        - $ref: '#/components/schemas/InvoiceCommonInputProperties'
    InvoicePagoEditInput:
      title: Pago
      allOf:
        - type: object
          properties:
            type:
              type: string
              enum:
                - I
                - E
                - P
                - 'N'
                - T
              description: >
                Tipo de comprobante. Puede tener los valores `"I"`: Ingreso,
                `"P"`: Pago, `"E"`: Egreso, `"N"`: Nómina, `"T"`: Traslado.
            related_documents:
              type: array
              description: Documentos relacionados con la factura.
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
            third_party:
              allOf:
                - type: object
                  required:
                    - legal_name
                    - tax_id
                    - tax_system
                    - zip
                - $ref: '#/components/schemas/ThirdParty'
            complements:
              type: array
              items:
                $ref: '#/components/schemas/PagoOrCustomComplementInput'
              description: Complementos a incluir en la factura.
        - $ref: '#/components/schemas/InvoiceCommonEditInputProperties'
    InvoiceNominaEditInput:
      title: Nómina
      allOf:
        - type: object
          properties:
            type:
              type: string
              enum:
                - I
                - E
                - P
                - 'N'
                - T
              description: >
                Tipo de comprobante. Puede tener los valores `"I"`: Ingreso,
                `"P"`: Pago, `"E"`: Egreso, `"N"`: Nómina, `"T"`: Traslado.
            complements:
              type: array
              items:
                $ref: '#/components/schemas/NominaOrCustomComplementInput'
              description: Complementos a incluir en la factura.
            related_documents:
              type: array
              description: Documentos relacionados con la factura.
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
        - $ref: '#/components/schemas/InvoiceCommonEditInputProperties'
    InvoiceTrasladoEditInput:
      title: Traslado
      allOf:
        - type: object
          properties:
            type:
              type: string
              enum:
                - I
                - E
                - P
                - 'N'
                - T
              description: >
                Tipo de comprobante. Puede tener los valores `"I"`: Ingreso,
                `"P"`: Pago, `"E"`: Egreso, `"N"`: Nómina, `"T"`: Traslado.
            items:
              type: array
              maxItems: 5000
              description: >
                Conceptos a incluir en el comprobante de Traslado.


                El número máximo de elementos que puedes incluir en un
                comprobante es de 5,000. Si necesitas

                emitir un comprobante con más de 5,000 conceptos, puedes dividir
                la transacción en varios comprobantes.
              items:
                $ref: '#/components/schemas/LineItemTrasladoInput'
            complements:
              type: array
              items:
                $ref: '#/components/schemas/CustomComplementInput'
              description: >
                Complementos a incluir en el comprobante. Puedes incluir
                cualquier complemento en

                el comprobante si tú mismo construyes el nodo XML del
                complemento y usas el tipo

                `custom`. Es necesario agregar la información del complemento al
                PDF por separado

                usando el parámetro `pdf_custom_section`.
            use:
              type: string
              example: G01
              description: >
                Código de Uso CFDI según el catálogo del SAT. Puedes ver los
                códigos en

                [esta tabla](#uso-cfdi), o utilizar las constantes incluídas en
                nuestras librerías.
            currency:
              type: string
              example: MXN
              description: >-
                Código de la moneda, acorde al estándar [ISO
                4217](https://es.wikipedia.org/wiki/ISO_4217).
            exchange:
              type: number
              description: >
                Tipo de cambio conforme a la moneda usada. Representa el número
                de pesos mexicanos

                (MXN) que equivalen a una unidad de la divisa señalada en el
                atributo `currency`.
            related_documents:
              type: array
              description: Documentos relacionados con el comprobante.
              items:
                $ref: '#/components/schemas/RelatedDocumentInput'
        - $ref: '#/components/schemas/InvoiceCommonEditInputProperties'
    Receipt:
      title: Objeto Receipt
      allOf:
        - $ref: '#/components/schemas/ResourceAutoGeneratedProps'
        - $ref: '#/components/schemas/ReceiptProperties'
    ReceiptProperties:
      allOf:
        - type: object
          properties:
            date:
              type: string
              format: date-time
              example: '2021-09-10T15:21:23.456Z'
              description: Fecha de emisión del recibo.
            expires_at:
              type: string
              format: date-time
              example: '2021-09-17T15:21:23.456Z'
              description: >
                Fecha de expiración en formato ISO8601 (UTC String).

                Es la fecha límite para que el cliente pueda facturar su recibo
                en el portal de autofactura.

                Se calcula automáticamente a partir de las configuraciones de
                recibo de la organización.
            status:
              type: string
              enum:
                - open
                - canceled
                - invoiced_to_customer
                - invoiced_globally
              description: Estado actual del recibo.
            self_invoice_url:
              type: string
              format: url
              example: https://factura.space/empresa-demo/r9YqYarL
              description: >
                Dirección URL para realizar autofactura. Incluye el `key` del
                recibo.

                Puedes usarla para generar un botón o un QR de facturación para
                tus clientes.
            total:
              type: number
              example: 356.78
              description: Monto total de la operación
            invoice:
              type: string
              example: 614496b471d422de4b6cfcc4
              description: ID de la factura asociada, en caso de estar facturado.
            customer:
              type: string
              example: 58e93bd8e86eb318b0197456
              description: ID del cliente asociado al recibo, en caso de haberse asignado.
            key:
              type: string
              example: r9YqYarL
              description: >-
                Autogenerado. Identificador único alfanumérico corto, útil para
                acceder a la autofactura desde tu micrositio en factura.space
            items:
              type: array
              description: Conceptos incluidos en el recibo
              items:
                $ref: '#/components/schemas/LineItem'
            external_id:
              type: string
              description: >-
                Identificador que puedes usar para relacionar este recibo con
                tus registros para después buscar por este número.
            idempotency_key:
              type: string
              description: >-
                Identificador único que puedes usar para evitar duplicados al
                reintentar una petición. Puede ser cualquier cadena de texto,
                mientras sea única para cada documento.
        - $ref: '#/components/schemas/ReceiptEditableProperties'
    ReceiptInput:
      allOf:
        - type: object
          required:
            - items
            - payment_form
          properties:
            customer:
              description: >
                Cliente asociado al recibo. Puedes enviar el ID de un cliente
                existente o un objeto de cliente para crearlo.
              oneOf:
                - type: string
                  minLength: 24
                  maxLength: 24
                  example: 58e93bd8e86eb318b0197456
                - $ref: '#/components/schemas/CustomerCreateInput'
            items:
              type: array
              maxItems: 5000
              description: >
                Conceptos a incluir en el recibo.


                El número máximo de elementos que puedes incluir en un recxibo
                es de 5,000. Si necesitas

                emitir una recibo con más de 5,000 conceptos, prueba dividir la
                transacción en varios recibos.
              items:
                $ref: '#/components/schemas/LineItemInput'
        - $ref: '#/components/schemas/ReceiptEditableProperties'
        - type: object
          properties:
            idempotency_key:
              type: string
              description: >
                Identificador único que puedes usar para evitar duplicados al
                reintentar una petición. Puede ser cualquier cadena de texto,
                mientras sea única para cada documento.

                Si se deja en blanco, no se tomará en cuenta.
    ReceiptEditableProperties:
      type: object
      properties:
        date:
          type: string
          format: date-time
          example: '2021-09-10T15:21:23.456Z'
          description: Fecha de emisión del recibo. Por defecto se utiliza la fecha actual.
        payment_form:
          type: string
          example: '03'
          description: >-
            Código que representa la forma de pago, según el [catálogo del
            SAT](#forma-de-pago).
        folio_number:
          type: integer
          example: 120
          description: >-
            Autoincremental. Número de folio del recibo para control interno y
            sin validez fiscal.
        currency:
          type: string
          example: MXN
          description: >-
            Código de la moneda, acorde al estándar [ISO
            4217](https://es.wikipedia.org/wiki/ISO_4217).
        exchange:
          type: number
          minimum: 0
          example: 1
          description: >-
            Tipo de cambio conforme a la moneda usada. Representa el número de
            pesos mexicanos que equivalen a una unidad de la divisa señalada en
            el atributo `currency`.
        branch:
          type: string
          description: Nombre de la sucursal donde se expidió el recibo.
        external_id:
          type: string
          description: >-
            Identificador opcional que puedes usar para relacionar este recibo
            con tus registros y poder hacer búsquedas usando este identificador.
            Facturapi no valida que este campo sea único.
    ReceiptAssignCustomerInput:
      type: object
      required:
        - customer
      properties:
        customer:
          description: >
            Cliente a asignar o reasignar al recibo. Puedes enviar el ID de un
            cliente existente o un objeto de cliente para crearlo.
          oneOf:
            - type: string
              minLength: 24
              maxLength: 24
              example: 58e93bd8e86eb318b0197456
            - $ref: '#/components/schemas/CustomerCreateInput'
    ReceiptSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Receipt'
    InvoiceReceiptInput:
      type: object
      allOf:
        - type: object
          properties:
            customer:
              description: >
                Cliente receptor de la factura. Puedes enviarlo como ID de un
                cliente existente

                o como objeto para crear un cliente nuevo. Si lo omites, el
                recibo debe tener

                un cliente asignado previamente.
              oneOf:
                - $ref: '#/components/schemas/CustomerCreateInput'
                - type: string
                  title: customer_id
                  description: >-
                    ID del objeto 'customer' previamente registrado en
                    Facturapi.
                  example: 58e93bd8e86eb318b0197456
            use:
              type: string
              default: G01
              description: >-
                Código de Uso CFDI según el catálogo del SAT. Puedes ver los
                códigos en [esta tabla](#uso-cfdi), o utilizar las constantes
                incluídas en nuestras librerías.
            conditions:
              type: string
              minLength: 1
              maxLength: 1000
              description: Condiciones de pago
        - $ref: '#/components/schemas/InvoiceableCommonInput'
    GlobalInvoiceInput:
      type: object
      required:
        - periodicity
      properties:
        from:
          type: string
          format: date
          default: Inicio del último periodo
          example: '2022-01-01T00:00:00.000'
          description: >
            Fecha inicial de los recibos que se incluirán en la factura global.

            Por default, este valor es el inicio del último periodo (día,
            semana,

            quincena o mes), según el valor de "Periodicidad" (`periodicity`)

            en la configuración de recibos de tu organización. Este valor es
            requerido cuando se envíe el campo `receipts`.
        to:
          type: string
          format: date
          default: Fin del último periodo
          example: '2022-31-01T23:59:59.999'
          description: >
            Fecha final de los recibos que se incluirán en la factura global.

            Por default, este valor es el fin del último periodo (día, semana,

            quincena o mes), según el valor de "Periodicidad" (`periodicity`)

            en la configuración de recibos de tu organización. Este valor es
            requerido cuando se envíe el campo `receipts`.
        periodicity:
          type: string
          default: >-
            Propiedad `periodicity` de la configuración de recibos de la
            organización.
          enum:
            - day
            - week
            - fortnight
            - month
            - two_months
          description: >
            Periodicidad que corresponde al rango de fechas utilizado.

            Si se omite, se tomará la configuración de recibos de la
            organización. 

            Si omites enviar los campos `from` y `to`, las fechas que se
            asignarán por default dependerán del valor de periodicity.
        months:
          type: string
          default: Mes contenido en el rango de fechas utilizado.
          description: >
            Clave que representa el mes o bimestre de la factura. Consulta

            los posibles valores en el [catálogo de Meses y
            Bimestres](#meses-y-bimestres).
          example: '01'
        folio_number:
          type: integer
          default: autoincremental
          description: >
            Número de folio asignado por la empresa para control interno.

            Si se omite, se asignará el valor autoincremental de la
            organización.
        series:
          type: string
          maxLength: 25
          description: >-
            Serie. Caracteres designados por la empresa para control interno y
            sin validez fiscal.
        date:
          type: string
          format: date
          default: Valor del atributo `to`
          example: '2022-01-01T00:00:00.000'
          description: |
            Fecha de emisión de la factura.
        payment_form:
          type: string
          minLength: 2
          maxLength: 2
          example: '02'
          description: >
            description: Código que representa la forma de pago, de acuerdo al
            [catálogo del SAT](#forma-de-pago). Si se incluye, los recibos se
            agruparán y se crearán la factura global por la forma de pago.
        receipts:
          type: array
          description: >
            Recibos a incluir en la factura global. Si se incluye este
            parámetro, los parámetros `from` y `to` serán requeridos y tendrán
            que cumplir con el campo `periodicity`.
          items:
            type: string
            format: hex
            minLength: 24
            maxLength: 24
            description: ID de un recibo previamente registrado en Facturapi.
            example: 614496b471d422de4b6cfcc4
    ToInvoiceInput:
      type: object
      required:
        - keys
      properties:
        keys:
          type: array
          minItems: 1
          maxItems: 1000
          description: Lista de keys de recibos que se incluirán en la factura.
          items:
            type: string
            description: Key del recibo.
            example: ticket_1001
        customer:
          oneOf:
            - $ref: '#/components/schemas/CustomerCreateInput'
            - type: string
              title: customer_id
              description: ID de un cliente previamente registrado en Facturapi.
              example: 58e93bd8e86eb318b0197456
          description: >
            Cliente receptor de la factura. Si lo envías, sobrescribe el cliente

            asignado a los recibos incluidos. Si lo omites, todos los recibos
            deben

            tener asignado el mismo cliente. Esta regla también aplica cuando

            `dry_run` es `true`.
        use:
          type: string
          default: G01
          description: Código de Uso CFDI según catálogo del SAT.
        dry_run:
          type: boolean
          default: false
          description: Si es `true`, sólo valida y regresa un resumen sin crear la factura.
        payment_form:
          type: string
          nullable: true
          minLength: 2
          maxLength: 2
          example: '03'
          description: |
            Código de forma de pago según el [catálogo del SAT](#forma-de-pago).
    ToInvoicePreviewInput:
      type: object
      required:
        - keys
      properties:
        keys:
          type: array
          minItems: 1
          maxItems: 1000
          description: Lista de keys de recibos que se incluirán en la vista previa.
          items:
            type: string
            description: Key del recibo.
            example: ticket_1001
        customer:
          nullable: true
          oneOf:
            - $ref: '#/components/schemas/CustomerCreateInput'
            - type: string
              title: customer_id
              description: ID de un cliente previamente registrado en Facturapi.
              example: 58e93bd8e86eb318b0197456
          description: |
            Cliente opcional para renderizar la vista previa. Si lo omites,
            todos los recibos deben tener asignado el mismo cliente.
        use:
          type: string
          default: G01
          description: Código de Uso CFDI según catálogo del SAT.
    ToInvoiceSummary:
      type: object
      description: Objeto resumen que regresa cuando `dry_run=true`.
    ToInvoiceNotFoundResponse:
      type: object
      required:
        - invoice
        - summary
        - missingKeys
      properties:
        invoice:
          nullable: true
          type: object
          description: Siempre `null` cuando no se creó la factura.
        summary:
          nullable: true
          type: object
          description: Resumen de vista previa cuando está disponible.
        missingKeys:
          type: array
          description: Keys de recibos no encontradas o no elegibles.
          items:
            type: string
    Retention:
      title: Objeto Retention
      allOf:
        - $ref: '#/components/schemas/ResourceAutoGeneratedProps'
        - $ref: '#/components/schemas/RetentionReadOnlyProperties'
        - $ref: '#/components/schemas/RetentionProperties'
    RetentionReadOnlyProperties:
      type: object
      properties:
        status:
          type: string
          enum:
            - valid
            - canceled
          description: |
            Estado actual de la retención.
          example: valid
        verification_url:
          type: string
          format: uri
          description: >-
            Dirección URL para verificar el estado de la retención en el portal
            del SAT. Este link es el mismo que aparece en el código QR, en el
            PDF de la retención.
          example: >-
            https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx?id=45BEC0CA-5F1E-491E-9417-698EA48C382A&re=AAA010101AAA&rr=ABC101010111&tt=345.600000&fe=bWApPw==
        type:
          type: string
          enum:
            - Retención
          example: Retención
          description: Tipo de comprobante.
        uuid:
          type: string
          format: uuid
          description: Folio fiscal de la retención, asignado por el SAT.
          example: 39c85a3f-275b-4341-b259-e8971d9f8a94
        stamp:
          $ref: '#/components/schemas/Stamp'
        customer:
          $ref: '#/components/schemas/CustomerInfo'
    RetentionProperties:
      type: object
      properties:
        cve_retenc:
          type: string
          example: 1
          description: >-
            Clave de la retención o información de pagos de acuerdo al catálogo
            del SAT.
        fecha_exp:
          type: string
          format: date-time
          example: '2021-09-15T06:03:23.000Z'
          description: Fecha de expedición del comprobante en formato ISO8601 (UTC String).
        desc_retenc:
          type: string
          description: >-
            Si la clave de la retención es “25” (Otro tipo de retenciones), este
            campo se usa para registrar la descripción de la retención.
        folio_int:
          type: string
          description: >-
            Identificador alfanumérico para control interno de la empresa y sin
            relevancia fiscal.
        periodo:
          type: object
          description: Información sobre el periodo de la retención.
          properties:
            mes_ini:
              type: integer
              minimum: 1
              maximum: 12
              description: Mes inicial del periodo de la retención.
            mes_fin:
              type: integer
              minimum: 1
              maximum: 12
              description: Mes final del periodo de la retención.
            ejerc:
              type: integer
              description: Año o ejercicio fiscal en que se realizó la retención.
        totales:
          type: object
          description: >-
            Información sobre el total de retenciones efectuadas en el periodo
            correspondiente.
          properties:
            monto_tot_operacion:
              type: number
              minimum: 0
              description: Monto total de la operación, con precisión de hasta 6 decimales.
            monto_tot_grav:
              type: number
              minimum: 0
              description: Monto total gravado.
            monto_tot_exent:
              type: number
              minimum: 0
              description: Monto total exento.
            monto_tot_ret:
              type: number
              minimum: 0
              description: Suma de los montos de impuestos retenidos.
            imp_retenidos:
              type: array
              description: Colección de impuestos retenidos.
              items:
                type: object
                properties:
                  base:
                    type: number
                    minimum: 0
                    description: Base del impuesto retenido.
                  impuesto:
                    type: string
                    enum:
                      - IVA
                      - ISR
                    example: IVA
                    description: Clave del tipo de impuesto retenido, del catálogo del SAT.
                  monto:
                    type: number
                    minimum: 0
                    description: Importe del impuesto retenido
                  tipo_pago_ret:
                    type: string
                    enum:
                      - 1
                      - 2
                      - 3
                      - 4
                    description: |
                      - `01`: Pago definitivo IVA
                      - `02`: Pago definitivo IEPS
                      - `03`: Pago definitivo ISR Plataformas
                      - `04`: Pago provisional ISR
        external_id:
          type: string
          description: >-
            Identificador opcional que puedes usar para relacionar esta
            retención con tus registros y poder hacer búsquedas usando este
            identificador. Facturapi no valida que este campo sea único.
        idempotency_key:
          type: string
          description: >
            Identificador único que puedes usar para evitar duplicados al
            reintentar una petición. Puede ser cualquier cadena de texto,
            mientras sea única para cada documento.

            Si se deja en blanco, no se tomará en cuenta.
        complements:
          type: array
          default: []
          items:
            $ref: '#/components/schemas/CustomComplementData'
          description: >
            Arreglo de complementos a incluir en la factura. Cada elemento
            contiene

            un `string` con el código XML del complemento.
        pdf_custom_section:
          type: string
          format: html
          description: >-
            En caso de que necesites incluir más información en el PDF, este
            campo te permite insertar código HTML con tu propio contenido.
        addenda:
          type: string
          format: xml
          description: Código XML con la Addenda que se necesite agregar a la factura.
        namespaces:
          type: array
          description: >-
            Namespaces a insertar en el nodo raíz de la factura. Requerido en
            `addenda`.
          items:
            $ref: '#/components/schemas/NamespaceProperties'
    RetentionSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Retention'
    RetentionInput:
      type: object
      required:
        - customer
        - cve_retenc
        - periodo
        - totales
      properties:
        customer:
          description: Cliente receptor de la factura.
          oneOf:
            - $ref: '#/components/schemas/CustomerCreateInput'
            - type: string
              title: customer_id
              description: ID del objeto 'customer' previamente registrado en Facturapi.
              example: 58e93bd8e86eb318b0197456
        cve_retenc:
          type: string
          example: 26
          description: >-
            Clave de la retención o información de pagos de acuerdo al [catálogo
            del SAT](#clave-de-retencion).
        fecha_exp:
          type: string
          format: date-time
          example: '2021-09-15T06:03:23.000Z'
          description: Fecha de expedición del comprobante en formato ISO8601 (UTC String).
        desc_retenc:
          type: string
          description: >-
            Si la clave de la retención es “25” (Otro tipo de retenciones), este
            campo se usa para registrar la descripción de la retención.
        folio_int:
          type: string
          example: R123
          description: >-
            Identificador alfanumérico para control interno de la empresa y sin
            relevancia fiscal.
        periodo:
          type: object
          description: Información sobre el periodo de la retención.
          required:
            - mes_ini
            - mes_fin
            - ejerc
          properties:
            mes_ini:
              type: integer
              minimum: 1
              maximum: 12
              example: 9
              description: Mes inicial del periodo de la retención.
            mes_fin:
              type: integer
              minimum: 1
              maximum: 12
              example: 9
              description: Mes final del periodo de la retención.
            ejerc:
              type: integer
              example: 2021
              description: Año o ejercicio fiscal en que se realizó la retención.
        totales:
          type: object
          description: >-
            Información sobre el total de retenciones efectuadas en el periodo
            correspondiente.
          required:
            - monto_tot_operacion
            - monto_tot_exent
            - imp_retenidos
          properties:
            monto_tot_operacion:
              type: number
              minimum: 0
              description: Monto total de la operación, con precisión de hasta 6 decimales.
            monto_tot_grav:
              type: number
              minimum: 0
              description: Monto total gravado.
            monto_tot_exent:
              type: number
              minimum: 0
              description: Monto total exento.
            monto_tot_ret:
              type: number
              minimum: 0
              description: Suma de los montos de impuestos retenidos.
            imp_retenidos:
              type: array
              description: Colección de impuestos retenidos.
              required:
                - monto_ret
              items:
                type: object
                required:
                  - monto_ret
                  - tipo_pago_ret
                properties:
                  base_ret:
                    type: number
                    minimum: 0
                    description: Base del impuesto retenido.
                  impuesto:
                    type: string
                    enum:
                      - IVA
                      - ISR
                    example: IVA
                    description: Clave del tipo de impuesto retenido, del catálogo del SAT.
                  monto_ret:
                    type: number
                    minimum: 0
                    description: Importe del impuesto retenido
                  tipo_pago_ret:
                    type: string
                    enum:
                      - 1
                      - 2
                      - 3
                      - 4
                    description: |
                      - `01`: Pago definitivo IVA
                      - `02`: Pago definitivo IEPS
                      - `03`: Pago definitivo ISR Plataformas
                      - `04`: Pago provisional ISR
        external_id:
          type: string
          description: >-
            Identificador opcional que puedes usar para relacionar esta
            retención con tus registros y poder hacer búsquedas usando este
            identificador. Facturapi no valida que este campo sea único.
        idempotency_key:
          type: string
          description: >
            Identificador único que puedes usar para evitar duplicados al
            reintentar una petición. Puede ser cualquier cadena de texto,
            mientras sea única para cada documento.
        complements:
          type: array
          default: []
          items:
            $ref: '#/components/schemas/CustomComplementData'
          description: >
            Arreglo de complementos a incluir en la factura. Cada elemento del
            arreglo deberá contener

            un `string` con el código XML de tu complemento tal cual como
            quieres que se inserte en el

            XML del CFDI. Sólo se permite un nodo XML raíz por elemento del
            arreglo.
        pdf_custom_section:
          type: string
          format: html
          description: >-
            En caso de que necesites incluir más información en el PDF, este
            campo te permite insertar código HTML con tu propio contenido.
        addenda:
          type: string
          format: xml
          description: Código XML con la Addenda que se necesite agregar a la factura.
        namespaces:
          type: array
          description: >-
            Namespaces a insertar en el nodo raíz de la factura. Requerido en
            `addenda`.
          items:
            allOf:
              - $ref: '#/components/schemas/NamespaceRequiredProperties'
              - $ref: '#/components/schemas/NamespaceProperties'
    OrganizationAddress:
      allOf:
        - $ref: '#/components/schemas/CommonAddressProperties'
        - type: object
          description: Domicilio fiscal de la organización emisora.
          properties:
            state:
              type: string
              description: Nombre del Estado o Entidad Federativa.
              example: Sonora
    OrganizationSearchResult:
      allOf:
        - $ref: '#/components/schemas/SearchResult'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Organization'
    Organization:
      title: Objeto Organization
      type: object
      properties:
        id:
          type: string
          description: ID del objeto
          example: 5a2a307be93a2f00129ea035
        logo_url:
          type: string
          format: uri
          description: URL del logotipo de la organización.
          example: >-
            https://storage.googleapis.com/cdn.facturapi.io/organization/6c100efa5c6f5d7db0379ca643476a4183526007/logo.jpg
        timezone:
          type: string
          description: Zona horaria de la organización, en formato IANA.
          example: America/Mexico_City
        created_at:
          type: string
          format: date-time
          description: Fecha de registro
          example: '2017-05-05T20:55:33.468Z'
        is_production_ready:
          type: boolean
          description: >-
            Indica si la organización tiene información necesaria para facturar
            en ambiente Live.
        pending_steps:
          type: array
          description: >-
            Lista de pasos que se necesitan completar para que esta organización
            pueda emitir facturas válidas en ambiente Live.
          items:
            type: object
            properties:
              type:
                type: string
                enum:
                  - legal
                  - logo
                  - certificate
                  - manifiesto
                description: >-
                  Código que representa el tipo de paso que se requiere
                  completar
              description:
                type: string
                description: >-
                  Texto que describe el paso que se requiere completar y que
                  puedes usar para mostrárselo al usuario.
        legal:
          type: object
          description: Datos fiscales de la empresa.
          properties:
            name:
              type: string
              description: Nombre comercial de la organización.
            legal_name:
              type: string
              description: >
                Nombre Fiscal o Razón Social de la organización, *sin* el
                régimen societario (ej.: S.A. de C.V.).
            tax_system:
              type: string
              example: '601'
              maxLength: 3
              minLength: 3
              description: >-
                Código de Régimen Fiscal, del [catálogo del
                SAT](#régimen-fiscal).
            website:
              type: string
              description: >-
                Sitio web de la organización, que se utilizará al enviar la
                factura por correo electrónico.
            phone:
              type: string
              description: >-
                Teléfono de la organización, que aparecerá en el PDF de la
                factura.
            address:
              allOf:
                - type: object
                  description: Domicilio fiscal de la organización.
                - $ref: '#/components/schemas/OrganizationAddress'
        customization:
          type: object
          description: >
            Configuración de personalización de la organización, que se
            utilizarán para reflejar el branding y

            las preferencias de PDFs de la organización. Estos datos se pueden
            actualizar en cualquier momento.
          properties:
            has_logo:
              type: boolean
              description: Indica si la organización ya tiene un logotipo cargado.
            color:
              type: string
              format: hex
              example: BADA55
              description: >-
                Color distintivo de la marca en representación Hexadecimal RGB
                de 6 caracteres.
            next_folio_number:
              type: integer
              example: 123
              description: >-
                Número de folio que se asignará a la siguiente factura en
                ambiente Live (y que se incrementará automáticamente por cada
                nueva factura).
            next_folio_number_test:
              type: integer
              example: 123
              description: >-
                Número de folio que se asignará a la siguiente factura en
                ambiente Test (y que se incrementará automáticamente por cada
                nueva factura).
            pdf_extra:
              type: object
              description: >-
                Configura qué campos opcionales se queiren mostrar en el PDF. El
                SAT no obliga a mostrar estos campos, pero pueden activarse
                según la preferencia de la organización.
              properties:
                codes:
                  type: boolean
                  default: true
                  description: >
                    Mostrar códigos de catálogos del SAT junto a sus
                    descripciones. Ejemplo: “KGM Kilogramo”.
                address_codes:
                  type: boolean
                  default: true
                  description: >
                    Mostrar los códigos estandarizados de estado y de país en el
                    PDF. Ejemplo: "SON" en lugar de "Sonora" y "MEX" en lugar de
                    "México".
                product_key:
                  type: boolean
                  default: true
                  description: |
                    Mostrar la clave de producto-servicio.
                export_key:
                  type: boolean
                  default: false
                  description: |
                    Mostrar la clave de exportación en el PDF.
                round_unit_price:
                  type: boolean
                  default: false
                  description: >
                    Redondear el precio unitario en el PDF a 2 decimales, pero
                    conservar los 6 decimales en el XML.
                tax_breakdown:
                  type: boolean
                  default: true
                  description: >
                    Mostrar el desglose de impuestos en el PDF. Si se desactiva,
                    sólo se mostratán los impuestos en los totales, pero no en
                    el detalle de cada concepto.
                ieps_breakdown:
                  type: boolean
                  default: true
                  description: >
                    Mostrar el desglose de IEPS en el PDF. Si se desactiva, solo
                    se mostrarán los impuestos relacionados al IVA en el
                    subtotal. 
                combine_ieps_with_subtotal:
                  type: boolean
                  default: false
                  description: |
                    Suma IEPS con subtotal sin desglosarlo en el PDF.
                render_carta_porte:
                  type: boolean
                  default: false
                  description: >
                    Renderizar el complemento de Carta Porte 3.1 en el PDF sólo
                    si el complemento de carta porte está incluido en la
                    factura.
                repeat_signature:
                  type: boolean
                  default: false
                  description: >
                    Repetir la firma electrónica en cada página del PDF. Si se
                    desactiva, la firma electrónica sólo se mostrará una vez.
                render_iedu:
                  type: boolean
                  default: false
                  description: >
                    Renderizar el complemento de Instituciones Educativas
                    Privadas en el PDF.
                render_hyp_complement:
                  type: boolean
                  default: false
                  description: >
                    Renderizar el complemento de hidrocarburos y petrolíferos en
                    el PDF.
                render_comercio_exterior:
                  type: boolean
                  default: false
                  description: |
                    Renderizar el complemento de comercio exterior en el PDF.
                payroll_options:
                  type: object
                  properties:
                    tipo_contrato:
                      type: boolean
                      default: false
                    puesto:
                      type: boolean
                      default: false
                    riesgo_puesto:
                      type: boolean
                      default: false
                    antiguedad:
                      type: boolean
                      default: false
        certificate:
          type: object
          description: >
            Información últil sobre el certificado de sello digital (CSD) de la
            organización, que se utilizará para firmar las facturas.
          properties:
            has_certificate:
              type: boolean
              description: >-
                Indica si la organización ya tiene el Certificado de Sello
                Digital (CSD) cargado.
            updated_at:
              type: string
              format: date-time
              example: '2023-05-05T20:55:33.468Z'
              description: Fecha de la última actualización del certificado.
            expires_at:
              type: string
              format: date-time
              example: '2025-05-05T20:55:33.468Z'
              description: Fecha de expiración del certificado.
            serial_number:
              type: string
              example: '30001000000300000101'
              description: Número de serie del certificado CSD.
        fiel:
          type: object
          description: >-
            Información sobre el certificado FIEL de la organización, que se
            utiliza para el servicio de descarga masiva de CFDI.
          properties:
            has_certificate:
              type: boolean
              description: Indica si la organización ya tiene el Certificado FIEL cargado.
            updated_at:
              type: string
              format: date-time
              example: '2023-05-05T20:55:33.468Z'
              description: Fecha de la última actualización del certificado FIEL.
            expires_at:
              type: string
              format: date-time
              example: '2025-05-05T20:55:33.468Z'
              description: Fecha de expiración del certificado FIEL.
            serial_number:
              type: string
              example: '30001000000300000101'
              description: Número de serie del certificado FIEL.
        receipts:
          type: object
          description: >
            Configuración para recibos y la emisión de facturas globales a
            partir de recibos.
          properties:
            periodicity:
              type: string
              default: month
              enum:
                - day
                - week
                - fortnight
                - month
                - two_months
              description: >
                Periodicidad con la que la empresa decide emitir una factura
                global

                (al público en general) por todos los recibos que no se hayan
                facturado.

                Este valor se utiliza como el default al crear una factura
                global.
            duration_days:
              type: integer
              default: 7
              description: >
                Número máximo de días para facturar a través del portal de
                autofactura

                después de que se emite el recibo y antes del último día del
                periodo.
            next_folio_number:
              type: integer
              example: 123
              description: >
                Número de folio que se asignará al siguiente recibo en ambiente
                Live.

                Se incrementará automáticamente por cada nuevo recibo.
            next_folio_number_test:
              type: integer
              example: 123
              description: >
                Número de folio que se asignará al siguiente recibo en ambiente
                Test.

                Se incrementará automáticamente por cada nuevo recibo.
        self_invoice:
          type: object
          description: >
            Configuraciones para el portal de autofactura, que permite a los
            clientes facturar sus recibos a través de un micrositio.
          properties:
            allowed_cfdi_uses:
              type: array
              description: >
                Lista de usos CFDI permitidos para la autofactura. Si este campo
                está vacío, se permitirán todos los usos CFDI.
              items:
                type: string
                example: G01
                description: |
                  Código de uso CFDI según el [catálogo de Uso CFDI](#uso-cfdi).
            apply_resico_isr:
              type: boolean
              description: >
                Indica si la organización aplica el ISR bajo el régimen RESICO.
                Si es verdadero, el ISR se calculará de acuerdo con el régimen
                RESICO.

                Si es falso, el ISR se calculará de acuerdo con el régimen
                general.
            support_email:
              type: string
              description: >
                Dirección de correo electrónico para aclaraciones. Aparecerá en
                el portal de autofacturación.
            support_email_verified:
              type: boolean
              description: >
                Indica si el correo electrónico de soporte ha sido verificado.
                Si es falso, el correo electrónico utilizado en el portal de
                autofacturación será el correo electrónico principal de la
                cuenta.
    OrganizationDeleteCerts:
      type: object
      properties:
        updated_at:
          type: string
          format: date-time
          description: Fecha de eliminación del certificado CSD.
    OrganizationCreateInput:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          maxLength: 100
          description: Nombre comercial de la organización.
    OrganizationLegalInput:
      type: object
      required:
        - name
        - legal_name
        - tax_system
        - address
      properties:
        name:
          type: string
          maxLength: 100
          description: Nombre comercial de la organización.
        legal_name:
          type: string
          maxLength: 100
          description: >
            Nombre Fiscal o Razón Social de la organización, *sin* el régimen
            societario (ej.: S.A. de C.V.).
        tax_system:
          type: string
          maxLength: 3
          minLength: 3
          example: '601'
          description: Código del Régimen Fiscal, del [catálogo del SAT](#régimen-fiscal).
        website:
          type: string
          description: >-
            Sitio web de la organización, que aparecerá en el PDF y correos de
            facturas y recibos.
        support_email:
          type: string
          description: >-
            Dirección de correo electrónico para aclaraciones. Aparecerá en el
            PDF y correos de facturas y recibos.
        phone:
          type: string
          description: >-
            Teléfono de la organización, que aparecerá en el PDF y correos de
            facturas y recibos.
        address:
          allOf:
            - type: object
              description: Domicilio fiscal de la organización emisora.
              required:
                - zip
            - $ref: '#/components/schemas/OrganizationAddress'
    OrganizationCertsInput:
      type: object
      required:
        - cer
        - key
        - password
      properties:
        cer:
          type: string
          format: binary
          description: >-
            Contenido binario del archivo con extensión `.cer` del certificado
            CSD.
        key:
          type: string
          format: binary
          description: >-
            Contenido binario del archivo con extensión `.key` del certificado
            CSD.
        password:
          type: string
          description: Contraseña de la llave del certificado.
    OrganizationFielInput:
      type: object
      required:
        - cer
        - key
        - password
      properties:
        cer:
          type: string
          format: binary
          description: >-
            Contenido binario del archivo con extensión `.cer` de la e.firma
            (FIEL).
        key:
          type: string
          format: binary
          description: >-
            Contenido binario del archivo con extensión `.key` de la e.firma
            (FIEL).
        password:
          type: string
          description: Contraseña de la llave privada de la e.firma (FIEL).
    OrganizationLogoInput:
      type: object
      required:
        - file
      properties:
        file:
          type: string
          format: binary
          description: |
            Contenido binario del archivo con la imagen que se usará como
            logotipo. Formatos soportados:
            - jpg
            - png
            - svg
    OrganizationCustomizationInput:
      type: object
      properties:
        color:
          type: string
          format: hex
          example: BADA55
          description: >-
            Color distintivo de la marca en representación Hexadecimal RGB de 6
            caracteres.
        next_folio_number:
          type: integer
          example: 123
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Live (y que se incrementará automáticamente por cada nueva factura).
        next_folio_number_test:
          type: integer
          example: 123
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Test (y que se incrementará automáticamente por cada nueva factura).
        pdf_extra:
          type: object
          description: >-
            Configura qué campos opcionales se queiren mostrar en el PDF. El SAT
            no obliga a mostrar estos campos, pero pueden activarse según la
            preferencia de la organización.
          properties:
            codes:
              type: boolean
              default: true
              description: >
                Mostrar códigos de catálogos del SAT junto a sus descripciones.
                Ejemplo: “KGM Kilogramo”.
            product_key:
              type: boolean
              default: true
              description: |
                Mostrar la clave de producto-servicio.
            address_codes:
              type: boolean
              default: true
              description: >
                Mostrar los códigos estandarizados de estado y de país en el
                PDF.
            export_key:
              type: boolean
              default: false
              description: |
                Mostrar la clave de exportación en el PDF.
            round_unit_price:
              type: boolean
              default: false
              description: >
                Redondear el precio unitario en el PDF a 2 decimales, pero
                conservar los 6 decimales en el XML.
            tax_breakdown:
              type: boolean
              default: true
              description: >
                Mostrar el desglose de impuestos en el PDF. Si se desactiva,
                sólo se mostratán los impuestos en los totales, pero no en el
                detalle de cada concepto.
            ieps_breakdown:
              type: boolean
              default: true
              description: >
                Mostrar el desglose de IEPS en el PDF. Si se desactiva, solo se
                mostrarán los impuestos relacionados al IVA en el subtotal.   
            combine_ieps_with_subtotal:
              type: boolean
              default: false
              description: |
                Suma IEPS con subtotal sin desglosarlo en el PDF.
            render_carta_porte:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de Carta Porte 3.1 en el PDF sólo si
                el complemento de carta porte está incluido en la factura.
            render_iedu:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de Instituciones Educativas Privadas
                en el PDF.
            render_hyp_complement:
              type: boolean
              default: false
              description: >
                Renderizar el complemento de hidrocarburos y petrolíferos en el
                PDF.
            render_comercio_exterior:
              type: boolean
              default: false
              description: |
                Renderizar el complemento de comercio exterior en el PDF.
            repeat_signature:
              type: boolean
              default: false
              description: |
                Repetir la firma electrónica en cada página del PDF.
            payroll_options:
              type: object
              properties:
                tipo_contrato:
                  type: boolean
                  default: false
                puesto:
                  type: boolean
                  default: false
                riesgo_puesto:
                  type: boolean
                  default: false
                antiguedad:
                  type: boolean
                  default: false
    OrganizationReceiptsInput:
      type: object
      properties:
        periodicity:
          type: string
          default: month
          enum:
            - day
            - week
            - fortnight
            - month
            - two_months
          description: >
            Periodicidad con la que la empresa decide realizar una factura
            global

            (al público en general) por todos los recibos no facturados. Este

            valor se utiliza como default al crear una factura global.
        duration_days:
          type: integer
          default: 7
          description: |
            Días máximos para facturar por medio del portal de autofactura
            después de emitido el recibo y antes del último día del periodo
            definido por el atributo `periodicity`. El valor `0` desactiva esta
            opción, haciendo que los recibos expiren siempre el último día del
            periodo.
        next_folio_number:
          type: integer
          description: >-
            Número de folio que se asignará al siguiente recibo creado en esta
            organización en ambiente Live.
        next_folio_number_test:
          type: integer
          description: >-
            Número de folio que se asignará al siguiente recibo creado en esta
            organización en ambiente Test.
    OrganizationSelfInvoiceInput:
      type: object
      properties:
        allowed_cfdi_uses:
          type: array
          description: >
            Lista de usos CFDI permitidos para la autofactura. Si este campo
            está vacío, se permitirán todos los usos CFDI.
          items:
            type: string
            example: G01
            description: |
              Código de uso CFDI según el [catálogo de Uso CFDI](#uso-cfdi).
        apply_resico_isr:
          type: boolean
          description: >
            Indica si la organización aplica el ISR bajo el régimen RESICO. Si
            es verdadero, el ISR se calculará de acuerdo con el régimen RESICO.

            Si es falso, el ISR se calculará de acuerdo con el régimen general.
        support_email:
          type: string
          description: >
            Dirección de correo electrónico para aclaraciones. Aparecerá en el
            portal de autofacturación.

            Al modificarlo se enviará un correo de verificación a la nueva
            dirección.
    DomainField:
      type: string
      maxLength: 50
      minLength: 4
      pattern: ^[a-z][a-z0-9-_]{2,48}[a-z0-9]$
      description: >
        Nombre del dominio. Se permiten caracteres alfanuméricos, sólo
        minúsculas,

        guión (-) y guión bajo (_). Debe empezar con una letra y

        terminar en letra o número.
    OrganizationDomainInput:
      type: object
      required:
        - domain
      properties:
        domain:
          $ref: '#/components/schemas/DomainField'
    OrganizationSeriesCreateInput:
      type: object
      required:
        - series
        - next_folio
        - next_folio_test
      properties:
        series:
          type: string
          maxLength: 55
          description: Nombre de la serie.
        next_folio:
          type: integer
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Live (y que se incrementará automáticamente por cada nueva factura).
        next_folio_test:
          type: integer
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Test (y que se incrementará automáticamente por cada nueva factura).
    OrganizationSeriesUpdateInput:
      type: object
      properties:
        next_folio:
          type: integer
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Live (y que se incrementará automáticamente por cada nueva factura).
        next_folio_test:
          type: integer
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Test (y que se incrementará automáticamente por cada nueva factura).
    OrganizationSeriesDefaultInput:
      type: object
      required:
        - type
        - series
      properties:
        type:
          type: string
          enum:
            - I
            - E
            - P
            - 'N'
            - T
          description: >
            Tipo de comprobante. Valores posibles:

            `I` (Ingreso), `E` (Egreso), `P` (Pago), `N` (Nómina), `T`
            (Traslado).
        series:
          type: string
          minLength: 1
          maxLength: 25
          description: Nombre de la serie.
    OrganizationSeriesGroup:
      title: Objeto Series
      type: object
      properties:
        series:
          type: string
          description: Nombre de la serie.
          example: New
        next_folio:
          type: integer
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Live (y que se incrementará automáticamente por cada nueva factura).
          example: 123
        next_folio_test:
          type: integer
          description: >-
            Número de folio que se asignará a la siguiente factura en ambiente
            Test (y que se incrementará automáticamente por cada nueva factura).
          example: 123
    OkResponse:
      type: object
      required:
        - ok
      properties:
        ok:
          type: boolean
          example: true
    OrganizationInvite:
      type: object
      properties:
        id:
          type: string
          description: Identificador único de la invitación.
        created_at:
          type: string
          format: date-time
          description: Fecha y hora en que se creó la invitación.
        email:
          type: string
          format: email
          description: Correo electrónico al que se envió la invitación.
        organization_name:
          type: string
          description: Nombre de la organización que envió la invitación.
        role:
          type: string
          nullable: true
          description: ID del rol asignado en la invitación, si existe.
        role_name:
          type: string
          nullable: true
          description: Nombre del rol asignado en la invitación, si existe.
        roles:
          type: array
          description: >-
            Lista de roles visibles que describe el acceso otorgado por la
            invitación.
          items:
            type: string
        expires_at:
          type: string
          format: date-time
          nullable: true
          description: Fecha y hora en que expira la invitación.
    OrganizationInviteList:
      type: array
      description: Lista de invitaciones de organización.
      items:
        $ref: '#/components/schemas/OrganizationInvite'
    OrganizationPermissionRole:
      type: object
      properties:
        id:
          type: string
          description: Identificador único del rol.
        name:
          type: string
          description: Nombre del rol.
        template_code:
          type: string
          nullable: true
          description: >-
            Código de plantilla base del rol, si proviene de una plantilla del
            sistema.
        organization:
          type: string
          nullable: true
          description: ID de la organización a la que pertenece el rol.
        used_by:
          type: integer
          description: Número de usuarios que actualmente usan este rol.
        overrides_add:
          type: array
          description: >-
            Operaciones agregadas al rol además de las definidas por su
            plantilla.
          items:
            type: string
        overrides_remove:
          type: array
          description: Operaciones removidas del rol respecto a su plantilla.
          items:
            type: string
        operations:
          type: array
          description: Lista final de operaciones permitidas por este rol.
          items:
            type: string
        created_at:
          type: string
          format: date-time
          nullable: true
          description: Fecha y hora de creación del rol.
        updated_at:
          type: string
          format: date-time
          nullable: true
          description: Fecha y hora de la última actualización del rol.
    OrganizationPermissionRoleList:
      type: array
      description: Lista de roles configurables de la organización.
      items:
        $ref: '#/components/schemas/OrganizationPermissionRole'
    OrganizationPermissionRoleTemplate:
      type: object
      properties:
        code:
          type: string
          enum:
            - org-admin
            - org-readonly
            - org-billing
            - org-developer
            - org-team-manager
          description: Código interno de la plantilla de rol.
        label:
          type: string
          description: Nombre visible de la plantilla de rol.
        operations:
          type: array
          description: Operaciones incluidas por defecto en la plantilla.
          items:
            type: string
    OrganizationPermissionRoleTemplateList:
      type: array
      description: Lista de plantillas de roles disponibles para la organización.
      items:
        $ref: '#/components/schemas/OrganizationPermissionRoleTemplate'
    OrganizationPermissionOperationList:
      type: array
      description: Lista de operaciones disponibles para permisos a nivel organización.
      items:
        type: string
    OrganizationUserAccess:
      type: object
      properties:
        id:
          type: string
          description: >-
            Identificador del acceso del usuario dentro de la organización. Para
            el propietario, este valor es `owner` porque su acceso es implícito.
        full_name:
          type: string
          description: Nombre completo del usuario.
        email:
          type: string
          format: email
          description: Correo electrónico del usuario.
        role:
          type: string
          nullable: true
          description: >-
            ID del rol asignado al usuario, si existe. Para el propietario, este
            valor es `null` porque su acceso es implícito.
        role_name:
          type: string
          nullable: true
          description: >-
            Nombre del rol asignado o del acceso implícito del usuario. Para el
            propietario, este valor es `owner`.
        organization:
          type: string
          nullable: true
          description: ID de la organización a la que pertenece el acceso.
        operations:
          type: array
          description: Lista final de operaciones permitidas para el usuario.
          items:
            type: string
        created_at:
          type: string
          format: date-time
          description: >-
            Fecha y hora en que se creó el acceso. Para el propietario,
            corresponde a la creación de la organización.
        updated_at:
          type: string
          format: date-time
          description: >-
            Fecha y hora de la última actualización del acceso. Para el
            propietario, corresponde a la creación de la organización porque su
            acceso es implícito.
    OrganizationUserAccessList:
      type: array
      description: >-
        Lista de accesos de usuarios a la organización, incluyendo accesos
        implícitos como el del propietario.
      items:
        $ref: '#/components/schemas/OrganizationUserAccess'
    OrganizationInviteCreateInput:
      type: object
      required:
        - email
      properties:
        email:
          type: string
          format: email
          description: Correo electrónico del usuario que será invitado.
        role:
          type: string
          description: ID de rol personalizado de la organización.
    OrganizationInviteRespondInput:
      type: object
      required:
        - accept
      properties:
        accept:
          type: boolean
          description: >-
            Indica si la invitación debe aceptarse (`true`) o rechazarse
            (`false`).
    OrganizationPermissionRoleCreateInput:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          description: Nombre del rol.
        template_code:
          type: string
          nullable: true
          enum:
            - org-admin
            - org-readonly
            - org-billing
            - org-developer
            - org-team-manager
          description: Código de plantilla base para inicializar el rol, si aplica.
        add:
          type: array
          description: Operaciones adicionales que se agregarán al rol.
          items:
            type: string
        remove:
          type: array
          description: Operaciones que se removerán del rol.
          items:
            type: string
    OrganizationPermissionRoleUpdateInput:
      type: object
      properties:
        name:
          type: string
          description: Nuevo nombre del rol.
        template_code:
          type: string
          nullable: true
          enum:
            - org-admin
            - org-readonly
            - org-billing
            - org-developer
            - org-team-manager
          description: Nuevo código de plantilla base del rol, si aplica.
        add:
          type: array
          description: Lista completa de operaciones extra que debe conservar el rol.
          items:
            type: string
        remove:
          type: array
          description: Lista completa de operaciones removidas que debe conservar el rol.
          items:
            type: string
    OrganizationUserAccessRoleUpdateInput:
      type: object
      required:
        - role
      properties:
        role:
          type: string
          description: ID del rol que se asignará al usuario.
  securitySchemes:
    SecretLiveKey:
      type: http
      scheme: bearer
      bearerFormat: sk_live_XXXXXXXXXXXX
      description: >-
        Única por organización. Permite crear, obtener y administrar recursos en
        ambiente Live para una organización en específico.
    SecretTestKey:
      type: http
      scheme: bearer
      bearerFormat: sk_test_XXXXXXXXXXXX
      description: >-
        Única por organización. Permite crear, obtener y administrar recursos en
        ambiente Test para una organización en específico.
    SecretUserKey:
      type: http
      scheme: bearer
      bearerFormat: sk_user_XXXXXXXXXXXX
      description: >-
        Única por cuenta. Permite crear y configurar organizaciones
        pertenecientes a la cuenta del usuario.
