Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
250 changes: 250 additions & 0 deletions ai-invoice-extractor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@

- 🔍 Extract invoice/receipt data
- 🧠 Choose your AI models (OpenAI, Mistral, Anthropic, Google Gemini, and Ollama)
- 🇮🇹 **Full FatturaPA support** for Italian e-invoicing (TD01, TD17-TD19)
- 🔧 Set AI keys with CLI and environment variables
- ⭐ Pretty print the output
- 🔄 Pipe output with other CLI
- 📄 Export to XML/JSON formats
- 🏛️ Public Administration support (CIG/CUP codes)

## Usage

Expand Down Expand Up @@ -117,6 +120,23 @@ export EXTRACTOR_API_KEY=sk-your-openai-key
npx ai-invoice-extractor invoice.pdf
```

#### FatturaPA (Italian E-Invoicing)
```sh
# Extract FatturaPA data with full Italian e-invoicing support
npx ai-invoice-extractor -k sk-key -p fattura.pdf

# Export to FatturaPA XML format
npx ai-invoice-extractor -k sk-key fattura.pdf | node -e "
const { FatturapaXmlExporter } = require('./dist/exporters');
const exporter = new FatturapaXmlExporter();
const data = JSON.parse(require('fs').readFileSync(0, 'utf8'));
console.log(exporter.export(data));
"

# Extract cross-border invoice (TD18)
npx ai-invoice-extractor -k sk-key crossborder-invoice.pdf
```

#### Different AI Vendors
```sh
# Mistral AI
Expand Down Expand Up @@ -171,6 +191,236 @@ The CLI provides helpful error messages for common issues:
- **Documents:** PDF
- **File size:** Up to 20MB (varies by AI provider)

## FatturaPA (Italian E-Invoicing) Support

The AI Invoice Extractor provides comprehensive support for FatturaPA, the Italian electronic invoicing standard mandated by the Agenzia delle Entrate (Italian Revenue Agency).

### Supported Document Types

| Code | Description | Support |
|------|-------------|---------|
| **TD01** | Domestic invoice | ✅ Full support |
| **TD17** | Domestic reverse charge integration | ✅ Full support |
| **TD18** | Intra-EU purchase integration | ✅ Full support |
| **TD19** | Extra-EU purchase integration | ✅ Full support |
| **TD20-27** | Specialized invoice types | ✅ Basic support |

### Key Features

- **🏢 Complete Party Data:** Italian VAT IDs, Codice Fiscale, REA registration, PEC addresses
- **🌍 Cross-Border Support:** Foreign VAT IDs, tax representatives, currency conversion
- **💰 Tax Compliance:** All Italian VAT rates, nature codes (N1-N7), withholding taxes
- **🏛️ Public Administration:** CIG/CUP codes, office codes, administrative references
- **📋 Line Items:** Product codes, service periods, discounts, custom information
- **💳 Payment Terms:** All Italian payment methods (MP01-MP22), IBAN/BIC, installments
- **📎 References:** Order numbers, contracts, transport documents
- **🔧 Export Formats:** SDI-compliant XML, structured JSON, validation format

### Extracted Fields

The extractor captures **300+ fields** including:

#### Document Header
- Document type code (TD01, TD17-TD19, etc.)
- Invoice number, issue date, due date
- Currency code and exchange rates (for cross-border)
- Transmission format and country codes

#### Party Information (Supplier & Customer)
- Legal name and form
- Italian VAT ID (`IT` + 11 digits) and Tax ID (Codice Fiscale)
- Foreign VAT IDs for cross-border transactions
- Complete addresses with Italian province codes
- Contact information (phone, email, PEC)
- REA registration details (office, number, share capital)
- Tax representative information (for foreign suppliers)

#### Tax Details
- Multiple VAT rates and amounts
- Nature codes for exemptions (N1-N7 with descriptions)
- Withholding taxes (RT01, RT02 types)
- Administrative references for PA invoices

#### Line Items
- Descriptions, quantities, unit prices, totals
- Discounts and markups (percentage and amount)
- VAT rates per line item
- Product codes (EAN, internal, etc.)
- Service periods (start/end dates)
- Cross-border customs information

#### Payment Information
- Payment conditions (TP01-TP03)
- Payment methods (MP01-MP22)
- Bank details (IBAN, BIC, bank name)
- Installment schedules
- Early payment discounts and late penalties

#### References & Additional Data
- CIG (tender codes) and CUP (project codes) for PA
- Order numbers and contract references
- Transport and delivery information
- Digital signature details
- Attachments and notes

### Usage Examples

#### Basic FatturaPA Extraction
```sh
# Extract Italian domestic invoice
npx ai-invoice-extractor -k sk-key fattura-domestica.pdf

# Extract cross-border invoice (German supplier to Italian customer)
npx ai-invoice-extractor -k sk-key fattura-crossborder.pdf

# Extract with pretty formatting
npx ai-invoice-extractor -k sk-key -p fattura.pdf
```

