From fd269311e0e4dc4962473cb79ea3d562f0a40e5f Mon Sep 17 00:00:00 2001 From: javorosas Date: Fri, 2 Oct 2026 02:50:40 +0200 Subject: [PATCH 1/2] docs: add Node SDK v6 usage and upgrade guidance --- website/docs/getting-started/dates.mdx | 9 ++ website/docs/getting-started/install.mdx | 4 +- website/docs/getting-started/node-sdk.mdx | 82 +++++++++++++++++++ website/docs/guides/customers.mdx | 6 +- .../current/getting-started/dates.mdx | 9 ++ .../current/getting-started/install.mdx | 4 +- .../current/getting-started/node-sdk.mdx | 82 +++++++++++++++++++ .../current/guides/customers.mdx | 6 +- 8 files changed, 196 insertions(+), 6 deletions(-) create mode 100644 website/docs/getting-started/node-sdk.mdx create mode 100644 website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx diff --git a/website/docs/getting-started/dates.mdx b/website/docs/getting-started/dates.mdx index 4b1e315fa..67a4181c7 100644 --- a/website/docs/getting-started/dates.mdx +++ b/website/docs/getting-started/dates.mdx @@ -22,3 +22,12 @@ La siguiente tabla muestra a manera resumida cómo Facturapi interpreta las fech En los objetos de respuesta, nuestra API siempre devolverá la fecha en formato ISO8601 con zona horaria UTC. En comprobantes, el SAT pide que las fechas se muestren en la zona horaria del emisor, por lo que haremos la conversión correspondiente y mostraremos la porción de la fecha que se requiera, pudiendo ser ésta sólo la fecha o la fecha y la hora. + + +## Fechas en el SDK de Node.js + +Desde el SDK 6, los timestamps de respuesta, como `created_at` y `expires_at`, se convierten en objetos `Date`. Esto también aplica a los eventos devueltos por `webhooks.validateSignature()`. Los valores `null` se conservan. + +Las fechas de calendario (`YYYY-MM-DD`), la fecha del timbre SAT (`stamp.date`) y los valores de `metadata` conservan su texto; no todas las propiedades llamadas `date` representan un timestamp. Las fechas de entrada admiten strings y, donde los tipos lo indican, objetos `Date`. Los filtros de búsqueda conservan sus objetos de rango. + +Consulta la [guía del SDK](./node-sdk.mdx) para migrar código que trataba los timestamps como strings. diff --git a/website/docs/getting-started/install.mdx b/website/docs/getting-started/install.mdx index 007acfe65..f32ee45fa 100644 --- a/website/docs/getting-started/install.mdx +++ b/website/docs/getting-started/install.mdx @@ -23,8 +23,10 @@ Empieza por incluir el cliente de Facturapi en las dependencias de tu proyecto. Instala el paquete de [NPM](https://www.npmjs.com/package/facturapi). +El SDK 6 requiere Node.js 18 o superior e incluye tipos para TypeScript. Consulta la [guía del SDK](./node-sdk.mdx) para conocer el autocompletado y actualizar desde versiones anteriores. + ```bash -$> npm install --save facturapi +$> npm install facturapi ``` diff --git a/website/docs/getting-started/node-sdk.mdx b/website/docs/getting-started/node-sdk.mdx new file mode 100644 index 000000000..3ddbea82c --- /dev/null +++ b/website/docs/getting-started/node-sdk.mdx @@ -0,0 +1,82 @@ +--- +sidebar_position: 2.5 +--- + +# Node.js y TypeScript + +El SDK 6 incluye tipos y documentación en el editor para las peticiones y respuestas. Requiere Node.js 18 o superior. Las validaciones de los datos fiscales siguen siendo responsabilidad de la API. + +## Imports y autocompletado + +Con ESM o TypeScript: + +```ts +import Facturapi, { PaymentForm, type InvoiceCreateInput } from 'facturapi'; +``` + +Con CommonJS: + +```js +const Facturapi = require('facturapi'); +const { PaymentForm } = Facturapi; +``` + +Importa siempre desde `facturapi`, incluidos los tipos y enums. No necesitas un paquete adicional de tipos. Pasa el cursor sobre un campo o método para consultar su descripción, o usa el autocompletado para explorar los argumentos y resultados. + +Si preparas una petición fuera de la llamada al SDK, puedes usar `satisfies` con TypeScript 4.9 o superior: + +```ts +const input = { + customer: 'cus_ejemplo', + payment_form: PaymentForm.EFECTIVO, + items: [{ + quantity: 1, + product: { description: 'Servicio', product_key: '84111506', price: 100 }, + }], +} satisfies InvoiceCreateInput; + +const invoice = await facturapi.invoices.create(input); +``` + +Este ejemplo presupone un cliente registrado y una instancia `facturapi`, como en la [guía de inicio](../quickstart.mdx). + +Los tipos distinguen los tipos de CFDI, borradores y complementos estructurados. En los casos representables en TypeScript, relacionan campos para ayudarte a detectar entradas incompletas o incompatibles antes de enviar la petición. No sustituyen la validación de la API. + +## Clientes según el caso + +En lugar de elegir una entrada general, puedes usar: + +- `customers.createNational()`: requiere razón social, RFC, régimen fiscal y código postal; el país puede omitirse para México. +- `customers.createForeign()`: requiere razón social y domicilio con país explícito. El país es un string libre en TypeScript; la API valida que corresponda al caso extranjero. +- `customers.createGeneric()`: requiere razón social y uno de los RFC genéricos `XAXX010101000` o `XEXX010101000`. + +Son métodos adicionales de la misma operación; `customers.create()` sigue disponible. Para datos incompletos, usa `create(data, { createEditLink: true })`. El flag literal `true` selecciona la entrada incompleta; un boolean dinámico conserva el contrato normal. Los métodos específicos conservan sus campos requeridos. + +Consulta los [ejemplos de clientes](../guides/customers.mdx). + +## Respuestas y descargas + +Los timestamps llegan como objetos `Date`; las fechas de calendario y del timbre SAT conservan su texto. Consulta [formato de fechas](./dates.mdx). + +Los métodos `downloadPdf()`, `downloadXml()` y `downloadZip()` devuelven streams en Node.js y `Blob` en navegadores. Los métodos terminados en `Url()` devuelven un objeto con `url`, `expires_at`, `content_type` y `filename`, no un string: + +```js +const download = await facturapi.invoices.downloadPdfUrl(invoice.id); +console.log(download.url, download.expires_at); +``` + +`webhooks.validateSignature()` devuelve un evento interpretado con sus fechas convertidas. Para verificar la firma, conserva el texto o bytes originales del body recibido; volver a serializarlo puede cambiar el contenido firmado. + +## Actualizar desde v3, v4 o v5 + +Puedes actualizar directamente a v6. Si usas métodos vigentes, imports desde `facturapi`, Node.js 18+ y no dependes de timestamps como strings ni de tipos anteriores, puedes conservar tus llamadas. Los nuevos métodos de clientes son opcionales; no requieren migrar llamadas a `create()`. + +Revisa estos casos si aplican a tu integración: + +- **Fechas:** cambia operaciones de string por métodos de `Date` o `toISOString()`, comprobando `null` cuando corresponda. `JSON.stringify()` sigue produciendo strings ISO, aunque puede normalizar su formato. +- **Imports internos:** sustituye `facturapi/dist/...` por imports desde `facturapi`. El alias `require('facturapi').default` sigue funcionando. +- **Entradas TypeScript:** compila tu proyecto para detectar campos desconocidos y relaciones ahora expresadas en tipos. Cancelaciones con motivos `01` o `04` requieren `substitution`; `receipts.toInvoice()` devuelve un resumen con `dry_run: true` y una factura cuando es falso u omitido. +- **Desde v4:** los totales y números de página de `SearchResult` pueden faltar en paginación por cursor. `CursorSearchResult` se reemplaza por `SearchResult`. +- **Desde v3:** revisa los métodos retirados en v4 y tu runtime de Node.js. + +La [guía de migración del README](https://github.com/FacturAPI/facturapi-node#actualizar-desde-v3-v4-o-v5) detalla los reemplazos y los casos que no requieren cambios. Consulta el [changelog](https://github.com/FacturAPI/facturapi-node/blob/main/CHANGELOG.md) para conocer las novedades. diff --git a/website/docs/guides/customers.mdx b/website/docs/guides/customers.mdx index d76a8aa78..91f4635b0 100644 --- a/website/docs/guides/customers.mdx +++ b/website/docs/guides/customers.mdx @@ -30,6 +30,8 @@ caso de uso. ## Cómo registrar un cliente +Los ejemplos de Node.js usan el SDK 6. Los métodos `createNational()`, `createForeign()` y `createGeneric()` seleccionan los tipos de entrada de cada caso; `create()` sigue disponible y usa la misma operación de la API. Para datos incompletos con un enlace de edición, conserva `create(data, { createEditLink: true })`. Consulta la [guía de Node.js y TypeScript](../getting-started/node-sdk.mdx). + En Facturapi, la forma de registrar los datos fiscales de clientes nacionales y extranjeros no es muy diferente entre sí, pero vale la pena analizarlos por separado, ya que sí es diferente de como lo indica el SAT en su estándar técnico. @@ -48,7 +50,7 @@ Para conocer qué otros datos puedes incluir, consulta la import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.create({ +const customer = await facturapi.customers.createNational({ legal_name: 'Dunder Mifflin', // Nombre o razón social tax_id: 'ABC101010111', // RFC tax_system: '601', // Regimen fiscal @@ -185,7 +187,7 @@ Para conocer qué otros datos puedes incluir, consulta la import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.create({ +const customer = await facturapi.customers.createForeign({ legal_name: 'Vättenfall, A.B.', // Nombre o razón social tax_id: '198912171234', // Núm. de reg. id. trib. (opcional) email: 'email@example.com', // Correo para envío (opcional). diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx index 16d6c7fe9..32f470b9c 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx @@ -26,3 +26,12 @@ In invoices, the SAT (Mexican tax authority) requires that dates be displayed in the time zone of the issuer, so we will make the corresponding conversion and display the required portion of the date, which can be either just the date or the date and time. + + +## Dates in the Node.js SDK + +Starting with SDK 6, response timestamps such as `created_at` and `expires_at` become `Date` objects. This also applies to events returned by `webhooks.validateSignature()`. Null values are preserved. + +Calendar dates (`YYYY-MM-DD`), SAT stamp timestamps (`stamp.date`), and `metadata` values keep their text; not every property called `date` is a timestamp. Input dates accept strings and, where the types allow them, `Date` objects. Search filters keep their range objects. + +See the [SDK guide](./node-sdk.mdx) to upgrade code that treated timestamps as strings. diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx index 1a9207f99..c2941ae22 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx @@ -24,9 +24,11 @@ Start by including the Facturapi client in your project dependencies. Install the package from [NPM](https://www.npmjs.com/package/facturapi). ```bash -$> npm install --save facturapi +$> npm install facturapi ``` +SDK 6 requires Node.js 18 or later and includes TypeScript types. See the [SDK guide](./node-sdk.mdx) for editor support and upgrading from earlier versions. + diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx new file mode 100644 index 000000000..50c181773 --- /dev/null +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx @@ -0,0 +1,82 @@ +--- +sidebar_position: 2.5 +--- + +# Node.js and TypeScript + +SDK 6 includes editor documentation and types for requests and responses. It requires Node.js 18 or later. The API remains responsible for tax information validation. + +## Imports and autocomplete + +With ESM or TypeScript: + +```ts +import Facturapi, { PaymentForm, type InvoiceCreateInput } from 'facturapi'; +``` + +With CommonJS: + +```js +const Facturapi = require('facturapi'); +const { PaymentForm } = Facturapi; +``` + +Always import from `facturapi`, including types and enums. You do not need a separate types package. Hover over a field or method to read its description, or use autocomplete to explore arguments and results. + +When preparing a request outside the SDK call, you can use `satisfies` with TypeScript 4.9 or later: + +```ts +const input = { + customer: 'cus_ejemplo', + payment_form: PaymentForm.EFECTIVO, + items: [{ + quantity: 1, + product: { description: 'Service', product_key: '84111506', price: 100 }, + }], +} satisfies InvoiceCreateInput; + +const invoice = await facturapi.invoices.create(input); +``` + +This example assumes a registered customer and a `facturapi` instance, as in the [quickstart](../quickstart.mdx). + +The types distinguish CFDI types, drafts, and structured complements. Where TypeScript can express the relationships, they connect fields to help you catch incomplete or incompatible inputs before sending a request. They do not replace API validation. + +## Customers by use case + +Instead of selecting a general input, you can use: + +- `customers.createNational()`: requires legal name, RFC, tax regime, and postal code; country can be omitted for Mexico. +- `customers.createForeign()`: requires legal name and an address with an explicit country. Country is a free string in TypeScript; the API validates that it matches the foreign customer case. +- `customers.createGeneric()`: requires legal name and either generic RFC `XAXX010101000` or `XEXX010101000`. + +These additional methods use the same operation; `customers.create()` remains available. For incomplete data, use `create(data, { createEditLink: true })`. A literal `true` selects the incomplete input; a dynamic boolean retains the normal contract. The specific methods retain their required fields. + +See the [customer examples](../guides/customers.mdx). + +## Responses and downloads + +Timestamps arrive as `Date` objects; calendar dates and SAT stamp timestamps keep their text. See [date formats](./dates.mdx). + +`downloadPdf()`, `downloadXml()`, and `downloadZip()` return streams in Node.js and `Blob` objects in browsers. Methods ending in `Url()` return an object with `url`, `expires_at`, `content_type`, and `filename`, rather than a string: + +```js +const download = await facturapi.invoices.downloadPdfUrl(invoice.id); +console.log(download.url, download.expires_at); +``` + +`webhooks.validateSignature()` returns a parsed event with converted dates. For signature verification, preserve the original text or bytes of the received body; serializing it again can change the signed content. + +## Upgrading from v3, v4, or v5 + +You can upgrade directly to v6. If you use current methods, import from `facturapi`, run Node.js 18+, and do not depend on timestamps being strings or on previous types, you can keep your calls. The new customer methods are optional; existing `create()` calls do not need to migrate. + +Review these cases if they apply to your integration: + +- **Dates:** replace string operations with `Date` methods or `toISOString()`, checking for `null` when applicable. `JSON.stringify()` still produces ISO strings, but may normalize their format. +- **Internal imports:** replace `facturapi/dist/...` with imports from `facturapi`. The `require('facturapi').default` alias still works. +- **TypeScript inputs:** compile your project to detect unknown fields and relationships now expressed in types. Cancellation motives `01` and `04` require `substitution`; `receipts.toInvoice()` returns a summary with `dry_run: true` and an invoice when it is false or omitted. +- **From v4:** `SearchResult` totals and page numbers may be absent with cursor pagination. `CursorSearchResult` is replaced by `SearchResult`. +- **From v3:** review methods removed in v4 and your Node.js runtime. + +The [README migration guide](https://github.com/FacturAPI/facturapi-node#actualizar-desde-v3-v4-o-v5) details replacements and cases that need no changes. See the [changelog](https://github.com/FacturAPI/facturapi-node/blob/main/CHANGELOG.md) for release improvements. diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx index 8c7b142a8..e6afdf6f9 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx @@ -27,6 +27,8 @@ use case. ## How to register a customer +The Node.js examples use SDK 6. `createNational()`, `createForeign()`, and `createGeneric()` select the input types for each case; `create()` remains available and uses the same API operation. For incomplete data with an edit link, keep using `create(data, { createEditLink: true })`. See the [Node.js and TypeScript guide](../getting-started/node-sdk.mdx). + In Facturapi, the process of registering the tax information of national and foreign customers is not very different from each other, but it is worth analyzing them separately, as it is different from what the SAT indicates in its technical standard. @@ -46,7 +48,7 @@ To learn about other data you can include, refer to the import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.create({ +const customer = await facturapi.customers.createNational({ legal_name: 'Dunder Mifflin', // Person's name or business legal name tax_id: 'ABC101010111', // RFC tax_system: '601', // Fiscal regime @@ -183,7 +185,7 @@ To learn about other data you can include, refer to the import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.create({ +const customer = await facturapi.customers.createForeign({ legal_name: 'Vättenfall, A.B.', // Person's name or business legal name tax_id: '198912171234', // Tax identification number (optional) email: 'email@example.com', // Email for sending (optional). From 0633ae6909fc42e533d970d94f0570fc6b07949a Mon Sep 17 00:00:00 2001 From: javorosas Date: Fri, 2 Oct 2026 03:56:37 +0200 Subject: [PATCH 2/2] docs: focus SDK guidance on installation imports --- AGENTS.md | 4 + website/docs/getting-started/dates.mdx | 9 -- website/docs/getting-started/install.mdx | 14 ++-- website/docs/getting-started/node-sdk.mdx | 82 ------------------- website/docs/guides/customers.mdx | 6 +- .../current/getting-started/dates.mdx | 9 -- .../current/getting-started/install.mdx | 14 ++-- .../current/getting-started/node-sdk.mdx | 82 ------------------- .../current/guides/customers.mdx | 6 +- 9 files changed, 24 insertions(+), 202 deletions(-) delete mode 100644 website/docs/getting-started/node-sdk.mdx delete mode 100644 website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx diff --git a/AGENTS.md b/AGENTS.md index 94611048c..0488495c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,3 +26,7 @@ or a review comment alone as proof of API behavior. - Keep the Spanish and English OpenAPI contracts structurally aligned. - Run the relevant repository checks for specification changes. + +## SDK guide style + +- Describe the current SDK as the available version. Keep release announcements out of general guides; version references may explain verified compatibility or when a capability became available. Document import options in the existing installation guide rather than adding a separate SDK article. diff --git a/website/docs/getting-started/dates.mdx b/website/docs/getting-started/dates.mdx index 67a4181c7..4b1e315fa 100644 --- a/website/docs/getting-started/dates.mdx +++ b/website/docs/getting-started/dates.mdx @@ -22,12 +22,3 @@ La siguiente tabla muestra a manera resumida cómo Facturapi interpreta las fech En los objetos de respuesta, nuestra API siempre devolverá la fecha en formato ISO8601 con zona horaria UTC. En comprobantes, el SAT pide que las fechas se muestren en la zona horaria del emisor, por lo que haremos la conversión correspondiente y mostraremos la porción de la fecha que se requiera, pudiendo ser ésta sólo la fecha o la fecha y la hora. - - -## Fechas en el SDK de Node.js - -Desde el SDK 6, los timestamps de respuesta, como `created_at` y `expires_at`, se convierten en objetos `Date`. Esto también aplica a los eventos devueltos por `webhooks.validateSignature()`. Los valores `null` se conservan. - -Las fechas de calendario (`YYYY-MM-DD`), la fecha del timbre SAT (`stamp.date`) y los valores de `metadata` conservan su texto; no todas las propiedades llamadas `date` representan un timestamp. Las fechas de entrada admiten strings y, donde los tipos lo indican, objetos `Date`. Los filtros de búsqueda conservan sus objetos de rango. - -Consulta la [guía del SDK](./node-sdk.mdx) para migrar código que trataba los timestamps como strings. diff --git a/website/docs/getting-started/install.mdx b/website/docs/getting-started/install.mdx index f32ee45fa..b60999d5b 100644 --- a/website/docs/getting-started/install.mdx +++ b/website/docs/getting-started/install.mdx @@ -23,8 +23,6 @@ Empieza por incluir el cliente de Facturapi en las dependencias de tu proyecto. Instala el paquete de [NPM](https://www.npmjs.com/package/facturapi). -El SDK 6 requiere Node.js 18 o superior e incluye tipos para TypeScript. Consulta la [guía del SDK](./node-sdk.mdx) para conocer el autocompletado y actualizar desde versiones anteriores. - ```bash $> npm install facturapi ``` @@ -79,16 +77,20 @@ Importa la librería antes de usarla. -```javascript -const Facturapi = require('facturapi'); +Elige el import que corresponda a tu proyecto. Con ESM o TypeScript: + +```typescript +import Facturapi from 'facturapi'; ``` -ESM / TypeScript +Con CommonJS: ```javascript -import Facturapi from 'facturapi'; +const Facturapi = require('facturapi'); ``` +El paquete incluye tipos para TypeScript y requiere Node.js 18 o superior. Importa el constructor, los tipos y los enums desde `facturapi`. + diff --git a/website/docs/getting-started/node-sdk.mdx b/website/docs/getting-started/node-sdk.mdx deleted file mode 100644 index 3ddbea82c..000000000 --- a/website/docs/getting-started/node-sdk.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -sidebar_position: 2.5 ---- - -# Node.js y TypeScript - -El SDK 6 incluye tipos y documentación en el editor para las peticiones y respuestas. Requiere Node.js 18 o superior. Las validaciones de los datos fiscales siguen siendo responsabilidad de la API. - -## Imports y autocompletado - -Con ESM o TypeScript: - -```ts -import Facturapi, { PaymentForm, type InvoiceCreateInput } from 'facturapi'; -``` - -Con CommonJS: - -```js -const Facturapi = require('facturapi'); -const { PaymentForm } = Facturapi; -``` - -Importa siempre desde `facturapi`, incluidos los tipos y enums. No necesitas un paquete adicional de tipos. Pasa el cursor sobre un campo o método para consultar su descripción, o usa el autocompletado para explorar los argumentos y resultados. - -Si preparas una petición fuera de la llamada al SDK, puedes usar `satisfies` con TypeScript 4.9 o superior: - -```ts -const input = { - customer: 'cus_ejemplo', - payment_form: PaymentForm.EFECTIVO, - items: [{ - quantity: 1, - product: { description: 'Servicio', product_key: '84111506', price: 100 }, - }], -} satisfies InvoiceCreateInput; - -const invoice = await facturapi.invoices.create(input); -``` - -Este ejemplo presupone un cliente registrado y una instancia `facturapi`, como en la [guía de inicio](../quickstart.mdx). - -Los tipos distinguen los tipos de CFDI, borradores y complementos estructurados. En los casos representables en TypeScript, relacionan campos para ayudarte a detectar entradas incompletas o incompatibles antes de enviar la petición. No sustituyen la validación de la API. - -## Clientes según el caso - -En lugar de elegir una entrada general, puedes usar: - -- `customers.createNational()`: requiere razón social, RFC, régimen fiscal y código postal; el país puede omitirse para México. -- `customers.createForeign()`: requiere razón social y domicilio con país explícito. El país es un string libre en TypeScript; la API valida que corresponda al caso extranjero. -- `customers.createGeneric()`: requiere razón social y uno de los RFC genéricos `XAXX010101000` o `XEXX010101000`. - -Son métodos adicionales de la misma operación; `customers.create()` sigue disponible. Para datos incompletos, usa `create(data, { createEditLink: true })`. El flag literal `true` selecciona la entrada incompleta; un boolean dinámico conserva el contrato normal. Los métodos específicos conservan sus campos requeridos. - -Consulta los [ejemplos de clientes](../guides/customers.mdx). - -## Respuestas y descargas - -Los timestamps llegan como objetos `Date`; las fechas de calendario y del timbre SAT conservan su texto. Consulta [formato de fechas](./dates.mdx). - -Los métodos `downloadPdf()`, `downloadXml()` y `downloadZip()` devuelven streams en Node.js y `Blob` en navegadores. Los métodos terminados en `Url()` devuelven un objeto con `url`, `expires_at`, `content_type` y `filename`, no un string: - -```js -const download = await facturapi.invoices.downloadPdfUrl(invoice.id); -console.log(download.url, download.expires_at); -``` - -`webhooks.validateSignature()` devuelve un evento interpretado con sus fechas convertidas. Para verificar la firma, conserva el texto o bytes originales del body recibido; volver a serializarlo puede cambiar el contenido firmado. - -## Actualizar desde v3, v4 o v5 - -Puedes actualizar directamente a v6. Si usas métodos vigentes, imports desde `facturapi`, Node.js 18+ y no dependes de timestamps como strings ni de tipos anteriores, puedes conservar tus llamadas. Los nuevos métodos de clientes son opcionales; no requieren migrar llamadas a `create()`. - -Revisa estos casos si aplican a tu integración: - -- **Fechas:** cambia operaciones de string por métodos de `Date` o `toISOString()`, comprobando `null` cuando corresponda. `JSON.stringify()` sigue produciendo strings ISO, aunque puede normalizar su formato. -- **Imports internos:** sustituye `facturapi/dist/...` por imports desde `facturapi`. El alias `require('facturapi').default` sigue funcionando. -- **Entradas TypeScript:** compila tu proyecto para detectar campos desconocidos y relaciones ahora expresadas en tipos. Cancelaciones con motivos `01` o `04` requieren `substitution`; `receipts.toInvoice()` devuelve un resumen con `dry_run: true` y una factura cuando es falso u omitido. -- **Desde v4:** los totales y números de página de `SearchResult` pueden faltar en paginación por cursor. `CursorSearchResult` se reemplaza por `SearchResult`. -- **Desde v3:** revisa los métodos retirados en v4 y tu runtime de Node.js. - -La [guía de migración del README](https://github.com/FacturAPI/facturapi-node#actualizar-desde-v3-v4-o-v5) detalla los reemplazos y los casos que no requieren cambios. Consulta el [changelog](https://github.com/FacturAPI/facturapi-node/blob/main/CHANGELOG.md) para conocer las novedades. diff --git a/website/docs/guides/customers.mdx b/website/docs/guides/customers.mdx index 91f4635b0..d76a8aa78 100644 --- a/website/docs/guides/customers.mdx +++ b/website/docs/guides/customers.mdx @@ -30,8 +30,6 @@ caso de uso. ## Cómo registrar un cliente -Los ejemplos de Node.js usan el SDK 6. Los métodos `createNational()`, `createForeign()` y `createGeneric()` seleccionan los tipos de entrada de cada caso; `create()` sigue disponible y usa la misma operación de la API. Para datos incompletos con un enlace de edición, conserva `create(data, { createEditLink: true })`. Consulta la [guía de Node.js y TypeScript](../getting-started/node-sdk.mdx). - En Facturapi, la forma de registrar los datos fiscales de clientes nacionales y extranjeros no es muy diferente entre sí, pero vale la pena analizarlos por separado, ya que sí es diferente de como lo indica el SAT en su estándar técnico. @@ -50,7 +48,7 @@ Para conocer qué otros datos puedes incluir, consulta la import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.createNational({ +const customer = await facturapi.customers.create({ legal_name: 'Dunder Mifflin', // Nombre o razón social tax_id: 'ABC101010111', // RFC tax_system: '601', // Regimen fiscal @@ -187,7 +185,7 @@ Para conocer qué otros datos puedes incluir, consulta la import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.createForeign({ +const customer = await facturapi.customers.create({ legal_name: 'Vättenfall, A.B.', // Nombre o razón social tax_id: '198912171234', // Núm. de reg. id. trib. (opcional) email: 'email@example.com', // Correo para envío (opcional). diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx index 32f470b9c..16d6c7fe9 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/dates.mdx @@ -26,12 +26,3 @@ In invoices, the SAT (Mexican tax authority) requires that dates be displayed in the time zone of the issuer, so we will make the corresponding conversion and display the required portion of the date, which can be either just the date or the date and time. - - -## Dates in the Node.js SDK - -Starting with SDK 6, response timestamps such as `created_at` and `expires_at` become `Date` objects. This also applies to events returned by `webhooks.validateSignature()`. Null values are preserved. - -Calendar dates (`YYYY-MM-DD`), SAT stamp timestamps (`stamp.date`), and `metadata` values keep their text; not every property called `date` is a timestamp. Input dates accept strings and, where the types allow them, `Date` objects. Search filters keep their range objects. - -See the [SDK guide](./node-sdk.mdx) to upgrade code that treated timestamps as strings. diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx index c2941ae22..0ae3148a2 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/install.mdx @@ -27,8 +27,6 @@ Install the package from [NPM](https://www.npmjs.com/package/facturapi). $> npm install facturapi ``` -SDK 6 requires Node.js 18 or later and includes TypeScript types. See the [SDK guide](./node-sdk.mdx) for editor support and upgrading from earlier versions. - @@ -79,16 +77,20 @@ Import the library before using it in your code. -```javascript -const Facturapi = require('facturapi'); +Choose the import that matches your project. With ESM or TypeScript: + +```typescript +import Facturapi from 'facturapi'; ``` -ESM / TypeScript +With CommonJS: ```javascript -import Facturapi from 'facturapi'; +const Facturapi = require('facturapi'); ``` +The package includes TypeScript types and requires Node.js 18 or later. Import the constructor, types, and enums from `facturapi`. + diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx deleted file mode 100644 index 50c181773..000000000 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/getting-started/node-sdk.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -sidebar_position: 2.5 ---- - -# Node.js and TypeScript - -SDK 6 includes editor documentation and types for requests and responses. It requires Node.js 18 or later. The API remains responsible for tax information validation. - -## Imports and autocomplete - -With ESM or TypeScript: - -```ts -import Facturapi, { PaymentForm, type InvoiceCreateInput } from 'facturapi'; -``` - -With CommonJS: - -```js -const Facturapi = require('facturapi'); -const { PaymentForm } = Facturapi; -``` - -Always import from `facturapi`, including types and enums. You do not need a separate types package. Hover over a field or method to read its description, or use autocomplete to explore arguments and results. - -When preparing a request outside the SDK call, you can use `satisfies` with TypeScript 4.9 or later: - -```ts -const input = { - customer: 'cus_ejemplo', - payment_form: PaymentForm.EFECTIVO, - items: [{ - quantity: 1, - product: { description: 'Service', product_key: '84111506', price: 100 }, - }], -} satisfies InvoiceCreateInput; - -const invoice = await facturapi.invoices.create(input); -``` - -This example assumes a registered customer and a `facturapi` instance, as in the [quickstart](../quickstart.mdx). - -The types distinguish CFDI types, drafts, and structured complements. Where TypeScript can express the relationships, they connect fields to help you catch incomplete or incompatible inputs before sending a request. They do not replace API validation. - -## Customers by use case - -Instead of selecting a general input, you can use: - -- `customers.createNational()`: requires legal name, RFC, tax regime, and postal code; country can be omitted for Mexico. -- `customers.createForeign()`: requires legal name and an address with an explicit country. Country is a free string in TypeScript; the API validates that it matches the foreign customer case. -- `customers.createGeneric()`: requires legal name and either generic RFC `XAXX010101000` or `XEXX010101000`. - -These additional methods use the same operation; `customers.create()` remains available. For incomplete data, use `create(data, { createEditLink: true })`. A literal `true` selects the incomplete input; a dynamic boolean retains the normal contract. The specific methods retain their required fields. - -See the [customer examples](../guides/customers.mdx). - -## Responses and downloads - -Timestamps arrive as `Date` objects; calendar dates and SAT stamp timestamps keep their text. See [date formats](./dates.mdx). - -`downloadPdf()`, `downloadXml()`, and `downloadZip()` return streams in Node.js and `Blob` objects in browsers. Methods ending in `Url()` return an object with `url`, `expires_at`, `content_type`, and `filename`, rather than a string: - -```js -const download = await facturapi.invoices.downloadPdfUrl(invoice.id); -console.log(download.url, download.expires_at); -``` - -`webhooks.validateSignature()` returns a parsed event with converted dates. For signature verification, preserve the original text or bytes of the received body; serializing it again can change the signed content. - -## Upgrading from v3, v4, or v5 - -You can upgrade directly to v6. If you use current methods, import from `facturapi`, run Node.js 18+, and do not depend on timestamps being strings or on previous types, you can keep your calls. The new customer methods are optional; existing `create()` calls do not need to migrate. - -Review these cases if they apply to your integration: - -- **Dates:** replace string operations with `Date` methods or `toISOString()`, checking for `null` when applicable. `JSON.stringify()` still produces ISO strings, but may normalize their format. -- **Internal imports:** replace `facturapi/dist/...` with imports from `facturapi`. The `require('facturapi').default` alias still works. -- **TypeScript inputs:** compile your project to detect unknown fields and relationships now expressed in types. Cancellation motives `01` and `04` require `substitution`; `receipts.toInvoice()` returns a summary with `dry_run: true` and an invoice when it is false or omitted. -- **From v4:** `SearchResult` totals and page numbers may be absent with cursor pagination. `CursorSearchResult` is replaced by `SearchResult`. -- **From v3:** review methods removed in v4 and your Node.js runtime. - -The [README migration guide](https://github.com/FacturAPI/facturapi-node#actualizar-desde-v3-v4-o-v5) details replacements and cases that need no changes. See the [changelog](https://github.com/FacturAPI/facturapi-node/blob/main/CHANGELOG.md) for release improvements. diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx b/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx index e6afdf6f9..8c7b142a8 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/guides/customers.mdx @@ -27,8 +27,6 @@ use case. ## How to register a customer -The Node.js examples use SDK 6. `createNational()`, `createForeign()`, and `createGeneric()` select the input types for each case; `create()` remains available and uses the same API operation. For incomplete data with an edit link, keep using `create(data, { createEditLink: true })`. See the [Node.js and TypeScript guide](../getting-started/node-sdk.mdx). - In Facturapi, the process of registering the tax information of national and foreign customers is not very different from each other, but it is worth analyzing them separately, as it is different from what the SAT indicates in its technical standard. @@ -48,7 +46,7 @@ To learn about other data you can include, refer to the import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.createNational({ +const customer = await facturapi.customers.create({ legal_name: 'Dunder Mifflin', // Person's name or business legal name tax_id: 'ABC101010111', // RFC tax_system: '601', // Fiscal regime @@ -185,7 +183,7 @@ To learn about other data you can include, refer to the import Facturapi from 'facturapi' const facturapi = new Facturapi('sk_test_API_KEY'); -const customer = await facturapi.customers.createForeign({ +const customer = await facturapi.customers.create({ legal_name: 'Vättenfall, A.B.', // Person's name or business legal name tax_id: '198912171234', // Tax identification number (optional) email: 'email@example.com', // Email for sending (optional).