npm package: @swsapiennpm/platform-js
Description: A TypeScript library for generating PDFs from XML invoices
Author: SW sapien
Latest version: 0.0.4

# Platform PDF

A TypeScript library for transforming CFDI (Mexican electronic invoice) XML documents and generating PDFs. This library provides a clean, type-safe API for parsing CFDI XML data, transforming it into structured data, and generating professional PDF documents.

## Features

- 🚀 **TypeScript First**: Built with TypeScript for excellent developer experience
- 📄 **CFDI XML to PDF**: Parse CFDI XML documents and generate PDFs
- 🔧 **Multiple CFDI Versions**: Support for CFDI 3.3 and 4.0
- 📋 **Specialized Documents**: Support for Nómina (payroll) and Pagos (payments) documents
- ✅ **Data Validation**: Built-in validation for CFDI data
- 🧪 **Comprehensive Testing**: Full test coverage with Jest
- 📦 **NPM Ready**: Ready to publish as an NPM package
- 🔤 **Embedded Fonts**: Roboto fonts are embedded and work out-of-the-box

## Project Structure

```
platform-js/
├── src/
│   ├── assets/
│   │   └── fonts/                    # Embedded Roboto fonts
│   ├── services/
│   │   ├── cfdiTransform/
│   │   │   ├── cfdi/                 # CFDI data interfaces
│   │   │   ├── cfdi33/               # CFDI 3.3 transformation handlers
│   │   │   ├── cfdi40/               # CFDI 4.0 transformation handlers
│   │   │   ├── nomina12/             # Nómina 1.2 transformation handlers
│   │   │   ├── pagos10/              # Pagos 1.0 transformation handlers
│   │   │   ├── pagos20/              # Pagos 2.0 transformation handlers
│   │   │   └── tfd11/                # TFD 1.1 transformation handlers
│   │   ├── cfdiTransformService.ts   # Main CFDI transformation service
│   │   ├── cfdiToPdfService.ts       # PDF generation service
│   │   └── cfdiToPdf/                # PDF generation implementations
│   └── index.ts                      # Main library exports
├── tests/
│   ├── resources/xmls/               # Test XML files
│   ├── cfdiTransformService.test.ts  # CFDI transformation tests
│   ├── cfdiToPdfService.test.ts      # PDF generation tests
│   └── platform.test.ts              # Main platform tests
├── package.json                      # NPM package configuration
├── tsconfig.json                     # TypeScript configuration
├── jest.config.js                    # Jest testing configuration
└── README.md                         # This file
```

## Installation

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Lint code
npm run lint

# Fix linting issues
npm run lint:fix

# Run specific test for debugging:
npm test -- --testNamePattern="should transform CFDI 4.0 XML successfully"

# Run a test suite:
npx jest -t "CFDITransformService"
```

## Embedded Fonts

This library includes embedded Roboto fonts that work out-of-the-box when the package is installed as an npm dependency. The fonts are:

- **Roboto Regular** - Normal text
- **Roboto Bold** - Bold text
- **Roboto Italic** - Italic text  
- **Roboto Medium Italic** - Bold italic text

The fonts are automatically loaded and used by the PDF generation service. No additional font installation or configuration is required.

## Usage

### Basic Usage

```typescript
import { Platform } from 'platform-pdf';

const platform = new Platform();

// Transform CFDI XML to structured data
const xmlString = `
  <cfdi:Comprobante Version="4.0" xmlns:cfdi="http://www.sat.gob.mx/cfd/4">
    <cfdi:Emisor Rfc="AAA010101AAA" Nombre="Test Emisor"/>
    <cfdi:Receptor Rfc="BBB010101BBB" Nombre="Test Receptor"/>
    <cfdi:Conceptos>
      <cfdi:Concepto Descripcion="Producto 1" Cantidad="2" ValorUnitario="50.00" Importe="100.00"/>
    </cfdi:Conceptos>
  </cfdi:Comprobante>
`;

const result = await platform.transformXmlToCfdiData(xmlString);
console.log(result.version); // "4.0"
console.log(result.cfdi40?.emisor?.nombre); // "Test Emisor"
```

### PDF Generation

```typescript
import CFDIToPdfService from 'platform-pdf/services/cfdiToPdfService';

const cfdiToPdfService = new CFDIToPdfService();

// Generate PDF from CFDI XML
const xmlString = '...'; // Your CFDI XML string
const pdfBuffer = await cfdiToPdfService.generatePdf(xmlString);

// Save PDF to file
const fs = require('fs');
fs.writeFileSync('invoice.pdf', pdfBuffer);
```

### Direct CFDI Transformation

```typescript
import { CFDITransformService } from 'platform-pdf';

