diff --git a/examples/ejemplo-datos-empleado-empleador.ts b/examples/ejemplo-datos-empleado-empleador.ts index 6e368e8..5836517 100644 --- a/examples/ejemplo-datos-empleado-empleador.ts +++ b/examples/ejemplo-datos-empleado-empleador.ts @@ -7,12 +7,13 @@ import { async function main(): Promise { - const settings: FiscalapiSettings = { - apiUrl: 'https://test.fisalapi.com', - apiKey: '', - tenant: '', - debug: true - }; + // Configuración de FiscalAPI +const settings: FiscalapiSettings = { + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. +}; const client = FiscalapiClient.create(settings); diff --git a/examples/ejemplo-timbres.ts b/examples/ejemplo-timbres.ts index 04844ad..65ef756 100644 --- a/examples/ejemplo-timbres.ts +++ b/examples/ejemplo-timbres.ts @@ -2,12 +2,13 @@ import { FiscalapiClient, FiscalapiSettings } from '../src/index'; async function main(): Promise { - const settings: FiscalapiSettings = { - apiUrl: 'https://test.fisalapi.com', - apiKey: '', - tenant: '', - debug: true - }; + // Configuración de FiscalAPI +const settings: FiscalapiSettings = { + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. +}; const client = FiscalapiClient.create(settings); diff --git a/examples/ejemplos-carta-porte-referencias.ts b/examples/ejemplos-carta-porte-referencias.ts index 8139de3..2409504 100644 --- a/examples/ejemplos-carta-porte-referencias.ts +++ b/examples/ejemplos-carta-porte-referencias.ts @@ -12,10 +12,10 @@ inspect.defaultOptions.colors = true; // Configuración de FiscalAPI const settings: FiscalapiSettings = { - apiUrl: 'https://test.fiscalapi.com', - apiKey: '', - tenant: '', - debug: true + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. }; // Sellos SAT de prueba diff --git a/examples/ejemplos-carta-porte-valores.ts b/examples/ejemplos-carta-porte-valores.ts index 4d3291d..417b003 100644 --- a/examples/ejemplos-carta-porte-valores.ts +++ b/examples/ejemplos-carta-porte-valores.ts @@ -12,10 +12,10 @@ inspect.defaultOptions.colors = true; // Configuración de FiscalAPI const settings: FiscalapiSettings = { - apiUrl: 'https://test.fiscalapi.com', - apiKey: 'sk_test_b7dae706_e16f_4faf_90fb_a5d1990985a2', - tenant: '275510ee-f64d-435a-9e92-1553d8f10a7e', - debug: true + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. }; // Sellos SAT de prueba diff --git a/examples/ejemplos-comercio-exterior-referencias.ts b/examples/ejemplos-comercio-exterior-referencias.ts new file mode 100644 index 0000000..f2c03aa --- /dev/null +++ b/examples/ejemplos-comercio-exterior-referencias.ts @@ -0,0 +1,1236 @@ +/** + * Ejemplos de facturas con complemento Comercio Exterior (CFDI 4.0) usando el SDK de FiscalAPI + * Todos los métodos usan el modo "ByReferences" - emisor y receptor se envían solo con su `id`. + * Cada caso de uso expone dos funciones: + * - UpdatePeople : actualiza emisor y receptor en FiscalAPI con sus datos completos. + * - PorReferencias : invoca UpdatePeople y luego crea la factura referenciando solo los ids. + * + * Pre-requisito: los certificados CSD (.cer y .key) del emisor deben estar previamente cargados + * en el dashboard de FiscalAPI para `issuerId`. Estos ejemplos NO los suben. + */ + +import { FiscalapiClient, FiscalapiSettings, Invoice, Person } from '../src/index'; +import { inspect } from 'util'; + +// Configuración de la consola para mostrar objetos anidados +inspect.defaultOptions.depth = null; +inspect.defaultOptions.colors = true; + +// Configuración de FiscalAPI +const settings: FiscalapiSettings = { + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. +}; + +// Fecha dinámica para los CFDI generados +const currentDate = '2026-05-19T08:56:40'; + +// IDs de personas previamente registradas en FiscalAPI (emisor y receptor) +const issuerId = '2e7b988f-3a2a-4f67-86e9-3f931dd48581'; +const recipientId = '109f4d94-63ea-4a21-ab15-20c8b87d8ee9'; + +// ============================================================================ +// 1. FACTURA CE INGRESO CON CARTA PORTE 31 (Facturación por referencias) +// ============================================================================ +async function facturaCEIngresoConCartaPorte31UpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'XEXX010101000', + legalName: 'Persona Fisica Extranjera', + email: 'persona.fisica.extranjera@example.com', + zipCode: '42501', + satTaxRegimeId: '616', + satCfdiUseId: 'S01', + countryId: 'USA', + foreignTin: '123456789' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCEIngresoConCartaPorte31PorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Ingreso Con Carta Porte 31 (Por Referencias) ===\n'); + + await facturaCEIngresoConCartaPorte31UpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PUE', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '78101800', + itemSku: 'SERV02', + quantity: 1.0, + unitOfMeasurementCode: 'HUR', + description: 'FLETE', + unitPrice: 2300.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '003', taxTypeCode: 'Tasa', taxRate: '0.300000', taxFlagCode: 'R' } + ] + }, + { + itemCode: '50161509', + itemSku: 'A0001', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'Gomitas', + unitPrice: 120.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' } + ] + }, + { + itemCode: '50307037', + itemSku: 'A0002', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'Pulparindo', + unitPrice: 100.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' } + ] + } + ], + complement: { + cartaPorte: { + transpInternacId: 'Sí', + entradaSalidaMercId: 'Salida', + paisOrigenDestinoId: 'ALB', + viaEntradaSalidaId: '01', + totalDistRec: 120.00, + unidadPesoId: 'KGM', + regimenAduaneros: [ + { regimenAduaneroId: 'EXD' } + ], + ubicaciones: [ + { + tipoUbicacion: 'Origen', + idUbicacion: 'OR000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Origen Nacional', + fechaHoraSalidaLlegada: '2026-04-27T08:00:00', + domicilio: { + calle: 'xola', + numeroExterior: '531', + coloniaId: '0496', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + }, + { + tipoUbicacion: 'Destino', + idUbicacion: 'DE000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Destino Nacional', + fechaHoraSalidaLlegada: '2026-04-27T20:00:00', + distanciaRecorrida: 120.00, + domicilio: { + calle: 'Av Coyoacan', + numeroExterior: '120', + coloniaId: '2624', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + } + ], + mercancias: [ + { + bienesTranspId: '50433238', + descripcion: 'Gomitas', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1200.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + }, + { + bienesTranspId: '50433238', + descripcion: 'Pulparindo', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1000.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + } + ], + autotransporte: { + permSCTId: 'TPAF02', + numPermisoSCT: '123456', + configVehicularId: 'C2', + pesoBrutoVehicular: 1, + placaVM: '555TTT', + anioModeloVM: 2023, + aseguraRespCivil: 'ODISEA', + polizaRespCivil: '3456YUHNB234RT' + }, + tiposFigura: [ + { + tipoFiguraId: '01', + rfcFigura: 'KAHO641101B39', + numLicencia: 'D0908240', + nombreFigura: 'OSCAR KALA HAAK' + } + ] + }, + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'CIF', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'Av Siempre viva', + numeroExterior: '123', + coloniaId: '0001', + localidadId: '06', + municipioId: '025', + estadoId: 'COA', + paisId: 'MEX', + codigoPostalId: '26015' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'Clinton ST', + numeroExterior: '10002', + estado: 'NY', + paisId: 'USA', + codigoPostal: '10002-0000' + } + }, + mercancias: [ + { + noIdentificacion: 'A0001', + fraccionArancelariaId: '4011101099', + cantidadAduana: '1.000', + unidadAduanaId: '06', + valorUnitarioAduana: '120.00', + valorDolares: '120.00' + }, + { + noIdentificacion: 'A0002', + fraccionArancelariaId: '8407210299', + cantidadAduana: '1.000', + unidadAduanaId: '06', + valorUnitarioAduana: '100.00', + valorDolares: '100.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 2. FACTURA CE INGRESO DIFERENTES MONEDAS (Facturación por referencias) +// ============================================================================ +async function facturaCEIngresoDiferentesMonedasUpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'XEXX010101000', + legalName: 'Persona Fisica Extranjera', + email: 'persona.fisica.extranjera@example.com', + zipCode: '42501', + satTaxRegimeId: '616', + satCfdiUseId: 'S01', + countryId: 'USA', + foreignTin: '123456789' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCEIngresoDiferentesMonedasPorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Ingreso Diferentes Monedas (Por Referencias) ===\n'); + + await facturaCEIngresoDiferentesMonedasUpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'MXN', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' }, + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.106666', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '2.00', + unidadAduanaId: '01', + valorUnitarioAduana: '11.74', + valorDolares: '23.47' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 3. FACTURA CE KIT PARTE (Facturación por referencias) +// ============================================================================ +async function facturaCEKitParteUpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'XEXX010101000', + legalName: 'U.S. 0026 SW', + email: 'us.0026.sw@example.com', + zipCode: '42501', + satTaxRegimeId: '616', + satCfdiUseId: 'CP01', + countryId: 'USA', + foreignTin: '123456789' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCEKitPartePorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Kit Parte (Por Referencias) ===\n'); + + await facturaCEKitParteUpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '01', + paymentMethodCode: 'PUE', + currencyCode: 'MXN', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '51241200', + itemSku: '131494-1055', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'FORMULA MAGISTRAL', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + }, + { + itemCode: '51241200', + itemSku: '131494-1055', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'FORMULA MAGISTRAL', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '2', + unidadAduanaId: '01', + valorUnitarioAduana: '10.00', + valorDolares: '20.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 4. FACTURA CE RECEPTOR EXTRANJERO (Facturación por referencias) +// ============================================================================ +async function facturaCEReceptorExtranjeroUpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'XEXX010101000', + legalName: 'U.S. 0026 SW', + email: 'us.0026.sw@example.com', + zipCode: '42501', + satTaxRegimeId: '616', + satCfdiUseId: 'CP01', + countryId: 'USA', + foreignTin: '123456789' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCEReceptorExtranjeroPorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Receptor Extranjero (Por Referencias) ===\n'); + + await facturaCEReceptorExtranjeroUpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '117.64', + unidadAduanaId: '01', + valorUnitarioAduana: '3.40', + valorDolares: '400.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 5. FACTURA CE RECEPTOR NACIONAL (Facturación por referencias) +// ============================================================================ +async function facturaCEReceptorNacionalUpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'URE180429TM6', + legalName: 'UNIVERSIDAD ROBOTICA ESPAÑOLA', + email: 'universidad.robotica.espanola@example.com', + zipCode: '86991', + satTaxRegimeId: '601', + satCfdiUseId: 'G01' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCEReceptorNacionalPorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Receptor Nacional (Por Referencias) ===\n'); + + await facturaCEReceptorNacionalUpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' }, + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.106666', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + colonia: '0214', + localidad: '01', + municipio: '014', + estado: 'QUE', + paisId: 'MEX', + codigoPostal: '76199' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '117.64', + unidadAduanaId: '01', + valorUnitarioAduana: '3.40', + valorDolares: '400.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 6. FACTURA CE TRASLADO CON CARTA PORTE 31 (Facturación por referencias) +// ============================================================================ +async function facturaCETrasladoConCartaPorte31UpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate.receptor@example.com', + zipCode: '42501', + satTaxRegimeId: '601', + satCfdiUseId: 'S01' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCETrasladoConCartaPorte31PorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Traslado Con Carta Porte 31 (Por Referencias) ===\n'); + + await facturaCETrasladoConCartaPorte31UpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + currencyCode: 'XXX', + typeCode: 'T', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '78101800', + itemSku: 'TR01', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'TRANSPORTE DE CARGA', + unitPrice: 0.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + }, + { + itemCode: '32101622', + itemSku: 'UT421511', + quantity: 100.00, + unitOfMeasurementCode: 'XBX', + description: 'MEMORIA FLASH', + unitPrice: 0.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + cartaPorte: { + transpInternacId: 'Sí', + entradaSalidaMercId: 'Salida', + paisOrigenDestinoId: 'ALB', + viaEntradaSalidaId: '01', + totalDistRec: 120.00, + unidadPesoId: 'KGM', + regimenAduaneros: [ + { regimenAduaneroId: 'EXD' } + ], + ubicaciones: [ + { + tipoUbicacion: 'Origen', + idUbicacion: 'OR000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Origen Nacional', + fechaHoraSalidaLlegada: '2026-04-27T08:00:00', + domicilio: { + calle: 'xola', + numeroExterior: '531', + coloniaId: '0496', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + }, + { + tipoUbicacion: 'Destino', + idUbicacion: 'DE000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Destino Nacional', + fechaHoraSalidaLlegada: '2026-04-27T20:00:00', + distanciaRecorrida: 120.00, + domicilio: { + calle: 'Av Coyoacan', + numeroExterior: '120', + coloniaId: '2624', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + } + ], + mercancias: [ + { + bienesTranspId: '50433238', + descripcion: 'Gomitas', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1200.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + }, + { + bienesTranspId: '50433238', + descripcion: 'Pulparindo', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1000.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + } + ], + autotransporte: { + permSCTId: 'TPAF02', + numPermisoSCT: '123456', + configVehicularId: 'C2', + pesoBrutoVehicular: 1, + placaVM: '555TTT', + anioModeloVM: 2023, + aseguraRespCivil: 'ODISEA', + polizaRespCivil: '3456YUHNB234RT' + }, + tiposFigura: [ + { + tipoFiguraId: '01', + rfcFigura: 'KAHO641101B39', + numLicencia: 'D0908240', + nombreFigura: 'OSCAR KALA HAAK' + } + ] + }, + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: 'UT421511', + fraccionArancelariaId: '2402200100', + cantidadAduana: '100.00', + unidadAduanaId: '01', + valorUnitarioAduana: '1.00', + valorDolares: '0.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 7. FACTURA CE TRASLADO TRASLADO MERCANCIA PROPIA (Facturación por referencias) +// ============================================================================ +async function facturaCETrasladoTrasladoMercanciaPropiaUpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate.receptor@example.com', + zipCode: '42501', + satTaxRegimeId: '601', + satCfdiUseId: 'S01' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCETrasladoTrasladoMercanciaPropiaPorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Traslado Traslado Mercancia Propia (Por Referencias) ===\n'); + + await facturaCETrasladoTrasladoMercanciaPropiaUpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + currencyCode: 'USD', + typeCode: 'T', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'My description...', + unitPrice: 0.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + comercioExterior: { + motivoTrasladoId: '02', + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FCA', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'SW Street.', + numeroExterior: '12345', + localidad: 'Oregon', + estado: 'OR', + paisId: 'USA', + codigoPostal: '12345' + } + }, + destinatarios: [ + { + numRegIdTrib: '123456789', + nombre: 'EKU9003173C9', + domicilios: [ + { + calle: 'SW Street.', + numeroExterior: '12345', + localidad: 'Oregon', + estado: 'OR', + paisId: 'USA', + codigoPostal: '12345' + } + ] + } + ], + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '0101210100', + cantidadAduana: '1', + unidadAduanaId: '07', + valorUnitarioAduana: '22.64', + valorDolares: '22.64' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 8. FACTURA CE TRASLADO TRASLADO (Facturación por referencias) +// ============================================================================ +async function facturaCETrasladoTrasladoUpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate.receptor@example.com', + zipCode: '42501', + satTaxRegimeId: '601', + satCfdiUseId: 'G01' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCETrasladoTrasladoPorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Traslado Traslado (Por Referencias) ===\n'); + + await facturaCETrasladoTrasladoUpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + currencyCode: 'USD', + typeCode: 'T', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '117.64', + unidadAduanaId: '01', + valorUnitarioAduana: '3.40', + valorDolares: '400.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 9. FACTURA CE UNIDADES DE MEDIDA NO EQUIVALENTES (Facturación por referencias) +// ============================================================================ +async function facturaCEUnidadesDeMedidaNoEquivalentesUpdatePeople(client: FiscalapiClient): Promise { + const issuer: Person = { + id: issuerId, + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + email: 'escuela.kemper.urgate@example.com', + zipCode: '42501', + satTaxRegimeId: '601' + }; + const recipient: Person = { + id: recipientId, + tin: 'XEXX010101000', + legalName: 'U.S. 0026 SW', + email: 'us.0026.sw@example.com', + zipCode: '42501', + satTaxRegimeId: '616', + satCfdiUseId: 'CP01', + countryId: 'USA', + foreignTin: '123456789' + }; + await client.persons.update(issuer); + await client.persons.update(recipient); +} + +async function facturaCEUnidadesDeMedidaNoEquivalentesPorReferencias(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Unidades De Medida No Equivalentes (Por Referencias) ===\n'); + + await facturaCEUnidadesDeMedidaNoEquivalentesUpdatePeople(client); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { id: issuerId }, + recipient: { id: recipientId }, + items: [ + { + itemCode: '50201708', + itemSku: '131494-1055', + quantity: 1.000, + unitOfMeasurementCode: 'H87', + description: 'Bebida', + unitPrice: 100.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' }, + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.106666', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2009310201', + cantidadAduana: '0.500', + unidadAduanaId: '08', + valorUnitarioAduana: '200.00', + valorDolares: '100.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// FUNCION PRINCIPAL +// ============================================================================ +async function main(): Promise { + console.log('=== Ejemplos de Factura con Comercio Exterior FiscalAPI (Por Referencias) ===\n'); + + const client = FiscalapiClient.create(settings); + + try { + // Descomentar el caso de uso que se desea ejecutar + + //await facturaCEIngresoConCartaPorte31PorReferencias(client); + // await facturaCEIngresoDiferentesMonedasPorReferencias(client); + // await facturaCEKitPartePorReferencias(client); + // await facturaCEReceptorExtranjeroPorReferencias(client); + // await facturaCEReceptorNacionalPorReferencias(client); + // await facturaCETrasladoConCartaPorte31PorReferencias(client); + // await facturaCETrasladoTrasladoMercanciaPropiaPorReferencias(client); + // await facturaCETrasladoTrasladoPorReferencias(client); + await facturaCEUnidadesDeMedidaNoEquivalentesPorReferencias(client); + + console.log('\nEjecución completada.'); + } catch (error) { + console.error('Error:', error); + } +} + +// Ejecutar función principal +main(); diff --git a/examples/ejemplos-comercio-exterior-valores.ts b/examples/ejemplos-comercio-exterior-valores.ts new file mode 100644 index 0000000..534249a --- /dev/null +++ b/examples/ejemplos-comercio-exterior-valores.ts @@ -0,0 +1,1140 @@ +/** + * Ejemplos de facturas con complemento Comercio Exterior (CFDI 4.0) usando el SDK de FiscalAPI + * Todos los métodos usan el modo "ByValues" - los datos del emisor y receptor van inline en la petición + */ + +import { FiscalapiClient, FiscalapiSettings, Invoice } from '../src/index'; +import { inspect } from 'util'; + +// Configuración de la consola para mostrar objetos anidados +inspect.defaultOptions.depth = null; +inspect.defaultOptions.colors = true; + +// Configuración de FiscalAPI +const settings: FiscalapiSettings = { + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. +}; + +// Sellos SAT de prueba +const currentDate = '2026-05-19T08:56:40'; +const escuelaKemperUrgateBase64Cer = "MIIFsDCCA5igAwIBAgIUMzAwMDEwMDAwMDA1MDAwMDM0MTYwDQYJKoZIhvcNAQELBQAwggErMQ8wDQYDVQQDDAZBQyBVQVQxLjAsBgNVBAoMJVNFUlZJQ0lPIERFIEFETUlOSVNUUkFDSU9OIFRSSUJVVEFSSUExGjAYBgNVBAsMEVNBVC1JRVMgQXV0aG9yaXR5MSgwJgYJKoZIhvcNAQkBFhlvc2Nhci5tYXJ0aW5lekBzYXQuZ29iLm14MR0wGwYDVQQJDBQzcmEgY2VycmFkYSBkZSBjYWxpejEOMAwGA1UEEQwFMDYzNzAxCzAJBgNVBAYTAk1YMRkwFwYDVQQIDBBDSVVEQUQgREUgTUVYSUNPMREwDwYDVQQHDAhDT1lPQUNBTjERMA8GA1UELRMIMi41LjQuNDUxJTAjBgkq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lrwVnlbzhLjeQY6PplKp3/a5Kr5yM0T4wJoKQQ6v3vSNmrhpbuAtKxpMILe8CQoo="; +const password = "12345678a"; + +// ============================================================================ +// 1. FACTURA CE INGRESO CON CARTA PORTE 31 (Facturación por valores) +// ============================================================================ +async function facturaCEIngresoConCartaPorte31PorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Ingreso Con Carta Porte 31 (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PUE', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'XEXX010101000', + legalName: 'Persona Fisica Extranjera', + zipCode: '42501', + taxRegimeCode: '616', + cfdiUseCode: 'S01', + countryId: 'USA', + foreignTin: '123456789' + }, + items: [ + { + itemCode: '78101800', + itemSku: 'SERV02', + quantity: 1.0, + unitOfMeasurementCode: 'HUR', + description: 'FLETE', + unitPrice: 2300.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '003', taxTypeCode: 'Tasa', taxRate: '0.300000', taxFlagCode: 'R' } + ] + }, + { + itemCode: '50161509', + itemSku: 'A0001', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'Gomitas', + unitPrice: 120.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' } + ] + }, + { + itemCode: '50307037', + itemSku: 'A0002', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'Pulparindo', + unitPrice: 100.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' } + ] + } + ], + complement: { + cartaPorte: { + transpInternacId: 'Sí', + entradaSalidaMercId: 'Salida', + paisOrigenDestinoId: 'ALB', + viaEntradaSalidaId: '01', + totalDistRec: 120.00, + unidadPesoId: 'KGM', + regimenAduaneros: [ + { regimenAduaneroId: 'EXD' } + ], + ubicaciones: [ + { + tipoUbicacion: 'Origen', + idUbicacion: 'OR000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Origen Nacional', + fechaHoraSalidaLlegada: '2026-04-27T08:00:00', + domicilio: { + calle: 'xola', + numeroExterior: '531', + coloniaId: '0496', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + }, + { + tipoUbicacion: 'Destino', + idUbicacion: 'DE000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Destino Nacional', + fechaHoraSalidaLlegada: '2026-04-27T20:00:00', + distanciaRecorrida: 120.00, + domicilio: { + calle: 'Av Coyoacan', + numeroExterior: '120', + coloniaId: '2624', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + } + ], + mercancias: [ + { + bienesTranspId: '50433238', + descripcion: 'Gomitas', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1200.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + }, + { + bienesTranspId: '50433238', + descripcion: 'Pulparindo', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1000.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + } + ], + autotransporte: { + permSCTId: 'TPAF02', + numPermisoSCT: '123456', + configVehicularId: 'C2', + pesoBrutoVehicular: 1, + placaVM: '555TTT', + anioModeloVM: 2023, + aseguraRespCivil: 'ODISEA', + polizaRespCivil: '3456YUHNB234RT' + }, + tiposFigura: [ + { + tipoFiguraId: '01', + rfcFigura: 'KAHO641101B39', + numLicencia: 'D0908240', + nombreFigura: 'OSCAR KALA HAAK' + } + ] + }, + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'CIF', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'Av Siempre viva', + numeroExterior: '123', + coloniaId: '0001', + localidadId: '06', + municipioId: '025', + estadoId: 'COA', + paisId: 'MEX', + codigoPostalId: '26015' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'Clinton ST', + numeroExterior: '10002', + estado: 'NY', + paisId: 'USA', + codigoPostal: '10002-0000' + } + }, + mercancias: [ + { + noIdentificacion: 'A0001', + fraccionArancelariaId: '4011101099', + cantidadAduana: '1.000', + unidadAduanaId: '06', + valorUnitarioAduana: '120.00', + valorDolares: '120.00' + }, + { + noIdentificacion: 'A0002', + fraccionArancelariaId: '8407210299', + cantidadAduana: '1.000', + unidadAduanaId: '06', + valorUnitarioAduana: '100.00', + valorDolares: '100.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 2. FACTURA CE INGRESO DIFERENTES MONEDAS (Facturación por valores) +// ============================================================================ +async function facturaCEIngresoDiferentesMonedasPorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Ingreso Diferentes Monedas (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'MXN', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'XEXX010101000', + legalName: 'Persona Fisica Extranjera', + zipCode: '42501', + taxRegimeCode: '616', + cfdiUseCode: 'S01', + countryId: 'USA', + foreignTin: '123456789' + }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' }, + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.106666', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '2.00', + unidadAduanaId: '01', + valorUnitarioAduana: '11.74', + valorDolares: '23.47' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 3. FACTURA CE KIT PARTE (Facturación por valores) +// ============================================================================ +async function facturaCEKitPartePorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Kit Parte (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '01', + paymentMethodCode: 'PUE', + currencyCode: 'MXN', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'XEXX010101000', + legalName: 'U.S. 0026 SW', + zipCode: '42501', + taxRegimeCode: '616', + cfdiUseCode: 'CP01', + countryId: 'USA', + foreignTin: '123456789' + }, + items: [ + { + itemCode: '51241200', + itemSku: '131494-1055', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'FORMULA MAGISTRAL', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + }, + { + itemCode: '51241200', + itemSku: '131494-1055', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'FORMULA MAGISTRAL', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '2', + unidadAduanaId: '01', + valorUnitarioAduana: '10.00', + valorDolares: '20.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 4. FACTURA CE RECEPTOR EXTRANJERO (Facturación por valores) +// ============================================================================ +async function facturaCEReceptorExtranjeroPorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Receptor Extranjero (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'XEXX010101000', + legalName: 'U.S. 0026 SW', + zipCode: '42501', + taxRegimeCode: '616', + cfdiUseCode: 'CP01', + countryId: 'USA', + foreignTin: '123456789' + }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '117.64', + unidadAduanaId: '01', + valorUnitarioAduana: '3.40', + valorDolares: '400.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 5. FACTURA CE RECEPTOR NACIONAL (Facturación por valores) +// ============================================================================ +async function facturaCEReceptorNacionalPorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Receptor Nacional (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'URE180429TM6', + legalName: 'UNIVERSIDAD ROBOTICA ESPAÑOLA', + zipCode: '86991', + taxRegimeCode: '601', + cfdiUseCode: 'G01' + }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' }, + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.106666', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + colonia: '0214', + localidad: '01', + municipio: '014', + estado: 'QUE', + paisId: 'MEX', + codigoPostal: '76199' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '117.64', + unidadAduanaId: '01', + valorUnitarioAduana: '3.40', + valorDolares: '400.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 6. FACTURA CE TRASLADO CON CARTA PORTE 31 (Facturación por valores) +// ============================================================================ +async function facturaCETrasladoConCartaPorte31PorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Traslado Con Carta Porte 31 (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + currencyCode: 'XXX', + typeCode: 'T', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + zipCode: '42501', + taxRegimeCode: '601', + cfdiUseCode: 'S01' + }, + items: [ + { + itemCode: '78101800', + itemSku: 'TR01', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'TRANSPORTE DE CARGA', + unitPrice: 0.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + }, + { + itemCode: '32101622', + itemSku: 'UT421511', + quantity: 100.00, + unitOfMeasurementCode: 'XBX', + description: 'MEMORIA FLASH', + unitPrice: 0.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + cartaPorte: { + transpInternacId: 'Sí', + entradaSalidaMercId: 'Salida', + paisOrigenDestinoId: 'ALB', + viaEntradaSalidaId: '01', + totalDistRec: 120.00, + unidadPesoId: 'KGM', + regimenAduaneros: [ + { regimenAduaneroId: 'EXD' } + ], + ubicaciones: [ + { + tipoUbicacion: 'Origen', + idUbicacion: 'OR000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Origen Nacional', + fechaHoraSalidaLlegada: '2026-04-27T08:00:00', + domicilio: { + calle: 'xola', + numeroExterior: '531', + coloniaId: '0496', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + }, + { + tipoUbicacion: 'Destino', + idUbicacion: 'DE000001', + rfcRemitenteDestinatario: 'XAXX010101000', + nombreRemitenteDestinatario: 'Destino Nacional', + fechaHoraSalidaLlegada: '2026-04-27T20:00:00', + distanciaRecorrida: 120.00, + domicilio: { + calle: 'Av Coyoacan', + numeroExterior: '120', + coloniaId: '2624', + localidadId: '03', + municipioId: '014', + estadoId: 'CMX', + paisId: 'MEX', + codigoPostalId: '03100' + } + } + ], + mercancias: [ + { + bienesTranspId: '50433238', + descripcion: 'Gomitas', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1200.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + }, + { + bienesTranspId: '50433238', + descripcion: 'Pulparindo', + cantidad: 1, + claveUnidadId: 'XPK', + pesoEnKg: 10.000, + valorMercancia: 1000.00, + monedaId: 'USD', + fraccionArancelariaId: '2005800100', + tipoMateriaId: '04' + } + ], + autotransporte: { + permSCTId: 'TPAF02', + numPermisoSCT: '123456', + configVehicularId: 'C2', + pesoBrutoVehicular: 1, + placaVM: '555TTT', + anioModeloVM: 2023, + aseguraRespCivil: 'ODISEA', + polizaRespCivil: '3456YUHNB234RT' + }, + tiposFigura: [ + { + tipoFiguraId: '01', + rfcFigura: 'KAHO641101B39', + numLicencia: 'D0908240', + nombreFigura: 'OSCAR KALA HAAK' + } + ] + }, + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: 'UT421511', + fraccionArancelariaId: '2402200100', + cantidadAduana: '100.00', + unidadAduanaId: '01', + valorUnitarioAduana: '1.00', + valorDolares: '0.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 7. FACTURA CE TRASLADO TRASLADO MERCANCIA PROPIA (Facturación por valores) +// ============================================================================ +async function facturaCETrasladoTrasladoMercanciaPropiaPorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Traslado Traslado Mercancia Propia (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + currencyCode: 'USD', + typeCode: 'T', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + zipCode: '42501', + taxRegimeCode: '601', + cfdiUseCode: 'S01' + }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 1.0, + unitOfMeasurementCode: 'H87', + description: 'My description...', + unitPrice: 0.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + comercioExterior: { + motivoTrasladoId: '02', + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FCA', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'SW Street.', + numeroExterior: '12345', + localidad: 'Oregon', + estado: 'OR', + paisId: 'USA', + codigoPostal: '12345' + } + }, + destinatarios: [ + { + numRegIdTrib: '123456789', + nombre: 'EKU9003173C9', + domicilios: [ + { + calle: 'SW Street.', + numeroExterior: '12345', + localidad: 'Oregon', + estado: 'OR', + paisId: 'USA', + codigoPostal: '12345' + } + ] + } + ], + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '0101210100', + cantidadAduana: '1', + unidadAduanaId: '07', + valorUnitarioAduana: '22.64', + valorDolares: '22.64' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 8. FACTURA CE TRASLADO TRASLADO (Facturación por valores) +// ============================================================================ +async function facturaCETrasladoTrasladoPorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Traslado Traslado (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + currencyCode: 'USD', + typeCode: 'T', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + zipCode: '42501', + taxRegimeCode: '601', + cfdiUseCode: 'G01' + }, + items: [ + { + itemCode: '50211503', + itemSku: '131494-1055', + quantity: 2, + unitOfMeasurementCode: 'H87', + description: 'Cigarros', + unitPrice: 200.00, + discount: 0, + taxObjectCode: '01', + itemTaxes: [] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2402200100', + cantidadAduana: '117.64', + unidadAduanaId: '01', + valorUnitarioAduana: '3.40', + valorDolares: '400.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// 9. FACTURA CE UNIDADES DE MEDIDA NO EQUIVALENTES (Facturación por valores) +// ============================================================================ +async function facturaCEUnidadesDeMedidaNoEquivalentesPorValores(client: FiscalapiClient): Promise { + console.log('\n=== Factura CE Unidades De Medida No Equivalentes (Por Valores) ===\n'); + + const invoice: Invoice = { + versionCode: '4.0', + paymentFormCode: '99', + paymentMethodCode: 'PPD', + currencyCode: 'USD', + typeCode: 'I', + expeditionZipCode: '42501', + series: 'CCE', + date: currentDate, + paymentConditions: 'CondicionesDePago', + exportCode: '02', + issuer: { + tin: 'EKU9003173C9', + legalName: 'ESCUELA KEMPER URGATE', + taxRegimeCode: '601', + taxCredentials: [ + { base64File: escuelaKemperUrgateBase64Cer, fileType: 0, password }, + { base64File: escuelaKemperUrgateBase64Key, fileType: 1, password } + ] + }, + recipient: { + tin: 'XEXX010101000', + legalName: 'U.S. 0026 SW', + zipCode: '42501', + taxRegimeCode: '616', + cfdiUseCode: 'CP01', + countryId: 'USA', + foreignTin: '123456789' + }, + items: [ + { + itemCode: '50201708', + itemSku: '131494-1055', + quantity: 1.000, + unitOfMeasurementCode: 'H87', + description: 'Bebida', + unitPrice: 100.00, + discount: 0, + taxObjectCode: '02', + itemTaxes: [ + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.160000', taxFlagCode: 'T' }, + { taxCode: '001', taxTypeCode: 'Tasa', taxRate: '0.100000', taxFlagCode: 'R' }, + { taxCode: '002', taxTypeCode: 'Tasa', taxRate: '0.106666', taxFlagCode: 'R' } + ] + } + ], + complement: { + comercioExterior: { + claveDePedimentoId: 'A1', + certificadoOrigen: 0, + incotermId: 'FOB', + tipoCambioUSD: '17.3477', + emisor: { + domicilio: { + calle: 'CALLE DEL PAPEL', + coloniaId: '0214', + localidadId: '01', + municipioId: '014', + estadoId: 'QUE', + paisId: 'MEX', + codigoPostalId: '76199' + } + }, + receptor: { + numRegIdTrib: '123456789', + domicilio: { + calle: 'ST. A', + estado: 'TX', + paisId: 'USA', + codigoPostal: '00000' + } + }, + mercancias: [ + { + noIdentificacion: '131494-1055', + fraccionArancelariaId: '2009310201', + cantidadAduana: '0.500', + unidadAduanaId: '08', + valorUnitarioAduana: '200.00', + valorDolares: '100.00' + } + ] + } + } + }; + + const response = await client.invoices.create(invoice); + console.log('Response:', response); +} + +// ============================================================================ +// FUNCION PRINCIPAL +// ============================================================================ +async function main(): Promise { + console.log('=== Ejemplos de Factura con Comercio Exterior FiscalAPI (Por Valores) ===\n'); + + const client = FiscalapiClient.create(settings); + + try { + // Descomentar el caso de uso que se desea ejecutar + + //await facturaCEIngresoConCartaPorte31PorValores(client); + // await facturaCEIngresoDiferentesMonedasPorValores(client); + // await facturaCEKitPartePorValores(client); + // await facturaCEReceptorExtranjeroPorValores(client); + // await facturaCEReceptorNacionalPorValores(client); + // await facturaCETrasladoConCartaPorte31PorValores(client); + // await facturaCETrasladoTrasladoMercanciaPropiaPorValores(client); + // await facturaCETrasladoTrasladoPorValores(client); + // await facturaCEUnidadesDeMedidaNoEquivalentesPorValores(client); + + console.log('\nEjecución completada.'); + } catch (error) { + console.error('Error:', error); + } +} + +// Ejecutar función principal +main(); diff --git a/examples/ejemplos-factura-impuestos-locales-referencias.ts b/examples/ejemplos-factura-impuestos-locales-referencias.ts index ee3e619..c808f76 100644 --- a/examples/ejemplos-factura-impuestos-locales-referencias.ts +++ b/examples/ejemplos-factura-impuestos-locales-referencias.ts @@ -12,10 +12,10 @@ inspect.defaultOptions.colors = true; // Configuración de FiscalAPI const settings: FiscalapiSettings = { - apiUrl: 'https://test.fiscalapi.com', - apiKey: '', - tenant: '', - debug: true + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. }; // IDs de personas pre-configuradas en FiscalAPI (modo ByReferences) diff --git a/examples/ejemplos-factura-impuestos-locales-valores.ts b/examples/ejemplos-factura-impuestos-locales-valores.ts index c8340e6..867a2a6 100644 --- a/examples/ejemplos-factura-impuestos-locales-valores.ts +++ b/examples/ejemplos-factura-impuestos-locales-valores.ts @@ -12,10 +12,10 @@ inspect.defaultOptions.colors = true; // Configuración de FiscalAPI const settings: FiscalapiSettings = { - apiUrl: 'https://test.fiscalapi.com', - apiKey: '', - tenant: '', - debug: true + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. }; // Sellos SAT de prueba diff --git a/examples/ejemplos-factura-nomina-referencias.ts b/examples/ejemplos-factura-nomina-referencias.ts index b122735..c6822e2 100644 --- a/examples/ejemplos-factura-nomina-referencias.ts +++ b/examples/ejemplos-factura-nomina-referencias.ts @@ -18,11 +18,10 @@ inspect.defaultOptions.colors = true; // Configuración de FiscalAPI const settings: FiscalapiSettings = { - apiUrl: 'https://test.fisalapi.com', - apiKey: '', - tenant: '', - debug: true - + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. }; // ============================================================================ diff --git a/examples/ejemplos-factura-nomina-valores.ts b/examples/ejemplos-factura-nomina-valores.ts index 69706a3..bec49bd 100644 --- a/examples/ejemplos-factura-nomina-valores.ts +++ b/examples/ejemplos-factura-nomina-valores.ts @@ -12,10 +12,10 @@ inspect.defaultOptions.colors = true; // Configuración de FiscalAPI const settings: FiscalapiSettings = { - apiUrl: 'https://test.fisalapi.com', - apiKey: '', - tenant: '', - debug: true + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. }; // Sellos SAT de prueba diff --git a/examples/ejemplos-firma-manifiestos.ts b/examples/ejemplos-firma-manifiestos.ts new file mode 100644 index 0000000..4f7a5fb --- /dev/null +++ b/examples/ejemplos-firma-manifiestos.ts @@ -0,0 +1,65 @@ +/** + * Ejemplo: firma de manifiesto vía POST /api/v4/manifests usando el SDK de FiscalAPI. + * El endpoint recibe el certificado (.cer), la llave privada (.key) y la contraseña en base64, + * y devuelve el PDF del manifiesto firmado (también en base64). + */ + +import { FiscalapiClient, FiscalapiSettings, SignManifestRequest } from '../src/index'; +import { inspect } from 'util'; + +// Configuración de la consola para mostrar objetos anidados +inspect.defaultOptions.depth = null; +inspect.defaultOptions.colors = true; + +// Configuración de FiscalAPI +const settings: FiscalapiSettings = { + apiUrl: 'https://test.fiscalapi.com', // https://live.fiscalapi.com + apiKey: '', // API key de FiscalAPI + tenant: '', // Tenant de FiscalAPI + debug: true // true, imprime raw request y response en consola, util durante el desarrollo de la integración. +}; + + + +// Sellos SAT de prueba (ESCUELA KEMPER URGATE) +const escuelaKemperUrgateBase64CerFIEL = "MIIGBDCCA+ygAwIBAgIUMzAwMDEwMDAwMDA1MDAwMDM0MTUwDQYJKoZIhvcNAQELBQAwggErMQ8wDQYDVQQDDAZBQyBVQVQxLjAsBgNVBAoMJVNFUlZJQ0lPIERFIEFETUlOSVNUUkFDSU9OIFRSSUJVVEFSSUExGjAYBgNVBAsMEVNBVC1JRVMgQXV0aG9yaXR5MSgwJgYJKoZIhvcNAQkBFhlvc2Nhci5tYXJ0aW5lekBzYXQuZ29iLm14MR0wGwYDVQQJDBQzcmEgY2VycmFkYSBkZSBjYWxpejEOMAwGA1UEE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C1h0mfObxOhcbwxCC18AnNqfxh5rCvNxKYi0yqa5g9UFBOOKyxrhvP/eMdnPpd1DtvzP79zMQCQ+NlXt/XtmDRNUpPc7nPwhdPbRJTsetDqZK9NQf6cZ4/2cDIMd1/QomTmzKU9cjNXZgMcDSY7UYrN+n8CrETwu9dgNDuYjynh4XYlm0x9/Rx5r+77d1nzE6rkBH17/lH3fb8p4MWDlr6HIIgXxYCmeAhiws8tthJoD/nk1n6fvrxTFrEmEE1XG7JrNrDP1dLnjH+paHXy0thdQ8lpBMM4Wtqk0KVPn2SyaY3dslkdHg="; +const password = "12345678a"; + +// ============================================================================ +// 1. FIRMA DE CARTA MANIFIESTO (ESCUELA KEMPER URGATE) +// ============================================================================ +async function firmaCartaManifiesto(client: FiscalapiClient): Promise { + console.log('\n=== Firma de Carta Manifiesto (ESCUELA KEMPER URGATE) ===\n'); + + const request: SignManifestRequest = { + base64Cer: escuelaKemperUrgateBase64CerFIEL, + base64Key: escuelaKemperUrgateBase64KeyFIEL, + password: password + }; + + const response = await client.manifests.sign(request); + console.log('Response:', response); +} + +// ============================================================================ +// FUNCION PRINCIPAL +// ============================================================================ +async function main(): Promise { + console.log('=== Ejemplos de Firma de Manifiesto FiscalAPI ===\n'); + + const client = FiscalapiClient.create(settings); + + try { + // Descomentar el caso de uso que se desea ejecutar + + await firmaCartaManifiesto(client); + + console.log('\nEjecución completada.'); + } catch (error) { + console.error('Error:', error); + } +} + +// Ejecutar función principal +main(); diff --git a/package.json b/package.json index f8081d0..2b86835 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fiscalapi", - "version": "4.0.384", + "version": "4.0.386", "description": "SDK de Node.js para Fiscalapi", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", diff --git a/src/abstractions/fiscalapi-client.interface.ts b/src/abstractions/fiscalapi-client.interface.ts index fada5e7..4909fce 100644 --- a/src/abstractions/fiscalapi-client.interface.ts +++ b/src/abstractions/fiscalapi-client.interface.ts @@ -4,6 +4,7 @@ import { IDownloadCatalogService } from './download-catalog-service.interface'; import { IDownloadRequestService } from './download-request-service.interface'; import { IDownloadRuleService } from './download-rule-service.interface'; import { IInvoiceService } from './invoice-service.interface'; +import { IManifestService } from './manifest-service.interface'; import { IPersonService } from './person-service.interface'; import { IProductService } from './product-service.interface'; import { IStampService } from './stamp-service.interface'; @@ -62,4 +63,9 @@ export interface IFiscalapiClient { * Servicio de timbres fiscales */ stamps: IStampService; + + /** + * Servicio de manifiestos + */ + manifests: IManifestService; } \ No newline at end of file diff --git a/src/abstractions/manifest-service.interface.ts b/src/abstractions/manifest-service.interface.ts new file mode 100644 index 0000000..afc5879 --- /dev/null +++ b/src/abstractions/manifest-service.interface.ts @@ -0,0 +1,14 @@ +import { ApiResponse } from '../common/api-response'; +import { SignManifestRequest, SignManifestResponse } from '../models/manifest'; + +/** + * Servicio de manifiestos + */ +export interface IManifestService { + /** + * Firma un manifiesto. + * @param {SignManifestRequest} request - Solicitud con certificado, llave y contraseña + * @returns {Promise>} Respuesta con el archivo firmado + */ + sign(request: SignManifestRequest): Promise>; +} diff --git a/src/index.ts b/src/index.ts index 7da24e2..cb3cb56 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,7 @@ export type { IFiscalapiService, OperationOptions, RequestOptions } from './abst export type { IApiKeyService } from './abstractions/api-key-service.interface'; export type { ICatalogService } from './abstractions/catalog-service.interface'; export type { IInvoiceService } from './abstractions/invoice-service.interface'; +export type { IManifestService } from './abstractions/manifest-service.interface'; export type { IPersonService } from './abstractions/person-service.interface'; export type { IProductService } from './abstractions/product-service.interface'; export type { ITaxFileService } from './abstractions/tax-file-service.interface'; @@ -90,8 +91,24 @@ export type { LadingRailTransport, LadingTransportPart, LadingFigure, + // Comercio Exterior complement + ComercioExteriorComplement, + ComercioExteriorEmisor, + ComercioExteriorEmisorDomicilio, + ComercioExteriorReceptor, + ComercioExteriorReceptorDomicilio, + ComercioExteriorPropietario, + ComercioExteriorDestinatario, + ComercioExteriorDestinatarioDomicilio, + ComercioExteriorMercancia, + ComercioExteriorMercanciaDescripcionEspecifica, } from './models/invoice'; +export type { + SignManifestRequest, + SignManifestResponse +} from './models/manifest'; + export type { DownloadRule, DownloadRequest, diff --git a/src/models/invoice.ts b/src/models/invoice.ts index 5b06d8b..933f877 100644 --- a/src/models/invoice.ts +++ b/src/models/invoice.ts @@ -105,6 +105,9 @@ export interface Complement { /** Complemento de carta porte */ cartaPorte?: LadingComplement; + + /** Complemento de Comercio Exterior */ + comercioExterior?: ComercioExteriorComplement; } // ============================================================================ @@ -1156,9 +1159,252 @@ export interface LadingComplement { tiposFigura?: LadingFigure[]; } +// ============================================================================ +// Comercio Exterior Complement +// ============================================================================ + +/** + * Complemento de Comercio Exterior + */ +export interface ComercioExteriorComplement { + /** Motivo del traslado. Catálogo SAT c_MotivoTraslado */ + motivoTrasladoId?: string; + + /** Clave de pedimento. Catálogo SAT c_ClaveDePedimento */ + claveDePedimentoId: string; + + /** Certificado de origen */ + certificadoOrigen: number; + + /** Número de certificado de origen */ + numCertificadoOrigen?: string; + + /** Número del exportador confiable */ + numeroExportadorConfiable?: string; + + /** Clave de Incoterm. Catálogo SAT c_INCOTERM */ + incotermId?: string; + + /** Observaciones */ + observaciones?: string; + + /** Tipo de cambio USD. Usar string para preservar escala/precisión decimal en la serialización JSON (e.g. "17.3477") */ + tipoCambioUSD: number | string; + + /** Datos del emisor para Comercio Exterior */ + emisor?: ComercioExteriorEmisor; + + /** Datos del receptor para Comercio Exterior */ + receptor?: ComercioExteriorReceptor; + + /** Propietarios de la mercancía */ + propietarios?: ComercioExteriorPropietario[]; + + /** Destinatarios de la mercancía */ + destinatarios?: ComercioExteriorDestinatario[]; + + /** Mercancías */ + mercancias: ComercioExteriorMercancia[]; +} + +/** + * Emisor del complemento de Comercio Exterior + */ +export interface ComercioExteriorEmisor { + /** CURP del emisor */ + curp?: string; + + /** Domicilio del emisor */ + domicilio: ComercioExteriorEmisorDomicilio; +} + +/** + * Domicilio del emisor del complemento de Comercio Exterior + */ +export interface ComercioExteriorEmisorDomicilio { + /** Calle */ + calle: string; + + /** Número exterior */ + numeroExterior?: string; + + /** Número interior */ + numeroInterior?: string; + + /** Clave de colonia. Catálogo SAT c_Colonia */ + coloniaId?: string; + + /** Clave de localidad. Catálogo SAT c_Localidad */ + localidadId?: string; + + /** Referencia del domicilio */ + referencia?: string; + + /** Clave de municipio. Catálogo SAT c_Municipio */ + municipioId?: string; + + /** Clave del estado. Catálogo SAT c_Estado */ + estadoId: string; + + /** Clave del país. Catálogo SAT c_Pais */ + paisId: string; + + /** Clave del código postal. Catálogo SAT c_CodigoPostal */ + codigoPostalId: string; +} + +/** + * Receptor del complemento de Comercio Exterior + */ +export interface ComercioExteriorReceptor { + /** Número de registro de identificación tributaria */ + numRegIdTrib?: string; + + /** Domicilio del receptor */ + domicilio?: ComercioExteriorReceptorDomicilio; +} + +/** + * Domicilio del receptor del complemento de Comercio Exterior + */ +export interface ComercioExteriorReceptorDomicilio { + /** Calle */ + calle: string; + + /** Número exterior */ + numeroExterior?: string; + + /** Número interior */ + numeroInterior?: string; + + /** Colonia */ + colonia?: string; + + /** Localidad */ + localidad?: string; + + /** Referencia del domicilio */ + referencia?: string; + + /** Municipio */ + municipio?: string; + + /** Estado */ + estado: string; + + /** Clave del país. Catálogo SAT c_Pais */ + paisId: string; + + /** Código postal */ + codigoPostal: string; +} + +/** + * Propietario de la mercancía en Comercio Exterior + */ +export interface ComercioExteriorPropietario { + /** Número de registro de identificación tributaria */ + numRegIdTrib: string; + + /** Clave de residencia fiscal. Catálogo SAT c_Pais */ + residenciaFiscalId: string; +} + +/** + * Destinatario de la mercancía en Comercio Exterior + */ +export interface ComercioExteriorDestinatario { + /** Número de registro de identificación tributaria */ + numRegIdTrib?: string; + + /** Nombre del destinatario */ + nombre?: string; + + /** Domicilios del destinatario */ + domicilios: ComercioExteriorDestinatarioDomicilio[]; +} + +/** + * Domicilio del destinatario del complemento de Comercio Exterior + */ +export interface ComercioExteriorDestinatarioDomicilio { + /** Calle */ + calle: string; + + /** Número exterior */ + numeroExterior?: string; + + /** Número interior */ + numeroInterior?: string; + + /** Colonia */ + colonia?: string; + + /** Localidad */ + localidad?: string; + + /** Referencia del domicilio */ + referencia?: string; + + /** Municipio */ + municipio?: string; + + /** Estado */ + estado: string; + + /** Clave del país. Catálogo SAT c_Pais */ + paisId: string; + + /** Código postal */ + codigoPostal: string; +} + +/** + * Mercancía del complemento de Comercio Exterior + */ +export interface ComercioExteriorMercancia { + /** Número de identificación de la mercancía */ + noIdentificacion: string; + + /** Clave de fracción arancelaria. Catálogo SAT c_FraccionArancelaria */ + fraccionArancelariaId?: string; + + /** Cantidad de la mercancía conforme a la unidad aduana. Usar string para preservar escala decimal (e.g. "1.000") */ + cantidadAduana?: number | string; + + /** Clave de unidad aduana. Catálogo SAT c_UnidadAduana */ + unidadAduanaId?: string; + + /** Valor unitario en aduana. Usar string para preservar escala decimal (e.g. "120.00") */ + valorUnitarioAduana?: number | string; + + /** Valor en dólares. Usar string para preservar escala decimal (e.g. "120.00") */ + valorDolares: number | string; + + /** Descripciones específicas de la mercancía */ + descripcionesEspecificas?: ComercioExteriorMercanciaDescripcionEspecifica[]; +} + +/** + * Descripción específica de una mercancía de Comercio Exterior + */ +export interface ComercioExteriorMercanciaDescripcionEspecifica { + /** Marca */ + marca: string; + + /** Modelo */ + modelo?: string; + + /** Sub-modelo */ + subModelo?: string; + + /** Número de serie */ + numeroSerie?: string; +} + /** * Modelo factura - * Contiene toda la información de una factura, como datos del emisor, receptor, + * Contiene toda la información de una factura, como datos del emisor, receptor, * productos/servicios, importes, método de pago, el tipo de factura, entre otros. */ export interface Invoice extends BaseDto { @@ -1207,6 +1453,9 @@ export interface Invoice extends BaseDto { /** Código de método para la factura de pago del catálogo del SAT c_MetodoPago */ paymentMethodCode?: string; + /** Condiciones de pago aplicables a la factura */ + paymentConditions?: string; + /** Tipo de cambio FIX conforme a la moneda registrada en la factura. Default: 1 */ exchangeRate?: number; @@ -1300,6 +1549,12 @@ export interface InvoiceRecipient { /** Correo electrónico del receptor. Para enviar la factura desde el dasborard */ email?: string; + /** Clave del país de residencia fiscal del receptor extranjero. Catálogo SAT c_Pais */ + countryId?: string; + + /** Número de registro de identificación tributaria del receptor extranjero */ + foreignTin?: string; + /** Datos del empleado para facturas de nómina (inline, modo ByValues) */ employeeData?: InvoiceRecipientEmployeeData; } diff --git a/src/models/manifest.ts b/src/models/manifest.ts new file mode 100644 index 0000000..3640bc7 --- /dev/null +++ b/src/models/manifest.ts @@ -0,0 +1,32 @@ +// src/models/manifest.ts +import { BaseDto } from '../common/base-dto'; + +/** + * Solicitud para firmar un manifiesto. + * Contiene el certificado, llave privada y contraseña en base64. + */ +export interface SignManifestRequest extends BaseDto { + /** Certificado (.cer) en base64 */ + base64Cer?: string; + + /** Llave privada (.key) en base64 */ + base64Key?: string; + + /** Contraseña de la llave privada */ + password?: string; +} + +/** + * Respuesta de la firma de un manifiesto. + * Contiene el archivo firmado en base64. + */ +export interface SignManifestResponse { + /** Archivo firmado en base64 */ + base64File: string; + + /** Nombre del archivo */ + fileName: string; + + /** Extensión del archivo */ + fileExtension: string; +} diff --git a/src/models/person.ts b/src/models/person.ts index 671a09a..59992d2 100644 --- a/src/models/person.ts +++ b/src/models/person.ts @@ -58,4 +58,10 @@ export interface Person extends BaseDto { /** ID del tenant al que pertenece el emisor. Atributo de sólo lectura */ tenantId?: string; + + /** Clave del país de residencia fiscal del receptor extranjero. Catálogo SAT c_Pais */ + countryId?: string; + + /** Número de registro de identificación tributaria del receptor extranjero */ + foreignTin?: string; } \ No newline at end of file diff --git a/src/services/fiscalapi-client.ts b/src/services/fiscalapi-client.ts index e236178..9b29733 100644 --- a/src/services/fiscalapi-client.ts +++ b/src/services/fiscalapi-client.ts @@ -1,5 +1,6 @@ import { IFiscalapiClient } from '../abstractions/fiscalapi-client.interface'; import { IInvoiceService } from '../abstractions/invoice-service.interface'; +import { IManifestService } from '../abstractions/manifest-service.interface'; import { IProductService } from '../abstractions/product-service.interface'; import { IPersonService } from '../abstractions/person-service.interface'; import { IApiKeyService } from '../abstractions/api-key-service.interface'; @@ -17,6 +18,7 @@ import { DownloadCatalogService } from './download-catalog-service'; import { DownloadRuleService } from './download-rule-service'; import { DownloadRequestService } from './download-request-service'; import { InvoiceService } from './invoice-service'; +import { ManifestService } from './manifest-service'; import { PersonService } from './person-service'; import { ProductService } from './product-service'; import { StampService } from './stamp-service'; @@ -76,6 +78,11 @@ export class FiscalapiClient implements IFiscalapiClient { */ readonly stamps: IStampService; + /** + * Servicio de manifiestos + */ + readonly manifests: IManifestService; + /** * Crea una nueva instancia del cliente de FiscalAPI * @param {FiscalapiSettings} settings - Configuración @@ -97,6 +104,7 @@ export class FiscalapiClient implements IFiscalapiClient { this.downloadRules = new DownloadRuleService(httpClient, apiVersion); this.downloadRequests = new DownloadRequestService(httpClient, apiVersion); this.stamps = new StampService(httpClient, apiVersion); + this.manifests = new ManifestService(httpClient, apiVersion); } /** diff --git a/src/services/manifest-service.ts b/src/services/manifest-service.ts new file mode 100644 index 0000000..222d41a --- /dev/null +++ b/src/services/manifest-service.ts @@ -0,0 +1,38 @@ +import { IFiscalapiHttpClient } from '../http/fiscalapi-http-client.interface'; +import { ApiResponse } from '../common/api-response'; +import { BaseFiscalapiService } from './base-fiscalapi-service'; +import { IManifestService } from '../abstractions/manifest-service.interface'; +import { SignManifestRequest, SignManifestResponse } from '../models/manifest'; + +/** + * Implementación del servicio de manifiestos + */ +export class ManifestService + extends BaseFiscalapiService + implements IManifestService { + + /** + * Crea una nueva instancia del servicio de manifiestos + * @param {IFiscalapiHttpClient} httpClient - Cliente HTTP + * @param {string} apiVersion - Versión de la API + */ + constructor(httpClient: IFiscalapiHttpClient, apiVersion: string) { + super(httpClient, 'manifests', apiVersion); + } + + /** + * Firma un manifiesto + * @param {SignManifestRequest} request - Solicitud con certificado, llave y contraseña + * @returns {Promise>} Respuesta con el archivo firmado + */ + async sign(request: SignManifestRequest): Promise> { + if (!request) { + throw new Error('request cannot be null'); + } + + return await this.executeRequest({ + data: request, + method: 'POST', + }); + } +}