diff --git a/CHANGELOG.md b/CHANGELOG.md index 3938e83..7cf1547 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,62 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. ## [Unreleased] +## [0.9.0] - 2026-11-13 + +M9 - Fatturazione elettronica. Le fatture emesse diventano file FatturaPA controllati prima dell'invio con i codici +dello SDI e partono dal canale scelto dalle regole di instradamento (PEC, SdICoop o due intermediari); le notifiche +aggiornano da sole file e documenti, gli scarti si correggono e si rigenerano, le fatture dei fornitori arrivano in +una casella da registrare e i file di un periodo si esportano per la conservazione. + +### Added +- File FatturaPA (#74, ADR 0039): `FatturaPaWriter` scrive `FPR12`, `FPA12` e `FSM10` v1.2 con nome + `IT_.xml` e progressivo in base 36 mai riusato; il modello del documento viene da + `EInvoiceBuilder` (cedente, cessionario, ritenute, cassa, bollo, sconti, riferimenti, DDT, riepilogo IVA, + pagamenti, allegati). +- Controllo prima dell'invio (#74): `FatturaPaValidator` ripete offline i controlli dello SDI con lo stesso codice + (00305-00473) e le tolleranze delle specifiche 1.9.1, più la struttura contro uno schema incorporato; + *Controlla senza generare* sul cruscotto. +- Notifiche SDI (#75): `SdiReceiptReader` legge RC, NS, MC, NE, DT, AT, SE e MT; ogni notifica è conservata una sola + volta, abbinata al file e applicata al file e al documento nella stessa transazione; import manuale di XML, P7M e + ZIP del portale; pagina *Notifiche SDI* con filtri e download. +- Canali (#76, #77): PEC con SMTP e un client IMAP e un lettore MIME scritti in casa (primo invio a + `sdi01@pec.fatturapa.it`, poi l'indirizzo appreso dallo SDI, cartella di archivio), SdICoop SOAP/MTOM con + certificato client, Intermediario A (chiave API) e Intermediario B (utente e password) dietro lo stesso contratto + `IEInvoiceTransport` (ADR 0040); prova di connessione, pausa, segreti cifrati. +- Instradamento (#77): regole *Sempre*, *Cliente PA*, *Cliente specifico*, *Tipo documento* e *Volume giornaliero* + con canale di riserva (`SdiRouter`); pagina *Canali di trasmissione* (mockup 059). +- Lettura dei canali (#76): attività `einvoice.poll` ogni 15 minuti e *Leggi i canali ora*; un messaggio si conferma + solo quando tutti i suoi file sono salvati. Ricezione push di SdICoop su `POST /sdicoop/{azienda}` con la chiave + di ricezione nell'intestazione `X-Khaemhat-SdiCoop-Key` e il certificato reciproco sul reverse proxy. +- Cruscotto SDI (#74, #75, mockup 058): sei contatori, viste *Emesse*, *Autofatture* e *Da fare*, filtri e + ricerca, documenti da generare, *Genera + invia*, *Invia*, *Correggi*, *Segna come inviata*, download dell'XML, + storico del file con le versioni sostituite, esito della trasmissione; avvisi sulla Home per scarti e file da + inviare (`EInvoiceFeedSource`). +- Copia di cortesia (#74): il PDF del documento con il file FatturaPA allegato (`/AF`). +- Fatture ricevute (#79): casella delle fatture dei fornitori dai canali o caricate (XML, P7M, metadati, ZIP) senza + doppioni, registrazione singola o in blocco con l'import del ciclo passivo, scarto e ripristino, download. +- Conservazione (#79): pacchetto ZIP di un periodo (fino a due anni) con `emesse/`, `ricevute/`, `notifiche/`, + `indice.csv` con SHA-256 e `LEGGIMI.txt`, e l'elenco dei pacchetti preparati. +- Fatturazione elettronica nei dati di esempio con il modulo EINV (#80): canale PEC in pausa, Intermediario A + disattivato, tre regole, i file delle fatture demo con consegne, uno scarto corretto, una mancata consegna e file + in attesa, tre fatture di fornitori da registrare. +- Rimozione dei dati di esempio (#80, ADR 0040): `DemoDataRemover` guidato dallo schema delle migrazioni elimina le + righe `is_demo` e quelle che appartengono loro in una transazione e si ferma se dati dell'utente vi fanno + riferimento; `scripts/seed.sh --remove-demo [--company CODICE]`; il seed stampa il tempo impiegato. +- Permessi `einvoice.document.read`, `einvoice.document.send`, `einvoice.inbox.read`, `einvoice.inbox.import`, + `einvoice.channel.manage`; testi in `Resources/it-IT/EInvoicing.json`. +- Tabelle `e_invoices`, `e_invoice_notifications`, `e_invoice_inbox`, `e_invoice_channels`, `e_invoice_routing`, + `e_invoice_conservation` (migrazione `M20261113_004`). +- ADR 0039 e 0040; pagina wiki *Fatturazione elettronica* completa con le schermate (#81). + +### Changed +- Il menu *Fatturazione elettronica* ha le voci *Cruscotto SDI*, *Fatture ricevute*, *Notifiche SDI*, + *Conservazione* e *Canali di trasmissione*, ognuna con il suo permesso; *Dichiarazioni d'intento* resta in M10. +- Una fattura scartata dallo SDI torna modificabile e si rigenera con un nuovo file. +- I seeder dimostrativi marcano come demo anche le righe scritte dai servizi per loro (registrazioni, partite, + pagamenti, mandati, estratti conto). +- Il modello delle fatture ricevute è condiviso con quello delle emesse (`EInvoice*` nelle astrazioni fiscali). + ## [0.8.0] - 2026-11-13 M8 - Scadenzario e tesoreria. Le partite aperte di clienti e fornitori si chiudono con incassi e pagamenti che si diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index b87cc6b..c53aef5 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -733,6 +733,7 @@ Migrazioni applicate in ordine: - `core` 20261113001 `create_inventory` (M20261113_001_CreateInventory) - `core` 20261113002 `create_ledger` (M20261113_002_CreateLedger) - `core` 20261113003 `create_treasury` (M20261113_003_CreateTreasury) +- `core` 20261113004 `create_einvoicing` (M20261113_004_CreateEInvoicing) #### `attachments` @@ -1241,6 +1242,180 @@ Migrazioni applicate in ordine: - indice unico `ux_dunning_levels_level` su `level` +#### `e_invoice_channels` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(20) | no | | | +| `enabled` | Bool | no | `false` | | +| `paused` | Bool | no | `false` | | +| `mailbox` | String(254) | sì | | | +| `smtp_host` | String(200) | sì | | | +| `smtp_port` | Int32 | no | `465` | | +| `imap_host` | String(200) | sì | | | +| `imap_port` | Int32 | no | `993` | | +| `tls` | Bool | no | `true` | | +| `user_name` | String(254) | sì | | | +| `protected_password` | Text | sì | | | +| `exchange_address` | String(254) | sì | | | +| `archive_folder` | String(100) | sì | | | +| `endpoint` | String(300) | sì | | | +| `protected_certificate` | Text | sì | | | +| `protected_certificate_password` | Text | sì | | | +| `protected_api_key` | Text | sì | | | +| `test_environment` | Bool | no | `false` | | +| `last_check_at` | DateTimeUtc | sì | | | +| `last_check_ok` | Bool | sì | | | +| `last_check_message` | String(1000) | sì | | | +| `last_poll_at` | DateTimeUtc | sì | | | +| `last_poll_message` | String(1000) | sì | | | +| `last_poll_failed` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_e_invoice_channels_code` su `code` + +#### `e_invoice_conservation` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `from_date` | Date | no | | | +| `to_date` | Date | no | | | +| `file_count` | Int32 | no | `0` | | +| `file_name` | String(100) | no | | | +| `hash` | String(64) | no | | | +| `size` | Int64 | no | `0` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +#### `e_invoice_inbox` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `file_name` | String(100) | no | | | +| `hash` | String(64) | no | | | +| `content` | Bytes | no | | | +| `metadata_file_name` | String(100) | sì | | | +| `metadata` | Bytes | sì | | | +| `exchange_id` | String(40) | sì | | | +| `received_at` | DateTimeUtc | no | | | +| `channel_code` | String(20) | sì | | | +| `supplier_vat` | String(30) | sì | | | +| `supplier_name` | String(200) | sì | | | +| `document_type` | String(10) | sì | | | +| `number` | String(40) | sì | | | +| `document_date` | Date | sì | | | +| `total_amount` | Decimal(19,6) | sì | | | +| `party_id` | Int64 | sì | | | +| `status` | String(40) | no | | | +| `purchase_document_id` | Int64 | sì | | | +| `error` | String(500) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_e_invoice_inbox_file` su `file_name` +- indice `ix_e_invoice_inbox_status` su `status`, `received_at` +- indice unico `ux_e_invoice_inbox_hash` su `hash` + +#### `e_invoice_notifications` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `e_invoice_id` | Int64 | sì | | -> `e_invoices` (Cascade) | +| `code` | String(4) | no | | | +| `file_name` | String(100) | no | | | +| `invoice_file_name` | String(100) | sì | | | +| `exchange_id` | String(40) | sì | | | +| `received_at` | DateTimeUtc | no | | | +| `outcome` | String(10) | sì | | | +| `description` | String(1000) | sì | | | +| `errors` | Text | sì | | | +| `channel_code` | String(20) | sì | | | +| `content` | Bytes | no | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_e_invoice_notifications_invoice` su `e_invoice_id` +- indice unico `ux_e_invoice_notifications_file` su `file_name` + +#### `e_invoice_routing` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `position` | Int32 | no | `0` | | +| `condition` | String(40) | no | | | +| `value` | String(40) | sì | | | +| `channel_code` | String(20) | no | | | +| `fallback_channel_code` | String(20) | sì | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +#### `e_invoices` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `family` | String(40) | no | | | +| `document_id` | Int64 | no | | | +| `kind` | String(40) | no | | | +| `document_number` | String(40) | sì | | | +| `document_date` | Date | no | | | +| `party_id` | Int64 | sì | | | +| `document_type` | String(10) | no | | | +| `file_name` | String(60) | no | | | +| `progressive` | Int64 | no | | | +| `format` | String(10) | no | | | +| `recipient_code` | String(7) | sì | | | +| `recipient_pec` | String(254) | sì | | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `status` | String(40) | no | | | +| `channel_code` | String(20) | sì | | | +| `exchange_id` | String(40) | sì | | | +| `message_id` | String(200) | sì | | | +| `generated_at` | DateTimeUtc | no | | | +| `sent_at` | DateTimeUtc | sì | | | +| `last_notification_at` | DateTimeUtc | sì | | | +| `last_message` | String(1000) | sì | | | +| `send_attempts` | Int32 | no | `0` | | +| `content` | Bytes | no | | | +| `superseded` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_e_invoices_document` su `family`, `document_id` +- indice `ix_e_invoices_exchange` su `exchange_id` +- indice `ix_e_invoices_status` su `superseded`, `status` +- indice unico `ux_e_invoices_file` su `file_name` + #### `exchange_rates` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/MODULES.md b/docs/MODULES.md index e557545..8569de9 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -220,14 +220,14 @@ menu *Fatturazione elettronica* se `EINV` è attivo e da *Contabilità* se è at | Voce | Contenuto | |---|---| | Licenza | `EINV` | -| Responsabilità | generazione e validazione XML FatturaPA (`FPR12`/`FPA12`/`FSM10`), lettura passive e P7M, notifiche SDI, quattro canali (PEC integrata, SdICoop, Intermediario A, Intermediario B) con instradamento, cruscotto, inbox, export per la conservazione, autofatture da inviare | -| Entità | `EInvoice`, `SdiNotification`, `EInvoiceInboxFile`, `SdiChannel`, `SdiRoutingRule`, `ConservationPackage` | -| Servizi | `EInvoiceService`, `EInvoiceExportService`, `SdiChannelService`, `SdiInboxService`, `SdiNotificationImportService`, `PurchaseInvoiceImportService`, `ConservationExportService`; nel pacchetto paese `FatturaPaWriter`, `FatturaPaValidator`, `FatturaPaReader`, `SdiRouter`, i quattro `ISdiTransport` | -| Maschere e mockup | cruscotto SDI (058, `EInvoiceDashboard`), canali SDI (059, `SdiChannelsPage`), bollo virtuale (060, `StampDutyPage`), dichiarazioni d'intento e plafond (061, `IntentDeclarationsPage`) | -| Permessi | proposte: `einvoicing.invoice.generate`, `einvoicing.invoice.send`, `einvoicing.channel.write`, `einvoicing.inbox.import` | +| Responsabilità | file FatturaPA (`FPR12`/`FPA12`/`FSM10`) con controlli offline e codici dello SDI, quattro canali (PEC, SdICoop, Intermediario A, Intermediario B) con instradamento e canale di riserva, lettura dei canali programmata e push SdICoop, notifiche, correzione degli scarti, copia di cortesia PDF con l'XML allegato, fatture ricevute da registrare, pacchetti per la conservazione, autofatture da inviare, rimozione dei dati di esempio | +| Entità | `EInvoice` (`e_invoices`), `EInvoiceNotification` (`e_invoice_notifications`), `EInvoiceInboxFile` (`e_invoice_inbox`), `EInvoiceChannelSetting` (`e_invoice_channels`), `SdiRoutingRule` (`e_invoice_routing`), `ConservationExport` (`e_invoice_conservation`) | +| Servizi | `EInvoiceService`, `EInvoiceChannelService`, `EInvoicePollingService` (+ job `einvoice.poll`), `SdiPushService` (endpoint `POST /sdicoop/{azienda}`), `SdiInboxService`, `ConservationExportService`, `EInvoiceFeedSource`, `DemoEInvoiceSeeder`, `DemoDataRemover`; nel core `SdiRouter`, `EInvoiceStates`; nel pacchetto italiano `FatturaPaWriter`, `FatturaPaValidator`, `FatturaPaReader`, `SdiReceiptReader`, `PecSdiTransport`, `SdiCoopTransport`, `IntermediaryATransport`, `IntermediaryBTransport`, `SdiCoopPushReader` (ADR 0039, 0040) | +| Maschere e mockup | cruscotto SDI (058, `EInvoiceDashboardPage`), canali e instradamento (059, `EInvoiceChannelsPage`), fatture ricevute (`EInvoiceInboxPage`), notifiche (`EInvoiceNotificationsPage`), conservazione (`ConservationPage`); dichiarazioni d'intento e plafond (061) in M10; bollo virtuale (060) in *IVA* dalla 0.7 | +| Permessi | `einvoice.document.read`, `einvoice.document.send`, `einvoice.inbox.read`, `einvoice.inbox.import`, `einvoice.channel.manage` | | Log | SDI/e-invoicing; invio e lettura PEC in E-mail/PEC; intermediari in Integrazioni | | Wiki | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) | -| Milestone | M9 `v0.9.0` (con seed demo completo); dichiarazioni d'intento in M10 | +| Milestone | M9 `v0.9.0` (consegnata); dichiarazioni d'intento in M10 | ### 3.12 Crm — CRM diff --git a/docs/STATUS.md b/docs/STATUS.md index c0ac2fc..68598e8 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -3,9 +3,9 @@ > Punto di ripresa per ogni sessione. Aggiornare a fine sessione. **Ultimo aggiornamento:** 2026-11-13 -**Milestone corrente:** M9 — Fatturazione elettronica (issue #74-#81), da iniziare. M8 chiusa: PR in `main`, tag -`v0.8.0`, immagine e release. -**Prossimo passo:** M9 dall'issue #74. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo +**Milestone corrente:** M10 — Cespiti, Intrastat, chiusura e bilancio (issue #82-#87), da iniziare. M9 chiusa: PR in +`main`, tag `v0.9.0`, immagine e release. +**Prossimo passo:** M10 dall'issue #82. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile). Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della password (mockup 003); schede *Layout salvati* e *Notifiche* del profilo; rinomina e filtro predefinito nei radar; @@ -17,11 +17,14 @@ bilancio dal file `khaemhat-coa.json`; scritture delle rimanenze e libro inventa cassa (fase 2). Da M8: tracciati CBI e SEPA da provare con un home banking reale; tabella semestrale dei tassi di mora da aggiornare a gennaio e luglio (ADR 0038); blocco per fido su ordini e documenti; report di tesoreria in *Report* (M12). +Da M9: schema XSD ufficiale FatturaPA al posto di quello scritto in casa (serve il permesso di scaricarlo); +intermediari reali e accreditamento SdICoop (#78, ADR 0040); conformità PDF/A-3 dichiarata della copia di cortesia; +pulsanti *Carica* e *Rimuovi dati di esempio* nell'interfaccia (M12); dichiarazioni d'intento (M10). ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7. -- ADR 0001-0038. +- ADR 0001-0040. - Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice). - Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid). - Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`, @@ -96,6 +99,14 @@ gennaio e luglio (ADR 0038); blocco per fido su ordini e documenti; report di te CSV/CBI/CAMT.053 senza doppioni con confidenza e regole (#71); solleciti a tre livelli con interessi di mora e job automatico, flusso di cassa, scadenze sulla Home (#72); tesoreria nei dati di esempio con FIN, wiki *Scadenzario* con le schermate (#73). Test: 823 verdi in locale, anche quelli di PostgreSQL (18) con un container locale. +- **M9 (chiusa, `v0.9.0`):** file FatturaPA `FPR12`/`FPA12`/`FSM10` con controllo offline dei codici SDI e schema + scritto in casa (#74, ADR 0039); notifiche RC/NS/MC/NE/DT/AT/SE/MT senza doppioni che muovono file e documento, + correzione degli scarti, copia di cortesia PDF con l'XML allegato (#75); canali PEC (IMAP e MIME in casa), + SdICoop SOAP/MTOM e due intermediari generici con instradamento e riserva, job `einvoice.poll` e push SdICoop su + `/sdicoop/{azienda}` (#76, #77, ADR 0040); fatture ricevute da registrare e pacchetti di conservazione (#79); + fatturazione nei dati di esempio e rimozione dei dati di esempio guidata dallo schema (#80); wiki *Fatturazione + elettronica* con le schermate (#81). #78 (scelta degli intermediari, accreditamento SdICoop) resta aperta. + Test: 874 verdi in locale, anche quelli di PostgreSQL (18) con un container locale. - Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13) e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36, M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91, diff --git a/docs/adr/0039-fatturazione-elettronica.md b/docs/adr/0039-fatturazione-elettronica.md new file mode 100644 index 0000000..e870222 --- /dev/null +++ b/docs/adr/0039-fatturazione-elettronica.md @@ -0,0 +1,81 @@ +# ADR 0039 - Fatturazione elettronica: file, stati, canali e ricezione + +- **Stato:** accettata +- **Data:** 2026-11-13 +- **Modifica:** SPEC §11.9, §10.3 (mockup 058 e 059); milestone M9, issue #74, #75, #76, #77, #79 + +## Contesto + +SPEC §11.9 chiede il file FatturaPA delle fatture emesse con controllo prima dell'invio, la trasmissione allo SDI +attraverso quattro canali (PEC integrata, SdICoop, due intermediari) con regole di instradamento, le notifiche che +aggiornano lo stato dei documenti, le fatture ricevute, la correzione degli scarti, la copia di cortesia e il +pacchetto per la conservazione. Restavano aperti: dove sta il file e come convive con il documento, come si +numerano i file, come si controlla il file senza librerie esterne né lo schema ufficiale (SPEC §1, nessun download +durante lo sviluppo), come si evitano doppioni di notifiche e fatture ricevute, come si leggono i canali senza perdere +messaggi, come riceve SdICoop e come si proteggono le credenziali. + +## Decisione + +1. **Il file sta nel database.** Ogni file è una riga di `e_invoices` con il contenuto XML, nome, progressivo, + canale, identificativo SDI e stato. Lo stato del documento di vendita segue quello del file nella stessa + transazione, attraverso il motore dei documenti (`AdvanceExchangeAsync`, azioni `GenerateXml`, `Send`, + `MarkDelivered`, `MarkRejected`, `MarkNotDelivered`). Un file scartato **non si cancella**: resta come + *sostituito* e il documento torna modificabile; la nuova generazione prende un nuovo progressivo. Un file + generato e non ancora inviato si riscrive con lo stesso nome. +2. **Nome e progressivo.** `IT_.xml`, progressivo di cinque caratteri in base 36 da un + contatore dell'azienda, mai riusato (60.466.175 file per trasmittente). +3. **Tutto ciò che è italiano nel pacchetto.** Le astrazioni (`IEInvoiceWriter`, `IEInvoiceValidator`, + `IEInvoiceReceiptReader`, `IEInvoiceChannels`, `IEInvoicePushReader`) sono in `Khaemhat.Fiscal.Abstractions`; + scrittura, controlli, lettura delle ricevute e i quattro trasporti sono in `Khaemhat.Fiscal.Italy`. Il web non + dipende dal pacchetto italiano. +4. **Controlli con i codici dello SDI e schema scritto in casa.** `FatturaPaValidator` ripete offline i controlli + documentati dall'Agenzia con lo **stesso codice di errore** (00400, 00423, 00471…), con le tolleranze delle + specifiche (un centesimo su `PrezzoTotale` e `Imposta`, un euro su `ImponibileImporto`); ciò che richiede i + registri dell'Agenzia (partita IVA esistente, codice destinatario accreditato, indice IPA) si controlla solo nella + forma. La struttura si controlla contro uno schema XSD **scritto per Khaemhat** sulle regole del formato 1.2 + (risorsa incorporata `FatturaPA_v1.2_khaemhat.xsd`), perché il file ufficiale non si può scaricare durante lo + sviluppo; le specifiche seguite sono la 1.9.1 (`FatturaPaCodeLists.SpecVersion`). Sostituire lo schema con + quello ufficiale non cambia il codice. +5. **Una notifica entra una volta.** Il nome del file della notifica è unico in `e_invoice_notifications`; un + doppione è riconosciuto e segnalato, non applicato due volte. La notifica si abbina al file per nome del file + fattura o per identificativo SDI; quella non abbinata resta registrata ed evidenziata. MT e SE si conservano + senza cambiare stato. Le fatture ricevute entrano in `e_invoice_inbox` una volta sola (impronta SHA-256 del + contenuto). +6. **Lettura dei canali senza perdite.** L'attività `einvoice.poll` (ogni 15 minuti) legge i canali attivi e non in + pausa; ogni messaggio è **confermato** (archiviato in PEC, `ack` o cancellazione presso l'intermediario) solo dopo + che tutti i suoi file sono stati salvati, così un arresto a metà rilegge il messaggio e la deduplicazione scarta + ciò che c'è già. Per la PEC si leggono solo i messaggi con mittente `fatturapa.it` e gli allegati `.xml`/`.p7m` + del messaggio originale; la cartella di archivio è l'impostazione consigliata. +7. **Instradamento a regole.** `SdiRouter` (core) sceglie la prima regola attiva che si applica, nell'ordine: + *Sempre*, *Cliente PA*, *Cliente specifico*, *Tipo documento*, *Volume giornaliero*. Ogni regola ha un canale di + riserva usato se il primo è in pausa, disattivato o fallisce l'invio. Senza regole vale il primo canale attivo. +8. **SdICoop in push.** Lo SDI consegna notifiche e fatture con chiamate SOAP verso l'azienda. Khaemhat espone + `POST /sdicoop/{azienda}` (anonimo per l'autenticazione dell'applicazione, senza antiforgery, al massimo 16 MB); + `SdiPushService` accetta la chiamata solo se il canale SDICOOP è attivo e l'intestazione + `X-Khaemhat-SdiCoop-Key` corrisponde alla chiave di ricezione (confronto a tempo costante delle impronte SHA-256). + Il certificato reciproco richiesto dall'Agenzia si verifica sul **reverse proxy**, che aggiunge l'intestazione: + Kestrel resta senza configurazione TLS speciale. Il pacchetto legge la busta (`IEInvoicePushReader`) e prepara la + risposta SOAP. Risposte: 404 azienda sconosciuta o senza modulo, 401 canale non attivo o chiave errata, 400 corpo + illeggibile, 200 dopo il salvataggio. +9. **Credenziali cifrate.** Password, chiavi API, chiave di ricezione e certificato PKCS#12 sono cifrati con + `ISecretProtector` (scopo `einvoice.channel`) e non tornano mai nell'interfaccia: un campo vuoto mantiene il valore. + Gli indirizzi dei servizi devono essere `https` (`http` solo verso `localhost`). +10. **Copia di cortesia in PDF.** La stampa del documento con il file FatturaPA come file associato (`/AF`, + struttura PDF/A-3). Non si dichiara la conformità PDF/A, che richiederebbe profili colore e font incorporati + certificati. +11. **Conservazione come esportazione.** Khaemhat non è un conservatore: `ConservationExportService` prepara uno ZIP + (`emesse/`, `ricevute/`, `notifiche/`, `indice.csv` con SHA-256, `LEGGIMI.txt`) per al massimo 731 giorni e + registra in `e_invoice_conservation` periodo, numero di file, dimensione e impronta. +12. **Permessi.** `einvoice.document.read`, `einvoice.document.send`, `einvoice.inbox.read`, `einvoice.inbox.import`, + `einvoice.channel.manage`, tutti nel modulo `EINV`. + +## Conseguenze + +- La fattura e i suoi file viaggiano insieme in backup e ripristino; il database cresce di qualche kB per fattura. +- Gli scarti più comuni si vedono prima dell'invio, con il messaggio che lo SDI darebbe. +- Lo schema scritto in casa può essere meno severo di quello ufficiale su dettagli di struttura: quando l'utente + autorizza il download, il file ufficiale va messo al posto della risorsa e i test di scrittura rieseguiti. +- SdICoop e gli intermediari sono pronti ma vanno attivati solo dopo l'accreditamento e la scelta del fornitore + (issue #78, ADR 0040); la PEC funziona da subito. +- Le dichiarazioni d'intento (M10) e il formato EN 16931 / UBL arriveranno come altre implementazioni delle stesse + astrazioni. diff --git a/docs/adr/0040-intermediari-e-dati-di-esempio.md b/docs/adr/0040-intermediari-e-dati-di-esempio.md new file mode 100644 index 0000000..a9f6e37 --- /dev/null +++ b/docs/adr/0040-intermediari-e-dati-di-esempio.md @@ -0,0 +1,44 @@ +# ADR 0040 - Contratti degli intermediari SDI e rimozione dei dati di esempio + +- **Stato:** accettata +- **Data:** 2026-11-13 +- **Modifica:** SPEC §11.9, §14; milestone M9, issue #77, #78, #80 + +## Contesto + +SPEC §11.9 prevede due intermediari accreditati come canali verso lo SDI, ma il titolare del progetto non ha ancora +scelto i fornitori (issue #78): non ci sono API reali da seguire. SPEC §14 chiede inoltre che i dati di esempio si +possano **rimuovere** senza toccare i dati dell'utente; finora ogni milestone aggiungeva tabelle demo e una rimozione +scritta a mano avrebbe dovuto essere aggiornata ogni volta. + +## Decisione + +1. **Due contratti generici.** `IntermediaryTransportBase` contiene il ciclo comune (invio, lettura dei file in + attesa, conferma, prova); le due classi derivate definiscono solo le richieste: + - **Intermediario A** (chiave API, `Authorization: Bearer`): `POST {endpoint}/invoices` con il file e + l'intestazione `X-File-Name`, risposta `{ "id", "sdiId" }`; `GET files` per notifiche e fatture in attesa; + `POST files/{id}/ack` per confermarle; `GET status` per la prova. + - **Intermediario B** (utente e password, `Authorization: Basic`): `POST api/v1/send`, `GET api/v1/inbox`, + `DELETE api/v1/inbox/{id}` come conferma, `GET api/v1/ping`. + Quando l'utente sceglie i fornitori, ogni contratto diventa l'API reale cambiando solo le richieste della classe + derivata; servizi, instradamento, interfaccia e test di integrazione restano uguali. +2. **Prima l'accreditamento.** SdICoop e intermediari sono scritti e provati con server finti nei test, ma si + attivano in produzione solo dopo accreditamento o contratto (#78). La PEC è il canale che funziona subito. +3. **Rimozione guidata dallo schema.** `DemoDataRemover` legge dalle migrazioni le tabelle con la colonna `is_demo` + e le chiavi esterne: elimina le righe marcate e quelle delle tabelle senza marca che appartengono loro (righe di + documento, giacenze), in ordine di dipendenza e in **una transazione**. Se una riga dell'utente si riferisce a una + riga demo (una fattura vera a un cliente demo) non elimina nulla e restituisce le tabelle che lo impediscono. + Le entità che possono essere demo implementano `IDemoMarkable`; un nuovo modulo è coperto senza modifiche. +4. **Comando.** `scripts/seed.sh --remove-demo [--company CODICE]` (non combinabile con `--base`, `--demo`, + `--scale`) stampa le righe rimosse per tabella o le tabelle bloccanti. +5. **Demo della fatturazione solo con EINV e senza rete.** `DemoEInvoiceSeeder` usa i servizi del programma, che + controllano la licenza; il canale PEC dell'esempio è **in pausa** con credenziali finte e le notifiche sono + applicate come se fossero arrivate, così nessun dato dimostrativo raggiunge lo SDI. + +## Conseguenze + +- Il lavoro per un intermediario reale è limitato a una classe e ai suoi test. +- Un database creato prima della marca `is_demo` su tutte le tabelle può bloccare la rimozione: è voluto, l'utente + vede quali tabelle controllare. +- La rimozione resta un'operazione da super utente e da riga di comando; il pulsante nell'interfaccia arriva con le + pagine di amministrazione (M12). diff --git a/docs/wiki/Acquisti.md b/docs/wiki/Acquisti.md index acb0c49..6deff40 100644 --- a/docs/wiki/Acquisti.md +++ b/docs/wiki/Acquisti.md @@ -87,7 +87,8 @@ fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota ![Khaemhat 0.6.0 · import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png) **Acquisti → Importa fatture** (o il link nell'elenco delle fatture passive) registra in bozza le fatture ricevute -dallo SDI o dal tuo intermediario. +dallo SDI o dal tuo intermediario. Dalla 0.9 le fatture che arrivano dai canali SDI si registrano anche da +**Fatturazione elettronica → Fatture ricevute**, con lo stesso import. 1. **Caricamento**: scegli uno o più file: **XML FatturaPA**, file firmati **.p7m** o archivi **ZIP** che li contengono (fino a 50 MB per file). I file che non sono fatture elettroniche leggibili sono elencati a parte con il @@ -136,7 +137,7 @@ ordinario** al posto della natura, il numero e la data della fattura del fornito di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` delle autofatture. Il **file XML** dell'autofattura (con il fornitore come cedente e l'azienda come cessionario) e l'invio allo SDI -arrivano con la [Fatturazione elettronica](Fatturazione-elettronica) (M9); la doppia registrazione nei registri IVA +si fanno dalla vista *Autofatture* della [Fatturazione elettronica](Fatturazione-elettronica) (dalla 0.9); la doppia registrazione nei registri IVA vendite e acquisti si fa da sola alla conferma dell'autofattura (dalla 0.7, vedi [IVA](IVA)). Le definizioni ufficiali dei codici TD sono in [Fiscalità italiana](Fiscalita-italiana). diff --git a/docs/wiki/Attivita-programmate.md b/docs/wiki/Attivita-programmate.md index 50e5500..580e254 100644 --- a/docs/wiki/Attivita-programmate.md +++ b/docs/wiki/Attivita-programmate.md @@ -50,7 +50,7 @@ Esempi presenti nel mockup (dati dimostrativi): | `dunning` | Solleciti di pagamento | Procedura | `0 9 * * 1` | | `vat-reminder` | Promemoria liquidazione IVA | Notifica | mensile | | `ecb-rates` | Aggiornamento cambi BCE | Procedura | nei giorni feriali | -| `sdi-inbox` | Lettura inbox e canali SDI | Procedura | ogni 30 minuti | +| `einvoice.poll` | Lettura dei canali SDI (notifiche e fatture ricevute) | Procedura | `*/15 * * * *` | | `report-sales-weekly` | Report vendite settimanale a direzione | Report via e-mail | `0 7 * * 1` | | `reorder` | Proposta di riordino | Procedura | `0 6 * * *` | | `stock-check` | Verifica coerenza giacenze | Verifica | settimanale | diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index 28f1452..f428174 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -1,6 +1,6 @@ # Changelog -> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13 +> **Stato:** completa per 0.9.0 · **Ultima revisione:** 2026-11-13 Le novità di ogni versione sono nel file [`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository @@ -11,6 +11,8 @@ Le novità di ogni versione sono nel file | Versione | Data | Contenuto | |---|---|---| +| 0.9.0 | 2026-11-13 | M9 — Fatturazione elettronica: file FatturaPA con controllo prima dell'invio e i codici dello SDI; canali PEC, SdICoop e due intermediari con regole di instradamento e canale di riserva; lettura dei canali ogni 15 minuti e ricezione push di SdICoop; notifiche che aggiornano file e documenti; correzione degli scarti; copia di cortesia PDF con l'XML allegato; fatture ricevute da registrare; pacchetti per la conservazione; fatturazione elettronica nei dati di esempio e rimozione dei dati di esempio. | +| 0.8.0 | 2026-11-13 | M8 — Scadenzario e tesoreria: partite aperte con aging, incassi e pagamenti con abbuoni, spese e differenze cambio; distinte RiBa, SDD e bonifici SEPA con insoluti, mandati SDD; riconciliazione bancaria CSV, CBI e CAMT.053 con abbinamento automatico; solleciti con interessi di mora; flusso di cassa; tesoreria nei dati di esempio. | | 0.7.0 | 2026-11-13 | M7 — Contabilità generale e IVA: piano dei conti PMI a tre livelli, causali, prima nota con registrazioni provvisorie, definitive e storni, ricorrenti; contabilizzazione automatica di fatture, note e autofatture con righe IVA, partite e ritenute; registri IVA con stampa definitiva, liquidazione mensile o trimestrale con acconto, F24 e LIPE; ritenute d'acconto e dati CU; bollo virtuale; partitari, mastrini, bilancio di verifica e libro giornale; contabilità nei dati di esempio. | | 0.6.0 | 2026-11-12 | M6 — Acquisti e Magazzino: ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo e controllo dei prezzi; import delle fatture elettroniche XML, P7M e ZIP con fornitore e articoli abbinati; autofatture e integrazioni TD16-TD29 con la loro scadenza; giacenze per deposito con impegnato, ordinato e costo medio ponderato, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione; giacenze iniziali da file; acquisti e magazzino nei dati di esempio. | | 0.5.0 | 2026-11-12 | M5 — Motore documenti e Vendite: preventivi, ordini, DDT, fatture, note di credito, pro forma e parcelle con numerazione senza buchi, castelletto IVA, bollo, ritenute e scadenze; documenti collegati riga per riga e *Crea …* per passare dall'uno all'altro; fatturazione differita guidata; anteprima di stampa e PDF salvato tra gli allegati; invio per e-mail con SMTP interno; un anno di vendite nei dati di esempio; [Guida all'uso](Guida-utente) con le schermate. | diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index 160462c..3637f27 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -1,6 +1,6 @@ # Dati di base e di esempio -> **Stato:** completa per M5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (dati di esempio di contabilità con il modulo, completi in M9) +> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) > **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14 ## A cosa serve @@ -115,7 +115,7 @@ reale. Contiene: | Articoli | 120 | | Documenti | 12 mesi coerenti: ordini → DDT → fatture differite, fatture immediate e accompagnatorie, note di credito, pro-forma, parcelle; ordini fornitore → carichi → fatture di acquisto; autofatture; inventario, movimenti, trasferimenti | | Contabilità | registrazioni dai documenti, incassi e pagamenti anche parziali, un insoluto RiBa, giroconti, liquidazioni IVA confermate fino al mese precedente, ritenute, 58 cespiti con ammortamenti, esercizio precedente chiuso con bilancio | -| Fatturazione elettronica | XML SDI in stati diversi, con notifiche | +| Fatturazione elettronica | file FatturaPA in stati diversi con le notifiche, canali e regole di instradamento, fatture ricevute da registrare | | Tesoreria | un estratto conto da riconciliare | | CRM | 23 lead, 18 opportunità, attività, 3 campagne, 2 ticket | | Servizi e canali | 2 contratti di assistenza con interventi, 1 canale e-commerce generico con ordini | @@ -176,6 +176,17 @@ confermate fino al mese precedente, le ritenute e il bollo virtuale (vedi [Conta | Estratto conto | un CSV di quattro movimenti da riconciliare: il saldo della fattura incassata in parte, un pagamento già registrato, le commissioni riconosciute dalla regola *Canone e commissioni* e una spesa da registrare su conto | | Solleciti | un primo sollecito già inviato al cliente con lo scaduto più vecchio | +**Da M9**, se la licenza comprende il modulo **EINV**, c'è anche la **fatturazione elettronica** (vedi +[Fatturazione elettronica](Fatturazione-elettronica)): + +| Dati | Che cosa mostrano | +|---|---| +| File FatturaPA | le fatture e le note già emesse hanno il loro file: la maggior parte **consegnata** (RC), una **scartata** (NS 00305) e poi corretta e consegnata, una con **mancata consegna** (MC), le ultime in attesa o ancora da inviare | +| Notifiche | le ricevute di ogni file, scaricabili come sono arrivate | +| Canali | la PEC configurata ma **in pausa** con credenziali finte, l'Intermediario A abbozzato e disattivato: nessun dato di esempio raggiunge lo SDI | +| Instradamento | tre regole: PA su PEC, oltre 200 file al giorno sull'Intermediario A, sempre PEC con l'Intermediario A di riserva | +| Fatture ricevute | tre fatture di fornitori da registrare | + Il resto della tabella arriva con le milestone dei rispettivi moduli. I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo stesso caricamento è usato come prova automatica di correttezza. @@ -191,8 +202,13 @@ alternativa si caricano al primo avvio con `KHAEMHAT_SEED_DEMO=true` (solo se il ### Rimuovi dati di esempio 1. Premi **Rimuovi dati di esempio** (solo **super utente**). -2. Khaemhat elimina le righe dimostrative in ordine di dipendenza e **si rifiuta** se esistono dati reali collegati - a righe dimostrative (ad esempio una fattura vera intestata a un cliente demo). +2. Khaemhat elimina le righe dimostrative (`is_demo`) e quelle che appartengono loro (le righe di un documento demo, + le giacenze di un articolo demo) in **una sola transazione**, e **si rifiuta** se esistono dati reali collegati a + righe dimostrative (ad esempio una fattura vera intestata a un cliente demo): in quel caso elenca le tabelle + coinvolte e non tocca nulla. + +Le tabelle e i loro collegamenti si leggono dalle migrazioni, quindi la rimozione copre anche i moduli aggiunti in +seguito. Da riga di comando: `scripts/seed.sh --remove-demo [--company CODICE]` (vedi sotto). Usalo quando un'azienda nata come demo diventa l'azienda reale; per partire puliti è comunque preferibile creare un'azienda nuova (vedi [Istanza e database](Istanza-e-database)). @@ -219,6 +235,7 @@ docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base --company DEMO docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --company DEMO docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --scale 10 --company PROVA +docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --remove-demo --company DEMO ``` In sviluppo, dalla cartella del repository: `scripts/seed.sh --base|--demo [--scale N] [--company CODICE]`. @@ -228,8 +245,12 @@ In sviluppo, dalla cartella del repository: `scripts/seed.sh --base|--demo [--sc | `--base` | aggiunge i codici di base mancanti | | `--demo` | prima i dati di base, poi i dati di esempio; ogni gruppo (anagrafiche, articoli) si carica solo nell'azienda che non ne ha ancora | | `--scale N` | solo con `--demo`: ripete il catalogo articoli N volte (da 1 a 100), per le prove di prestazione | +| `--remove-demo` | rimuove solo i dati di esempio (non si combina con le altre opzioni); stampa le righe rimosse per tabella o le tabelle che lo impediscono | | `--company CODICE` | lavora solo su quell'azienda invece che su tutte quelle attive | +Il caricamento completo dell'azienda di esempio richiede pochi secondi su SQLite (circa 2,5 s in sviluppo) e stampa +il tempo impiegato per ogni azienda. + I dati di esempio si caricano anche al primo avvio con `KHAEMHAT_SEED_DEMO=true`. ## Migrazioni diff --git a/docs/wiki/Fatturazione-elettronica.md b/docs/wiki/Fatturazione-elettronica.md index 8c3c37c..a5121ce 100644 --- a/docs/wiki/Fatturazione-elettronica.md +++ b/docs/wiki/Fatturazione-elettronica.md @@ -1,200 +1,323 @@ # Fatturazione elettronica e canali SDI -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M9) -> **Modulo di licenza:** EINV · **Permessi principali:** `sales.invoice.issue`, `einvoice.document.send`, `einvoice.channel.manage`, `einvoice.inbox.import` · **Specifica:** SPEC §11.9, §11.3, §11.5, §9.4 +> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) +> **Modulo di licenza:** EINV · **Permessi principali:** `einvoice.document.read` (cruscotto, notifiche, +> conservazione), `einvoice.document.send` (generare, inviare, importare notifiche), `einvoice.inbox.read` e +> `einvoice.inbox.import` (fatture ricevute), `einvoice.channel.manage` (canali e instradamento) · **Specifica:** +> SPEC §11.9, ADR 0039 e 0040 -## A cosa serve +Il modulo produce il **file FatturaPA** delle fatture emesse, lo **controlla** come farebbe il Sistema di +Interscambio (SDI), lo **trasmette** attraverso il canale scelto dalle regole di instradamento e segue le +**notifiche** che tornano indietro (consegna, scarto, mancata consegna, esito della pubblica amministrazione). Dalla +stessa sezione arrivano le **fatture dei fornitori**, che si registrano come fatture di acquisto, e si prepara il +**pacchetto per la conservazione**. -Il modulo genera l'**XML FatturaPA** delle fatture emesse, lo **valida**, lo **trasmette al Sistema di -Interscambio (SDI)** attraverso uno dei canali configurati, importa le **notifiche** e le **fatture passive**, -gestisce le **autofatture** da inviare e prepara il **pacchetto per la conservazione**. Il **cruscotto SDI** riunisce -tutto in una schermata ordinata per priorità. +Lo SDI è il sistema dell'Agenzia delle Entrate e non fa parte di Khaemhat. Per raggiungerlo Khaemhat offre quattro +canali con lo stesso modo di lavorare: la **PEC dell'azienda** (nessun servizio esterno), il web service **SdICoop** +e **due intermediari** accreditati. -Lo SDI è il sistema dell'Agenzia delle Entrate e non può essere "inglobato" in un gestionale. Khaemhat include però un -**canale proprio via PEC** che non richiede alcun servizio esterno, e supporta con la stessa interfaccia **SdICoop** -(web service dell'Agenzia) e **due intermediari**. +> **In questa versione** ci sono il file FatturaPA (`FPR12`, `FPA12`, `FSM10`) con controllo prima dell'invio, i +> quattro canali con prova di connessione, pausa e regole di instradamento con canale di riserva, la lettura +> automatica dei canali ogni 15 minuti, la ricezione push di SdICoop, l'import manuale delle notifiche, la correzione +> delle fatture scartate, la copia di cortesia in PDF con l'XML allegato, le fatture ricevute con registrazione in +> blocco, l'elenco delle notifiche e i pacchetti per la conservazione. Arrivano più avanti: le **dichiarazioni +> d'intento** e la **LIPE** ([IVA](IVA), M10), **Intrastat** ([Intrastat](Intrastat), M10) e il formato europeo +> **EN 16931 / UBL** ([Roadmap](Roadmap)). ## Dove si trova -Menu laterale **Fatturazione elettronica**: **Cruscotto SDI**, **Fatture emesse**, **Fatture ricevute**, -**Notifiche**, **Bollo virtuale**, **Intrastat**, **LIPE**; la configurazione dei canali è in **Fatturazione -elettronica → Canali**. Il contatore accanto alla voce di menu indica i documenti che richiedono attenzione. -Bollo virtuale, dichiarazioni d'intento e LIPE sono descritti nella pagina [IVA](IVA), Intrastat in [Intrastat](Intrastat). +Menu laterale **Fatturazione elettronica** → *Cruscotto SDI*, *Fatture ricevute*, *Notifiche SDI*, +*Conservazione*, *Canali di trasmissione* (e *Dichiarazioni d'intento*, ancora da sviluppare). -## Schermate +Il menu compare solo se la licenza comprende il modulo **EINV** e l'utente ha i permessi (vedi +[Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)). Ogni voce chiede il suo permesso: +chi non ha `einvoice.channel.manage`, per esempio, non vede i canali. -![058 · Cruscotto SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/058-cruscotto-sdi.png) -*Mockup 058 — cruscotto con i contatori per stato (da generare, da inviare, inviate in attesa, consegnate, scartate, mancata consegna), azioni Genera + invia, Correggi, Importa notifiche e l'elenco dei documenti con TD, canale, stato SDI e ultima notifica o errore* +Prima di iniziare servono: -![059 · Canali di trasmissione SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/059-canali-trasmissione-sdi.png) -*Mockup 059 — i quattro canali (PEC integrata, SdICoop, Intermediario A, Intermediario B) con il loro stato, le regole di instradamento e le impostazioni della casella PEC* +- il **profilo dell'azienda** completo in [Impostazioni](Impostazioni): partita IVA, codice fiscale, sede e + **regime fiscale** (RF01…). Senza questi dati la generazione si ferma con un messaggio che dice cosa manca; +- per ogni cliente il **codice destinatario** o la **PEC**, e per la pubblica amministrazione il **codice + ufficio IPA** di sei caratteri ([Anagrafiche](Anagrafiche)); +- almeno un **canale attivo** (vedi [I canali di trasmissione](#i-canali-di-trasmissione)). Senza canali si può + comunque generare il file, caricarlo dal portale *Fatture e Corrispettivi* e segnarlo come inviato. ## Il ciclo di una fattura -1. La fattura viene **confermata ed emessa** in [Vendite](Vendite) (numero definitivo, sola lettura). -2. **Genera XML**: Khaemhat produce il file FatturaPA e lo allega al documento (bloccato dopo l'invio). -3. **Valida**: il validatore controlla il file prima dell'invio. -4. **Invia**: il canale scelto dalle regole di instradamento trasmette il file allo SDI. -5. **Notifiche**: lo SDI risponde con ricevute e notifiche che aggiornano lo stato del documento. +1. La fattura, la nota di credito, la parcella o l'autofattura viene **confermata** in [Vendite](Vendite) o in + [Acquisti](Acquisti): da quel momento ha il numero definitivo e compare fra i *documenti da generare*. +2. **Genera**: Khaemhat scrive il file FatturaPA e lo controlla. Il documento passa a *XML generato*. +3. **Invia**: il canale scelto dalle regole di instradamento trasmette il file. Il documento passa a *Inviato*. +4. **Notifiche**: lo SDI risponde e lo stato del file e del documento cambia da solo. -Il pulsante **Genera + invia** esegue i passi 2-4 sui documenti selezionati. +Il pulsante **Genera + invia** fa i passi 2 e 3 in un colpo solo sui documenti selezionati. -| Stato del documento | Quando | -|---|---| -| **Bozza** | fattura in lavorazione | -| **Emessa** | confermata, senza XML (*Da generare*) | -| **XML generato** | XML prodotto e validato (*Da inviare*) | -| **Inviata** | trasmessa allo SDI, in attesa di ricevuta | -| **Consegnata** | ricevuta di consegna (RC) | -| **Scartata** | notifica di scarto (NS): va corretta e rigenerata | -| **Mancata consegna** | lo SDI non è riuscito a recapitarla (MC) | +| Stato del file | Quando | Stato del documento | +|---|---|---| +| **Generata** | file scritto e controllato, non ancora trasmesso | XML generato | +| **Inviata** | trasmessa allo SDI, in attesa della ricevuta | Inviato | +| **Consegnata** | ricevuta di consegna (RC) | Consegnato | +| **Scartata** | notifica di scarto (NS): la fattura **non è emessa** e va corretta | Scartato | +| **Mancata consegna** | lo SDI non è riuscito a recapitarla (MC): è comunque emessa | Non consegnato | +| **Accettata** / **Rifiutata** | esito del committente PA, EC01 o EC02 (NE) | | +| **Decorrenza termini** | la PA non ha risposto entro 15 giorni (DT) | | +| **Impossibile recapitare** | attestazione di trasmissione verso una PA (AT) | | -Una fattura emessa non si modifica: se l'XML **non è ancora stato inviato** si può annullare indicando il motivo; -altrimenti si emette una nota di credito. Una fattura **scartata** non è emessa ai fini fiscali: con **Correggi** si -corregge il dato e si rigenera l'XML (nuova versione dell'allegato). +## Cruscotto SDI -## L'XML FatturaPA +![Khaemhat 0.9.0 · cruscotto SDI con i contatori, i documenti da generare e i file trasmessi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-cruscotto.png) +*Khaemhat 0.9.0 — il cruscotto dell'azienda di esempio: i sei contatori, i documenti emessi senza file e i file +trasmessi con stato SDI, canale, ultima notifica e azioni.* + +In alto sei **contatori**: *Da generare* (documenti emessi senza XML), *Da inviare* (file generati e controllati), +*Inviate in attesa*, *Consegnate* (RC, esito EC01, decorrenza termini), *Scartate* e *Mancata consegna*. Sopra, a +destra, il collegamento alle **fatture ricevute da registrare**, **Importa notifiche** e, per chi gestisce i canali, +**Leggi i canali ora**. + +Il pannello ha tre viste: + +- **Emesse**: fatture, note di credito e parcelle verso i clienti; +- **Autofatture**: i documenti TD16-TD29 nati dagli [acquisti](Acquisti) (integrazioni del reverse charge, + servizi e beni dall'estero, estrazione da deposito IVA, splafonamento…), che vanno trasmessi **entro il 15 del + mese successivo**; +- **Da fare**: solo ciò che chiede un intervento, cioè documenti da generare, file da inviare, scartati, non + consegnati e rifiutati. Gli avvisi della Home su fatture scartate o da inviare portano qui. + +Sotto la vista si filtrano **stato** e **periodo** e si cerca per numero, nome del file, identificativo SDI o +controparte. + +### Documenti da generare + +La prima tabella elenca i documenti confermati che non hanno ancora un file. Si selezionano e si preme **Genera + +invia**; **Controlla senza generare** (icona a forma di scudo) prova il file senza salvarlo e mostra gli errori, +utile per sistemare i dati prima di trasmettere. + +![Khaemhat 0.9.0 · il controllo di un documento prima della generazione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-controllo.png) +*Khaemhat 0.9.0 — Controlla senza generare: il file supera i controlli dello SDI.* + +### File trasmessi + +La seconda tabella ha un file per riga: nome (`IT01234567890_0000A.xml`), documento, cliente, data, totale, tipo +documento, **canale**, **stato SDI** e **ultima notifica o errore** con la data. I file *Generata* hanno la casella +per **Invia (n)**. Le azioni della riga: + +| Azione | Quando | Cosa fa | +|---|---|---| +| **Correggi** | file scartato | apre il documento, che torna modificabile; dopo la correzione si genera un **nuovo file** con un nuovo progressivo, il vecchio resta nello storico come *sostituito* | +| **Segna come inviata** | file generato | per chi lo ha caricato dal portale *Fatture e Corrispettivi*: si può indicare l'identificativo SDI; le notifiche si importano poi a mano | +| **XML** | sempre | scarica il file trasmesso | +| **Copia di cortesia (PDF)** | sempre | il PDF del documento con il file FatturaPA **allegato dentro il PDF**, da mandare al cliente: non sostituisce l'invio allo SDI | +| **Storico del file** | sempre | tutte le versioni del file con generazione, invio, identificativo SDI e notifiche | + +![Khaemhat 0.9.0 · lo storico di un file scartato e rigenerato](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-storico.png) +*Khaemhat 0.9.0 — lo storico SDI di una fattura: la prima versione scartata con l'errore dello SDI, sostituita da +quella corretta e consegnata.* + +Dopo **Invia** o **Genera + invia** una finestra riassume l'esito file per file: preso in carico da quale canale, +oppure il motivo per cui non è partito. + +![Khaemhat 0.9.0 · l'esito della trasmissione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-esito-invio.png) +*Khaemhat 0.9.0 — esito della trasmissione di due file.* + +![Khaemhat 0.9.0 · la vista Da fare](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-da-fare.png) +*Khaemhat 0.9.0 — la vista Da fare: documenti da generare e file scartati o non consegnati.* + +## Il file FatturaPA | Formato | Uso | |---|---| | `FPR12` | fatture verso privati (aziende e consumatori) | -| `FPA12` | fatture verso la Pubblica Amministrazione | +| `FPA12` | fatture verso la pubblica amministrazione | | `FSM10` | fattura semplificata | -Khaemhat segue le **specifiche tecniche dell'Agenzia delle Entrate**: alla stesura di questa pagina la **versione -1.9, in vigore dal 1° aprile 2025** (con il tipo documento TD29 e il TD20 ridefinito). La versione supportata è -indicata nel programma; prima di ogni rilascio va **sempre verificata l'ultima versione pubblicata** dall'Agenzia. +Khaemhat segue le **specifiche tecniche 1.9.1** dell'Agenzia delle Entrate (tipi documento fino a TD29). La +versione è scritta nel pacchetto fiscale italiano; prima di ogni rilascio va confrontata con l'ultima pubblicata +dall'Agenzia. -L'XML contiene, fra l'altro: dati di trasmissione, cedente e cessionario, dati generali con tipo documento (TD), -ritenuta, bollo, cassa previdenziale, sconti e causale; riferimenti a ordine d'acquisto, contratto, convenzione, -ricezione e fatture collegate (con CIG e CUP per la PA); DDT, trasporto, righe di dettaglio, riepilogo IVA, -pagamento e allegati. +Il file contiene i dati di trasmissione, cedente e cessionario (con stabile organizzazione e rappresentante fiscale +quando servono), i dati generali con tipo documento, ritenute, bollo virtuale, cassa previdenziale, sconti e +causale, i riferimenti a ordine, contratto, convenzione, ricezione e fatture collegate (con CIG e CUP per la PA), +DDT e trasporto, le righe, il riepilogo IVA con nature ed esigibilità, i pagamenti e gli allegati. -**Nome del file**: `IT_.xml`, con progressivo alfanumerico -univoco in base 36 (es. `IT01234567890_00A1Z.xml`). +**Nome del file**: `IT` + identificativo fiscale del trasmittente + `_` + progressivo di cinque caratteri in base 36 +(per esempio `IT01234567890_0000A.xml`). Il progressivo non si ripete mai: un file rigenerato dopo uno scarto ne +prende uno nuovo. -## Validazione e scarti noti +### I controlli prima dell'invio -Prima dell'invio il validatore controlla: +Il file viene controllato **prima** di partire, con gli stessi codici di errore dello SDI, così il messaggio è +quello che si leggerebbe nello scarto: -- valori ammessi delle code list (TD, nature, modalità di pagamento, regime fiscale…) e lunghezze dei campi; -- totali coerenti con tolleranza di ± 0,01; -- **nature IVA** (`N1`…`N7` con sotto-codici) e relativi riferimenti normativi; -- codice destinatario o PEC del cliente; per la **PA** codice IPA a 6 caratteri, CIG e CUP quando servono; -- codice fiscale dei gruppi IVA; -- bollo virtuale. +- **struttura** del file contro lo schema del formato; +- **totali**: `PrezzoTotale` e imposta con tolleranza di un centesimo, imponibile del riepilogo con tolleranza di un + euro (00421, 00422, 00423); +- **riepilogo IVA** presente per ogni aliquota e natura (00419); +- **nature IVA** e aliquote su righe, cassa previdenziale e riepilogo (00400, 00401, 00413, 00414, 00429, 00430), + con i sotto-codici obbligatori al posto delle nature generiche N2, N3 e N6 (00445); +- **ritenute** (00411, 00415) e **sconti e maggiorazioni** (00437, 00438); +- **cliente**: partita IVA o codice fiscale presenti e ben formati (00305, 00306, 00417), codice destinatario e PEC + coerenti con il formato (00311, 00426, 00427); +- **autofatture**: cedente e cessionario devono essere diversi o uguali secondo il tipo (00471, 00472, 00473). -Esempi di scarto dello SDI visti nel cruscotto e usati nei test: **00311** (CodiceDestinatario non valido), -**00423** (PrezzoTotale non calcolato correttamente), **00327**. Il messaggio dell'errore compare nella colonna -*Ultima notifica / errore*. +Alcuni controlli richiedono i registri dell'Agenzia (partita IVA esistente, codice destinatario accreditato, codice +IPA presente nell'indice delle PA): Khaemhat ne verifica solo la **forma**. -## I quattro canali di trasmissione +> Lo schema usato per il controllo della struttura è scritto per Khaemhat sulle regole del formato 1.2: non è il file +> XSD ufficiale dell'Agenzia, che non è incluso. Gli scarti più comuni sono comunque coperti dai controlli di +> contenuto. -Tutti i canali hanno la stessa interfaccia (invia, stato, notifiche, scarica passive): cambiare canale non cambia il -modo di lavorare. +## Le notifiche dello SDI -| Canale | Come funziona | Pro | Contro | -|---|---|---|---| -| **PEC integrata** | l'XML parte come allegato dalla **PEC aziendale** (SMTP) verso la PEC dello SDI; notifiche e fatture passive si leggono dalla stessa casella con il client **IMAP** interno, filtrando per mittente e oggetto e archiviando in una cartella | nessun servizio esterno, nessun accreditamento, costo della sola casella PEC | più lento; i volumi elevati vanno distribuiti (regola di *throttling*); dipende dalla disponibilità della casella; non include la conservazione | -| **SdICoop** | web service dell'Agenzia; richiede l'**accreditamento** e un **certificato** rilasciato all'azienda; Khaemhat costruisce la chiamata SOAP con certificato client | notifiche e fatture passive in tempo reale; adatto ai volumi alti | procedura di accreditamento; certificato da rinnovare (il mockup ne mostra la scadenza); per ricevere, lo SDI deve raggiungere un servizio dell'azienda: i requisiti di rete saranno verificati in sviluppo | -| **Intermediario A** | connettore REST verso il servizio di un intermediario accreditato: upload dell'XML, stato, notifiche, download delle passive | semplice da attivare; la **conservazione a norma** può essere inclusa nel servizio | costo del servizio; dipendenza da un terzo; credenziali e token API con scadenza | -| **Intermediario B** | secondo connettore REST, stessa interfaccia, con la propria mappatura di stati ed errori | alternativa o riserva al primo | come l'intermediario A | +![Khaemhat 0.9.0 · elenco delle notifiche SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-notifiche.png) +*Khaemhat 0.9.0 — Notifiche SDI: ogni ricevuta con il file a cui si riferisce, scaricabile così come è arrivata.* -Gli intermediari A e B sono i due servizi scelti dal titolare del progetto; le credenziali sono conservate cifrate. +| Sigla | Notifica | Effetto | +|---|---|---| +| **RC** | ricevuta di consegna | *Consegnata* | +| **NS** | notifica di scarto, con codice e descrizione degli errori | *Scartata*: correggi e rigenera; l'Agenzia indica di ritrasmettere entro 5 giorni | +| **MC** | mancata consegna | la fattura è emessa ma il cliente la trova nel suo cassetto fiscale: conviene mandargli la **copia di cortesia** | +| **NE** | esito del committente PA: **EC01** accettazione, **EC02** rifiuto | *Accettata* o *Rifiutata*; un rifiuto richiede una nota di credito | +| **DT** | decorrenza termini (PA) | *Decorrenza termini*: vale come consegna | +| **AT** | attestazione di avvenuta trasmissione con impossibilità di recapito (PA) | *Impossibile recapitare* | +| **SE** | scarto dell'esito inviato dal committente PA | conservata fra le notifiche | +| **MT** | file metadati di una fattura ricevuta | tenuto con la fattura in *Fatture ricevute* | -### Configurare il canale PEC +Le notifiche arrivano in tre modi: -1. **Fatturazione elettronica → Canali**, riquadro **PEC · impostazioni**. -2. Inserisci **Casella PEC**, server **SMTP** (es. porta 465) e **IMAP** (es. porta 993), la frequenza del - **Controllo notifiche** (es. ogni 15 minuti) e la **Cartella archivio**. -3. Premi **Prova connessione**, poi **Salva**. Il riquadro del canale mostra casella, ultimo controllo e notifiche lette. +- **dai canali**, con l'attività programmata *Lettura dei canali SDI* (`einvoice.poll`) **ogni 15 minuti**, o subito + con **Leggi i canali ora**; +- **in push da SdICoop**, appena lo SDI le consegna (vedi sotto); +- **a mano** con **Importa notifiche** sul cruscotto: file XML, P7M o lo ZIP scaricato dal portale. La stessa + notifica non viene importata due volte. -Il primo invio via PEC va all'indirizzo `sdi01@pec.fatturapa.it`; con la prima risposta lo SDI indica l'indirizzo -PEC da usare per gli invii successivi. La gestione di questo indirizzo sarà verificata in sviluppo. +Nella pagina **Notifiche SDI** si filtrano periodo (dal 1° gennaio a oggi in partenza) e tipo. Le righe evidenziate +sono notifiche che non corrispondono a nessun file emesso. + +## Fatture ricevute + +![Khaemhat 0.9.0 · fatture ricevute dai fornitori](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-ricevute.png) +*Khaemhat 0.9.0 — Fatture ricevute: le fatture dei fornitori da registrare, con fornitore, numero, totale, tipo, +canale e identificativo SDI.* + +Le fatture dei fornitori arrivano dai canali o si caricano con **Carica file**: XML, **P7M** firmati CAdES (anche +annidati o in base64; l'XML viene estratto dalla busta), il file metadati e lo ZIP del portale. Lo stesso file non +entra due volte (impronta SHA-256). + +| Stato | Significato | +|---|---| +| **Da registrare** | arrivata, da trasformare in fattura di acquisto | +| **Registrata** | diventata una fattura o nota di credito di acquisto: **Apri** la porta al documento | +| **Scartata** | messa da parte a mano (**Ripristina** la riporta indietro) | +| **Illeggibile** | il file non è una FatturaPA leggibile: l'errore è scritto sotto lo stato | + +Si selezionano le fatture e si preme **Registra (n)**, oppure **Registra come fattura di acquisto** sulla riga. +La registrazione usa l'import del ciclo passivo ([Acquisti](Acquisti)): il fornitore si riconosce dalla partita +IVA e, se manca, viene creato; righe, IVA e scadenze vengono dal file. Gli avvisi dell'import compaiono nel messaggio +di esito. + +## I canali di trasmissione + +![Khaemhat 0.9.0 · canali di trasmissione e regole di instradamento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-canali.png) +*Khaemhat 0.9.0 — i quattro canali con il loro stato, le impostazioni del canale scelto e le regole di +instradamento.* + +Tutti i canali fanno le stesse cose (inviare, leggere notifiche e fatture ricevute, provare la connessione): cambiare +canale non cambia il modo di lavorare. Ogni scheda mostra lo stato (*Attivo*, *Configurato · in pausa*, *Non +configurato*), l'ultima prova e l'ultima lettura. Password, chiavi e certificati sono **cifrati** nel database; nel +modulo un campo segreto lasciato vuoto mantiene il valore memorizzato. + +| Canale | Come funziona | Impostazioni | +|---|---|---| +| **PEC** | il file parte come allegato dalla PEC dell'azienda (SMTP) verso lo SDI; ricevute e fatture si leggono dalla stessa casella (IMAP) e i messaggi letti vanno nella cartella di archivio | casella, server e porte SMTP e IMAP, TLS, utente, password, indirizzo PEC dello SDI, cartella di archivio | +| **SdICoop** | web service dell'Agenzia con **certificato client**; lo SDI consegna notifiche e fatture al servizio di ricezione di Khaemhat | indirizzo del servizio, certificato PKCS#12 (`.p12`) con password, chiave di ricezione, ambiente di prova | +| **Intermediario A** | API REST di un intermediario accreditato con **chiave API** | indirizzo del servizio, chiave API, ambiente di prova | +| **Intermediario B** | API REST di un intermediario accreditato con **utente e password** | indirizzo del servizio, utente, password, ambiente di prova | + +Per ogni canale: **Prova connessione**, **Metti in pausa** / **Riprendi** e **Salva**. Gli indirizzi dei servizi +devono essere `https`. + +**PEC.** Il primo invio va all'indirizzo `sdi01@pec.fatturapa.it`; con la prima risposta lo SDI comunica la casella +da usare da lì in poi, che Khaemhat ricorda e mostra nel campo *Indirizzo PEC dello SDI*. La PEC non richiede +accreditamento ma è il canale più lento: per volumi alti conviene una regola che sposti il traffico su un altro +canale. + +Della casella si leggono solo i messaggi dello SDI (mittente `fatturapa.it`); le ricevute di accettazione e consegna +del gestore PEC restano dove sono. Imposta sempre la **cartella di archivio**: i messaggi elaborati vengono spostati +lì. Senza cartella vengono solo segnati come letti, e un messaggio aperto dalla webmail prima della lettura di +Khaemhat verrebbe saltato. + +**SdICoop in ricezione.** Lo SDI chiama il servizio `POST /sdicoop/` di Khaemhat. Il servizio +accetta solo le chiamate con l'intestazione `X-Khaemhat-SdiCoop-Key` uguale alla **chiave di ricezione** del canale. +Il certificato reciproco (mTLS) richiesto dall'Agenzia si configura sul **reverse proxy** davanti a Khaemhat, che +aggiunge l'intestazione: vedi [Installazione con Docker](Installazione-Docker). ### Instradamento -Le **regole di instradamento** decidono quale canale usa ogni documento. Esempio del mockup: +Le regole decidono quale canale usa ogni file. Vale **la prima regola attiva che si applica**, nell'ordine indicato; +il **canale di riserva** si usa se il primo è in pausa, disattivato o non risponde. Senza regole si usa il primo +canale attivo. -| Regola | Canale | Condizione | -|---|---|---| -| Predefinito | PEC | tutti i documenti | -| Clienti PA | SdICoop | cessionario PA (codice IPA) | -| Volumi > 50/giorno | SdICoop | throttling della PEC | -| Conservazione | Intermediario A | pacchetti trimestrali | +| Condizione | Si applica a | +|---|---| +| **Sempre** | tutti i file | +| **Cliente pubblica amministrazione** | i clienti con codice IPA (formato `FPA12`) | +| **Cliente specifico** | il cliente con il codice indicato | +| **Tipo documento** | un tipo (TD01, TD17…) | +| **Volume giornaliero** | i file oltre un numero di invii nella giornata | -Il canale usato è registrato su ogni documento (colonna *Canale* del cruscotto). - -## Notifiche SDI - -| Sigla | Notifica | Effetto in Khaemhat | -|---|---|---| -| **RC** | ricevuta di consegna | stato *Consegnata* | -| **NS** | notifica di scarto | stato *Scartata*, con codice e descrizione dell'errore; la regola predefinita avvisa l'amministrazione ([Automazioni](Automazioni)) | -| **MC** | mancata consegna | la fattura è emessa ma non recapitata: è messa a disposizione del cliente nella sua area riservata dell'Agenzia; conviene inviargli la **copia di cortesia** | -| **NE** | notifica di esito del committente PA (**EC01** accettazione, **EC02** rifiuto) | stato *Accettata* o *Rifiutata* | -| **DT** | decorrenza termini (PA) | nessun esito del committente nei termini previsti | -| **AT** | attestazione di avvenuta trasmissione con impossibilità di recapito (PA) | come la mancata consegna | - -Le notifiche si importano in automatico dal canale (procedura **Import inbox SDI**, pianificata) o con **Importa -notifiche**; restano come allegati del documento ([Allegati e file](Allegati-e-file)). Sono letti anche i -**metadati** che accompagnano le fatture ricevute. - -## Fatture passive - -Le fatture ricevute arrivano dal canale (PEC, SdICoop o intermediario) o si caricano a mano (anche come file -**P7M** firmati CAdES: la firma viene verificata e l'XML estratto). Khaemhat le legge, riconosce il fornitore da -P.IVA o codice fiscale e prepara la **fattura di acquisto in bozza** con mappatura delle righe e confronto con -l'ordine: il dettaglio è nella pagina [Acquisti](Acquisti) (import XML). La vista **Ricevute** del cruscotto elenca -le passive e il loro stato di importazione. - -## Cruscotto SDI - -- **Contatori**: *Da generare* (emesse senza XML), *Da inviare* (XML validati), *Inviate · in attesa*, - *Consegnate* (nell'anno), *Scartate* (da correggere), *Mancata consegna*. -- **Elenco prioritizzato**: prima le scartate, poi le da inviare, poi quelle in attesa. -- **Viste**: **Emesse**, **Ricevute**, **Autofatture**. -- **Azioni**: genera, valida, invia, scarica, **Correggi** e rigenera, **Importa notifiche** e passive. -- In testa: canali attivi e ora dell'ultima sincronizzazione. - -### Autofatture da inviare - -Le autofatture e integrazioni (TD16 reverse charge interno, TD17 servizi dall'estero, TD18 beni intra-UE, TD19, TD20 -e TD29, TD21, TD22/TD23, TD28) nascono da [Acquisti](Acquisti) e compaiono nella vista **Autofatture** fino all'invio. -L'XML va trasmesso **entro il 15 del mese successivo**; Khaemhat mostra un promemoria. - -## Copia di cortesia - -Da ogni fattura si può generare la **copia di cortesia** (PDF + XML in uno ZIP) da inviare al cliente via e-mail o -PEC. Non sostituisce l'invio allo SDI. +Le regole dell'azienda di esempio: PA → PEC; oltre 200 file al giorno → Intermediario A con PEC di riserva; +sempre → PEC con Intermediario A di riserva. Il canale usato resta scritto su ogni file. ## Conservazione -Khaemhat **non è un sistema di conservazione a norma**. Prepara per ogni periodo un **pacchetto di esportazione** -(XML, notifiche e indice) da affidare a un **conservatore** o al servizio messo a disposizione dall'Agenzia delle -Entrate. Se l'intermediario scelto include la conservazione, la regola di instradamento *Conservazione* gli invia i -pacchetti. +![Khaemhat 0.9.0 · pacchetti per la conservazione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/fatturazione-conservazione.png) +*Khaemhat 0.9.0 — la preparazione di un pacchetto e l'elenco di quelli già preparati con l'impronta.* -## Sviluppi futuri +Khaemhat **non è un sistema di conservazione a norma**: prepara il materiale da consegnare al conservatore (o al +servizio gratuito dell'Agenzia). Si sceglie il periodo (in partenza il mese precedente, al massimo due anni) e si +preme **Prepara e scarica**: lo ZIP contiene le cartelle `emesse/`, `ricevute/` e `notifiche/`, l'indice +`indice.csv` con l'impronta SHA-256 di ogni file e un `LEGGIMI.txt`. L'elenco dei pacchetti preparati ricorda +periodo, numero di file, dimensione e impronta dello ZIP. -Il formato europeo **EN 16931 / UBL (Peppol)** è previsto come implementazione successiva della stessa interfaccia -dei formati ([Roadmap](Roadmap)). +## Dati di esempio + +L'azienda di esempio ([Dati di base e di esempio](Dati-di-base-e-esempio)) ha i canali, le tre regole di +instradamento sopra, alcune fatture già trasmesse con ricevute di consegna, +uno scarto (00305) corretto e rigenerato, una mancata consegna e tre fatture di fornitori da registrare. Nessun +dato di esempio raggiunge lo SDI: il canale PEC dell'esempio è configurato ma **in pausa**, con credenziali finte, +e l'Intermediario A è solo abbozzato e disattivato. ## Permessi e licenza -Serve il modulo **EINV**. `sales.invoice.issue` è il permesso di emissione delle fatture (SPEC §7.2); gli altri -codici in testa sono indicativi e saranno fissati in sviluppo. La configurazione dei canali e delle credenziali è -riservata a chi gestisce le impostazioni dell'azienda. +| Permesso | Cosa consente | +|---|---| +| `einvoice.document.read` | cruscotto, storico, download di XML e copia di cortesia, notifiche, conservazione | +| `einvoice.document.send` | generare, inviare, segnare come inviata, importare le notifiche | +| `einvoice.inbox.read` | vedere le fatture ricevute | +| `einvoice.inbox.import` | caricare, registrare, scartare e ripristinare le fatture ricevute | +| `einvoice.channel.manage` | canali, credenziali, regole di instradamento, *Leggi i canali ora* | + +Serve il modulo **EINV**. Le modifiche ai canali e alle regole finiscono nel registro delle modifiche; invii, +notifiche e letture dei canali sono scritti nel [log](Log) dell'applicazione. ## Domande frequenti **Una fattura è scartata per codice destinatario non valido (00311).** Correggi il codice destinatario o la PEC -nella scheda fiscale del cliente ([Anagrafiche](Anagrafiche)), poi **Correggi** nel cruscotto e reinvia. Secondo le -indicazioni dell'Agenzia la fattura corretta va ritrasmessa entro 5 giorni dallo scarto. +nella scheda del cliente ([Anagrafiche](Anagrafiche)), poi **Correggi** nel cruscotto, salva il documento e genera +di nuovo il file. Secondo l'Agenzia la fattura corretta va ritrasmessa entro 5 giorni dallo scarto, con lo stesso +numero e la stessa data. -**Posso usare più canali insieme?** Sì: le regole di instradamento scelgono il canale per ogni documento. +**Ho inviato la fattura dal portale dell'Agenzia.** Usa **Segna come inviata** con l'identificativo SDI e poi +**Importa notifiche** con le ricevute scaricate dal portale. -**Dove trovo la ricevuta di consegna?** Fra gli allegati della fattura e nella voce **Notifiche**. +**Posso usare più canali insieme?** Sì: le regole di instradamento scelgono il canale per ogni file e il canale di +riserva interviene se il primo non risponde. + +**Il cliente non ha ricevuto la fattura (MC).** È comunque emessa: la trova nel suo cassetto fiscale. Mandagli la +**copia di cortesia** dal cruscotto. + +**Una PA ha rifiutato la fattura (EC02).** La fattura resta emessa: va stornata con una nota di credito +([Vendite](Vendite)). ## Pagine correlate diff --git a/docs/wiki/Fiscalita-italiana.md b/docs/wiki/Fiscalita-italiana.md index 41aee9d..8349435 100644 --- a/docs/wiki/Fiscalita-italiana.md +++ b/docs/wiki/Fiscalita-italiana.md @@ -1,7 +1,7 @@ # Fiscalità italiana -> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7) -> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14, ADR 0036, ADR 0037, ADR 0038 +> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) +> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14, ADR 0036, ADR 0037, ADR 0038, ADR 0039 Questa pagina raccoglie in un solo posto i **codici e le regole fiscali italiane** che Khaemhat usa: tipi documento SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, il **piano dei conti modello**, i **codici @@ -16,14 +16,15 @@ fa fede il testo mostrato dal programma, non questa pagina. > **In questa versione** sono in uso i codici dei documenti, delle nature, dei pagamenti e dei regimi (dalla 0.4), > e con la 0.7 il piano dei conti *PMI standard*, i registri IVA, le regole della liquidazione e dell'acconto, i -> codici tributo e le scadenze dell'F24, il tracciato LIPE, le ritenute d'acconto e il bollo virtuale. Le parti su -> notifiche SDI, dichiarazioni d'intento, Intrastat e cespiti descrivono regole che il programma userà con la -> [Fatturazione elettronica](Fatturazione-elettronica) (M9) e con [Cespiti](Cespiti) e [Intrastat](Intrastat) (M10). +> codici tributo e le scadenze dell'F24, il tracciato LIPE, le ritenute d'acconto e il bollo virtuale. Con la 0.9 il +> file FatturaPA e le notifiche SDI sono in uso nella [Fatturazione elettronica](Fatturazione-elettronica). Le parti +> su dichiarazioni d'intento, Intrastat e cespiti descrivono regole che il programma userà con [IVA](IVA), +> [Cespiti](Cespiti) e [Intrastat](Intrastat) (M10). > **Attenzione.** Khaemhat calcola e prepara i dati (F24, LIPE, Certificazione Unica, bollo) ma **non sostituisce il > commercialista** né invia F24, LIPE e CU: l'invio telematico avviene con i servizi dell'Agenzia delle Entrate, > l'home banking o l'intermediario, come ricordato nelle maschere. Le norme cambiano: la versione delle specifiche SDI -> supportata è indicata nel programma ed è verificata a ogni rilascio. +> supportata (oggi la 1.9.1) è scritta nel pacchetto fiscale ed è verificata a ogni rilascio. ## Dove si trovano questi codici nel programma @@ -178,6 +179,9 @@ fatture passive. Il codice RF03 non esiste più nelle specifiche correnti. | MC | Mancata consegna | fattura **non consegnata**: messa a disposizione nell'area riservata del cliente | | NE | Notifica di esito (PA: EC01 accettazione, EC02 rifiuto) | esito del committente pubblico | | DT | Decorrenza termini | la PA non ha risposto nei termini | +| AT | Attestazione di avvenuta trasmissione con impossibilità di recapito (PA) | fattura **impossibile da recapitare** | + +Il dettaglio di come Khaemhat usa ogni notifica è nella pagina [Fatturazione elettronica](Fatturazione-elettronica#le-notifiche-dello-sdi). | AT | Attestazione di avvenuta trasmissione con impossibilità di recapito | come mancata consegna, per la PA | I dettagli operativi sono in [Fatturazione-elettronica](Fatturazione-elettronica). @@ -328,8 +332,9 @@ si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermedia ## Domande frequenti -**Dove vedo la versione delle specifiche SDI supportata?** In **Amministrazione → Stato sistema** e nel cruscotto -SDI: è registrata nel programma e aggiornata con i rilasci. +**Quale versione delle specifiche SDI segue Khaemhat?** La 1.9.1 (in Khaemhat 0.9.0): è scritta nel pacchetto +fiscale, riportata nelle note di ogni rilascio e aggiornata quando l'Agenzia pubblica una nuova versione. La pagina +*Stato sistema* la mostrerà con le pagine di amministrazione (M12). **Una natura o un codice non c'è nella tabella.** Lancia **Aggiorna tabelle di base**: il pacchetto dati porta i codici correnti. Se manca ancora, segnalalo: le code list sono parte del pacchetto fiscale italiano. diff --git a/docs/wiki/Guida-utente.md b/docs/wiki/Guida-utente.md index 343a6f6..25cc861 100644 --- a/docs/wiki/Guida-utente.md +++ b/docs/wiki/Guida-utente.md @@ -1,6 +1,6 @@ # Guida all'uso -> **Stato:** completa per la versione 0.8 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.8.0 (M8) +> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) Questa pagina accompagna chi usa Khaemhat ogni giorno: dall'accesso alla fattura inviata al cliente, un passo per volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina che lo spiega per intero. Chi deve @@ -9,20 +9,20 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c ## Che cosa c'è in questa versione -| Area | In 0.8.0 | Arriva con | +| Area | In 0.9.0 | Arriva con | |---|---|---| | Accesso e sicurezza | password, verifica in due passaggi, codici di recupero, blocco dopo i tentativi sbagliati | — | | Interfaccia | menu, schede, ricerca globale, notifiche, aiuto F1, dashboard a widget, temi e colori | — | | Tabelle azienda | profilo azienda, esercizi, cambi, codici IVA, pagamenti, banche, depositi, tipi documento, numeratori e le altre tabelle di base | — | | Anagrafiche | clienti, fornitori, contatti, controlli di partita IVA e codice fiscale, VIES | CRM (lead, opportunità): M11 | | Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente, costo medio e ultimo costo dai movimenti | — | -| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail, scarico del magazzino e impegno, registrazione contabile automatica, incassi dallo scadenzario | XML SDI M9 | -| Acquisti | ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, controllo dei prezzi, import delle fatture elettroniche XML/P7M/ZIP, autofatture e integrazioni in bozza con scadenza, registrazione contabile e registri IVA, pagamenti dallo scadenzario | XML delle autofatture M9 | +| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail, scarico del magazzino e impegno, registrazione contabile automatica, incassi dallo scadenzario, file FatturaPA e invio allo SDI | — | +| Acquisti | ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, controllo dei prezzi, import delle fatture elettroniche XML/P7M/ZIP, autofatture e integrazioni in bozza con scadenza, registrazione contabile e registri IVA, pagamenti dallo scadenzario, file e invio delle autofatture | — | | Magazzino | giacenze per deposito, impegnato e ordinato, costo medio, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione | scritture delle rimanenze e libro inventari con la chiusura dell'esercizio M10 | | Contabilità | piano dei conti, causali, prima nota, contabilizzazione automatica dei documenti, registrazioni ricorrenti e definitive, partitari, mastrini, bilancio di verifica, libro giornale | chiusura dell'esercizio, bilancio CEE e cespiti M10 | | IVA | registri IVA, liquidazione con F24, acconto, file LIPE, ritenute d'acconto con prospetto F24 e dati CU, bollo virtuale | dichiarazioni d'intento M10 | | Scadenzario | partite aperte con aging, incassi e pagamenti, distinte RiBa/SDD/bonifici SEPA con insoluti, mandati SDD, riconciliazione bancaria CSV/CBI/CAMT.053, solleciti con interessi di mora, flusso di cassa | collegamento diretto con la banca e report di tesoreria M12 | -| Fatturazione elettronica | — | M9 | +| Fatturazione elettronica | file FatturaPA con controllo prima dell'invio, canali PEC, SdICoop e due intermediari con instradamento, notifiche, correzione degli scarti, copia di cortesia, fatture ricevute da registrare, pacchetti per la conservazione | dichiarazioni d'intento M10, formato europeo UBL più avanti | | Import ed export | clienti, fornitori, articoli, prezzi e giacenze iniziali da CSV, Excel e JSON; esportazione dai radar | import del piano dei conti: più avanti | | Amministrazione da interfaccia | utenti e licenze da variabili e riga di comando | pagine di amministrazione: M12 | diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 73c35f8..2f1b24c 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -1,6 +1,6 @@ # Khaemhat -> **Stato:** completa per 0.8.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.8.0 (M8; sviluppo in corso) +> **Stato:** completa per 0.9.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9; sviluppo in corso) ![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png) diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index a34a825..da5c07b 100644 --- a/docs/wiki/Roadmap.md +++ b/docs/wiki/Roadmap.md @@ -13,7 +13,7 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo quando verrà deciso esplicitamente. -**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0), M7 (0.7.0), M8 (0.8.0). **Prossima:** M9. +**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0), M7 (0.7.0), M8 (0.8.0), M9 (0.9.0). **Prossima:** M10. | # | Milestone | Contenuto principale | Versione | |---|---|---|---| diff --git a/docs/wiki/Vendite.md b/docs/wiki/Vendite.md index 6813c31..66ced6f 100644 --- a/docs/wiki/Vendite.md +++ b/docs/wiki/Vendite.md @@ -12,8 +12,8 @@ e si inviano per e-mail. > riga per riga, stampa ed e-mail. Dalla 0.6 i documenti **muovono il magazzino** (DDT e fatture > accompagnatorie scaricano, gli ordini impegnano: vedi [Magazzino](Magazzino)). Dalla 0.7 fatture e note > **si contabilizzano** da sole (vedi [Contabilità](Contabilita)). Dalla 0.8 gli **incassi** si registrano dallo [Scadenzario](Scadenzario). -> Arrivano più avanti: il controllo del fido, il **file XML** per lo -> SDI (M9) e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la +> Dalla 0.9 le fatture emesse diventano **file FatturaPA** e si trasmettono allo SDI dalla +> [Fatturazione elettronica](Fatturazione-elettronica). Arrivano più avanti: il controllo del fido e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la > funzione c'è. ## Dove si trova @@ -277,7 +277,7 @@ Le autofatture e le integrazioni (TD16-TD29) sono negli [Acquisti](Acquisti). L' |---|---| | **Bozza** | modificabile | | **Emessa** | numerata e immutabile | -| **XML generato**, **Inviata allo SdI**, **Consegnata**, **Scartata**, **Non consegnata** | gli stati della fatturazione elettronica (M9) | +| **XML generato**, **Inviata allo SdI**, **Consegnata**, **Scartata**, **Non consegnata** | gli stati della [fatturazione elettronica](Fatturazione-elettronica) | Che cosa si può fare: diff --git a/docs/wiki/img/fatturazione-canali.png b/docs/wiki/img/fatturazione-canali.png new file mode 100644 index 0000000..a15c73a Binary files /dev/null and b/docs/wiki/img/fatturazione-canali.png differ diff --git a/docs/wiki/img/fatturazione-conservazione.png b/docs/wiki/img/fatturazione-conservazione.png new file mode 100644 index 0000000..d51a4ae Binary files /dev/null and b/docs/wiki/img/fatturazione-conservazione.png differ diff --git a/docs/wiki/img/fatturazione-controllo.png b/docs/wiki/img/fatturazione-controllo.png new file mode 100644 index 0000000..933cc3f Binary files /dev/null and b/docs/wiki/img/fatturazione-controllo.png differ diff --git a/docs/wiki/img/fatturazione-cruscotto.png b/docs/wiki/img/fatturazione-cruscotto.png new file mode 100644 index 0000000..b0dc7a2 Binary files /dev/null and b/docs/wiki/img/fatturazione-cruscotto.png differ diff --git a/docs/wiki/img/fatturazione-da-fare.png b/docs/wiki/img/fatturazione-da-fare.png new file mode 100644 index 0000000..c01df2d Binary files /dev/null and b/docs/wiki/img/fatturazione-da-fare.png differ diff --git a/docs/wiki/img/fatturazione-esito-invio.png b/docs/wiki/img/fatturazione-esito-invio.png new file mode 100644 index 0000000..3019830 Binary files /dev/null and b/docs/wiki/img/fatturazione-esito-invio.png differ diff --git a/docs/wiki/img/fatturazione-notifiche.png b/docs/wiki/img/fatturazione-notifiche.png new file mode 100644 index 0000000..ab94604 Binary files /dev/null and b/docs/wiki/img/fatturazione-notifiche.png differ diff --git a/docs/wiki/img/fatturazione-ricevute.png b/docs/wiki/img/fatturazione-ricevute.png new file mode 100644 index 0000000..c24bcab Binary files /dev/null and b/docs/wiki/img/fatturazione-ricevute.png differ diff --git a/docs/wiki/img/fatturazione-storico.png b/docs/wiki/img/fatturazione-storico.png new file mode 100644 index 0000000..d9a4c62 Binary files /dev/null and b/docs/wiki/img/fatturazione-storico.png differ diff --git a/scripts/seed.sh b/scripts/seed.sh index bb82fdc..272a1c4 100755 --- a/scripts/seed.sh +++ b/scripts/seed.sh @@ -3,6 +3,7 @@ # tables still empty (--scale N repeats the demo catalogues N times). Rows already there are never changed. # scripts/seed.sh --base [--company CODE] # scripts/seed.sh --demo [--scale N] [--company CODE] +# scripts/seed.sh --remove-demo [--company CODE] removes only the rows marked demo (and what belongs to them) # In the container (shipped as /app/scripts/seed.sh, same KHAEMHAT_* variables as the service): # docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base # On a development machine it runs the project with the variables already set in the shell (see scripts/run-dev.sh). diff --git a/src/Khaemhat.Application/Audit/AuditTrail.cs b/src/Khaemhat.Application/Audit/AuditTrail.cs index dd024d8..16bd38e 100644 --- a/src/Khaemhat.Application/Audit/AuditTrail.cs +++ b/src/Khaemhat.Application/Audit/AuditTrail.cs @@ -33,6 +33,7 @@ public sealed class AuditTrail(TimeProvider clock) { nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion", "PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString", + "ProtectedPassword", "ProtectedCertificate", "ProtectedCertificatePassword", "ProtectedApiKey", "Content", "Metadata", }; /// Writes the history row of a change, inside the caller's unit of work. diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index 97c8cc2..4acf027 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -451,6 +451,48 @@ public sealed partial class DocumentEngine }, null, cancellationToken); } + /// + /// Moves a document along the steps of the electronic invoice inside the transaction of the caller (the e-invoice + /// service and its jobs, ADR 0039), which has already checked the permission. Steps the state does not allow are + /// skipped: a late or repeated notification never fails. + /// + /// The open unit of work. + /// The family. + /// The document. + /// The steps, in order, from the state the document is in. + /// Who, for the history. + /// Cancellation. + /// The state reached, or when the document does not exist. + internal async Task AdvanceExchangeAsync( + IUnitOfWork uow, DocumentFamily family, long id, Func> steps, string userName, CancellationToken cancellationToken) + { + var store = DocumentStores.Of(family); + var header = await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false); + if (header is null) + { + return null; + } + + var lifecycle = DocumentBehaviors.Of(header.Kind).Lifecycle; + var old = header.Clone(); + foreach (var step in steps(header.Status)) + { + if (DocumentStateMachine.Allows(lifecycle, header.Status, step)) + { + header.Status = DocumentStateMachine.Apply(lifecycle, header.Status, step); + header.XmlGenerated |= step == DocumentAction.GenerateXml; + } + } + + if (header.Status != old.Status || header.XmlGenerated != old.XmlGenerated) + { + await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false); + await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, header, userName, cancellationToken).ConfigureAwait(false); + } + + return header.Status; + } + /// Records that the document was printed (its PDF kept among the attachments); the state does not change. /// Who prints: needs to read the document. /// The company. diff --git a/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs index b9bf3b8..6f0b0e4 100644 --- a/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs +++ b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs @@ -52,7 +52,24 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment { ArgumentNullException.ThrowIfNull(context); var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false); - await WriteAsync(model, context, output, cancellationToken).ConfigureAwait(false); + await WriteAsync(model, context, output, [], cancellationToken).ConfigureAwait(false); + } + + /// + /// The courtesy copy of an e-invoice (SPEC §11.9, issue #79): the print of the document with the XML sent to the + /// exchange system embedded as an associated file (structure of PDF/A-3, /AF). + /// + /// The document. + /// The name of the XML file. + /// The XML file. + /// The stream that receives the PDF. + /// Cancellation. + /// A task. + public async Task CourtesyCopyAsync(FileGenerationContext context, string xmlName, byte[] xml, Stream output, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false); + await WriteAsync(model, context, output, [(xmlName, xml)], cancellationToken).ConfigureAwait(false); } // The file name follows the document (number and kind); without the logo, which the name does not need. @@ -95,7 +112,8 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment } } - private static async Task WriteAsync(DocumentPrintModel model, FileGenerationContext context, Stream output, CancellationToken cancellationToken) + private static async Task WriteAsync( + DocumentPrintModel model, FileGenerationContext context, Stream output, IReadOnlyList<(string Name, byte[] Content)> embedded, CancellationToken cancellationToken) { var info = new PdfDocumentInfo { @@ -111,6 +129,11 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment await sheet.LinesAsync().ConfigureAwait(false); await sheet.FooterBlocksAsync().ConfigureAwait(false); sheet.Finish(); + foreach (var (name, content) in embedded) + { + pdf.AddAttachment(name, "application/xml", content, "Fattura elettronica " + model.Number, "Source"); + } + await pdf.CloseAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs b/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs new file mode 100644 index 0000000..785f1b7 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs @@ -0,0 +1,194 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.EInvoicing; + +/// A conservation package made. +/// The row that records it. +/// The ZIP. +public sealed record ConservationPackage(ConservationExport Export, byte[] Content); + +/// +/// The package for the conservation of the e-invoices of a period (issue #79): a ZIP with the files sent +/// (emesse/), their notifications (notifiche/) and the files received (ricevute/), each as it +/// travelled, an index indice.csv with the SHA-256 of every file and a LEGGIMI.txt. It is what a +/// conservation service (or the free service of the AdE) takes in; Khaemhat does not replace the conservation itself. +/// +/// Permission: einvoice.document.read. Every package made is recorded with its hash. +public sealed class ConservationExportService +{ + private static readonly DateTimeOffset Stamp = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The clock. + public ConservationExportService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _clock = clock; + } + + /// The packages made, newest first. + /// Who looks: needs einvoice.document.read. + /// The company. + /// Cancellation. + /// The rows. + public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync(Query.For().OrderByDescending(e => e.Id).Take(50), cancellationToken) + .ConfigureAwait(false)).Items; + } + + /// Makes the package of a period: e-invoices sent by date of the document, files received by date of arrival. + /// Who makes it: needs einvoice.document.read. + /// The company. + /// First day. + /// Last day. + /// Cancellation. + /// The package. + public async Task ExportAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + if (to < from || to.DayNumber - from.DayNumber > 731) + { + throw new ValidationFailedException(["To:" + EInvoiceErrors.PeriodInvalid]); + } + + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var sent = (await uow.Repository() + .ListAsync(Query.For().Where(e => e.DocumentDate >= from && e.DocumentDate <= to && e.Status != EInvoiceStatus.Generated).OrderBy(e => e.Progressive), cancellationToken) + .ConfigureAwait(false)).Items; + var notifications = new List(); + foreach (var chunk in sent.Select(e => e.Id).Chunk(500)) + { + var ids = chunk.Select(id => (long?)id).ToList(); + notifications.AddRange((await uow.Repository() + .ListAsync(Query.For().Where(n => ids.Contains(n.EInvoiceId)).OrderBy(n => n.ReceivedAt), cancellationToken) + .ConfigureAwait(false)).Items); + } + + var start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var received = (await uow.Repository() + .ListAsync(Query.For().Where(f => f.ReceivedAt >= start && f.ReceivedAt < end && f.Status != InboxFileStatus.Discarded).OrderBy(f => f.ReceivedAt), cancellationToken) + .ConfigureAwait(false)).Items; + + var index = new StringBuilder("cartella;file;tipo;documento;data;controparte;identificativo_sdi;stato;sha256\r\n"); + var count = 0; + using var buffer = new MemoryStream(); + using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + void Add(string folder, string name, byte[] content, string kind, string? number, string? date, string? party, string? exchange, string state) + { + var path = Unique(names, folder + "/" + Path.GetFileName(name)); + var entry = zip.CreateEntry(path, CompressionLevel.Optimal); + entry.LastWriteTime = Stamp; + using (var stream = entry.Open()) + { + stream.Write(content); + } + + index.Append(string.Join(';', folder, Csv(Path.GetFileName(path)), kind, Csv(number), date, Csv(party), Csv(exchange), state, EInvoiceStore.Hash(content))).Append("\r\n"); + count++; + } + + foreach (var e in sent) + { + Add("emesse", e.FileName, e.Content, e.DocumentType, e.DocumentNumber, Date(e.DocumentDate), e.RecipientCode, e.ExchangeId, e.Status.ToString()); + } + + foreach (var n in notifications) + { + Add("notifiche", n.FileName, n.Content, n.Code, n.InvoiceFileName, Date(DateOnly.FromDateTime(n.ReceivedAt)), null, n.ExchangeId, n.Outcome ?? string.Empty); + } + + foreach (var f in received) + { + Add("ricevute", f.FileName, f.Content, f.DocumentType ?? string.Empty, f.Number, f.DocumentDate is { } d ? Date(d) : null, f.SupplierName, f.ExchangeId, f.Status.ToString()); + if (f.Metadata is { Length: > 0 } metadata && f.MetadataFileName is { } metadataName) + { + Add("ricevute", metadataName, metadata, "MT", f.Number, null, f.SupplierName, f.ExchangeId, string.Empty); + } + } + + Write(zip, "indice.csv", Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(index.ToString())).ToArray()); + Write(zip, "LEGGIMI.txt", Encoding.UTF8.GetBytes(Readme(company, from, to, sent.Count, notifications.Count, received.Count))); + } + + var content = buffer.ToArray(); + var fileName = string.Create(CultureInfo.InvariantCulture, $"conservazione-{company}-{from:yyyyMMdd}-{to:yyyyMMdd}.zip"); + var export = new ConservationExport + { + FromDate = from, + ToDate = to, + FileCount = count, + FileName = fileName, + Hash = EInvoiceStore.Hash(content), + Size = content.LongLength, + }; + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + export.Id = await uow.Repository().InsertAsync(export, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return new ConservationPackage(export, content); + } + + private static void Write(ZipArchive zip, string name, byte[] content) + { + var entry = zip.CreateEntry(name, CompressionLevel.Optimal); + entry.LastWriteTime = Stamp; + using var stream = entry.Open(); + stream.Write(content); + } + + private static string Unique(HashSet names, string path) + { + var candidate = path; + for (var i = 2; !names.Add(candidate); i++) + { + candidate = Path.ChangeExtension(path, null) + "-" + i.ToString(CultureInfo.InvariantCulture) + Path.GetExtension(path); + } + + return candidate; + } + + private static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + + private static string Csv(string? value) => + string.IsNullOrEmpty(value) ? string.Empty : value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; + + private string Readme(string company, DateOnly from, DateOnly to, int sent, int notifications, int received) => + string.Create(CultureInfo.InvariantCulture, $""" + Khaemhat - pacchetto per la conservazione delle fatture elettroniche + Azienda: {company} + Periodo: dal {from:dd/MM/yyyy} al {to:dd/MM/yyyy} + Creato il: {_clock.GetUtcNow():yyyy-MM-dd HH:mm} UTC + + emesse/ {sent} fatture inviate al SDI, nel formato in cui sono state trasmesse + notifiche/ {notifications} ricevute e notifiche del SDI relative alle fatture emesse + ricevute/ {received} fatture ricevute dai fornitori, con i file metadati (MT) + indice.csv l'elenco dei file con l'impronta SHA-256 di ciascuno + + I file sono quelli originali: nessuno è stato modificato. Il pacchetto va consegnato al servizio di + conservazione (ad esempio il servizio gratuito dell'Agenzia delle Entrate o un conservatore accreditato); + Khaemhat non sostituisce la conservazione a norma. + """); +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs new file mode 100644 index 0000000..9ad1eaf --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs @@ -0,0 +1,553 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Tax; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.EInvoicing; + +/// +/// Turns a document into the model of the e-invoice (SPEC §11.9, ADR 0039): the company and the customer (or the +/// supplier and the company for a self-invoice), the lines with their codes, units and discounts, the summary by rate +/// and nature, stamp duty, withholding, social security fund, the documents referred to (order with CIG and CUP, +/// delivery notes, the invoice a credit note corrects) and the installments. +/// +/// +/// Amounts follow the document as computed by Khaemhat: a footer discount becomes one discount line (SC) +/// per rate, prices that include tax are taken back to their taxable amount, what is left by rounding goes in +/// Arrotondamento of the summary. A stamp duty charged to the customer is a line excluded from VAT (N1). +/// The file name is not set here: the service gives it with the progressive. +/// +internal static class EInvoiceBuilder +{ + /// The country code of foreign customers without a VAT number (FatturaPA: eleven nines). + public const string NoVatNumber = "99999999999"; + + /// The recipient code of a foreign customer. + public const string ForeignRecipient = "XXXXXXX"; + + /// The recipient code when the file goes to a certified mailbox or to the tax drawer. + public const string NoRecipient = "0000000"; + + /// The type of the format of a document: the one of its document type, otherwise the default of its kind. + /// The kind. + /// The document type. + /// The type (TD01 …), or when the kind has no e-invoice. + public static string? DocumentTypeOf(DocumentKind kind, DocumentType? type) + { + if (!string.IsNullOrWhiteSpace(type?.EInvoiceType)) + { + return type.EInvoiceType.Trim().ToUpperInvariant(); + } + + return kind switch + { + DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice => "TD01", + DocumentKind.DeferredInvoice => "TD24", + DocumentKind.DownPaymentInvoice => "TD02", + DocumentKind.CreditNote => "TD04", + DocumentKind.DebitNote => "TD05", + DocumentKind.Fee => "TD06", + DocumentKind.SelfInvoice when type?.Code is { Length: 4 } code && code.StartsWith("AF", StringComparison.OrdinalIgnoreCase) => "TD" + code[2..], + _ => null, + }; + } + + /// Whether a kind of document goes to the exchange system. + /// The kind. + /// for invoices, credit and debit notes, fees and self-invoices. + public static bool IsElectronic(DocumentKind kind) => DocumentBehaviors.Of(kind).Effects.HasFlag(DocumentEffects.EInvoice); + + /// Builds the file of a document. + /// The unit of work of the company. + /// The document, with lines and figures. + /// Cancellation. + /// The model (file name empty), the party and whether it is a public administration. + public static async Task<(EInvoiceFile File, Party Party, bool PublicAdministration)> BuildAsync(IUnitOfWork uow, DocumentRecord record, CancellationToken cancellationToken) + { + var header = record.Header; + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([":" + EInvoiceErrors.CompanyProfileMissing]); + var party = header.PartyId is { } partyId ? await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null; + if (party is null) + { + throw new ValidationFailedException(["PartyId:" + DocumentErrors.PartyRequired]); + } + + var fiscal = await uow.Repository().FindAsync(Query.For().Where(f => f.PartyId == party.Id), cancellationToken).ConfigureAwait(false); + var type = await uow.Repository().GetAsync(header.DocumentTypeId, cancellationToken).ConfigureAwait(false); + var documentType = DocumentTypeOf(header.Kind, type) ?? throw new ValidationFailedException([":" + EInvoiceErrors.NotElectronic]); + var self = header.Kind == DocumentKind.SelfInvoice; + var publicAdministration = !self && party.SubjectType == SubjectType.PublicAdministration; + + var company = CompanyParty(profile); + var counterpart = PartyOf(party, fiscal, self); + var foreign = !string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase); + var (recipientCode, recipientPec) = self + ? ((string Code, string? Pec))(profile.RecipientCode?.Trim().ToUpperInvariant() is { Length: > 0 } own ? own : NoRecipient, null) + : Recipient(party, fiscal, publicAdministration, foreign); + + var body = await BodyAsync(uow, record, documentType, profile, fiscal, cancellationToken).ConfigureAwait(false); + var intermediary = !string.IsNullOrWhiteSpace(profile.IntermediaryTaxCode) + ? new EInvoiceParty("IT", null, profile.IntermediaryTaxCode.Trim().ToUpperInvariant(), profile.IntermediaryName, null, null, + null, null, null, null, null, null, null, null, null, null, null) + : null; + var file = new EInvoiceFile( + string.Empty, + publicAdministration ? "FPA12" : "FPR12", + null, + recipientCode, + self ? counterpart : company, + self ? company with { TaxRegime = null, ReaOffice = null, ReaNumber = null, ShareCapital = null, Shareholders = null, LiquidationStatus = null } : counterpart, + [body], + null, + []) + { + TransmitterCountry = (profile.TransmitterCountry ?? "IT").Trim().ToUpperInvariant(), + TransmitterId = (profile.TransmitterId ?? profile.TaxCode ?? profile.VatNumber)?.Trim().ToUpperInvariant(), + RecipientPec = recipientPec, + Intermediary = intermediary, + IssuedBy = self ? "CC" : intermediary is not null ? "TZ" : null, + }; + return (file, party, publicAdministration); + } + + /// The company as it appears in the file. + /// The profile. + /// The party. + public static EInvoiceParty CompanyParty(CompanyProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + var country = (profile.AddressCountry ?? profile.Country ?? "IT").Trim().ToUpperInvariant(); + return new EInvoiceParty( + (profile.Country ?? "IT").Trim().ToUpperInvariant(), + Digits(profile.VatNumber, profile.Country), + profile.TaxCode?.Trim().ToUpperInvariant(), + profile.LegalName, + null, + null, + profile.Address, + profile.StreetNumber, + profile.PostalCode, + profile.City, + country == "IT" ? profile.ProvinceCode : null, + country, + string.IsNullOrWhiteSpace(profile.TaxRegime) ? "RF01" : profile.TaxRegime, + profile.Email, + profile.Phone, + string.IsNullOrWhiteSpace(profile.ReaNumber) ? null : profile.ReaOffice, + string.IsNullOrWhiteSpace(profile.ReaOffice) ? null : profile.ReaNumber) + { + ShareCapital = profile.ShareCapital, + Shareholders = profile.Shareholders, + LiquidationStatus = string.IsNullOrWhiteSpace(profile.ReaNumber) ? null : profile.LiquidationStatus ?? "LN", + }; + } + + // The customer, or the supplier of a self-invoice. + internal static EInvoiceParty PartyOf(Party party, PartyFiscal? fiscal, bool supplier) + { + var country = (party.CountryCode ?? "IT").Trim().ToUpperInvariant(); + var italian = country == "IT"; + var vat = Digits(party.VatNumber, country); + var taxCode = italian ? party.TaxCode?.Trim().ToUpperInvariant() : null; + if (!italian && vat is null) + { + vat = NoVatNumber; + } + + var person = party.SubjectType == SubjectType.Person && !string.IsNullOrWhiteSpace(party.LastName); + return new EInvoiceParty( + vat is null ? null : country, + vat, + taxCode, + person ? null : party.Name, + person ? party.FirstName : null, + person ? party.LastName : null, + party.Address, + party.StreetNumber, + party.PostalCode, + party.City, + italian ? party.Province : null, + country, + supplier ? (italian ? "RF01" : "RF18") : null, + null, + null, + null, + null) + { + AdministrationReference = supplier ? null : fiscal?.AdministrationReference, + }; + } + + // The recipient: the code of the party, its certified mailbox, the code of foreign customers, or none. + private static (string Code, string? Pec) Recipient(Party party, PartyFiscal? fiscal, bool publicAdministration, bool foreign) + { + var code = fiscal?.RecipientCode?.Trim().ToUpperInvariant(); + if (!string.IsNullOrEmpty(code) && (publicAdministration ? code.Length == 6 : code.Length == 7) && code != NoRecipient) + { + return (code, null); + } + + if (foreign && !publicAdministration) + { + return (ForeignRecipient, null); + } + + var pec = fiscal?.RecipientPec ?? party.Pec; + return (publicAdministration ? code ?? string.Empty : NoRecipient, string.IsNullOrWhiteSpace(pec) || publicAdministration ? null : pec.Trim()); + } + + private static async Task BodyAsync( + IUnitOfWork uow, DocumentRecord record, string documentType, CompanyProfile profile, PartyFiscal? fiscal, CancellationToken cancellationToken) + { + var header = record.Header; + var taxIds = record.Lines.Select(l => l.TaxCodeId).Append(header.SocialSecurityTaxCodeId).OfType().Distinct().ToList(); + var taxCodes = (await uow.Repository().ListAsync(Query.For().Where(t => taxIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false)) + .Items.ToDictionary(t => t.Id); + var unitIds = record.Lines.Select(l => l.UnitOfMeasureId).OfType().Distinct().ToList(); + var units = (await uow.Repository().ListAsync(Query.For().Where(u => unitIds.Contains(u.Id)), cancellationToken).ConfigureAwait(false)) + .Items.ToDictionary(u => u.Id); + var itemIds = record.Lines.Select(l => l.ItemId).OfType().Distinct().ToList(); + var items = itemIds.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id); + + var summary = record.Figures.Summary; + var first = summary.Count > 0 ? summary[0] : null; + var withholding = header.WithholdingRate is > 0m && header.WithholdingAmount != 0m; + var intent = fiscal is { IntentActive: true } && !string.IsNullOrWhiteSpace(fiscal.IntentProtocol); + var lines = new List(); + var sourceLines = new Dictionary(); + foreach (var line in record.Lines.OrderBy(l => l.LineNumber)) + { + var tax = line.TaxCodeId is { } taxId && taxCodes.TryGetValue(taxId, out var code) ? code : null; + var rate = tax?.Rate ?? first?.Rate ?? 0m; + var nature = tax is null ? first?.Nature : tax.Nature; + var number = lines.Count + 1; + var description = string.IsNullOrWhiteSpace(line.Description) ? "-" : line.Description; + if (line.Kind == DocumentLineKind.Description) + { + lines.Add(new EInvoiceLine(number, [], description, null, null, 0m, 0m, rate, rate == 0m ? nature ?? "N2.2" : null, [], false, null, null, null, null)); + continue; + } + + var amount = line.TaxableAmount; + var quantity = line.Quantity; + var price = line.Price; + var discounts = DiscountsOf(line.DiscountFormula); + if (header.PricesIncludeTax && rate != 0m) + { + // The file has taxable amounts: the line becomes its taxable part, discounts included. + amount = Math.Round(amount * 100m / (100m + rate), 2, MidpointRounding.AwayFromZero); + price = quantity == 0m ? amount : Math.Round(amount / quantity, 8, MidpointRounding.AwayFromZero); + discounts = []; + if (quantity < 0m) + { + price = -price; + } + } + + if (quantity < 0m) + { + // A negative quantity (a return on the invoice): the sign goes to the price. + quantity = -quantity; + price = -price; + } + + var lineType = line.Kind switch + { + DocumentLineKind.Discount => "SC", + DocumentLineKind.Expense => "AC", + _ => null, + }; + if (line.Kind == DocumentLineKind.Discount) + { + price = -Math.Abs(amount); + quantity = 0m; + discounts = []; + } + + var codes = line.ItemId is { } itemId && items.TryGetValue(itemId, out var item) ? new[] { new EInvoiceItemCode("INTERNO", item.Code) } : []; + var unit = line.UnitOfMeasureId is { } unitId && units.TryGetValue(unitId, out var uom) ? uom.EInvoiceCode ?? uom.Code : null; + var withheld = withholding && !line.WithholdingExcluded && line.Kind != DocumentLineKind.Discount; + sourceLines[number] = line; + lines.Add(new EInvoiceLine( + number, + codes, + description, + quantity == 0m ? null : quantity, + quantity == 0m ? null : unit, + quantity == 0m ? amount : price, + amount, + rate, + rate == 0m ? nature : null, + discounts, + withheld, + lineType, + null, + null, + fiscal?.AdministrationReference) + { + OtherData = intent && nature == "N3.5" + ? [new EInvoiceOtherData("INTENTO", fiscal!.IntentProtocol, null, fiscal.IntentDate)] + : [], + }); + } + + // The social security fund is part of the taxable of its rate, not of a line. + EInvoiceSocialSecurity? fund = null; + decimal fundRate = 0m; + string? fundNature = null; + if (header.SocialSecurityAmount != 0m && header.SocialSecurityRate is > 0m and var socialRate) + { + var fundTax = header.SocialSecurityTaxCodeId is { } fundTaxId && taxCodes.TryGetValue(fundTaxId, out var ft) ? ft : null; + fundRate = fundTax?.Rate ?? summary.Where(s => s.Rate > 0m).Select(s => s.Rate).FirstOrDefault(); + fundNature = fundTax is null ? (fundRate == 0m ? first?.Nature : null) : fundTax.Nature; + fund = new EInvoiceSocialSecurity( + string.IsNullOrWhiteSpace(header.SocialSecurityFund) ? "TC22" : header.SocialSecurityFund, + socialRate, + header.SocialSecurityAmount, + Math.Round(header.SocialSecurityAmount * 100m / socialRate, 2, MidpointRounding.AwayFromZero), + fundRate, + withholding && header.SocialSecurityWithheld, + fundRate == 0m ? fundNature : null); + } + + // The summary; what the lines do not explain becomes a discount line (footer discount) or the rounding. + var rows = new List(); + foreach (var row in summary) + { + var linesSum = lines.Where(l => l.TaxRate == row.Rate && (row.Rate != 0m || l.Nature == row.Nature)).Sum(l => l.TotalPrice); + var fundPart = fund is not null && fundRate == row.Rate && (row.Rate != 0m || fundNature == row.Nature) ? fund.Amount : 0m; + var rest = row.Taxable - linesSum - fundPart; + decimal? rounding = null; + if (Math.Abs(rest) >= 0.01m && header.FooterDiscountAmount != 0m) + { + lines.Add(new EInvoiceLine( + lines.Count + 1, [], "Sconto di fine documento" + (string.IsNullOrWhiteSpace(header.FooterDiscount) ? string.Empty : " " + header.FooterDiscount + "%"), + null, null, rest, rest, row.Rate, row.Rate == 0m ? row.Nature : null, [], withholding, "SC", null, null, null)); + } + else if (Math.Abs(rest) >= 0.01m) + { + rounding = rest; + } + + rows.Add(new EInvoiceTaxSummary( + row.Rate, + row.Rate == 0m ? row.Nature : null, + row.Taxable, + row.Tax, + row.Rate == 0m ? null : row.Exigibility switch + { + TaxExigibility.Deferred => "D", + TaxExigibility.SplitPayment => "S", + _ => "I", + }, + row.Rate == 0m ? row.LegalReference : null, + null, + rounding)); + } + + // Stamp duty charged to the customer: a line excluded from VAT, and its row in the summary. + if (header.StampDutyCharged && header.StampDuty > 0m) + { + lines.Add(new EInvoiceLine(lines.Count + 1, [], "Imposta di bollo", null, null, header.StampDuty, header.StampDuty, 0m, "N1", [], false, "AC", null, null, null)); + var n1 = rows.FindIndex(r => r.Rate == 0m && r.Nature == "N1"); + rows = n1 < 0 + ? [.. rows, new EInvoiceTaxSummary(0m, "N1", header.StampDuty, 0m, null, "Escluso art. 15 DPR 633/72", null, null)] + : [.. rows.Select((r, i) => i == n1 ? r with { Taxable = r.Taxable + header.StampDuty } : r)]; + } + + var (orders, related, deliveries) = await ReferencesAsync(uow, record, sourceLines, cancellationToken).ConfigureAwait(false); + var payments = await PaymentsAsync(uow, record, profile, cancellationToken).ConfigureAwait(false); + return new EInvoiceBody( + documentType, + header.CurrencyCode, + header.DocumentDate, + header.DocumentNumber ?? string.Empty, + header.TotalAmount, + null, + string.IsNullOrWhiteSpace(header.Notes) ? [] : [header.Notes.Trim()], + false, + withholding + ? [new EInvoiceWithholding(string.IsNullOrWhiteSpace(header.WithholdingType) ? "RT01" : header.WithholdingType, header.WithholdingAmount, header.WithholdingRate!.Value, + string.IsNullOrWhiteSpace(header.WithholdingReason) ? "A" : header.WithholdingReason)] + : [], + header.StampDuty > 0m ? new EInvoiceStampDuty(true, header.StampDuty) : null, + fund is null ? [] : [fund], + [], + orders, + [], + related, + deliveries, + lines, + rows, + payments, + []) + { + Transport = await TransportAsync(uow, header, cancellationToken).ConfigureAwait(false), + PaymentConditions = payments.FirstOrDefault()?.Conditions, + }; + } + + // "10+5" gives two discounts in percent, in order. + private static IReadOnlyList DiscountsOf(string? formula) => + DiscountFormula.TryParse(formula, out var steps) + ? [.. steps.Select(s => s < 0m ? new EInvoiceDiscount(true, -s, null) : new EInvoiceDiscount(false, s, null))] + : []; + + // The order of the customer (with CIG and CUP), the invoice corrected, the delivery notes of the lines. + private static async Task<(List Orders, List Related, List Deliveries)> ReferencesAsync( + IUnitOfWork uow, DocumentRecord record, Dictionary sourceLines, CancellationToken cancellationToken) + { + var header = record.Header; + var orders = new List(); + if (!string.IsNullOrWhiteSpace(header.Cig) || !string.IsNullOrWhiteSpace(header.Cup) || !string.IsNullOrWhiteSpace(header.ExternalReference)) + { + orders.Add(new EInvoiceReference( + string.IsNullOrWhiteSpace(header.ExternalReference) ? header.DocumentNumber : header.ExternalReference.Trim(), + header.ExternalDate, + [], + string.IsNullOrWhiteSpace(header.Cig) ? null : header.Cig.Trim().ToUpperInvariant(), + string.IsNullOrWhiteSpace(header.Cup) ? null : header.Cup.Trim().ToUpperInvariant())); + } + + var related = new List(); + if (!string.IsNullOrWhiteSpace(header.RelatedNumber)) + { + related.Add(new EInvoiceReference(header.RelatedNumber.Trim(), header.RelatedDate, [], null, null)); + } + else if (header.RelatedDocumentId is { } relatedId) + { + // A self-invoice integrates the supplier's invoice: its number is the one of the supplier. + var family = header.Kind == DocumentKind.SelfInvoice ? DocumentFamily.PurchaseDocument : record.Family; + if (await DocumentStores.Of(family).GetAsync(uow, relatedId, cancellationToken).ConfigureAwait(false) is { } other) + { + related.Add(family == DocumentFamily.PurchaseDocument + ? new EInvoiceReference(other.ExternalReference ?? other.DocumentNumber, other.ExternalDate ?? other.DocumentDate, [], null, null) + : new EInvoiceReference(other.DocumentNumber, other.DocumentDate, [], null, null)); + } + } + + var deliveries = new Dictionary Lines)>(); + var store = DocumentStores.Of(DocumentFamily.SaleDocument); + foreach (var (number, line) in sourceLines) + { + if (line.SourceFamily != DocumentFamily.SaleDocument || line.SourceLineId is not { } sourceLineId) + { + continue; + } + + var source = await store.GetLineAsync(uow, sourceLineId, cancellationToken).ConfigureAwait(false); + if (source is null) + { + continue; + } + + if (!deliveries.TryGetValue(source.DocumentId, out var entry)) + { + if (await store.GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false) is not { Kind: DocumentKind.DeliveryNote } note) + { + continue; + } + + entry = (note, []); + deliveries[source.DocumentId] = entry; + } + + entry.Lines.Add(number); + } + + return (orders, related, [.. deliveries.Values.Select(d => new EInvoiceReference(d.Note.DocumentNumber, d.Note.DocumentDate, d.Lines, null, null))]); + } + + // The installments with the method of each; the IBAN of the company for bank transfers. + private static async Task> PaymentsAsync(IUnitOfWork uow, DocumentRecord record, CompanyProfile profile, CancellationToken cancellationToken) + { + var header = record.Header; + var methodIds = record.Figures.Installments.Select(i => i.PaymentMethodId).Append(header.PaymentMethodId).OfType().Distinct().ToList(); + var methods = methodIds.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(m => methodIds.Contains(m.Id)), cancellationToken).ConfigureAwait(false)) + .Items.ToDictionary(m => m.Id); + var bankId = header.BankAccountId ?? profile.DefaultBankAccountId; + var bank = bankId is { } id ? await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) : null; + string? Code(long? methodId) => methodId is { } m && methods.TryGetValue(m, out var method) && !string.IsNullOrWhiteSpace(method.EInvoiceCode) ? method.EInvoiceCode : null; + + var installments = record.Figures.Installments.OrderBy(i => i.Number).ToList(); + var conditions = header.Kind == DocumentKind.DownPaymentInvoice ? "TP03" : installments.Count > 1 ? "TP01" : "TP02"; + var result = new List(); + if (installments.Count == 0) + { + if (Code(header.PaymentMethodId) is { } only) + { + result.Add(new EInvoicePayment(conditions, only, null, header.NetAmount, only == "MP05" ? bank?.Iban : null, only == "MP05" ? bank?.Bic : null, null)); + } + + return result; + } + + foreach (var installment in installments) + { + if (Code(installment.PaymentMethodId ?? header.PaymentMethodId) is not { } method) + { + continue; + } + + result.Add(new EInvoicePayment(conditions, method, installment.DueDate, installment.Amount, + method == "MP05" ? bank?.Iban?.Replace(" ", string.Empty, StringComparison.Ordinal) : null, method == "MP05" ? bank?.Bic : null, null)); + } + + return result; + } + + // The transport of an accompanying invoice: carrier, packages, weights, start. + private static async Task TransportAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) + { + if (header.Kind != DocumentKind.AccompanyingInvoice && header.CarrierId is null && header.Packages is null) + { + return null; + } + + var carrier = header.CarrierId is { } carrierId ? await uow.Repository().GetAsync(carrierId, cancellationToken).ConfigureAwait(false) : null; + var reason = header.TransportReasonId is { } reasonId ? await uow.Repository().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) : null; + var vat = carrier?.VatNumber?.Trim(); + return new EInvoiceTransport( + carrier?.Description, + string.IsNullOrWhiteSpace(vat) ? null : "IT", + string.IsNullOrWhiteSpace(vat) ? null : Digits(vat, "IT"), + header.TransportBy switch + { + TransportResponsibility.Sender => "Mittente", + TransportResponsibility.Recipient => "Destinatario", + TransportResponsibility.Carrier => "Vettore", + _ => null, + }, + reason?.Description, + header.Packages, + null, + header.GrossWeight, + header.NetWeight, + header.TransportStart, + null); + } + + // A VAT number without the country prefix and spaces. + private static string? Digits(string? vat, string? country) + { + if (string.IsNullOrWhiteSpace(vat)) + { + return null; + } + + var value = vat.Replace(" ", string.Empty, StringComparison.Ordinal).Trim().ToUpperInvariant(); + return country is { Length: 2 } prefix && value.StartsWith(prefix.ToUpperInvariant(), StringComparison.Ordinal) && value.Length > 2 ? value[2..] : value; + } +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceChannelService.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceChannelService.cs new file mode 100644 index 0000000..13a02c4 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceChannelService.cs @@ -0,0 +1,424 @@ +using System.Globalization; +using System.Net.Mail; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.EInvoicing; + +/// A channel as the configuration page shows it: secrets never leave the service, only whether they are set. +/// The code of the channel. +/// Its name. +/// Whether Khaemhat reads it on a schedule (PEC, intermediaries) or receives a push (SdICoop). +/// The settings, secrets removed (a new row when never saved). +/// Whether a password is stored. +/// Whether a client certificate is stored. +/// Whether an API key is stored. +public sealed record EInvoiceChannelView(string Code, string Name, bool Polls, EInvoiceChannelSetting Setting, bool HasPassword, bool HasCertificate, bool HasApiKey); + +/// +/// What the user saves for a channel. Secrets: keeps the stored one, an empty value removes it. +/// +public sealed record EInvoiceChannelInput +{ + /// The code of the channel. + public required string Code { get; init; } + + /// Whether the channel is used. + public bool Enabled { get; init; } + + /// The certified mailbox. + public string? Mailbox { get; init; } + + /// The SMTP server. + public string? SmtpHost { get; init; } + + /// The SMTP port. + public int SmtpPort { get; init; } = 465; + + /// The IMAP server. + public string? ImapHost { get; init; } + + /// The IMAP port. + public int ImapPort { get; init; } = 993; + + /// Whether TLS is used. + public bool Tls { get; init; } = true; + + /// The user. + public string? UserName { get; init; } + + /// The password: keeps it, empty removes it. + public string? Password { get; init; } + + /// The address of the SDI to write to. + public string? ExchangeAddress { get; init; } + + /// The folder the processed messages go to. + public string? ArchiveFolder { get; init; } + + /// The address of the web service or of the API. + public string? Endpoint { get; init; } + + /// The client certificate (PKCS#12): keeps it, empty removes it. + public byte[]? Certificate { get; init; } + + /// The password of the certificate: keeps it, empty removes it. + public string? CertificatePassword { get; init; } + + /// The API key: keeps it, empty removes it. + public string? ApiKey { get; init; } + + /// Whether the test environment is used. + public bool TestEnvironment { get; init; } +} + +/// +/// The channels to the SDI and the routing of the files (mockup 059, issues #76-#77): the PEC mailbox, the SdICoop web +/// service, the intermediaries; each can be tried, paused and resumed. Secrets are kept protected (SPEC §8.5) and never +/// shown again. The routing rules choose the channel of each file, with a fallback. +/// +/// Permission: einvoice.channel.manage. +public sealed class EInvoiceChannelService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly ISecretProtector _secrets; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// Protects the secrets. + /// The history of the changes. + /// The clock. + public EInvoiceChannelService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, ISecretProtector secrets, AuditTrail audit, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(secrets); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _secrets = secrets; + _audit = audit; + _clock = clock; + } + + /// The channels of the pack with their settings. + /// Who looks: needs einvoice.channel.manage. + /// The company. + /// Cancellation. + /// The channels, in the order of the pack. + public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var rows = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(r => r.Code, StringComparer.OrdinalIgnoreCase); + return [.. channels.All.Select(c => View(c, rows.GetValueOrDefault(c.Code) ?? new EInvoiceChannelSetting { Code = c.Code }))]; + } + + /// Saves the settings of a channel. + /// Who saves: needs einvoice.channel.manage. + /// The company. + /// The settings. + /// Cancellation. + /// The channel. + public async Task SaveAsync(Actor actor, string companyCode, EInvoiceChannelInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(input.Code) + ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + Validate(input); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var code = channel.Code; + var row = await repository.FindAsync(Query.For().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false); + var before = row is null ? null : Copy(row); + row ??= new EInvoiceChannelSetting { Code = code }; + row.Enabled = input.Enabled; + row.Mailbox = EInvoiceStore.Trim(input.Mailbox, 200); + row.SmtpHost = EInvoiceStore.Trim(input.SmtpHost, 200); + row.SmtpPort = input.SmtpPort; + row.ImapHost = EInvoiceStore.Trim(input.ImapHost, 200); + row.ImapPort = input.ImapPort; + row.Tls = input.Tls; + row.UserName = EInvoiceStore.Trim(input.UserName, 200); + row.ExchangeAddress = EInvoiceStore.Trim(input.ExchangeAddress, 200); + row.ArchiveFolder = EInvoiceStore.Trim(input.ArchiveFolder, 200); + row.Endpoint = EInvoiceStore.Trim(input.Endpoint, 500); + row.TestEnvironment = input.TestEnvironment; + row.ProtectedPassword = Secret(input.Password, row.ProtectedPassword); + row.ProtectedCertificate = input.Certificate is null + ? row.ProtectedCertificate + : input.Certificate.Length == 0 ? null : _secrets.Protect(Convert.ToBase64String(input.Certificate), EInvoiceStore.SecretPurpose); + row.ProtectedCertificatePassword = Secret(input.CertificatePassword, row.ProtectedCertificatePassword); + row.ProtectedApiKey = Secret(input.ApiKey, row.ProtectedApiKey); + if (before is null) + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return View(channel, row); + } + + /// Pauses or resumes a channel: a paused channel neither sends nor is read. + /// Who does it: needs einvoice.channel.manage. + /// The company. + /// The channel. + /// Whether to pause. + /// Cancellation. + /// A task. + public async Task PauseAsync(Actor actor, string companyCode, string code, bool paused, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = await repository.FindAsync(Query.For().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + var before = Copy(row); + row.Paused = paused; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Tries a channel with its saved settings (login to the mailbox, the service or the API) and keeps the outcome. + /// Who tries: needs einvoice.channel.manage. + /// The company. + /// The channel. + /// Cancellation. + /// The outcome. + public async Task CheckAsync(Actor actor, string companyCode, string code, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(code) + ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + EInvoiceChannelSetting row; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + row = await uow.Repository().FindAsync(Query.For().Where(c => c.Code == channel.Code), cancellationToken) + .ConfigureAwait(false) ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + } + + EInvoiceChannelCheck check; + try + { + check = await channel.Transport.CheckAsync(EInvoiceStore.Settings(row, _secrets), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + check = new EInvoiceChannelCheck(false, ex.Message); + } + + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var current = await uow.Repository().GetAsync(row.Id, cancellationToken).ConfigureAwait(false)!; + if (current is not null) + { + current.LastCheckAt = _clock.GetUtcNow().UtcDateTime; + current.LastCheckOk = check.Success; + current.LastCheckMessage = EInvoiceStore.Trim(check.Message, 1000); + await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return check; + } + + /// The routing rules, in order. + /// Who looks: needs einvoice.channel.manage. + /// The company. + /// Cancellation. + /// The rules. + public async Task> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync(Query.For().OrderBy(r => r.Position), cancellationToken).ConfigureAwait(false)).Items; + } + + /// Adds or changes a routing rule. + /// Who saves: needs einvoice.channel.manage. + /// The company. + /// The rule (identifier 0 to add). + /// Cancellation. + /// The rule. + public async Task SaveRuleAsync(Actor actor, string companyCode, SdiRoutingRule rule, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(rule); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false); + var errors = new List(); + if (channels.Find(rule.ChannelCode) is null) + { + errors.Add(nameof(SdiRoutingRule.ChannelCode) + ":" + EInvoiceErrors.ChannelUnknown); + } + + if (!string.IsNullOrWhiteSpace(rule.FallbackChannelCode) && (channels.Find(rule.FallbackChannelCode) is null + || string.Equals(rule.FallbackChannelCode, rule.ChannelCode, StringComparison.OrdinalIgnoreCase))) + { + errors.Add(nameof(SdiRoutingRule.FallbackChannelCode) + ":" + EInvoiceErrors.ChannelUnknown); + } + + var value = rule.Value?.Trim(); + var valueOk = rule.Condition switch + { + SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType => !string.IsNullOrEmpty(value), + SdiRoutingCondition.DailyVolume => int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var limit) && limit > 0, + _ => true, + }; + if (!valueOk) + { + errors.Add(nameof(SdiRoutingRule.Value) + ":" + EInvoiceErrors.RuleValueInvalid); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = rule.Id == 0 ? new SdiRoutingRule() : await repository.GetAsync(rule.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + var before = rule.Id == 0 ? null : CopyRule(row); + if (rule.Id == 0 && rule.Position <= 0) + { + var last = await repository.FindAsync(Query.For().OrderByDescending(r => r.Position), cancellationToken).ConfigureAwait(false); + row.Position = (last?.Position ?? 0) + 10; + } + else + { + row.Position = rule.Position; + } + + row.Condition = rule.Condition; + row.Value = rule.Condition is SdiRoutingCondition.Default or SdiRoutingCondition.PublicAdministration ? null : value!.ToUpperInvariant(); + row.ChannelCode = rule.ChannelCode.Trim().ToUpperInvariant(); + row.FallbackChannelCode = string.IsNullOrWhiteSpace(rule.FallbackChannelCode) ? null : rule.FallbackChannelCode.Trim().ToUpperInvariant(); + row.Disabled = rule.Disabled; + if (before is null) + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return row; + } + + /// Removes a routing rule. + /// Who removes: needs einvoice.channel.manage. + /// The company. + /// The rule. + /// Cancellation. + /// A task. + public async Task DeleteRuleAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, row.Id, row, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + private async Task ChannelsAsync(string company, CancellationToken cancellationToken) => + (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature() + ?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]); + + private string? Secret(string? input, string? stored) => + input is null ? stored : input.Length == 0 ? null : _secrets.Protect(input, EInvoiceStore.SecretPurpose); + + private static void Validate(EInvoiceChannelInput input) + { + var errors = new List(); + if (input.SmtpPort is < 1 or > 65535) + { + errors.Add(nameof(input.SmtpPort) + ":" + EInvoiceErrors.PortInvalid); + } + + if (input.ImapPort is < 1 or > 65535) + { + errors.Add(nameof(input.ImapPort) + ":" + EInvoiceErrors.PortInvalid); + } + + if (!string.IsNullOrWhiteSpace(input.Mailbox) && !MailAddress.TryCreate(input.Mailbox.Trim(), out _)) + { + errors.Add(nameof(input.Mailbox) + ":" + EInvoiceErrors.MailboxInvalid); + } + + if (!string.IsNullOrWhiteSpace(input.ExchangeAddress) && !MailAddress.TryCreate(input.ExchangeAddress.Trim(), out _)) + { + errors.Add(nameof(input.ExchangeAddress) + ":" + EInvoiceErrors.MailboxInvalid); + } + + if (!string.IsNullOrWhiteSpace(input.Endpoint) && !IsServiceAddress(input.Endpoint.Trim())) + { + errors.Add(nameof(input.Endpoint) + ":" + EInvoiceErrors.EndpointInvalid); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + } + + // https, or http only to this machine (a test service). + private static bool IsServiceAddress(string value) => + Uri.TryCreate(value, UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback)); + + private static EInvoiceChannelView View(EInvoiceChannel channel, EInvoiceChannelSetting row) + { + var shown = Copy(row); + shown.ProtectedPassword = null; + shown.ProtectedCertificate = null; + shown.ProtectedCertificatePassword = null; + shown.ProtectedApiKey = null; + return new EInvoiceChannelView(channel.Code, channel.Name, channel.Transport.Polls, shown, + !string.IsNullOrEmpty(row.ProtectedPassword), !string.IsNullOrEmpty(row.ProtectedCertificate), !string.IsNullOrEmpty(row.ProtectedApiKey)); + } + + private static EInvoiceChannelSetting Copy(EInvoiceChannelSetting row) => EInvoiceStore.Clone(row); + + private static SdiRoutingRule CopyRule(SdiRoutingRule row) => EInvoiceStore.Clone(row); +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceFeedSource.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceFeedSource.cs new file mode 100644 index 0000000..e422972 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceFeedSource.cs @@ -0,0 +1,60 @@ +using Khaemhat.Application.Dashboard; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; + +namespace Khaemhat.Application.EInvoicing; + +/// +/// The electronic invoice on the dashboard (SPEC §10.3): the files rejected by the SDI or refused by a public +/// administration, the documents to generate or send, the invoices received to register. Only for who may see them. +/// +/// The e-invoices. +/// The permissions, licence included. +/// The texts. +public sealed class EInvoiceFeedSource(EInvoiceService invoices, PermissionService permissions, ITexts texts) : ITodoSource +{ + /// The text key of the area. + public const string Area = "Dashboard.Areas.EInvoicing"; + + /// + public async Task> GetAsync(FeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (context.Actor.CompanyCode is not { } company + || !(await permissions.CheckAsync(context.Actor, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false)).Allowed) + { + return []; + } + + var counters = (await invoices.DashboardAsync(context.Actor, company, new EInvoiceFilter(EInvoiceView.ToDo), cancellationToken).ConfigureAwait(false)).Counters; + var result = new List(); + if (counters.Rejected > 0) + { + result.Add(new FeedItem("einvoice-rejected", texts.Format("Dashboard.Feed.EInvoiceRejected", counters.Rejected), Area, FeedTone.Error) + { + Priority = 30, + Href = "/fatturazione-elettronica?vista=da-fare", + }); + } + + if (counters.ToGenerate + counters.ToSend > 0) + { + result.Add(new FeedItem("einvoice-to-send", texts.Format("Dashboard.Feed.EInvoiceToSend", counters.ToGenerate + counters.ToSend), Area, FeedTone.Warning) + { + Priority = 50, + Href = "/fatturazione-elettronica?vista=da-fare", + }); + } + + if (counters.Received > 0 && (await permissions.CheckAsync(context.Actor, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false)).Allowed) + { + result.Add(new FeedItem("einvoice-received", texts.Format("Dashboard.Feed.EInvoiceReceived", counters.Received), Area, FeedTone.Info) + { + Priority = 60, + Href = "/fatturazione-elettronica/ricevute", + }); + } + + return result; + } +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoicePollingService.cs b/src/Khaemhat.Application/EInvoicing/EInvoicePollingService.cs new file mode 100644 index 0000000..64dcce1 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoicePollingService.cs @@ -0,0 +1,302 @@ +using System.Globalization; +using Khaemhat.Application.Jobs; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Instance; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Core.Logging; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.EInvoicing; + +/// What reading one channel brought. +/// The channel. +/// Messages read. +/// Invoices received and stored. +/// Notifications applied. +/// Files already known. +/// Why the channel could not be read. +public sealed record EInvoicePollOutcome(string Channel, int Messages, int Invoices, int Receipts, int Skipped, string? Error); + +/// +/// Reads the channels of the SDI (issue #76): the PEC mailbox and the intermediaries on a schedule, the SdICoop web +/// service when it calls. Every file is sorted: supplier invoices to the inbox, their metadata (MT) with them, the +/// notifications to the e-invoices they are about. A message is acknowledged (archived, marked as read) only when all +/// its files were kept, so nothing is lost when Khaemhat stops halfway. +/// +public sealed partial class EInvoicePollingService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly EInvoiceService _invoices; + private readonly ISecretProtector _secrets; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The e-invoices (notifications). + /// Opens the secrets of the channels. + /// The clock. + /// The log (section SDI). + public EInvoicePollingService( + IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, EInvoiceService invoices, ISecretProtector secrets, TimeProvider clock, + ILogger logger) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(invoices); + ArgumentNullException.ThrowIfNull(secrets); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _factory = factory; + _permissions = permissions; + _packs = packs; + _invoices = invoices; + _secrets = secrets; + _clock = clock; + _logger = logger; + } + + /// Reads the channels of the company now (the button Leggi ora). + /// Who asks: needs einvoice.channel.manage. + /// The company. + /// Cancellation. + /// What each channel brought. + public async Task> PollNowAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + return await PollCompanyAsync(company, cancellationToken).ConfigureAwait(false); + } + + /// Reads every enabled, not paused channel of a company that is read on a schedule. + /// The company. + /// Cancellation. + /// What each channel brought. + public async Task> PollCompanyAsync(string company, CancellationToken cancellationToken = default) + { + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } channels) + { + return []; + } + + List rows; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + rows = [.. (await uow.Repository().ListAsync(Query.For().Where(c => c.Enabled && !c.Paused), cancellationToken) + .ConfigureAwait(false)).Items]; + } + + var result = new List(); + foreach (var row in rows) + { + if (channels.Find(row.Code) is not { Transport.Polls: true } channel) + { + continue; + } + + result.Add(await PollChannelAsync(company, pack, channel, row, cancellationToken).ConfigureAwait(false)); + } + + return result; + } + + /// Takes the files a channel pushed (SdICoop: RiceviFatture, RiceviNotifica) for a company. + /// The company the endpoint belongs to. + /// The channel. + /// The files. + /// Cancellation. + /// What the files brought. + public async Task ReceivePushedAsync(string company, string channel, IReadOnlyList files, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(files); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var (invoices, receipts, skipped, _) = await ProcessAsync(company, pack, channel, files, cancellationToken).ConfigureAwait(false); + return new EInvoicePollOutcome(channel, 1, invoices, receipts, skipped, null); + } + + private async Task PollChannelAsync(string company, IFiscalPack pack, EInvoiceChannel channel, EInvoiceChannelSetting row, CancellationToken cancellationToken) + { + using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)); + var settings = EInvoiceStore.Settings(row, _secrets); + EInvoicePollOutcome outcome; + string? learned = null; + try + { + var fetched = await channel.Transport.FetchAsync(settings, cancellationToken).ConfigureAwait(false); + learned = fetched.ExchangeAddress; + var (invoices, receipts, skipped, done) = await ProcessAsync(company, pack, channel.Code, fetched.Files, cancellationToken).ConfigureAwait(false); + var keys = fetched.Files.GroupBy(f => f.MessageKey, StringComparer.Ordinal).Where(g => g.All(done.Contains)).Select(g => g.Key).ToList(); + if (keys.Count > 0) + { + await channel.Transport.AcknowledgeAsync(settings, keys, cancellationToken).ConfigureAwait(false); + } + + outcome = new EInvoicePollOutcome(channel.Code, fetched.MessagesRead, invoices, receipts, skipped, null); + LogPolled(_logger, channel.Code, company, fetched.MessagesRead, invoices, receipts); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + outcome = new EInvoicePollOutcome(channel.Code, 0, 0, 0, 0, ex.Message); + LogPollFailed(_logger, ex, channel.Code, company); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + if (await uow.Repository().GetAsync(row.Id, cancellationToken).ConfigureAwait(false) is { } current) + { + current.LastPollAt = _clock.GetUtcNow().UtcDateTime; + current.LastPollFailed = outcome.Error is not null; + current.LastPollMessage = EInvoiceStore.Trim( + outcome.Error ?? string.Create(CultureInfo.InvariantCulture, $"{outcome.Messages} messaggi, {outcome.Invoices} fatture, {outcome.Receipts} notifiche"), 1000); + if (!string.IsNullOrWhiteSpace(learned) && !string.Equals(current.ExchangeAddress, learned, StringComparison.OrdinalIgnoreCase)) + { + current.ExchangeAddress = learned; + } + + await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return outcome; + } + + // Invoices first, then their metadata, then the notifications: each file in its own transaction. + private async Task<(int Invoices, int Receipts, int Skipped, HashSet Done)> ProcessAsync( + string company, IFiscalPack pack, string channel, IReadOnlyList files, CancellationToken cancellationToken) + { + var reader = pack.GetFeature(); + var receiptReader = pack.GetFeature(); + var sorted = files.Select(f => (File: f, Receipt: ReadReceipt(receiptReader, f))) + .OrderBy(x => x.Receipt is null ? 0 : x.Receipt.Kind == EInvoiceReceiptKind.Metadata ? 1 : 2) + .ToList(); + int invoices = 0, receipts = 0, skipped = 0; + var done = new HashSet(); + foreach (var (file, receipt) in sorted) + { + try + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + if (receipt is null) + { + var stored = await SdiInboxService.StoreCoreAsync(uow, reader, file.FileName, file.Content, file.ReceivedAt.UtcDateTime, channel, null, false, cancellationToken) + .ConfigureAwait(false); + if (stored.Error is null) + { + invoices++; + } + else + { + skipped++; + } + } + else if (receipt.Kind == EInvoiceReceiptKind.Metadata) + { + await SdiInboxService.AttachMetadataCoreAsync(uow, receipt, cancellationToken).ConfigureAwait(false); + } + else + { + var applied = await _invoices.ApplyReceiptCoreAsync(uow, receipt, channel, Actor.System.UserName, false, cancellationToken).ConfigureAwait(false); + if (applied.Error == EInvoiceErrors.ReceiptDuplicate) + { + skipped++; + } + else + { + receipts++; + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + done.Add(file); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogFileFailed(_logger, ex, file.FileName, channel, company); + } + } + + return (invoices, receipts, skipped, done); + } + + private static EInvoiceReceipt? ReadReceipt(IEInvoiceReceiptReader? reader, EInvoiceIncoming file) + { + if (reader is null || !reader.IsReceipt(file.FileName, file.Content)) + { + return null; + } + + try + { + return reader.Read(file.FileName, file.Content); + } + catch (IncomingInvoiceException) + { + return null; + } + } + + [LoggerMessage(EventId = 9111, Level = LogLevel.Information, Message = "Channel {Channel} of {Company}: {Messages} messages, {Invoices} invoices, {Receipts} notifications.")] + private static partial void LogPolled(ILogger logger, string channel, string company, int messages, int invoices, int receipts); + + [LoggerMessage(EventId = 9112, Level = LogLevel.Warning, Message = "Channel {Channel} of {Company} could not be read.")] + private static partial void LogPollFailed(ILogger logger, Exception exception, string channel, string company); + + [LoggerMessage(EventId = 9113, Level = LogLevel.Error, Message = "File {FileName} from channel {Channel} of {Company} was not kept; the message stays to read again.")] + private static partial void LogFileFailed(ILogger logger, Exception exception, string fileName, string channel, string company); +} + +/// Reads the channels of the SDI of every company (job einvoice.poll, every 15 minutes). +/// The companies. +/// The reading of the channels. +/// The licence. +public sealed class EInvoicePollingJob(ICompanyRegistry companies, EInvoicePollingService service, ILicenseGate license) : IScheduledJob +{ + /// The job type. + public const string JobType = "einvoice.poll"; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + if (!license.IsModuleActive(ModuleCodes.EInvoicing)) + { + return "Modulo fatturazione elettronica non attivo."; + } + + int done = 0, invoices = 0, receipts = 0, failed = 0; + foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status is CompanyStatus.Disabled) + { + continue; + } + + foreach (var outcome in await service.PollCompanyAsync(company.Code, cancellationToken).ConfigureAwait(false)) + { + invoices += outcome.Invoices; + receipts += outcome.Receipts; + failed += outcome.Error is null ? 0 : 1; + } + + done++; + } + + return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {invoices} fatture ricevute, {receipts} notifiche, {failed} canali non letti."); + } +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs new file mode 100644 index 0000000..da52fef --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs @@ -0,0 +1,761 @@ +using System.Globalization; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Files; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Logging; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.EInvoicing; + +/// +/// The electronic invoices of the company (SPEC §11.9, mockup 058, ADR 0039, issues #74-#75): the dashboard, the file +/// of each issued document written and checked by the fiscal pack, sending through the channel the router chooses +/// (with its fallback), the notifications of the SDI that move the e-invoice and its document, the correction of a +/// rejected invoice and the courtesy copy. +/// +/// +/// Permissions: einvoice.document.read to see, einvoice.document.send to generate, send and import +/// notifications. The state of the document follows the e-invoice in the same transaction (generated, sent, delivered, +/// rejected, not delivered); a rejected invoice can be changed and generated again with a new progressive. +/// +public sealed partial class EInvoiceService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly DocumentEngine _engine; + private readonly ISecretProtector _secrets; + private readonly DocumentPdfGenerator _pdf; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The document engine. + /// Opens the secrets of the channels. + /// The print of the documents (courtesy copy). + /// The clock. + /// The log (section SDI). + public EInvoiceService( + IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, ISecretProtector secrets, + DocumentPdfGenerator pdf, TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(secrets); + ArgumentNullException.ThrowIfNull(pdf); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _factory = factory; + _permissions = permissions; + _packs = packs; + _engine = engine; + _secrets = secrets; + _pdf = pdf; + _clock = clock; + _logger = logger; + } + + /// The dashboard: the e-invoices of the view, the documents to generate, the counters. + /// Who looks: needs einvoice.document.read. + /// The company. + /// The filter. + /// Cancellation. + /// The dashboard. + public async Task DashboardAsync(Actor actor, string companyCode, EInvoiceFilter filter, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(filter); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For().Where(e => !e.Superseded); + if (filter.From is { } from) + { + query = query.Where(e => e.DocumentDate >= from); + } + + if (filter.To is { } to) + { + query = query.Where(e => e.DocumentDate <= to); + } + + var all = (await uow.Repository().ListAsync(query.OrderByDescending(e => e.DocumentDate), cancellationToken).ConfigureAwait(false)).Items + .Select(EInvoiceStore.Light) + .ToList(); + var pending = await PendingAsync(uow, filter, cancellationToken).ConfigureAwait(false); + var received = await uow.Repository().CountAsync(Query.For().Where(f => f.Status == InboxFileStatus.New), cancellationToken) + .ConfigureAwait(false); + var counters = new EInvoiceCounters( + pending.Count(p => p.Status == DocumentStatus.Issued), + all.Count(e => e.Status == EInvoiceStatus.Generated), + all.Count(e => e.Status == EInvoiceStatus.Sent), + all.Count(e => EInvoiceStates.IsIssued(e.Status) && e.Status is not (EInvoiceStatus.Refused or EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable)), + all.Count(e => EInvoiceStates.NeedsAction(e.Status)), + all.Count(e => e.Status is EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable), + received); + + IEnumerable rows = filter.View switch + { + EInvoiceView.SelfInvoices => all.Where(e => e.Kind == DocumentKind.SelfInvoice), + EInvoiceView.ToDo => all.Where(e => e.Status == EInvoiceStatus.Generated || EInvoiceStates.NeedsAction(e.Status)), + _ => all.Where(e => e.Kind != DocumentKind.SelfInvoice), + }; + if (filter.Status is { } status) + { + rows = rows.Where(e => e.Status == status); + } + + var list = rows.ToList(); + var parties = await PartiesAsync(uow, list.Select(e => e.PartyId).OfType(), cancellationToken).ConfigureAwait(false); + var result = list.Select(e => new EInvoiceRow(e, parties.GetValueOrDefault(e.PartyId ?? 0)?.Code, parties.GetValueOrDefault(e.PartyId ?? 0)?.Name)); + if (!string.IsNullOrWhiteSpace(filter.Search)) + { + var text = filter.Search.Trim(); + result = result.Where(r => Contains(r.Invoice.DocumentNumber, text) || Contains(r.Invoice.FileName, text) || Contains(r.Invoice.ExchangeId, text) + || Contains(r.PartyName, text) || Contains(r.PartyCode, text)); + } + + var visiblePending = filter.View switch + { + EInvoiceView.SelfInvoices => pending.Where(p => p.Kind == DocumentKind.SelfInvoice), + EInvoiceView.ToDo => pending, + _ => pending.Where(p => p.Kind != DocumentKind.SelfInvoice), + }; + return new EInvoiceDashboard([.. result], [.. visiblePending], counters); + } + + /// The e-invoices of a document with their notifications, newest first (the page of the document). + /// Who looks. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The files and their notifications. + public async Task Notifications)>> HistoryAsync( + Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var invoices = (await uow.Repository() + .ListAsync(Query.For().Where(e => e.Family == family && e.DocumentId == documentId).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items; + var result = new List<(EInvoice, IReadOnlyList)>(); + foreach (var invoice in invoices) + { + var id = invoice.Id; + var notifications = (await uow.Repository() + .ListAsync(Query.For().Where(n => n.EInvoiceId == id).OrderBy(n => n.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items; + result.Add((EInvoiceStore.Light(invoice), [.. notifications.Select(n => { n.Content = []; return n; })])); + } + + return result; + } + + /// The notifications received in a period, newest first (files not loaded). + /// Who looks: needs einvoice.document.read. + /// The company. + /// From this day. + /// Up to this day. + /// Cancellation. + /// The notifications. + public async Task> NotificationsAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var rows = (await uow.Repository() + .ListAsync(Query.For().Where(n => n.ReceivedAt >= start && n.ReceivedAt < end).OrderByDescending(n => n.ReceivedAt).Take(2000), cancellationToken) + .ConfigureAwait(false)).Items; + foreach (var row in rows) + { + row.Content = []; + } + + return rows; + } + + /// Checks the file a document would have, without writing it. + /// Who checks: needs einvoice.document.read. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The problems, empty when the file can be sent. + public async Task> CheckAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + if (!EInvoiceBuilder.IsElectronic(record.Header.Kind)) + { + return [Problem(EInvoiceErrors.NotElectronic)]; + } + + var (file, _, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false); + file = file with { FileName = writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? "0", 1), ProgressiveNumber = writer.Progressive(1) }; + var problems = validator.Validate(file).ToList(); + if (problems.All(p => p.Severity != EInvoiceProblemSeverity.Error)) + { + problems.AddRange(validator.ValidateXml(writer.Write(file))); + } + + return problems; + } + + /// + /// Writes the file of an issued document (or of one rejected by the SDI): built from the document, checked against + /// the rules of the pack and its schema; the document goes to XML generato. A file generated and not sent is + /// written again with the same name; a rejected one is kept, superseded, and the new file has a new progressive. + /// + /// Who generates: needs einvoice.document.send. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The e-invoice, or the errors. + public async Task GenerateAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false); + var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var result = await GenerateCoreAsync(uow, writer, validator, family, documentId, actor.UserName, cancellationToken).ConfigureAwait(false); + if (result.Success) + { + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing))) + { + LogGenerated(_logger, result.Invoice!.FileName, result.Invoice.DocumentNumber, company); + } + } + + return result; + } + + /// Generates the files of several documents and sends them (the button Genera e invia). + /// Who sends. + /// The company. + /// The documents. + /// Cancellation. + /// For each document, the generation and the sending. + public async Task> GenerateAndSendAsync( + Actor actor, string companyCode, IReadOnlyList<(DocumentFamily Family, long DocumentId)> documents, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(documents); + var result = new List<(PendingEInvoice?, EInvoiceGeneration, EInvoiceSendOutcome?)>(); + foreach (var (family, id) in documents) + { + var generation = await GenerateAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false); + EInvoiceSendOutcome? sending = null; + if (generation.Invoice is { } invoice) + { + sending = (await SendAsync(actor, companyCode, [invoice.Id], cancellationToken).ConfigureAwait(false))[0]; + } + + result.Add((null, generation, sending)); + } + + return result; + } + + /// + /// Sends generated files through the channel the router chooses; when the channel refuses the file the fallback of + /// the rule is tried. A file a channel took goes to Inviato with its document; one no channel took keeps its + /// state and the error. + /// + /// Who sends: needs einvoice.document.send. + /// The company. + /// The e-invoices. + /// Cancellation. + /// What happened to each. + public async Task> SendAsync(Actor actor, string companyCode, IReadOnlyList ids, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(ids); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var channels = pack.GetFeature(); + var result = new List(); + foreach (var id in ids.Distinct()) + { + result.Add(await SendOneAsync(company, channels, id, actor.UserName, cancellationToken).ConfigureAwait(false)); + } + + return result; + } + + /// Records that a generated file was sent outside Khaemhat (portal of the AdE, another program). + /// Who records it: needs einvoice.document.send. + /// The company. + /// The e-invoice. + /// The identifier of the SDI, when known. + /// Cancellation. + /// The e-invoice. + public async Task MarkSentAsync(Actor actor, string companyCode, long id, string? exchangeId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated) + { + throw new ValidationFailedException([":" + EInvoiceErrors.AlreadySent]); + } + + await MarkSentCoreAsync(uow, invoice, EInvoiceStore.ManualChannel, EInvoiceStore.Trim(exchangeId, 40), null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return EInvoiceStore.Light(invoice); + } + + /// Imports notifications downloaded from the portal of the AdE or from another program. + /// Who imports: needs einvoice.document.send. + /// The company. + /// The files. + /// Cancellation. + /// What happened to each. + public async Task> ImportReceiptsAsync( + Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(files); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false); + var reader = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature() + ?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]); + var result = new List(); + foreach (var (name, content) in files) + { + EInvoiceReceipt receipt; + try + { + if (!reader.IsReceipt(name, content)) + { + result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt)); + continue; + } + + receipt = reader.Read(name, content); + } + catch (IncomingInvoiceException) + { + result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt)); + continue; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var outcome = await ApplyReceiptCoreAsync(uow, receipt, EInvoiceStore.ManualChannel, actor.UserName, false, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + result.Add(outcome); + } + + return result; + } + + /// The file of an e-invoice, as sent. + /// Who downloads: needs einvoice.document.read. + /// The company. + /// The e-invoice. + /// Cancellation. + /// Name and content. + public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + return (invoice.FileName, invoice.Content); + } + + /// The file of a notification. + /// Who downloads: needs einvoice.document.read. + /// The company. + /// The notification. + /// Cancellation. + /// Name and content. + public async Task<(string FileName, byte[] Content)> NotificationFileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var notification = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + return (notification.FileName, notification.Content); + } + + /// The courtesy copy: the print of the document with the XML of the e-invoice embedded. + /// Who downloads: needs einvoice.document.read and to read the document. + /// The company. + /// The e-invoice. + /// Cancellation. + /// Name and content of the PDF. + public async Task<(string FileName, byte[] Content)> CourtesyCopyAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var (name, xml) = await FileAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false); + EInvoice invoice; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) + { + invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + } + + using var output = new MemoryStream(); + var context = new FileGenerationContext(actor, companyCode, DocumentPrintService.EntityOf(invoice.Family), invoice.DocumentId, CultureInfo.GetCultureInfo("it-IT"), _clock.GetUtcNow().UtcDateTime); + await _pdf.CourtesyCopyAsync(context, name, xml, output, cancellationToken).ConfigureAwait(false); + return (EInvoiceStore.Stem(name) + ".pdf", output.ToArray()); + } + + /// The core of the generation, in the transaction of the caller (also the demo seed). + internal async Task GenerateCoreAsync( + IUnitOfWork uow, IEInvoiceWriter writer, IEInvoiceValidator validator, DocumentFamily family, long documentId, string userName, CancellationToken cancellationToken) + { + var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + var header = record.Header; + if (!EInvoiceBuilder.IsElectronic(header.Kind)) + { + return new(null, [Problem(EInvoiceErrors.NotElectronic)]); + } + + if (header.Status is DocumentStatus.Draft or DocumentStatus.Cancelled) + { + return new(null, [Problem(EInvoiceErrors.NotIssued)]); + } + + var repository = uow.Repository(); + var active = await repository.FindAsync(Query.For().Where(e => e.Family == family && e.DocumentId == documentId && !e.Superseded), cancellationToken) + .ConfigureAwait(false); + if (header.Status is not (DocumentStatus.Issued or DocumentStatus.SdiGenerated or DocumentStatus.SdiRejected) + || active is { Status: not (EInvoiceStatus.Generated or EInvoiceStatus.Rejected) }) + { + return new(null, [Problem(EInvoiceErrors.AlreadySent)]); + } + + var (file, party, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false); + var problems = validator.Validate(file).ToList(); + if (problems.Any(p => p.Severity == EInvoiceProblemSeverity.Error)) + { + return new(null, problems); + } + + var reuse = active is { Status: EInvoiceStatus.Generated }; + var progressive = reuse ? active!.Progressive : await NextProgressiveAsync(uow, cancellationToken).ConfigureAwait(false); + var fileName = reuse ? active!.FileName : writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? string.Empty, progressive); + file = file with { FileName = fileName, ProgressiveNumber = writer.Progressive(progressive) }; + var xml = writer.Write(file); + var schema = validator.ValidateXml(xml); + if (schema.Any(p => p.Severity == EInvoiceProblemSeverity.Error)) + { + return new(null, [.. problems, .. schema]); + } + + var now = _clock.GetUtcNow().UtcDateTime; + var invoice = reuse ? active! : new EInvoice(); + invoice.Family = family; + invoice.DocumentId = documentId; + invoice.Kind = header.Kind; + invoice.DocumentNumber = header.DocumentNumber; + invoice.DocumentDate = header.DocumentDate; + invoice.PartyId = party.Id; + invoice.DocumentType = file.Invoices[0].DocumentType; + invoice.FileName = fileName; + invoice.Progressive = progressive; + invoice.Format = file.TransmissionFormat ?? string.Empty; + invoice.RecipientCode = file.RecipientCode; + invoice.RecipientPec = file.RecipientPec; + invoice.TotalAmount = header.TotalAmount; + invoice.Status = EInvoiceStatus.Generated; + invoice.GeneratedAt = now; + invoice.LastMessage = null; + invoice.Content = xml; + invoice.IsDemo = header.IsDemo; + if (reuse) + { + await repository.UpdateAsync(invoice, cancellationToken).ConfigureAwait(false); + } + else + { + if (active is not null) + { + active.Superseded = true; + await repository.UpdateAsync(active, cancellationToken).ConfigureAwait(false); + } + + invoice.Id = await repository.InsertAsync(invoice, cancellationToken).ConfigureAwait(false); + } + + await _engine.AdvanceExchangeAsync(uow, family, documentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Generated), userName, cancellationToken).ConfigureAwait(false); + return new(invoice, problems); + } + + /// A file taken by a channel: Inviato, with the document. + internal async Task MarkSentCoreAsync(IUnitOfWork uow, EInvoice invoice, string channel, string? exchangeId, string? messageId, string userName, CancellationToken cancellationToken) + { + invoice.Status = EInvoiceStatus.Sent; + invoice.SentAt = _clock.GetUtcNow().UtcDateTime; + invoice.ChannelCode = channel; + invoice.ExchangeId = exchangeId ?? invoice.ExchangeId; + invoice.MessageId = EInvoiceStore.Trim(messageId, 200); + invoice.LastMessage = null; + await uow.Repository().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false); + await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Sent), userName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Applies a notification in the transaction of the caller: kept as received (once: the file name is unique), the + /// e-invoice found by file name or identifier of the SDI gets the new state and its document follows. + /// + internal async Task ApplyReceiptCoreAsync( + IUnitOfWork uow, EInvoiceReceipt receipt, string? channel, string userName, bool demo, CancellationToken cancellationToken) + { + var notifications = uow.Repository(); + var name = receipt.FileName; + if (await notifications.FindAsync(Query.For().Where(n => n.FileName == name), cancellationToken).ConfigureAwait(false) is { } known) + { + return new ReceiptOutcome(name, receipt.Code, known.InvoiceFileName, known.EInvoiceId, null, EInvoiceErrors.ReceiptDuplicate); + } + + var invoice = await FindInvoiceAsync(uow, receipt, cancellationToken).ConfigureAwait(false); + var errors = receipt.Errors.Count == 0 ? null : string.Join('\n', receipt.Errors.Select(e => e.Code + " - " + e.Description + (e.Hint is null ? string.Empty : " (" + e.Hint + ")"))); + var receivedAt = (receipt.ReceivedAt ?? _clock.GetUtcNow()).UtcDateTime; + await notifications.InsertAsync( + new EInvoiceNotification + { + EInvoiceId = invoice?.Id, + Code = receipt.Code, + FileName = EInvoiceStore.Trim(name, 100)!, + InvoiceFileName = EInvoiceStore.Trim(receipt.InvoiceFileName ?? invoice?.FileName, 100), + ExchangeId = EInvoiceStore.Trim(receipt.ExchangeId, 40), + ReceivedAt = receivedAt, + Outcome = EInvoiceStore.Trim(receipt.Outcome, 10), + Description = EInvoiceStore.Trim(receipt.Description, 1000), + Errors = errors, + ChannelCode = channel, + Content = receipt.Content, + IsDemo = demo || invoice?.IsDemo == true, + }, + cancellationToken).ConfigureAwait(false); + + if (invoice is null) + { + return new ReceiptOutcome(name, receipt.Code, receipt.InvoiceFileName, null, null, receipt.Code is "MT" or "SE" ? null : EInvoiceErrors.ReceiptUnmatched); + } + + var next = EInvoiceStates.After(receipt.Code, receipt.Outcome); + if (next is { } status) + { + if (invoice.Status == EInvoiceStatus.Generated) + { + invoice.SentAt ??= receivedAt; + invoice.ChannelCode ??= channel; + } + + invoice.Status = status; + invoice.ExchangeId ??= EInvoiceStore.Trim(receipt.ExchangeId, 40); + invoice.LastNotificationAt = receivedAt; + invoice.LastMessage = EInvoiceStore.Trim(errors ?? receipt.Description, 1000); + await uow.Repository().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false); + await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, status), userName, cancellationToken).ConfigureAwait(false); + using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing))) + { + LogReceipt(_logger, receipt.Code, invoice.FileName, status); + } + } + + return new ReceiptOutcome(name, receipt.Code, invoice.FileName, invoice.Id, next, null); + } + + private static async Task FindInvoiceAsync(IUnitOfWork uow, EInvoiceReceipt receipt, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + var stem = receipt.InvoiceFileName is { } invoiceName ? EInvoiceStore.Stem(invoiceName) : EInvoiceStore.InvoiceStem(receipt.FileName); + if (stem is not null) + { + foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" }) + { + if (await repository.FindAsync(Query.For().Where(e => e.FileName == candidate), cancellationToken).ConfigureAwait(false) is { } byName) + { + return byName; + } + } + } + + if (receipt.ExchangeId is { Length: > 0 } exchange) + { + return await repository.FindAsync(Query.For().Where(e => e.ExchangeId == exchange).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false); + } + + return null; + } + + private async Task SendOneAsync(string company, IEInvoiceChannels? channels, long id, string userName, CancellationToken cancellationToken) + { + EInvoice invoice; + List<(string Code, EInvoiceChannelSettings Settings)> route; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + invoice = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated) + { + return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, invoice.ChannelCode, EInvoiceErrors.AlreadySent); + } + + route = await RouteAsync(uow, channels, invoice, cancellationToken).ConfigureAwait(false); + } + + if (route.Count == 0 || channels is null) + { + return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, null, EInvoiceErrors.NoChannel); + } + + EInvoiceSendResult? result = null; + string? used = null; + var errors = new List(); + foreach (var (code, settings) in route) + { + var transport = channels.Find(code)!.Transport; + used = code; + result = await transport.SendAsync(settings, new EInvoiceOutgoing(invoice.FileName, invoice.Content, invoice.DocumentNumber), cancellationToken).ConfigureAwait(false); + if (result.Accepted) + { + break; + } + + errors.Add(code + ": " + result.Error); + using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing))) + { + LogSendFailed(_logger, invoice.FileName, code, result.Error); + } + } + + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var current = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + if (result is { Accepted: true }) + { + await MarkSentCoreAsync(uow, current, used!, EInvoiceStore.Trim(result.ExchangeId, 40), result.MessageId, userName, cancellationToken).ConfigureAwait(false); + } + else + { + current.SendAttempts++; + current.LastMessage = EInvoiceStore.Trim(string.Join(" | ", errors), 1000); + await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + if (result is { Accepted: true }) + { + using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing))) + { + LogSent(_logger, invoice.FileName, used!, company); + } + } + + return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, result?.Accepted == true, used, result?.Accepted == true ? null : string.Join(" | ", errors)); + } + + // The channels to try, in order: the one of the router, then its fallback; each with its settings. + private async Task> RouteAsync(IUnitOfWork uow, IEInvoiceChannels? channels, EInvoice invoice, CancellationToken cancellationToken) + { + if (channels is null) + { + return []; + } + + var rows = (await uow.Repository().ListAsync(Query.For().Where(c => c.Enabled && !c.Paused), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(c => c.Code, StringComparer.OrdinalIgnoreCase); + var usable = channels.All.Select(c => c.Code).Where(rows.ContainsKey).ToList(); + var rules = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var party = invoice.PartyId is { } partyId ? await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null; + var today = _clock.GetUtcNow().UtcDateTime.Date; + var sentToday = await uow.Repository().CountAsync(Query.For().Where(e => e.SentAt >= today), cancellationToken).ConfigureAwait(false); + var choice = SdiRouter.Choose(new SdiRoutingInput(invoice.DocumentType, party?.Code, invoice.Format == "FPA12", sentToday), rules, usable); + if (choice is null) + { + return []; + } + + return [.. new[] { choice.Channel, choice.Fallback }.OfType().Distinct(StringComparer.OrdinalIgnoreCase) + .Select(code => (code, EInvoiceStore.Settings(rows[code], _secrets)))]; + } + + private async Task<(IEInvoiceWriter Writer, IEInvoiceValidator Validator, IFiscalPack Pack)> FeaturesAsync(string company, CancellationToken cancellationToken) + { + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var writer = pack.GetFeature(); + var validator = pack.GetFeature(); + return writer is null || validator is null ? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]) : (writer, validator, pack); + } + + private static async Task NextProgressiveAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var last = await uow.Repository().FindAsync(Query.For().OrderByDescending(e => e.Progressive), cancellationToken).ConfigureAwait(false); + return (last?.Progressive ?? 0L) + 1L; + } + + // Issued (or rejected) electronic documents without a file ready to send. + private static async Task> PendingAsync(IUnitOfWork uow, EInvoiceFilter filter, CancellationToken cancellationToken) + { + var query = Query.For().Where(d => d.Status == DocumentStatus.Issued || d.Status == DocumentStatus.SdiRejected); + if (filter.From is { } from) + { + query = query.Where(d => d.DocumentDate >= from); + } + + if (filter.To is { } to) + { + query = query.Where(d => d.DocumentDate <= to); + } + + var documents = (await uow.Repository().ListAsync(query.OrderBy(d => d.DocumentDate), cancellationToken).ConfigureAwait(false)).Items + .Where(d => EInvoiceBuilder.IsElectronic(d.Kind)) + .ToList(); + var parties = await PartiesAsync(uow, documents.Select(d => d.PartyId).OfType(), cancellationToken).ConfigureAwait(false); + return [.. documents.Select(d => new PendingEInvoice(DocumentFamily.SaleDocument, d.Id, d.Kind, d.DocumentNumber, d.DocumentDate, + parties.GetValueOrDefault(d.PartyId ?? 0)?.Name, d.TotalAmount, d.Status))]; + } + + private static async Task> PartiesAsync(IUnitOfWork uow, IEnumerable ids, CancellationToken cancellationToken) + { + var set = ids.Distinct().ToList(); + var result = new Dictionary(); + foreach (var chunk in set.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var party in (await uow.Repository().ListAsync(Query.For().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items) + { + result[party.Id] = party; + } + } + + return result; + } + + private static bool Contains(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true; + + private static EInvoiceProblem Problem(string code) => new(code, string.Empty, code, EInvoiceProblemSeverity.Error); + + [LoggerMessage(EventId = 9101, Level = LogLevel.Information, Message = "E-invoice {FileName} generated for document {Number} in {Company}.")] + private static partial void LogGenerated(ILogger logger, string fileName, string? number, string company); + + [LoggerMessage(EventId = 9102, Level = LogLevel.Information, Message = "E-invoice {FileName} sent through {Channel} in {Company}.")] + private static partial void LogSent(ILogger logger, string fileName, string channel, string company); + + [LoggerMessage(EventId = 9103, Level = LogLevel.Warning, Message = "E-invoice {FileName} not taken by channel {Channel}: {Error}")] + private static partial void LogSendFailed(ILogger logger, string fileName, string channel, string? error); + + [LoggerMessage(EventId = 9104, Level = LogLevel.Information, Message = "Notification {Code} for {FileName}: now {Status}.")] + private static partial void LogReceipt(ILogger logger, string code, string fileName, EInvoiceStatus status); +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs new file mode 100644 index 0000000..7c3646a --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs @@ -0,0 +1,284 @@ +using System.Security.Cryptography; +using Khaemhat.Core.Documents; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Security; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.EInvoicing; + +/// The permissions of the electronic invoice (module EINV, ). +public static class EInvoicePermissions +{ + /// See the e-invoices, their notifications and the conservation packages. + public const string Read = "einvoice.document.read"; + + /// Generate, send and send again; import notifications. + public const string Send = "einvoice.document.send"; + + /// See the invoices received. + public const string InboxRead = "einvoice.inbox.read"; + + /// Register, discard and upload the invoices received. + public const string InboxImport = "einvoice.inbox.import"; + + /// Configure the channels and the routing; read the channels now. + public const string ChannelManage = "einvoice.channel.manage"; +} + +/// The error codes of the electronic invoice (texts in EInvoicing.json). +public static class EInvoiceErrors +{ + /// No e-invoice, notification or file with that identifier. + public const string NotFound = "einvoice.not-found"; + + /// The kind of document does not go to the exchange system. + public const string NotElectronic = "einvoice.not-electronic"; + + /// The document is not issued yet. + public const string NotIssued = "einvoice.not-issued"; + + /// The file was already sent: it can only receive notifications. + public const string AlreadySent = "einvoice.already-sent"; + + /// The profile of the company is missing. + public const string CompanyProfileMissing = "einvoice.profile-missing"; + + /// The fiscal pack of the company does not write e-invoices. + public const string NotSupported = "einvoice.not-supported"; + + /// No channel is enabled. + public const string NoChannel = "einvoice.no-channel"; + + /// The file is not a notification of the exchange system. + public const string NotAReceipt = "einvoice.not-a-receipt"; + + /// The notification is about a file Khaemhat did not send. + public const string ReceiptUnmatched = "einvoice.receipt-unmatched"; + + /// The notification was already imported. + public const string ReceiptDuplicate = "einvoice.receipt-duplicate"; + + /// The channel is not one of the pack. + public const string ChannelUnknown = "einvoice.channel-unknown"; + + /// A port out of range. + public const string PortInvalid = "einvoice.port-invalid"; + + /// The mailbox is not an e-mail address. + public const string MailboxInvalid = "einvoice.mailbox-invalid"; + + /// The address of the service is not an https address. + public const string EndpointInvalid = "einvoice.endpoint-invalid"; + + /// The value of a routing rule is missing or wrong. + public const string RuleValueInvalid = "einvoice.rule-value"; + + /// The received file is already in the inbox. + public const string InboxDuplicate = "einvoice.inbox-duplicate"; + + /// The received file is not in a state that allows the action. + public const string InboxState = "einvoice.inbox-state"; + + /// The period of the conservation package is wrong. + public const string PeriodInvalid = "einvoice.period-invalid"; +} + +/// An e-invoice in the lists, with its counterpart. +/// The e-invoice (the file is not loaded for lists). +/// The code of the customer or supplier. +/// The name. +public sealed record EInvoiceRow(EInvoice Invoice, string? PartyCode, string? PartyName); + +/// An issued document without its file yet, or whose file was rejected. +/// The family. +/// The document. +/// The kind. +/// The number. +/// The date. +/// The customer, or the supplier of a self-invoice. +/// The total. +/// The state of the document. +public sealed record PendingEInvoice(DocumentFamily Family, long DocumentId, DocumentKind Kind, string? Number, DateOnly Date, string? PartyName, decimal Total, DocumentStatus Status); + +/// What the dashboard shows. +public enum EInvoiceView +{ + /// Invoices, notes and fees sent to customers. + Issued = 0, + + /// Self-invoices and integrations. + SelfInvoices = 1, + + /// Everything that needs the user: to generate, to send, rejected, refused. + ToDo = 2, +} + +/// The filter of the dashboard. +/// The view. +/// Only this state. +/// From this date of the document. +/// Up to this date. +/// Number, file name, identifier of the SDI or counterpart. +public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EInvoiceStatus? Status = null, DateOnly? From = null, DateOnly? To = null, string? Search = null); + +/// The counters of the dashboard (mockup 058). +/// Issued documents without a file. +/// Files generated and not sent. +/// Sent, waiting for the receipt. +/// Delivered or accepted (RC, NE EC01, DT). +/// Rejected by the SDI or refused by a public administration. +/// Issued but not delivered: in the reserved area of the customer (MC, AT). +/// Invoices received to register. +public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int NotDelivered, int Received); + +/// The dashboard. +/// The e-invoices of the view. +/// The documents to generate (view and the counters). +/// The counters. +public sealed record EInvoiceDashboard(IReadOnlyList Rows, IReadOnlyList Pending, EInvoiceCounters Counters); + +/// The outcome of a generation: the file, or why not. +/// The e-invoice written. +/// Errors (nothing written) and warnings. +public sealed record EInvoiceGeneration(EInvoice? Invoice, IReadOnlyList Problems) +{ + /// Whether the file was written. + public bool Success => Invoice is not null; +} + +/// The outcome of sending one file. +/// The e-invoice. +/// The file. +/// The document. +/// Whether a channel took it. +/// The channel that took it, or the last one tried. +/// Why not (a message of the channel, or an error code). +public sealed record EInvoiceSendOutcome(long EInvoiceId, string FileName, string? DocumentNumber, bool Sent, string? ChannelCode, string? Error); + +/// The outcome of a notification imported or received. +/// The notification. +/// Its code (RC, NS …). +/// The file it is about. +/// The e-invoice updated. +/// The state it reached. +/// Why it was not applied (error code). +public sealed record ReceiptOutcome(string FileName, string? Code, string? InvoiceFileName, long? EInvoiceId, EInvoiceStatus? Status, string? Error); + +/// What the services of the electronic invoice share. +internal static class EInvoiceStore +{ + /// The channel of what the user uploads or sends from the portal of the AdE. + public const string ManualChannel = "MANUAL"; + + /// The purpose of the protection of the secrets of the channels. + public const string SecretPurpose = "einvoice.channel"; + + /// The SHA-256 of a file in lower-case hexadecimal. + public static string Hash(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content)); + + /// A text cut to a length. + public static string? Trim(string? text, int length) => + string.IsNullOrWhiteSpace(text) ? null : text.Trim().Length <= length ? text.Trim() : text.Trim()[..length]; + + /// The settings of a channel for its transport, secrets unprotected. + public static EInvoiceChannelSettings Settings(EInvoiceChannelSetting row, ISecretProtector secrets) + { + string? Open(string? value) => string.IsNullOrEmpty(value) ? null : secrets.Unprotect(value, SecretPurpose); + var certificate = Open(row.ProtectedCertificate); + return new EInvoiceChannelSettings + { + Code = row.Code, + Mailbox = row.Mailbox, + SmtpHost = row.SmtpHost, + SmtpPort = row.SmtpPort, + ImapHost = row.ImapHost, + ImapPort = row.ImapPort, + Tls = row.Tls, + User = row.UserName, + Password = Open(row.ProtectedPassword), + ExchangeAddress = row.ExchangeAddress, + ArchiveFolder = row.ArchiveFolder, + Endpoint = row.Endpoint, + Certificate = certificate is null ? null : Convert.FromBase64String(certificate), + CertificatePassword = Open(row.ProtectedCertificatePassword), + ApiKey = Open(row.ProtectedApiKey), + TestEnvironment = row.TestEnvironment, + }; + } + + /// The name of the invoice file a notification is about, from the name of the notification. + /// The notification (IT01234567890_00001_RC_001.xml). + /// The stem of the invoice file (IT01234567890_00001), or . + public static string? InvoiceStem(string receiptFileName) + { + var name = Path.GetFileName(receiptFileName); + var parts = name.Split('_'); + return parts.Length >= 4 ? string.Join('_', parts[..^2]) : null; + } + + /// The stem of a file name: without .xml and .p7m. + public static string Stem(string fileName) + { + var name = Path.GetFileName(fileName); + foreach (var extension in new[] { ".p7m", ".xml" }) + { + if (name.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) + { + name = name[..^extension.Length]; + } + } + + return name; + } + + /// A shallow copy of a row (public properties that can be written), for the history of a change. + public static T Clone(T row) + where T : class, new() + { + var copy = new T(); + foreach (var property in typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) + { + if (property is { CanRead: true, CanWrite: true } && property.GetIndexParameters().Length == 0) + { + property.SetValue(copy, property.GetValue(row)); + } + } + + return copy; + } + + /// A copy without the file, for lists and history. + public static EInvoice Light(EInvoice e) => new() + { + Id = e.Id, + Family = e.Family, + DocumentId = e.DocumentId, + Kind = e.Kind, + DocumentNumber = e.DocumentNumber, + DocumentDate = e.DocumentDate, + PartyId = e.PartyId, + DocumentType = e.DocumentType, + FileName = e.FileName, + Progressive = e.Progressive, + Format = e.Format, + RecipientCode = e.RecipientCode, + RecipientPec = e.RecipientPec, + TotalAmount = e.TotalAmount, + Status = e.Status, + ChannelCode = e.ChannelCode, + ExchangeId = e.ExchangeId, + MessageId = e.MessageId, + GeneratedAt = e.GeneratedAt, + SentAt = e.SentAt, + LastNotificationAt = e.LastNotificationAt, + LastMessage = e.LastMessage, + SendAttempts = e.SendAttempts, + Superseded = e.Superseded, + IsDemo = e.IsDemo, + CreatedAt = e.CreatedAt, + CreatedBy = e.CreatedBy, + UpdatedAt = e.UpdatedAt, + UpdatedBy = e.UpdatedBy, + RowVersion = e.RowVersion, + }; +} diff --git a/src/Khaemhat.Application/EInvoicing/SdiInboxService.cs b/src/Khaemhat.Application/EInvoicing/SdiInboxService.cs new file mode 100644 index 0000000..c68bce6 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/SdiInboxService.cs @@ -0,0 +1,351 @@ +using Khaemhat.Application.Purchases; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.EInvoicing; + +/// The filter of the invoices received. +/// Only this state. +/// Supplier, VAT number, number or file name. +public sealed record InboxFilter(InboxFileStatus? Status = null, string? Search = null); + +/// A received file stored, or why not. +/// The file. +/// The row of the inbox. +/// Its state. +/// Why it was not stored (error code). +public sealed record InboxStored(string FileName, long? Id, InboxFileStatus? Status, string? Error); + +/// A received invoice registered as a supplier document, or why not. +/// The row of the inbox. +/// The file. +/// The draft supplier document. +/// Why it was not registered (error code). +/// What to check on the draft (codes). +public sealed record InboxRegistered(long Id, string FileName, long? PurchaseDocumentId, string? Error, IReadOnlyList Warnings); + +/// +/// The invoices received from the SDI (SPEC §11.9, issue #79): every file that arrives through a channel, or that the +/// user uploads, is kept as it was received with its metadata file (MT); the user registers it as a draft supplier +/// invoice (with the import of mockup 034), or discards it. A file is kept once, by its hash. +/// +/// Permissions: einvoice.inbox.read to see, einvoice.inbox.import to upload, register and discard +/// (registering also needs purchases.invoice.write). +public sealed class SdiInboxService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly PurchaseInvoiceImportService _import; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The import of supplier invoices. + /// The clock. + public SdiInboxService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, PurchaseInvoiceImportService import, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(import); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _import = import; + _clock = clock; + } + + /// The invoices received, newest first (files not loaded). + /// Who looks: needs einvoice.inbox.read. + /// The company. + /// The filter. + /// Cancellation. + /// The rows. + public async Task> ListAsync(Actor actor, string companyCode, InboxFilter filter, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(filter); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For(); + if (filter.Status is { } status) + { + query = query.Where(f => f.Status == status); + } + + var rows = (await uow.Repository().ListAsync(query.OrderByDescending(f => f.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items + .Select(Light); + if (!string.IsNullOrWhiteSpace(filter.Search)) + { + var text = filter.Search.Trim(); + rows = rows.Where(f => Has(f.SupplierName, text) || Has(f.SupplierVat, text) || Has(f.Number, text) || Has(f.FileName, text) || Has(f.ExchangeId, text)); + } + + return [.. rows]; + } + + /// The received file, as it arrived. + /// Who downloads: needs einvoice.inbox.read. + /// The company. + /// The row. + /// The metadata file (MT) instead of the invoice. + /// Cancellation. + /// Name and content. + public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, bool metadata = false, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var row = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + return metadata + ? (row.MetadataFileName ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound), row.Metadata ?? []) + : (row.FileName, row.Content); + } + + /// Stores files the user uploads (downloaded from the portal of the AdE or received elsewhere). + /// Who uploads: needs einvoice.inbox.import. + /// The company. + /// The files. + /// Cancellation. + /// What happened to each. + public async Task> UploadAsync( + Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(files); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var reader = pack.GetFeature(); + var receipts = pack.GetFeature(); + var result = new List(); + foreach (var (name, content) in files) + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + InboxStored stored; + if (receipts is not null && receipts.IsReceipt(name, content) && TryRead(receipts, name, content) is { Kind: EInvoiceReceiptKind.Metadata } meta) + { + var row = await AttachMetadataCoreAsync(uow, meta, cancellationToken).ConfigureAwait(false); + stored = new InboxStored(name, row?.Id, row?.Status, row is null ? EInvoiceErrors.ReceiptUnmatched : null); + } + else + { + stored = await StoreCoreAsync(uow, reader, name, content, _clock.GetUtcNow().UtcDateTime, EInvoiceStore.ManualChannel, null, false, cancellationToken) + .ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + result.Add(stored); + } + + return result; + } + + /// + /// Registers received invoices as draft supplier documents, through the import of supplier invoices: the supplier is + /// found or added, the lines take their items and tax codes, the file is attached. + /// + /// Who registers: needs einvoice.inbox.import and purchases.invoice.write. + /// The company. + /// The rows. + /// Cancellation. + /// What happened to each. + public async Task> RegisterAsync(Actor actor, string companyCode, IReadOnlyList ids, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(ids); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false); + var result = new List(); + foreach (var id in ids.Distinct()) + { + EInvoiceInboxFile row; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + row = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + } + + if (row.Status != InboxFileStatus.New) + { + result.Add(new InboxRegistered(id, row.FileName, row.PurchaseDocumentId, EInvoiceErrors.InboxState, [])); + continue; + } + + var reading = await _import.ReadAsync(actor, company, [(row.FileName, row.Content)], cancellationToken).ConfigureAwait(false); + if (reading.Rejected.Count > 0 || reading.Invoices.Count == 0) + { + result.Add(new InboxRegistered(id, row.FileName, null, (reading.Rejected.Count > 0 ? reading.Rejected[0].Error : PurchaseInvoiceImportService.EmptyArchive), [])); + continue; + } + + var blocked = reading.Invoices.FirstOrDefault(c => !c.CanImport); + if (blocked is not null) + { + result.Add(new InboxRegistered(id, row.FileName, null, (blocked.Problems.Count > 0 ? blocked.Problems[0] : PurchaseInvoiceImportService.UnsupportedType), blocked.Problems)); + continue; + } + + var imported = await _import.ImportAsync(actor, company, reading.Invoices, cancellationToken).ConfigureAwait(false); + var failed = imported.FirstOrDefault(i => i.Error is not null); + var first = imported.FirstOrDefault(i => i.Record is not null); + var documentId = first?.Record?.Header.Id; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var current = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + if (documentId is not null) + { + current.Status = InboxFileStatus.Registered; + current.PurchaseDocumentId = documentId; + current.PartyId = first!.Record!.Header.PartyId ?? current.PartyId; + } + + current.Error = failed?.Error; + await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + result.Add(new InboxRegistered(id, row.FileName, documentId, failed?.Error, [.. imported.SelectMany(i => i.Warnings).Distinct(StringComparer.Ordinal)])); + } + + return result; + } + + /// Discards a received invoice (a copy, a file not for the company), or takes it back. + /// Who does it: needs einvoice.inbox.import. + /// The company. + /// The row. + /// Discard, or take back. + /// Cancellation. + /// A task. + public async Task DiscardAsync(Actor actor, string companyCode, long id, bool discard, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + var allowed = discard ? row.Status is InboxFileStatus.New or InboxFileStatus.Unreadable : row.Status == InboxFileStatus.Discarded; + if (!allowed) + { + throw new ValidationFailedException([":" + EInvoiceErrors.InboxState]); + } + + row.Status = discard ? InboxFileStatus.Discarded : row.SupplierVat is null && row.Number is null ? InboxFileStatus.Unreadable : InboxFileStatus.New; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Stores a received file in the transaction of the caller: read by the pack for the list (supplier, number, date, + /// total); a file the pack cannot read is kept as unreadable, a file already kept is not stored again. + /// + internal static async Task StoreCoreAsync( + IUnitOfWork uow, IIncomingInvoiceReader? reader, string fileName, byte[] content, DateTime receivedAt, string? channel, string? exchangeId, bool demo, + CancellationToken cancellationToken) + { + var repository = uow.Repository(); + var hash = EInvoiceStore.Hash(content); + if (await repository.FindAsync(Query.For().Where(f => f.Hash == hash), cancellationToken).ConfigureAwait(false) is { } known) + { + return new InboxStored(fileName, known.Id, known.Status, EInvoiceErrors.InboxDuplicate); + } + + var row = new EInvoiceInboxFile + { + FileName = EInvoiceStore.Trim(Path.GetFileName(fileName), 200) ?? "fattura.xml", + Hash = hash, + Content = content, + ReceivedAt = receivedAt, + ChannelCode = channel, + ExchangeId = EInvoiceStore.Trim(exchangeId, 40), + Status = InboxFileStatus.Unreadable, + IsDemo = demo, + }; + try + { + if (reader is not null && reader.CanRead(fileName, content)) + { + var file = reader.Read(fileName, content); + var invoice = file.Invoices[0]; + row.SupplierVat = EInvoiceStore.Trim((file.Supplier.CountryCode ?? string.Empty) + (file.Supplier.VatNumber ?? file.Supplier.TaxCode), 30); + row.SupplierName = EInvoiceStore.Trim(file.Supplier.DisplayName, 200); + row.DocumentType = invoice.DocumentType; + row.Number = EInvoiceStore.Trim(invoice.Number, 40); + row.DocumentDate = invoice.Date; + row.TotalAmount = file.Invoices.Count == 1 ? invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) : null; + row.PartyId = await PurchaseInvoiceImportService.FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false); + row.Status = InboxFileStatus.New; + } + else + { + row.Error = IncomingInvoiceErrors.NotReadable; + } + } + catch (IncomingInvoiceException ex) + { + row.Error = ex.Code; + } + + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + return new InboxStored(fileName, row.Id, row.Status, null); + } + + /// Keeps the metadata file (MT) with the invoice it describes, by the name of the invoice file. + internal static async Task AttachMetadataCoreAsync(IUnitOfWork uow, EInvoiceReceipt metadata, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + var stem = metadata.InvoiceFileName is { } name ? EInvoiceStore.Stem(name) : EInvoiceStore.InvoiceStem(metadata.FileName); + if (stem is null) + { + return null; + } + + EInvoiceInboxFile? row = null; + foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" }) + { + row = await repository.FindAsync(Query.For().Where(f => f.FileName == candidate).OrderByDescending(f => f.Id), cancellationToken).ConfigureAwait(false); + if (row is not null) + { + break; + } + } + + if (row is null) + { + return null; + } + + row.MetadataFileName = EInvoiceStore.Trim(metadata.FileName, 200); + row.Metadata = metadata.Content; + row.ExchangeId ??= EInvoiceStore.Trim(metadata.ExchangeId, 40); + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + return row; + } + + private static EInvoiceReceipt? TryRead(IEInvoiceReceiptReader reader, string name, byte[] content) + { + try + { + return reader.Read(name, content); + } + catch (IncomingInvoiceException) + { + return null; + } + } + + private static EInvoiceInboxFile Light(EInvoiceInboxFile row) + { + var copy = EInvoiceStore.Clone(row); + copy.Content = []; + copy.Metadata = null; + return copy; + } + + private static bool Has(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true; +} diff --git a/src/Khaemhat.Application/EInvoicing/SdiPushService.cs b/src/Khaemhat.Application/EInvoicing/SdiPushService.cs new file mode 100644 index 0000000..ada4d25 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/SdiPushService.cs @@ -0,0 +1,138 @@ +using System.Security.Cryptography; +using System.Text; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Tables; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Logging; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.EInvoicing; + +/// The answer to a push of the exchange system. +/// The HTTP status. +/// The content type. +/// The body. +public sealed record SdiPushAnswer(int StatusCode, string ContentType, string Body); + +/// +/// Takes what the SDI pushes to the web service of a company (SdICoop, issue #76): invoices of suppliers and +/// notifications. The request carries the key stored in the channel (header X-Khaemhat-SdiCoop-Key); the mutual +/// TLS with the SDI is the job of the reverse proxy in front of Khaemhat. A disabled company, a channel that is not +/// enabled or a wrong key get nothing. +/// +public sealed partial class SdiPushService +{ + /// The header with the key of the channel. + public const string KeyHeader = "X-Khaemhat-SdiCoop-Key"; + + private readonly ICompanyRegistry _companies; + private readonly ILicenseGate _license; + private readonly IUnitOfWorkFactory _factory; + private readonly CompanyFiscalContext _packs; + private readonly ISecretProtector _secrets; + private readonly EInvoicePollingService _polling; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + + /// Creates the service. + /// The companies. + /// The licence. + /// The units of work. + /// The fiscal pack of each company. + /// Opens the key of the channel. + /// Sorts the files received. + /// The clock. + /// The log (section SDI). + public SdiPushService( + ICompanyRegistry companies, ILicenseGate license, IUnitOfWorkFactory factory, CompanyFiscalContext packs, ISecretProtector secrets, + EInvoicePollingService polling, TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(companies); + ArgumentNullException.ThrowIfNull(license); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(secrets); + ArgumentNullException.ThrowIfNull(polling); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _companies = companies; + _license = license; + _factory = factory; + _packs = packs; + _secrets = secrets; + _polling = polling; + _clock = clock; + _logger = logger; + } + + /// Takes a push. + /// The company in the address. + /// The key in the header. + /// The content type. + /// The body. + /// Cancellation. + /// The answer. + public async Task ReceiveAsync(string companyCode, string? key, string? contentType, byte[] body, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(body); + using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)); + var notFound = new SdiPushAnswer(404, "text/plain", "Not found."); + if (!_license.IsModuleActive(ModuleCodes.EInvoicing) + || await _companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false) is not { } company + || company.Status is CompanyStatus.Disabled) + { + return notFound; + } + + var pack = await _packs.PackOfAsync(company.Code, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } reader) + { + return notFound; + } + + var channel = reader.Channel; + EInvoiceChannelSetting? row; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false)) + { + var rows = (await uow.Repository().ListAsync(Query.For().Where(c => c.Code == channel).Take(1), cancellationToken) + .ConfigureAwait(false)).Items; + row = rows.Count > 0 ? rows[0] : null; + } + + var expected = row is { Enabled: true, ProtectedApiKey: { Length: > 0 } stored } ? _secrets.Unprotect(stored, EInvoiceStore.SecretPurpose) : null; + if (expected is null || key is null || !SameKey(expected, key)) + { + LogRefused(_logger, company.Code, channel); + return new SdiPushAnswer(401, "text/plain", "Unauthorized."); + } + + if (reader.Read(contentType, body) is not { } push) + { + var (type, refusal) = reader.Refusal(); + return new SdiPushAnswer(400, type, refusal); + } + + var now = _clock.GetUtcNow(); + var messageKey = push.ExchangeId ?? EInvoiceStore.Hash(body); + var files = push.Files.Select(f => new EInvoiceIncoming(f.FileName, f.Content, now, messageKey, null)).ToList(); + var outcome = await _polling.ReceivePushedAsync(company.Code, channel, files, cancellationToken).ConfigureAwait(false); + LogReceived(_logger, company.Code, channel, outcome.Invoices, outcome.Receipts); + return new SdiPushAnswer(200, push.AnswerContentType, push.Answer); + } + + private static bool SameKey(string expected, string given) => + CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(expected)), SHA256.HashData(Encoding.UTF8.GetBytes(given))); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Push of channel {Channel} for company {Company} refused: wrong key or channel not enabled.")] + private static partial void LogRefused(ILogger logger, string company, string channel); + + [LoggerMessage(Level = LogLevel.Information, Message = "Push of channel {Channel} for company {Company}: {Invoices} invoices, {Receipts} notifications.")] + private static partial void LogReceived(ILogger logger, string company, string channel, int invoices, int receipts); +} diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index 51c3d98..7bb9b04 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -61,6 +61,7 @@ public sealed class JobScheduler new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600), new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800), new("finance.dunning", "Solleciti automatici", Treasury.DunningJob.JobType, "0 7 * * 1-5", 1800, UsesNetwork: true), + new("einvoice.poll", "Lettura dei canali SDI", EInvoicing.EInvoicePollingJob.JobType, "*/15 * * * *", 900, UsesNetwork: true), ]; private readonly IUnitOfWorkFactory _factory; diff --git a/src/Khaemhat.Application/Modules/BuiltInModules.cs b/src/Khaemhat.Application/Modules/BuiltInModules.cs index ca98c18..e9a2e92 100644 --- a/src/Khaemhat.Application/Modules/BuiltInModules.cs +++ b/src/Khaemhat.Application/Modules/BuiltInModules.cs @@ -70,7 +70,8 @@ public static class BuiltInModules ("einvoice.document.read", "Vedere i documenti elettronici"), ("einvoice.document.send", "Inviare documenti allo SDI"), ("einvoice.inbox.read", "Vedere le fatture ricevute"), - ("einvoice.inbox.import", "Importare le fatture ricevute")), + ("einvoice.inbox.import", "Importare le fatture ricevute"), + ("einvoice.channel.manage", "Configurare i canali verso lo SDI")), Module(ModuleCodes.Intrastat, "Intrastat", ("intrastat.list.read", "Vedere gli elenchi Intrastat"), ("intrastat.list.write", "Compilare gli elenchi Intrastat"), diff --git a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs index 19bff2a..39a9256 100644 --- a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs +++ b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs @@ -26,7 +26,7 @@ namespace Khaemhat.Application.Purchases; /// Taxable plus tax of the summary, plus rounding: what the total should be. /// What stops or warns (resource codes). public sealed record IncomingCandidate( - string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal, + string FileName, EInvoiceFile File, EInvoiceBody Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal, IReadOnlyList Problems) { /// Whether it can be registered. @@ -141,7 +141,7 @@ public sealed class PurchaseInvoiceImportService var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); var reader = pack.GetFeature(); var rules = pack.GetFeature(); - var found = new List<(string Name, IncomingInvoiceFile File)>(); + var found = new List<(string Name, EInvoiceFile File)>(); var rejected = new List(); foreach (var (name, content) in Expand(files, rejected)) { @@ -330,16 +330,16 @@ public sealed class PurchaseInvoiceImportService return result; } - private static string KeyOf(IncomingParty party) => + private static string KeyOf(EInvoiceParty party) => (party.VatNumber is { Length: > 0 } vat ? (party.CountryCode ?? "IT") + vat : party.TaxCode ?? string.Empty).ToUpperInvariant(); // The VAT number as the archive keeps it: digits only for Italy, with the country prefix abroad. - private static string? VatOf(IncomingParty party) => + private static string? VatOf(EInvoiceParty party) => party.VatNumber is not { Length: > 0 } vat ? null : party.CountryCode is null or "IT" ? vat : vat.StartsWith(party.CountryCode, StringComparison.OrdinalIgnoreCase) ? vat : party.CountryCode + vat; - private static async Task FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken) + internal static async Task FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken) { var parties = uow.Repository(); if (VatOf(party) is { } vat) @@ -365,7 +365,7 @@ public sealed class PurchaseInvoiceImportService .OrderBy(p => p.Disabled).ThenBy(p => p.Kind == PartyKind.Supplier ? 0 : p.IsSupplier ? 1 : 2).ThenBy(p => p.Id).FirstOrDefault()?.Id; } - private static async Task IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken) + private static async Task IsDuplicateAsync(IUnitOfWork uow, long supplierId, EInvoiceBody invoice, CancellationToken cancellationToken) { var number = invoice.Number.Trim(); var from = new DateOnly(invoice.Date.Year, 1, 1); @@ -377,7 +377,7 @@ public sealed class PurchaseInvoiceImportService cancellationToken).ConfigureAwait(false) > 0; } - private async Task CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken) + private async Task CreateSupplierAsync(Actor actor, string company, EInvoiceParty party, CancellationToken cancellationToken) { var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false); var p = record.Party; @@ -493,7 +493,7 @@ public sealed class PurchaseInvoiceImportService return (saved, warnings); } - private static long? ItemOf(IncomingLine line, Dictionary bySupplierCode, Dictionary byBarcode, Dictionary byCode) + private static long? ItemOf(EInvoiceLine line, Dictionary bySupplierCode, Dictionary byBarcode, Dictionary byCode) { foreach (var code in line.Codes.Select(c => c.Value.Trim())) { diff --git a/src/Khaemhat.Application/Seeding/DemoDataRemover.cs b/src/Khaemhat.Application/Seeding/DemoDataRemover.cs new file mode 100644 index 0000000..e436051 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoDataRemover.cs @@ -0,0 +1,181 @@ +using Khaemhat.Data; +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Application.Seeding; + +/// What the removal of the demo data did. +/// Rows removed, by table. +/// Tables whose own rows (not demo) still refer to demo rows: nothing was removed. +public sealed record DemoRemoval(IReadOnlyDictionary Removed, IReadOnlyList Blockers) +{ + /// Whether the demo data were removed. + public bool Done => Blockers.Count == 0; + + /// All the rows removed. + public int Total => Removed.Values.Sum(); +} + +/// +/// Removes the demo data of a company, and only them (SPEC §14, issue #80): the rows marked is_demo and the rows +/// of the tables without the mark that belong to them through a foreign key (the lines of a demo document, the balances +/// of a demo item). The tables and their keys come from the migrations, so a new module is covered without changes. +/// When a row the user entered refers to a demo row (an invoice to a demo customer) nothing is removed and the tables +/// are reported: the user decides what to do. Everything happens in one transaction. +/// +/// The units of work. +public sealed class DemoDataRemover(IUnitOfWorkFactory factory) +{ + private const string DemoColumn = "is_demo"; + + /// Removes the demo data of a company. + /// The company. + /// Cancellation. + /// What was removed, or what stopped it. + public async Task RemoveAsync(string companyCode, CancellationToken cancellationToken = default) + { + var model = MigrationCatalog.ForCompany().BuildModel(); + var tables = model.Tables.ToDictionary(t => t.Name, StringComparer.Ordinal); + var doomed = new Dictionary(StringComparer.Ordinal); + foreach (var table in tables.Values) + { + Predicate(table, tables, doomed, []); + } + + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + + // Rows of the user that point to demo rows through a key that does not follow them. + var blockers = new List(); + foreach (var table in tables.Values.Where(t => t.Column(DemoColumn) is not null)) + { + foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1)) + { + if (doomed.GetValueOrDefault(key.ReferencedTable) is not { } parent) + { + continue; + } + + var count = await uow.QuerySingleAsync( + SqlFragment.Literal("SELECT COUNT(*) FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ") + + SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(false) + SqlFragment.Literal(" AND ") + + SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable) + + SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")"), + cancellationToken).ConfigureAwait(false); + if (count > 0 && !blockers.Contains(table.Name)) + { + blockers.Add(table.Name); + } + } + } + + if (blockers.Count > 0) + { + await uow.RollbackAsync(cancellationToken).ConfigureAwait(false); + return new DemoRemoval(new Dictionary(), blockers); + } + + var removed = new Dictionary(StringComparer.Ordinal); + foreach (var table in DeleteOrder(tables.Values.Where(t => doomed.GetValueOrDefault(t.Name) is not null).ToList())) + { + var where = doomed[table.Name]!; + + // A key to the same table (an item and its parent) is cleared first, so the rows can go in one statement. + foreach (var key in table.ForeignKeys.Where(k => k.ReferencedTable == table.Name && k.Columns.Count == 1)) + { + if (table.Column(key.Columns[0]) is { IsNullable: true }) + { + await uow.ExecuteAsync( + SqlFragment.Literal("UPDATE ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" SET ") + SqlFragment.Identifier(key.Columns[0]) + + SqlFragment.Literal(" = NULL WHERE ") + where, + cancellationToken).ConfigureAwait(false); + } + } + + var rows = await uow.ExecuteAsync(SqlFragment.Literal("DELETE FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ") + where, cancellationToken) + .ConfigureAwait(false); + if (rows > 0) + { + removed[table.Name] = rows; + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return new DemoRemoval(removed, []); + } + + // The rows of a table that go: marked demo, or (for a table without the mark) belonging to a row that goes. + private static SqlFragment? Predicate(TableDefinition table, Dictionary tables, Dictionary doomed, HashSet visiting) + { + if (doomed.TryGetValue(table.Name, out var known)) + { + return known; + } + + if (table.Column(DemoColumn) is not null) + { + var own = SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(true); + doomed[table.Name] = own; + return own; + } + + if (table.ForeignKeys.Count == 0) + { + doomed[table.Name] = null; + return null; + } + + if (!visiting.Add(table.Name)) + { + return null; + } + + var parts = new List(); + foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1)) + { + if (tables.TryGetValue(key.ReferencedTable, out var parentTable) && Predicate(parentTable, tables, doomed, visiting) is { } parent) + { + parts.Add(SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable) + + SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")")); + } + } + + visiting.Remove(table.Name); + var result = parts.Count == 0 ? null : SqlFragment.Join(" OR ", parts.Select(p => p.Parenthesize())).Parenthesize(); + doomed[table.Name] = result; + return result; + } + + // Children before their parents. + private static List DeleteOrder(List tables) + { + var names = tables.Select(t => t.Name).ToHashSet(StringComparer.Ordinal); + var result = new List(); + var placed = new HashSet(StringComparer.Ordinal); + while (result.Count < tables.Count) + { + var progress = false; + foreach (var table in tables.Where(t => !placed.Contains(t.Name))) + { + // A table goes once no table still to place refers to it. + var referenced = tables.Any(other => !placed.Contains(other.Name) && other.Name != table.Name + && other.ForeignKeys.Any(k => k.ReferencedTable == table.Name && names.Contains(other.Name))); + if (!referenced) + { + result.Add(table); + placed.Add(table.Name); + progress = true; + } + } + + if (!progress) + { + // A cycle between tables: the rest in any order (keys that set null resolve it). + result.AddRange(tables.Where(t => !placed.Contains(t.Name))); + break; + } + } + + return result; + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoEInvoiceSeeder.cs b/src/Khaemhat.Application/Seeding/DemoEInvoiceSeeder.cs new file mode 100644 index 0000000..daca0db --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoEInvoiceSeeder.cs @@ -0,0 +1,289 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.EInvoicing; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Seeding; + +/// +/// The demo electronic invoice (SPEC §14, issue #80): the PEC channel (paused, so the demo never writes to a real +/// mailbox) and the intermediary, the routing rules, the files of the demo invoices with the notifications the SDI +/// would have sent (delivered, one rejected to correct, one not delivered, the last ones still waiting), and three +/// supplier invoices received with their metadata. The notifications are written in the layout of the SDI and read by +/// the fiscal pack, as real ones. It runs after the demo treasury, only when the electronic invoice (EINV) is licensed +/// and only once: when the company has e-invoices it adds nothing. +/// +/// The e-invoices. +/// The fiscal pack of the company. +/// Protects the demo password. +/// Reads and writes the company. +/// Whether the electronic invoice is licensed. +public sealed class DemoEInvoiceSeeder( + EInvoiceService invoices, CompanyFiscalContext packs, ISecretProtector secrets, IUnitOfWorkFactory factory, ILicenseGate licenses) + : ICompanySeeder +{ + /// The demo certified mailbox. + public const string Mailbox = "fatture@pec.khaemhat-demo.it"; + + /// How many of the last invoices stay without a file (to generate). + public const int LeftToGenerate = 1; + + /// How many files stay generated and not sent. + public const int LeftToSend = 1; + + /// How many files sent stay waiting for the receipt. + public const int LeftWaiting = 2; + + private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0"; + + /// + public int Order => 60; + + /// + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.EInvoicing)) + { + return; + } + + var pack = await packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } writer || pack.GetFeature() is not { } validator + || pack.GetFeature() is not { } receipts) + { + return; + } + + List documents; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) + { + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false) is null) + { + return; + } + + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await ChannelsAsync(uow, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + documents = [.. (await uow.Repository() + .ListAsync(Query.For().Where(d => d.IsDemo && d.Status == DocumentStatus.Issued).OrderBy(d => d.DocumentDate).OrderBy(d => d.Id), cancellationToken) + .ConfigureAwait(false)).Items.Where(d => EInvoiceBuilder.IsElectronic(d.Kind))]; + } + + var generated = new List(); + foreach (var document in documents.Take(Math.Max(0, documents.Count - LeftToGenerate))) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var result = await invoices.GenerateCoreAsync(uow, writer, validator, DocumentFamily.SaleDocument, document.Id, Actor.System.UserName, cancellationToken) + .ConfigureAwait(false); + if (result.Invoice is { } invoice) + { + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + generated.Add(invoice); + } + else + { + await uow.RollbackAsync(cancellationToken).ConfigureAwait(false); + } + } + + var sent = generated.Take(Math.Max(0, generated.Count - LeftToSend)).ToList(); + var answered = sent.Count - LeftWaiting; + for (var i = 0; i < sent.Count; i++) + { + var invoice = sent[i]; + var exchangeId = (4_000_000_000L + invoice.Progressive).ToString(CultureInfo.InvariantCulture); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var current = await uow.Repository().GetAsync(invoice.Id, cancellationToken).ConfigureAwait(false); + if (current is null) + { + continue; + } + + await invoices.MarkSentCoreAsync(uow, current, "PEC", null, "", Actor.System.UserName, cancellationToken) + .ConfigureAwait(false); + + // The file was written and sent the day after the document, not today. + var sentAt = new DateTimeOffset(current.DocumentDate.AddDays(1).ToDateTime(new TimeOnly(9, 40)), TimeSpan.FromHours(1)).UtcDateTime; + current.GeneratedAt = sentAt.AddMinutes(-5); + current.SentAt = sentAt; + await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false); + if (i < answered) + { + var at = new DateTimeOffset(current.DocumentDate.AddDays(1).ToDateTime(new TimeOnly(10, 15)), TimeSpan.FromHours(1)); + var stem = EInvoiceStore.Stem(current.FileName); + var (code, root, body) = (i % 9) switch + { + 1 when answered >= 3 => ("NS", "NotificaScarto", Rejection(current.FileName, exchangeId, at)), + 4 when answered >= 5 => ("MC", "NotificaMancataConsegna", Basic(current.FileName, exchangeId, at, "Casella del destinatario piena: fattura messa a disposizione nell'area riservata.")), + _ => ("RC", "RicevutaConsegna", Delivery(current.FileName, exchangeId, at)), + }; + var name = stem + "_" + code + "_001.xml"; + var receipt = receipts.Read(name, Notification(root, body)); + await invoices.ApplyReceiptCoreAsync(uow, receipt, "PEC", Actor.System.UserName, true, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await InboxAsync(companyCode, pack, writer, documents.FirstOrDefault(), cancellationToken).ConfigureAwait(false); + } + + /// A notification as the SDI writes it (MessaggiTypes v1.0). + /// The root element. + /// The children. + /// The file. + public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes( + $"""{body}"""); + + private static string Stamp(DateTimeOffset at) => at.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", CultureInfo.InvariantCulture); + + private static string Delivery(string file, string exchangeId, DateTimeOffset at) => + $"{exchangeId}{file}demo{Stamp(at.AddMinutes(-20))}" + + $"{Stamp(at)}{exchangeId}1"; + + private static string Basic(string file, string exchangeId, DateTimeOffset at, string note) => + $"{exchangeId}{file}demo{Stamp(at.AddMinutes(-20))}" + + $"{note}{exchangeId}2{note}"; + + private static string Rejection(string file, string exchangeId, DateTimeOffset at) => + $"{exchangeId}{file}demo{Stamp(at.AddMinutes(-20))}" + + "003051.4.1.1.2 IdCodice del cessionario/committente non valido" + + "Verificare la partita IVA del cliente in anagrafica" + + $"{exchangeId}3"; + + private async Task ChannelsAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var channels = uow.Repository(); + await channels.InsertAsync( + new EInvoiceChannelSetting + { + Code = "PEC", + Enabled = true, + Paused = true, + Mailbox = Mailbox, + SmtpHost = "smtps.pec.khaemhat-demo.it", + SmtpPort = 465, + ImapHost = "imaps.pec.khaemhat-demo.it", + ImapPort = 993, + Tls = true, + UserName = Mailbox, + ProtectedPassword = secrets.Protect("demo-non-valida", EInvoiceStore.SecretPurpose), + ExchangeAddress = "sdi27@pec.fatturapa.it", + ArchiveFolder = "SDI/Archiviati", + LastCheckMessage = "Canale dimostrativo in pausa: nessun messaggio viene inviato o letto.", + IsDemo = true, + }, + cancellationToken).ConfigureAwait(false); + await channels.InsertAsync( + new EInvoiceChannelSetting + { + Code = "INTA", + Enabled = false, + Endpoint = "https://api.intermediario.khaemhat-demo.it/v1", + TestEnvironment = true, + IsDemo = true, + }, + cancellationToken).ConfigureAwait(false); + var rules = uow.Repository(); + await rules.InsertAsync(new SdiRoutingRule { Position = 10, Condition = SdiRoutingCondition.PublicAdministration, ChannelCode = "PEC", IsDemo = true }, cancellationToken) + .ConfigureAwait(false); + await rules.InsertAsync(new SdiRoutingRule { Position = 20, Condition = SdiRoutingCondition.DailyVolume, Value = "200", ChannelCode = "INTA", FallbackChannelCode = "PEC", IsDemo = true }, + cancellationToken).ConfigureAwait(false); + await rules.InsertAsync(new SdiRoutingRule { Position = 90, Condition = SdiRoutingCondition.Default, ChannelCode = "PEC", FallbackChannelCode = "INTA", IsDemo = true }, + cancellationToken).ConfigureAwait(false); + } + + // Three supplier invoices received through the SDI, with their metadata: made from a demo invoice, turned around. + private async Task InboxAsync(string companyCode, IFiscalPack pack, IEInvoiceWriter writer, SaleDocument? model, CancellationToken cancellationToken) + { + if (model is null || pack.GetFeature() is not { } reader) + { + return; + } + + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var record = await DocumentEngine.LoadAsync(uow, DocumentFamily.SaleDocument, model.Id, cancellationToken).ConfigureAwait(false); + if (profile is null || record is null) + { + return; + } + + var suppliers = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo && p.Kind == PartyKind.Supplier).OrderBy(p => p.Id).Take(3), cancellationToken) + .ConfigureAwait(false)).Items; + var (file, _, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false); + var customer = EInvoiceBuilder.CompanyParty(profile); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var n = 0; + foreach (var supplier in suppliers) + { + n++; + var supplierId = supplier.Id; + var fiscal = await uow.Repository().FindAsync(Query.For().Where(f => f.PartyId == supplierId), cancellationToken).ConfigureAwait(false); + var party = EInvoiceBuilder.PartyOf(supplier, fiscal, supplier: true); + var country = party.CountryCode ?? "IT"; + var id = party.VatNumber ?? party.TaxCode ?? "00000000000"; + var date = model.DocumentDate.AddDays(-3 * n); + var name = writer.FileName(country, id, 100 + n); + var number = string.Create(CultureInfo.InvariantCulture, $"{date.Year}/{(40 * n) + 7}"); + var incoming = file with + { + FileName = name, + ProgressiveNumber = writer.Progressive(100 + n), + TransmitterCountry = country, + TransmitterId = id, + RecipientCode = profile.RecipientCode is { Length: 7 } code ? code : "0000000", + RecipientPec = profile.RecipientCode is { Length: 7 } ? null : Mailbox, + Supplier = party, + Customer = customer, + Invoices = [file.Invoices[0] with { Number = number, Date = date, DocumentType = "TD01" }], + IssuedBy = null, + }; + var content = writer.Write(incoming); + var receivedAt = date.AddDays(1).ToDateTime(new TimeOnly(9, 30 + n), DateTimeKind.Utc); + var exchangeId = (5_000_000_000L + n).ToString(CultureInfo.InvariantCulture); + var stored = await SdiInboxService.StoreCoreAsync(uow, reader, name, content, receivedAt, "PEC", exchangeId, true, cancellationToken).ConfigureAwait(false); + if (stored.Id is { } rowId) + { + var row = await uow.Repository().GetAsync(rowId, cancellationToken).ConfigureAwait(false); + if (row is not null) + { + row.MetadataFileName = EInvoiceStore.Stem(name) + "_MT_001.xml"; + row.Metadata = Notification("FileMetadati", + $"{exchangeId}{name}demo{incoming.RecipientCode}" + + $"FPR121{exchangeId}9"); + await uow.Repository().UpdateAsync(row, cancellationToken).ConfigureAwait(false); + } + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs b/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs index 22994c0..d917f82 100644 --- a/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs @@ -41,7 +41,15 @@ public sealed class DemoLedgerSeeder( public int Order => 40; /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo) diff --git a/src/Khaemhat.Application/Seeding/DemoMarker.cs b/src/Khaemhat.Application/Seeding/DemoMarker.cs new file mode 100644 index 0000000..ccf9ebe --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoMarker.cs @@ -0,0 +1,71 @@ +using Khaemhat.Data; +using Khaemhat.Data.Migrations; + +namespace Khaemhat.Application.Seeding; + +/// +/// Marks as demo every row a demo seeder created, also those the services wrote for it (the entries of an issued +/// invoice, the open items, the payments): the last identifier of every table with is_demo is taken before the +/// seeder runs, and the rows after it are marked when it ends. So finds them all. A demo +/// seed is an administrative operation: rows the users would write meanwhile in the same company would be marked too. +/// +internal sealed class DemoMarker +{ + private const string DemoColumn = "is_demo"; + + private static readonly Lazy> Tables = new(() => + [.. MigrationCatalog.ForCompany().BuildModel().Tables.Where(t => t.Column(DemoColumn) is not null && t.PrimaryKey is ["id"]).Select(t => t.Name).Order(StringComparer.Ordinal)]); + + private readonly IUnitOfWorkFactory _factory; + private readonly string _company; + private readonly Dictionary _last; + + private DemoMarker(IUnitOfWorkFactory factory, string company, Dictionary last) + { + _factory = factory; + _company = company; + _last = last; + } + + /// Runs a demo seeder and marks what it created. + /// The units of work. + /// The company. + /// The seeder. + /// Cancellation. + /// A task. + public static async Task RunAsync(IUnitOfWorkFactory factory, string company, Func seed, CancellationToken cancellationToken) + { + var marker = await TakeAsync(factory, company, cancellationToken).ConfigureAwait(false); + await seed().ConfigureAwait(false); + await marker.MarkAsync(cancellationToken).ConfigureAwait(false); + } + + private static async Task TakeAsync(IUnitOfWorkFactory factory, string company, CancellationToken cancellationToken) + { + var last = new Dictionary(StringComparer.Ordinal); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + foreach (var table in Tables.Value) + { + last[table] = await uow.QuerySingleAsync( + SqlFragment.Literal("SELECT MAX(id) FROM ") + SqlFragment.Identifier(table), cancellationToken).ConfigureAwait(false) ?? 0L; + } + + return new DemoMarker(factory, company, last); + } + + private async Task MarkAsync(CancellationToken cancellationToken) + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(_company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + foreach (var (table, last) in _last) + { + await uow.ExecuteAsync( + SqlFragment.Literal("UPDATE ") + SqlFragment.Identifier(table) + SqlFragment.Literal(" SET ") + SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + + SqlFragment.Parameter(true) + SqlFragment.Literal(" WHERE id > ") + SqlFragment.Parameter(last) + SqlFragment.Literal(" AND ") + SqlFragment.Identifier(DemoColumn) + + SqlFragment.Literal(" = ") + SqlFragment.Parameter(false), + cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs index 8f4edbd..bcb596a 100644 --- a/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs @@ -43,7 +43,15 @@ public sealed class DemoPurchasesSeeder( public int Order => 30; /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo) diff --git a/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs index 1fa80f7..5834b1f 100644 --- a/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs @@ -43,7 +43,15 @@ public sealed class DemoSalesSeeder( public int Order => 20; /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo) diff --git a/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs index bc950ab..f42ac01 100644 --- a/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs @@ -78,7 +78,15 @@ public sealed class DemoTreasurySeeder( } /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.Finance)) diff --git a/src/Khaemhat.Core/Documents/DocumentStateMachine.cs b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs index 69b5b60..6057681 100644 --- a/src/Khaemhat.Core/Documents/DocumentStateMachine.cs +++ b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs @@ -94,7 +94,7 @@ public static class DocumentStateMachine Add(DocumentLifecycle.Invoice, DocumentStatus.SdiGenerated, (Copy, null), (DocumentAction.GenerateXml, null), (DocumentAction.Send, DocumentStatus.SdiSent), (DocumentAction.Cancel, DocumentStatus.Cancelled)); Add(DocumentLifecycle.Invoice, DocumentStatus.SdiSent, (Copy, null), (DocumentAction.MarkDelivered, DocumentStatus.SdiDelivered), (DocumentAction.MarkRejected, DocumentStatus.SdiRejected), (DocumentAction.MarkNotDelivered, DocumentStatus.SdiNotDelivered)); - Add(DocumentLifecycle.Invoice, DocumentStatus.SdiRejected, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled)); + Add(DocumentLifecycle.Invoice, DocumentStatus.SdiRejected, (Edit, null), (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled)); Add(DocumentLifecycle.Invoice, DocumentStatus.SdiDelivered, (Copy, null)); Add(DocumentLifecycle.Invoice, DocumentStatus.SdiNotDelivered, (Copy, null)); Add(DocumentLifecycle.Invoice, DocumentStatus.Cancelled, (Copy, null)); diff --git a/src/Khaemhat.Core/EInvoicing/EInvoicing.cs b/src/Khaemhat.Core/EInvoicing/EInvoicing.cs new file mode 100644 index 0000000..0a6268c --- /dev/null +++ b/src/Khaemhat.Core/EInvoicing/EInvoicing.cs @@ -0,0 +1,534 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.EInvoicing; + +/// Where an e-invoice is in its exchange with the SDI (SPEC §11.9, mockup 058). +public enum EInvoiceStatus +{ + /// The file was written and checked; not sent yet. + Generated = 0, + + /// Taken by the channel; waiting for the receipt of the SDI. + Sent = 1, + + /// Delivered to the customer (RC). + Delivered = 2, + + /// Not delivered, but available in the customer's tax drawer (MC): the invoice is issued. + NotDelivered = 3, + + /// Rejected by the SDI (NS): the invoice is not issued; correct it and send it again. + Rejected = 4, + + /// Accepted by the public administration (NE EC01). + Accepted = 5, + + /// Refused by the public administration (NE EC02): a credit note is needed. + Refused = 6, + + /// The public administration did not answer within 15 days (DT). + TermsElapsed = 7, + + /// A public administration could not be reached (AT): the invoice is issued. + Undeliverable = 8, +} + +/// What a notification of the SDI does to an e-invoice. +public static class EInvoiceStates +{ + /// The state after a notification, by its code (RC, NS, MC, NE, DT, AT); when it does not change. + /// The code of the notification. + /// The outcome of an NE (EC01, EC02). + /// The new state. + public static EInvoiceStatus? After(string code, string? outcome) => code switch + { + "RC" => EInvoiceStatus.Delivered, + "NS" => EInvoiceStatus.Rejected, + "MC" => EInvoiceStatus.NotDelivered, + "NE" => outcome == "EC02" ? EInvoiceStatus.Refused : EInvoiceStatus.Accepted, + "DT" => EInvoiceStatus.TermsElapsed, + "AT" => EInvoiceStatus.Undeliverable, + _ => null, + }; + + /// The state of the document for a state of its e-invoice. + /// The state of the e-invoice. + /// The state of the document. + public static DocumentStatus DocumentStatusOf(EInvoiceStatus status) => status switch + { + EInvoiceStatus.Generated => DocumentStatus.SdiGenerated, + EInvoiceStatus.Sent => DocumentStatus.SdiSent, + EInvoiceStatus.Rejected => DocumentStatus.SdiRejected, + EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable => DocumentStatus.SdiNotDelivered, + _ => DocumentStatus.SdiDelivered, + }; + + /// The steps of the document that lead from one state to another. + /// The state of the document now. + /// The state of the e-invoice. + /// The actions, in order (empty when already there). + public static IReadOnlyList StepsTo(DocumentStatus current, EInvoiceStatus target) + { + var steps = new List(); + var wanted = DocumentStatusOf(target); + if (current == wanted && target != EInvoiceStatus.Generated) + { + return steps; + } + + if (current is DocumentStatus.Issued or DocumentStatus.SdiRejected || target == EInvoiceStatus.Generated) + { + steps.Add(DocumentAction.GenerateXml); + } + + if (target == EInvoiceStatus.Generated) + { + return steps; + } + + // A notification for a file never marked as sent (sent from the portal of the AdE): it was sent. + if (current is not DocumentStatus.SdiSent) + { + steps.Add(DocumentAction.Send); + } + + if (target == EInvoiceStatus.Sent) + { + return steps; + } + + steps.Add(wanted switch + { + DocumentStatus.SdiRejected => DocumentAction.MarkRejected, + DocumentStatus.SdiNotDelivered => DocumentAction.MarkNotDelivered, + _ => DocumentAction.MarkDelivered, + }); + return steps; + } + + /// Whether the invoice is legally issued in this state (everything after the SDI took it, except a rejection). + /// The state. + /// when issued. + public static bool IsIssued(EInvoiceStatus status) => status is not (EInvoiceStatus.Generated or EInvoiceStatus.Sent or EInvoiceStatus.Rejected); + + /// Whether the state needs the user (a rejection, a refusal). + /// The state. + /// when something must be done. + public static bool NeedsAction(EInvoiceStatus status) => status is EInvoiceStatus.Rejected or EInvoiceStatus.Refused; +} + +/// +/// An e-invoice file of a document (SPEC §11.9, e_invoices): the file as sent, its name and progressive, the +/// channel and the identifier of the SDI, the last state. A file rejected and sent again leaves its row, marked as +/// superseded, and a new one takes its place. +/// +public sealed class EInvoice : Entity, IDemoMarkable +{ + /// The family of the document. + public DocumentFamily Family { get; set; } + + /// The document. + public long DocumentId { get; set; } + + /// The kind of the document. + public DocumentKind Kind { get; set; } + + /// The number of the document, for the lists. + public string? DocumentNumber { get; set; } + + /// The date of the document. + public DateOnly DocumentDate { get; set; } + + /// The customer, or the supplier of a self-invoice. + public long? PartyId { get; set; } + + /// The type of the format (Italy: TD01 …). + public string DocumentType { get; set; } = string.Empty; + + /// The name of the file (Italy: IT01234567890_00001.xml). + public string FileName { get; set; } = string.Empty; + + /// The progressive number of the file in the company. + public long Progressive { get; set; } + + /// The format (Italy: FPR12, FPA12). + public string Format { get; set; } = string.Empty; + + /// The recipient code. + public string? RecipientCode { get; set; } + + /// The certified mailbox of the recipient. + public string? RecipientPec { get; set; } + + /// The total of the document. + public decimal TotalAmount { get; set; } + + /// The state. + public EInvoiceStatus Status { get; set; } + + /// The channel it was sent through (MANUAL when sent from the portal of the AdE). + public string? ChannelCode { get; set; } + + /// The identifier of the SDI. + public string? ExchangeId { get; set; } + + /// The identifier at the channel. + public string? MessageId { get; set; } + + /// When the file was written (UTC). + public DateTime GeneratedAt { get; set; } + + /// When it was sent (UTC). + public DateTime? SentAt { get; set; } + + /// When the last notification arrived (UTC). + public DateTime? LastNotificationAt { get; set; } + + /// The last message: the error of the channel, or the description of the last notification. + public string? LastMessage { get; set; } + + /// How many times sending failed. + public int SendAttempts { get; set; } + + /// The file. + public byte[] Content { get; set; } = []; + + /// Whether a newer file of the same document replaced it. + public bool Superseded { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A notification of the SDI (e_invoice_notifications), kept as received. +public sealed class EInvoiceNotification : Entity, IDemoMarkable +{ + /// The e-invoice it is about, when found. + public long? EInvoiceId { get; set; } + + /// The code (RC, NS, MC, NE, DT, AT, SE). + public string Code { get; set; } = string.Empty; + + /// The name of the notification file. + public string FileName { get; set; } = string.Empty; + + /// The name of the invoice file it is about. + public string? InvoiceFileName { get; set; } + + /// The identifier of the SDI. + public string? ExchangeId { get; set; } + + /// When it was received (UTC). + public DateTime ReceivedAt { get; set; } + + /// The outcome of an NE (EC01, EC02). + public string? Outcome { get; set; } + + /// The description. + public string? Description { get; set; } + + /// The errors of a rejection, one per line: code - description. + public string? Errors { get; set; } + + /// The channel it came from (MANUAL when uploaded). + public string? ChannelCode { get; set; } + + /// The file. + public byte[] Content { get; set; } = []; + + /// + public bool IsDemo { get; set; } +} + +/// Where a received invoice is. +public enum InboxFileStatus +{ + /// Received, to register. + New = 0, + + /// Registered as a supplier invoice or credit note. + Registered = 1, + + /// Set aside by the user (a duplicate, an invoice not for the company). + Discarded = 2, + + /// The file could not be read. + Unreadable = 3, +} + +/// +/// A supplier invoice received through a channel or uploaded (e_invoice_inbox, issue #79): the file with its +/// metadata, what it says, and the purchase document that registers it. The same file never enters twice (hash). +/// +public sealed class EInvoiceInboxFile : Entity, IDemoMarkable +{ + /// The name of the file. + public string FileName { get; set; } = string.Empty; + + /// The SHA-256 of the file, in hexadecimal. + public string Hash { get; set; } = string.Empty; + + /// The file. + public byte[] Content { get; set; } = []; + + /// The name of the metadata file (MT). + public string? MetadataFileName { get; set; } + + /// The metadata file. + public byte[]? Metadata { get; set; } + + /// The identifier of the SDI. + public string? ExchangeId { get; set; } + + /// When it was received (UTC). + public DateTime ReceivedAt { get; set; } + + /// The channel (MANUAL when uploaded). + public string? ChannelCode { get; set; } + + /// The VAT number of the supplier. + public string? SupplierVat { get; set; } + + /// The name of the supplier. + public string? SupplierName { get; set; } + + /// The type of the document (TD01 …). + public string? DocumentType { get; set; } + + /// The number of the invoice. + public string? Number { get; set; } + + /// The date of the invoice. + public DateOnly? DocumentDate { get; set; } + + /// The total of the invoice. + public decimal? TotalAmount { get; set; } + + /// The supplier in the archive, when found. + public long? PartyId { get; set; } + + /// The state. + public InboxFileStatus Status { get; set; } + + /// The purchase document that registers it. + public long? PurchaseDocumentId { get; set; } + + /// Why it could not be read or registered. + public string? Error { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// +/// The settings of a channel in a company (e_invoice_channels, mockup 059). Passwords, keys and certificates are +/// stored protected (ISecretProtector, purpose einvoice.channel) and never shown again. +/// +public sealed class EInvoiceChannelSetting : Entity, IDemoMarkable +{ + /// The code of the channel. + public string Code { get; set; } = string.Empty; + + /// Whether it is used. + public bool Enabled { get; set; } + + /// Whether it is paused: no sending and no polling until resumed. + public bool Paused { get; set; } + + /// The certified mailbox (PEC). + public string? Mailbox { get; set; } + + /// The SMTP server. + public string? SmtpHost { get; set; } + + /// The SMTP port. + public int SmtpPort { get; set; } = 465; + + /// The IMAP server. + public string? ImapHost { get; set; } + + /// The IMAP port. + public int ImapPort { get; set; } = 993; + + /// Whether the connections use TLS. + public bool Tls { get; set; } = true; + + /// The user. + public string? UserName { get; set; } + + /// The password, protected. + public string? ProtectedPassword { get; set; } + + /// The address of the SDI to write to (PEC), learned from its messages. + public string? ExchangeAddress { get; set; } + + /// The folder of the mailbox for processed messages. + public string? ArchiveFolder { get; set; } + + /// The address of the web service or API. + public string? Endpoint { get; set; } + + /// The client certificate (PKCS#12, base64), protected. + public string? ProtectedCertificate { get; set; } + + /// The password of the certificate, protected. + public string? ProtectedCertificatePassword { get; set; } + + /// The API key, protected. + public string? ProtectedApiKey { get; set; } + + /// Whether the test environment is used. + public bool TestEnvironment { get; set; } + + /// When the connection was last tested (UTC). + public DateTime? LastCheckAt { get; set; } + + /// Whether the last test worked. + public bool? LastCheckOk { get; set; } + + /// What the last test said. + public string? LastCheckMessage { get; set; } + + /// When the channel was last read (UTC). + public DateTime? LastPollAt { get; set; } + + /// What the last reading found, or its error. + public string? LastPollMessage { get; set; } + + /// Whether the last reading failed. + public bool LastPollFailed { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// When a routing rule applies. +public enum SdiRoutingCondition +{ + /// Always (the last rule, usually). + Default = 0, + + /// The customer is a public administration. + PublicAdministration = 1, + + /// The customer has the code in . + Party = 2, + + /// The type of the format is the one in (TD01, TD17 …). + DocumentType = 3, + + /// The files sent today are at least the number in . + DailyVolume = 4, +} + +/// A rule of the router (e_invoice_routing, issue #77): the first enabled rule that applies chooses the channel. +public sealed class SdiRoutingRule : Entity, IDemoMarkable +{ + /// The order (lower first). + public int Position { get; set; } + + /// When it applies. + public SdiRoutingCondition Condition { get; set; } + + /// The value of the condition. + public string? Value { get; set; } + + /// The channel. + public string ChannelCode { get; set; } = string.Empty; + + /// The channel used when the first is paused, disabled or fails. + public string? FallbackChannelCode { get; set; } + + /// Whether the rule is ignored. + public bool Disabled { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// What the router knows of a file to send. +/// The type of the format. +/// The code of the customer. +/// Whether the customer is a public administration. +/// How many files were sent today. +public sealed record SdiRoutingInput(string DocumentType, string? PartyCode, bool PublicAdministration, int SentToday); + +/// The channels chosen for a file. +/// The channel to use. +/// The channel to try when the first fails. +/// The rule that chose them. +public sealed record SdiRoute(string Channel, string? Fallback, long? RuleId); + +/// +/// Chooses the channel of a file (SPEC §11.9, issue #77): the enabled rules in order, the first that applies wins; a +/// channel that is paused or disabled gives way to the fallback of the rule. Without rules, the first usable channel +/// in the order of the pack. +/// +public static class SdiRouter +{ + /// Chooses. + /// The file. + /// The rules. + /// The codes of the channels enabled and not paused, in the order of the pack. + /// The route, or when no channel can take the file. + public static SdiRoute? Choose(SdiRoutingInput input, IEnumerable rules, IReadOnlyList usable) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(rules); + ArgumentNullException.ThrowIfNull(usable); + bool Usable(string? code) => code is not null && usable.Contains(code, StringComparer.OrdinalIgnoreCase); + foreach (var rule in rules.Where(r => !r.Disabled).OrderBy(r => r.Position).ThenBy(r => r.Id)) + { + if (!Applies(rule, input)) + { + continue; + } + + if (Usable(rule.ChannelCode)) + { + return new SdiRoute(rule.ChannelCode, Usable(rule.FallbackChannelCode) ? rule.FallbackChannelCode : null, rule.Id); + } + + if (Usable(rule.FallbackChannelCode)) + { + return new SdiRoute(rule.FallbackChannelCode!, null, rule.Id); + } + } + + return usable.Count == 0 ? null : new SdiRoute(usable[0], usable.Count > 1 ? usable[1] : null, null); + } + + private static bool Applies(SdiRoutingRule rule, SdiRoutingInput input) => rule.Condition switch + { + SdiRoutingCondition.Default => true, + SdiRoutingCondition.PublicAdministration => input.PublicAdministration, + SdiRoutingCondition.Party => string.Equals(rule.Value?.Trim(), input.PartyCode, StringComparison.OrdinalIgnoreCase), + SdiRoutingCondition.DocumentType => string.Equals(rule.Value?.Trim(), input.DocumentType, StringComparison.OrdinalIgnoreCase), + SdiRoutingCondition.DailyVolume => int.TryParse(rule.Value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) + && input.SentToday >= limit, + _ => false, + }; +} + +/// A conservation package exported (e_invoice_conservation, issue #79): what went out, and its fingerprint. +public sealed class ConservationExport : Entity +{ + /// The first day. + public DateOnly FromDate { get; set; } + + /// The last day. + public DateOnly ToDate { get; set; } + + /// The files in the package. + public int FileCount { get; set; } + + /// The name of the package. + public string FileName { get; set; } = string.Empty; + + /// The SHA-256 of the package. + public string Hash { get; set; } = string.Empty; + + /// The size in bytes. + public long Size { get; set; } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/EInvoicingMaps.cs b/src/Khaemhat.Data/CompanyDatabase/EInvoicingMaps.cs new file mode 100644 index 0000000..8a2a45f --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/EInvoicingMaps.cs @@ -0,0 +1,106 @@ +using Khaemhat.Core.EInvoicing; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to e_invoices. +public sealed class EInvoiceMap : EntityMap +{ + /// Creates the map. + public EInvoiceMap() + { + ToTable("e_invoices"); + Map(x => x.DocumentNumber).MaxLength(40); + Map(x => x.DocumentType).MaxLength(10); + Map(x => x.FileName).MaxLength(60); + Map(x => x.Format).MaxLength(10); + Map(x => x.RecipientCode).MaxLength(7); + Map(x => x.RecipientPec).MaxLength(254); + Map(x => x.ChannelCode).MaxLength(20); + Map(x => x.ExchangeId).MaxLength(40); + Map(x => x.MessageId).MaxLength(200); + Map(x => x.LastMessage).MaxLength(1000); + } +} + +/// Map of to e_invoice_notifications. +public sealed class EInvoiceNotificationMap : EntityMap +{ + /// Creates the map. + public EInvoiceNotificationMap() + { + ToTable("e_invoice_notifications"); + Map(x => x.Code).MaxLength(4); + Map(x => x.FileName).MaxLength(100); + Map(x => x.InvoiceFileName).MaxLength(100); + Map(x => x.ExchangeId).MaxLength(40); + Map(x => x.Outcome).MaxLength(10); + Map(x => x.Description).MaxLength(1000); + Map(x => x.ChannelCode).MaxLength(20); + } +} + +/// Map of to e_invoice_inbox. +public sealed class EInvoiceInboxFileMap : EntityMap +{ + /// Creates the map. + public EInvoiceInboxFileMap() + { + ToTable("e_invoice_inbox"); + Map(x => x.FileName).MaxLength(100); + Map(x => x.Hash).MaxLength(64); + Map(x => x.MetadataFileName).MaxLength(100); + Map(x => x.ExchangeId).MaxLength(40); + Map(x => x.ChannelCode).MaxLength(20); + Map(x => x.SupplierVat).MaxLength(30); + Map(x => x.SupplierName).MaxLength(200); + Map(x => x.DocumentType).MaxLength(10); + Map(x => x.Number).MaxLength(40); + Map(x => x.Error).MaxLength(500); + } +} + +/// Map of to e_invoice_channels. +public sealed class EInvoiceChannelSettingMap : EntityMap +{ + /// Creates the map. + public EInvoiceChannelSettingMap() + { + ToTable("e_invoice_channels"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Mailbox).MaxLength(254); + Map(x => x.SmtpHost).MaxLength(200); + Map(x => x.ImapHost).MaxLength(200); + Map(x => x.UserName).MaxLength(254); + Map(x => x.ExchangeAddress).MaxLength(254); + Map(x => x.ArchiveFolder).MaxLength(100); + Map(x => x.Endpoint).MaxLength(300); + Map(x => x.LastCheckMessage).MaxLength(1000); + Map(x => x.LastPollMessage).MaxLength(1000); + } +} + +/// Map of to e_invoice_routing. +public sealed class SdiRoutingRuleMap : EntityMap +{ + /// Creates the map. + public SdiRoutingRuleMap() + { + ToTable("e_invoice_routing"); + Map(x => x.Value).MaxLength(40); + Map(x => x.ChannelCode).MaxLength(20); + Map(x => x.FallbackChannelCode).MaxLength(20); + } +} + +/// Map of to e_invoice_conservation. +public sealed class ConservationExportMap : EntityMap +{ + /// Creates the map. + public ConservationExportMap() + { + ToTable("e_invoice_conservation"); + Map(x => x.FileName).MaxLength(100); + Map(x => x.Hash).MaxLength(64); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_004_CreateEInvoicing.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_004_CreateEInvoicing.cs new file mode 100644 index 0000000..ff16dab --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_004_CreateEInvoicing.cs @@ -0,0 +1,159 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// The electronic invoice (SPEC §11.9, ADR 0039, issues #74-#79): the files sent with their state, the notifications +/// of the SDI, the invoices received, the channels with their protected settings, the rules of the router and the log +/// of the conservation packages. +/// +[Migration(20261113_004, "create_einvoicing")] +public sealed class M20261113_004_CreateEInvoicing : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("e_invoices", t => + { + t.Id(); + t.String("family", 40).NotNull(); + t.Int64("document_id").NotNull(); + t.String("kind", 40).NotNull(); + t.String("document_number", 40); + t.Date("document_date").NotNull(); + t.Int64("party_id"); + t.String("document_type", 10).NotNull(); + t.String("file_name", 60).NotNull(); + t.Int64("progressive").NotNull(); + t.String("format", 10).NotNull(); + t.String("recipient_code", 7); + t.String("recipient_pec", 254); + t.Decimal("total_amount").NotNull().Default(0m); + t.String("status", 40).NotNull(); + t.String("channel_code", 20); + t.String("exchange_id", 40); + t.String("message_id", 200); + t.DateTimeUtc("generated_at").NotNull(); + t.DateTimeUtc("sent_at"); + t.DateTimeUtc("last_notification_at"); + t.String("last_message", 1000); + t.Int32("send_attempts").NotNull().Default(0); + t.Bytes("content").NotNull(); + t.Bool("superseded").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_e_invoices_file", "file_name"); + t.Index("ix_e_invoices_document", "family", "document_id"); + t.Index("ix_e_invoices_status", "superseded", "status"); + t.Index("ix_e_invoices_exchange", "exchange_id"); + }); + + schema.CreateTable("e_invoice_notifications", t => + { + t.Id(); + t.Int64("e_invoice_id"); + t.String("code", 4).NotNull(); + t.String("file_name", 100).NotNull(); + t.String("invoice_file_name", 100); + t.String("exchange_id", 40); + t.DateTimeUtc("received_at").NotNull(); + t.String("outcome", 10); + t.String("description", 1000); + t.Text("errors"); + t.String("channel_code", 20); + t.Bytes("content").NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_e_invoice_notifications_file", "file_name"); + t.Index("ix_e_invoice_notifications_invoice", "e_invoice_id"); + t.ForeignKey("fk_e_invoice_notifications_invoice", "e_invoice_id", "e_invoices", ReferentialAction.Cascade); + }); + + schema.CreateTable("e_invoice_inbox", t => + { + t.Id(); + t.String("file_name", 100).NotNull(); + t.String("hash", 64).NotNull(); + t.Bytes("content").NotNull(); + t.String("metadata_file_name", 100); + t.Bytes("metadata"); + t.String("exchange_id", 40); + t.DateTimeUtc("received_at").NotNull(); + t.String("channel_code", 20); + t.String("supplier_vat", 30); + t.String("supplier_name", 200); + t.String("document_type", 10); + t.String("number", 40); + t.Date("document_date"); + t.Decimal("total_amount"); + t.Int64("party_id"); + t.String("status", 40).NotNull(); + t.Int64("purchase_document_id"); + t.String("error", 500); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_e_invoice_inbox_hash", "hash"); + t.Index("ix_e_invoice_inbox_status", "status", "received_at"); + t.Index("ix_e_invoice_inbox_file", "file_name"); + }); + + schema.CreateTable("e_invoice_channels", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.Bool("enabled").NotNull().Default(false); + t.Bool("paused").NotNull().Default(false); + t.String("mailbox", 254); + t.String("smtp_host", 200); + t.Int32("smtp_port").NotNull().Default(465); + t.String("imap_host", 200); + t.Int32("imap_port").NotNull().Default(993); + t.Bool("tls").NotNull().Default(true); + t.String("user_name", 254); + t.Text("protected_password"); + t.String("exchange_address", 254); + t.String("archive_folder", 100); + t.String("endpoint", 300); + t.Text("protected_certificate"); + t.Text("protected_certificate_password"); + t.Text("protected_api_key"); + t.Bool("test_environment").NotNull().Default(false); + t.DateTimeUtc("last_check_at"); + t.Bool("last_check_ok"); + t.String("last_check_message", 1000); + t.DateTimeUtc("last_poll_at"); + t.String("last_poll_message", 1000); + t.Bool("last_poll_failed").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_e_invoice_channels_code", "code"); + }); + + schema.CreateTable("e_invoice_routing", t => + { + t.Id(); + t.Int32("position").NotNull().Default(0); + t.String("condition", 40).NotNull(); + t.String("value", 40); + t.String("channel_code", 20).NotNull(); + t.String("fallback_channel_code", 20); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + }); + + schema.CreateTable("e_invoice_conservation", t => + { + t.Id(); + t.Date("from_date").NotNull(); + t.Date("to_date").NotNull(); + t.Int32("file_count").NotNull().Default(0); + t.String("file_name", 100).NotNull(); + t.String("hash", 64).NotNull(); + t.Int64("size").NotNull().Default(0L); + t.AuditColumns(); + }); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/EInvoices.cs b/src/Khaemhat.Fiscal.Abstractions/EInvoices.cs new file mode 100644 index 0000000..2901975 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/EInvoices.cs @@ -0,0 +1,253 @@ +namespace Khaemhat.Fiscal.Abstractions; + +// The model of an e-invoice file of the country's format (Italy: FatturaPA), the same in both directions: the reader +// fills it from a received file (M6), the writer turns it into the file to send (M9). It keeps the codes of the format. + +/// An e-invoice file: the transmission header, the two parties and one or more invoices. +/// The name of the file, as received or as it will be sent. +/// The transmission format (Italy: FPR12, FPA12, FSM10). +/// The progressive number of the transmission given by the sender. +/// The recipient code of the transmission. +/// The supplier who issued the invoices. +/// The customer the invoices are addressed to (normally the company). +/// The invoices, one per body of the file (a batch has more than one). +/// The signature of the envelope, or for an unsigned file. +/// The XML of the invoice, taken out of the envelope when the file was signed. +public sealed record EInvoiceFile( + string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode, + EInvoiceParty Supplier, EInvoiceParty Customer, IReadOnlyList Invoices, + EInvoiceSignature? Signature, byte[] Xml) +{ + /// The country of the transmitter (Italy: IdTrasmittente/IdPaese). + public string? TransmitterCountry { get; init; } + + /// The tax identifier of the transmitter (Italy: IdTrasmittente/IdCodice). + public string? TransmitterId { get; init; } + + /// The certified mailbox the invoice is delivered to, when there is no recipient code. + public string? RecipientPec { get; init; } + + /// The e-mail of the transmitter, for the exchange system (Italy: ContattiTrasmittente/Email). + public string? TransmitterEmail { get; init; } + + /// The third party that issues the invoice for the supplier, if any (Italy: TerzoIntermediarioOSoggettoEmittente). + public EInvoiceParty? Intermediary { get; init; } + + /// Who issues the document when not the supplier (Italy: SoggettoEmittente, CC customer, TZ third party). + public string? IssuedBy { get; init; } +} + +/// +/// The signature of a signed file. says only that the content is intact and signed by the key +/// of the embedded certificate: the trust chain and the revocation of the certificate are not checked, because no +/// trusted list is available offline. +/// +/// Whether the digest and the signature match the content. +/// The name of the signer, from the certificate. +/// The tax code of the signer, when the certificate carries it. +/// The signing time declared by the signer, if any (not a trusted timestamp). +/// The start of validity of the certificate. +/// The end of validity of the certificate. +/// Why the signature is not verified, or . +public sealed record EInvoiceSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt, + DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem); + +/// A party of the invoice (supplier, customer or intermediary) as written in the file. +/// The country of the VAT number. +/// The VAT number without the country prefix. +/// The tax code. +/// The company name, when the party is a company. +/// The first name, when the party is a person. +/// The last name, when the party is a person. +/// The street of the registered office. +/// The street number. +/// The postal code. +/// The city. +/// The province. +/// The country of the registered office. +/// The tax regime (supplier only). +/// The e-mail address (supplier only). +/// The phone number (supplier only). +/// The office of the companies register. +/// The number in the companies register. +public sealed record EInvoiceParty( + string? CountryCode, string? VatNumber, string? TaxCode, string? Name, string? FirstName, string? LastName, + string? Address, string? StreetNumber, string? PostalCode, string? City, string? Province, string? Country, + string? TaxRegime, string? Email, string? Phone, string? ReaOffice, string? ReaNumber) +{ + /// The company name, or first and last name of a person. + public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s))); + + /// The share capital, for a company in the companies register. + public decimal? ShareCapital { get; init; } + + /// One or more shareholders (Italy: SU sole, SM several). + public string? Shareholders { get; init; } + + /// Whether the company is being wound up (Italy: LS yes, LN no). + public string? LiquidationStatus { get; init; } + + /// The reference of the administration, for the public administration (Italy: RiferimentoAmministrazione). + public string? AdministrationReference { get; init; } +} + +/// An invoice of the file (one body). +/// The document type (Italy: TD01, TD04...). +/// The currency code. +/// The date of the document. +/// The number of the document. +/// The total amount declared by the supplier, if any. +/// The rounding on the total, if any. +/// The free-text causals. +/// Whether the document is issued under the rule that allows several documents with the same +/// number in a year (Italy: art. 73 DPR 633/72). +/// The withholding taxes. +/// The stamp duty, if any. +/// The social security contributions. +/// The discounts and surcharges on the whole document. +/// The purchase orders referred to. +/// The contracts referred to. +/// The invoices referred to (the invoice a credit note corrects). +/// The delivery notes referred to. +/// The lines. +/// The tax summary, one row per rate or nature. +/// The payment installments. +/// The attached files. +public sealed record EInvoiceBody( + string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding, + IReadOnlyList Causals, bool Art73, + IReadOnlyList Withholdings, EInvoiceStampDuty? StampDuty, + IReadOnlyList SocialSecurity, IReadOnlyList Discounts, + IReadOnlyList Orders, IReadOnlyList Contracts, + IReadOnlyList RelatedInvoices, IReadOnlyList DeliveryNotes, + IReadOnlyList Lines, IReadOnlyList TaxSummary, + IReadOnlyList Payments, IReadOnlyList Attachments) +{ + /// The transport data of an accompanying invoice, if any. + public EInvoiceTransport? Transport { get; init; } + + /// The payment conditions of the whole document (Italy: TP01, TP02, TP03). + public string? PaymentConditions { get; init; } +} + +/// The transport data of an accompanying invoice (Italy: DatiTrasporto). +/// The carrier. +/// The country of the VAT number of the carrier. +/// The VAT number of the carrier. +/// The means of transport. +/// The reason of the transport. +/// The number of packages. +/// The appearance of the goods. +/// The gross weight, kg. +/// The net weight, kg. +/// When the transport starts. +/// The terms of delivery (Incoterms). +public sealed record EInvoiceTransport( + string? CarrierName, string? CarrierCountry, string? CarrierVat, string? Means, string? Reason, int? Packages, + string? Description, decimal? GrossWeight, decimal? NetWeight, DateTime? Start, string? ShippingTerms); + +/// A line of an invoice. +/// The line number. +/// The item codes (type and value). +/// The description. +/// The quantity, if given. +/// The unit of measure, if given. +/// The unit price. +/// The total of the line, net of tax. +/// The tax rate in percent (zero with a nature). +/// The reason of a zero rate (Italy: N2.2...). +/// The discounts and surcharges of the line. +/// Whether the line is subject to withholding tax. +/// The kind of line (Italy: SC discount, PR premium, AB rebate, +/// AC ancillary cost). +/// The start of the period the line refers to. +/// The end of the period the line refers to. +/// The administrative reference (cost centre, internal code). +public sealed record EInvoiceLine( + int Number, IReadOnlyList Codes, string Description, decimal? Quantity, string? Unit, + decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList Discounts, + bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference) +{ + /// Further data of the line (Italy: AltriDatiGestionali, such as the declaration of intent). + public IReadOnlyList OtherData { get; init; } = []; +} + +/// Further data of a line (Italy: AltriDatiGestionali). +/// The kind of data (Italy: TipoDato, such as INTENTO). +/// A text value. +/// A number value. +/// A date value. +public sealed record EInvoiceOtherData(string Type, string? Text, decimal? Number, DateOnly? Date); + +/// A code of the item of a line. +/// The kind of code (EAN, SKU, the supplier's code...). +/// The code. +public sealed record EInvoiceItemCode(string Type, string Value); + +/// A discount or surcharge. +/// Whether it is a surcharge (Italy: MG) instead of a discount (SC). +/// The percentage, if given. +/// The amount, if given. +public sealed record EInvoiceDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount); + +/// A row of the tax summary. +/// The tax rate in percent. +/// The reason of a zero rate. +/// The taxable amount. +/// The tax. +/// When the tax is due (Italy: I immediate, D deferred, S split payment). +/// The law that justifies the nature. +/// Ancillary expenses, if any. +/// The rounding, if any. +public sealed record EInvoiceTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility, + string? LegalReference, decimal? ExpensesAmount, decimal? Rounding); + +/// A payment installment. +/// The payment conditions (Italy: TP01 installments, TP02 full, TP03 advance). +/// The payment method (Italy: MP05 bank transfer...). +/// The due date, if given. +/// The amount. +/// The IBAN to pay to, if given. +/// The BIC, if given. +/// The beneficiary, if different from the supplier. +public sealed record EInvoicePayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount, + string? Iban, string? Bic, string? Beneficiary); + +/// A reference to another document (order, contract, invoice, delivery note). +/// The number of the document. +/// The date of the document. +/// The lines of the invoice the reference applies to; empty when it applies to all. +/// The tender code, if any (public administration). +/// The project code, if any (public administration). +public sealed record EInvoiceReference(string? Id, DateOnly? Date, IReadOnlyList LineNumbers, string? Cig, string? Cup); + +/// A withholding tax. +/// The kind of withholding (Italy: RT01...). +/// The amount withheld. +/// The rate in percent. +/// The payment reason (Italy: A...), if given. +public sealed record EInvoiceWithholding(string Type, decimal Amount, decimal Rate, string? Reason); + +/// The stamp duty of an invoice. +/// Whether it is paid virtually by the issuer. +/// The amount. +public sealed record EInvoiceStampDuty(bool Virtual, decimal Amount); + +/// A social security contribution added to the invoice. +/// The fund (Italy: TC01...). +/// The rate of the contribution in percent. +/// The amount of the contribution. +/// The amount the contribution is computed on, if given. +/// The tax rate applied to the contribution. +/// Whether the contribution is subject to withholding tax. +/// The reason of a zero tax rate. +public sealed record EInvoiceSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate, + bool Withheld, string? Nature); + +/// A file attached to the invoice. +/// The name of the attachment. +/// The format declared by the supplier (such as PDF), if any. +/// The description, if any. +/// The decoded content. +public sealed record EInvoiceAttachment(string Name, string? Format, string? Description, byte[] Content); + diff --git a/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs b/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs new file mode 100644 index 0000000..99ccce1 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs @@ -0,0 +1,307 @@ +namespace Khaemhat.Fiscal.Abstractions; + +// The electronic invoice of the country (SPEC §11.9, ADR 0039): writing and checking the file, reading the receipts of +// the exchange system and the channels that carry files to it and back. The model of the file is EInvoiceFile; the +// Italian pack implements everything with FatturaPA and the SDI. The rest of Khaemhat works with these contracts only. + +/// Writes the e-invoice file of the country's format (Italy: FatturaPA FPR12/FPA12). +public interface IEInvoiceWriter +{ + /// The name of the file to send (Italy: IT01234567890_00A1Z.xml). + /// The country of the transmitter. + /// The tax identifier of the transmitter. + /// The progressive number of the file for this transmitter, from 1. + /// The file name. + string FileName(string transmitterCountry, string transmitterId, long progressive); + + /// The progressive written in the file for a progressive number (Italy: base 36, five characters). + /// The progressive number, from 1. + /// The text. + string Progressive(long progressive); + + /// Writes the file. + /// The content; and are ignored. + /// The XML, UTF-8. + byte[] Write(EInvoiceFile file); +} + +/// How serious a problem found by is. +public enum EInvoiceProblemSeverity +{ + /// The exchange system would reject the file: it is not sent. + Error = 0, + + /// The file is accepted but something looks wrong. + Warning = 1, +} + +/// A problem of an e-invoice found before sending. +/// The code: the check of the exchange system when there is one (Italy: 00423), else a +/// text code of Khaemhat (einvoice.xml.schema). +/// Where: the element of the format, such as DettaglioLinee[2]/PrezzoTotale. +/// What is wrong, in the language of the format's documentation (Italian for FatturaPA). +/// Error or warning. +public sealed record EInvoiceProblem(string Code, string Path, string Message, EInvoiceProblemSeverity Severity = EInvoiceProblemSeverity.Error); + +/// Checks an e-invoice before it leaves: the rules of the exchange system and the schema of the format. +public interface IEInvoiceValidator +{ + /// The version of the rules checked, shown with the results. + string RulesVersion { get; } + + /// The checks on the content: code lists, lengths, totals, natures, recipient, references. + /// The file content. + /// The problems, errors first; empty when the file can be sent. + IReadOnlyList Validate(EInvoiceFile file); + + /// The checks on the XML: well formed and valid against the schema of the format. + /// The file. + /// The problems; empty when the file is valid. + IReadOnlyList ValidateXml(byte[] xml); +} + +/// What a receipt of the exchange system says (Italy: the SDI notifications). +public enum EInvoiceReceiptKind +{ + /// Delivered to the customer (Italy: RC ricevuta di consegna). + Delivered = 0, + + /// Rejected by the exchange system: the invoice is not issued (Italy: NS notifica di scarto). + Rejected = 1, + + /// Not delivered, made available to the customer (Italy: MC mancata consegna). + NotDelivered = 2, + + /// The outcome of a public administration: accepted or refused (Italy: NE notifica di esito). + Outcome = 3, + + /// The public administration did not answer in time (Italy: DT decorrenza termini). + TermsElapsed = 4, + + /// Sent to a public administration that could not receive it (Italy: AT attestazione). + Undeliverable = 5, + + /// The metadata that go with a received invoice (Italy: MT file metadati). + Metadata = 6, + + /// The exchange system rejected the outcome the company sent (Italy: SE scarto esito). + OutcomeRejected = 7, +} + +/// An error listed in a rejection. +/// The code (Italy: 00311). +/// The description given by the exchange system. +/// The suggestion given with it, if any. +public sealed record EInvoiceReceiptError(string Code, string Description, string? Hint); + +/// A receipt or notification of the exchange system about one file. +/// What it says. +/// The short code of the format (Italy: RC, NS...). +/// The name of the receipt file. +/// The name of the invoice file it is about. +/// The identifier the exchange system gave to the invoice file (Italy: IdentificativoSdI). +/// When the exchange system received the invoice file. +/// When it was delivered, for a delivery receipt. +/// The outcome of the administration (Italy: EC01 accepted, EC02 refused). +/// The free text of the notification. +/// The errors of a rejection. +/// The identifier of the message. +/// The recipient code, for the metadata of a received invoice. +/// The file as received. +public sealed record EInvoiceReceipt( + EInvoiceReceiptKind Kind, string Code, string FileName, string? InvoiceFileName, string? ExchangeId, + DateTimeOffset? ReceivedAt, DateTimeOffset? DeliveredAt, string? Outcome, string? Description, + IReadOnlyList Errors, string? MessageId, string? RecipientCode, byte[] Content) +{ + /// Whether an outcome says the administration refused the invoice. + public bool Refused => Kind == EInvoiceReceiptKind.Outcome && string.Equals(Outcome, "EC02", StringComparison.Ordinal); +} + +/// Reads the receipts of the exchange system (Italy: SDI notifications, MessaggiTypes v1.0). +public interface IEInvoiceReceiptReader +{ + /// Whether a file is a receipt, by its name or its root element. + /// The name of the file. + /// The content. + /// when is worth trying. + bool IsReceipt(string fileName, ReadOnlySpan content); + + /// Reads a receipt. + /// The name of the file. + /// The content. + /// The receipt. + /// The file is not a receipt. + EInvoiceReceipt Read(string fileName, byte[] content); +} + +/// +/// The settings of a channel to the exchange system. Each channel uses the fields it needs (the PEC mailbox, the web +/// service, the API of an intermediary); secrets arrive decrypted and never leave the transport. +/// +public sealed record EInvoiceChannelSettings +{ + /// The channel code (Italy: PEC, SDICOOP, INTA, INTB). + public required string Code { get; init; } + + /// The certified mailbox of the company. + public string? Mailbox { get; init; } + + /// The SMTP server of the mailbox. + public string? SmtpHost { get; init; } + + /// The SMTP port (465 for TLS from the start, 587 for STARTTLS). + public int SmtpPort { get; init; } = 465; + + /// The IMAP server of the mailbox. + public string? ImapHost { get; init; } + + /// The IMAP port (993 for TLS). + public int ImapPort { get; init; } = 993; + + /// Whether the connections are protected by TLS (always, except in tests on the local machine). + public bool Tls { get; init; } = true; + + /// The user of the mailbox or of the service. + public string? User { get; init; } + + /// The password of the mailbox or of the service. + public string? Password { get; init; } + + /// The address of the exchange system to write to (Italy: sdi01@pec.fatturapa.it, then the one assigned). + public string? ExchangeAddress { get; init; } + + /// The folder of the mailbox the processed messages are moved to. + public string? ArchiveFolder { get; init; } + + /// The address of the web service or of the API. + public string? Endpoint { get; init; } + + /// The client certificate (PKCS#12) of the web service. + public byte[]? Certificate { get; init; } + + /// The password of the certificate. + public string? CertificatePassword { get; init; } + + /// The API key or token of an intermediary. + public string? ApiKey { get; init; } + + /// Whether the test environment of the service is used. + public bool TestEnvironment { get; init; } +} + +/// A file to send. +/// The name of the file. +/// The content. +/// What it is, for messages and logs (the number of the document). +public sealed record EInvoiceOutgoing(string FileName, byte[] Content, string? Reference); + +/// The answer of a channel to a file sent. +/// Whether the channel took the file. +/// The identifier given by the exchange system, when the channel knows it at once (Italy: SdICoop). +/// The identifier of the message or of the upload at the channel. +/// Why the file was not taken. +public sealed record EInvoiceSendResult(bool Accepted, string? ExchangeId, string? MessageId, string? Error); + +/// A file received from a channel: a receipt, a supplier invoice or its metadata. +/// The name of the file. +/// The content. +/// When the channel received it. +/// The key of the message at the channel, to acknowledge it once stored. +/// Who sent it (the address of the exchange system), if known. +public sealed record EInvoiceIncoming(string FileName, byte[] Content, DateTimeOffset ReceivedAt, string MessageKey, string? Sender); + +/// What a channel had for the company. +/// The files received. +/// How many messages the channel read, files or not. +/// The address the exchange system assigned for the next files, if it changed (Italy: PEC). +public sealed record EInvoiceFetchResult(IReadOnlyList Files, int MessagesRead, string? ExchangeAddress); + +/// The outcome of a connection test. +/// Whether every step worked. +/// What was checked, or what failed. +public sealed record EInvoiceChannelCheck(bool Success, string Message); + +/// +/// A channel to the exchange system (SPEC §11.9: ISdiTransport): send a file, fetch receipts and supplier +/// invoices, acknowledge what was stored, test the connection. Every channel has the same contract, so the rest of +/// Khaemhat does not change with the channel. +/// +public interface IEInvoiceTransport +{ + /// The code of the channel (Italy: PEC, SDICOOP, INTA, INTB). + string Code { get; } + + /// Whether receipts and invoices are fetched by polling ( when the exchange system pushes them). + bool Polls { get; } + + /// Sends a file. + /// The settings of the channel. + /// The file. + /// Cancellation. + /// The answer of the channel. + Task SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default); + + /// Fetches the files waiting at the channel; nothing is removed until . + /// The settings of the channel. + /// Cancellation. + /// The files. + Task FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default); + + /// Marks messages as processed (Italy, PEC: moved to the archive folder). + /// The settings of the channel. + /// The keys of . + /// Cancellation. + /// A task. + Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection messageKeys, CancellationToken cancellationToken = default); + + /// Tests the connection without sending anything. + /// The settings of the channel. + /// Cancellation. + /// The outcome. + Task CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default); +} + +/// A channel the pack offers, with its description for the configuration screen. +/// The code. +/// The name shown. +/// The implementation. +public sealed record EInvoiceChannel(string Code, string Name, IEInvoiceTransport Transport); + +/// The channels to the exchange system the pack offers (Italy: PEC, SdICoop, intermediary A and B). +public interface IEInvoiceChannels +{ + /// The channels, in the order of the configuration screen. + IReadOnlyList All { get; } + + /// A channel by code. + /// The code. + /// The channel, or . + EInvoiceChannel? Find(string code); +} + +/// What the exchange system pushed to the company over HTTP: the files and how to answer. +/// The identifier of the exchange system. +/// The files: a notification, or an invoice with its metadata. +/// The content type of the answer. +/// The body of the answer. +public sealed record EInvoicePush(string? ExchangeId, IReadOnlyList<(string FileName, byte[] Content)> Files, string AnswerContentType, string Answer); + +/// +/// Reads what the exchange system sends to the web services of the company (Italy: the SdICoop operations +/// RiceviFatture, RicevutaConsegna, NotificaScarto …), for the channel that receives them. +/// +public interface IEInvoicePushReader +{ + /// The code of the channel the pushes belong to (Italy: SDICOOP). + string Channel { get; } + + /// Reads a request. + /// The content type of the HTTP request. + /// The body. + /// The files with the answer, or when the request is not one of the exchange system. + EInvoicePush? Read(string? contentType, byte[] body); + + /// The answer to a request that could not be read. + /// The content type and the body. + (string ContentType, string Body) Refusal(); +} diff --git a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs index 6949382..9d938c1 100644 --- a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs +++ b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs @@ -25,7 +25,7 @@ public interface IIncomingInvoiceReader /// The file with its invoices. /// The file is not readable, not an invoice, or misses mandatory data; /// is one of . - IncomingInvoiceFile Read(string fileName, byte[] content); + EInvoiceFile Read(string fileName, byte[] content); } /// A received e-invoice file that cannot be read; is one of . @@ -85,189 +85,6 @@ public static class IncomingInvoiceErrors public const string Invalid = "incoming.invalid"; } -/// A received e-invoice file: the transmission header, the two parties and one or more invoices. -/// The name of the file as received. -/// The transmission format (Italy: FPR12, FPA12, FSM10). -/// The progressive number of the transmission given by the sender. -/// The recipient code of the transmission. -/// The supplier who issued the invoices. -/// The customer the invoices are addressed to (normally the company). -/// The invoices, one per body of the file (a batch has more than one). -/// The signature of the envelope, or for an unsigned file. -/// The XML of the invoice, taken out of the envelope when the file was signed. -public sealed record IncomingInvoiceFile( - string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode, - IncomingParty Supplier, IncomingParty Customer, IReadOnlyList Invoices, - IncomingSignature? Signature, byte[] Xml); - -/// -/// The signature of a signed file. says only that the content is intact and signed by the key -/// of the embedded certificate: the trust chain and the revocation of the certificate are not checked, because no -/// trusted list is available offline. -/// -/// Whether the digest and the signature match the content. -/// The name of the signer, from the certificate. -/// The tax code of the signer, when the certificate carries it. -/// The signing time declared by the signer, if any (not a trusted timestamp). -/// The start of validity of the certificate. -/// The end of validity of the certificate. -/// Why the signature is not verified, or . -public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt, - DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem); - -/// A party of the invoice (supplier or customer) as written in the file. -/// The country of the VAT number. -/// The VAT number without the country prefix. -/// The tax code. -/// The company name, when the party is a company. -/// The first name, when the party is a person. -/// The last name, when the party is a person. -/// The street of the registered office. -/// The street number. -/// The postal code. -/// The city. -/// The province. -/// The country of the registered office. -/// The tax regime (supplier only). -/// The e-mail address (supplier only). -/// The phone number (supplier only). -/// The office of the companies register. -/// The number in the companies register. -public sealed record IncomingParty( - string? CountryCode, string? VatNumber, string? TaxCode, string? Name, string? FirstName, string? LastName, - string? Address, string? StreetNumber, string? PostalCode, string? City, string? Province, string? Country, - string? TaxRegime, string? Email, string? Phone, string? ReaOffice, string? ReaNumber) -{ - /// The company name, or first and last name of a person. - public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s))); -} - -/// An invoice of the file (one body). -/// The document type (Italy: TD01, TD04...). -/// The currency code. -/// The date of the document. -/// The number of the document. -/// The total amount declared by the supplier, if any. -/// The rounding on the total, if any. -/// The free-text causals. -/// Whether the document is issued under the rule that allows several documents with the same -/// number in a year (Italy: art. 73 DPR 633/72). -/// The withholding taxes. -/// The stamp duty, if any. -/// The social security contributions. -/// The discounts and surcharges on the whole document. -/// The purchase orders referred to. -/// The contracts referred to. -/// The invoices referred to (the invoice a credit note corrects). -/// The delivery notes referred to. -/// The lines. -/// The tax summary, one row per rate or nature. -/// The payment installments. -/// The attached files. -public sealed record IncomingInvoice( - string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding, - IReadOnlyList Causals, bool Art73, - IReadOnlyList Withholdings, IncomingStampDuty? StampDuty, - IReadOnlyList SocialSecurity, IReadOnlyList Discounts, - IReadOnlyList Orders, IReadOnlyList Contracts, - IReadOnlyList RelatedInvoices, IReadOnlyList DeliveryNotes, - IReadOnlyList Lines, IReadOnlyList TaxSummary, - IReadOnlyList Payments, IReadOnlyList Attachments); - -/// A line of an invoice. -/// The line number. -/// The item codes (type and value). -/// The description. -/// The quantity, if given. -/// The unit of measure, if given. -/// The unit price. -/// The total of the line, net of tax. -/// The tax rate in percent (zero with a nature). -/// The reason of a zero rate (Italy: N2.2...). -/// The discounts and surcharges of the line. -/// Whether the line is subject to withholding tax. -/// The kind of line (Italy: SC discount, PR premium, AB rebate, -/// AC ancillary cost). -/// The start of the period the line refers to. -/// The end of the period the line refers to. -/// The administrative reference (cost centre, internal code). -public sealed record IncomingLine( - int Number, IReadOnlyList Codes, string Description, decimal? Quantity, string? Unit, - decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList Discounts, - bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference); - -/// A code of the item of a line. -/// The kind of code (EAN, SKU, the supplier's code...). -/// The code. -public sealed record IncomingItemCode(string Type, string Value); - -/// A discount or surcharge. -/// Whether it is a surcharge (Italy: MG) instead of a discount (SC). -/// The percentage, if given. -/// The amount, if given. -public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount); - -/// A row of the tax summary. -/// The tax rate in percent. -/// The reason of a zero rate. -/// The taxable amount. -/// The tax. -/// When the tax is due (Italy: I immediate, D deferred, S split payment). -/// The law that justifies the nature. -/// Ancillary expenses, if any. -/// The rounding, if any. -public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility, - string? LegalReference, decimal? ExpensesAmount, decimal? Rounding); - -/// A payment installment. -/// The payment conditions (Italy: TP01 installments, TP02 full, TP03 advance). -/// The payment method (Italy: MP05 bank transfer...). -/// The due date, if given. -/// The amount. -/// The IBAN to pay to, if given. -/// The BIC, if given. -/// The beneficiary, if different from the supplier. -public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount, - string? Iban, string? Bic, string? Beneficiary); - -/// A reference to another document (order, contract, invoice, delivery note). -/// The number of the document. -/// The date of the document. -/// The lines of the invoice the reference applies to; empty when it applies to all. -/// The tender code, if any (public administration). -/// The project code, if any (public administration). -public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList LineNumbers, string? Cig, string? Cup); - -/// A withholding tax. -/// The kind of withholding (Italy: RT01...). -/// The amount withheld. -/// The rate in percent. -/// The payment reason (Italy: A...), if given. -public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason); - -/// The stamp duty of an invoice. -/// Whether it is paid virtually by the issuer. -/// The amount. -public sealed record IncomingStampDuty(bool Virtual, decimal Amount); - -/// A social security contribution added to the invoice. -/// The fund (Italy: TC01...). -/// The rate of the contribution in percent. -/// The amount of the contribution. -/// The amount the contribution is computed on, if given. -/// The tax rate applied to the contribution. -/// Whether the contribution is subject to withholding tax. -/// The reason of a zero tax rate. -public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate, - bool Withheld, string? Nature); - -/// A file attached to the invoice. -/// The name of the attachment. -/// The format declared by the supplier (such as PDF), if any. -/// The description, if any. -/// The decoded content. -public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content); - /// /// How a received e-invoice becomes a document of the company: which document type registers each type of the format /// (Italy: TD01 and the like as supplier invoice FF, TD04 and TD08 as supplier credit note NCF). diff --git a/src/Khaemhat.Fiscal.Italy/Data/FatturaPA_v1.2_khaemhat.xsd b/src/Khaemhat.Fiscal.Italy/Data/FatturaPA_v1.2_khaemhat.xsd new file mode 100644 index 0000000..e156fc8 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Data/FatturaPA_v1.2_khaemhat.xsd @@ -0,0 +1,558 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs index 9775730..9d49cd0 100644 --- a/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs +++ b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs @@ -39,7 +39,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader !content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content)); /// - public IncomingInvoiceFile Read(string fileName, byte[] content) + public EInvoiceFile Read(string fileName, byte[] content) { ArgumentNullException.ThrowIfNull(fileName); ArgumentNullException.ThrowIfNull(content); @@ -53,7 +53,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, $"The file is larger than {MaxSize / (1024 * 1024)} MB."); } - IncomingSignature? signature = null; + EInvoiceSignature? signature = null; var xml = content; if (!LooksLikeXml(content) && CmsSignedData.LooksLikeCms(content)) { @@ -69,7 +69,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader xml = envelope.Content; var signer = envelope.Signer; - signature = new IncomingSignature( + signature = new EInvoiceSignature( envelope.Verified, signer?.Name, signer?.TaxCode, signer?.SigningTime, signer?.CertificateNotBefore, signer?.CertificateNotAfter, envelope.Problem); } @@ -189,7 +189,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader // --- Ordinary invoice -------------------------------------------------------------------------------------------- - private static IncomingInvoiceFile ReadOrdinary(string fileName, XElement root, IncomingSignature? signature, byte[] xml) + private static EInvoiceFile ReadOrdinary(string fileName, XElement root, EInvoiceSignature? signature, byte[] xml) { var header = El(root, "FatturaElettronicaHeader") ?? throw Invalid("The invoice has no FatturaElettronicaHeader."); @@ -202,7 +202,9 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader throw Invalid("The invoice has no FatturaElettronicaBody."); } - return new IncomingInvoiceFile( + var transmitter = El(transmission, "IdTrasmittente"); + var third = El(header, "TerzoIntermediarioOSoggettoEmittente"); + return new EInvoiceFile( fileName, Text(transmission, "FormatoTrasmissione"), Text(transmission, "ProgressivoInvio"), @@ -211,10 +213,18 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader ReadParty(customer), bodies.Select(ReadBody).ToList(), signature, - xml); + xml) + { + TransmitterCountry = Text(transmitter, "IdPaese"), + TransmitterId = Text(transmitter, "IdCodice"), + RecipientPec = Text(transmission, "PECDestinatario"), + TransmitterEmail = Text(El(transmission, "ContattiTrasmittente"), "Email"), + Intermediary = third is null ? null : ReadParty(third), + IssuedBy = Text(header, "SoggettoEmittente"), + }; } - private static IncomingParty ReadParty(XElement party) + private static EInvoiceParty ReadParty(XElement party) { var personal = El(party, "DatiAnagrafici"); var identifiers = El(party, "IdentificativiFiscali"); @@ -224,7 +234,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader var office = El(party, "Sede") ?? El(others, "Sede"); var register = El(party, "IscrizioneREA"); var contacts = El(party, "Contatti"); - return new IncomingParty( + return new EInvoiceParty( Text(vat, "IdPaese"), Text(vat, "IdCodice"), Text(personal, "CodiceFiscale") ?? Text(identifiers, "CodiceFiscale") ?? Text(party, "CodiceFiscale"), @@ -241,10 +251,16 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader Text(contacts, "Email"), Text(contacts, "Telefono"), Text(register, "Ufficio"), - Text(register, "NumeroREA")); + Text(register, "NumeroREA")) + { + ShareCapital = OptionalDecimal(register, "CapitaleSociale"), + Shareholders = Text(register, "SocioUnico"), + LiquidationStatus = Text(register, "StatoLiquidazione"), + AdministrationReference = Text(party, "RiferimentoAmministrazione"), + }; } - private static IncomingInvoice ReadBody(XElement body, int index) + private static EInvoiceBody ReadBody(XElement body, int index) { var general = El(body, "DatiGenerali"); var document = El(general, "DatiGeneraliDocumento") @@ -252,7 +268,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader var goods = El(body, "DatiBeniServizi"); var stamp = El(document, "DatiBollo"); - return new IncomingInvoice( + return new EInvoiceBody( Required(document, "TipoDocumento", index), Text(document, "Divisa") ?? "EUR", RequiredDate(document, "Data", index), @@ -261,13 +277,13 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader OptionalDecimal(document, "Arrotondamento"), Els(document, "Causale").Select(c => c.Value.Trim()).Where(c => c.Length > 0).ToList(), Flag(document, "Art73"), - Els(document, "DatiRitenuta").Select(w => new IncomingWithholding( + Els(document, "DatiRitenuta").Select(w => new EInvoiceWithholding( Required(w, "TipoRitenuta", index), RequiredDecimal(w, "ImportoRitenuta", index), RequiredDecimal(w, "AliquotaRitenuta", index), Text(w, "CausalePagamento"))).ToList(), - stamp is null ? null : new IncomingStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m), - Els(document, "DatiCassaPrevidenziale").Select(s => new IncomingSocialSecurity( + stamp is null ? null : new EInvoiceStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m), + Els(document, "DatiCassaPrevidenziale").Select(s => new EInvoiceSocialSecurity( Required(s, "TipoCassa", index), RequiredDecimal(s, "AlCassa", index), RequiredDecimal(s, "ImportoContributoCassa", index), @@ -279,10 +295,10 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader ReadReferences(general, "DatiOrdineAcquisto"), ReadReferences(general, "DatiContratto"), ReadReferences(general, "DatiFattureCollegate"), - Els(general, "DatiDDT").Select(d => new IncomingReference( + Els(general, "DatiDDT").Select(d => new EInvoiceReference( Text(d, "NumeroDDT"), OptionalDate(d, "DataDDT"), LineNumbers(d), null, null)).ToList(), Els(goods, "DettaglioLinee").Select((l, i) => ReadLine(l, i, index)).ToList(), - Els(goods, "DatiRiepilogo").Select(r => new IncomingTaxSummary( + Els(goods, "DatiRiepilogo").Select(r => new EInvoiceTaxSummary( RequiredDecimal(r, "AliquotaIVA", index), Text(r, "Natura"), RequiredDecimal(r, "ImponibileImporto", index), @@ -292,13 +308,41 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader OptionalDecimal(r, "SpeseAccessorie"), OptionalDecimal(r, "Arrotondamento"))).ToList(), ReadPayments(body, index), - ReadAttachments(body)); + ReadAttachments(body)) + { + Transport = ReadTransport(El(general, "DatiTrasporto")), + PaymentConditions = Text(El(body, "DatiPagamento"), "CondizioniPagamento"), + }; } - private static IncomingLine ReadLine(XElement line, int position, int index) => new( + private static EInvoiceTransport? ReadTransport(XElement? transport) + { + if (transport is null) + { + return null; + } + + var carrier = El(transport, "DatiAnagraficiVettore"); + var carrierVat = El(carrier, "IdFiscaleIVA"); + var start = OptionalDate(transport, "DataInizioTrasporto"); + return new EInvoiceTransport( + Text(El(carrier, "Anagrafica"), "Denominazione"), + Text(carrierVat, "IdPaese"), + Text(carrierVat, "IdCodice"), + Text(transport, "MezzoTrasporto"), + Text(transport, "CausaleTrasporto"), + OptionalInt(transport, "NumeroColli"), + Text(transport, "Descrizione"), + OptionalDecimal(transport, "PesoLordo"), + OptionalDecimal(transport, "PesoNetto"), + start?.ToDateTime(TimeOnly.MinValue), + Text(transport, "TipoResa")); + } + + private static EInvoiceLine ReadLine(XElement line, int position, int index) => new( OptionalInt(line, "NumeroLinea") ?? position + 1, Els(line, "CodiceArticolo") - .Select(c => new IncomingItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty)) + .Select(c => new EInvoiceItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty)) .Where(c => c.Value.Length > 0) .ToList(), Text(line, "Descrizione") ?? string.Empty, @@ -313,16 +357,21 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader Text(line, "TipoCessionePrestazione"), OptionalDate(line, "DataInizioPeriodo"), OptionalDate(line, "DataFinePeriodo"), - Text(line, "RiferimentoAmministrazione")); + Text(line, "RiferimentoAmministrazione")) + { + OtherData = Els(line, "AltriDatiGestionali") + .Select(d => new EInvoiceOtherData(Text(d, "TipoDato") ?? string.Empty, Text(d, "RiferimentoTesto"), OptionalDecimal(d, "RiferimentoNumero"), OptionalDate(d, "RiferimentoData"))) + .ToList(), + }; - private static List ReadDiscounts(XElement? parent) => - Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount( + private static List ReadDiscounts(XElement? parent) => + Els(parent, "ScontoMaggiorazione").Select(d => new EInvoiceDiscount( string.Equals(Text(d, "Tipo"), "MG", StringComparison.OrdinalIgnoreCase), OptionalDecimal(d, "Percentuale"), OptionalDecimal(d, "Importo"))).ToList(); - private static List ReadReferences(XElement? general, string name) => - Els(general, name).Select(r => new IncomingReference( + private static List ReadReferences(XElement? general, string name) => + Els(general, name).Select(r => new EInvoiceReference( Text(r, "IdDocumento"), OptionalDate(r, "Data"), LineNumbers(r), Text(r, "CodiceCIG"), Text(r, "CodiceCUP"))).ToList(); private static List LineNumbers(XElement reference) => @@ -331,11 +380,11 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader .Where(n => n > 0) .ToList(); - private static List ReadPayments(XElement body, int index) => + private static List ReadPayments(XElement body, int index) => Els(body, "DatiPagamento").SelectMany(p => { var conditions = Text(p, "CondizioniPagamento"); - return Els(p, "DettaglioPagamento").Select(d => new IncomingPayment( + return Els(p, "DettaglioPagamento").Select(d => new EInvoicePayment( conditions, Text(d, "ModalitaPagamento"), OptionalDate(d, "DataScadenzaPagamento"), @@ -345,8 +394,8 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader Text(d, "Beneficiario"))); }).ToList(); - private static List ReadAttachments(XElement body) => - Els(body, "Allegati").Select(a => new IncomingAttachment( + private static List ReadAttachments(XElement body) => + Els(body, "Allegati").Select(a => new EInvoiceAttachment( Text(a, "NomeAttachment") ?? "allegato", Text(a, "FormatoAttachment"), Text(a, "DescrizioneAttachment"), @@ -375,7 +424,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader // --- Simplified invoice ------------------------------------------------------------------------------------------ - private static IncomingInvoiceFile ReadSimplified(string fileName, XElement root, IncomingSignature? signature, byte[] xml) + private static EInvoiceFile ReadSimplified(string fileName, XElement root, EInvoiceSignature? signature, byte[] xml) { var header = El(root, "FatturaElettronicaHeader") ?? throw Invalid("The invoice has no FatturaElettronicaHeader."); @@ -388,7 +437,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader throw Invalid("The invoice has no FatturaElettronicaBody."); } - return new IncomingInvoiceFile( + return new EInvoiceFile( fileName, Text(transmission, "FormatoTrasmissione"), Text(transmission, "ProgressivoInvio"), @@ -400,7 +449,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader xml); } - private static IncomingInvoice ReadSimplifiedBody(XElement body, int index) + private static EInvoiceBody ReadSimplifiedBody(XElement body, int index) { var general = El(body, "DatiGenerali"); var document = El(general, "DatiGeneraliDocumento") @@ -409,15 +458,15 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader var gross = Els(body, "DatiBeniServizi").Sum(l => RequiredDecimal(l, "Importo", index)); var summary = lines .GroupBy(l => (l.TaxRate, l.Nature)) - .Select(g => new IncomingTaxSummary( + .Select(g => new EInvoiceTaxSummary( g.Key.TaxRate, g.Key.Nature, g.Sum(l => l.TotalPrice), g.Sum(l => l.Tax), null, g.Select(l => l.LegalReference).FirstOrDefault(r => r is not null), null, null)) .ToList(); var corrected = Els(general, "DatiFatturaRettificata") - .Select(r => new IncomingReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null)) + .Select(r => new EInvoiceReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null)) .ToList(); - return new IncomingInvoice( + return new EInvoiceBody( Required(document, "TipoDocumento", index), Text(document, "Divisa") ?? "EUR", RequiredDate(document, "Data", index), @@ -427,7 +476,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader [], false, [], - Flag(document, "BolloVirtuale") ? new IncomingStampDuty(true, 0m) : null, + Flag(document, "BolloVirtuale") ? new EInvoiceStampDuty(true, 0m) : null, [], [], [], @@ -451,13 +500,13 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader rate ??= net != 0m ? Math.Round(tax.Value / net * 100m, 2, MidpointRounding.AwayFromZero) : 0m; var nature = Text(line, "Natura"); return new SimplifiedLine( - new IncomingLine(position + 1, [], Text(line, "Descrizione") ?? string.Empty, null, null, net, net, rate.Value, nature, + new EInvoiceLine(position + 1, [], Text(line, "Descrizione") ?? string.Empty, null, null, net, net, rate.Value, nature, [], false, null, null, null, null), tax.Value, Text(line, "RiferimentoNormativo")); } - private sealed record SimplifiedLine(IncomingLine Line, decimal Tax, string? LegalReference) + private sealed record SimplifiedLine(EInvoiceLine Line, decimal Tax, string? LegalReference) { public decimal TaxRate => Line.TaxRate; @@ -494,7 +543,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader private static decimal RequiredDecimal(XElement parent, string localName, int index) => OptionalDecimal(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a number."); - private static int? OptionalInt(XElement parent, string localName) => + private static int? OptionalInt(XElement? parent, string localName) => Text(parent, localName) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null; private static DateOnly? OptionalDate(XElement? parent, string localName) diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaValidator.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaValidator.cs new file mode 100644 index 0000000..7fce25a --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/FatturaPaValidator.cs @@ -0,0 +1,513 @@ +using System.Globalization; +using System.Xml; +using System.Xml.Schema; +using Khaemhat.Core.Validation; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Checks a FatturaPA before it is sent (SPEC §11.9, issue #74, ADR 0039): the content with the controls of the +/// exchange system that can be made offline, and the XML with the schema of the format. +/// +/// +/// The checks that the SDI documents with a code keep that code (00400, 00423...), so the message is +/// the one the user would read in a rejection; the others have a code of Khaemhat (einvoice.*). Checks that need +/// the registers of the Agenzia (a VAT number that exists, a recipient code that is accredited, the office code of an +/// administration in the IPA index) cannot be made offline: only the form of those values is checked. +/// Tolerances follow the specifications: one cent on PrezzoTotale and Imposta, one euro on +/// ImponibileImporto. +/// +public sealed class FatturaPaValidator : IEInvoiceValidator +{ + private static readonly Lazy Schemas = new(LoadSchemas); + + private static readonly HashSet GenericNatures = new(StringComparer.Ordinal) { "N2", "N3", "N6" }; + + // Types where supplier and customer must be different subjects (an integration or self-invoice is issued by the + // customer for a supplier) and types where they must be the same subject (00471, 00472). + private static readonly HashSet DifferentParties = new(StringComparer.Ordinal) + { + "TD01", "TD02", "TD03", "TD06", "TD16", "TD17", "TD18", "TD19", "TD20", "TD24", "TD25", "TD28", "TD29", + }; + + private static readonly HashSet SameParty = new(StringComparer.Ordinal) { "TD21", "TD27" }; + + private static readonly HashSet ForeignSupplier = new(StringComparer.Ordinal) { "TD17", "TD18", "TD19", "TD28" }; + + /// + public string RulesVersion => FatturaPaCodeLists.SpecVersion; + + /// + public IReadOnlyList Validate(EInvoiceFile file) + { + ArgumentNullException.ThrowIfNull(file); + var problems = new List(); + CheckTransmission(file, problems); + CheckSupplier(file.Supplier, problems); + CheckCustomer(file, problems); + for (var i = 0; i < file.Invoices.Count; i++) + { + CheckBody(file, file.Invoices[i], file.Invoices.Count > 1 ? $"FatturaElettronicaBody[{i + 1}]/" : string.Empty, problems); + } + + return [.. problems.OrderBy(p => p.Severity)]; + } + + /// + public IReadOnlyList ValidateXml(byte[] xml) + { + ArgumentNullException.ThrowIfNull(xml); + var problems = new List(); + var settings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + ValidationType = ValidationType.Schema, + Schemas = Schemas.Value, + }; + settings.ValidationEventHandler += (_, e) => + { + if (problems.Count < 50) + { + problems.Add(new EInvoiceProblem("einvoice.xml.schema", e.Exception?.LineNumber > 0 ? "riga " + e.Exception.LineNumber.ToString(CultureInfo.InvariantCulture) : string.Empty, + e.Message, e.Severity == XmlSeverityType.Error ? EInvoiceProblemSeverity.Error : EInvoiceProblemSeverity.Warning)); + } + }; + + try + { + using var reader = XmlReader.Create(new MemoryStream(xml), settings); + while (reader.Read()) + { + } + } + catch (XmlException ex) + { + problems.Add(new EInvoiceProblem("einvoice.xml.malformed", "riga " + ex.LineNumber.ToString(CultureInfo.InvariantCulture), ex.Message)); + } + + return problems; + } + + // --- Header ------------------------------------------------------------------------------------------------------ + + private static void CheckTransmission(EInvoiceFile file, List problems) + { + var format = file.TransmissionFormat; + if (format is not ("FPR12" or "FPA12")) + { + problems.Add(new("einvoice.format", "FormatoTrasmissione", $"Formato di trasmissione {format} non gestito: Khaemhat emette FPR12 e FPA12.")); + return; + } + + if (string.IsNullOrWhiteSpace(file.TransmitterId)) + { + problems.Add(new("einvoice.transmitter", "IdTrasmittente/IdCodice", "Manca l'identificativo fiscale del trasmittente: compila partita IVA o codice fiscale nel profilo dell'azienda.")); + } + + var code = file.RecipientCode ?? string.Empty; + if (format == "FPA12" && code.Length != 6) + { + problems.Add(new("00427", "CodiceDestinatario", "Per una pubblica amministrazione (FPA12) il codice destinatario è il codice univoco dell'ufficio di 6 caratteri (indice IPA).")); + } + else if (format == "FPR12" && code.Length != 7) + { + problems.Add(new("00427", "CodiceDestinatario", "Per un privato (FPR12) il codice destinatario ha 7 caratteri: 0000000 senza codice, XXXXXXX per l'estero.")); + } + else if (!code.All(char.IsAsciiLetterUpper) && !code.All(c => char.IsAsciiLetterUpper(c) || char.IsAsciiDigit(c))) + { + problems.Add(new("00311", "CodiceDestinatario", "Il codice destinatario contiene caratteri non ammessi (solo lettere maiuscole e cifre).")); + } + + if (!string.IsNullOrWhiteSpace(file.RecipientPec) && code != FatturaPaCodeLists.RecipientCodeNone) + { + problems.Add(new("00426", "PECDestinatario", "La PEC del destinatario si indica solo con il codice destinatario 0000000.")); + } + + if (!string.IsNullOrWhiteSpace(file.RecipientPec) && !EmailValidator.IsValid(file.RecipientPec)) + { + problems.Add(new("einvoice.recipient.pec", "PECDestinatario", "La PEC del destinatario non è un indirizzo valido.")); + } + } + + private static void CheckSupplier(EInvoiceParty supplier, List problems) + { + const string Path = "CedentePrestatore/"; + if (string.IsNullOrWhiteSpace(supplier.VatNumber)) + { + problems.Add(new("einvoice.supplier.vat", Path + "IdFiscaleIVA", "Manca la partita IVA del cedente/prestatore.")); + } + else if ((supplier.CountryCode ?? "IT") == "IT" && !ItalianVatNumberValidator.IsValid(supplier.VatNumber)) + { + problems.Add(new("einvoice.supplier.vat", Path + "IdFiscaleIVA/IdCodice", $"La partita IVA {supplier.VatNumber} del cedente/prestatore non è valida.")); + } + + if (!string.IsNullOrWhiteSpace(supplier.TaxCode) && !FiscalCodeValidator.IsValid(supplier.TaxCode)) + { + problems.Add(new("einvoice.supplier.tax-code", Path + "CodiceFiscale", $"Il codice fiscale {supplier.TaxCode} del cedente/prestatore non è valido.")); + } + + CheckNames(supplier, Path, problems); + CheckOffice(supplier, Path, problems); + if (supplier.TaxRegime is { } regime && FatturaPaCodeLists.TaxRegimes.Find(regime) is null) + { + problems.Add(new("einvoice.code-list", Path + "RegimeFiscale", $"Il regime fiscale {regime} non è fra quelli ammessi.")); + } + + if (string.IsNullOrWhiteSpace(supplier.ReaOffice) != string.IsNullOrWhiteSpace(supplier.ReaNumber)) + { + problems.Add(new("einvoice.supplier.rea", Path + "IscrizioneREA", "Per l'iscrizione al REA servono ufficio e numero.", EInvoiceProblemSeverity.Warning)); + } + } + + private static void CheckCustomer(EInvoiceFile file, List problems) + { + const string Path = "CessionarioCommittente/"; + var customer = file.Customer; + var italian = (customer.CountryCode ?? customer.Country ?? "IT") == "IT"; + if (string.IsNullOrWhiteSpace(customer.VatNumber) && string.IsNullOrWhiteSpace(customer.TaxCode)) + { + problems.Add(new("00417", Path + "DatiAnagrafici", "Il cessionario/committente non ha né partita IVA né codice fiscale: almeno uno dei due è obbligatorio.")); + } + + if (italian && !string.IsNullOrWhiteSpace(customer.VatNumber) && !ItalianVatNumberValidator.IsValid(customer.VatNumber)) + { + problems.Add(new("00305", Path + "IdFiscaleIVA/IdCodice", $"La partita IVA {customer.VatNumber} del cessionario/committente non è valida.")); + } + + if (italian && !string.IsNullOrWhiteSpace(customer.TaxCode) && !FiscalCodeValidator.IsValid(customer.TaxCode)) + { + problems.Add(new("00306", Path + "CodiceFiscale", $"Il codice fiscale {customer.TaxCode} del cessionario/committente non è valido.")); + } + + CheckNames(customer, Path, problems); + CheckOffice(customer, Path, problems); + if (!italian && file.RecipientCode != FatturaPaCodeLists.RecipientCodeForeign) + { + problems.Add(new("einvoice.recipient.foreign", "CodiceDestinatario", "Per un cliente estero il codice destinatario è XXXXXXX.", EInvoiceProblemSeverity.Warning)); + } + } + + private static void CheckNames(EInvoiceParty party, string path, List problems) + { + if (string.IsNullOrWhiteSpace(party.Name) && (string.IsNullOrWhiteSpace(party.FirstName) || string.IsNullOrWhiteSpace(party.LastName))) + { + problems.Add(new("einvoice.party.name", path + "Anagrafica", "Serve la denominazione, oppure nome e cognome.")); + } + } + + private static void CheckOffice(EInvoiceParty party, string path, List problems) + { + var country = party.Country ?? party.CountryCode ?? "IT"; + if (string.IsNullOrWhiteSpace(party.Address) || string.IsNullOrWhiteSpace(party.City)) + { + problems.Add(new("einvoice.party.office", path + "Sede", "Servono indirizzo e comune della sede.")); + } + + if (country == "IT" && (party.PostalCode is not { Length: 5 } cap || !cap.All(char.IsAsciiDigit))) + { + problems.Add(new("einvoice.party.cap", path + "Sede/CAP", "Il CAP di una sede italiana ha 5 cifre.")); + } + + if (country == "IT" && party.Province is { Length: > 0 } province && (province.Length != 2 || !province.All(char.IsAsciiLetter))) + { + problems.Add(new("einvoice.party.province", path + "Sede/Provincia", "La provincia si indica con la sigla di due lettere.")); + } + } + + // --- Body -------------------------------------------------------------------------------------------------------- + + private static void CheckBody(EInvoiceFile file, EInvoiceBody body, string prefix, List problems) + { + var document = prefix + "DatiGeneraliDocumento/"; + if (FatturaPaCodeLists.DocumentTypes.Find(body.DocumentType) is null || FatturaPaCodeLists.SimplifiedDocumentTypes.Contains(body.DocumentType)) + { + problems.Add(new("einvoice.code-list", document + "TipoDocumento", $"Il tipo documento {body.DocumentType} non è ammesso in una fattura ordinaria.")); + } + + if (string.IsNullOrWhiteSpace(body.Number) || body.Number.Length > 20 || !body.Number.Any(char.IsAsciiDigit)) + { + problems.Add(new("einvoice.number", document + "Numero", "Il numero del documento è obbligatorio, contiene almeno una cifra e non supera 20 caratteri.")); + } + + if (body.Currency.Length != 3) + { + problems.Add(new("einvoice.currency", document + "Divisa", "La divisa è il codice ISO di 3 lettere.")); + } + + CheckParties(file, body, problems); + CheckWithholdings(body, document, problems); + CheckDiscounts(body.Discounts, document + "ScontoMaggiorazione", "00437", problems); + CheckReferences(file, body, prefix, problems); + + var lines = prefix + "DatiBeniServizi/DettaglioLinee"; + if (body.Lines.Count == 0) + { + problems.Add(new("einvoice.lines", lines, "La fattura non ha righe.")); + } + + foreach (var line in body.Lines) + { + CheckLine(line, $"{lines}[{line.Number}]/", problems); + } + + CheckSummary(body, prefix + "DatiBeniServizi/DatiRiepilogo", problems); + CheckPayments(body, prefix + "DatiPagamento", problems); + } + + private static void CheckParties(EInvoiceFile file, EInvoiceBody body, List problems) + { + var same = SameSubject(file.Supplier, file.Customer); + if (DifferentParties.Contains(body.DocumentType) && same) + { + problems.Add(new("00471", "CedentePrestatore", $"Con il tipo documento {body.DocumentType} cedente/prestatore e cessionario/committente non possono coincidere.")); + } + + if (SameParty.Contains(body.DocumentType) && !same) + { + problems.Add(new("00472", "CedentePrestatore", $"Con il tipo documento {body.DocumentType} cedente/prestatore e cessionario/committente devono coincidere.")); + } + + if (ForeignSupplier.Contains(body.DocumentType) && (file.Supplier.CountryCode ?? "IT") == "IT") + { + problems.Add(new("00473", "CedentePrestatore/IdFiscaleIVA/IdPaese", $"Con il tipo documento {body.DocumentType} il cedente/prestatore non può essere residente in Italia.")); + } + + if (body.DocumentType == "TD28" && file.Supplier.CountryCode != "SM") + { + problems.Add(new("00473", "CedentePrestatore/IdFiscaleIVA/IdPaese", "Con il tipo documento TD28 il cedente/prestatore è di San Marino (SM).")); + } + } + + private static bool SameSubject(EInvoiceParty a, EInvoiceParty b) + { + static string Key(EInvoiceParty p) => ((p.CountryCode ?? "IT") + ":" + (p.VatNumber ?? p.TaxCode ?? string.Empty)).Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + return !string.IsNullOrWhiteSpace(a.VatNumber ?? a.TaxCode) && Key(a) == Key(b); + } + + private static void CheckWithholdings(EInvoiceBody body, string document, List problems) + { + if (body.Withholdings.Count == 0 && body.Lines.Any(l => l.Withheld)) + { + problems.Add(new("00411", document + "DatiRitenuta", "Ci sono righe soggette a ritenuta ma manca il blocco DatiRitenuta.")); + } + + if (body.Withholdings.Count == 0 && body.SocialSecurity.Any(s => s.Withheld)) + { + problems.Add(new("00415", document + "DatiRitenuta", "Il contributo cassa è soggetto a ritenuta ma manca il blocco DatiRitenuta.")); + } + + foreach (var withholding in body.Withholdings) + { + if (FatturaPaCodeLists.WithholdingTypes.Find(withholding.Type) is null) + { + problems.Add(new("einvoice.code-list", document + "DatiRitenuta/TipoRitenuta", $"Il tipo di ritenuta {withholding.Type} non è ammesso.")); + } + + if (withholding.Reason is { } reason && FatturaPaCodeLists.WithholdingReasons.Find(reason) is null) + { + problems.Add(new("einvoice.code-list", document + "DatiRitenuta/CausalePagamento", $"La causale di pagamento {reason} non è ammessa.")); + } + } + + foreach (var fund in body.SocialSecurity) + { + if (FatturaPaCodeLists.SocialSecurityFunds.Find(fund.Fund) is null) + { + problems.Add(new("einvoice.code-list", document + "DatiCassaPrevidenziale/TipoCassa", $"La cassa {fund.Fund} non è ammessa.")); + } + + CheckNature(fund.TaxRate, fund.Nature, document + "DatiCassaPrevidenziale/", "00413", "00414", problems); + } + } + + private static void CheckDiscounts(IReadOnlyList discounts, string path, string code, List problems) + { + if (discounts.Any(d => d.Percent is null && d.Amount is null)) + { + problems.Add(new(code, path, "Uno sconto o una maggiorazione non ha né percentuale né importo.")); + } + } + + private static void CheckReferences(EInvoiceFile file, EInvoiceBody body, string prefix, List problems) + { + foreach (var reference in body.Orders.Concat(body.Contracts).Concat(body.RelatedInvoices)) + { + if (string.IsNullOrWhiteSpace(reference.Id)) + { + problems.Add(new("einvoice.reference.id", prefix + "DatiGenerali", "Un riferimento a ordine, contratto o fattura collegata non ha il numero del documento (IdDocumento).")); + } + + if (reference.Cig is { Length: > 0 } cig && (cig.Length != 10 || !cig.All(char.IsAsciiLetterOrDigit))) + { + problems.Add(new("einvoice.reference.cig", prefix + "DatiGenerali/CodiceCIG", $"Il CIG {cig} non ha la forma di 10 caratteri alfanumerici.", EInvoiceProblemSeverity.Warning)); + } + + if (reference.Cup is { Length: > 0 } cup && (cup.Length != 15 || !cup.All(char.IsAsciiLetterOrDigit))) + { + problems.Add(new("einvoice.reference.cup", prefix + "DatiGenerali/CodiceCUP", $"Il CUP {cup} non ha la forma di 15 caratteri alfanumerici.", EInvoiceProblemSeverity.Warning)); + } + } + + if (body.DocumentType is "TD04" or "TD05" && body.RelatedInvoices.Count == 0) + { + problems.Add(new("einvoice.reference.related", prefix + "DatiGenerali/DatiFattureCollegate", "Una nota di credito o di debito di solito indica la fattura collegata.", EInvoiceProblemSeverity.Warning)); + } + + if (file.TransmissionFormat == "FPA12" && body.Orders.Concat(body.Contracts).All(r => string.IsNullOrWhiteSpace(r.Cig))) + { + problems.Add(new("einvoice.reference.pa-cig", prefix + "DatiGenerali", "Fattura verso una pubblica amministrazione senza CIG: indicalo, oppure verifica che il contratto ne sia escluso.", EInvoiceProblemSeverity.Warning)); + } + } + + private static void CheckLine(EInvoiceLine line, string path, List problems) + { + if (string.IsNullOrWhiteSpace(line.Description)) + { + problems.Add(new("einvoice.line.description", path + "Descrizione", "La riga non ha descrizione.")); + } + + if (line.Quantity is < 0m) + { + problems.Add(new("einvoice.line.quantity", path + "Quantita", "La quantità non può essere negativa: il segno va sul prezzo.")); + } + + CheckNature(line.TaxRate, line.Nature, path, "00400", "00401", problems); + CheckDiscounts(line.Discounts, path + "ScontoMaggiorazione", "00438", problems); + + // PrezzoTotale = PrezzoUnitario × Quantita (1 without quantity), less discounts and plus surcharges in order. + var price = line.UnitPrice; + foreach (var discount in line.Discounts) + { + var change = discount.Amount ?? Math.Round(price * (discount.Percent ?? 0m) / 100m, 8, MidpointRounding.AwayFromZero); + price += discount.IsSurcharge ? change : -change; + } + + var expected = price * (line.Quantity ?? 1m); + if (Math.Abs(expected - line.TotalPrice) > 0.01m) + { + problems.Add(new("00423", path + "PrezzoTotale", + $"PrezzoTotale {FatturaPaWriter.Amount8(line.TotalPrice)} non è PrezzoUnitario × Quantita al netto degli sconti ({FatturaPaWriter.Amount8(Math.Round(expected, 8))}).")); + } + } + + private static void CheckNature(decimal rate, string? nature, string path, string missingCode, string presentCode, List problems) + { + if (rate == 0m && string.IsNullOrWhiteSpace(nature)) + { + problems.Add(new(missingCode, path + "Natura", "Con aliquota IVA zero serve la natura dell'operazione (N1-N7).")); + } + else if (rate != 0m && !string.IsNullOrWhiteSpace(nature)) + { + problems.Add(new(presentCode, path + "Natura", "La natura si indica solo con aliquota IVA zero.")); + } + else if (nature is { Length: > 0 } && GenericNatures.Contains(nature)) + { + problems.Add(new("00445", path + "Natura", $"La natura {nature} non è più ammessa: usa il sotto-codice (per esempio N2.2, N3.1, N6.3).")); + } + else if (nature is { Length: > 0 } && VatNatures.All.Find(nature) is null) + { + problems.Add(new("einvoice.code-list", path + "Natura", $"La natura {nature} non è fra quelle ammesse.")); + } + + if (rate is < 0m or > 100m) + { + problems.Add(new("einvoice.rate", path + "AliquotaIVA", "L'aliquota IVA è una percentuale fra 0 e 100.")); + } + } + + private static void CheckSummary(EInvoiceBody body, string path, List problems) + { + static (decimal, string) Key(decimal rate, string? nature) => (rate, nature ?? string.Empty); + var rows = body.TaxSummary.GroupBy(r => Key(r.Rate, r.Nature)).ToDictionary(g => g.Key, g => g.ToList()); + var lines = body.Lines.GroupBy(l => Key(l.TaxRate, l.Nature)).ToDictionary(g => g.Key, g => g.Sum(l => l.TotalPrice)); + foreach (var fund in body.SocialSecurity) + { + var key = Key(fund.TaxRate, fund.Nature); + lines[key] = (lines.TryGetValue(key, out var sum) ? sum : 0m) + fund.Amount; + } + + foreach (var (key, total) in lines) + { + if (!rows.TryGetValue(key, out var summary)) + { + problems.Add(new("00419", path, $"Manca il riepilogo per l'aliquota {FatturaPaWriter.Rate(key.Item1)}{(key.Item2.Length > 0 ? " natura " + key.Item2 : string.Empty)} usata nelle righe.")); + continue; + } + + var declared = summary.Sum(r => r.Taxable - (r.Rounding ?? 0m)); + var expenses = summary.Sum(r => r.ExpensesAmount ?? 0m); + if (Math.Abs(declared - expenses - total) > 1m) + { + problems.Add(new("00422", path + "/ImponibileImporto", + $"ImponibileImporto {FatturaPaWriter.Amount2(declared)} non corrisponde alla somma delle righe con aliquota {FatturaPaWriter.Rate(key.Item1)} ({FatturaPaWriter.Amount2(total)}).")); + } + } + + foreach (var row in body.TaxSummary) + { + CheckNature(row.Rate, row.Nature, path + "/", "00429", "00430", problems); + var tax = Math.Round(row.Taxable * row.Rate / 100m, 2, MidpointRounding.AwayFromZero); + if (Math.Abs(tax - row.Tax) > 0.01m) + { + problems.Add(new("00421", path + "/Imposta", + $"Imposta {FatturaPaWriter.Amount2(row.Tax)} non è ImponibileImporto × AliquotaIVA ({FatturaPaWriter.Amount2(tax)}).")); + } + + if (row.Exigibility is { } exigibility && exigibility is not ("I" or "D" or "S")) + { + problems.Add(new("einvoice.code-list", path + "/EsigibilitaIVA", $"L'esigibilità {exigibility} non è ammessa (I, D, S).")); + } + + if (row.Exigibility == "S" && row.Nature is not null) + { + problems.Add(new("einvoice.split.nature", path + "/EsigibilitaIVA", "La scissione dei pagamenti (S) non si applica alle operazioni senza IVA.")); + } + + if (row.Nature is not null && string.IsNullOrWhiteSpace(row.LegalReference)) + { + problems.Add(new("einvoice.summary.legal-reference", path + "/RiferimentoNormativo", $"Per la natura {row.Nature} conviene indicare la norma (RiferimentoNormativo).", EInvoiceProblemSeverity.Warning)); + } + } + + if (body.StampDuty is null && body.TaxSummary.Where(r => VatNatures.CountsForStampDuty(r.Nature)).Sum(r => r.Taxable) > 77.47m) + { + problems.Add(new("einvoice.stamp-duty", "DatiGeneraliDocumento/DatiBollo", + "Le operazioni senza IVA superano 77,47 euro: di solito è dovuto il bollo virtuale di 2 euro.", EInvoiceProblemSeverity.Warning)); + } + } + + private static void CheckPayments(EInvoiceBody body, string path, List problems) + { + foreach (var payment in body.Payments) + { + if (payment.Method is { } method && FatturaPaCodeLists.PaymentMethods.Find(method) is null) + { + problems.Add(new("einvoice.code-list", path + "/DettaglioPagamento/ModalitaPagamento", $"La modalità di pagamento {method} non è ammessa.")); + } + + if (payment.Iban is { Length: > 0 } iban && !IbanValidator.IsValid(iban)) + { + problems.Add(new("einvoice.payment.iban", path + "/DettaglioPagamento/IBAN", $"L'IBAN {iban} non è valido.")); + } + } + + if (body.PaymentConditions is { } conditions && FatturaPaCodeLists.PaymentConditions.Find(conditions) is null) + { + problems.Add(new("einvoice.code-list", path + "/CondizioniPagamento", $"La condizione di pagamento {conditions} non è ammessa.")); + } + } + + private static XmlSchemaSet LoadSchemas() + { + var assembly = typeof(FatturaPaValidator).Assembly; + var name = assembly.GetManifestResourceNames().Single(n => n.EndsWith("FatturaPA_v1.2_khaemhat.xsd", StringComparison.Ordinal)); + using var stream = assembly.GetManifestResourceStream(name)!; + var set = new XmlSchemaSet { XmlResolver = null }; + using var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); + set.Add(FatturaPaWriter.Namespace, reader); + set.Compile(); + return set; + } +} diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs new file mode 100644 index 0000000..4099463 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs @@ -0,0 +1,655 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Writes FatturaPA files v1.2 (FPR12 to businesses and consumers, FPA12 to the public administration) +/// following the technical specifications of the Agenzia delle Entrate (, +/// SPEC §11.9, ADR 0039). +/// +/// +/// Only the root element is in the namespace of the schema (its elementFormDefault is unqualified); the +/// children follow the order of the schema. Amounts use the dot and the decimals of the schema types: two for +/// totals, from two to eight for prices and quantities. Optional values that are empty are left out. +/// Text fields of the schema accept Basic Latin and Latin-1 only: typographic quotes, dashes and the euro sign are +/// replaced by their plain equivalents, other characters by ?, and texts longer than the field are cut. The +/// writer does not check the content: does, before the file is written. +/// The simplified invoice FSM10 is read () but not written: Khaemhat issues +/// ordinary invoices only. +/// +public sealed class FatturaPaWriter : IEInvoiceWriter +{ + /// The namespace of FatturaPA v1.2. + public const string Namespace = "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2"; + + private const string DigitsBase36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + /// + public string FileName(string transmitterCountry, string transmitterId, long progressive) + { + ArgumentException.ThrowIfNullOrWhiteSpace(transmitterCountry); + ArgumentException.ThrowIfNullOrWhiteSpace(transmitterId); + return transmitterCountry.Trim().ToUpperInvariant() + transmitterId.Trim().ToUpperInvariant() + "_" + Progressive(progressive) + ".xml"; + } + + /// + public string Progressive(long progressive) + { + ArgumentOutOfRangeException.ThrowIfLessThan(progressive, 1); + + // Five characters of base 36 give 60,466,175 files per transmitter, more than the life of a company. + ArgumentOutOfRangeException.ThrowIfGreaterThan(progressive, 60_466_175); + var text = new char[5]; + var value = progressive; + for (var i = text.Length - 1; i >= 0; i--) + { + text[i] = DigitsBase36[(int)(value % 36)]; + value /= 36; + } + + return new string(text); + } + + /// + public byte[] Write(EInvoiceFile file) + { + ArgumentNullException.ThrowIfNull(file); + var format = file.TransmissionFormat ?? "FPR12"; + if (format is not ("FPR12" or "FPA12")) + { + throw new ArgumentException($"The format {format} is not written: only FPR12 and FPA12.", nameof(file)); + } + + if (file.Invoices.Count == 0) + { + throw new ArgumentException("The file has no invoice.", nameof(file)); + } + + using var buffer = new MemoryStream(); + var settings = new XmlWriterSettings + { + Encoding = new UTF8Encoding(false), + Indent = true, + IndentChars = " ", + NewLineChars = "\n", + }; + using (var xml = XmlWriter.Create(buffer, settings)) + { + xml.WriteStartDocument(); + xml.WriteStartElement("p", "FatturaElettronica", Namespace); + xml.WriteAttributeString("versione", format); + xml.WriteAttributeString("xmlns", "ds", null, "http://www.w3.org/2000/09/xmldsig#"); + xml.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance"); + WriteHeader(xml, file, format); + foreach (var body in file.Invoices) + { + WriteBody(xml, body); + } + + xml.WriteEndElement(); + xml.WriteEndDocument(); + } + + return buffer.ToArray(); + } + + // --- Header ------------------------------------------------------------------------------------------------------ + + private static void WriteHeader(XmlWriter xml, EInvoiceFile file, string format) + { + xml.WriteStartElement("FatturaElettronicaHeader"); + + xml.WriteStartElement("DatiTrasmissione"); + xml.WriteStartElement("IdTrasmittente"); + Element(xml, "IdPaese", file.TransmitterCountry ?? file.Supplier.CountryCode ?? "IT"); + Element(xml, "IdCodice", file.TransmitterId ?? file.Supplier.TaxCode ?? file.Supplier.VatNumber ?? string.Empty); + xml.WriteEndElement(); + Element(xml, "ProgressivoInvio", file.ProgressiveNumber ?? "00001"); + Element(xml, "FormatoTrasmissione", format); + Element(xml, "CodiceDestinatario", file.RecipientCode ?? (format == "FPA12" ? string.Empty : FatturaPaCodeLists.RecipientCodeNone)); + if (!string.IsNullOrWhiteSpace(file.TransmitterEmail)) + { + xml.WriteStartElement("ContattiTrasmittente"); + Element(xml, "Email", Text(file.TransmitterEmail, 256)); + xml.WriteEndElement(); + } + + Optional(xml, "PECDestinatario", file.RecipientPec, 256); + xml.WriteEndElement(); + + xml.WriteStartElement("CedentePrestatore"); + xml.WriteStartElement("DatiAnagrafici"); + WriteVat(xml, file.Supplier); + Optional(xml, "CodiceFiscale", file.Supplier.TaxCode, 16); + WriteNames(xml, file.Supplier); + Element(xml, "RegimeFiscale", file.Supplier.TaxRegime ?? "RF01"); + xml.WriteEndElement(); + WriteOffice(xml, file.Supplier); + if (!string.IsNullOrWhiteSpace(file.Supplier.ReaOffice) && !string.IsNullOrWhiteSpace(file.Supplier.ReaNumber)) + { + xml.WriteStartElement("IscrizioneREA"); + Element(xml, "Ufficio", file.Supplier.ReaOffice!.Trim().ToUpperInvariant()); + Element(xml, "NumeroREA", Text(file.Supplier.ReaNumber, 20)); + if (file.Supplier.ShareCapital is { } capital) + { + Element(xml, "CapitaleSociale", Amount2(capital)); + } + + Optional(xml, "SocioUnico", file.Supplier.Shareholders, 2); + Element(xml, "StatoLiquidazione", file.Supplier.LiquidationStatus ?? "LN"); + xml.WriteEndElement(); + } + + if (!string.IsNullOrWhiteSpace(file.Supplier.Phone) || !string.IsNullOrWhiteSpace(file.Supplier.Email)) + { + xml.WriteStartElement("Contatti"); + Optional(xml, "Telefono", Phone(file.Supplier.Phone), 12); + Optional(xml, "Email", file.Supplier.Email, 256); + xml.WriteEndElement(); + } + + Optional(xml, "RiferimentoAmministrazione", file.Supplier.AdministrationReference, 20); + xml.WriteEndElement(); + + xml.WriteStartElement("CessionarioCommittente"); + xml.WriteStartElement("DatiAnagrafici"); + if (!string.IsNullOrWhiteSpace(file.Customer.VatNumber)) + { + WriteVat(xml, file.Customer); + } + + Optional(xml, "CodiceFiscale", file.Customer.TaxCode, 16); + WriteNames(xml, file.Customer); + xml.WriteEndElement(); + WriteOffice(xml, file.Customer); + xml.WriteEndElement(); + + if (file.Intermediary is { } intermediary) + { + xml.WriteStartElement("TerzoIntermediarioOSoggettoEmittente"); + xml.WriteStartElement("DatiAnagrafici"); + if (!string.IsNullOrWhiteSpace(intermediary.VatNumber)) + { + WriteVat(xml, intermediary); + } + + Optional(xml, "CodiceFiscale", intermediary.TaxCode, 16); + WriteNames(xml, intermediary); + xml.WriteEndElement(); + xml.WriteEndElement(); + } + + Optional(xml, "SoggettoEmittente", file.IssuedBy, 2); + xml.WriteEndElement(); + } + + private static void WriteVat(XmlWriter xml, EInvoiceParty party) + { + xml.WriteStartElement("IdFiscaleIVA"); + Element(xml, "IdPaese", (party.CountryCode ?? "IT").Trim().ToUpperInvariant()); + Element(xml, "IdCodice", Text(party.VatNumber, 28).Replace(" ", string.Empty, StringComparison.Ordinal)); + xml.WriteEndElement(); + } + + private static void WriteNames(XmlWriter xml, EInvoiceParty party) + { + xml.WriteStartElement("Anagrafica"); + if (!string.IsNullOrWhiteSpace(party.Name)) + { + Element(xml, "Denominazione", Text(party.Name, 80)); + } + else + { + Element(xml, "Nome", Text(party.FirstName, 60)); + Element(xml, "Cognome", Text(party.LastName, 60)); + } + + xml.WriteEndElement(); + } + + private static void WriteOffice(XmlWriter xml, EInvoiceParty party) + { + var country = (party.Country ?? party.CountryCode ?? "IT").Trim().ToUpperInvariant(); + xml.WriteStartElement("Sede"); + Element(xml, "Indirizzo", Text(party.Address, 60)); + Optional(xml, "NumeroCivico", party.StreetNumber, 8); + + // A foreign address has no Italian postal code: the specifications ask for 00000 and no province. + Element(xml, "CAP", country == "IT" ? Text(party.PostalCode, 5) : "00000"); + Element(xml, "Comune", Text(party.City, 60)); + if (country == "IT") + { + Optional(xml, "Provincia", party.Province?.Trim().ToUpperInvariant(), 2); + } + + Element(xml, "Nazione", country); + xml.WriteEndElement(); + } + + // --- Body -------------------------------------------------------------------------------------------------------- + + private static void WriteBody(XmlWriter xml, EInvoiceBody body) + { + xml.WriteStartElement("FatturaElettronicaBody"); + xml.WriteStartElement("DatiGenerali"); + WriteDocumentData(xml, body); + WriteReferences(xml, "DatiOrdineAcquisto", body.Orders); + WriteReferences(xml, "DatiContratto", body.Contracts); + WriteReferences(xml, "DatiFattureCollegate", body.RelatedInvoices); + foreach (var note in body.DeliveryNotes) + { + xml.WriteStartElement("DatiDDT"); + Element(xml, "NumeroDDT", Text(note.Id, 20)); + Element(xml, "DataDDT", Date(note.Date ?? body.Date)); + foreach (var line in note.LineNumbers) + { + Element(xml, "RiferimentoNumeroLinea", line.ToString(CultureInfo.InvariantCulture)); + } + + xml.WriteEndElement(); + } + + if (body.Transport is { } transport) + { + WriteTransport(xml, transport); + } + + xml.WriteEndElement(); + + xml.WriteStartElement("DatiBeniServizi"); + foreach (var line in body.Lines) + { + WriteLine(xml, line); + } + + foreach (var row in body.TaxSummary) + { + xml.WriteStartElement("DatiRiepilogo"); + Element(xml, "AliquotaIVA", Rate(row.Rate)); + Optional(xml, "Natura", row.Nature, 4); + if (row.ExpensesAmount is { } expenses) + { + Element(xml, "SpeseAccessorie", Amount2(expenses)); + } + + if (row.Rounding is { } rounding) + { + Element(xml, "Arrotondamento", Amount8(rounding)); + } + + Element(xml, "ImponibileImporto", Amount2(row.Taxable)); + Element(xml, "Imposta", Amount2(row.Tax)); + Optional(xml, "EsigibilitaIVA", row.Exigibility, 1); + Optional(xml, "RiferimentoNormativo", row.LegalReference, 100); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + + if (body.Payments.Count > 0) + { + xml.WriteStartElement("DatiPagamento"); + Element(xml, "CondizioniPagamento", body.PaymentConditions ?? body.Payments[0].Conditions ?? (body.Payments.Count > 1 ? "TP01" : "TP02")); + foreach (var payment in body.Payments) + { + xml.WriteStartElement("DettaglioPagamento"); + Optional(xml, "Beneficiario", payment.Beneficiary, 200); + Element(xml, "ModalitaPagamento", payment.Method ?? "MP05"); + if (payment.DueDate is { } due) + { + Element(xml, "DataScadenzaPagamento", Date(due)); + } + + Element(xml, "ImportoPagamento", Amount2(payment.Amount)); + Optional(xml, "IBAN", payment.Iban?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(), 34); + Optional(xml, "BIC", payment.Bic?.Trim().ToUpperInvariant(), 11); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + } + + foreach (var attachment in body.Attachments) + { + xml.WriteStartElement("Allegati"); + Element(xml, "NomeAttachment", Text(attachment.Name, 60)); + Optional(xml, "FormatoAttachment", attachment.Format, 10); + Optional(xml, "DescrizioneAttachment", attachment.Description, 100); + Element(xml, "Attachment", Convert.ToBase64String(attachment.Content)); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + } + + private static void WriteDocumentData(XmlWriter xml, EInvoiceBody body) + { + xml.WriteStartElement("DatiGeneraliDocumento"); + Element(xml, "TipoDocumento", body.DocumentType); + Element(xml, "Divisa", body.Currency); + Element(xml, "Data", Date(body.Date)); + Element(xml, "Numero", Text(body.Number, 20)); + foreach (var withholding in body.Withholdings) + { + xml.WriteStartElement("DatiRitenuta"); + Element(xml, "TipoRitenuta", withholding.Type); + Element(xml, "ImportoRitenuta", Amount2(withholding.Amount)); + Element(xml, "AliquotaRitenuta", Rate(withholding.Rate)); + Element(xml, "CausalePagamento", withholding.Reason ?? "A"); + xml.WriteEndElement(); + } + + if (body.StampDuty is { } stamp) + { + xml.WriteStartElement("DatiBollo"); + Element(xml, "BolloVirtuale", "SI"); + Element(xml, "ImportoBollo", Amount2(stamp.Amount)); + xml.WriteEndElement(); + } + + foreach (var fund in body.SocialSecurity) + { + xml.WriteStartElement("DatiCassaPrevidenziale"); + Element(xml, "TipoCassa", fund.Fund); + Element(xml, "AlCassa", Rate(fund.Rate)); + Element(xml, "ImportoContributoCassa", Amount2(fund.Amount)); + if (fund.Taxable is { } taxable) + { + Element(xml, "ImponibileCassa", Amount2(taxable)); + } + + Element(xml, "AliquotaIVA", Rate(fund.TaxRate)); + if (fund.Withheld) + { + Element(xml, "Ritenuta", "SI"); + } + + Optional(xml, "Natura", fund.Nature, 4); + xml.WriteEndElement(); + } + + WriteDiscounts(xml, body.Discounts); + if (body.Total is { } total) + { + Element(xml, "ImportoTotaleDocumento", Amount2(total)); + } + + if (body.Rounding is { } rounding) + { + Element(xml, "Arrotondamento", Amount2(rounding)); + } + + foreach (var causal in body.Causals.SelectMany(c => Chunks(c, 200))) + { + Element(xml, "Causale", causal); + } + + if (body.Art73) + { + Element(xml, "Art73", "SI"); + } + + xml.WriteEndElement(); + } + + private static void WriteReferences(XmlWriter xml, string name, IReadOnlyList references) + { + foreach (var reference in references) + { + xml.WriteStartElement(name); + foreach (var line in reference.LineNumbers) + { + Element(xml, "RiferimentoNumeroLinea", line.ToString(CultureInfo.InvariantCulture)); + } + + Element(xml, "IdDocumento", Text(reference.Id, 20)); + if (reference.Date is { } date) + { + Element(xml, "Data", Date(date)); + } + + Optional(xml, "CodiceCUP", reference.Cup, 15); + Optional(xml, "CodiceCIG", reference.Cig, 15); + xml.WriteEndElement(); + } + } + + private static void WriteTransport(XmlWriter xml, EInvoiceTransport transport) + { + xml.WriteStartElement("DatiTrasporto"); + + // The carrier is written only with its VAT number, which the schema requires. + if (!string.IsNullOrWhiteSpace(transport.CarrierVat) && !string.IsNullOrWhiteSpace(transport.CarrierName)) + { + xml.WriteStartElement("DatiAnagraficiVettore"); + xml.WriteStartElement("IdFiscaleIVA"); + Element(xml, "IdPaese", transport.CarrierCountry ?? "IT"); + Element(xml, "IdCodice", Text(transport.CarrierVat, 28)); + xml.WriteEndElement(); + xml.WriteStartElement("Anagrafica"); + Element(xml, "Denominazione", Text(transport.CarrierName, 80)); + xml.WriteEndElement(); + xml.WriteEndElement(); + } + + Optional(xml, "MezzoTrasporto", transport.Means, 80); + Optional(xml, "CausaleTrasporto", transport.Reason, 100); + if (transport.Packages is { } packages and > 0) + { + Element(xml, "NumeroColli", packages.ToString(CultureInfo.InvariantCulture)); + } + + Optional(xml, "Descrizione", transport.Description, 100); + if (transport.GrossWeight is not null || transport.NetWeight is not null) + { + Element(xml, "UnitaMisuraPeso", "KG"); + } + + if (transport.GrossWeight is { } gross) + { + Element(xml, "PesoLordo", Weight(gross)); + } + + if (transport.NetWeight is { } net) + { + Element(xml, "PesoNetto", Weight(net)); + } + + if (transport.Start is { } start) + { + Element(xml, "DataInizioTrasporto", Date(DateOnly.FromDateTime(start))); + } + + Optional(xml, "TipoResa", transport.ShippingTerms, 3); + xml.WriteEndElement(); + } + + private static void WriteLine(XmlWriter xml, EInvoiceLine line) + { + xml.WriteStartElement("DettaglioLinee"); + Element(xml, "NumeroLinea", line.Number.ToString(CultureInfo.InvariantCulture)); + Optional(xml, "TipoCessionePrestazione", line.LineType, 2); + foreach (var code in line.Codes) + { + xml.WriteStartElement("CodiceArticolo"); + Element(xml, "CodiceTipo", Text(code.Type, 35)); + Element(xml, "CodiceValore", Text(code.Value, 35)); + xml.WriteEndElement(); + } + + Element(xml, "Descrizione", Text(line.Description, 1000)); + if (line.Quantity is { } quantity) + { + Element(xml, "Quantita", Amount8(Math.Abs(quantity))); + } + + Optional(xml, "UnitaMisura", line.Unit, 10); + if (line.PeriodStart is { } from) + { + Element(xml, "DataInizioPeriodo", Date(from)); + } + + if (line.PeriodEnd is { } to) + { + Element(xml, "DataFinePeriodo", Date(to)); + } + + Element(xml, "PrezzoUnitario", Amount8(line.UnitPrice)); + WriteDiscounts(xml, line.Discounts); + Element(xml, "PrezzoTotale", Amount8(line.TotalPrice)); + Element(xml, "AliquotaIVA", Rate(line.TaxRate)); + if (line.Withheld) + { + Element(xml, "Ritenuta", "SI"); + } + + Optional(xml, "Natura", line.Nature, 4); + Optional(xml, "RiferimentoAmministrazione", line.AdministrativeReference, 20); + foreach (var data in line.OtherData) + { + xml.WriteStartElement("AltriDatiGestionali"); + Element(xml, "TipoDato", Text(data.Type, 10)); + Optional(xml, "RiferimentoTesto", data.Text, 60); + if (data.Number is { } number) + { + Element(xml, "RiferimentoNumero", Amount8(number)); + } + + if (data.Date is { } date) + { + Element(xml, "RiferimentoData", Date(date)); + } + + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + } + + private static void WriteDiscounts(XmlWriter xml, IReadOnlyList discounts) + { + foreach (var discount in discounts) + { + xml.WriteStartElement("ScontoMaggiorazione"); + Element(xml, "Tipo", discount.IsSurcharge ? "MG" : "SC"); + if (discount.Percent is { } percent) + { + Element(xml, "Percentuale", Rate(percent)); + } + + if (discount.Amount is { } amount) + { + Element(xml, "Importo", Amount8(amount)); + } + + xml.WriteEndElement(); + } + } + + // --- Values ------------------------------------------------------------------------------------------------------ + + private static void Element(XmlWriter xml, string name, string value) => xml.WriteElementString(name, value); + + private static void Optional(XmlWriter xml, string name, string? value, int maxLength) + { + if (!string.IsNullOrWhiteSpace(value)) + { + xml.WriteElementString(name, Text(value, maxLength)); + } + } + + /// A text in the characters and length the schema accepts. + /// The text. + /// The length of the field. + /// The text, trimmed, in Latin-1 and cut to the length. + public static string Text(string? value, int maxLength) + { + if (string.IsNullOrWhiteSpace(value)) + { + return string.Empty; + } + + var text = new StringBuilder(value.Length); + foreach (var c in value.Trim()) + { + text.Append(c switch + { + '‘' or '’' or '‚' or '′' => "'", + '“' or '”' or '„' or '″' => "\"", + '–' or '—' or '−' => "-", + '…' => "...", + '€' => "EUR", + ' ' or '\t' => " ", + '\r' => string.Empty, + '\n' => " ", + _ when c <= 'ÿ' && !char.IsControl(c) => c.ToString(), + _ => "?", + }); + } + + var result = text.ToString().Trim(); + return result.Length <= maxLength ? result : result[..maxLength].TrimEnd(); + } + + // The causal is a list of fields of 200 characters: a long note becomes several, cut at a space when possible. + private static IEnumerable Chunks(string value, int size) + { + var text = Text(value, int.MaxValue); + while (text.Length > size) + { + var cut = text.LastIndexOf(' ', size - 1); + if (cut < size / 2) + { + cut = size; + } + + yield return text[..cut].TrimEnd(); + text = text[cut..].TrimStart(); + } + + if (text.Length > 0) + { + yield return text; + } + } + + private static string? Phone(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + var digits = new string(value.Where(c => char.IsAsciiDigit(c) || c == '+').ToArray()); + return digits.Length is >= 5 and <= 12 ? digits : null; + } + + /// A date as the schema wants it. + /// The date. + /// yyyy-MM-dd. + public static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + + /// An amount with two decimals (Amount2DecimalType). + /// The amount. + /// The text. + public static string Amount2(decimal value) => + Math.Round(value, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture); + + /// An amount with two to eight decimals (Amount8DecimalType, QuantitaType). + /// The amount. + /// The text. + public static string Amount8(decimal value) => + Math.Round(value, 8, MidpointRounding.AwayFromZero).ToString("0.00######", CultureInfo.InvariantCulture); + + /// A rate in percent (RateType). + /// The rate. + /// The text with two decimals. + public static string Rate(decimal value) => + Math.Round(value, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture); + + private static string Weight(decimal value) => + Math.Round(value, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture); +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs index 39bbbe1..3b055d1 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs @@ -3,7 +3,7 @@ using Khaemhat.Fiscal.Abstractions; namespace Khaemhat.Fiscal.Italy; -/// The FatturaPA format: version of the specifications and code lists (writer and reader arrive in M9). +/// The FatturaPA format: version of the specifications and code lists (writer, validator and readers are features of their own). public sealed class FatturaPaFormat : IEInvoiceFormat { /// diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 2996c89..1d823b9 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -18,6 +18,11 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new LatePaymentRulesIt()); AddFeature(new RemittanceMethodsIt()); AddFeature(new FatturaPaReader()); + AddFeature(new FatturaPaWriter()); + AddFeature(new FatturaPaValidator()); + AddFeature(new SdiReceiptReader()); + AddFeature(new Sdi.SdiChannels()); + AddFeature(new Sdi.SdiCoopPushReader()); AddFeature(new IncomingInvoiceRulesIt()); AddFeature(new SelfInvoiceRulesIt()); AddFeature(new WithholdingRulesIt()); diff --git a/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj b/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj index a03d77e..bafab0b 100644 --- a/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj +++ b/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj @@ -7,6 +7,7 @@ + diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/IntermediaryTransports.cs b/src/Khaemhat.Fiscal.Italy/Sdi/IntermediaryTransports.cs new file mode 100644 index 0000000..c30cdaa --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Sdi/IntermediaryTransports.cs @@ -0,0 +1,355 @@ +using System.Globalization; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Sdi; + +/// +/// The common part of the channels through an intermediary (SPEC §11.9, issue #77): an HTTP API that sends files to the +/// SDI on behalf of the company and keeps receipts and supplier invoices until they are acknowledged. +/// +/// The two contracts (, ) are generic and +/// documented in ADR 0040: they become the API of a real provider once the user chooses one (issue #78), changing only +/// the requests of the derived class. +/// Makes the HTTP handler (tests); by default a plain handler. +public abstract class IntermediaryTransportBase(Func? handlerFactory) : IEInvoiceTransport +{ + /// JSON with camel-case names. + protected static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + /// + public abstract string Code { get; } + + /// + public bool Polls => true; + + /// + public async Task SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(file); + if (Missing(settings) is { } missing) + { + return new EInvoiceSendResult(false, null, null, missing); + } + + try + { + using var client = Client(settings); + using var request = SendRequest(settings, file); + using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false); + var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + return new EInvoiceSendResult(false, null, null, $"{(int)response.StatusCode}: {ErrorOf(text)}"); + } + + var (messageId, exchangeId) = ReadSendAnswer(text); + return new EInvoiceSendResult(true, exchangeId, messageId, null); + } + catch (Exception ex) when (ex is HttpRequestException or JsonException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested)) + { + return new EInvoiceSendResult(false, null, null, ex.Message); + } + } + + /// + public async Task FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + if (Missing(settings) is { } missing) + { + throw new HttpRequestException(missing); + } + + using var client = Client(settings); + using var response = await client.SendAsync(FetchRequest(settings), cancellationToken).ConfigureAwait(false); + var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + throw new HttpRequestException($"{(int)response.StatusCode}: {ErrorOf(text)}"); + } + + var files = ReadFiles(text); + return new EInvoiceFetchResult(files, files.Select(f => f.MessageKey).Distinct().Count(), null); + } + + /// + public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection messageKeys, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(messageKeys); + using var client = Client(settings); + foreach (var key in messageKeys.Distinct(StringComparer.Ordinal)) + { + using var response = await client.SendAsync(AcknowledgeRequest(settings, key), cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode && response.StatusCode != System.Net.HttpStatusCode.NotFound) + { + throw new HttpRequestException($"{(int)response.StatusCode} acknowledging {key}."); + } + } + } + + /// + public async Task CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + if (Missing(settings) is { } missing) + { + return new EInvoiceChannelCheck(false, missing); + } + + try + { + using var client = Client(settings); + using var response = await client.SendAsync(CheckRequest(settings), cancellationToken).ConfigureAwait(false); + return response.IsSuccessStatusCode + ? new EInvoiceChannelCheck(true, $"{settings.Endpoint} answered {(int)response.StatusCode}: credentials accepted.") + : new EInvoiceChannelCheck(false, $"{settings.Endpoint} answered {(int)response.StatusCode}."); + } + catch (Exception ex) when (ex is HttpRequestException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested)) + { + return new EInvoiceChannelCheck(false, ex.Message); + } + } + + /// What is missing in the settings, or . + /// The settings. + /// The message. + protected abstract string? Missing(EInvoiceChannelSettings settings); + + /// The request that sends a file. + /// The settings. + /// The file. + /// The request. + protected abstract HttpRequestMessage SendRequest(EInvoiceChannelSettings settings, EInvoiceOutgoing file); + + /// Reads the answer to a file sent. + /// The body. + /// The identifier at the intermediary and the one of the SDI, if already known. + protected abstract (string? MessageId, string? ExchangeId) ReadSendAnswer(string json); + + /// The request that lists the waiting files. + /// The settings. + /// The request. + protected abstract HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings); + + /// Reads the waiting files. + /// The body. + /// The files. + protected abstract IReadOnlyList ReadFiles(string json); + + /// The request that acknowledges a file. + /// The settings. + /// The key. + /// The request. + protected abstract HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key); + + /// The request that tests the credentials. + /// The settings. + /// The request. + protected abstract HttpRequestMessage CheckRequest(EInvoiceChannelSettings settings); + + /// An address under the endpoint. + /// The settings. + /// The relative path. + /// The address. + protected static Uri Url(EInvoiceChannelSettings settings, string path) + { + ArgumentNullException.ThrowIfNull(settings); + return new Uri(settings.Endpoint!.TrimEnd('/') + "/" + path.TrimStart('/')); + } + + /// A date of the API, or now. + /// The ISO 8601 text. + /// The time. + protected static DateTimeOffset TimeOf(string? text) => + DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var value) ? value : DateTimeOffset.UtcNow; + + private static string ErrorOf(string text) + { + try + { + using var document = JsonDocument.Parse(text); + foreach (var name in new[] { "error", "message", "detail" }) + { + if (document.RootElement.ValueKind == JsonValueKind.Object && document.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String) + { + return value.GetString()!; + } + } + } + catch (JsonException) + { + } + + return text.Length > 200 ? text[..200] : text; + } + + private HttpClient Client(EInvoiceChannelSettings settings) => + new(handlerFactory is null ? new SocketsHttpHandler() : handlerFactory(settings), disposeHandler: true) { Timeout = TimeSpan.FromMinutes(2) }; +} + +/// +/// Intermediary A: an API key as bearer token; the file is the body of the request. +/// +/// POST {endpoint}/invoices, body the file, header X-File-Name → { "id", "sdiId" }. +/// GET {endpoint}/files → [{ "id", "fileName", "content" (base64), "receivedAt" }]. +/// POST {endpoint}/files/{id}/ack; GET {endpoint}/status. +/// +/// +/// Makes the HTTP handler (tests). +public sealed class IntermediaryATransport(Func? handlerFactory = null) : IntermediaryTransportBase(handlerFactory) +{ + /// The code of the channel. + public const string ChannelCode = "INTA"; + + /// + public override string Code => ChannelCode; + + /// + protected override string? Missing(EInvoiceChannelSettings settings) => + string.IsNullOrWhiteSpace(settings.Endpoint) || string.IsNullOrWhiteSpace(settings.ApiKey) ? "Intermediary A needs the address of the API and the API key." : null; + + /// + protected override HttpRequestMessage SendRequest(EInvoiceChannelSettings settings, EInvoiceOutgoing file) + { + var request = Authorized(settings, HttpMethod.Post, "invoices"); + request.Content = new ByteArrayContent(file.Content); + request.Content.Headers.ContentType = new MediaTypeHeaderValue(file.FileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" : "application/xml"); + request.Headers.Add("X-File-Name", file.FileName); + return request; + } + + /// + protected override (string? MessageId, string? ExchangeId) ReadSendAnswer(string json) + { + var answer = JsonSerializer.Deserialize(json, Json); + return (answer?.Id, answer?.SdiId); + } + + /// + protected override HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "files"); + + /// + protected override IReadOnlyList ReadFiles(string json) => + (JsonSerializer.Deserialize>(json, Json) ?? []) + .Where(f => !string.IsNullOrWhiteSpace(f.Id) && !string.IsNullOrWhiteSpace(f.FileName) && f.Content is not null) + .Select(f => new EInvoiceIncoming(Path.GetFileName(f.FileName!), Convert.FromBase64String(f.Content!), TimeOf(f.ReceivedAt), f.Id!, ChannelCode)) + .ToList(); + + /// + protected override HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key) => + Authorized(settings, HttpMethod.Post, "files/" + Uri.EscapeDataString(key) + "/ack"); + + /// + protected override HttpRequestMessage CheckRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "status"); + + private static HttpRequestMessage Authorized(EInvoiceChannelSettings settings, HttpMethod method, string path) + { + var request = new HttpRequestMessage(method, Url(settings, path)); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", settings.ApiKey); + return request; + } + + private sealed record SendAnswer(string? Id, string? SdiId); + + private sealed record FileItem(string? Id, string? FileName, string? Content, string? ReceivedAt); +} + +/// +/// Intermediary B: user and password with basic authentication; the file travels in JSON. +/// +/// POST {endpoint}/api/v1/send with { "fileName", "content" } → { "uploadId", "identificativoSdi" }. +/// GET {endpoint}/api/v1/inbox → { "items": [{ "key", "name", "data" (base64), "date" }] }. +/// DELETE {endpoint}/api/v1/inbox/{key}; GET {endpoint}/api/v1/ping. +/// +/// +/// Makes the HTTP handler (tests). +public sealed class IntermediaryBTransport(Func? handlerFactory = null) : IntermediaryTransportBase(handlerFactory) +{ + /// The code of the channel. + public const string ChannelCode = "INTB"; + + /// + public override string Code => ChannelCode; + + /// + protected override string? Missing(EInvoiceChannelSettings settings) => + string.IsNullOrWhiteSpace(settings.Endpoint) || string.IsNullOrWhiteSpace(settings.User) || string.IsNullOrEmpty(settings.Password) + ? "Intermediary B needs the address of the API, the user and the password." + : null; + + /// + protected override HttpRequestMessage SendRequest(EInvoiceChannelSettings settings, EInvoiceOutgoing file) + { + var request = Authorized(settings, HttpMethod.Post, "api/v1/send"); + request.Content = new StringContent(JsonSerializer.Serialize(new { fileName = file.FileName, content = Convert.ToBase64String(file.Content) }), Encoding.UTF8, "application/json"); + return request; + } + + /// + protected override (string? MessageId, string? ExchangeId) ReadSendAnswer(string json) + { + var answer = JsonSerializer.Deserialize(json, Json); + return (answer?.UploadId, answer?.IdentificativoSdi); + } + + /// + protected override HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "api/v1/inbox"); + + /// + protected override IReadOnlyList ReadFiles(string json) => + (JsonSerializer.Deserialize(json, Json)?.Items ?? []) + .Where(f => !string.IsNullOrWhiteSpace(f.Key) && !string.IsNullOrWhiteSpace(f.Name) && f.Data is not null) + .Select(f => new EInvoiceIncoming(Path.GetFileName(f.Name!), Convert.FromBase64String(f.Data!), TimeOf(f.Date), f.Key!, ChannelCode)) + .ToList(); + + /// + protected override HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key) => + Authorized(settings, HttpMethod.Delete, "api/v1/inbox/" + Uri.EscapeDataString(key)); + + /// + protected override HttpRequestMessage CheckRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "api/v1/ping"); + + private static HttpRequestMessage Authorized(EInvoiceChannelSettings settings, HttpMethod method, string path) + { + var request = new HttpRequestMessage(method, Url(settings, path)); + request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(settings.User + ":" + settings.Password))); + return request; + } + + private sealed record SendAnswer(string? UploadId, string? IdentificativoSdi); + + private sealed record Inbox(List? Items); + + private sealed record InboxItem(string? Key, string? Name, string? Data, string? Date); +} + +/// The channels of the Italian pack, in the order of the configuration screen (mockup 059). +public sealed class SdiChannels : IEInvoiceChannels +{ + /// Creates the channels. + /// The PEC channel. + /// The SdICoop channel. + /// Intermediary A. + /// Intermediary B. + public SdiChannels(PecSdiTransport? pec = null, SdiCoopTransport? coop = null, IntermediaryATransport? intermediaryA = null, IntermediaryBTransport? intermediaryB = null) + { + All = + [ + new EInvoiceChannel(PecSdiTransport.ChannelCode, "PEC", pec ?? new PecSdiTransport()), + new EInvoiceChannel(SdiCoopTransport.ChannelCode, "SdICoop (web service)", coop ?? new SdiCoopTransport()), + new EInvoiceChannel(IntermediaryATransport.ChannelCode, "Intermediario A (API REST)", intermediaryA ?? new IntermediaryATransport()), + new EInvoiceChannel(IntermediaryBTransport.ChannelCode, "Intermediario B (API REST)", intermediaryB ?? new IntermediaryBTransport()), + ]; + } + + /// + public IReadOnlyList All { get; } + + /// + public EInvoiceChannel? Find(string code) => All.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs b/src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs new file mode 100644 index 0000000..90110be --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs @@ -0,0 +1,276 @@ +using System.Globalization; +using System.Net.Security; +using System.Net.Sockets; +using System.Text.RegularExpressions; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Mail; + +namespace Khaemhat.Fiscal.Italy.Sdi; + +/// +/// The PEC channel to the SDI (SPEC §11.9, issue #76): files go by certified mail to the address of the SDI +/// (sdi01@pec.fatturapa.it the first time, then the sdiNN address the SDI writes from), receipts and +/// supplier invoices are read from the mailbox by IMAP. +/// +/// +/// Only messages whose sender contains fatturapa.it are read: the acceptance and delivery receipts of the +/// PEC provider stay where they are. The files are the .xml and .p7m attachments of the original message +/// (postacert.eml); daticert.xml and the signature of the provider are ignored. +/// With an archive folder, processed messages are moved there and every message of the SDI still in the inbox is +/// read again at the next poll (the services discard what they already have); without it, messages are marked as read +/// and only unread ones are fetched, so a message opened in webmail before the poll is missed: the archive folder is +/// the recommended setting. +/// +/// The clock (date of the messages sent). +/// A custom check of the server certificates (tests only). +public sealed partial class PecSdiTransport(TimeProvider? clock = null, RemoteCertificateValidationCallback? certificateValidation = null) : IEInvoiceTransport +{ + /// The code of the channel. + public const string ChannelCode = "PEC"; + + /// The address of the SDI for the first file. + public const string FirstAddress = "sdi01@pec.fatturapa.it"; + + /// The most messages read in one poll. + public const int MaxMessages = 200; + + private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2); + private readonly TimeProvider _clock = clock ?? TimeProvider.System; + + /// + public string Code => ChannelCode; + + /// + public bool Polls => true; + + /// Whether an address is one the SDI writes from (sdiNN@pec.fatturapa.it). + /// The address, possibly with a display name. + /// The bare address when it is one, otherwise . + public static string? SdiAddress(string? address) + { + var match = SdiAddressPattern().Match(address ?? string.Empty); + return match.Success ? match.Value.ToLowerInvariant() : null; + } + + /// + public async Task SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(file); + if (Missing(settings, smtp: true) is { } missing) + { + return new EInvoiceSendResult(false, null, null, missing); + } + + var to = SdiAddress(settings.ExchangeAddress) ?? settings.ExchangeAddress ?? FirstAddress; + var mediaType = file.FileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" : "application/xml"; + var mail = new OutgoingMail([to], "Invio file " + file.FileName, "File " + file.FileName + (file.Reference is null ? string.Empty : " (" + file.Reference + ")") + ".") + { + Attachments = [new MailAttachment(file.FileName, mediaType, file.Content)], + Reference = file.Reference, + }; + try + { + await new SmtpMailSender(Smtp(settings), _clock).SendAsync(mail, cancellationToken).ConfigureAwait(false); + return new EInvoiceSendResult(true, null, null, null); + } + catch (MailException ex) + { + return new EInvoiceSendResult(false, null, null, ex.Message); + } + } + + /// + public async Task FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + if (Missing(settings, smtp: false) is { } missing) + { + throw new MailException(missing); + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(Timeout); + var token = timeout.Token; + await using var imap = await OpenAsync(settings, token).ConfigureAwait(false); + var criteria = (string.IsNullOrWhiteSpace(settings.ArchiveFolder) ? "UNSEEN " : string.Empty) + "FROM " + ImapClient.Quote("fatturapa.it"); + var uids = (await imap.SearchAsync(criteria, token).ConfigureAwait(false)).Take(MaxMessages).ToList(); + var files = new List(); + var empty = new List(); + string? exchange = null; + foreach (var uid in uids) + { + var message = await imap.FetchAsync(uid, token).ConfigureAwait(false); + if (message is null) + { + continue; + } + + var (found, sender) = Files(message.Content, uid.ToString(CultureInfo.InvariantCulture), _clock.GetUtcNow()); + exchange = SdiAddress(sender) ?? exchange; + if (found.Count == 0) + { + empty.Add(uid); + } + + files.AddRange(found); + } + + // A message of the SDI with no file (rare: a notice) is done at once. + foreach (var uid in empty) + { + await DoneAsync(imap, settings, uid, token).ConfigureAwait(false); + } + + await imap.LogoutAsync(token).ConfigureAwait(false); + var known = SdiAddress(settings.ExchangeAddress); + return new EInvoiceFetchResult(files, uids.Count, exchange is not null && exchange != known ? exchange : null); + } + + /// + public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection messageKeys, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(messageKeys); + var uids = messageKeys.Select(k => long.TryParse(k, NumberStyles.None, CultureInfo.InvariantCulture, out var uid) ? uid : -1).Where(u => u > 0).Distinct().ToList(); + if (uids.Count == 0) + { + return; + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(Timeout); + await using var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false); + foreach (var uid in uids) + { + await DoneAsync(imap, settings, uid, timeout.Token).ConfigureAwait(false); + } + + await imap.LogoutAsync(timeout.Token).ConfigureAwait(false); + } + + /// + public async Task CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + if (Missing(settings, smtp: true) is { } missing) + { + return new EInvoiceChannelCheck(false, missing); + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + try + { + int count; + await using (var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false)) + { + count = (await imap.SearchAsync("FROM " + ImapClient.Quote("fatturapa.it"), timeout.Token).ConfigureAwait(false)).Count; + await imap.LogoutAsync(timeout.Token).ConfigureAwait(false); + } + + using var smtp = new TcpClient(); + await smtp.ConnectAsync(settings.SmtpHost!, settings.SmtpPort, timeout.Token).ConfigureAwait(false); + return new EInvoiceChannelCheck(true, $"IMAP {settings.ImapHost}:{settings.ImapPort}: login OK, {count} SDI messages in the inbox; SMTP {settings.SmtpHost}:{settings.SmtpPort}: reachable."); + } + catch (Exception ex) when (ex is MailException or SocketException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + return new EInvoiceChannelCheck(false, ex.Message); + } + } + + /// + /// The files of the SDI in a message: the .xml and .p7m attachments of the original message of a + /// certified mail (or of the message itself when it is not certified). + /// + /// The raw message. + /// The key of the message. + /// The time used when the message has no date. + /// The files and the sender of the original message. + public static (IReadOnlyList Files, string? Sender) Files(byte[] message, string key, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(message); + var root = MimeParser.Parse(message); + var original = Original(root) ?? root; + var sender = original.Header("from"); + var date = DateTimeOffset.TryParse(Strip(original.Header("date")), CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) ? parsed : now; + var files = original.Attachments() + .Where(a => a.FileName is { } name && IsSdiFile(name)) + .Select(a => new EInvoiceIncoming(Path.GetFileName(a.FileName!), a.Body, date, key, SdiAddress(sender) ?? sender)) + .ToList(); + return (files, sender); + } + + private static bool IsSdiFile(string name) => + (name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase)) + && !name.Equals("daticert.xml", StringComparison.OrdinalIgnoreCase) + && !name.Equals("smime.p7m", StringComparison.OrdinalIgnoreCase); + + // The message enclosed by the PEC provider (postacert.eml), searched in the parts of the envelope. + private static MimePart? Original(MimePart part) + { + if (part.Enclosed is not null) + { + return part.Enclosed; + } + + return part.Parts.Select(Original).FirstOrDefault(p => p is not null); + } + + // "Thu, 12 Nov 2026 10:15:00 +0100 (CET)": the comment is not part of the date. + private static string? Strip(string? date) + { + if (date is null) + { + return null; + } + + var comment = date.IndexOf('(', StringComparison.Ordinal); + return (comment < 0 ? date : date[..comment]).Trim(); + } + + private static string? Missing(EInvoiceChannelSettings settings, bool smtp) + { + if (string.IsNullOrWhiteSpace(settings.ImapHost) || string.IsNullOrWhiteSpace(settings.User) || string.IsNullOrEmpty(settings.Password)) + { + return "The PEC channel needs the IMAP server, the user and the password."; + } + + return smtp && (string.IsNullOrWhiteSpace(settings.SmtpHost) || string.IsNullOrWhiteSpace(settings.Mailbox)) + ? "The PEC channel needs the SMTP server and the address of the mailbox." + : null; + } + + private static SmtpSettings Smtp(EInvoiceChannelSettings settings) => new( + settings.SmtpHost, + settings.SmtpPort, + settings.User, + settings.Password, + settings.Mailbox, + !settings.Tls ? SmtpTransportSecurity.None : settings.SmtpPort == 587 ? SmtpTransportSecurity.StartTls : SmtpTransportSecurity.Ssl); + + private async Task OpenAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken) + { + var imap = await ImapClient.ConnectAsync( + new ImapSettings(settings.ImapHost!, settings.ImapPort, settings.Tls, settings.User!, settings.Password!), cancellationToken, certificateValidation).ConfigureAwait(false); + try + { + await imap.LoginAsync(settings.User!, settings.Password!, cancellationToken).ConfigureAwait(false); + await imap.SelectAsync("INBOX", cancellationToken).ConfigureAwait(false); + return imap; + } + catch + { + await imap.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + private static Task DoneAsync(ImapClient imap, EInvoiceChannelSettings settings, long uid, CancellationToken cancellationToken) => + string.IsNullOrWhiteSpace(settings.ArchiveFolder) + ? imap.AddFlagsAsync(uid, @"\Seen", cancellationToken) + : imap.MoveAsync(uid, settings.ArchiveFolder.Trim(), cancellationToken); + + [GeneratedRegex(@"sdi[0-9]{2}@pec\.fatturapa\.it", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex SdiAddressPattern(); +} diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopPushReader.cs b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopPushReader.cs new file mode 100644 index 0000000..9454536 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopPushReader.cs @@ -0,0 +1,24 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Sdi; + +/// The SdICoop messages the SDI sends to the company, as pushes of the channel SDICOOP (issue #76). +public sealed class SdiCoopPushReader : IEInvoicePushReader +{ + private const string Soap = "text/xml; charset=utf-8"; + + /// + public string Channel => SdiCoopTransport.ChannelCode; + + /// + public EInvoicePush? Read(string? contentType, byte[] body) + { + ArgumentNullException.ThrowIfNull(body); + return SdiCoopMessages.Read(contentType, body) is { } inbound + ? new EInvoicePush(inbound.ExchangeId, inbound.Files, Soap, SdiCoopMessages.Answer(inbound)) + : null; + } + + /// + public (string ContentType, string Body) Refusal() => (Soap, SdiCoopMessages.Answer(null)); +} diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopTransport.cs b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopTransport.cs new file mode 100644 index 0000000..0940bb7 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopTransport.cs @@ -0,0 +1,322 @@ +using System.Globalization; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Mail; + +namespace Khaemhat.Fiscal.Italy.Sdi; + +/// +/// The SdICoop channel (SPEC §11.9, issue #77): files go to the web service SdIRiceviFile of the SDI over SOAP +/// 1.1 with MTOM and the client certificate the Agenzia delle Entrate issues at accreditation; the SDI answers at once +/// with the IdentificativoSdI. Notifications and supplier invoices are pushed by the SDI to the web services of +/// the company (TrasmissioneFatture, RicezioneFatture), read by . +/// +/// Ready but meant to be enabled only after the accreditation of the company (issue #78): the endpoints of the +/// company must be published behind a proxy that checks the certificate of the SDI. +/// Makes the HTTP handler for a channel (tests); by default a handler with the client certificate. +public sealed class SdiCoopTransport(Func? handlerFactory = null) : IEInvoiceTransport +{ + /// The code of the channel. + public const string ChannelCode = "SDICOOP"; + + /// The address of SdIRiceviFile in production. + public const string ProductionEndpoint = "https://servizi.fatturapa.it/ricevi_file"; + + /// The address of SdIRiceviFile in the test environment. + public const string TestEndpoint = "https://testservizi.fatturapa.it/ricevi_file"; + + /// The SOAP action of RiceviFile. + public const string RiceviFileAction = "http://www.fatturapa.it/SdIRiceviFile/RiceviFile"; + + private const string TypesNamespace = "http://www.fatturapa.gov.it/sdi/ws/trasmissione/v1.0/types"; + + /// + public string Code => ChannelCode; + + /// + public bool Polls => false; + + /// The address to send to: the one configured, otherwise the one of the environment. + /// The settings. + /// The address. + public static string EndpointOf(EInvoiceChannelSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + return !string.IsNullOrWhiteSpace(settings.Endpoint) ? settings.Endpoint.Trim() : settings.TestEnvironment ? TestEndpoint : ProductionEndpoint; + } + + /// + public async Task SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(file); + if (settings.Certificate is null && handlerFactory is null) + { + return new EInvoiceSendResult(false, null, null, "The SdICoop channel needs the client certificate issued at accreditation."); + } + + try + { + using var client = Client(settings); + using var request = new HttpRequestMessage(HttpMethod.Post, EndpointOf(settings)) { Content = Mtom(file) }; + request.Headers.Add("SOAPAction", "\"" + RiceviFileAction + "\""); + using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false); + var body = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); + var envelope = SdiCoopMessages.Envelope(response.Content.Headers.ContentType?.ToString(), body); + if (envelope is null) + { + return new EInvoiceSendResult(false, null, null, $"The SDI answered {(int)response.StatusCode} without a SOAP envelope."); + } + + var fault = Find(envelope, "faultstring"); + if (fault is not null) + { + return new EInvoiceSendResult(false, null, null, "SOAP fault: " + fault); + } + + var error = Find(envelope, "Errore"); + var id = Find(envelope, "IdentificativoSdI"); + return error is not null + ? new EInvoiceSendResult(false, id, null, error + " " + ErrorText(error)) + : new EInvoiceSendResult(id is not null, id, id, id is null ? "The answer of the SDI has no IdentificativoSdI." : null); + } + catch (Exception ex) when (ex is HttpRequestException or CryptographicException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested)) + { + return new EInvoiceSendResult(false, null, null, ex.Message); + } + } + + /// + public Task FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) => + Task.FromResult(new EInvoiceFetchResult([], 0, null)); + + /// + public Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection messageKeys, CancellationToken cancellationToken = default) => + Task.CompletedTask; + + /// + public async Task CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(settings); + if (settings.Certificate is null && handlerFactory is null) + { + return new EInvoiceChannelCheck(false, "The SdICoop channel needs the client certificate issued at accreditation."); + } + + try + { + string subject = "(test handler)"; + if (settings.Certificate is not null) + { + using var certificate = X509CertificateLoader.LoadPkcs12(settings.Certificate, settings.CertificatePassword); + subject = certificate.Subject + ", valid until " + certificate.NotAfter.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + if (!certificate.HasPrivateKey) + { + return new EInvoiceChannelCheck(false, "The certificate has no private key."); + } + } + + // An empty request: the service answers with a SOAP fault, which proves the TLS session with the certificate. + using var client = Client(settings); + using var response = await client.GetAsync(EndpointOf(settings) + "?wsdl", cancellationToken).ConfigureAwait(false); + return new EInvoiceChannelCheck(true, $"Certificate {subject}; {EndpointOf(settings)} answered {(int)response.StatusCode}."); + } + catch (Exception ex) when (ex is HttpRequestException or CryptographicException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested)) + { + return new EInvoiceChannelCheck(false, ex.Message); + } + } + + /// The meaning of the error codes of RiceviFile. + /// EI01, EI02 or EI03. + /// The description. + public static string ErrorText(string code) => code switch + { + "EI01" => "(empty file)", + "EI02" => "(service not available)", + "EI03" => "(user not enabled)", + _ => string.Empty, + }; + + // The request as MTOM: the SOAP envelope references the file, sent as a binary part. + private static MultipartContent Mtom(EInvoiceOutgoing file) + { + XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/"; + XNamespace types = TypesNamespace; + XNamespace xop = "http://www.w3.org/2004/08/xop/include"; + var envelope = new XElement( + soap + "Envelope", + new XAttribute(XNamespace.Xmlns + "soapenv", soap), + new XAttribute(XNamespace.Xmlns + "typ", types), + new XElement(soap + "Header"), + new XElement( + soap + "Body", + new XElement( + types + "fileSdIAccoglienza", + new XElement("NomeFile", file.FileName), + new XElement("File", new XElement(xop + "Include", new XAttribute(XNamespace.Xmlns + "xop", xop), new XAttribute("href", "cid:file@khaemhat")))))); + var content = new MultipartContent("related", "khaemhat-" + Guid.NewGuid().ToString("N")); + content.Headers.ContentType!.Parameters.Add(new NameValueHeaderValue("type", "\"application/xop+xml\"")); + content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("start", "\"\"")); + content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("start-info", "\"text/xml\"")); + + var root = new ByteArrayContent(Encoding.UTF8.GetBytes(envelope.ToString(SaveOptions.DisableFormatting))); + root.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xop+xml; charset=UTF-8; type=\"text/xml\""); + root.Headers.Add("Content-Transfer-Encoding", "8bit"); + root.Headers.Add("Content-ID", ""); + content.Add(root); + + var binary = new ByteArrayContent(file.Content); + binary.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + binary.Headers.Add("Content-Transfer-Encoding", "binary"); + binary.Headers.Add("Content-ID", ""); + content.Add(binary); + return content; + } + + private static string? Find(XElement root, string localName) => + root.Descendants().FirstOrDefault(e => e.Name.LocalName == localName)?.Value.Trim() is { Length: > 0 } value ? value : null; + + private HttpClient Client(EInvoiceChannelSettings settings) + { + if (handlerFactory is not null) + { + return new HttpClient(handlerFactory(settings), disposeHandler: true) { Timeout = TimeSpan.FromMinutes(2) }; + } + + var handler = new SocketsHttpHandler(); + handler.SslOptions.ClientCertificates = [X509CertificateLoader.LoadPkcs12(settings.Certificate!, settings.CertificatePassword)]; + return new HttpClient(handler, disposeHandler: true) { Timeout = TimeSpan.FromMinutes(2) }; + } +} + +/// A file pushed by the SDI to the web services of the company. +/// The SOAP operation (RicevutaConsegna, RiceviFatture, …). +/// The IdentificativoSdI. +/// The files: the notification, or the invoice and its metadata. +public sealed record SdiCoopInbound(string Operation, string? ExchangeId, IReadOnlyList<(string FileName, byte[] Content)> Files); + +/// +/// Reads the SOAP messages the SDI sends to the company (TrasmissioneFatture: RicevutaConsegna, +/// NotificaMancataConsegna, NotificaScarto, NotificaEsito, NotificaDecorrenzaTermini, AttestazioneTrasmissioneFattura; +/// RicezioneFatture: RiceviFatture, NotificaDecorrenzaTermini) and writes the answers. +/// +public static class SdiCoopMessages +{ + /// The SOAP envelope of a body, plain or MTOM, with the binary parts put back in place of the references. + /// The content type of the HTTP message. + /// The body. + /// The envelope, or when the body is not SOAP. + public static XElement? Envelope(string? contentType, byte[] body) + { + ArgumentNullException.ThrowIfNull(body); + var parts = new Dictionary(StringComparer.OrdinalIgnoreCase); + var xml = body; + if (contentType is not null && contentType.Contains("multipart/", StringComparison.OrdinalIgnoreCase)) + { + var message = MimeParser.Parse([.. Encoding.ASCII.GetBytes("Content-Type: " + contentType + "\r\n\r\n"), .. body]); + if (message.Parts.Count == 0) + { + return null; + } + + xml = message.Parts[0].Body; + foreach (var part in message.Parts.Skip(1)) + { + if (part.Header("content-id") is { } id) + { + parts[id.Trim('<', '>', ' ')] = part.Body; + } + } + } + + XElement root; + try + { + var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; + using var reader = XmlReader.Create(new MemoryStream(xml), settings); + root = XDocument.Load(reader).Root!; + } + catch (XmlException) + { + return null; + } + + if (root.Name.LocalName != "Envelope") + { + return null; + } + + // xop:Include href="cid:..." becomes the base64 of the part, as if the file had been sent inline. + foreach (var include in root.Descendants().Where(e => e.Name.LocalName == "Include").ToList()) + { + var href = (string?)include.Attribute("href") ?? string.Empty; + var id = Uri.UnescapeDataString(href.StartsWith("cid:", StringComparison.OrdinalIgnoreCase) ? href[4..] : href); + if (parts.TryGetValue(id, out var bytes) && include.Parent is { } parent) + { + include.Remove(); + parent.Value = Convert.ToBase64String(bytes); + } + } + + return root; + } + + /// Reads a message of the SDI. + /// The content type of the HTTP message. + /// The body. + /// The files, or when the message is not one of the SDI. + public static SdiCoopInbound? Read(string? contentType, byte[] body) + { + var envelope = Envelope(contentType, body); + var request = envelope?.Elements().FirstOrDefault(e => e.Name.LocalName == "Body")?.Elements().FirstOrDefault(); + if (request is null) + { + return null; + } + + string? Text(string name) => request.Elements().FirstOrDefault(e => e.Name.LocalName == name)?.Value.Trim(); + byte[]? Bytes(string name) => Text(name) is { Length: > 0 } text ? MimeParser.Base64(Encoding.ASCII.GetBytes(text)) : null; + + var files = new List<(string, byte[])>(); + if (Text("NomeFile") is { Length: > 0 } name && Bytes("File") is { } file) + { + files.Add((Path.GetFileName(name), file)); + } + + if (Text("NomeFileMetadati") is { Length: > 0 } metadataName && Bytes("Metadati") is { } metadata) + { + files.Add((Path.GetFileName(metadataName), metadata)); + } + + var operation = request.Name.LocalName switch + { + "fileSdIConMetadati" => "RiceviFatture", + "fileSdI" => "Notifica", + _ => request.Name.LocalName, + }; + return files.Count == 0 ? null : new SdiCoopInbound(operation, Text("IdentificativoSdI"), files); + } + + /// The answer to a message of the SDI: empty, or esito ER01 for RiceviFatture. + /// The message, or when it could not be read. + /// The SOAP envelope (text/xml). + public static string Answer(SdiCoopInbound? inbound) + { + const string Soap = "http://schemas.xmlsoap.org/soap/envelope/"; + if (inbound is null) + { + return $"soapenv:ClientNot a message of the SDI."; + } + + var body = inbound.Operation == "RiceviFatture" + ? "ER01" + : string.Empty; + return $"{body}"; + } +} diff --git a/src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs b/src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs new file mode 100644 index 0000000..0983ab5 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs @@ -0,0 +1,120 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Linq; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Reads the notifications of the SDI (MessaggiTypes v1.0, SPEC §11.9, issue #75): delivery receipt (RC), +/// rejection (NS), failed delivery (MC), outcome of a public administration (NE, EC01/EC02), terms elapsed (DT), +/// transmission certificate (AT), metadata of a received invoice (MT) and rejection of an outcome (SE). +/// +/// +/// Elements are matched by local name, whatever the prefix; the XAdES signature of the SDI is not checked (the file +/// arrives from the channel the company trusts). The name of a notification is the name of the invoice file followed by +/// the code and a progressive (IT01234567890_00A1Z_RC_001.xml); when the root element is clear the name is not +/// needed. +/// +public sealed partial class SdiReceiptReader : IEInvoiceReceiptReader +{ + private static readonly Dictionary Roots = new(StringComparer.Ordinal) + { + ["RicevutaConsegna"] = (EInvoiceReceiptKind.Delivered, "RC"), + ["NotificaScarto"] = (EInvoiceReceiptKind.Rejected, "NS"), + ["NotificaMancataConsegna"] = (EInvoiceReceiptKind.NotDelivered, "MC"), + ["NotificaEsito"] = (EInvoiceReceiptKind.Outcome, "NE"), + ["NotificaDecorrenzaTermini"] = (EInvoiceReceiptKind.TermsElapsed, "DT"), + ["AttestazioneTrasmissioneFattura"] = (EInvoiceReceiptKind.Undeliverable, "AT"), + ["FileMetadati"] = (EInvoiceReceiptKind.Metadata, "MT"), + ["ScartoEsitoCommittente"] = (EInvoiceReceiptKind.OutcomeRejected, "SE"), + }; + + /// The code of a notification in a file name (..._RC_001.xml), or . + /// The name. + /// The code. + public static string? CodeOfName(string fileName) + { + var match = NamePattern().Match(Path.GetFileName(fileName ?? string.Empty)); + return match.Success ? match.Groups["code"].Value : null; + } + + /// + public bool IsReceipt(string fileName, ReadOnlySpan content) + { + if (CodeOfName(fileName) is not null) + { + return true; + } + + var head = Encoding.UTF8.GetString(content[..Math.Min(content.Length, 2048)]); + return Roots.Keys.Any(root => head.Contains(":" + root, StringComparison.Ordinal) || head.Contains("<" + root, StringComparison.Ordinal)); + } + + /// + public EInvoiceReceipt Read(string fileName, byte[] content) + { + ArgumentNullException.ThrowIfNull(fileName); + ArgumentNullException.ThrowIfNull(content); + XElement root; + try + { + var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreComments = true }; + using var reader = XmlReader.Create(new MemoryStream(content), settings); + root = XDocument.Load(reader).Root ?? throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The notification has no root element."); + } + catch (XmlException ex) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The notification is not well formed XML: " + ex.Message, ex); + } + + if (!Roots.TryGetValue(root.Name.LocalName, out var kind)) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotInvoice, $"The XML is a '{root.Name.LocalName}', not a notification of the SDI."); + } + + var outcome = El(root, "EsitoCommittente"); + var errors = Els(El(root, "ListaErrori"), "Errore") + .Select(e => new EInvoiceReceiptError(Text(e, "Codice") ?? string.Empty, Text(e, "Descrizione") ?? string.Empty, Text(e, "Suggerimento"))) + .ToList(); + if (kind.Kind == EInvoiceReceiptKind.OutcomeRejected && Text(root, "Scarto") is { } rejection) + { + errors.Add(new EInvoiceReceiptError(rejection, Text(root, "Descrizione") ?? rejection, null)); + } + + return new EInvoiceReceipt( + kind.Kind, + kind.Code, + Path.GetFileName(fileName), + Text(root, "NomeFile"), + Text(root, "IdentificativoSdI") ?? Text(outcome, "IdentificativoSdI"), + Time(Text(root, "DataOraRicezione")), + Time(Text(root, "DataOraConsegna")), + Text(outcome, "Esito"), + Text(outcome, "Descrizione") ?? Text(root, "Descrizione") ?? Text(root, "Note"), + errors, + Text(root, "MessageId"), + Text(root, "CodiceDestinatario"), + content); + } + + private static DateTimeOffset? Time(string? text) => + text is not null && DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var value) ? value : null; + + private static XElement? El(XElement? parent, string localName) => + parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName); + + private static IEnumerable Els(XElement? parent, string localName) => + parent is null ? [] : parent.Elements().Where(e => e.Name.LocalName == localName); + + private static string? Text(XElement? parent, string localName) + { + var value = El(parent, localName)?.Value.Trim(); + return string.IsNullOrEmpty(value) ? null : value; + } + + [GeneratedRegex(@"_(?RC|NS|MC|NE|DT|AT|MT|SE)_[0-9A-Za-z]{1,3}\.xml$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex NamePattern(); +} diff --git a/src/Khaemhat.Infrastructure/Files/PdfWriter.cs b/src/Khaemhat.Infrastructure/Files/PdfWriter.cs index f310170..3ec5255 100644 --- a/src/Khaemhat.Infrastructure/Files/PdfWriter.cs +++ b/src/Khaemhat.Infrastructure/Files/PdfWriter.cs @@ -418,6 +418,7 @@ public sealed class PdfWriter : IAsyncDisposable private readonly List _offsets = [0, -1, -1, -1]; private readonly List _pageObjects = []; private readonly Dictionary _fontObjects = []; + private readonly List<(string Name, int Spec)> _attachments = []; private long _flushed; private int _images; private PdfPage? _page; @@ -483,6 +484,45 @@ public sealed class PdfWriter : IAsyncDisposable return new PdfImage(number, "Im" + _images.ToString(CultureInfo.InvariantCulture), info); } + /// + /// Embeds a file in the document, as PDF/A-3 does for the XML of an e-invoice: an embedded file stream, its file + /// specification with the relationship to the document (/AFRelationship), listed in the names of the catalogue + /// and in its associated files (/AF). Readers show it among the attachments. + /// + /// This gives the structure of PDF/A-3 for attachments; the document still uses the standard fonts without + /// embedding them, so it does not claim PDF/A conformance. + /// The name of the file. + /// The media type, such as application/xml. + /// The file. + /// What it is. + /// The relationship: Source, Data, Alternative, Supplement or Unspecified. + public void AddAttachment(string fileName, string mediaType, ReadOnlySpan content, string? description = null, string relationship = "Alternative") + { + ObjectDisposedException.ThrowIf(_closed, this); + ArgumentException.ThrowIfNullOrWhiteSpace(fileName); + ArgumentException.ThrowIfNullOrWhiteSpace(mediaType); + if (relationship is not ("Source" or "Data" or "Alternative" or "Supplement" or "Unspecified")) + { + throw new ArgumentOutOfRangeException(nameof(relationship), relationship, "Not a relationship of PDF/A-3."); + } + + var created = PdfDate(_info.CreationDate ?? DateTimeOffset.UtcNow); + var length = content.Length.ToString(CultureInfo.InvariantCulture); + var stream = Allocate(); + BeginObject(stream); + Ascii("<< /Type /EmbeddedFile /Subtype /" + mediaType.Trim().Replace("/", "#2F", StringComparison.Ordinal) + " /Length " + length + + " /Params << /Size " + length + " /ModDate (" + created + ") >> >>\nstream\n"); + _buffer.Write(content); + Ascii("\nendstream\nendobj\n"); + + var spec = Allocate(); + BeginObject(spec); + Ascii("<< /Type /Filespec /F " + TextString(fileName) + " /UF " + TextString(fileName) + + (string.IsNullOrWhiteSpace(description) ? string.Empty : " /Desc " + TextString(description)) + + " /AFRelationship /" + relationship + " /EF << /F " + Ref(stream) + " /UF " + Ref(stream) + " >> >>\nendobj\n"); + _attachments.Add((fileName, spec)); + } + /// Writes what is buffered to the output. /// Cancellation. /// A task. @@ -527,7 +567,11 @@ public sealed class PdfWriter : IAsyncDisposable Ascii("<< /Type /Pages /Kids [" + string.Join(' ', _pageObjects.Select(p => Ref(p))) + "] /Count " + _pageObjects.Count.ToString(CultureInfo.InvariantCulture) + " >>\nendobj\n"); BeginObject(CatalogObject); - Ascii("<< /Type /Catalog /Pages " + Ref(PagesObject) + " >>\nendobj\n"); + var attachments = _attachments.Count == 0 + ? string.Empty + : " /Names << /EmbeddedFiles << /Names [" + string.Join(' ', _attachments.OrderBy(a => a.Name, StringComparer.Ordinal).Select(a => TextString(a.Name) + " " + Ref(a.Spec))) + + "] >> >> /AF [" + string.Join(' ', _attachments.Select(a => Ref(a.Spec))) + "] /PageMode /UseAttachments"; + Ascii("<< /Type /Catalog /Pages " + Ref(PagesObject) + attachments + " >>\nendobj\n"); BeginObject(InfoObject); Ascii("<< " + InfoEntries() + ">>\nendobj\n"); diff --git a/src/Khaemhat.Infrastructure/Mail/ImapClient.cs b/src/Khaemhat.Infrastructure/Mail/ImapClient.cs new file mode 100644 index 0000000..51de0b1 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Mail/ImapClient.cs @@ -0,0 +1,431 @@ +using System.Globalization; +using System.Net.Security; +using System.Net.Sockets; +using System.Text; +using System.Text.RegularExpressions; + +namespace Khaemhat.Infrastructure.Mail; + +/// The IMAP server of a mailbox (for the PEC of the SDI: implicit TLS on port 993). +/// The host. +/// The port. +/// Whether the connection starts with TLS (port 993); only for tests and LAN servers. +/// The user. +/// The password. +public sealed record ImapSettings(string Host, int Port, bool Tls, string User, string Password) +{ + /// The server without the credentials. + /// Host and port. + public override string ToString() => $"{Host}:{Port}" + (Tls ? " (TLS)" : string.Empty); +} + +/// A message fetched from a mailbox. +/// The unique identifier in the mailbox. +/// The raw message (RFC 5322). +public sealed record ImapMessage(long Uid, byte[] Content); + +/// +/// An IMAP4rev1 client (RFC 3501) written in house for the PEC channel of the SDI (SPEC §11.9, issue #76): connect with +/// implicit TLS, LOGIN, SELECT, UID SEARCH, UID FETCH BODY.PEEK[] (message read without +/// marking it), UID STORE, UID MOVE or UID COPY + \Deleted + EXPUNGE to archive, +/// CREATE when the archive folder is missing, LOGOUT. +/// +/// One command at a time, no IDLE, no pipelining. Mailbox names must be ASCII (modified UTF-7 is not written). +/// Strings that are not plain ASCII (a password with accents) are sent as literals. +public sealed partial class ImapClient : IAsyncDisposable +{ + private const int MaxLiteral = 64 * 1024 * 1024; + private const int MaxLine = 1024 * 1024; + + private readonly TcpClient _client; + private readonly Stream _stream; + private readonly byte[] _buffer = new byte[16384]; + private int _start; + private int _end; + private int _tag; + + private ImapClient(TcpClient client, Stream stream) + { + _client = client; + _stream = stream; + } + + /// The capabilities the server announced, in upper case. + public IReadOnlySet Capabilities { get; private set; } = new HashSet(StringComparer.Ordinal); + + /// Connects and reads the greeting. + /// The server. + /// Cancellation. + /// A custom certificate check (tests); the system check when . + /// The client, not yet logged in. + public static async Task ConnectAsync(ImapSettings settings, CancellationToken cancellationToken, RemoteCertificateValidationCallback? certificateValidation = null) + { + ArgumentNullException.ThrowIfNull(settings); + var client = new TcpClient(); + try + { + await client.ConnectAsync(settings.Host, settings.Port, cancellationToken).ConfigureAwait(false); + Stream stream = client.GetStream(); + if (settings.Tls) + { + var tls = new SslStream(stream, leaveInnerStreamOpen: false); + await tls.AuthenticateAsClientAsync( + new SslClientAuthenticationOptions { TargetHost = settings.Host, RemoteCertificateValidationCallback = certificateValidation }, + cancellationToken).ConfigureAwait(false); + stream = tls; + } + + var imap = new ImapClient(client, stream); + var greeting = await imap.ReadUntaggedAsync(cancellationToken).ConfigureAwait(false); + if (!greeting.Text.StartsWith("* OK", StringComparison.OrdinalIgnoreCase) && !greeting.Text.StartsWith("* PREAUTH", StringComparison.OrdinalIgnoreCase)) + { + throw new MailException("The IMAP server " + settings + " refused the connection: " + greeting.Text); + } + + return imap; + } + catch (Exception ex) when (ex is SocketException or IOException or System.Security.Authentication.AuthenticationException) + { + client.Dispose(); + throw new MailException("The IMAP server " + settings + " could not be reached: " + ex.Message, ex); + } + catch + { + client.Dispose(); + throw; + } + } + + /// Logs in with user and password and reads the capabilities. + /// The user. + /// The password. + /// Cancellation. + /// A task. + public async Task LoginAsync(string user, string password, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(password); + await CapabilityAsync(cancellationToken).ConfigureAwait(false); + if (Capabilities.Contains("LOGINDISABLED")) + { + throw new MailException("The IMAP server does not accept LOGIN on this connection: use TLS (port 993)."); + } + + var reply = await SendAsync(["LOGIN ", AString(user), " ", AString(password)], cancellationToken, "LOGIN ***").ConfigureAwait(false); + Ensure(reply, "LOGIN ***"); + await CapabilityAsync(cancellationToken).ConfigureAwait(false); + } + + /// Selects a mailbox. + /// The name (ASCII), such as INBOX. + /// Cancellation. + /// The number of messages in the mailbox. + public async Task SelectAsync(string mailbox, CancellationToken cancellationToken) + { + var reply = await SendAsync(["SELECT ", Quote(mailbox)], cancellationToken).ConfigureAwait(false); + Ensure(reply, "SELECT " + mailbox); + foreach (var line in reply.Untagged) + { + var match = ExistsPattern().Match(line.Text); + if (match.Success) + { + return int.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture); + } + } + + return 0; + } + + /// Searches the selected mailbox. + /// The criteria, already in IMAP syntax (UNSEEN FROM "fatturapa.it"); see . + /// Cancellation. + /// The unique identifiers, ascending. + public async Task> SearchAsync(string criteria, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrWhiteSpace(criteria); + var reply = await SendAsync(["UID SEARCH " + criteria], cancellationToken).ConfigureAwait(false); + Ensure(reply, "UID SEARCH"); + var uids = new SortedSet(); + foreach (var line in reply.Untagged.Where(l => l.Text.StartsWith("* SEARCH", StringComparison.OrdinalIgnoreCase))) + { + foreach (var part in line.Text[8..].Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + if (long.TryParse(part, NumberStyles.None, CultureInfo.InvariantCulture, out var uid)) + { + uids.Add(uid); + } + } + } + + return [.. uids]; + } + + /// Fetches a whole message without marking it as read. + /// The unique identifier. + /// Cancellation. + /// The message, or when it no longer exists. + public async Task FetchAsync(long uid, CancellationToken cancellationToken) + { + var reply = await SendAsync([$"UID FETCH {uid.ToString(CultureInfo.InvariantCulture)} (UID BODY.PEEK[])"], cancellationToken).ConfigureAwait(false); + Ensure(reply, "UID FETCH"); + var fetch = reply.Untagged.FirstOrDefault(l => l.Text.Contains(" FETCH ", StringComparison.OrdinalIgnoreCase) && l.Literals.Count > 0); + return fetch is null ? null : new ImapMessage(uid, fetch.Literals[0]); + } + + /// Adds flags to a message. + /// The unique identifier. + /// The flags, such as \Seen. + /// Cancellation. + /// A task. + public async Task AddFlagsAsync(long uid, string flags, CancellationToken cancellationToken) + { + var reply = await SendAsync([$"UID STORE {uid.ToString(CultureInfo.InvariantCulture)} +FLAGS.SILENT ({flags})"], cancellationToken).ConfigureAwait(false); + Ensure(reply, "UID STORE"); + } + + /// Moves a message to another mailbox, creating it when missing. + /// The unique identifier. + /// The target (ASCII). + /// Cancellation. + /// A task. + public async Task MoveAsync(long uid, string mailbox, CancellationToken cancellationToken) + { + var id = uid.ToString(CultureInfo.InvariantCulture); + var command = Capabilities.Contains("MOVE") ? "UID MOVE " : "UID COPY "; + var reply = await SendAsync([command + id + " ", Quote(mailbox)], cancellationToken).ConfigureAwait(false); + if (reply.Status == "NO" && reply.Text.Contains("[TRYCREATE]", StringComparison.OrdinalIgnoreCase)) + { + Ensure(await SendAsync(["CREATE ", Quote(mailbox)], cancellationToken).ConfigureAwait(false), "CREATE " + mailbox); + reply = await SendAsync([command + id + " ", Quote(mailbox)], cancellationToken).ConfigureAwait(false); + } + + Ensure(reply, command.Trim() + " " + mailbox); + if (!Capabilities.Contains("MOVE")) + { + await AddFlagsAsync(uid, @"\Deleted", cancellationToken).ConfigureAwait(false); + var expunge = Capabilities.Contains("UIDPLUS") ? "UID EXPUNGE " + id : "EXPUNGE"; + Ensure(await SendAsync([expunge], cancellationToken).ConfigureAwait(false), expunge); + } + } + + /// Logs out (the server closes the connection). + /// Cancellation. + /// A task. + public async Task LogoutAsync(CancellationToken cancellationToken) + { + try + { + await SendAsync(["LOGOUT"], cancellationToken).ConfigureAwait(false); + } + catch (MailException) + { + // The server may close before the tagged reply: the session is over either way. + } + } + + /// + public async ValueTask DisposeAsync() + { + await _stream.DisposeAsync().ConfigureAwait(false); + _client.Dispose(); + } + + /// A string in IMAP quoted form (backslash and double quote escaped). + /// The text (ASCII, no line breaks). + /// The quoted string. + public static string Quote(string value) + { + ArgumentNullException.ThrowIfNull(value); + if (value.Any(c => c > 126 || c < 32)) + { + throw new MailException("IMAP names and search texts must be printable ASCII: '" + value + "'."); + } + + return "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + "\""; + } + + /// A date in the form of the search keys (SINCE 1-Nov-2026). + /// The date. + /// The text. + public static string SearchDate(DateOnly date) => date.ToString("d-MMM-yyyy", CultureInfo.InvariantCulture); + + // A string as quoted text when it is plain ASCII, otherwise as a literal of its UTF-8 bytes. + private static object AString(string value) => + value.All(c => c is >= ' ' and <= '~') ? Quote(value) : Encoding.UTF8.GetBytes(value); + + private static void Ensure(Reply reply, string shown) + { + if (reply.Status != "OK") + { + throw new MailException($"The IMAP server answered {reply.Status} {reply.Text} to {shown}."); + } + } + + private async Task CapabilityAsync(CancellationToken cancellationToken) + { + var reply = await SendAsync(["CAPABILITY"], cancellationToken).ConfigureAwait(false); + Ensure(reply, "CAPABILITY"); + var line = reply.Untagged.FirstOrDefault(l => l.Text.StartsWith("* CAPABILITY", StringComparison.OrdinalIgnoreCase)); + if (line is not null) + { + Capabilities = line.Text[12..].Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(c => c.ToUpperInvariant()).ToHashSet(StringComparer.Ordinal); + } + } + + // Sends a command made of text parts and literals (byte arrays, sent after the server's "+" continuation) and reads + // the untagged lines up to the tagged reply. + private async Task SendAsync(IReadOnlyList parts, CancellationToken cancellationToken, string? shown = null) + { + var tag = "K" + (++_tag).ToString("D4", CultureInfo.InvariantCulture); + var pending = new StringBuilder(tag).Append(' '); + foreach (var part in parts) + { + if (part is byte[] literal) + { + pending.Append('{').Append(literal.Length.ToString(CultureInfo.InvariantCulture)).Append("}\r\n"); + await WriteAsync(pending.ToString(), cancellationToken).ConfigureAwait(false); + pending.Clear(); + var go = await ReadUntaggedAsync(cancellationToken).ConfigureAwait(false); + if (!go.Text.StartsWith('+')) + { + throw new MailException($"The IMAP server refused a literal in {shown ?? parts[0]}: {go.Text}"); + } + + await _stream.WriteAsync(literal, cancellationToken).ConfigureAwait(false); + } + else + { + pending.Append((string)part); + } + } + + pending.Append("\r\n"); + await WriteAsync(pending.ToString(), cancellationToken).ConfigureAwait(false); + + var untagged = new List(); + while (true) + { + var response = await ReadUntaggedAsync(cancellationToken).ConfigureAwait(false); + if (response.Text.StartsWith(tag + " ", StringComparison.Ordinal)) + { + var rest = response.Text[(tag.Length + 1)..]; + var space = rest.IndexOf(' ', StringComparison.Ordinal); + var status = (space < 0 ? rest : rest[..space]).ToUpperInvariant(); + return new Reply(status, space < 0 ? string.Empty : rest[(space + 1)..], untagged); + } + + untagged.Add(response); + } + } + + private async Task WriteAsync(string text, CancellationToken cancellationToken) + { + await _stream.WriteAsync(Encoding.UTF8.GetBytes(text), cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + // One response: a line, and when it ends with {n} the n bytes that follow and the rest of the line, repeated. + private async Task ReadUntaggedAsync(CancellationToken cancellationToken) + { + var text = new StringBuilder(); + var literals = new List(); + while (true) + { + var line = await ReadLineAsync(cancellationToken).ConfigureAwait(false); + text.Append(line); + var match = LiteralPattern().Match(line); + if (!match.Success) + { + return new Response(text.ToString(), literals); + } + + var length = long.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture); + if (length > MaxLiteral) + { + throw new MailException($"The IMAP server sent a literal of {length} bytes, more than {MaxLiteral}."); + } + + literals.Add(await ReadExactAsync((int)length, cancellationToken).ConfigureAwait(false)); + } + } + + private async Task ReadLineAsync(CancellationToken cancellationToken) + { + using var line = new MemoryStream(); + while (true) + { + if (_start == _end) + { + await FillAsync(cancellationToken).ConfigureAwait(false); + } + + var index = Array.IndexOf(_buffer, (byte)'\n', _start, _end - _start); + if (index < 0) + { + line.Write(_buffer, _start, _end - _start); + _start = _end; + if (line.Length > MaxLine) + { + throw new MailException("The IMAP server sent a line longer than " + MaxLine + " bytes."); + } + + continue; + } + + line.Write(_buffer, _start, index - _start); + _start = index + 1; + return Encoding.UTF8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r'); + } + } + + private async Task ReadExactAsync(int length, CancellationToken cancellationToken) + { + var result = new byte[length]; + var written = 0; + while (written < length) + { + if (_start == _end) + { + await FillAsync(cancellationToken).ConfigureAwait(false); + } + + var take = Math.Min(length - written, _end - _start); + Array.Copy(_buffer, _start, result, written, take); + _start += take; + written += take; + } + + return result; + } + + private async Task FillAsync(CancellationToken cancellationToken) + { + int read; + try + { + read = await _stream.ReadAsync(_buffer, cancellationToken).ConfigureAwait(false); + } + catch (IOException ex) + { + throw new MailException("The IMAP connection failed: " + ex.Message, ex); + } + + if (read == 0) + { + throw new MailException("The IMAP server closed the connection."); + } + + _start = 0; + _end = read; + } + + [GeneratedRegex(@"\{(?[0-9]{1,10})\+?\}$", RegexOptions.CultureInvariant)] + private static partial Regex LiteralPattern(); + + [GeneratedRegex(@"^\* (?[0-9]+) EXISTS", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex ExistsPattern(); + + private sealed record Response(string Text, IReadOnlyList Literals); + + private sealed record Reply(string Status, string Text, IReadOnlyList Untagged); +} diff --git a/src/Khaemhat.Infrastructure/Mail/MimeParser.cs b/src/Khaemhat.Infrastructure/Mail/MimeParser.cs new file mode 100644 index 0000000..d297e0e --- /dev/null +++ b/src/Khaemhat.Infrastructure/Mail/MimeParser.cs @@ -0,0 +1,541 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Infrastructure.Mail; + +/// A part of a MIME message: headers and body, or the parts of a multipart, or an enclosed message. +public sealed class MimePart +{ + /// The headers, names in lower case; repeated headers keep the first value. + public required IReadOnlyDictionary Headers { get; init; } + + /// The media type in lower case, such as multipart/mixed or application/xml. + public required string MediaType { get; init; } + + /// The parameters of Content-Type (boundary, charset, name), names in lower case. + public required IReadOnlyDictionary TypeParameters { get; init; } + + /// The decoded body (transfer encoding removed); empty for a multipart. + public byte[] Body { get; init; } = []; + + /// The parts of a multipart. + public IReadOnlyList Parts { get; init; } = []; + + /// The message enclosed in a message/rfc822 part. + public MimePart? Enclosed { get; init; } + + /// The file name, from Content-Disposition or Content-Type, decoded. + public string? FileName { get; init; } + + /// A header by name. + /// The name, any case. + /// The value, decoded, or . + public string? Header(string name) => Headers.TryGetValue(name.ToLowerInvariant(), out var value) ? value : null; + + /// The body as text, in its charset (UTF-8 when not declared). + /// The text. + public string Text() => MimeParser.CharsetOf(TypeParameters.TryGetValue("charset", out var charset) ? charset : null).GetString(Body); + + /// Every part with a file name, also inside multiparts and enclosed messages, in order. + /// The attachments. + public IEnumerable Attachments() + { + if (FileName is not null && Parts.Count == 0 && Enclosed is null) + { + yield return this; + } + + foreach (var part in Parts) + { + foreach (var attachment in part.Attachments()) + { + yield return attachment; + } + } + + if (Enclosed is not null) + { + foreach (var attachment in Enclosed.Attachments()) + { + yield return attachment; + } + } + } +} + +/// +/// Reads MIME messages (RFC 5322, 2045-2047, 2231) written in house for the PEC channel of the SDI (SPEC §11.9, +/// issue #76): headers with folded lines and encoded words, multiparts at any depth, enclosed messages +/// (message/rfc822, the postacert.eml of a certified mail), bodies in base64, quoted-printable, 7bit and +/// 8bit, file names in filename, filename* and name. +/// +/// Malformed input does not throw: a part whose boundary never closes ends with the message, a broken base64 +/// body is decoded as far as it goes. Nesting is limited to 10 levels. +public static class MimeParser +{ + private const int MaxDepth = 10; + + /// Parses a message. + /// The raw message. + /// The root part. + public static MimePart Parse(byte[] message) + { + ArgumentNullException.ThrowIfNull(message); + return ParsePart(message, 0, message.Length, 0); + } + + /// The encoding of a charset name, UTF-8 when unknown. + /// The name. + /// The encoding. + public static Encoding CharsetOf(string? charset) + { + switch (charset?.Trim().Trim('"').ToLowerInvariant()) + { + case null or "" or "utf-8" or "utf8" or "us-ascii" or "ascii": + return new UTF8Encoding(false); + case "iso-8859-1" or "latin1": + return Encoding.Latin1; + case "windows-1252" or "cp1252": + return CodePagesEncodingProvider.Instance.GetEncoding(1252) ?? Encoding.Latin1; + case "iso-8859-15": + return CodePagesEncodingProvider.Instance.GetEncoding(28605) ?? Encoding.Latin1; + default: + try + { + return Encoding.GetEncoding(charset!.Trim().Trim('"')); + } + catch (ArgumentException) + { + return new UTF8Encoding(false); + } + } + } + + /// Decodes the encoded words of a header (=?utf-8?B?...?=, =?iso-8859-1?Q?...?=). + /// The raw value. + /// The text. + public static string DecodeHeader(string value) + { + ArgumentNullException.ThrowIfNull(value); + var text = new StringBuilder(); + var position = 0; + var lastWasEncoded = false; + while (position < value.Length) + { + var start = value.IndexOf("=?", position, StringComparison.Ordinal); + var decoded = start < 0 ? null : TryDecodeWord(value, start, out var end, out var word) ? (end, word) : ((int, string)?)null; + if (decoded is null) + { + var next = start < 0 ? value.Length : start + 2; + text.Append(value, position, next - position); + position = next; + lastWasEncoded = false; + continue; + } + + // White space between two encoded words is not part of the text (RFC 2047 §6.2). + var between = value[position..start]; + if (!(lastWasEncoded && string.IsNullOrWhiteSpace(between))) + { + text.Append(between); + } + + text.Append(decoded.Value.Item2); + position = decoded.Value.Item1; + lastWasEncoded = true; + } + + return text.ToString(); + } + + private static bool TryDecodeWord(string value, int start, out int end, out string word) + { + end = start; + word = string.Empty; + var q1 = value.IndexOf('?', start + 2); + var q2 = q1 < 0 ? -1 : value.IndexOf('?', q1 + 1); + var close = q2 < 0 ? -1 : value.IndexOf("?=", q2 + 1, StringComparison.Ordinal); + if (close < 0) + { + return false; + } + + var charset = value[(start + 2)..q1]; + var star = charset.IndexOf('*', StringComparison.Ordinal); + if (star >= 0) + { + charset = charset[..star]; + } + + var mode = value[(q1 + 1)..q2].ToUpperInvariant(); + var payload = value[(q2 + 1)..close]; + byte[] bytes; + if (mode == "B") + { + bytes = Base64(Encoding.ASCII.GetBytes(payload)); + } + else if (mode == "Q") + { + bytes = QuotedPrintable(Encoding.ASCII.GetBytes(payload.Replace('_', ' '))); + } + else + { + return false; + } + + word = CharsetOf(charset).GetString(bytes); + end = close + 2; + return true; + } + + // --- Parts ------------------------------------------------------------------------------------------------------- + + private static MimePart ParsePart(byte[] data, int start, int end, int depth) + { + var (headers, bodyStart) = ReadHeaders(data, start, end); + var (mediaType, parameters) = ContentType(headers.TryGetValue("content-type", out var type) ? type : "text/plain"); + var disposition = headers.TryGetValue("content-disposition", out var d) ? Parameters(d) : new Dictionary(StringComparer.Ordinal); + var fileName = disposition.GetValueOrDefault("filename") ?? parameters.GetValueOrDefault("name"); + + if (mediaType.StartsWith("multipart/", StringComparison.Ordinal) && parameters.TryGetValue("boundary", out var boundary) && depth < MaxDepth) + { + return new MimePart + { + Headers = headers, + MediaType = mediaType, + TypeParameters = parameters, + Parts = SplitMultipart(data, bodyStart, end, boundary).Select(p => ParsePart(data, p.Start, p.End, depth + 1)).ToList(), + FileName = fileName, + }; + } + + var body = Decode(data, bodyStart, end, headers.TryGetValue("content-transfer-encoding", out var encoding) ? encoding : null); + if (mediaType == "message/rfc822" && depth < MaxDepth) + { + return new MimePart + { + Headers = headers, + MediaType = mediaType, + TypeParameters = parameters, + Body = body, + Enclosed = ParsePart(body, 0, body.Length, depth + 1), + FileName = fileName, + }; + } + + return new MimePart { Headers = headers, MediaType = mediaType, TypeParameters = parameters, Body = body, FileName = fileName }; + } + + private static (Dictionary Headers, int BodyStart) ReadHeaders(byte[] data, int start, int end) + { + var headers = new Dictionary(StringComparer.Ordinal); + var position = start; + string? name = null; + var value = new StringBuilder(); + void Flush() + { + if (name is not null && !headers.ContainsKey(name)) + { + headers[name] = DecodeHeader(value.ToString().Trim()); + } + + name = null; + value.Clear(); + } + + while (position < end) + { + var lineEnd = IndexOf(data, (byte)'\n', position, end); + var next = lineEnd < 0 ? end : lineEnd + 1; + var line = Encoding.Latin1.GetString(data, position, (lineEnd < 0 ? end : lineEnd) - position).TrimEnd('\r'); + position = next; + if (line.Length == 0) + { + Flush(); + return (headers, position); + } + + if ((line[0] == ' ' || line[0] == '\t') && name is not null) + { + value.Append(' ').Append(line.Trim()); + continue; + } + + Flush(); + var colon = line.IndexOf(':', StringComparison.Ordinal); + if (colon > 0) + { + name = line[..colon].Trim().ToLowerInvariant(); + value.Append(line[(colon + 1)..]); + } + } + + Flush(); + return (headers, end); + } + + private static List<(int Start, int End)> SplitMultipart(byte[] data, int start, int end, string boundary) + { + var delimiter = Encoding.ASCII.GetBytes("--" + boundary); + var parts = new List<(int, int)>(); + int? partStart = null; + var position = start; + while (position < end) + { + var lineEnd = IndexOf(data, (byte)'\n', position, end); + var contentEnd = lineEnd < 0 ? end : lineEnd; + var next = lineEnd < 0 ? end : lineEnd + 1; + if (StartsWith(data, position, contentEnd, delimiter)) + { + var rest = Encoding.ASCII.GetString(data, position + delimiter.Length, contentEnd - position - delimiter.Length).TrimEnd('\r', ' ', '\t'); + if (rest is "" or "--") + { + if (partStart is { } open) + { + // The line break before the delimiter belongs to the delimiter. + var close = position; + if (close > open && data[close - 1] == '\n') + { + close--; + } + + if (close > open && data[close - 1] == '\r') + { + close--; + } + + parts.Add((open, close)); + } + + if (rest == "--") + { + return parts; + } + + partStart = next; + } + } + + position = next; + } + + if (partStart is { } last && last < end) + { + parts.Add((last, end)); + } + + return parts; + } + + private static byte[] Decode(byte[] data, int start, int end, string? encoding) + { + var slice = data.AsSpan(start, Math.Max(0, end - start)).ToArray(); + return encoding?.Trim().ToLowerInvariant() switch + { + "base64" => Base64(slice), + "quoted-printable" => QuotedPrintable(slice), + _ => slice, + }; + } + + /// Decodes base64, ignoring line breaks and stopping at the first character that is not base64. + /// The encoded bytes. + /// The decoded bytes. + public static byte[] Base64(byte[] text) + { + ArgumentNullException.ThrowIfNull(text); + var clean = new StringBuilder(text.Length); + foreach (var b in text) + { + var c = (char)b; + if (char.IsAsciiLetterOrDigit(c) || c is '+' or '/' or '=') + { + clean.Append(c); + } + } + + var value = clean.ToString().TrimEnd('='); + value = (value.Length % 4) switch + { + 2 => value + "==", + 3 => value + "=", + 1 => value[..^1], + _ => value, + }; + var buffer = new byte[value.Length / 4 * 3 + 3]; + return Convert.TryFromBase64String(value, buffer, out var written) ? buffer[..written] : []; + } + + /// Decodes quoted-printable (soft line breaks removed). + /// The encoded bytes. + /// The decoded bytes. + public static byte[] QuotedPrintable(byte[] text) + { + ArgumentNullException.ThrowIfNull(text); + using var output = new MemoryStream(text.Length); + for (var i = 0; i < text.Length; i++) + { + var b = text[i]; + if (b != '=') + { + output.WriteByte(b); + continue; + } + + if (i + 1 < text.Length && text[i + 1] == '\n') + { + i++; + continue; + } + + if (i + 2 < text.Length && text[i + 1] == '\r' && text[i + 2] == '\n') + { + i += 2; + continue; + } + + if (i + 2 < text.Length && byte.TryParse(Encoding.ASCII.GetString(text, i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value)) + { + output.WriteByte(value); + i += 2; + continue; + } + + output.WriteByte(b); + } + + return output.ToArray(); + } + + private static (string MediaType, Dictionary Parameters) ContentType(string value) + { + var semicolon = value.IndexOf(';', StringComparison.Ordinal); + var mediaType = (semicolon < 0 ? value : value[..semicolon]).Trim().ToLowerInvariant(); + return (mediaType.Length == 0 ? "text/plain" : mediaType, Parameters(value)); + } + + // The parameters after the first ';': name=value, name="quoted value", and RFC 2231 name*=charset''encoded and + // name*0=..., name*1=... continuations, joined. + private static Dictionary Parameters(string value) + { + var raw = new List<(string Name, string Value)>(); + var position = value.IndexOf(';', StringComparison.Ordinal); + while (position >= 0 && position < value.Length) + { + position++; + var equals = value.IndexOf('=', position); + if (equals < 0) + { + break; + } + + var name = value[position..equals].Trim().ToLowerInvariant(); + position = equals + 1; + while (position < value.Length && value[position] == ' ') + { + position++; + } + + string parameter; + if (position < value.Length && value[position] == '"') + { + var close = position + 1; + var quoted = new StringBuilder(); + while (close < value.Length && value[close] != '"') + { + if (value[close] == '\\' && close + 1 < value.Length) + { + close++; + } + + quoted.Append(value[close]); + close++; + } + + parameter = quoted.ToString(); + position = value.IndexOf(';', Math.Min(close + 1, value.Length)); + } + else + { + var semicolon = value.IndexOf(';', position); + parameter = (semicolon < 0 ? value[position..] : value[position..semicolon]).Trim(); + position = semicolon; + } + + raw.Add((name, parameter)); + } + + var result = new Dictionary(StringComparer.Ordinal); + foreach (var group in raw.GroupBy(p => p.Name.Split('*')[0])) + { + var extended = group.Where(p => p.Name.Contains('*', StringComparison.Ordinal)).ToList(); + if (extended.Count == 0) + { + result[group.Key] = DecodeHeader(group.First().Value); + continue; + } + + var ordered = extended + .OrderBy(p => int.TryParse(p.Name.Split('*').ElementAtOrDefault(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : 0) + .ToList(); + var charset = "utf-8"; + var bytes = new List(); + foreach (var (name, part) in ordered) + { + var text = part; + if (name.EndsWith('*')) + { + var first = text.IndexOf('\'', StringComparison.Ordinal); + var second = first < 0 ? -1 : text.IndexOf('\'', first + 1); + if (second > first) + { + if (first > 0) + { + charset = text[..first]; + } + + text = text[(second + 1)..]; + } + + bytes.AddRange(PercentDecode(text)); + } + else + { + bytes.AddRange(Encoding.UTF8.GetBytes(text)); + } + } + + result[group.Key] = CharsetOf(charset).GetString(bytes.ToArray()); + } + + return result; + } + + private static byte[] PercentDecode(string text) + { + var output = new List(text.Length); + for (var i = 0; i < text.Length; i++) + { + if (text[i] == '%' && i + 2 < text.Length && byte.TryParse(text.AsSpan(i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value)) + { + output.Add(value); + i += 2; + } + else + { + output.AddRange(Encoding.UTF8.GetBytes(text[i].ToString())); + } + } + + return [.. output]; + } + + private static int IndexOf(byte[] data, byte value, int start, int end) + { + var index = Array.IndexOf(data, value, start, end - start); + return index; + } + + private static bool StartsWith(byte[] data, int start, int end, byte[] prefix) => + end - start >= prefix.Length && data.AsSpan(start, prefix.Length).SequenceEqual(prefix); +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/ConservationPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/ConservationPage.razor new file mode 100644 index 0000000..d758e07 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/ConservationPage.razor @@ -0,0 +1,130 @@ +@page "/fatturazione-elettronica/conservazione" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject ConservationExportService Conservation +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The packages for substitute conservation (SPEC §11.9, issue #79): the files issued and received in a period, their + notifications, an index with the fingerprint of each file, to hand to the conservation provider. Khaemhat is not a + conservation system: it prepares what goes to one, and remembers what went out. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Conservation.Title"]
+

@T["EInvoicing.Conservation.Heading"]

+
@T["EInvoicing.Conservation.Hint"]
+
+
+ +
+ +
+ + +
+

@T["EInvoicing.Conservation.Contents"]

+ +
+ + @if (_exports.Count == 0) + { +

@T["EInvoicing.Conservation.None"]

+ } + else + { +
+ + + + + + + + + + + + @foreach (var x in _exports) + { + + + + + + + + } + +
@T["EInvoicing.Conservation.Period"]@T["EInvoicing.Conservation.File"]@T["EInvoicing.Conservation.Files"]@T["EInvoicing.Conservation.Size"]@T["EInvoicing.Conservation.Hash"]
@T.Date(x.FromDate) – @T.Date(x.ToDate)@x.FileName@x.FileCount@Size(x.Size)@x.Hash[..16]…
+
+ } +
@T["EInvoicing.Conservation.Footer"]
+
+
+
+ +@code { + private IReadOnlyList _exports = []; + private DateOnly? _from; + private DateOnly? _to; + private bool _busy; + + private string Size(long bytes) => bytes >= 1024 * 1024 + ? T.Format("EInvoicing.Conservation.MegaBytes", bytes / 1048576m) + : T.Format("EInvoicing.Conservation.KiloBytes", Math.Max(1, bytes / 1024)); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + var previous = new DateOnly(today.Year, today.Month, 1).AddMonths(-1); + _from = previous; + _to = previous.AddMonths(1).AddDays(-1); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.Read)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _exports = await Conservation.ListAsync(actor, company); + } + } + + private async Task ExportAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to) + { + return; + } + + _busy = true; + try + { + var package = await Conservation.ExportAsync(actor, company, from, to); + await EInvoicingScreens.DownloadAsync(JS, package.Export.FileName, "application/zip", package.Content); + Toasts.Show(ToastKind.Success, T["EInvoicing.Conservation.Done"], T.Format("EInvoicing.Conservation.DoneText", package.Export.FileCount)); + await LoadAsync(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceChannelsPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceChannelsPage.razor new file mode 100644 index 0000000..e46382b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceChannelsPage.razor @@ -0,0 +1,471 @@ +@page "/fatturazione-elettronica/canali" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject EInvoiceChannelService Channels +@inject EInvoicePollingService Polling +@inject ToastService Toasts +@inject DialogService Dialogs + +@* The channels to the SDI (SPEC §11.9, mockup 059): the PEC mailbox, the SdICoop web service and the intermediaries, + each with its settings, a connection test, pause and resume; below, the rules that choose the channel of each file, + with a fallback when the first is paused or fails. Secrets are kept protected and never shown again. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Channels.Title"]
+

@T["EInvoicing.Channels.Heading"]

+
@T["EInvoicing.Channels.Hint"]
+
+
+ +
+
+ +
+ @foreach (var ch in _channels) + { + var s = ch.Setting; + + } +
+ + @if (_selected is { } sel && _form is { } f) + { + + + @T[StateOf(sel.Setting)] + + +
+ + @if (Kind == "PEC") + { + + + + + + + + + + + } + else + { + + @if (Kind == "SDICOOP") + { + + + + + + } + else if (Kind == "INTA") + { + + } + else + { + + + } + + } +
+ @if (sel.Setting.LastCheckAt is { } checkedAt) + { +

+ + @T.Format("EInvoicing.Channels.LastCheck", T.DateTime(checkedAt, TimeZoneInfo.Local)) · @sel.Setting.LastCheckMessage +

+ } +
+ + @if (sel.Setting.Enabled) + { + + } + + +
+
+
+ } + + + + + + + @if (_rules.Count == 0) + { +

@T["EInvoicing.Routing.None"]

+ } + else + { + + + + + + + + + + + + @foreach (var r in _rules) + { + + + + + + + + } + +
#@T["EInvoicing.Routing.Condition"]@T["EInvoicing.Fields.Channel"]@T["EInvoicing.Routing.Fallback"]
@r.Position@RuleText(r) @(r.Disabled ? " · " + T["EInvoicing.Routing.Disabled"] : null)@ChannelName(r.ChannelCode)@(r.FallbackChannelCode is { } fb ? ChannelName(fb) : "—") + + +
+ } +

@T["EInvoicing.Routing.Note"]

+
+
+ + + + @if (_rule is { } rule) + { +
+ + + @if (rule.Condition is SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType or SdiRoutingCondition.DailyVolume) + { + + } + + + +
+ } +
+
+ + +
+
+
+ +@code { + private IReadOnlyList _channels = []; + private IReadOnlyList _rules = []; + private string? _code; + private ChannelForm? _form; + private SdiRoutingRule? _rule; + private decimal? _rulePosition; + private bool _busy; + + private EInvoiceChannelView? _selected => _channels.FirstOrDefault(c => c.Code == _code); + + private string Kind => _code?.ToUpperInvariant() ?? string.Empty; + + private IReadOnlyList> Conditions => EInvoicingScreens.Choices(T); + + private IReadOnlyList> ChannelOptions => [.. _channels.Select(c => new KhOption(c.Code, c.Name))]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.ChannelManage)) + { + await LoadAsync(); + if ((_channels.FirstOrDefault(c => c.Setting.Enabled) ?? _channels.FirstOrDefault()) is { } first) + { + Select(first); + } + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _channels = await Channels.ListAsync(actor, company); + _rules = await Channels.RulesAsync(actor, company); + } + + private void Select(EInvoiceChannelView channel) + { + _code = channel.Code; + _form = ChannelForm.From(channel.Setting); + } + + private static string IconOf(string code) => code.ToUpperInvariant() switch + { + "PEC" => "mail", + "SDICOOP" => "server", + _ => "globe", + }; + + private static string StateOf(EInvoiceChannelSetting s) => + !s.Enabled ? "EInvoicing.Channels.State.Off" : s.Paused ? "EInvoicing.Channels.State.Paused" : "EInvoicing.Channels.State.On"; + + private static KhTone ToneOf(EInvoiceChannelSetting s) => !s.Enabled ? KhTone.Neutral : s.Paused ? KhTone.Warning : KhTone.Ok; + + private string Secret(string key, bool stored) => stored ? T[key] + " · " + T["EInvoicing.Channels.Stored"] : T[key]; + + private string ChannelName(string code) => _channels.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase))?.Name ?? code; + + private string RuleText(SdiRoutingRule r) => r.Condition switch + { + SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType or SdiRoutingCondition.DailyVolume => T.Format("EInvoicing.Routing.Text." + r.Condition, r.Value), + _ => T["EInvoicing.Routing.Text." + r.Condition], + }; + + private async Task ReadCertificateAsync(InputFileChangeEventArgs e) + { + if (_form is not { } f) + { + return; + } + + using var buffer = new MemoryStream(); + await using (var stream = e.File.OpenReadStream(512 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + f.Certificate = buffer.ToArray(); + f.CertificateName = e.File.Name; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + if (_form is { } f && _code is { } code) + { + await Channels.SaveAsync(actor, company, f.ToInput(code)); + Toasts.Show(ToastKind.Success, T["EInvoicing.Channels.Saved"], ChannelName(code)); + await LoadAsync(); + if (_selected is { } sel) + { + Select(sel); + } + } + }); + + private async Task CheckAsync() => await RunAsync(async (actor, company) => + { + if (_code is { } code) + { + var check = await Channels.CheckAsync(actor, company, code); + Toasts.Show(check.Success ? ToastKind.Success : ToastKind.Error, T[check.Success ? "EInvoicing.Channels.TestOk" : "EInvoicing.Channels.TestFailed"], check.Message); + await LoadAsync(); + } + }); + + private async Task PauseAsync() => await RunAsync(async (actor, company) => + { + if (_selected is { } sel) + { + await Channels.PauseAsync(actor, company, sel.Code, !sel.Setting.Paused); + await LoadAsync(); + } + }); + + private async Task PollAsync() => await RunAsync(async (actor, company) => + { + var outcomes = await Polling.PollNowAsync(actor, company); + if (outcomes.Count == 0) + { + Toasts.Show(ToastKind.Warning, T["EInvoicing.Dashboard.PollNow"], T["EInvoicing.Report.NoChannel"]); + } + + foreach (var o in outcomes) + { + Toasts.Show(o.Error is null ? ToastKind.Success : ToastKind.Error, ChannelName(o.Channel), + o.Error is null ? T.Format("EInvoicing.Report.Polled", o.Messages, o.Invoices, o.Receipts) : EInvoicingScreens.ErrorText(T, o.Error)); + } + + await LoadAsync(); + }); + + private void NewRule() + { + _rule = new SdiRoutingRule { Condition = SdiRoutingCondition.Default, ChannelCode = _channels.FirstOrDefault(c => c.Setting.Enabled)?.Code ?? _channels.FirstOrDefault()?.Code ?? string.Empty }; + _rulePosition = null; + } + + private void EditRule(SdiRoutingRule rule) + { + _rule = new SdiRoutingRule + { + Id = rule.Id, + Position = rule.Position, + Condition = rule.Condition, + Value = rule.Value, + ChannelCode = rule.ChannelCode, + FallbackChannelCode = rule.FallbackChannelCode, + Disabled = rule.Disabled, + IsDemo = rule.IsDemo, + }; + _rulePosition = rule.Position; + } + + private async Task SaveRuleAsync() => await RunAsync(async (actor, company) => + { + if (_rule is { } rule) + { + rule.Position = _rulePosition is { } p ? (int)p : 0; + await Channels.SaveRuleAsync(actor, company, rule); + _rule = null; + await LoadAsync(); + } + }); + + private async Task DeleteRuleAsync(SdiRoutingRule rule) + { + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["EInvoicing.Routing.Delete"], RuleText(rule), T["Common.Delete"], T["Common.Cancel"], Danger: true))) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Channels.DeleteRuleAsync(actor, company, rule.Id); + await LoadAsync(); + }); + } + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } + + /// What the form edits; secrets start empty and are sent only when typed. + private sealed class ChannelForm + { + public bool Enabled { get; set; } + + public string? Mailbox { get; set; } + + public string? SmtpHost { get; set; } + + public decimal? SmtpPort { get; set; } + + public string? ImapHost { get; set; } + + public decimal? ImapPort { get; set; } + + public bool Tls { get; set; } + + public string? UserName { get; set; } + + public string? Password { get; set; } + + public string? ExchangeAddress { get; set; } + + public string? ArchiveFolder { get; set; } + + public string? Endpoint { get; set; } + + public byte[]? Certificate { get; set; } + + public string? CertificateName { get; set; } + + public string? CertificatePassword { get; set; } + + public string? ApiKey { get; set; } + + public bool TestEnvironment { get; set; } + + public static ChannelForm From(EInvoiceChannelSetting s) => new() + { + Enabled = s.Enabled, + Mailbox = s.Mailbox, + SmtpHost = s.SmtpHost, + SmtpPort = s.SmtpPort, + ImapHost = s.ImapHost, + ImapPort = s.ImapPort, + Tls = s.Tls, + UserName = s.UserName, + ExchangeAddress = s.ExchangeAddress, + ArchiveFolder = s.ArchiveFolder, + Endpoint = s.Endpoint, + TestEnvironment = s.TestEnvironment, + }; + + public EInvoiceChannelInput ToInput(string code) => new() + { + Code = code, + Enabled = Enabled, + Mailbox = Mailbox, + SmtpHost = SmtpHost, + SmtpPort = SmtpPort is { } sp ? (int)sp : 465, + ImapHost = ImapHost, + ImapPort = ImapPort is { } ip ? (int)ip : 993, + Tls = Tls, + UserName = UserName, + Password = string.IsNullOrEmpty(Password) ? null : Password, + ExchangeAddress = ExchangeAddress, + ArchiveFolder = ArchiveFolder, + Endpoint = Endpoint, + Certificate = Certificate, + CertificatePassword = string.IsNullOrEmpty(CertificatePassword) ? null : CertificatePassword, + ApiKey = string.IsNullOrEmpty(ApiKey) ? null : ApiKey, + TestEnvironment = TestEnvironment, + }; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceDashboardPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceDashboardPage.razor new file mode 100644 index 0000000..471a94e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceDashboardPage.razor @@ -0,0 +1,603 @@ +@page "/fatturazione-elettronica" +@page "/fatturazione-elettronica/cruscotto" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.Documents +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.Documents +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject EInvoiceService EInvoices +@inject EInvoicePollingService Polling +@inject ToastService Toasts +@inject IJSRuntime JS + +@* The SDI dashboard (SPEC §11.9, mockup 058): the counters of the exchange, the files issued with their state and the + last notification, the documents still to generate. From here a document is generated and sent, a rejected one is + corrected, the notifications downloaded from the portal are imported, and each file shows its history. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Dashboard.Crumb"]
+

@T["EInvoicing.Dashboard.Heading"]

+
@T["EInvoicing.Dashboard.Hint"]
+
+
+ @if (_dashboard?.Counters.Received is > 0 and var received) + { + @T.Format("EInvoicing.Dashboard.ReceivedLink", received) + } + @if (CanSend) + { + + @if (Session.Permissions.Allows(EInvoicePermissions.ChannelManage)) + { + + } + } +
+
+ + @if (_dashboard is { } d) + { + var c = d.Counters; +
+ @T["EInvoicing.Tiles.ToGenerateHint"] + @T["EInvoicing.Tiles.ToSendHint"] + @T["EInvoicing.Tiles.WaitingHint"] + @T["EInvoicing.Tiles.DeliveredHint"] + @T["EInvoicing.Tiles.RejectedHint"] + @T["EInvoicing.Tiles.NotDeliveredHint"] +
+ } + + +
+
+ + + +
+ +
+
+ + + + + @if (CanSend) + { + + + } +
+ + @if (_dashboard is { } dash) + { + @if (dash.Pending.Count > 0) + { +

@T.Format("EInvoicing.Dashboard.PendingTitle", dash.Pending.Count)

+
+ + + + + + + + + + + + + + @foreach (var p in dash.Pending) + { + var key = (p.Family, p.DocumentId); + + + + + + + + + + } + +
@T["EInvoicing.Fields.Document"]@T["EInvoicing.Fields.Date"]@T["EInvoicing.Fields.Party"]@T["EInvoicing.Fields.Total"]@T["EInvoicing.Fields.DocumentStatus"]
+ @if (SalesScreens.RecordUrl(p.Kind, p.DocumentId) is { } url) + { + @SalesScreens.KindName(T, p.Kind) @p.Number + } + else + { + @(SalesScreens.KindName(T, p.Kind) + " " + p.Number) + } + @T.Date(p.Date)@p.PartyName@T.Money(p.Total)@T["Sales.States." + p.Status] + + +
+
+ @if (dash.Rows.Count > 0) + { +

@T["EInvoicing.Dashboard.FilesTitle"]

+ } + } + + @if (dash.Rows.Count == 0 && dash.Pending.Count == 0) + { +

@T[_view == EInvoiceView.ToDo ? "EInvoicing.Dashboard.NothingToDo" : "EInvoicing.Dashboard.None"]

+ } + else if (dash.Rows.Count > 0) + { +
+ + + + + + + + + + + + + + + + + @foreach (var row in dash.Rows) + { + var e = row.Invoice; + var sendable = e.Status == EInvoiceStatus.Generated; + + + + + + + + + + + + + } + +
@T["EInvoicing.Select"]@T["EInvoicing.Fields.Document"]@T["EInvoicing.Fields.Date"]@T[_view == EInvoiceView.SelfInvoices ? "EInvoicing.Fields.Supplier" : "EInvoicing.Fields.Customer"]@T["EInvoicing.Fields.Total"]@T["EInvoicing.Fields.Type"]@T["EInvoicing.Fields.Channel"]@T["EInvoicing.Fields.SdiStatus"]@T["EInvoicing.Fields.LastMessage"]
+ @if (sendable && CanSend) + { + + } + + @if (SalesScreens.RecordUrl(e.Kind, e.DocumentId) is { } url) + { + @e.DocumentNumber + } + else + { + @e.DocumentNumber + } +
@e.FileName
+
@T.Date(e.DocumentDate)@row.PartyName@T.Money(e.TotalAmount)@e.DocumentType@ChannelName(e.ChannelCode)@T[EInvoicingScreens.EnumKey(e.Status)] + @EInvoicingScreens.ErrorText(T, e.LastMessage) + @if (e.LastNotificationAt is { } at) + { +
@T.DateTime(at, TimeZoneInfo.Local)
+ } +
+ @if (CanSend && e.Status is EInvoiceStatus.Rejected && SalesScreens.RecordUrl(e.Kind, e.DocumentId) is { } fix) + { + @T["EInvoicing.Dashboard.Correct"] + } + @if (CanSend && sendable) + { + + } + + + +
+
+ } +
@T["EInvoicing.Dashboard.Footer"]
+ } + else + { +

@T["Common.Loading"]

+ } +
+ + + + @if (_history is { Count: 0 }) + { +

@T["EInvoicing.History.None"]

+ } + else if (_history is { } history) + { + @foreach (var (file, notes) in history) + { +
+
+ + @file.FileName + @T[EInvoicingScreens.EnumKey(file.Status)] + @if (file.Superseded) + { + @T["EInvoicing.History.Superseded"] + } + + +
+
+ @T.Format("EInvoicing.History.Generated", T.DateTime(file.GeneratedAt, TimeZoneInfo.Local), file.Format) + @(file.SentAt is { } sent ? " · " + T.Format("EInvoicing.History.Sent", T.DateTime(sent, TimeZoneInfo.Local), ChannelName(file.ChannelCode)) : null) + @(file.ExchangeId is { } sdi ? " · " + T.Format("EInvoicing.History.ExchangeId", sdi) : null) +
+ @if (notes.Count > 0) + { + + + @foreach (var n in notes) + { + + + + + + + } + +
@n.Code@T.DateTime(n.ReceivedAt, TimeZoneInfo.Local) + @T["EInvoicing.Codes." + n.Code] @(n.Description is { Length: > 0 } desc ? "· " + desc : null) + @if (n.Errors is { Length: > 0 } errors) + { +
@errors
+ } +
+ } +
+ } + } +
+
+ +
+
+ + + +

@T.Format("EInvoicing.MarkSent.Text", _markSent?.FileName)

+
+ +
+
+
+ + +
+
+ + + +
    + @foreach (var (ok, title, text) in _report) + { +
  • + +
    @title @text
    +
  • + } +
+
+
+ +
+
+
+ +@code { + private EInvoiceDashboard? _dashboard; + private EInvoiceView _view = EInvoiceView.Issued; + private EInvoiceStatus? _status; + private DateOnly? _from; + private DateOnly? _to; + private string? _search; + private readonly HashSet<(DocumentFamily, long)> _docs = []; + private readonly HashSet _files = []; + private bool _busy; + private IReadOnlyList<(EInvoice Invoice, IReadOnlyList Notifications)>? _history; + private string? _historyNumber; + private EInvoice? _markSent; + private string? _exchangeId; + private readonly List<(bool Ok, string Title, string Text)> _report = []; + private string _reportTitle = string.Empty; + + /// The view asked by the address (?vista=da-fare, from the feed of the dashboard). + [SupplyParameterFromQuery(Name = "vista")] + public string? ViewQuery { get; set; } + + private bool CanSend => Session.Permissions.Allows(EInvoicePermissions.Send); + + private IReadOnlyList> Statuses => + [.. Enum.GetValues().Select(s => new KhOption(s, T[EInvoicingScreens.EnumKey(s)]))]; + + private string Count(int value) => value.ToString(T.Culture); + + private string ChannelName(string? code) => + string.IsNullOrEmpty(code) ? "—" : T.Contains("EInvoicing.Channels.Names." + code) ? T["EInvoicing.Channels.Names." + code] : code; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _view = ViewQuery switch + { + "da-fare" => EInvoiceView.ToDo, + "autofatture" => EInvoiceView.SelfInvoices, + _ => EInvoiceView.Issued, + }; + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.Read)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _dashboard = await EInvoices.DashboardAsync(actor, company, new EInvoiceFilter(_view, _status, _from, _to, _search)); + _docs.Clear(); + _files.Clear(); + if (_view == EInvoiceView.ToDo) + { + _docs.UnionWith(_dashboard.Pending.Where(p => p.Status != DocumentStatus.SdiRejected).Select(p => (p.Family, p.DocumentId))); + _files.UnionWith(_dashboard.Rows.Where(r => r.Invoice.Status == EInvoiceStatus.Generated).Select(r => r.Invoice.Id)); + } + } + + private async Task SetViewAsync(EInvoiceView view) + { + _view = view; + await LoadAsync(); + } + + private async Task SetStatusAsync(EInvoiceStatus? status) + { + _status = status; + await LoadAsync(); + } + + private async Task SetFromAsync(DateOnly? date) + { + _from = date; + await LoadAsync(); + } + + private async Task SetToAsync(DateOnly? date) + { + _to = date; + await LoadAsync(); + } + + private async Task SearchAsync(ChangeEventArgs e) + { + _search = e.Value?.ToString(); + await LoadAsync(); + } + + private void ToggleDoc((DocumentFamily, long) key, bool on) + { + if (on) + { + _docs.Add(key); + } + else + { + _docs.Remove(key); + } + } + + private void ToggleAllDocs(bool on) + { + _docs.Clear(); + if (on && _dashboard is { } d) + { + _docs.UnionWith(d.Pending.Select(p => (p.Family, p.DocumentId))); + } + } + + private void ToggleFile(long id, bool on) + { + if (on) + { + _files.Add(id); + } + else + { + _files.Remove(id); + } + } + + private async Task GenerateAndSendAsync() => await RunAsync(async (actor, company) => + { + var results = await EInvoices.GenerateAndSendAsync(actor, company, [.. _docs.Select(k => (k.Item1, k.Item2))]); + _report.Clear(); + foreach (var (doc, generation, sending) in results) + { + var title = doc is not null ? SalesScreens.KindName(T, doc.Kind) + " " + doc.Number + : generation.Invoice is { } made ? SalesScreens.KindName(T, made.Kind) + " " + made.DocumentNumber : string.Empty; + if (!generation.Success) + { + _report.Add((false, title, EInvoicingScreens.Problems(T, generation.Problems))); + } + else if (sending is { Sent: false } failed) + { + _report.Add((false, title, T.Format("EInvoicing.Report.NotSent", generation.Invoice!.FileName, EInvoicingScreens.ErrorText(T, failed.Error)))); + } + else + { + _report.Add((true, title, T.Format("EInvoicing.Report.Sent", generation.Invoice!.FileName, ChannelName(sending?.ChannelCode)))); + } + } + + _reportTitle = T["EInvoicing.Report.Title"]; + await LoadAsync(); + }); + + private async Task SendAsync() => await RunAsync(async (actor, company) => + { + var results = await EInvoices.SendAsync(actor, company, [.. _files]); + _report.Clear(); + foreach (var r in results) + { + _report.Add((r.Sent, r.DocumentNumber ?? r.FileName, r.Sent + ? T.Format("EInvoicing.Report.Sent", r.FileName, ChannelName(r.ChannelCode)) + : T.Format("EInvoicing.Report.NotSent", r.FileName, EInvoicingScreens.ErrorText(T, r.Error)))); + } + + _reportTitle = T["EInvoicing.Report.Title"]; + await LoadAsync(); + }); + + private async Task CheckAsync(PendingEInvoice document) => await RunAsync(async (actor, company) => + { + var problems = await EInvoices.CheckAsync(actor, company, document.Family, document.DocumentId); + var title = SalesScreens.KindName(T, document.Kind) + " " + document.Number; + _report.Clear(); + if (problems.Count == 0) + { + _report.Add((true, title, T["EInvoicing.Report.Valid"])); + } + + foreach (var p in problems) + { + _report.Add((p.Severity != Khaemhat.Fiscal.Abstractions.EInvoiceProblemSeverity.Error, p.Code, (string.IsNullOrEmpty(p.Path) ? string.Empty : p.Path + ": ") + EInvoicingScreens.ErrorText(T, p.Message))); + } + + _reportTitle = T["EInvoicing.Report.CheckTitle"]; + }); + + private async Task ImportReceiptsAsync(InputFileChangeEventArgs e) => await RunAsync(async (actor, company) => + { + var files = new List<(string, byte[])>(); + foreach (var file in e.GetMultipleFiles(200)) + { + using var buffer = new MemoryStream(); + await using (var stream = file.OpenReadStream(20 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + files.Add((file.Name, buffer.ToArray())); + } + + var outcomes = await EInvoices.ImportReceiptsAsync(actor, company, files); + _report.Clear(); + foreach (var o in outcomes) + { + _report.Add((o.Error is null, o.FileName, o.Error is null + ? T.Format("EInvoicing.Report.Applied", o.Code, o.InvoiceFileName, o.Status is { } s ? T[EInvoicingScreens.EnumKey(s)] : string.Empty) + : EInvoicingScreens.ErrorText(T, o.Error))); + } + + _reportTitle = T["EInvoicing.Report.ReceiptsTitle"]; + await LoadAsync(); + }); + + private async Task PollAsync() => await RunAsync(async (actor, company) => + { + var outcomes = await Polling.PollNowAsync(actor, company); + _report.Clear(); + foreach (var o in outcomes) + { + _report.Add((o.Error is null, ChannelName(o.Channel), o.Error is null + ? T.Format("EInvoicing.Report.Polled", o.Messages, o.Invoices, o.Receipts) + : EInvoicingScreens.ErrorText(T, o.Error))); + } + + if (_report.Count == 0) + { + _report.Add((false, T["EInvoicing.Dashboard.PollNow"], T["EInvoicing.Report.NoChannel"])); + } + + _reportTitle = T["EInvoicing.Dashboard.PollNow"]; + await LoadAsync(); + }); + + private async Task HistoryAsync(DocumentFamily family, long documentId, string? number) => await RunAsync(async (actor, company) => + { + _historyNumber = number; + _history = await EInvoices.HistoryAsync(actor, company, family, documentId); + }); + + private void OpenMarkSent(EInvoice invoice) + { + _markSent = invoice; + _exchangeId = null; + } + + private async Task MarkSentAsync() => await RunAsync(async (actor, company) => + { + if (_markSent is { } invoice) + { + await EInvoices.MarkSentAsync(actor, company, invoice.Id, string.IsNullOrWhiteSpace(_exchangeId) ? null : _exchangeId.Trim()); + _markSent = null; + Toasts.Show(ToastKind.Success, T["EInvoicing.MarkSent.Done"], invoice.FileName); + await LoadAsync(); + } + }); + + private async Task DownloadAsync(long id) => await RunAsync(async (actor, company) => + { + var (name, content) = await EInvoices.FileAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + }); + + private async Task NotificationAsync(long id) => await RunAsync(async (actor, company) => + { + var (name, content) = await EInvoices.NotificationFileAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + }); + + private async Task CourtesyAsync(long id) => await RunAsync(async (actor, company) => + { + var (name, content) = await EInvoices.CourtesyCopyAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, "application/pdf", content); + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceGuard.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceGuard.razor new file mode 100644 index 0000000..42bf980 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceGuard.razor @@ -0,0 +1,62 @@ +@using Khaemhat.Application.Modules +@inject ShellSession Session + +@* What every page of the electronic invoice checks first: an open company, the module EINV in the licence and the permission. *@ +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +
+ +

@T["EInvoicing.NoCompany"]

+
+} +else if (!Session.Licenses.IsModuleActive(ModuleCodes.EInvoicing)) +{ +
+ +

@T["EInvoicing.NoModule.Title"]

+

@T["EInvoicing.NoModule.Lead"]

+
+} +else if (!Session.Permissions.Allows(Permission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+ @T["Common.BackHome"] +
+} +else +{ + @ChildContent +} + +@code { + private bool _loaded; + + /// The permission the page needs. + [Parameter, EditorRequired] + public string Permission { get; set; } = string.Empty; + + /// The page. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// Whether the page may load its data: company, licence and permission. + /// The session. + /// The permission. + /// True when it may. + public static bool Allowed(ShellSession session, string permission) => + session is { Actor: not null, Company: not null } && session.Licenses.IsModuleActive(ModuleCodes.EInvoicing) && session.Permissions.Allows(permission); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceInboxPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceInboxPage.razor new file mode 100644 index 0000000..d990e2b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceInboxPage.razor @@ -0,0 +1,253 @@ +@page "/fatturazione-elettronica/ricevute" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.Documents +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.Documents +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject SdiInboxService Inbox +@inject ToastService Toasts +@inject IJSRuntime JS + +@* The invoices received from the SDI (SPEC §11.9, issue #79): what the channels downloaded and what the user uploads + (XML, P7M, the metadata file, a ZIP of the portal). Each one is registered as a supplier invoice through the import + of the purchases, or set aside; the same file never enters twice. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Inbox.Title"]
+

@T["EInvoicing.Inbox.Heading"]

+
@T["EInvoicing.Inbox.Hint"]
+
+
+ + +
+ + + + @if (CanImport) + { + + + } +
+ @if (_files.Count == 0) + { +

@T["EInvoicing.Inbox.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var f in _files) + { + + + + + + + + + + + + } + +
@T["EInvoicing.Select"]@T["EInvoicing.Fields.Supplier"]@T["EInvoicing.Fields.Document"]@T["EInvoicing.Fields.Date"]@T["EInvoicing.Fields.Total"]@T["EInvoicing.Fields.Type"]@T["EInvoicing.Inbox.ReceivedAt"]@T["EInvoicing.Fields.Status"]
+ @if (CanImport && f.Status == InboxFileStatus.New) + { + + } + + @(f.SupplierName ?? "—") +
@f.SupplierVat
+
+ @f.Number +
@f.FileName
+
@(f.DocumentDate is { } date ? T.Date(date) : null)@(f.TotalAmount is { } total ? T.Money(total) : null)@f.DocumentType + @T.DateTime(f.ReceivedAt, TimeZoneInfo.Local) +
@(f.ChannelCode == "MANUAL" ? T["EInvoicing.Inbox.Manual"] : f.ChannelCode) @(f.ExchangeId is { } sdi ? "· " + sdi : null)
+
+ @T[EInvoicingScreens.EnumKey(f.Status)] + @if (!string.IsNullOrEmpty(f.Error)) + { +
@EInvoicingScreens.ErrorText(T, f.Error)
+ } +
+ @if (f.PurchaseDocumentId is { } purchase && SalesScreens.RecordUrl(f.DocumentType == "TD04" ? DocumentKind.PurchaseCreditNote : DocumentKind.PurchaseInvoice, purchase) is { } url) + { + @T["EInvoicing.Inbox.Open"] + } + @if (CanImport && f.Status == InboxFileStatus.New) + { + + } + @if (CanImport && f.Status is InboxFileStatus.New or InboxFileStatus.Unreadable) + { + + } + @if (CanImport && f.Status == InboxFileStatus.Discarded) + { + + } + + @if (f.MetadataFileName is not null) + { + + } +
+
+ } +
@T["EInvoicing.Inbox.Footer"]
+
+
+ +@code { + private IReadOnlyList _files = []; + private readonly HashSet _chosen = []; + private InboxFileStatus? _status = InboxFileStatus.New; + private string? _search; + private bool _busy; + + private bool CanImport => Session.Permissions.Allows(EInvoicePermissions.InboxImport); + + private IReadOnlyList> Statuses => + [.. Enum.GetValues().Select(s => new KhOption(s, T[EInvoicingScreens.EnumKey(s)]))]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.InboxRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _files = await Inbox.ListAsync(actor, company, new InboxFilter(_status, _search)); + _chosen.IntersectWith(_files.Where(f => f.Status == InboxFileStatus.New).Select(f => f.Id)); + } + + private async Task SetStatusAsync(InboxFileStatus? status) + { + _status = status; + await LoadAsync(); + } + + private async Task SearchAsync(ChangeEventArgs e) + { + _search = e.Value?.ToString(); + await LoadAsync(); + } + + private void Toggle(long id, bool on) + { + if (on) + { + _chosen.Add(id); + } + else + { + _chosen.Remove(id); + } + } + + private async Task UploadAsync(InputFileChangeEventArgs e) => await RunAsync(async (actor, company) => + { + var files = new List<(string, byte[])>(); + foreach (var file in e.GetMultipleFiles(200)) + { + using var buffer = new MemoryStream(); + await using (var stream = file.OpenReadStream(50 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + files.Add((file.Name, buffer.ToArray())); + } + + var stored = await Inbox.UploadAsync(actor, company, files); + var added = stored.Count(s => s.Error is null); + Toasts.Show(added > 0 ? ToastKind.Success : ToastKind.Warning, T.Format("EInvoicing.Inbox.Uploaded", added, stored.Count), + string.Join(" · ", stored.Where(s => s.Error is not null).Select(s => s.FileName + ": " + EInvoicingScreens.ErrorText(T, s.Error)))); + _status = InboxFileStatus.New; + await LoadAsync(); + }); + + private async Task RegisterAsync(IReadOnlyList ids) => await RunAsync(async (actor, company) => + { + var results = await Inbox.RegisterAsync(actor, company, ids); + var done = results.Count(r => r.Error is null); + var problems = results.Where(r => r.Error is not null).Select(r => r.FileName + ": " + EInvoicingScreens.ErrorText(T, r.Error)) + .Concat(results.SelectMany(r => r.Warnings.Select(w => r.FileName + ": " + EInvoicingScreens.ErrorText(T, w)))); + Toasts.Show(done == results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("EInvoicing.Inbox.Registered", done, results.Count), string.Join(" · ", problems)); + _chosen.ExceptWith(ids); + await LoadAsync(); + }); + + private async Task DiscardAsync(long id, bool discard) => await RunAsync(async (actor, company) => + { + await Inbox.DiscardAsync(actor, company, id, discard); + await LoadAsync(); + }); + + private async Task DownloadAsync(long id, bool metadata) => await RunAsync(async (actor, company) => + { + var (name, content) = await Inbox.FileAsync(actor, company, id, metadata); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceNotificationsPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceNotificationsPage.razor new file mode 100644 index 0000000..d24e6aa --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceNotificationsPage.razor @@ -0,0 +1,149 @@ +@page "/fatturazione-elettronica/notifiche" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject EInvoiceService EInvoices +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The notifications of the SDI (SPEC §11.9, issue #75): every receipt kept as it arrived (RC, NS, MC, NE, DT, AT), + with the file it is about; each one can be downloaded again. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Notifications.Title"]
+

@T["EInvoicing.Notifications.Heading"]

+
@T["EInvoicing.Notifications.Hint"]
+
+
+ + +
+ + + +
+ @if (Shown.Count == 0) + { +

@T["EInvoicing.Notifications.None"]

+ } + else + { +
+ + + + + + + + + + + + + @foreach (var n in Shown) + { + + + + + + + + + } + +
@T["EInvoicing.Notifications.ReceivedAt"]@T["EInvoicing.Notifications.Code"]@T["EInvoicing.Notifications.InvoiceFile"]@T["EInvoicing.Notifications.ExchangeId"]@T["EInvoicing.Notifications.Description"]
@T.DateTime(n.ReceivedAt, TimeZoneInfo.Local)@n.Code @T["EInvoicing.Codes." + n.Code]@n.InvoiceFileName@n.ExchangeId@(n.Errors ?? n.Description)
+
+ } +
@T.Format("EInvoicing.Notifications.Footer", Shown.Count)
+
+
+ +@code { + private IReadOnlyList _rows = []; + private DateOnly? _from; + private DateOnly? _to; + private string? _code; + private bool _busy; + + private static readonly string[] AllCodes = ["RC", "NS", "MC", "NE", "DT", "AT", "SE"]; + + private IReadOnlyList Shown => _code is null ? _rows : [.. _rows.Where(n => n.Code == _code)]; + + private IReadOnlyList> Codes => [.. AllCodes.Select(c => new KhOption(c, c + " · " + T["EInvoicing.Codes." + c]))]; + + private static KhTone ToneOf(EInvoiceNotification n) => n.Code switch + { + "RC" or "DT" => KhTone.Ok, + "NS" or "SE" => KhTone.Error, + "NE" => n.Outcome == "EC02" ? KhTone.Error : KhTone.Ok, + "MC" or "AT" => KhTone.Warning, + _ => KhTone.Neutral, + }; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _to = today; + _from = new DateOnly(today.Year, 1, 1); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.Read)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to) + { + return; + } + + _rows = await EInvoices.NotificationsAsync(actor, company, from, to); + } + + private async Task SetFromAsync(DateOnly? date) + { + _from = date; + await LoadAsync(); + } + + private async Task SetToAsync(DateOnly? date) + { + _to = date; + await LoadAsync(); + } + + private async Task DownloadAsync(long id) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var (name, content) = await EInvoices.NotificationFileAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor index 3196542..c0995b3 100644 --- a/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor @@ -277,7 +277,7 @@ else private string ShownTitle => _shown is { } shown ? shown.File.Supplier.DisplayName + " · " + shown.Invoice.Number : T["Purchases.Import.View"]; - private IReadOnlyList SummaryOf(IncomingInvoice invoice) => + private IReadOnlyList SummaryOf(EInvoiceBody invoice) => [ new(T["Sales.Totals.Taxable"], T.Money(invoice.TaxSummary.Sum(t => t.Taxable))), new(T["Sales.Totals.Tax"], T.Money(invoice.TaxSummary.Sum(t => t.Tax))), diff --git a/src/Khaemhat.Web/EInvoicing/EInvoicingScreens.cs b/src/Khaemhat.Web/EInvoicing/EInvoicingScreens.cs new file mode 100644 index 0000000..1603117 --- /dev/null +++ b/src/Khaemhat.Web/EInvoicing/EInvoicingScreens.cs @@ -0,0 +1,111 @@ +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Ledger; +using Khaemhat.Web.Ui; +using Microsoft.JSInterop; + +namespace Khaemhat.Web.EInvoicing; + +/// What the screens of the electronic invoice share (SPEC §11.9, mockups 058-059): addresses, texts, tones, downloads. +public static class EInvoicingScreens +{ + /// The address of the area. + public const string BasePath = "/fatturazione-elettronica"; + + /// The address of the invoices received. + public const string InboxPath = BasePath + "/ricevute"; + + /// The address of the channels. + public const string ChannelsPath = BasePath + "/canali"; + + /// The key of the text of an enum value. + /// The value. + /// The key. + public static string EnumKey(Enum value) + { + ArgumentNullException.ThrowIfNull(value); + return "EInvoicing.Enums." + value.GetType().Name + "." + value; + } + + /// The choices of an enum. + /// The enum. + /// The texts. + /// The choices in declaration order. + public static IReadOnlyList> Choices(ITexts texts) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v, texts[EnumKey(v)]))]; + } + + /// The tone of the state of an e-invoice. + /// The state. + /// The tone. + public static KhTone ToneOf(EInvoiceStatus status) => status switch + { + EInvoiceStatus.Generated => KhTone.Neutral, + EInvoiceStatus.Sent => KhTone.Info, + EInvoiceStatus.Delivered or EInvoiceStatus.Accepted or EInvoiceStatus.TermsElapsed => KhTone.Ok, + EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable => KhTone.Warning, + _ => KhTone.Error, + }; + + /// The tone of the state of a received file. + /// The state. + /// The tone. + public static KhTone ToneOf(InboxFileStatus status) => status switch + { + InboxFileStatus.New => KhTone.Info, + InboxFileStatus.Registered => KhTone.Ok, + InboxFileStatus.Unreadable => KhTone.Error, + _ => KhTone.Neutral, + }; + + /// The text of an error code, or the code itself. + /// The texts. + /// The code (or a message of a channel). + /// The text. + public static string ErrorText(ITexts texts, string? code) + { + ArgumentNullException.ThrowIfNull(texts); + return string.IsNullOrEmpty(code) ? string.Empty : texts.Contains(code) ? texts[code] : code; + } + + /// The text of the errors of a refused operation. + /// The texts. + /// The refusal. + /// The messages. + public static string Errors(ITexts texts, ValidationFailedException exception) => LedgerScreens.Errors(texts, exception); + + /// The problems of a file as one line each: where, and what. + /// The texts. + /// The problems. + /// The text. + public static string Problems(ITexts texts, IEnumerable problems) + { + ArgumentNullException.ThrowIfNull(texts); + ArgumentNullException.ThrowIfNull(problems); + return string.Join(" · ", problems.Where(p => p.Severity == EInvoiceProblemSeverity.Error) + .Select(p => (string.IsNullOrEmpty(p.Path) ? string.Empty : p.Path + ": ") + ErrorText(texts, p.Message))); + } + + /// Gives the browser a file to save. + /// The interop. + /// The name. + /// The media type. + /// The content. + /// A task. + public static Task DownloadAsync(IJSRuntime js, string fileName, string mediaType, byte[] content) => + LedgerScreens.DownloadAsync(js, new Khaemhat.Application.Ledger.LedgerFile(fileName, mediaType, content)); + + /// The media type of a file by its extension. + /// The name. + /// The media type. + public static string MediaTypeOf(string fileName) => + fileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" + : fileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase) ? "application/pdf" + : fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) ? "application/zip" + : "application/xml"; +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs index 80068a6..0d7cb59 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs @@ -120,6 +120,7 @@ public static class KhaemhatApp app.MapCompanySwitch(); app.MapHelp(); app.MapFiles(); + app.MapSdiPush(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 0f30e22..b6b9631 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -174,6 +174,15 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); + // Electronic invoice (SPEC §11.9, M9): files, channels to the SDI, inbox, conservation. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + // The document engine (ADR 0032): one engine, the copies, a typed service per family. services.AddSingleton(); services.AddSingleton(); @@ -211,6 +220,9 @@ internal static class KhaemhatServices services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); @@ -247,6 +259,7 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -265,7 +278,8 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); // Mail (#52): the SMTP client written in house, the queue that sends in the background, documents by e-mail. services.AddSingleton(new Khaemhat.Infrastructure.Mail.SmtpSettings( diff --git a/src/Khaemhat.Web/Hosting/SdiEndpoints.cs b/src/Khaemhat.Web/Hosting/SdiEndpoints.cs new file mode 100644 index 0000000..65f75f3 --- /dev/null +++ b/src/Khaemhat.Web/Hosting/SdiEndpoints.cs @@ -0,0 +1,53 @@ +using Khaemhat.Application.EInvoicing; + +namespace Khaemhat.Web.Hosting; + +/// +/// The web service the SDI calls (SdICoop, issue #76): POST /sdicoop/{company} takes the invoices of suppliers +/// and the notifications. No session: the request carries the key of the channel in X-Khaemhat-SdiCoop-Key, and +/// the reverse proxy in front of Khaemhat does the mutual TLS with the SDI and adds the header. +/// +public static class SdiEndpoints +{ + /// The address, followed by the code of the company. + public const string BasePath = "/sdicoop"; + + /// The largest message accepted: an invoice of 5 MB in base64 with its metadata. + public const int MaxBody = 16 * 1024 * 1024; + + /// Maps the endpoint. + /// The routes. + /// The routes. + public static IEndpointRouteBuilder MapSdiPush(this IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + endpoints.MapPost(BasePath + "/{company}", async (HttpContext context, string company, SdiPushService service) => + { + if (context.Request.ContentLength is > MaxBody) + { + return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + } + + using var buffer = new MemoryStream(); + var read = new byte[81920]; + int n; + while ((n = await context.Request.Body.ReadAsync(read, context.RequestAborted)) > 0) + { + if (buffer.Length + n > MaxBody) + { + return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + } + + buffer.Write(read, 0, n); + } + + var key = context.Request.Headers[SdiPushService.KeyHeader].ToString(); + var answer = await service.ReceiveAsync(company, key.Length == 0 ? null : key, context.Request.ContentType, buffer.ToArray(), context.RequestAborted); + return Results.Content(answer.Body, answer.ContentType, System.Text.Encoding.UTF8, answer.StatusCode); + }) + .AllowAnonymous() + .DisableAntiforgery() + .ExcludeFromDescription(); + return endpoints; + } +} diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index a9c1922..6d5ff25 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -12,13 +12,15 @@ namespace Khaemhat.Web.Hosting; /// Add the demo data too, after the base data, to the tables still empty. /// How many times the demo catalogues are repeated. /// The company, or for every active one. -public sealed record SeedOptions(bool Demo, int Scale, string? Company); +/// Remove the demo data instead (only the rows marked demo and what belongs to them). +public sealed record SeedOptions(bool Demo, int Scale, string? Company, bool RemoveDemo = false); /// /// The command line of scripts/seed.sh (SPEC §4, §14): seed --base|--demo [--scale N] [--company CODE] /// runs the start sequence without serving anything (migrations, first company), then adds the missing base data, and /// with --demo the demo data, to one company or to every active one, and prints what it added. Rows already there -/// are never changed (ADR 0026); each demo seeder fills only its tables still empty. +/// are never changed (ADR 0026); each demo seeder fills only its tables still empty. seed --remove-demo removes +/// the demo data with . /// public static class SeedCommand { @@ -48,6 +50,7 @@ public static class SeedCommand error = null; var wantsBase = false; var wantsDemo = false; + var removeDemo = false; int? scale = null; string? company = null; for (var i = 1; i < args.Length; i++) @@ -60,6 +63,9 @@ public static class SeedCommand case "--demo": wantsDemo = true; break; + case "--remove-demo": + removeDemo = true; + break; case "--scale" when i + 1 < args.Length && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n is >= 1 and <= MaxScale: scale = n; i++; @@ -73,9 +79,15 @@ public static class SeedCommand } } - if (!wantsBase && !wantsDemo) + if (removeDemo && (wantsBase || wantsDemo || scale is not null)) { - error = "Uso: seed --base | --demo [--scale N] [--company CODICE]"; + error = "--remove-demo non si combina con --base, --demo o --scale."; + return false; + } + + if (!wantsBase && !wantsDemo && !removeDemo) + { + error = "Uso: seed --base | --demo [--scale N] | --remove-demo [--company CODICE]"; return false; } @@ -85,7 +97,7 @@ public static class SeedCommand return false; } - options = new SeedOptions(wantsDemo, scale ?? 1, company); + options = new SeedOptions(wantsDemo, scale ?? 1, company, removeDemo); return true; } @@ -119,7 +131,32 @@ public static class SeedCommand return 1; } + if (options.RemoveDemo) + { + var failed = false; + foreach (var code in codes) + { + var removal = await services.GetRequiredService().RemoveAsync(code).ConfigureAwait(false); + if (!removal.Done) + { + failed = true; + await Console.Error.WriteLineAsync(code + ": dati dimostrativi non rimossi, righe inserite dagli utenti li usano in: " + string.Join(", ", removal.Blockers)) + .ConfigureAwait(false); + continue; + } + + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{code}: dati dimostrativi rimossi, {removal.Total} righe.")); + foreach (var (table, count) in removal.Removed.OrderBy(r => r.Key, StringComparer.Ordinal)) + { + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $" {table}: {count}")); + } + } + + return failed ? 1 : 0; + } + var runner = services.GetRequiredService(); + var watch = System.Diagnostics.Stopwatch.StartNew(); foreach (var code in codes) { // The demo data need the base tables: --demo runs the base seeders first. @@ -135,7 +172,11 @@ public static class SeedCommand await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); + await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } + + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{code}: completato in {watch.Elapsed.TotalSeconds:0.0} s.")); + watch.Restart(); } return 0; diff --git a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json index 0f7cc77..69c29d1 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json +++ b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json @@ -51,7 +51,8 @@ "Areas": { "System": "Sistema", "Notifications": "Avvisi", - "Treasury": "Tesoreria" + "Treasury": "Tesoreria", + "EInvoicing": "Fatturazione elettronica" }, "Coming": { "Text": "Questo widget si riempie con i dati di {0}, in arrivo con la milestone {1}. Intanto puoi già metterlo dove ti serve.", @@ -75,7 +76,10 @@ "JobFailed": "Attività «{0}» non riuscita", "DueReceivable": "Incasso da {0}: {1}", "DuePayable": "Pagamento a {0}: {1}", - "Overdue": "{0} partite di clienti scadute da incassare ({1})" + "Overdue": "{0} partite di clienti scadute da incassare ({1})", + "EInvoiceRejected": "{0} fatture elettroniche scartate o rifiutate da correggere", + "EInvoiceToSend": "{0} fatture elettroniche da generare o inviare allo SDI", + "EInvoiceReceived": "{0} fatture ricevute dallo SDI da registrare" }, "Widgets": { "Kpi": { diff --git a/src/Khaemhat.Web/Resources/it-IT/EInvoicing.json b/src/Khaemhat.Web/Resources/it-IT/EInvoicing.json new file mode 100644 index 0000000..249bb5f --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/EInvoicing.json @@ -0,0 +1,278 @@ +{ + "EInvoicing": { + "NoCompany": "Scegli un'azienda per vedere la fatturazione elettronica.", + "NoModule": { + "Title": "Il modulo Fatturazione elettronica non è attivo", + "Lead": "La generazione dei file FatturaPA, l'invio allo SDI e le fatture ricevute richiedono il modulo EINV nella licenza." + }, + "NotDone": "Operazione non eseguita", + "All": "Tutti", + "Select": "Seleziona", + "SelectAll": "Seleziona tutti", + "Fields": { + "Document": "Documento", + "Date": "Data", + "Party": "Controparte", + "Customer": "Cliente", + "Supplier": "Fornitore", + "Total": "Totale", + "Type": "TD", + "Channel": "Canale", + "Status": "Stato", + "SdiStatus": "Stato SDI", + "DocumentStatus": "Stato documento", + "LastMessage": "Ultima notifica / errore", + "From": "Dal", + "To": "Al" + }, + "Tiles": { + "ToGenerate": "Da generare", + "ToGenerateHint": "documenti emessi senza XML", + "ToSend": "Da inviare", + "ToSendHint": "XML generati e controllati", + "Waiting": "Inviate in attesa", + "WaitingHint": "attendono la ricevuta SDI", + "Delivered": "Consegnate", + "DeliveredHint": "RC, esito EC01, decorrenza termini", + "Rejected": "Scartate", + "RejectedHint": "da correggere e reinviare", + "NotDelivered": "Mancata consegna", + "NotDeliveredHint": "nel cassetto fiscale del cliente" + }, + "Dashboard": { + "Title": "Cruscotto SDI", + "Crumb": "Cruscotto SDI", + "Heading": "Fatturazione elettronica · SDI", + "Hint": "I file FatturaPA emessi, il loro stato presso il Sistema di Interscambio e i documenti ancora da trasmettere.", + "ReceivedLink": "{0} fatture ricevute da registrare", + "View": "Vista", + "Issued": "Emesse", + "SelfInvoices": "Autofatture", + "ToDo": "Da fare", + "Search": "Numero, file, identificativo SDI, controparte", + "ImportReceipts": "Importa notifiche", + "PollNow": "Leggi i canali ora", + "Send": "Invia ({0})", + "GenerateAndSend": "Genera + invia ({0})", + "PendingTitle": "Documenti da generare ({0})", + "FilesTitle": "File trasmessi", + "None": "Nessun file in questo periodo.", + "NothingToDo": "Niente da fare: tutti i documenti sono stati trasmessi e nessuno è stato scartato.", + "Check": "Controlla senza generare", + "History": "Storico del file", + "Correct": "Correggi", + "MarkSent": "Segna come inviata", + "Xml": "Scarica l'XML", + "XmlShort": "XML", + "Courtesy": "Copia di cortesia (PDF)", + "Footer": "Una fattura scartata (NS) non è emessa: correggi il documento e genera un nuovo file. Una fattura rifiutata da una pubblica amministrazione (NE EC02) richiede una nota di credito." + }, + "History": { + "Title": "Storico SDI · {0}", + "None": "Il documento non ha ancora un file.", + "Superseded": "sostituito", + "Generated": "Generato il {0} · formato {1}", + "Sent": "inviato il {0} via {1}", + "ExchangeId": "identificativo SDI {0}", + "Notifications": "Notifiche" + }, + "MarkSent": { + "Text": "Segna {0} come inviata fuori da Khaemhat (dal portale Fatture e Corrispettivi). Le notifiche si importano poi con «Importa notifiche».", + "ExchangeId": "Identificativo SDI (facoltativo)", + "Done": "File segnato come inviato" + }, + "Report": { + "Title": "Esito della trasmissione", + "CheckTitle": "Controllo del file", + "ReceiptsTitle": "Notifiche importate", + "Sent": "{0} preso in carico da {1}", + "NotSent": "{0} non inviato: {1}", + "Valid": "Il file supera i controlli dello SDI.", + "Applied": "{0} su {1}: ora {2}", + "Polled": "{0} messaggi letti · {1} fatture ricevute · {2} notifiche", + "NoChannel": "Nessun canale attivo da leggere." + }, + "Inbox": { + "Title": "Fatture ricevute", + "Heading": "Fatture ricevute dallo SDI", + "Hint": "Le fatture dei fornitori scaricate dai canali o caricate a mano (XML, P7M, file metadati, ZIP del portale): si registrano come fatture di acquisto.", + "Search": "Fornitore, partita IVA, numero, file", + "Upload": "Carica file", + "Register": "Registra ({0})", + "RegisterOne": "Registra come fattura di acquisto", + "Discard": "Scarta", + "Restore": "Ripristina", + "Metadata": "Scarica il file metadati", + "Open": "Apri", + "Manual": "caricata a mano", + "ReceivedAt": "Ricevuta", + "None": "Nessuna fattura ricevuta con questi criteri.", + "Uploaded": "{0} file su {1} acquisiti", + "Registered": "{0} fatture registrate su {1}", + "Footer": "Lo stesso file non entra due volte (impronta SHA-256). Il fornitore si riconosce dalla partita IVA; se manca viene creato dall'importazione." + }, + "Notifications": { + "Title": "Notifiche SDI", + "Heading": "Notifiche dello SDI", + "Hint": "Ogni ricevuta conservata così come è arrivata, con il file a cui si riferisce.", + "Code": "Tipo", + "ReceivedAt": "Ricevuta il", + "InvoiceFile": "File fattura", + "ExchangeId": "Identificativo SDI", + "Description": "Descrizione", + "None": "Nessuna notifica in questo periodo.", + "Footer": "{0} notifiche. Le righe evidenziate non sono state abbinate a un file emesso." + }, + "Conservation": { + "Title": "Conservazione", + "Heading": "Pacchetti per la conservazione", + "Hint": "I file emessi e ricevuti in un periodo, con notifiche e indice delle impronte, da consegnare al conservatore.", + "New": "Nuovo pacchetto", + "Contents": "Lo ZIP contiene le cartelle emesse/, ricevute/ e notifiche/, l'indice indice.csv con l'impronta SHA-256 di ogni file e un LEGGIMI. Al massimo due anni per pacchetto.", + "Export": "Prepara e scarica", + "History": "Pacchetti preparati", + "Period": "Periodo", + "File": "File", + "Files": "File inclusi", + "Size": "Dimensione", + "Hash": "Impronta SHA-256", + "None": "Nessun pacchetto preparato.", + "KiloBytes": "{0:N0} kB", + "MegaBytes": "{0:N1} MB", + "Done": "Pacchetto pronto", + "DoneText": "{0} file inclusi", + "Footer": "Khaemhat non è un sistema di conservazione sostitutiva: prepara il pacchetto e ricorda cosa è uscito e con quale impronta." + }, + "Channels": { + "Title": "Canali di trasmissione", + "Heading": "Canali verso lo SDI", + "Hint": "Come i file arrivano al Sistema di Interscambio e come tornano le notifiche e le fatture dei fornitori.", + "Settings": "{0} · impostazioni", + "Enabled": "Canale attivo", + "Mailbox": "Casella PEC", + "SmtpHost": "Server SMTP", + "SmtpPort": "Porta SMTP", + "ImapHost": "Server IMAP", + "ImapPort": "Porta IMAP", + "Tls": "Connessione cifrata (TLS)", + "UserName": "Utente", + "Password": "Password", + "ExchangeAddress": "Indirizzo PEC dello SDI", + "ArchiveFolder": "Cartella di archivio", + "Endpoint": "Indirizzo del servizio", + "Certificate": "Certificato client (PKCS#12)", + "CertificatePick": "Scegli il file .p12", + "CertificatePassword": "Password del certificato", + "PushKey": "Chiave di ricezione (header X-Khaemhat-SdiCoop-Key)", + "ApiKey": "Chiave API", + "TestEnvironment": "Ambiente di prova", + "Stored": "memorizzata, lascia vuoto per non cambiarla", + "LastCheck": "Ultima prova {0}", + "LastPoll": "letto {0}", + "Test": "Prova connessione", + "TestOk": "Connessione riuscita", + "TestFailed": "Connessione non riuscita", + "Pause": "Metti in pausa", + "Resume": "Riprendi", + "Saved": "Canale salvato", + "State": { + "On": "Attivo", + "Paused": "Configurato · in pausa", + "Off": "Non configurato" + }, + "About": { + "PEC": "Invio dalla casella PEC dell'azienda all'indirizzo dello SDI; ricevute e fatture lette via IMAP.", + "SDICOOP": "Web service SdICoop con certificato client; lo SDI consegna notifiche e fatture al servizio di ricezione.", + "INTA": "Intermediario accreditato con API REST e chiave API.", + "INTB": "Intermediario accreditato con API REST, utente e password." + }, + "Names": { + "PEC": "PEC", + "SDICOOP": "SdICoop", + "INTA": "Intermediario A", + "INTB": "Intermediario B", + "MANUAL": "Portale AdE" + } + }, + "Routing": { + "Title": "Instradamento", + "Add": "Nuova regola", + "Edit": "Modifica regola", + "Delete": "Elimina la regola", + "Condition": "Condizione", + "Fallback": "Canale di riserva", + "Position": "Ordine", + "Disabled": "disattivata", + "None": "Nessuna regola: i file usano il primo canale attivo.", + "Note": "Vale la prima regola attiva che si applica. Il canale di riserva si usa quando il primo è in pausa, disattivato o non risponde.", + "Value": { + "Party": "Codice del cliente", + "DocumentType": "Tipo documento (TD01, TD17…)", + "DailyVolume": "File inviati oggi (almeno)" + }, + "Text": { + "Default": "Sempre", + "PublicAdministration": "Cliente pubblica amministrazione", + "Party": "Cliente {0}", + "DocumentType": "Tipo documento {0}", + "DailyVolume": "Oltre {0} file al giorno" + } + }, + "Codes": { + "RC": "Ricevuta di consegna", + "NS": "Notifica di scarto", + "MC": "Mancata consegna", + "NE": "Esito committente", + "DT": "Decorrenza termini", + "AT": "Attestazione di trasmissione", + "SE": "Scarto esito committente", + "MT": "File metadati" + }, + "Enums": { + "EInvoiceStatus": { + "Generated": "Generata", + "Sent": "Inviata", + "Delivered": "Consegnata", + "NotDelivered": "Mancata consegna", + "Rejected": "Scartata", + "Accepted": "Accettata", + "Refused": "Rifiutata", + "TermsElapsed": "Decorrenza termini", + "Undeliverable": "Impossibile recapitare" + }, + "InboxFileStatus": { + "New": "Da registrare", + "Registered": "Registrata", + "Discarded": "Scartata", + "Unreadable": "Illeggibile" + }, + "SdiRoutingCondition": { + "Default": "Sempre", + "PublicAdministration": "Cliente pubblica amministrazione", + "Party": "Cliente specifico", + "DocumentType": "Tipo documento", + "DailyVolume": "Volume giornaliero" + } + } + }, + "einvoice": { + "not-found": "Il file non esiste più.", + "not-electronic": "Il documento non si trasmette allo SDI (per esempio un DDT o una pro forma).", + "not-issued": "Il documento non è ancora emesso: confermalo prima di generare l'XML.", + "already-sent": "Il file è già stato inviato.", + "profile-missing": "Mancano i dati dell'azienda per la fattura elettronica: completa il profilo azienda (partita IVA, sede, regime fiscale).", + "not-supported": "Il pacchetto fiscale dell'azienda non gestisce la fattura elettronica.", + "no-channel": "Nessun canale attivo per inviare il file: configura un canale o segna il file come inviato dal portale.", + "not-a-receipt": "Il file non è una notifica dello SDI.", + "receipt-unmatched": "La notifica non corrisponde a nessun file emesso.", + "receipt-duplicate": "La notifica era già stata importata.", + "channel-unknown": "Canale sconosciuto.", + "port-invalid": "La porta deve essere tra 1 e 65535.", + "mailbox-invalid": "L'indirizzo PEC non è valido.", + "endpoint-invalid": "L'indirizzo del servizio deve essere https (http solo verso questo computer).", + "rule-value": "La condizione richiede un valore valido.", + "inbox-duplicate": "Il file era già stato ricevuto.", + "inbox-state": "La fattura è già registrata o scartata.", + "period-invalid": "Il periodo non è valido (al massimo due anni)." + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index 11b5622..b019147 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -111,6 +111,9 @@ "EInvoicing": { "_": "Fatt. elettronica", "Dashboard": "Cruscotto SDI", + "Inbox": "Fatture ricevute", + "Notifications": "Notifiche SDI", + "Conservation": "Conservazione", "Channels": "Canali di trasmissione", "IntentDeclarations": "Dichiarazioni d'intento" }, diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 28153da..4af9a07 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -78,9 +78,7 @@ public static class MenuCatalog ("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Receipts", "incassi"), ("Shell.Menu.Finance.Payments", "pagamenti"), ("Shell.Menu.Finance.Dunning", "solleciti"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Mandates", "mandati"), ("Shell.Menu.Finance.Reconciliation", "riconciliazione"), ("Shell.Menu.Finance.CashFlow", "flusso-di-cassa")), - Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M9", - ("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"), - ("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento")), + EInvoicing(), Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10", ("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")), Area("Shell.Menu.Services", "wrench", "/servizi", ModuleCodes.Services, null, "M12", @@ -127,6 +125,27 @@ public static class MenuCatalog // An entry delivered before the rest of its area (the guided import of M4 under the administration of M13). private static MenuItem WithChild(MenuItem area, MenuItem child) => area with { Children = [.. area.Children, child] }; + /// The electronic invoice (M9): each page has its own permission; the intent declarations come with M10. + private static MenuItem EInvoicing() + { + const string href = "/fatturazione-elettronica"; + const string icon = "file-check"; + MenuItem Child(string key, string slug, string permission, string? milestone = null) => + new(key, icon, href + "/" + slug, ModuleCodes.EInvoicing, permission, milestone); + return new MenuItem("Shell.Menu.EInvoicing", icon, href, ModuleCodes.EInvoicing, "einvoice.document.read", null) + { + Children = + [ + Child("Shell.Menu.EInvoicing.Dashboard", "cruscotto", "einvoice.document.read"), + Child("Shell.Menu.EInvoicing.Inbox", "ricevute", "einvoice.inbox.read"), + Child("Shell.Menu.EInvoicing.Notifications", "notifiche", "einvoice.document.read"), + Child("Shell.Menu.EInvoicing.Conservation", "conservazione", "einvoice.document.read"), + Child("Shell.Menu.EInvoicing.Channels", "canali", "einvoice.channel.manage"), + Child("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento", "einvoice.document.read", "M10"), + ], + }; + } + private static MenuItem Area(string key, string icon, string href, string module, string? permission, string? milestone, params (string Key, string Slug)[] children) => Area(key, icon, href, module, permission, milestone, MenuAudience.Everyone, children); diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 5c1d41d..5472296 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -457,3 +457,32 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } .kh-cfbar { display: block; height: 8px; border-radius: 4px; background: var(--kh-accent); min-width: 2px; } .kh-cfbar.neg { background: var(--kh-err); } @media (max-width: 1100px) { .kh-remit { grid-template-columns: minmax(0, 1fr); } } + +/* Electronic invoice (M9, mockups 058-059): six counters, channel cards, the history of a file, the reports. */ +.kh-sdi-tiles { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); } +.kh-mono { font-family: var(--kh-mono); font-size: 11.5px; } +.kh-pad-x { padding: 0 14px; } +.sm { font-size: 11.5px; } +.grid tr.kh-off td { color: var(--kh-text-3); } +.kh-sdi-channels { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; margin: 10px 0 12px; } +.kh-sdi-card { text-align: left; font: inherit; color: inherit; cursor: pointer; } +.kh-sdi-card:hover { border-color: var(--kh-accent); } +.kh-sdi-card.sel { border-color: var(--kh-accent); box-shadow: 0 0 0 2px var(--kh-accent-soft); } +.kh-sdi-card .mf { flex-wrap: wrap; } +.kh-sdi-actions { display: flex; gap: 8px; align-items: center; margin-top: 12px; flex-wrap: wrap; } +.kh-sdi-actions .grow { flex: 1; } +.kh-sdi-check { display: flex; gap: 6px; align-items: center; margin: 10px 0 0; font-size: 12px; } +.kh-sdi-check.ok { color: var(--kh-ok); } .kh-sdi-check.no { color: var(--kh-err); } +.kh-note { display: flex; gap: 6px; align-items: flex-start; margin: 0; padding: 10px 14px; font-size: 12px; color: var(--kh-text-2); border-top: 1px solid var(--kh-border); } +.kh-sdi-file { border: 1px solid var(--kh-border); border-radius: var(--kh-radius, 8px); padding: 10px 12px; margin-bottom: 10px; } +.kh-sdi-filehead { display: flex; gap: 8px; align-items: center; margin-bottom: 4px; flex-wrap: wrap; } +.kh-sdi-filehead .grow { flex: 1; } +.kh-sdi-notes { margin-top: 8px; } +.kh-sdi-notes .kh-sdi-desc { white-space: normal; } +.kh-sdi-report { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; max-height: 60vh; overflow: auto; } +.kh-sdi-report li { display: flex; gap: 8px; align-items: flex-start; } +.kh-sdi-report li.ok > svg { color: var(--kh-ok); } .kh-sdi-report li.no > svg { color: var(--kh-err); } +.kh-headacts { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; } +.kh-sdi-panel .gridwrap { flex: none; } +.kh-sdi-panel .kh-searchbox { flex: 1; width: auto; min-width: 220px; } +.kh-prewrap { white-space: pre-wrap; } diff --git a/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs index 9d14106..0eb9169 100644 --- a/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs +++ b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs @@ -64,7 +64,7 @@ public sealed class DocumentRulesTests Assert.AreEqual(DocumentStatus.SdiDelivered, status); CollectionAssert.AreEqual(new[] { DocumentAction.Copy }, DocumentStateMachine.Actions(Invoice, DocumentStatus.SdiDelivered).ToArray()); - foreach (var issued in DocumentStateMachine.States(Invoice).Where(s => s != DocumentStatus.Draft)) + foreach (var issued in DocumentStateMachine.States(Invoice).Where(s => s is not (DocumentStatus.Draft or DocumentStatus.SdiRejected))) { Assert.IsFalse(DocumentStateMachine.IsEditable(Invoice, issued), issued.ToString()); Assert.IsFalse(DocumentStateMachine.Allows(Invoice, issued, DocumentAction.Delete), issued.ToString()); @@ -72,6 +72,8 @@ public sealed class DocumentRulesTests Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiGenerated, DocumentAction.Cancel)); Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiRejected, DocumentAction.Cancel)); + Assert.IsTrue(DocumentStateMachine.IsEditable(Invoice, DocumentStatus.SdiRejected), "A rejected invoice is corrected and sent again."); + Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiRejected, DocumentAction.Delete)); Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiSent, DocumentAction.Cancel)); Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.Draft, DocumentAction.Confirm), "Invoices are issued, not confirmed."); Assert.AreEqual(DocumentStatus.SdiGenerated, DocumentStateMachine.Apply(Invoice, DocumentStatus.SdiRejected, DocumentAction.GenerateXml)); diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index bc19b8c..ca438a5 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -86,6 +86,7 @@ public sealed class MappingTests "gl_open_items", "gl_recurring_entries", "vat_settlements", "vat_settlement_lines", "tax_payments", "withholdings", "vat_register_prints", "payments", "payment_lines", "remittances", "remittance_lines", "sdd_mandates", "bank_statements", "bank_statement_lines", "bank_match_rules", "dunning_levels", "dunning_letters", + "e_invoices", "e_invoice_notifications", "e_invoice_inbox", "e_invoice_channels", "e_invoice_routing", "e_invoice_conservation", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs index 96fc5f6..b44aa5f 100644 --- a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs +++ b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs @@ -159,7 +159,7 @@ public sealed class FatturaPaReaderTests 22.00100.0022.00I """; - private static IncomingInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml)); + private static EInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml)); [TestMethod] public void Read_OrdinaryInvoice_ReadsHeaderPartiesAndTransmission() @@ -209,14 +209,14 @@ public sealed class FatturaPaReaderTests Assert.IsNull(invoice.Rounding); CollectionAssert.AreEqual(new[] { "Fornitura di marzo", "Consegna in cantiere" }, invoice.Causals.ToArray()); Assert.IsFalse(invoice.Art73); - Assert.AreEqual(new IncomingDiscount(false, 2.00m, null), invoice.Discounts[0]); - Assert.AreEqual(new IncomingDiscount(true, null, 1.50m), invoice.Discounts[1]); + Assert.AreEqual(new EInvoiceDiscount(false, 2.00m, null), invoice.Discounts[0]); + Assert.AreEqual(new EInvoiceDiscount(true, null, 1.50m), invoice.Discounts[1]); Assert.HasCount(3, invoice.Lines); var bolts = invoice.Lines[0]; Assert.AreEqual(1, bolts.Number); - Assert.AreEqual(new IncomingItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]); - Assert.AreEqual(new IncomingItemCode("EAN", "8001234567895"), bolts.Codes[1]); + Assert.AreEqual(new EInvoiceItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]); + Assert.AreEqual(new EInvoiceItemCode("EAN", "8001234567895"), bolts.Codes[1]); Assert.AreEqual("Bulloni M8 zincati", bolts.Description); Assert.AreEqual(100m, bolts.Quantity); Assert.AreEqual("PZ", bolts.Unit); @@ -224,7 +224,7 @@ public sealed class FatturaPaReaderTests Assert.AreEqual(45m, bolts.TotalPrice); Assert.AreEqual(22m, bolts.TaxRate); Assert.IsNull(bolts.Nature); - Assert.AreEqual(new IncomingDiscount(false, 10m, null), bolts.Discounts.Single()); + Assert.AreEqual(new EInvoiceDiscount(false, 10m, null), bolts.Discounts.Single()); Assert.IsFalse(bolts.Withheld); Assert.AreEqual(4m, invoice.Lines[1].TaxRate); @@ -238,13 +238,13 @@ public sealed class FatturaPaReaderTests Assert.AreEqual("CC-12", contribution.AdministrativeReference); Assert.HasCount(3, invoice.TaxSummary); - Assert.AreEqual(new IncomingTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]); + Assert.AreEqual(new EInvoiceTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]); Assert.AreEqual(4m, invoice.TaxSummary[1].Rate); Assert.AreEqual("N2.2", invoice.TaxSummary[2].Nature); Assert.AreEqual("Non soggetto art. 15 DPR 633/72", invoice.TaxSummary[2].LegalReference); Assert.HasCount(2, invoice.Payments); - Assert.AreEqual(new IncomingPayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]); + Assert.AreEqual(new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]); Assert.AreEqual("BPMOIT22XXX", invoice.Payments[1].Bic); Assert.AreEqual("Ferramenta Piemontese S.r.l.", invoice.Payments[1].Beneficiary); Assert.IsEmpty(invoice.Attachments); @@ -377,9 +377,9 @@ public sealed class FatturaPaReaderTests Assert.AreEqual("Giulia", file.Supplier.FirstName); Assert.AreEqual("Bianchi", file.Supplier.LastName); Assert.AreEqual("Giulia Bianchi", file.Supplier.DisplayName); - Assert.AreEqual(new IncomingWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single()); - Assert.AreEqual(new IncomingStampDuty(true, 2m), invoice.StampDuty); - Assert.AreEqual(new IncomingSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single()); + Assert.AreEqual(new EInvoiceWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single()); + Assert.AreEqual(new EInvoiceStampDuty(true, 2m), invoice.StampDuty); + Assert.AreEqual(new EInvoiceSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single()); Assert.AreEqual(1270.88m, invoice.Total); Assert.AreEqual(0.01m, invoice.Rounding); Assert.IsTrue(invoice.Art73); diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs new file mode 100644 index 0000000..bbfc9a3 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs @@ -0,0 +1,335 @@ +using System.Text; +using System.Xml.Linq; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// +/// The writer and the validator of FatturaPA (issue #74): every file written is valid against the schema, reads back to +/// the same content and passes the checks of the exchange system; each check is shown failing on a broken invoice. +/// The parties are fictitious, with VAT numbers that only pass the check digit. +/// +[TestClass] +public sealed class FatturaPaWriterTests +{ + private static readonly FatturaPaWriter Writer = new(); + private static readonly FatturaPaValidator Validator = new(); + private static readonly FatturaPaReader Reader = new(); + + /// The company: an Italian limited company in the companies register. + public static EInvoiceParty Company { get; } = new( + "IT", "01234567897", "01234567897", "Khaemhat Demo S.r.l.", null, null, + "Via dei Granai", "57", "10121", "Torino", "TO", "IT", "RF01", "amministrazione@demo.example", "011 555 1234", "TO", "123456") + { + ShareCapital = 10_000m, + Shareholders = "SU", + LiquidationStatus = "LN", + }; + + /// A business customer. + public static EInvoiceParty Customer { get; } = new( + "IT", "09876543217", null, "Officine Esempio S.p.A.", null, null, + "Corso Milano", "4", "20121", "Milano", "MI", "IT", null, null, null, null, null); + + /// An invoice with two rates, a discount, a delivery note and two installments. + /// The file. + public static EInvoiceFile Invoice() => new( + "IT01234567897_00001.xml", "FPR12", "00001", "ABC1234", Company, Customer, + [ + new EInvoiceBody( + "TD01", "EUR", new DateOnly(2026, 10, 9), "FT/2026/000414", 1_311.62m, null, + ["Fornitura di ottobre"], false, [], null, [], [], + [new EInvoiceReference("ORD-77", new DateOnly(2026, 9, 30), [], null, null)], [], [], + [new EInvoiceReference("DDT/2026/88", new DateOnly(2026, 10, 2), [1, 2], null, null)], + [ + new EInvoiceLine(1, [new EInvoiceItemCode("INTERNO", "VIT-08")], "Viti autofilettanti 8 mm", 100m, "PZ", 0.85m, 80.75m, 22m, null, + [new EInvoiceDiscount(false, 5m, null)], false, null, null, null, null), + new EInvoiceLine(2, [], "Trapano a percussione", 2m, "PZ", 489.50m, 979m, 22m, null, [], false, null, null, null, null), + new EInvoiceLine(3, [], "Manuale tecnico", 1m, "PZ", 18m, 18m, 4m, null, [], false, null, null, null, null), + ], + [ + new EInvoiceTaxSummary(22m, null, 1_059.75m, 233.15m, "I", null, null, null), + new EInvoiceTaxSummary(4m, null, 18m, 0.72m, "I", null, null, null), + ], + [ + new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 11, 30), 655.81m, "IT60X0542811101000000123456", null, null), + new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 12, 31), 655.81m, "IT60X0542811101000000123456", null, null), + ], + []), + ], + null, []) + { + TransmitterCountry = "IT", + TransmitterId = "01234567897", + }; + + [TestMethod] + public void FileName_UsesTheTransmitterAndAFiveCharacterBase36Progressive() + { + Assert.AreEqual("IT01234567897_00001.xml", Writer.FileName("IT", "01234567897", 1)); + Assert.AreEqual("00010", Writer.Progressive(36)); + Assert.AreEqual("0000Z", Writer.Progressive(35)); + Assert.AreEqual("ZZZZZ", Writer.Progressive(60_466_175)); + Assert.ThrowsExactly(() => Writer.Progressive(0)); + } + + [TestMethod] + public void Write_Invoice_IsValidAgainstTheSchemaAndPassesTheChecks() + { + var file = Invoice(); + Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList()); + + var xml = Writer.Write(file); + + var problems = Validator.ValidateXml(xml); + Assert.IsEmpty(problems, string.Join("\n", problems.Select(p => p.Path + ": " + p.Message))); + } + + [TestMethod] + public void Write_Invoice_ReadsBackToTheSameContent() + { + var file = Invoice(); + + var read = Reader.Read(file.FileName, Writer.Write(file)); + + Assert.AreEqual("FPR12", read.TransmissionFormat); + Assert.AreEqual("ABC1234", read.RecipientCode); + Assert.AreEqual("01234567897", read.TransmitterId); + Assert.AreEqual("Khaemhat Demo S.r.l.", read.Supplier.Name); + Assert.AreEqual(10_000m, read.Supplier.ShareCapital); + Assert.AreEqual("SU", read.Supplier.Shareholders); + Assert.AreEqual("0115551234", read.Supplier.Phone); + var body = read.Invoices.Single(); + Assert.AreEqual("FT/2026/000414", body.Number); + Assert.AreEqual(1_311.62m, body.Total); + Assert.HasCount(3, body.Lines); + Assert.AreEqual(80.75m, body.Lines[0].TotalPrice); + Assert.AreEqual(5m, body.Lines[0].Discounts.Single().Percent); + Assert.AreEqual("VIT-08", body.Lines[0].Codes.Single().Value); + Assert.HasCount(2, body.TaxSummary); + Assert.AreEqual("DDT/2026/88", body.DeliveryNotes.Single().Id); + CollectionAssert.AreEqual(new[] { 1, 2 }, body.DeliveryNotes.Single().LineNumbers.ToArray()); + Assert.AreEqual("ORD-77", body.Orders.Single().Id); + Assert.HasCount(2, body.Payments); + Assert.AreEqual("TP01", body.PaymentConditions); + } + + [TestMethod] + public void Write_RootIsQualifiedAndChildrenAreNot() + { + var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice()))).Root!; + + Assert.AreEqual(FatturaPaWriter.Namespace, root.Name.NamespaceName); + Assert.AreEqual("FPR12", root.Attribute("versione")!.Value); + Assert.IsTrue(root.Elements().All(e => e.Name.NamespaceName.Length == 0)); + } + + [TestMethod] + public void Write_ProfessionalFee_WithWithholdingFundStampAndNature() + { + var professional = Company with { TaxRegime = "RF19" }; + var body = new EInvoiceBody( + "TD06", "EUR", new DateOnly(2026, 10, 12), "P/2026/7", 1_286.80m, null, [], false, + [new EInvoiceWithholding("RT01", 200m, 20m, "A")], new EInvoiceStampDuty(true, 2m), + [new EInvoiceSocialSecurity("TC04", 4m, 40m, 1_000m, 22m, false, null)], [], [], [], [], [], + [ + new EInvoiceLine(1, [], "Consulenza tecnica di ottobre", null, null, 1_000m, 1_000m, 22m, null, [], true, null, null, null, null), + new EInvoiceLine(2, [], "Diritti di segreteria anticipati", null, null, 16m, 16m, 0m, "N1", [], false, null, null, null, null), + ], + [ + new EInvoiceTaxSummary(22m, null, 1_040m, 228.80m, "I", null, null, null), + new EInvoiceTaxSummary(0m, "N1", 16m, 0m, null, "Art. 15 DPR 633/72", null, null), + ], + [new EInvoicePayment("TP02", "MP05", null, 1_086.80m, null, null, null)], + [new EInvoiceAttachment("cortesia.pdf", "PDF", "Copia di cortesia", Encoding.ASCII.GetBytes("%PDF-1.4"))]); + var file = Invoice() with { Supplier = professional, Invoices = [body] }; + + var errors = Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList(); + Assert.IsEmpty(errors, string.Join("\n", errors)); + var xml = Writer.Write(file); + Assert.IsEmpty(Validator.ValidateXml(xml)); + var read = Reader.Read(file.FileName, xml).Invoices.Single(); + Assert.AreEqual(200m, read.Withholdings.Single().Amount); + Assert.AreEqual("TC04", read.SocialSecurity.Single().Fund); + Assert.AreEqual(2m, read.StampDuty!.Amount); + Assert.IsTrue(read.Lines[0].Withheld); + Assert.AreEqual("N1", read.Lines[1].Nature); + Assert.AreEqual("%PDF-1.4", Encoding.ASCII.GetString(read.Attachments.Single().Content)); + } + + [TestMethod] + public void Write_PublicAdministration_SplitPaymentWithCigCupAndIntentData() + { + var administration = Customer with { VatNumber = null, TaxCode = "80012345676", Name = "Comune di Esempio" }; + var line = new EInvoiceLine(1, [], "Manutenzione impianto", 1m, null, 1_000m, 1_000m, 22m, null, [], false, null, null, null, "UFF-12") + { + OtherData = [new EInvoiceOtherData("INTENTO", "26012345678901-000001", null, new DateOnly(2026, 1, 8))], + }; + var body = new EInvoiceBody( + "TD01", "EUR", new DateOnly(2026, 9, 30), "FT/2026/390", 1_220m, null, [], false, [], null, [], [], + [new EInvoiceReference("DET-2026-15", new DateOnly(2026, 6, 1), [], "ZAB1234567", "J51B26000010007")], [], [], [], + [line], + [new EInvoiceTaxSummary(22m, null, 1_000m, 220m, "S", null, null, null)], + [new EInvoicePayment("TP02", "MP05", new DateOnly(2026, 10, 30), 1_000m, "IT60X0542811101000000123456", null, null)], + []); + var file = Invoice() with { TransmissionFormat = "FPA12", RecipientCode = "UFE7GH", Customer = administration, Invoices = [body] }; + + Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList()); + var xml = Writer.Write(file); + Assert.IsEmpty(Validator.ValidateXml(xml)); + var read = Reader.Read(file.FileName, xml); + Assert.AreEqual("FPA12", read.TransmissionFormat); + Assert.AreEqual("ZAB1234567", read.Invoices[0].Orders.Single().Cig); + Assert.AreEqual("J51B26000010007", read.Invoices[0].Orders.Single().Cup); + Assert.AreEqual("S", read.Invoices[0].TaxSummary.Single().Exigibility); + Assert.AreEqual("INTENTO", read.Invoices[0].Lines[0].OtherData.Single().Type); + Assert.AreEqual("UFF-12", read.Invoices[0].Lines[0].AdministrativeReference); + } + + [TestMethod] + public void Write_ForeignCustomerAndConsumerWithPec() + { + var foreign = Customer with { CountryCode = "DE", VatNumber = "DE123456789", Country = "DE", PostalCode = "80331", Province = null, City = "München", Name = "Alpenbau GmbH" }; + var file = Invoice() with { RecipientCode = "XXXXXXX", Customer = foreign }; + var xml = Writer.Write(file); + Assert.IsEmpty(Validator.ValidateXml(xml)); + var read = Reader.Read(file.FileName, xml); + Assert.AreEqual("00000", read.Customer.PostalCode); + Assert.IsNull(read.Customer.Province); + Assert.AreEqual("München", read.Customer.City); + + var consumer = new EInvoiceParty("IT", null, "RSSMRA80A01H501U", null, "Mario", "Rossi", "Via Po", "1", "10124", "Torino", "TO", "IT", null, null, null, null, null); + var toConsumer = Invoice() with { RecipientCode = "0000000", RecipientPec = "mario.rossi@pec.example.it", Customer = consumer }; + Assert.IsEmpty(Validator.Validate(toConsumer).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList()); + var consumerXml = Writer.Write(toConsumer); + Assert.IsEmpty(Validator.ValidateXml(consumerXml)); + Assert.AreEqual("mario.rossi@pec.example.it", Reader.Read(toConsumer.FileName, consumerXml).RecipientPec); + } + + [TestMethod] + public void Write_TextOutsideLatin1_IsReplacedAndCut() + { + Assert.AreEqual("Viti 'speciali' - EUR 5...", FatturaPaWriter.Text("Viti ‘speciali’ — € 5…", 100)); + Assert.AreEqual("abc", FatturaPaWriter.Text("abcdef", 3)); + Assert.AreEqual("a ? b", FatturaPaWriter.Text("a 漢 b", 10)); + + var line = Invoice().Invoices[0].Lines[2] with { Description = "Manuale “tecnico” – ed. 2026 ✓" }; + var body = Invoice().Invoices[0] with { Lines = [.. Invoice().Invoices[0].Lines.Take(2), line] }; + Assert.IsEmpty(Validator.ValidateXml(Writer.Write(Invoice() with { Invoices = [body] }))); + } + + [TestMethod] + public void Write_LongCausal_IsSplitIntoFieldsOf200Characters() + { + var note = string.Join(' ', Enumerable.Repeat("Consegna al magazzino di via dei Granai.", 12)); + var body = Invoice().Invoices[0] with { Causals = [note] }; + + var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice() with { Invoices = [body] }))).Root!; + + var causals = root.Descendants("Causale").Select(c => c.Value).ToList(); + Assert.IsGreaterThan(1, causals.Count); + Assert.IsTrue(causals.All(c => c.Length <= 200)); + Assert.AreEqual(note.Replace(" ", string.Empty, StringComparison.Ordinal), string.Concat(causals).Replace(" ", string.Empty, StringComparison.Ordinal)); + } + + [TestMethod] + public void Validate_WrongLineTotal_Gives00423() + { + var body = Invoice().Invoices[0]; + var wrong = body with { Lines = [body.Lines[0] with { TotalPrice = 85m }, body.Lines[1], body.Lines[2]] }; + + var problems = Validator.Validate(Invoice() with { Invoices = [wrong] }); + + Assert.IsTrue(problems.Any(p => p.Code == "00423" && p.Path.Contains("DettaglioLinee[1]", StringComparison.Ordinal))); + } + + [TestMethod] + public void Validate_NatureRules_Give00400_00401_00445_00429() + { + var body = Invoice().Invoices[0]; + var noNature = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m }] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [noNature] }).Any(p => p.Code == "00400")); + + var natureWithRate = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { Nature = "N4" }] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [natureWithRate] }).Any(p => p.Code == "00401")); + + var generic = body with + { + Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m, Nature = "N2" }], + TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, "N2", 18m, 0m, null, "Art. 7", null, null)], + }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [generic] }).Any(p => p.Code == "00445")); + + var summaryWithout = body with { TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, null, 18m, 0m, null, null, null, null)] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [summaryWithout] }).Any(p => p.Code == "00429")); + } + + [TestMethod] + public void Validate_SummaryRules_Give00419_00421_00422() + { + var body = Invoice().Invoices[0]; + var missing = body with { TaxSummary = [body.TaxSummary[0]] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [missing] }).Any(p => p.Code == "00419")); + + var wrongTax = body with { TaxSummary = [body.TaxSummary[0] with { Tax = 230m }, body.TaxSummary[1]] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTax] }).Any(p => p.Code == "00421")); + + var wrongTaxable = body with { TaxSummary = [body.TaxSummary[0] with { Taxable = 1_070m, Tax = 235.40m }, body.TaxSummary[1]] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTaxable] }).Any(p => p.Code == "00422")); + } + + [TestMethod] + public void Validate_RecipientAndCustomerRules() + { + Assert.IsTrue(Validator.Validate(Invoice() with { RecipientCode = "ABC123" }).Any(p => p.Code == "00427")); + Assert.IsTrue(Validator.Validate(Invoice() with { TransmissionFormat = "FPA12" }).Any(p => p.Code == "00427")); + Assert.IsTrue(Validator.Validate(Invoice() with { RecipientPec = "a@pec.example.it" }).Any(p => p.Code == "00426")); + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = null, TaxCode = null } }).Any(p => p.Code == "00417")); + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = "09876543210" } }).Any(p => p.Code == "00305")); + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { TaxCode = "RSSMRA80A01H501X" } }).Any(p => p.Code == "00306")); + Assert.IsTrue(Validator.Validate(Invoice() with { TransmitterId = null }).Any(p => p.Code == "einvoice.transmitter")); + } + + [TestMethod] + public void Validate_SelfInvoiceRules_Give00471_00472_00473() + { + var body = Invoice().Invoices[0]; + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Company }).Any(p => p.Code == "00471")); + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD27" }] }).Any(p => p.Code == "00472")); + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD17" }] }).Any(p => p.Code == "00473")); + } + + [TestMethod] + public void Validate_WithholdingLinesWithoutData_Give00411() + { + var body = Invoice().Invoices[0]; + var withheld = body with { Lines = [body.Lines[0] with { Withheld = true }, body.Lines[1], body.Lines[2]] }; + + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [withheld] }).Any(p => p.Code == "00411")); + } + + [TestMethod] + public void Validate_ExemptOverThresholdWithoutStamp_IsAWarning() + { + var body = Invoice().Invoices[0] with + { + Lines = [new EInvoiceLine(1, [], "Servizio esente", 1m, null, 100m, 100m, 0m, "N4", [], false, null, null, null, null)], + TaxSummary = [new EInvoiceTaxSummary(0m, "N4", 100m, 0m, null, "Art. 10 DPR 633/72", null, null)], + }; + + var problem = Validator.Validate(Invoice() with { Invoices = [body] }).Single(p => p.Code == "einvoice.stamp-duty"); + + Assert.AreEqual(EInvoiceProblemSeverity.Warning, problem.Severity); + } + + [TestMethod] + public void ValidateXml_BrokenFile_ReportsSchemaErrors() + { + var xml = Encoding.UTF8.GetString(Writer.Write(Invoice())).Replace("EUR", "EURO", StringComparison.Ordinal); + + var problems = Validator.ValidateXml(Encoding.UTF8.GetBytes(xml)); + + Assert.IsTrue(problems.Any(p => p.Code == "einvoice.xml.schema")); + Assert.AreEqual("einvoice.xml.malformed", Validator.ValidateXml(Encoding.UTF8.GetBytes(" + + diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/SdiReceiptReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/SdiReceiptReaderTests.cs new file mode 100644 index 0000000..863299b --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/SdiReceiptReaderTests.cs @@ -0,0 +1,102 @@ +using System.Text; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// The notifications of the SDI (issue #75), written here in the layout of MessaggiTypes v1.0. +[TestClass] +public sealed class SdiReceiptReaderTests +{ + private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0"; + private static readonly SdiReceiptReader Reader = new(); + + /// A notification as the SDI writes it. + /// The root element. + /// The children. + /// The file. + public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes( + $"""{body}"""); + + [TestMethod] + public void Read_DeliveryReceipt() + { + var content = Notification("RicevutaConsegna", """ + 111222333IT01234567897_00001.xmlabc + 2026-10-12T15:40:10.000+02:002026-10-12T15:41:00.000+02:00 + ABC1234Officine9001 + """); + + var receipt = Reader.Read("IT01234567897_00001_RC_001.xml", content); + + Assert.AreEqual(EInvoiceReceiptKind.Delivered, receipt.Kind); + Assert.AreEqual("RC", receipt.Code); + Assert.AreEqual("IT01234567897_00001.xml", receipt.InvoiceFileName); + Assert.AreEqual("111222333", receipt.ExchangeId); + Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 15, 41, 0, TimeSpan.FromHours(2)), receipt.DeliveredAt); + Assert.AreEqual("9001", receipt.MessageId); + } + + [TestMethod] + public void Read_Rejection_ListsTheErrors() + { + var content = Notification("NotificaScarto", """ + 111222334IT01234567897_00002.xml + 2026-10-09T10:00:00 + + 003111.1.4 CodiceDestinatario non valido + 004232.2.1.11 PrezzoTotale non calcolato correttamenteVerificare + 9002 + """); + + var receipt = Reader.Read("IT01234567897_00002_NS_001.xml", content); + + Assert.AreEqual(EInvoiceReceiptKind.Rejected, receipt.Kind); + Assert.HasCount(2, receipt.Errors); + Assert.AreEqual("00311", receipt.Errors[0].Code); + Assert.AreEqual("Verificare", receipt.Errors[1].Hint); + } + + [TestMethod] + public void Read_OutcomeOfAnAdministration() + { + var content = Notification("NotificaEsito", """ + 555IT01234567897_00003.xml + 555EC02CIG errato + 9003 + """); + + var receipt = Reader.Read("IT01234567897_00003_NE_001.xml", content); + + Assert.AreEqual(EInvoiceReceiptKind.Outcome, receipt.Kind); + Assert.AreEqual("EC02", receipt.Outcome); + Assert.IsTrue(receipt.Refused); + Assert.AreEqual("CIG errato", receipt.Description); + } + + [TestMethod] + [DataRow("NotificaMancataConsegna", "MC", EInvoiceReceiptKind.NotDelivered)] + [DataRow("NotificaDecorrenzaTermini", "DT", EInvoiceReceiptKind.TermsElapsed)] + [DataRow("AttestazioneTrasmissioneFattura", "AT", EInvoiceReceiptKind.Undeliverable)] + [DataRow("FileMetadati", "MT", EInvoiceReceiptKind.Metadata)] + public void Read_OtherNotifications(string root, string code, EInvoiceReceiptKind kind) + { + var content = Notification(root, "777IT09876543217_0A1B2.xml.p7mABC12341"); + + var receipt = Reader.Read("anything.xml", content); + + Assert.AreEqual(kind, receipt.Kind); + Assert.AreEqual(code, receipt.Code); + Assert.AreEqual("777", receipt.ExchangeId); + Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", receipt.InvoiceFileName); + } + + [TestMethod] + public void IsReceipt_ByNameOrRoot_AndNotForInvoices() + { + Assert.IsTrue(Reader.IsReceipt("IT01234567897_00001_NS_001.xml", [])); + Assert.IsTrue(Reader.IsReceipt("x.xml", Notification("RicevutaConsegna", string.Empty))); + Assert.IsFalse(Reader.IsReceipt("IT01234567897_00001.xml", Encoding.UTF8.GetBytes(""))); + Assert.AreEqual("MT", SdiReceiptReader.CodeOfName("IT09876543217_0A1B2_MT_001.xml")); + Assert.ThrowsExactly(() => Reader.Read("a.xml", Encoding.UTF8.GetBytes(""))); + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/SdiTransportTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/SdiTransportTests.cs new file mode 100644 index 0000000..6348f00 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/SdiTransportTests.cs @@ -0,0 +1,345 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Text; +using System.Text.Json; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Fiscal.Italy.Sdi; +using Khaemhat.Infrastructure.Mail; +using Khaemhat.Infrastructure.Tests.Mail; + +namespace Khaemhat.Fiscal.Italy.Tests; + +[TestClass] +public sealed class PecSdiTransportTests +{ + private const string Mailbox = "fatture@pec.example.it"; + private const string Secret = "test-secret"; + + public TestContext TestContext { get; set; } = null!; + + private static EInvoiceChannelSettings Settings(FakeSmtpServer? smtp, FakeImapServer? imap, string? archive = null, string? exchange = null) => new() + { + Code = PecSdiTransport.ChannelCode, + Mailbox = Mailbox, + SmtpHost = "127.0.0.1", + SmtpPort = smtp?.Port ?? 1, + ImapHost = "127.0.0.1", + ImapPort = imap?.Port ?? 1, + Tls = false, + User = Mailbox, + Password = Secret, + ArchiveFolder = archive, + ExchangeAddress = exchange, + }; + + [TestMethod] + public async Task First_file_goes_to_sdi01_then_to_the_assigned_address() + { + await using var smtp = new FakeSmtpServer(); + var transport = new PecSdiTransport(); + var file = new EInvoiceOutgoing("IT01234567897_00001.xml", Encoding.UTF8.GetBytes(""), "FT 1/2026"); + + var first = await transport.SendAsync(Settings(smtp, null), file, TestContext.CancellationToken); + var next = await transport.SendAsync(Settings(smtp, null, exchange: "sdi23@pec.fatturapa.it"), file, TestContext.CancellationToken); + + Assert.IsTrue(first.Accepted, first.Error); + Assert.IsTrue(next.Accepted, next.Error); + var messages = smtp.Messages.ToList(); + Assert.AreEqual("sdi01@pec.fatturapa.it", messages[0].To.Single()); + Assert.AreEqual("sdi23@pec.fatturapa.it", messages[1].To.Single()); + Assert.AreEqual(Mailbox, messages[0].From); + + var sent = MimeParser.Parse(messages[0].Content); + var attachment = sent.Attachments().Single(); + Assert.AreEqual("IT01234567897_00001.xml", attachment.FileName); + CollectionAssert.AreEqual(file.Content, attachment.Body); + } + + [TestMethod] + public async Task Refused_recipient_is_reported_not_thrown() + { + await using var smtp = new FakeSmtpServer { RejectRecipient = "550 Mailbox unavailable" }; + + var result = await new PecSdiTransport().SendAsync(Settings(smtp, null), new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); + + Assert.IsFalse(result.Accepted); + StringAssert.Contains(result.Error, "550"); + } + + [TestMethod] + public async Task Fetch_reads_only_the_sdi_and_learns_its_address() + { + var receipt = Encoding.UTF8.GetBytes(""); + var invoice = Encoding.UTF8.GetBytes(""); + var metadata = Encoding.UTF8.GetBytes(""); + await using var imap = new FakeImapServer(Mailbox, Secret, + PecSamples.Envelope("sdi07@pec.fatturapa.it", "Ricevuta di consegna", ("IT01234567897_00001_RC_001.xml", receipt)), + PecSamples.Acceptance("Invio file IT01234567897_00002.xml"), + PecSamples.Envelope("sdi07@pec.fatturapa.it", "Invio File 99", ("IT09876543217_0A1B2.xml", invoice), ("IT09876543217_0A1B2_MT_001.xml", metadata))); + var transport = new PecSdiTransport(); + var settings = Settings(null, imap, archive: "Khaemhat/SDI"); + + var result = await transport.FetchAsync(settings, TestContext.CancellationToken); + + Assert.AreEqual(2, result.MessagesRead, "The acceptance of the provider is not a message of the SDI."); + CollectionAssert.AreEqual( + new[] { "IT01234567897_00001_RC_001.xml", "IT09876543217_0A1B2.xml", "IT09876543217_0A1B2_MT_001.xml" }, + result.Files.Select(f => f.FileName).ToList()); + Assert.AreEqual("sdi07@pec.fatturapa.it", result.ExchangeAddress); + Assert.AreEqual("sdi07@pec.fatturapa.it", result.Files[0].Sender); + CollectionAssert.AreEqual(receipt, result.Files[0].Content); + + await transport.AcknowledgeAsync(settings, result.Files.Select(f => f.MessageKey).ToList(), TestContext.CancellationToken); + + Assert.AreEqual(2, imap.Mailboxes["Khaemhat/SDI"].Count); + Assert.AreEqual(1, imap.Mailboxes["INBOX"].Count, "Only the acceptance of the provider is left."); + var again = await transport.FetchAsync(settings with { ExchangeAddress = "sdi07@pec.fatturapa.it" }, TestContext.CancellationToken); + Assert.AreEqual(0, again.Files.Count); + Assert.IsNull(again.ExchangeAddress, "The address did not change."); + } + + [TestMethod] + public async Task Without_archive_messages_are_marked_as_read() + { + await using var imap = new FakeImapServer(Mailbox, Secret, + PecSamples.Envelope("sdi01@pec.fatturapa.it", "Scarto", ("IT01234567897_00003_NS_001.xml", [1, 2]))); + var transport = new PecSdiTransport(); + var settings = Settings(null, imap); + + var first = await transport.FetchAsync(settings, TestContext.CancellationToken); + Assert.AreEqual(1, first.Files.Count); + Assert.AreEqual(1, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count, "Not acknowledged: read again."); + + await transport.AcknowledgeAsync(settings, [first.Files[0].MessageKey], TestContext.CancellationToken); + + Assert.AreEqual(0, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count); + Assert.IsTrue(imap.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen")); + } + + [TestMethod] + public async Task Check_reports_login_and_missing_settings() + { + await using var smtp = new FakeSmtpServer(); + await using var imap = new FakeImapServer(Mailbox, Secret); + var transport = new PecSdiTransport(); + + var ok = await transport.CheckAsync(Settings(smtp, imap), TestContext.CancellationToken); + var wrong = await transport.CheckAsync(Settings(smtp, imap) with { Password = "other" }, TestContext.CancellationToken); + var missing = await transport.CheckAsync(new EInvoiceChannelSettings { Code = "PEC" }, TestContext.CancellationToken); + + Assert.IsTrue(ok.Success, ok.Message); + Assert.IsFalse(wrong.Success); + Assert.IsFalse(wrong.Message.Contains("other", StringComparison.Ordinal), "The password must not appear."); + Assert.IsFalse(missing.Success); + } + + [TestMethod] + public void Sdi_addresses_are_recognised() + { + Assert.AreEqual("sdi07@pec.fatturapa.it", PecSdiTransport.SdiAddress("\"Per conto di: SDI07@pec.fatturapa.it\" ")); + Assert.IsNull(PecSdiTransport.SdiAddress("info@fatturapa.it")); + } +} + +/// An HTTP handler that answers from a function and keeps the requests (with their bodies). +internal sealed class StubHandler(Func answer, ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)> log) : HttpMessageHandler +{ + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? [] : await request.Content.ReadAsByteArrayAsync(cancellationToken); + log.Enqueue((request, body)); + return answer(request, body); + } +} + +[TestClass] +public sealed class SdiCoopTransportTests +{ + public TestContext TestContext { get; set; } = null!; + + private static HttpResponseMessage Soap(string body) => new(HttpStatusCode.OK) + { + Content = new StringContent( + "" + body + "", + Encoding.UTF8, + "text/xml"), + }; + + [TestMethod] + public async Task Send_posts_mtom_and_reads_the_identifier() + { + var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); + var transport = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap( + "1112223332026-11-13T10:00:00.000+01:00"), log)); + var content = Encoding.UTF8.GetBytes(""); + var settings = new EInvoiceChannelSettings { Code = "SDICOOP", TestEnvironment = true }; + + var result = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", content, null), TestContext.CancellationToken); + + Assert.IsTrue(result.Accepted, result.Error); + Assert.AreEqual("111222333", result.ExchangeId); + var (request, body) = log.Single(); + Assert.AreEqual(SdiCoopTransport.TestEndpoint, request.RequestUri!.ToString()); + Assert.AreEqual("multipart/related", request.Content!.Headers.ContentType!.MediaType); + Assert.AreEqual("\"" + SdiCoopTransport.RiceviFileAction + "\"", request.Headers.GetValues("SOAPAction").Single()); + + // What the SDI would read: the envelope with the file put back in place of the reference. + var envelope = SdiCoopMessages.Envelope(request.Content.Headers.ContentType.ToString(), body)!; + Assert.AreEqual("IT01234567897_00001.xml", envelope.Descendants().Single(e => e.Name.LocalName == "NomeFile").Value); + CollectionAssert.AreEqual(content, Convert.FromBase64String(envelope.Descendants().Single(e => e.Name.LocalName == "File").Value)); + } + + [TestMethod] + public async Task Errors_of_the_service_are_reported() + { + var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); + var error = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("EI03"), log)); + var fault = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("xBad request"), log)); + var settings = new EInvoiceChannelSettings { Code = "SDICOOP" }; + var file = new EInvoiceOutgoing("a.xml", [1], null); + + var refused = await error.SendAsync(settings, file, TestContext.CancellationToken); + var faulted = await fault.SendAsync(settings, file, TestContext.CancellationToken); + var noCertificate = await new SdiCoopTransport().SendAsync(settings, file, TestContext.CancellationToken); + + StringAssert.Contains(refused.Error, "EI03"); + StringAssert.Contains(faulted.Error, "Bad request"); + Assert.IsFalse(noCertificate.Accepted); + Assert.AreEqual(SdiCoopTransport.ProductionEndpoint, SdiCoopTransport.EndpointOf(settings)); + } + + [TestMethod] + public void Inbound_messages_are_read_inline_and_mtom() + { + var receipt = Convert.ToBase64String(Encoding.UTF8.GetBytes("")); + var inline = Encoding.UTF8.GetBytes( + "" + + "42IT01234567897_00001_NS_001.xml" + receipt + ""); + + var notification = SdiCoopMessages.Read("text/xml; charset=utf-8", inline)!; + + Assert.AreEqual("Notifica", notification.Operation); + Assert.AreEqual("42", notification.ExchangeId); + Assert.AreEqual("", Encoding.UTF8.GetString(notification.Files.Single().Content)); + Assert.IsFalse(SdiCoopMessages.Answer(notification).Contains("ER01", StringComparison.Ordinal)); + + const string Boundary = "uuid:b1"; + var mtom = Encoding.UTF8.GetBytes( + "--" + Boundary + "\r\nContent-Type: application/xop+xml; type=\"text/xml\"\r\nContent-ID: \r\n\r\n" + + "" + + "77IT09876543217_0A1B2.xml.p7m" + + "IT09876543217_0A1B2_MT_001.xml" + + "\r\n" + + "--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: \r\n\r\nP7M\r\n" + + "--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-ID: \r\n\r\n\r\n" + + "--" + Boundary + "--\r\n"); + + var invoice = SdiCoopMessages.Read("multipart/related; type=\"application/xop+xml\"; boundary=\"" + Boundary + "\"", mtom)!; + + Assert.AreEqual("RiceviFatture", invoice.Operation); + Assert.AreEqual("77", invoice.ExchangeId); + Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", invoice.Files[0].FileName); + Assert.AreEqual("P7M", Encoding.UTF8.GetString(invoice.Files[0].Content)); + Assert.AreEqual("", Encoding.UTF8.GetString(invoice.Files[1].Content)); + StringAssert.Contains(SdiCoopMessages.Answer(invoice), "ER01"); + Assert.IsNull(SdiCoopMessages.Read("text/xml", Encoding.UTF8.GetBytes(""))); + StringAssert.Contains(SdiCoopMessages.Answer(null), "Fault"); + } +} + +[TestClass] +public sealed class IntermediaryTransportTests +{ + public TestContext TestContext { get; set; } = null!; + + private static HttpResponseMessage Json(object value, HttpStatusCode status = HttpStatusCode.OK) => + new(status) { Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json") }; + + [TestMethod] + public async Task Intermediary_a_sends_lists_and_acknowledges() + { + var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>(); + var waiting = Convert.ToBase64String(Encoding.UTF8.GetBytes("")); + var transport = new IntermediaryATransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch + { + ("POST", "/v1/invoices") => Json(new { id = "up-1", sdiId = (string?)null }), + ("GET", "/v1/files") => Json(new[] { new { id = "f-9", fileName = "IT01234567897_00001_RC_001.xml", content = waiting, receivedAt = "2026-11-13T09:00:00Z" } }), + ("POST", "/v1/files/f-9/ack") => new HttpResponseMessage(HttpStatusCode.NoContent), + ("GET", "/v1/status") => Json(new { ok = true }), + _ => new HttpResponseMessage(HttpStatusCode.NotFound), + }, log)); + var settings = new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://int-a.example/v1/", ApiKey = "test-key" }; + + var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", [1, 2, 3], null), TestContext.CancellationToken); + var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken); + await transport.AcknowledgeAsync(settings, [fetched.Files[0].MessageKey], TestContext.CancellationToken); + var check = await transport.CheckAsync(settings, TestContext.CancellationToken); + + Assert.IsTrue(sent.Accepted, sent.Error); + Assert.AreEqual("up-1", sent.MessageId); + var post = log.First(); + Assert.AreEqual("Bearer", post.Request.Headers.Authorization!.Scheme); + Assert.AreEqual("IT01234567897_00001.xml", post.Request.Headers.GetValues("X-File-Name").Single()); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, post.Body); + Assert.AreEqual("IT01234567897_00001_RC_001.xml", fetched.Files.Single().FileName); + Assert.AreEqual("", Encoding.UTF8.GetString(fetched.Files[0].Content)); + Assert.IsTrue(log.Any(l => l.Request.RequestUri!.AbsolutePath == "/v1/files/f-9/ack")); + Assert.IsTrue(check.Success, check.Message); + } + + [TestMethod] + public async Task Intermediary_b_uses_basic_authentication_and_json() + { + var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>(); + var transport = new IntermediaryBTransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch + { + ("POST", "/api/v1/send") => Json(new { uploadId = "u-5", identificativoSdi = "998877" }), + ("GET", "/api/v1/inbox") => Json(new { items = new[] { new { key = "k1", name = "IT09876543217_0A1B2.xml", data = Convert.ToBase64String([9]), date = "2026-11-12" } } }), + ("DELETE", "/api/v1/inbox/k1") => new HttpResponseMessage(HttpStatusCode.OK), + ("GET", "/api/v1/ping") => new HttpResponseMessage(HttpStatusCode.Unauthorized), + _ => new HttpResponseMessage(HttpStatusCode.NotFound), + }, log)); + var settings = new EInvoiceChannelSettings { Code = "INTB", Endpoint = "https://int-b.example", User = "azienda", Password = "test-secret" }; + + var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00002.xml", [7], null), TestContext.CancellationToken); + var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken); + await transport.AcknowledgeAsync(settings, ["k1"], TestContext.CancellationToken); + var check = await transport.CheckAsync(settings, TestContext.CancellationToken); + var missing = await transport.SendAsync(settings with { Password = null }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); + + Assert.AreEqual("998877", sent.ExchangeId); + Assert.AreEqual("Basic", log.First().Request.Headers.Authorization!.Scheme); + using (var body = JsonDocument.Parse(log.First().Body)) + { + Assert.AreEqual("IT01234567897_00002.xml", body.RootElement.GetProperty("fileName").GetString()); + } + + Assert.AreEqual("k1", fetched.Files.Single().MessageKey); + Assert.IsTrue(log.Any(l => l.Request.Method == HttpMethod.Delete)); + Assert.IsFalse(check.Success); + Assert.IsFalse(missing.Accepted); + } + + [TestMethod] + public async Task Refused_file_is_reported_with_the_message_of_the_api() + { + var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); + var transport = new IntermediaryATransport(_ => new StubHandler((_, _) => Json(new { error = "Invalid XML" }, HttpStatusCode.UnprocessableEntity), log)); + + var result = await transport.SendAsync( + new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://a.example", ApiKey = "k" }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); + + Assert.IsFalse(result.Accepted); + Assert.AreEqual("422: Invalid XML", result.Error); + } + + [TestMethod] + public void The_pack_offers_the_four_channels() + { + var channels = new ItalyFiscalPack().GetFeature()!; + + CollectionAssert.AreEqual(new[] { "PEC", "SDICOOP", "INTA", "INTB" }, channels.All.Select(c => c.Code).ToList()); + Assert.IsFalse(channels.Find("sdicoop")!.Transport.Polls); + Assert.IsNull(channels.Find("X")); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs b/tests/Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs new file mode 100644 index 0000000..3ffc8cb --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs @@ -0,0 +1,477 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.RegularExpressions; + +namespace Khaemhat.Infrastructure.Tests.Mail; + +/// A message held by . +internal sealed class FakeImapMessage(long uid, byte[] content) +{ + public long Uid { get; } = uid; + + public byte[] Content { get; } = content; + + public HashSet Flags { get; } = new(StringComparer.OrdinalIgnoreCase); +} + +/// +/// An IMAP server on the loopback interface, enough for the tests of the client and of the PEC channel: CAPABILITY, +/// LOGIN (quoted or literal), SELECT, UID SEARCH (ALL, UNSEEN, FROM, SINCE ignored), UID FETCH, UID STORE, UID MOVE, +/// UID COPY (NO [TRYCREATE] for a missing folder), CREATE, EXPUNGE, UID EXPUNGE, LOGOUT. One connection at a time. +/// +internal sealed partial class FakeImapServer : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _stop = new(); + private readonly Task _loop; + private long _nextUid = 100; + + public FakeImapServer(string user, string password, params byte[][] messages) + { + User = user; + Password = password; + Mailboxes["INBOX"] = [.. messages.Select(m => new FakeImapMessage(_nextUid++, m))]; + _listener.Start(); + _loop = Task.Run(AcceptAsync); + } + + public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; + + public string User { get; } + + public string Password { get; } + + /// Whether MOVE and UIDPLUS are announced. + public bool SupportsMove { get; init; } = true; + + public ConcurrentDictionary> Mailboxes { get; } = new(StringComparer.OrdinalIgnoreCase); + + public ConcurrentQueue Commands { get; } = new(); + + public void Add(byte[] message) => Mailboxes["INBOX"].Add(new FakeImapMessage(_nextUid++, message)); + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + try + { + await _loop; + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + } + + _stop.Dispose(); + } + + private async Task AcceptAsync() + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + return; + } + + using (client) + { + try + { + await ServeAsync(client.GetStream()); + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) + { + } + } + } + } + + private async Task ServeAsync(NetworkStream stream) + { + var reader = new LineReader(stream); + async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token); + await Send("* OK Fake IMAP ready"); + var authenticated = false; + List? selected = null; + while (true) + { + var (line, literals) = await reader.CommandAsync(() => Send("+ go ahead"), _stop.Token); + if (line is null) + { + return; + } + + Commands.Enqueue(line); + var space = line.IndexOf(' ', StringComparison.Ordinal); + var tag = line[..space]; + var rest = line[(space + 1)..]; + var verb = rest.Split(' ')[0].ToUpperInvariant(); + if (verb == "UID") + { + verb = "UID " + rest.Split(' ')[1].ToUpperInvariant(); + } + + switch (verb) + { + case "CAPABILITY": + await Send("* CAPABILITY IMAP4rev1" + (SupportsMove ? " MOVE UIDPLUS" : string.Empty)); + await Send(tag + " OK CAPABILITY completed"); + break; + case "LOGIN": + var values = Arguments(rest[6..], literals); + authenticated = values.Count == 2 && values[0] == User && values[1] == Password; + await Send(tag + (authenticated ? " OK LOGIN completed" : " NO [AUTHENTICATIONFAILED] Invalid credentials")); + break; + case "SELECT" when authenticated: + var name = Arguments(rest[7..], literals)[0]; + selected = Mailboxes.GetValueOrDefault(name); + await Send(selected is null ? tag + " NO Mailbox does not exist" : $"* {selected.Count} EXISTS"); + if (selected is not null) + { + await Send(tag + " OK [READ-WRITE] SELECT completed"); + } + + break; + case "UID SEARCH" when selected is not null: + var criteria = rest[11..]; + var found = selected.Where(m => + (!criteria.Contains("UNSEEN", StringComparison.OrdinalIgnoreCase) || !m.Flags.Contains(@"\Seen")) + && !m.Flags.Contains(@"\Deleted") + && (FromPattern().Match(criteria) is not { Success: true } from + || Encoding.Latin1.GetString(m.Content).Contains(from.Groups["v"].Value, StringComparison.OrdinalIgnoreCase))); + await Send("* SEARCH " + string.Join(' ', found.Select(m => m.Uid.ToString(CultureInfo.InvariantCulture)))); + await Send(tag + " OK SEARCH completed"); + break; + case "UID FETCH" when selected is not null: + var fetchUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture); + var message = selected.FirstOrDefault(m => m.Uid == fetchUid); + if (message is not null) + { + var index = selected.IndexOf(message) + 1; + await stream.WriteAsync(Encoding.ASCII.GetBytes($"* {index} FETCH (UID {message.Uid} BODY[] {{{message.Content.Length}}}\r\n"), _stop.Token); + await stream.WriteAsync(message.Content, _stop.Token); + await Send(")"); + } + + await Send(tag + " OK FETCH completed"); + break; + case "UID STORE" when selected is not null: + var storeUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture); + var flags = rest[(rest.IndexOf('(', StringComparison.Ordinal) + 1)..rest.LastIndexOf(')')]; + foreach (var m in selected.Where(m => m.Uid == storeUid)) + { + m.Flags.UnionWith(flags.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + } + + await Send(tag + " OK STORE completed"); + break; + case "UID MOVE" or "UID COPY" when selected is not null: + var parts = rest.Split(' ', 4); + var uid = long.Parse(parts[2], CultureInfo.InvariantCulture); + var target = Arguments(parts[3], literals)[0]; + if (!Mailboxes.TryGetValue(target, out var targetBox)) + { + await Send(tag + " NO [TRYCREATE] Mailbox does not exist"); + break; + } + + foreach (var m in selected.Where(m => m.Uid == uid).ToList()) + { + targetBox.Add(new FakeImapMessage(_nextUid++, m.Content)); + if (verb == "UID MOVE") + { + selected.Remove(m); + } + } + + await Send(tag + " OK done"); + break; + case "CREATE" when authenticated: + Mailboxes.TryAdd(Arguments(rest[7..], literals)[0], []); + await Send(tag + " OK CREATE completed"); + break; + case "EXPUNGE" or "UID EXPUNGE" when selected is not null: + selected.RemoveAll(m => m.Flags.Contains(@"\Deleted")); + await Send(tag + " OK EXPUNGE completed"); + break; + case "LOGOUT": + await Send("* BYE Logging out"); + await Send(tag + " OK LOGOUT completed"); + return; + default: + await Send(tag + " BAD Unknown or not allowed: " + verb); + break; + } + } + } + + // The arguments: quoted strings, atoms, and {n} literals taken in order. + private static List Arguments(string text, Queue literals) + { + var values = new List(); + var i = 0; + while (i < text.Length) + { + if (text[i] == ' ') + { + i++; + } + else if (text[i] == '"') + { + var value = new StringBuilder(); + i++; + while (i < text.Length && text[i] != '"') + { + if (text[i] == '\\') + { + i++; + } + + value.Append(text[i]); + i++; + } + + values.Add(value.ToString()); + i++; + } + else if (text[i] == '{') + { + values.Add(Encoding.UTF8.GetString(literals.Dequeue())); + i = text.IndexOf('}', i) + 1; + } + else + { + var end = text.IndexOf(' ', i); + values.Add(end < 0 ? text[i..] : text[i..end]); + i = end < 0 ? text.Length : end; + } + } + + return values; + } + + [GeneratedRegex("FROM \"(?[^\"]*)\"", RegexOptions.IgnoreCase)] + private static partial Regex FromPattern(); +} + +/// An SMTP server on the loopback interface that keeps every message it receives (no TLS). +internal sealed class FakeSmtpServer : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _stop = new(); + private readonly Task _loop; + + public FakeSmtpServer() + { + _listener.Start(); + _loop = Task.Run(AcceptAsync); + } + + public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; + + /// The messages: sender, recipients, raw content. + public ConcurrentQueue<(string From, IReadOnlyList To, byte[] Content)> Messages { get; } = new(); + + /// When set, RCPT TO is refused with this reply. + public string? RejectRecipient { get; set; } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + try + { + await _loop; + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + } + + _stop.Dispose(); + } + + private async Task AcceptAsync() + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + return; + } + + using (client) + { + try + { + await ServeAsync(client.GetStream()); + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) + { + } + } + } + } + + private async Task ServeAsync(NetworkStream stream) + { + var reader = new LineReader(stream); + async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token); + await Send("220 fake.smtp ESMTP"); + string from = string.Empty; + var to = new List(); + while (true) + { + var line = await reader.LineAsync(_stop.Token); + if (line is null) + { + return; + } + + var upper = line.ToUpperInvariant(); + if (upper.StartsWith("EHLO", StringComparison.Ordinal)) + { + await Send("250-fake.smtp"); + await Send("250 AUTH PLAIN LOGIN"); + } + else if (upper.StartsWith("AUTH PLAIN", StringComparison.Ordinal)) + { + await Send("235 Authenticated"); + } + else if (upper.StartsWith("MAIL FROM:", StringComparison.Ordinal)) + { + from = line[10..].Trim('<', '>', ' '); + to.Clear(); + await Send("250 OK"); + } + else if (upper.StartsWith("RCPT TO:", StringComparison.Ordinal)) + { + if (RejectRecipient is not null) + { + await Send(RejectRecipient); + continue; + } + + to.Add(line[8..].Trim('<', '>', ' ')); + await Send("250 OK"); + } + else if (upper == "DATA") + { + await Send("354 End data with ."); + var data = new StringBuilder(); + while (await reader.LineAsync(_stop.Token) is { } dataLine && dataLine != ".") + { + data.Append(dataLine.StartsWith("..", StringComparison.Ordinal) ? dataLine[1..] : dataLine).Append("\r\n"); + } + + Messages.Enqueue((from, [.. to], Encoding.Latin1.GetBytes(data.ToString()))); + await Send("250 OK queued"); + } + else if (upper == "QUIT") + { + await Send("221 Bye"); + return; + } + else + { + await Send("502 Not implemented"); + } + } + } +} + +/// Reads CRLF lines and IMAP literals from a stream. +internal sealed class LineReader(Stream stream) +{ + private readonly byte[] _buffer = new byte[8192]; + private int _start; + private int _end; + + public async Task LineAsync(CancellationToken cancellationToken) + { + using var line = new MemoryStream(); + while (true) + { + if (_start == _end) + { + _start = 0; + _end = await stream.ReadAsync(_buffer, cancellationToken); + if (_end == 0) + { + return null; + } + } + + var index = Array.IndexOf(_buffer, (byte)'\n', _start, _end - _start); + if (index < 0) + { + line.Write(_buffer, _start, _end - _start); + _start = _end; + continue; + } + + line.Write(_buffer, _start, index - _start); + _start = index + 1; + return Encoding.Latin1.GetString(line.ToArray()).TrimEnd('\r'); + } + } + + // A command line with its literals: after each {n} the server says "+" and reads n bytes. + public async Task<(string? Line, Queue Literals)> CommandAsync(Func continuation, CancellationToken cancellationToken) + { + var text = new StringBuilder(); + var literals = new Queue(); + while (true) + { + var line = await LineAsync(cancellationToken); + if (line is null) + { + return (null, literals); + } + + text.Append(line); + var match = Regex.Match(line, @"\{(?[0-9]+)\}$"); + if (!match.Success) + { + return (text.ToString(), literals); + } + + await continuation(); + var length = int.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture); + var bytes = new byte[length]; + var read = 0; + while (read < length) + { + if (_start == _end) + { + _start = 0; + _end = await stream.ReadAsync(_buffer, cancellationToken); + if (_end == 0) + { + return (null, literals); + } + } + + var take = Math.Min(length - read, _end - _start); + Array.Copy(_buffer, _start, bytes, read, take); + _start += take; + read += take; + } + + literals.Enqueue(bytes); + } + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs b/tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs new file mode 100644 index 0000000..1e17af0 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs @@ -0,0 +1,151 @@ +using System.Text; +using Khaemhat.Infrastructure.Mail; + +namespace Khaemhat.Infrastructure.Tests.Mail; + +[TestClass] +public sealed class MimeParserTests +{ + [TestMethod] + public void Certified_mail_gives_the_files_of_the_enclosed_message() + { + var receipt = Encoding.UTF8.GetBytes(""); + var message = MimeParser.Parse(PecSamples.Envelope("sdi07@pec.fatturapa.it", "Consegna", ("IT01234567897_00001_RC_001.xml", receipt))); + + Assert.AreEqual("multipart/signed", message.MediaType); + Assert.AreEqual("POSTA CERTIFICATA: Consegna", message.Header("Subject")); + var envelope = message.Parts[0]; + var original = envelope.Parts.Single(p => p.MediaType == "message/rfc822"); + Assert.AreEqual("postacert.eml", original.FileName); + Assert.IsNotNull(original.Enclosed); + Assert.AreEqual("sdi07@pec.fatturapa.it", original.Enclosed.Header("from")); + var file = original.Enclosed.Attachments().Single(); + Assert.AreEqual("IT01234567897_00001_RC_001.xml", file.FileName); + CollectionAssert.AreEqual(receipt, file.Body); + + var all = message.Attachments().Select(a => a.FileName).ToList(); + CollectionAssert.AreEqual(new[] { "daticert.xml", "IT01234567897_00001_RC_001.xml", "smime.p7s" }, all); + StringAssert.Contains(envelope.Parts[0].Text(), "il messaggio originale è allegato"); + } + + [TestMethod] + public void Encoded_words_are_decoded_and_joined() + { + Assert.AreEqual("Fattura n° 12", MimeParser.DecodeHeader("=?utf-8?Q?Fattura_n=C2=B0?= 12")); + Assert.AreEqual("perché sì", MimeParser.DecodeHeader("=?iso-8859-1?Q?perch=E9?= =?iso-8859-1?Q?_s=EC?=")); + Assert.AreEqual("città", MimeParser.DecodeHeader("=?UTF-8?B?Y2l0dMOg?=")); + Assert.AreEqual("plain =? text", MimeParser.DecodeHeader("plain =? text")); + } + + [TestMethod] + public void File_names_follow_rfc_2231() + { + var message = Encoding.ASCII.GetBytes( + "Content-Type: multipart/mixed; boundary=b\r\n\r\n" + + "--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment; filename*=utf-8''fattura%20citt%C3%A0.xml\r\n\r\n\r\n" + + "--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment;\r\n filename*0=\"IT0123_\"; filename*1=\"00001.xml\"\r\n\r\n\r\n" + + "--b\r\nContent-Type: application/xml; name=\"=?utf-8?Q?n=C2=B0.xml?=\"\r\n\r\n\r\n" + + "--b--\r\n"); + + var names = MimeParser.Parse(message).Attachments().Select(a => a.FileName).ToList(); + + CollectionAssert.AreEqual(new[] { "fattura città.xml", "IT0123_00001.xml", "n°.xml" }, names); + } + + [TestMethod] + public void Quoted_printable_and_broken_input_do_not_throw() + { + CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("a=b c"), MimeParser.QuotedPrintable(Encoding.ASCII.GetBytes("a=3Db =\r\nc"))); + CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("ab"), MimeParser.Base64(Encoding.ASCII.GetBytes("YW\r\nI="))); + + var unclosed = MimeParser.Parse(Encoding.ASCII.GetBytes("Content-Type: multipart/mixed; boundary=x\r\n\r\n--x\r\nContent-Type: text/plain\r\n\r\nhello")); + Assert.AreEqual("hello", unclosed.Parts.Single().Text()); + + var noHeaders = MimeParser.Parse(Encoding.ASCII.GetBytes("just text")); + Assert.AreEqual("text/plain", noHeaders.MediaType); + } +} + +[TestClass] +public sealed class ImapClientTests +{ + private static readonly byte[] First = PecSamples.Envelope("sdi01@pec.fatturapa.it", "Uno", ("IT01234567897_00001_RC_001.xml", [1])); + private static readonly byte[] Second = PecSamples.Acceptance("Due"); + + [TestMethod] + public async Task Search_fetch_flag_and_move() + { + await using var server = new FakeImapServer("fatture@pec.example.it", "segreto", First, Second); + var token = TestContext.CancellationToken; + await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "fatture@pec.example.it", "segreto"), token); + await imap.LoginAsync("fatture@pec.example.it", "segreto", token); + Assert.IsTrue(imap.Capabilities.Contains("MOVE")); + + Assert.AreEqual(2, await imap.SelectAsync("INBOX", token)); + var uids = await imap.SearchAsync("UNSEEN FROM " + ImapClient.Quote("fatturapa.it"), token); + Assert.AreEqual(1, uids.Count); + + var message = await imap.FetchAsync(uids[0], token); + Assert.IsNotNull(message); + CollectionAssert.AreEqual(First, message.Content); + Assert.IsFalse(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen"), "BODY.PEEK must not mark the message."); + + await imap.AddFlagsAsync(uids[0], @"\Seen", token); + Assert.IsTrue(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen")); + Assert.AreEqual(0, (await imap.SearchAsync("UNSEEN FROM \"fatturapa.it\"", token)).Count); + + await imap.MoveAsync(uids[0], "Khaemhat/SDI", token); + Assert.AreEqual(1, server.Mailboxes["Khaemhat/SDI"].Count); + Assert.AreEqual(1, server.Mailboxes["INBOX"].Count); + Assert.IsNull(await imap.FetchAsync(uids[0], token)); + await imap.LogoutAsync(token); + } + + [TestMethod] + public async Task Without_move_the_message_is_copied_and_expunged() + { + await using var server = new FakeImapServer("u", "p", First) { SupportsMove = false }; + server.Mailboxes["Archivio"] = []; + var token = TestContext.CancellationToken; + await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "p"), token); + await imap.LoginAsync("u", "p", token); + await imap.SelectAsync("INBOX", token); + + await imap.MoveAsync((await imap.SearchAsync("ALL", token))[0], "Archivio", token); + + Assert.AreEqual(0, server.Mailboxes["INBOX"].Count); + Assert.AreEqual(1, server.Mailboxes["Archivio"].Count); + Assert.IsTrue(server.Commands.Any(c => c.Contains("UID COPY", StringComparison.Ordinal))); + Assert.IsTrue(server.Commands.Any(c => c.EndsWith("EXPUNGE", StringComparison.Ordinal))); + } + + [TestMethod] + public async Task Password_with_accents_goes_as_a_literal_and_wrong_password_fails() + { + await using var server = new FakeImapServer("u", "pàssword"); + var token = TestContext.CancellationToken; + await using (var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "pàssword"), token)) + { + await imap.LoginAsync("u", "pàssword", token); + } + + Assert.IsTrue(server.Commands.Any(c => c.StartsWith("K0002 LOGIN \"u\" {", StringComparison.Ordinal))); + + await using var wrong = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "x"), token); + var error = await Assert.ThrowsExactlyAsync(() => wrong.LoginAsync("u", "x", token)); + StringAssert.Contains(error.Message, "LOGIN ***"); + Assert.IsFalse(error.Message.Contains("\"x\"", StringComparison.Ordinal), "The password must not appear in the error."); + } + + [TestMethod] + public async Task Unreachable_server_gives_a_mail_exception() + { + var settings = new ImapSettings("127.0.0.1", 1, false, "u", "p"); + await Assert.ThrowsExactlyAsync(() => ImapClient.ConnectAsync(settings, TestContext.CancellationToken)); + Assert.AreEqual("127.0.0.1:1", settings.ToString()); + Assert.AreEqual("1-Nov-2026", ImapClient.SearchDate(new DateOnly(2026, 11, 1))); + Assert.ThrowsExactly(() => ImapClient.Quote("città")); + } + + public TestContext TestContext { get; set; } = null!; +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs b/tests/Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs new file mode 100644 index 0000000..28b7961 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs @@ -0,0 +1,86 @@ +using System.Text; + +namespace Khaemhat.Infrastructure.Tests.Mail; + +/// +/// Certified mail messages built in the test, shaped like the ones a PEC provider delivers: a multipart/mixed +/// envelope with the text of the provider, daticert.xml, the original message as postacert.eml +/// (message/rfc822) and the signature smime.p7s. Nothing is downloaded. +/// +internal static class PecSamples +{ + /// A certified message whose original was sent by with the given files. + public static byte[] Envelope(string sender, string subject, params (string Name, byte[] Content)[] files) + { + var inner = new StringBuilder() + .Append("From: ").Append(sender).Append("\r\n") + .Append("To: fatture@pec.example.it\r\n") + .Append("Subject: ").Append(subject).Append("\r\n") + .Append("MIME-Version: 1.0\r\n") + .Append("Content-Type: multipart/mixed; boundary=\"inner-b\"\r\n\r\n") + .Append("--inner-b\r\n") + .Append("Content-Type: text/plain; charset=utf-8\r\n\r\n") + .Append("Messaggio del Sistema di Interscambio\r\n"); + foreach (var (name, content) in files) + { + inner.Append("--inner-b\r\n") + .Append("Content-Type: application/octet-stream; name=\"").Append(name).Append("\"\r\n") + .Append("Content-Transfer-Encoding: base64\r\n") + .Append("Content-Disposition: attachment; filename=\"").Append(name).Append("\"\r\n\r\n") + .Append(Wrap(Convert.ToBase64String(content))).Append("\r\n"); + } + + inner.Append("--inner-b--\r\n"); + + var outer = new StringBuilder() + .Append("From: \"Per conto di: ").Append(sender).Append("\" \r\n") + .Append("To: fatture@pec.example.it\r\n") + .Append("Subject: =?utf-8?B?").Append(Convert.ToBase64String(Encoding.UTF8.GetBytes("POSTA CERTIFICATA: " + subject))).Append("?=\r\n") + .Append("X-Trasporto: posta-certificata\r\n") + .Append("MIME-Version: 1.0\r\n") + .Append("Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha-256;\r\n boundary=\"signed-b\"\r\n\r\n") + .Append("--signed-b\r\n") + .Append("Content-Type: multipart/mixed; boundary=\"outer-b\"\r\n\r\n") + .Append("--outer-b\r\n") + .Append("Content-Type: text/plain; charset=iso-8859-1\r\n") + .Append("Content-Transfer-Encoding: quoted-printable\r\n\r\n") + .Append("Messaggio di posta certificata: il messaggio originale =E8 allegato.\r\n") + .Append("--outer-b\r\n") + .Append("Content-Type: application/xml; name=daticert.xml\r\n") + .Append("Content-Disposition: inline; filename=daticert.xml\r\n\r\n") + .Append("\r\n") + .Append("--outer-b\r\n") + .Append("Content-Type: message/rfc822; name=postacert.eml\r\n") + .Append("Content-Disposition: inline; filename=postacert.eml\r\n\r\n") + .Append(inner) + .Append("--outer-b--\r\n") + .Append("--signed-b\r\n") + .Append("Content-Type: application/pkcs7-signature; name=smime.p7s\r\n") + .Append("Content-Transfer-Encoding: base64\r\n") + .Append("Content-Disposition: attachment; filename=smime.p7s\r\n\r\n") + .Append(Convert.ToBase64String([1, 2, 3, 4])).Append("\r\n") + .Append("--signed-b--\r\n"); + return Encoding.UTF8.GetBytes(outer.ToString()); + } + + /// The acceptance receipt of the provider: no original message, no files of the SDI. + public static byte[] Acceptance(string subject) => Encoding.UTF8.GetBytes( + "From: posta-certificata@pec.provider.example\r\n" + + "Subject: ACCETTAZIONE: " + subject + "\r\n" + + "X-Ricevuta: accettazione\r\n" + + "Content-Type: multipart/mixed; boundary=\"a\"\r\n\r\n" + + "--a\r\nContent-Type: text/plain\r\n\r\nIl messaggio e' stato accettato dal sistema.\r\n" + + "--a\r\nContent-Type: application/xml; name=daticert.xml\r\nContent-Disposition: attachment; filename=daticert.xml\r\n\r\n\r\n" + + "--a--\r\n"); + + private static string Wrap(string base64) + { + var lines = new StringBuilder(); + for (var i = 0; i < base64.Length; i += 76) + { + lines.Append(base64, i, Math.Min(76, base64.Length - i)).Append("\r\n"); + } + + return lines.ToString().TrimEnd(); + } +} diff --git a/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs b/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs new file mode 100644 index 0000000..e7efe40 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs @@ -0,0 +1,301 @@ +using System.IO.Compression; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.EInvoicing; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Application.Seeding; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.EInvoicing; + +/// +/// The electronic invoice on a real instance (issues #74-#80): the demo files checked against the schema with their +/// notifications, a rejected invoice corrected and generated again, notifications imported by hand, the invoices +/// received registered as supplier documents, the conservation package, the courtesy copy and the removal of the demo +/// data. +/// +[TestClass] +public sealed class EInvoiceTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task DemoEInvoices_AreValid_AndFollowTheirNotifications() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var service = app.Services.GetRequiredService(); + var dashboard = await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.Issued)); + var counters = dashboard.Counters; + TestContext.WriteLine($"Rows {dashboard.Rows.Count}, pending {dashboard.Pending.Count}, {counters}"); + Assert.IsGreaterThanOrEqualTo(5, dashboard.Rows.Count, "The demo invoices have their files."); + Assert.IsGreaterThan(0, counters.Delivered); + Assert.AreEqual(DemoEInvoiceSeeder.LeftToSend, counters.ToSend); + Assert.IsGreaterThanOrEqualTo(DemoEInvoiceSeeder.LeftToGenerate, counters.ToGenerate); + Assert.AreEqual(DemoEInvoiceSeeder.LeftWaiting, counters.Waiting); + Assert.AreEqual(3, counters.Received); + + // Every file is valid for the schema, and the document follows its e-invoice. + var pack = await app.Services.GetRequiredService().PackOfAsync(company); + var validator = pack.GetFeature()!; + var engine = app.Services.GetRequiredService(); + foreach (var row in dashboard.Rows) + { + var (name, xml) = await service.FileAsync(Root, company, row.Invoice.Id); + var problems = validator.ValidateXml(xml).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList(); + Assert.IsEmpty(problems, name + ": " + string.Join("; ", problems.Select(p => p.Path + " " + p.Message))); + var document = await engine.GetAsync(Root, company, row.Invoice.Family, row.Invoice.DocumentId); + Assert.AreEqual(EInvoiceStates.DocumentStatusOf(row.Invoice.Status), document!.Header.Status, row.Invoice.FileName); + } + + // The history of a delivered invoice has its receipt. + var delivered = dashboard.Rows.First(r => r.Invoice.Status == EInvoiceStatus.Delivered).Invoice; + var history = await service.HistoryAsync(Root, company, delivered.Family, delivered.DocumentId); + Assert.AreEqual("RC", history[0].Notifications[0].Code); + Assert.IsNotNull(history[0].Invoice.ExchangeId); + + // No channel to send through: the demo PEC is paused. + var toSend = dashboard.Rows.First(r => r.Invoice.Status == EInvoiceStatus.Generated).Invoice; + var outcome = (await service.SendAsync(Root, company, [toSend.Id]))[0]; + Assert.IsFalse(outcome.Sent); + Assert.AreEqual(EInvoiceErrors.NoChannel, outcome.Error); + + // Seeding again adds nothing. + await app.Services.GetRequiredService().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true)); + Assert.HasCount(dashboard.Rows.Count, (await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.Issued))).Rows); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task ARejectedInvoice_IsCorrected_AndSentAgainWithANewFile() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var service = app.Services.GetRequiredService(); + var engine = app.Services.GetRequiredService(); + var pending = (await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.ToDo))).Pending.First(p => p.Status == DocumentStatus.Issued); + + // Generate, mark as sent from the portal, then the SDI rejects it. + var generation = await service.GenerateAsync(Root, company, pending.Family, pending.DocumentId); + Assert.IsTrue(generation.Success, string.Join("; ", generation.Problems.Select(p => p.Code + " " + p.Message))); + var first = generation.Invoice!; + Assert.AreEqual(DocumentStatus.SdiGenerated, (await engine.GetAsync(Root, company, pending.Family, pending.DocumentId))!.Header.Status); + await service.MarkSentAsync(Root, company, first.Id, "777000111"); + await Assert.ThrowsExactlyAsync(() => service.MarkSentAsync(Root, company, first.Id, null)); + var rejection = DemoEInvoiceSeeder.Notification("NotificaScarto", + $"777000111{first.FileName}2026-11-12T10:00:00" + + "00311CodiceDestinatario non valido1"); + var name = first.FileName[..first.FileName.IndexOf(".xml", StringComparison.Ordinal)] + "_NS_001.xml"; + var imported = await service.ImportReceiptsAsync(Root, company, [(name, rejection), ("altro.xml", Encoding.UTF8.GetBytes(""))]); + Assert.AreEqual(EInvoiceStatus.Rejected, imported[0].Status); + Assert.AreEqual(EInvoiceErrors.NotAReceipt, imported[1].Error); + Assert.AreEqual(EInvoiceErrors.ReceiptDuplicate, (await service.ImportReceiptsAsync(Root, company, [(name, rejection)]))[0].Error); + var document = (await engine.GetAsync(Root, company, pending.Family, pending.DocumentId))!; + Assert.AreEqual(DocumentStatus.SdiRejected, document.Header.Status); + + // The invoice can be changed now; generated again it gets a new progressive, the old file is kept. + document.Header.Notes = "Corretta dopo lo scarto"; + await engine.SaveAsync(Root, company, document); + var second = (await service.GenerateAsync(Root, company, pending.Family, pending.DocumentId)).Invoice!; + Assert.AreNotEqual(first.FileName, second.FileName); + Assert.IsGreaterThan(first.Progressive, second.Progressive); + var history = await service.HistoryAsync(Root, company, pending.Family, pending.DocumentId); + Assert.HasCount(2, history); + Assert.IsTrue(history[1].Invoice.Superseded); + Assert.AreEqual("NS", history[1].Notifications[0].Code); + + // Generated twice before sending, the same file name is kept. + Assert.AreEqual(second.FileName, (await service.GenerateAsync(Root, company, pending.Family, pending.DocumentId)).Invoice!.FileName); + + // The courtesy copy carries the XML. + var (pdfName, pdf) = await service.CourtesyCopyAsync(Root, company, second.Id); + StringAssert.EndsWith(pdfName, ".pdf"); + var text = Encoding.Latin1.GetString(pdf); + StringAssert.Contains(text, "/EmbeddedFiles"); + StringAssert.Contains(text, "/AFRelationship /Source"); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task ReceivedInvoices_AreRegistered_Discarded_AndPackedForConservation() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var inbox = app.Services.GetRequiredService(); + var rows = await inbox.ListAsync(Root, company, new InboxFilter(InboxFileStatus.New)); + Assert.HasCount(3, rows); + Assert.IsTrue(rows.All(r => r.MetadataFileName is not null && r.SupplierName is not null && r.PartyId is not null)); + + // Registered: a draft supplier invoice with the file attached. + var registered = (await inbox.RegisterAsync(Root, company, [rows[0].Id]))[0]; + Assert.IsNull(registered.Error, registered.Error); + var purchase = await app.Services.GetRequiredService().GetAsync(Root, company, DocumentFamily.PurchaseDocument, registered.PurchaseDocumentId!.Value); + Assert.AreEqual(DocumentStatus.Draft, purchase!.Header.Status); + Assert.AreEqual(EInvoiceErrors.InboxState, (await inbox.RegisterAsync(Root, company, [rows[0].Id]))[0].Error); + + // Discarded and taken back; the same file uploaded again is not kept twice. + await inbox.DiscardAsync(Root, company, rows[1].Id, discard: true); + Assert.HasCount(1, await inbox.ListAsync(Root, company, new InboxFilter(InboxFileStatus.Discarded))); + await inbox.DiscardAsync(Root, company, rows[1].Id, discard: false); + var (fileName, content) = await inbox.FileAsync(Root, company, rows[1].Id); + Assert.AreEqual(EInvoiceErrors.InboxDuplicate, (await inbox.UploadAsync(Root, company, [(fileName, content)]))[0].Error); + var unreadable = (await inbox.UploadAsync(Root, company, [("note.xml", Encoding.UTF8.GetBytes(""))]))[0]; + Assert.AreEqual(InboxFileStatus.Unreadable, unreadable.Status); + + // The package of the year: the files as they travelled, with their hashes in the index. + var year = DateTime.Now.Year; + var package = await app.Services.GetRequiredService().ExportAsync(Root, company, new DateOnly(year - 1, 1, 1), new DateOnly(year, 12, 31)); + using var zip = new ZipArchive(new MemoryStream(package.Content)); + var names = zip.Entries.Select(e => e.FullName).ToList(); + Assert.IsTrue(names.Any(n => n.StartsWith("emesse/", StringComparison.Ordinal))); + Assert.IsTrue(names.Any(n => n.StartsWith("notifiche/", StringComparison.Ordinal))); + Assert.IsTrue(names.Any(n => n.StartsWith("ricevute/", StringComparison.Ordinal))); + using var reader = new StreamReader(zip.GetEntry("indice.csv")!.Open()); + var index = await reader.ReadToEndAsync(); + Assert.HasCount(package.Export.FileCount, index.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Skip(1)); + await Assert.ThrowsExactlyAsync(() => + app.Services.GetRequiredService().ExportAsync(Root, company, new DateOnly(year, 2, 1), new DateOnly(year, 1, 1))); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task DemoData_AreRemoved_OnlyWhenNothingOfTheUsersNeedsThem() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var factory = app.Services.GetRequiredService(); + var remover = app.Services.GetRequiredService(); + + // A mandate the user entered for a demo customer: nothing is removed, and the table is named. + long blockerId; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company))) + { + await uow.BeginAsync(); + var customer = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo && p.Kind == PartyKind.Customer).Take(1))).Items[0]; + blockerId = await uow.Repository().InsertAsync(new SddMandate + { + PartyId = customer.Id, + Reference = "UTENTE-1", + SignatureDate = new DateOnly(2026, 1, 10), + Iban = DemoTreasurySeeder.Iban('X', "05428", "11101", "000000123456"), + }); + await uow.CommitAsync(); + } + + var blocked = await remover.RemoveAsync(company); + Assert.IsFalse(blocked.Done); + CollectionAssert.AreEqual(new[] { "sdd_mandates" }, blocked.Blockers.ToArray()); + Assert.AreEqual(0, blocked.Total); + + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company))) + { + await uow.BeginAsync(); + await uow.Repository().DeleteAsync(blockerId); + await uow.CommitAsync(); + } + + var removal = await remover.RemoveAsync(company); + Assert.IsTrue(removal.Done, string.Join(", ", removal.Blockers)); + TestContext.WriteLine($"Removed {removal.Total}: " + string.Join(", ", removal.Removed.Select(r => r.Key + "=" + r.Value))); + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company))) + { + Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For().Where(p => p.IsDemo))); + Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); + Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); + Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); + Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For()), "The entries of the demo go with it."); + Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); + } + + Assert.IsTrue((await remover.RemoveAsync(company)).Done, "Running it again removes nothing and fails nothing."); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task TheSdi_PushesANotification_WithTheKeyOfTheChannel() + { + var (app, address, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var service = app.Services.GetRequiredService(); + var waiting = (await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.Issued))).Rows.First(r => r.Invoice.Status == EInvoiceStatus.Sent).Invoice; + var receipt = DemoEInvoiceSeeder.Notification("RicevutaConsegna", + $"{waiting.ExchangeId ?? "555000111"}{waiting.FileName}x" + + "2026-11-12T10:00:002026-11-12T10:05:009"); + var stem = waiting.FileName[..waiting.FileName.IndexOf(".xml", StringComparison.Ordinal)]; + var soap = "" + + "" + + $"{waiting.ExchangeId ?? "555000111"}{stem}_RC_009.xml{Convert.ToBase64String(receipt)}" + + ""; + using var client = new HttpClient { BaseAddress = address }; + async Task PostAsync(string? key, string body) + { + using var request = new HttpRequestMessage(HttpMethod.Post, "sdicoop/" + company) { Content = new StringContent(body, Encoding.UTF8, "text/xml") }; + if (key is not null) + { + request.Headers.Add(SdiPushService.KeyHeader, key); + } + + return await client.SendAsync(request); + } + + // The channel has no key yet: nobody gets in. + Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, (await PostAsync("chiave", soap)).StatusCode); + + var channels = app.Services.GetRequiredService(); + await channels.SaveAsync(Root, company, new EInvoiceChannelInput { Code = "SDICOOP", Enabled = true, Endpoint = "https://sdi.example.test/trasmissione", ApiKey = "chiave-di-prova" }); + Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, (await PostAsync("chiave-sbagliata", soap)).StatusCode); + Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, (await PostAsync(null, soap)).StatusCode); + Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, (await PostAsync("chiave-di-prova", "")).StatusCode); + Assert.AreEqual(System.Net.HttpStatusCode.NotFound, (await client.PostAsync("sdicoop/NESSUNA", new StringContent(soap))).StatusCode); + + var accepted = await PostAsync("chiave-di-prova", soap); + Assert.AreEqual(System.Net.HttpStatusCode.OK, accepted.StatusCode, await accepted.Content.ReadAsStringAsync()); + StringAssert.Contains(await accepted.Content.ReadAsStringAsync(), "Envelope"); + var history = await service.HistoryAsync(Root, company, waiting.Family, waiting.DocumentId); + Assert.AreEqual(EInvoiceStatus.Delivered, history[0].Invoice.Status); + Assert.AreEqual("RC", history[0].Notifications[^1].Code); + await app.StopAsync(); + } + } + + private static async Task SeedAsync(IServiceProvider services, string company) + { + var activation = await services.GetRequiredService().ActivateAsync(Root, "KH-TEST-ALL-0000-9999"); + Assert.IsTrue(activation.Succeeded, activation.Outcome); + await services.GetRequiredService().RunAsync(company, SeedKind.Demo); + var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + } +}