Skip to content

Commit bfaab13

Browse files
authored
Merge pull request #3 from FiscalAPI/agrega-soporte-facturas-cfdi-nomina
Agrega soporte facturas cfdi nomina
2 parents 59b89ee + a8ee735 commit bfaab13

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+4300
-303
lines changed

.claude/settings.local.json

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"permissions": {
3+
"allow": [
4+
"Bash(npm run build:*)",
5+
"Bash(npm test)",
6+
"Bash(npx ts-node:*)",
7+
"Bash(findstr:*)"
8+
],
9+
"defaultMode": "bypassPermissions"
10+
}
11+
}

.github/workflows/main.yml

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,19 @@ jobs:
4646
echo "ESM build missing"
4747
exit 1
4848
fi
49-
if [ ! -d "dist/types" ]; then
49+
if [ ! -f "dist/cjs/index.d.ts" ]; then
5050
echo "TypeScript definitions missing"
5151
exit 1
5252
fi
53+
if [ ! -f "dist/cjs/package.json" ]; then
54+
echo "CJS package.json missing"
55+
exit 1
56+
fi
57+
if [ ! -f "dist/esm/package.json" ]; then
58+
echo "ESM package.json missing"
59+
exit 1
60+
fi
61+
echo "Build artifacts verified successfully"
5362
5463
- name: Publish to NPM
5564
run: npm publish --access public

CLAUDE.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# CLAUDE.md
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
## Project Overview
6+
7+
FiscalAPI SDK for Node.js - Official TypeScript SDK for Mexican electronic invoicing (CFDI 4.0) and fiscal services. Wraps the FiscalAPI REST API for invoice creation, payment complements, bulk XML downloads, and SAT catalog queries.
8+
9+
## Build Commands
10+
11+
```bash
12+
npm run build # Full build: clean + esm + cjs + types
13+
npm run build:esm # TypeScript to ES Modules (dist/esm)
14+
npm run build:cjs # TypeScript to CommonJS (dist/cjs)
15+
npm run build:types # TypeScript declaration files (dist/types)
16+
npm run clean # Remove dist directory
17+
npm test # Run Jest tests
18+
npm run lint # ESLint on src/**/*.ts
19+
npm run main # Run examples/main.ts with ts-node
20+
```
21+
22+
## Architecture
23+
24+
**Facade Pattern**: `FiscalapiClient` is the main entry point exposing all services:
25+
- `invoices` - CFDI invoice creation, cancellation, PDF generation
26+
- `products` - Product/service catalog management
27+
- `persons` - Issuer/recipient (emisor/receptor) management
28+
- `taxFiles` - CSD certificate upload
29+
- `catalogs` - SAT catalog queries
30+
- `downloadCatalogs`, `downloadRules`, `downloadRequests` - Bulk XML download
31+
32+
**Directory Structure**:
33+
- `src/abstractions/` - Service interfaces (I*Service)
34+
- `src/services/` - Service implementations extending `BaseFiscalapiService`
35+
- `src/models/` - Data models (Invoice, Person, Product, etc.)
36+
- `src/common/` - Shared DTOs (ApiResponse, PagedList, FiscalapiSettings)
37+
- `src/utils/` - Date formatting (Luxon), Base64 encoding, validation helpers
38+
39+
**Key Patterns**:
40+
- All services implement interfaces from `abstractions/`
41+
- HTTP client injected via factory pattern
42+
- Dual-package output: ESM + CommonJS + TypeScript declarations
43+
- Date handling uses Luxon with `America/Mexico_City` timezone
44+
- SAT date format: `yyyy-MM-ddTHH:mm:ss`
45+
46+
## Configuration
47+
48+
```typescript
49+
const settings: FiscalapiSettings = {
50+
apiUrl: "https://test.fiscalapi.com", // or https://live.fiscalapi.com
51+
apiKey: "<api_key>",
52+
tenant: "<tenant>",
53+
apiVersion?: "v4", // default
54+
timeZone?: "America/Mexico_City", // default
55+
debug?: false
56+
};
57+
const client = FiscalapiClient.create(settings);
58+
```
59+
60+
## Two Operation Modes
61+
62+
1. **By References**: Send only IDs of pre-configured entities in FiscalAPI dashboard
63+
2. **By Values**: Send complete data in each request (no prior setup needed)
64+
65+
## TypeScript Configuration
66+
67+
Strict mode enabled with all checks: `noImplicitAny`, `strictNullChecks`, `noImplicitReturns`, `noUnusedParameters`. Target ES2018.