#### Programmatic Usage
```javascript
import { Extractor } from 'ai-invoice-extractor';
import { FatturapaXmlExporter, FatturapaJsonExporter } from 'ai-invoice-extractor/exporters';

// Extract invoice data
const extractor = Extractor.create({
vendor: 'openai',
model: 'gpt-4o',
apiKey: 'sk-your-key'
});

const invoiceData = await extractor.analyseFile({
path: 'fattura.pdf',
prompt: 'EXTRACT_INVOICE_FATTURAPA',
output: fatturapaInvoiceSchema
});

// Export to XML (SDI-compliant)
const xmlExporter = new FatturapaXmlExporter({
formatOutput: true,
validateRequired: true
});
const xml = xmlExporter.export(invoiceData);

// Export to JSON (structured)
const jsonExporter = new FatturapaJsonExporter({
includeMetadata: true,
cleanNullValues: true
});
const json = jsonExporter.export(invoiceData);

// Export for validation
const validationJson = jsonExporter.exportForValidation(invoiceData);
```

#### XML Output Sample
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ns2:FatturaElettronica versione="FPR12" xmlns:ns2="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2">
<FatturaElettronicaHeader>
<DatiTrasmissione>
<IdTrasmittente>
<IdPaese>IT</IdPaese>
<IdCodice>12345678901</IdCodice>
</IdTrasmittente>
<FormatoTrasmissione>FPR12</FormatoTrasmissione>
</DatiTrasmissione>
<CedentePrestatore>
<DatiAnagrafici>
<IdFiscaleIVA>
<IdPaese>IT</IdPaese>
<IdCodice>IT12345678901</IdCodice>
</IdFiscaleIVA>
<Anagrafica>
<Denominazione>Tech Solutions S.r.l.</Denominazione>
</Anagrafica>
</DatiAnagrafici>
</CedentePrestatore>
</FatturaElettronicaHeader>
<FatturaElettronicaBody>
<DatiGenerali>
<DatiGeneraliDocumento>
<TipoDocumento>TD01</TipoDocumento>
<Divisa>EUR</Divisa>
<Data>2024-03-15</Data>
<Numero>INV-2024-001</Numero>
</DatiGeneraliDocumento>
</DatiGenerali>
<!-- ... more XML content ... -->
</FatturaElettronicaBody>
</ns2:FatturaElettronica>
```

#### JSON Output Sample
```json
{
"header": {
"transmission": {
"sender_country": "IT",
"sender_code": "IT12345678901",
"format": "FPR12"
},
"supplier": {
"identification": {
"vat_id": "IT12345678901",
"tax_id": "12345678901"
},
"legal_info": {
"name": "Tech Solutions S.r.l."
},
"address": {
"street": "Via Roma",
"city": "Milano",
"postal_code": "20121",
"province": "MI",
"country": "IT"
}
}
},
"body": {
"general_data": {
"document_type": "TD01",
"currency": { "code": "EUR" },
"date": "2024-03-15",
"number": "INV-2024-001",
"totals": {
"taxable_amount": 1000.00,
"vat_amount": 220.00,
"total_amount": 1220.00
}
},
"line_items": [
{
"line_number": 1,
"description": "Servizi di consulenza IT",
"quantity": 1,
"unit_price": 1000.00,
"total_price": 1000.00,
"vat": {
"rate": 22.00,
"amount": 220.00
}
}
]
}
}
```

### Validation & Compliance

The XML exporter generates output that is:
- ✅ **SDI Compliant:** Validates against Italian Sistema di Interscambio
- ✅ **Schema Valid:** Follows FatturaPA XSD 1.2.1 specification
- ✅ **Tax Authority Ready:** Can be submitted directly to Agenzia delle Entrate
- ✅ **Cross-Border Ready:** Handles TD17-TD19 scenarios correctly

### Examples & Testing

The repository includes comprehensive examples:
- `examples/fatturapa/domestic-invoice-sample.json` - Italian domestic invoice (TD01)
- `examples/fatturapa/crossborder-invoice-sample.json` - Cross-border invoice (TD18)
- Complete test suite with 15+ scenarios covering all document types

## Contributing

We use [Bun](https://bun.sh/) instead of npm:
Expand Down
26 changes: 26 additions & 0 deletions ai-invoice-extractor/examples/fatturapa/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# FatturaPA Examples

This directory contains sample invoices in various formats demonstrating FatturaPA support:

## Domestic Invoices (TD01)
- `domestic-invoice-sample.json` - Sample Italian domestic invoice
- `domestic-invoice-golden.xml` - Expected XML output
- `domestic-invoice-golden.json` - Expected JSON output

## Cross-Border Invoices (TD17-TD19)
- `crossborder-invoice-sample.json` - Sample cross-border invoice
- `crossborder-invoice-golden.xml` - Expected XML output
- `crossborder-invoice-golden.json` - Expected JSON output

## Public Administration
- `pa-invoice-sample.json` - Sample PA invoice with CIG/CUP codes
- `pa-invoice-golden.xml` - Expected XML output
- `pa-invoice-golden.json` - Expected JSON output

## Usage

These examples can be used for:
- Testing the FatturaPA extraction and export functionality
- Validating output against Italian SDI requirements
- Understanding the complete FatturaPA data structure
- Development and integration testing
Loading
Loading