const cfdiTransformService = new CFDITransformService();

// Transform with custom configuration
const customTransformService = new CFDITransformService(
  '',      // emptyChar
  true,    // safeNumerics
  '',      // escDelimiters
  true,    // concepts
  true     // cfdisRelacionados
);

const xmlString = '...'; // Your CFDI XML string
const transformData = await cfdiTransformService.transform(xmlString);

// Access transformed data
if (transformData.version === '4.0' && transformData.cfdi40) {
  console.log('CFDI 4.0 document');
  console.log('Emisor:', transformData.cfdi40.emisor?.nombre);
  console.log('Receptor:', transformData.cfdi40.receptor?.nombre);
} else if (transformData.version === '3.3' && transformData.cfdi33) {
  console.log('CFDI 3.3 document');
  console.log('Emisor:', transformData.cfdi33.emisor?.nombre);
  console.log('Receptor:', transformData.cfdi33.receptor?.nombre);
}
```

## Supported Document Types

### CFDI Documents
- **CFDI 3.3**: Standard CFDI version 3.3 documents
- **CFDI 4.0**: Standard CFDI version 4.0 documents

### Specialized Documents
- **Nómina 1.2**: Payroll documents (both CFDI 3.3 and 4.0)
- **Pagos 1.0**: Payment documents (CFDI 3.3)
- **Pagos 2.0**: Payment documents (CFDI 4.0)

### Digital Stamp (TFD)
- **TFD 1.1**: Digital stamp information

## API Reference

### Platform Class

#### `transformXmlToCfdiData(xmlString: string): Promise<TransformData>`
Transforms CFDI XML string into structured data.

### CFDITransformService Class

#### `transform(xmlString: string): Promise<TransformData>`
Transforms CFDI XML string into structured data with configurable options.

#### Constructor Options
```typescript
constructor(
  emptyChar: string = '',           // Character to use for empty values
  safeNumerics: boolean = true,     // Safe numeric parsing
  escDelimiters: string = '',       // Escape delimiters
  concepts: boolean = true,         // Include concepts
  cfdisRelacionados: boolean = true // Include related CFDIs
)
```

### CFDIToPdfService Class

#### `generatePdf(xmlString: string): Promise<Buffer>`
Generates a PDF buffer from CFDI XML string.

### Types

#### `TransformData`
```typescript
interface TransformData {
  cfdi40?: CFDIData;        // CFDI 4.0 data
  cfdi33?: CFDIData;        // CFDI 3.3 data
  nomina12?: Nomina12Data;  // Nómina 1.2 data
  pago10?: Pagos10Data;     // Pagos 1.0 data
  pago20?: Pagos20Data;     // Pagos 2.0 data
  tfd11?: TFD11Data;        // TFD 1.1 data
  version?: string;         // CFDI version
}
```

#### `CFDIData`
```typescript
interface CFDIData {
  version: string;
  serie: string;
  folio: string;
  fecha: string;
  no_certificado: string;
  subtotal: string;
  descuento: string;
  total: string;
  moneda: string;
  tipo_cambio: string;
  tipo_comprobante: string;
  metodo_pago: string;
  forma_pago: string;
  condiciones_pago: string;
  lugar_expedicion: string;
  exportacion: string;
  sello: string;
  certificado: string;
  confirmacion: string;
  emisor: CFDIEmisor;
  receptor: CFDIReceptor;
  conceptos: CFDIConcepto[];
  impuestos: CFDIImpuestos;
  cfdis_relacionados: CFDIRelacionado[];
  complementos: any;
  addendas: string;
}
```

## Development

### Current Status: Full Implementation

This library provides complete CFDI transformation and PDF generation functionality:

1. **CFDI Transformation**: Full support for CFDI 3.3 and 4.0 XML parsing
2. **PDF Generation**: Actual PDF generation using pdfmake library
3. **Type Safety**: Complete TypeScript interfaces for all CFDI components
4. **Testing**: Comprehensive test suite with real CFDI XML files
5. **Error Handling**: Robust error handling and validation

### Building for Production

```bash
# Clean and build
npm run clean
npm run build

# The compiled JavaScript will be in the dist/ folder
```

### Publishing to NPM

```bash
# Login to AWS Sapien-Devops
Set env variables AWS_SECRET_ACCESS_KEY , AWS_SESSION_TOKEN 
# Login to NPM (if not already logged in)
aws codeartifact login --tool npm --repository sw-sapien-codeartifact --domain sw-sapien-codeartifact --domain-owner 405894839087 --region us-east-1

# Publish the package
npm publish
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Run the test suite
6. Submit a pull request

## License

MIT License - see LICENSE file for details.

## Support

For issues and questions, please create an issue in the GitHub repository.