README.md

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@
1010
- **Soporte completo para CFDI 4.0** con todas las especificaciones oficiales
1111
- **Timbrado de facturas de ingreso** con validación automática
1212
- **Timbrado de notas de crédito** (facturas de egreso)
13-
- **Timbrado de complementos de pago** en MXN, USD y EUR.
13+
- **Timbrado de complementos de pago** en MXN, USD y EUR
14+
- **Timbrado de facturas de nómina** (CFDI Nómina 1.2)
1415
- **Consulta del estatus de facturas** en el SAT en tiempo real
15-
- **Cancelación de facturas**
16+
- **Cancelación de facturas**
1617
- **Generación de archivos PDF** de las facturas con formato profesional
1718
- **Personalización de logos y colores** en los PDF generados
1819
- **Envío de facturas por correo electrónico** automatizado
1920
- **Descarga de archivos XML** con estructura completa
20-
- **Almacenamiento y recuperación** de facturas por 5 años.
21+
- **Almacenamiento y recuperación** de facturas por 5 años
2122
- Dos [modos de operación](https://docs.fiscalapi.com/modes-of-operation): **Por valores** o **Por referencias**
2223

2324
## 📥 Descarga Masiva
@@ -32,11 +33,16 @@
3233
- **Administración de personas** (emisores, receptores, clientes, usuarios, etc.)
3334
- **Gestión de certificados CSD y FIEL** (subir archivos .cer y .key a FiscalAPI)
3435
- **Configuración de datos fiscales** (RFC, domicilio fiscal, régimen fiscal)
36+
- **Datos de empleado** (agrega/actualiza/elimina datos de empleado a una persona. CFDI Nómina)
37+
- **Datos de empleador** (agrega/actualiza/elimina datos de empleador a una persona. CFDI Nómina)
3538

3639
## 🛍️ Gestión de Productos/Servicios
3740
- **Gestión de productos y servicios** con catálogo personalizable
3841
- **Administración de impuestos aplicables** (IVA, ISR, IEPS)
3942

43+
## 🎖️ Gestión de Timbres
44+
- **Gestión de folios fiscales** Compra timbres a fiscalapi y transfiere/retira a las personas de tu organizacion segun tus reglas de negocio.
45+
4046
## 📚 Consulta de Catálogos SAT
4147
- **Consulta en catálogos oficiales del SAT** actualizados
4248
- **Consulta en catálogos oficiales de Descarga masiva del SAT** actualizados
@@ -381,16 +387,24 @@ try {
381387
}
382388
```
383389

390+
## 📂 Más Ejemplos
391+
392+
- [Gestión de Timbres](examples/ejemplo-timbres.ts)
393+
- [Datos Empleador/Empleado](examples/ejemplo-datos-empleado-empleador.ts)
394+
- [Facturas de Nómina (Por Valores)](examples/ejemplos-factura-nomina-valores.ts)
395+
- [Facturas de Nómina (Por Referencias)](examples/ejemplos-factura-nomina-referencias.ts)
396+
- [Facturas de Impuestos Locales (Por Referencias)](examples/ejemplos-factura-impuestos-locales-referencias.ts)
397+
- [Facturas de Impuestos Locales (Por Valores)](examples/ejemplos-factura-impuestos-locales-valores.ts)
398+
399+
384400
---
385401

386402
## 📋 Operaciones Principales
387403

388-
- **Facturas (CFDI)**
389-
Crear facturas de ingreso, notas de crédito, complementos de pago, cancelaciones, generación de PDF/XML.
390-
- **Personas (Clientes/Emisores)**
391-
Alta y administración de personas, gestión de certificados (CSD).
392-
- **Productos y Servicios**
393-
Administración de catálogos de productos, búsqueda en catálogos SAT.
404+
- **Facturas (CFDI)** - Ingreso, egreso, pago, nómina, cancelaciones, PDF/XML
405+
- **Personas** - Emisores, receptores, certificados CSD
406+
- **Productos** - Catálogo de productos/servicios
407+
- **Timbres** - Transferencias y retiros
394408

395409

396410
## 🤝 Contribuir
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import {
2+
FiscalapiClient,
3+
FiscalapiSettings,
4+
CreateEmployerRequest,
5+
CreateEmployeeRequest
6+
} from '../src';
7+
8+
async function main(): Promise<void> {
9+
10+
const settings: FiscalapiSettings = {
11+
apiUrl: 'https://test.fisalapi.com',
12+
apiKey: '<API_KEY>',
13+
tenant: '<TENANT_ID>',
14+
debug: true
15+
};
16+
17+
const client = FiscalapiClient.create(settings);
18+
19+
const escuelaKemperUrgateId = '<id-empleador>';
20+
const karlaFuenteNolascoId = '<id-empleado>';
21+
22+
// Crear datos de empleador
23+
const employerRequest: CreateEmployerRequest = {
24+
personId: escuelaKemperUrgateId,
25+
employerRegistration: 'B5510768108',
26+
};
27+
const employerResult = await client.persons.employer.create(employerRequest);
28+
console.log('Empleador:', JSON.stringify(employerResult, null, 2));
29+
30+
// Crear datos de empleado
31+
const employeeRequest: CreateEmployeeRequest = {
32+
employerPersonId: escuelaKemperUrgateId,
33+
employeePersonId: karlaFuenteNolascoId,
34+
employeeNumber: '123456789',
35+
socialSecurityNumber: '04078873454',
36+
laborRelationStartDate: '2024-08-18',
37+
satContractTypeId: '01',
38+
satTaxRegimeTypeId: '02',
39+
satJobRiskId: '1',
40+
satPaymentPeriodicityId: '05',
41+
satBankId: '012',
42+
satPayrollStateId: 'JAL',
43+
department: 'GenAI',
44+
position: 'Sr Software Engineer',
45+
seniority: 'P54W',
46+
baseSalaryForContributions: 2828.50,
47+
integratedDailySalary: 0.00,
48+
};
49+
const employeeResult = await client.persons.employee.create(employeeRequest);
50+
console.log('Empleado:', JSON.stringify(employeeResult, null, 2));
51+
52+
// Consultar datos
53+
const employer = await client.persons.employer.getById(escuelaKemperUrgateId);
54+
console.log('Consulta empleador:', JSON.stringify(employer, null, 2));
55+
56+
const employee = await client.persons.employee.getById(karlaFuenteNolascoId);
57+
console.log('Consulta empleado:', JSON.stringify(employee, null, 2));
58+
}
59+
60+
main().catch(console.error);

examples/ejemplo-timbres.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { FiscalapiClient, FiscalapiSettings } from '../src/index';
2+
3+
async function main(): Promise<void> {
4+
5+
const settings: FiscalapiSettings = {
6+
apiUrl: 'https://test.fisalapi.com',
7+
apiKey: '<API_KEY>',
8+
tenant: '<TENANT_ID>',
9+
debug: true
10+
};
11+
12+
const client = FiscalapiClient.create(settings);
13+
14+
// 1. Listar transacciones de timbres
15+
const list = await client.stamps.getList(1, 10);
16+
console.log('Lista de transacciones:', list);
17+
18+
// 2. Obtener transacción por ID
19+
const transaction = await client.stamps.getById('77678d6d-94b1-4635-aa91-15cdd7423aab');
20+
console.log('Transacción por ID:', transaction);
21+
22+
// 3. Transferir timbres
23+
const transfer = await client.stamps.transferStamps({
24+
fromPersonId: '2e7b988f-3a2a-4f67-86e9-3f931dd48581',
25+
toPersonId: '5fd9f48c-a6a2-474f-944b-88a01751d432',
26+
amount: 1,
27+
comments: 'Transferencia de prueba'
28+
});
29+
console.log('Transferencia:', transfer);
30+
31+
// 4. Retirar timbres
32+
const withdraw = await client.stamps.withdrawStamps({
33+
fromPersonId: '5fd9f48c-a6a2-474f-944b-88a01751d432',
34+
toPersonId: '2e7b988f-3a2a-4f67-86e9-3f931dd48581',
35+
amount: 1,
36+
comments: 'Retiro de prueba'
37+
});
38+
console.log('Retiro:', withdraw);
39+
}
40+
41+
main();

0 commit comments

Comments
 (0)