Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7b5cfb1bd | ||
|
|
83ef60fce2 | ||
|
|
a8f00cbae0 | ||
|
|
51007d68ca | ||
|
|
836a316b05 | ||
|
|
246d6f9357 | ||
|
|
b78260beb0 | ||
|
|
9d7cb9e71f | ||
|
|
fb12411404 | ||
|
|
709bb13532 |
No files matched your search
@@ -7,6 +7,122 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
- Decisioni del titolare (ADR 0044): le schermate con sola miniatura si disegnano dalla miniatura e dalla grafica del
|
||||
gestionale, senza attendere altri PNG (#35); nessun elenco ABI/CAB precaricato, nome della banca e BIC dal conto
|
||||
dell'azienda o a mano (#45); intermediari reali, accreditamento SdICoop e PEC di prova rimandati (#78). La guida
|
||||
*Fatturazione elettronica* spiega quale canale usare.
|
||||
|
||||
## [0.10.0] - 2026-11-13
|
||||
|
||||
M10 - Cespiti, Intrastat, chiusura, bilancio. I beni ammortizzabili hanno il loro registro con il piano civilistico e
|
||||
fiscale; gli elenchi Intrastat nascono dalle fatture con il file per le Dogane; le dichiarazioni d'intento hanno un
|
||||
registro e il plafond è controllato quando si conferma la fattura; a fine anno ratei, risconti e una chiusura guidata
|
||||
in nove passi portano al bilancio CEE con riclassificato, indici ed export per il commercialista.
|
||||
|
||||
### Added
|
||||
- Cespiti (#82, ADR 0041, mockup 048): categorie con i coefficienti del DM 31/12/1988 (*Categorie standard*), conti e
|
||||
aliquote civilistica e fiscale; registro con piano di ammortamento per anno, movimenti, beni già in uso con i fondi
|
||||
iniziali; ammortamenti dell'anno registrati per categoria e annullabili finché non definitivi; dismissioni totali e
|
||||
parziali con plusvalenza o minusvalenza; stampa del registro dei beni ammortizzabili.
|
||||
- Intrastat (#83, ADR 0042, mockup 049): elenchi di cessioni e acquisti generati da fatture e note confermate (beni
|
||||
raggruppati, servizi per fattura, rettifiche), righe manuali che sopravvivono alla rigenerazione, controlli di
|
||||
nomenclatura, massa, partita IVA e codice CPA, periodicità dovuta dalle soglie dei quattro trimestri precedenti,
|
||||
file `SCAMBI.CEE` e invio registrato con il protocollo.
|
||||
- Dichiarazioni d'intento (#83, ADR 0042, mockup 061): registro cronologico delle dichiarazioni ricevute ed emesse
|
||||
con protocollo telematico, plafond, utilizzato ricalcolato dalle vendite in N3.5, avviso dal 90 %, revoca e stampa;
|
||||
la conferma di una fattura in N3.5 è rifiutata senza dichiarazione valida o oltre il plafond.
|
||||
- Ratei e risconti (#84): inserimento con calcolo per giorni, proposta dei risconti dalle fatture di acquisto sui
|
||||
costi tipicamente a cavallo dell'anno, differenze di cambio al 31/12 sulle partite in valuta.
|
||||
- Chiusura guidata (#85, ADR 0043, mockup 050): controlli, ammortamenti, ratei e risconti, rimanenze al costo medio
|
||||
ponderato, accantonamenti (svalutazione crediti 0,5 %, TFR), chiusura dei conti economici e patrimoniali, apertura
|
||||
dell'esercizio successivo con lo storno dei ratei, stampe definitive (libro giornale, registri IVA, registro
|
||||
cespiti, bilancio); ogni passo si ripete o si annulla fino alle stampe; blocco dell'esercizio.
|
||||
- Bilancio (#86, ADR 0043, mockup 051): schede *CEE*, *Riclassificato* e *Indici* nella pagina *Bilancio*; schema
|
||||
ordinario, abbreviato e micro con l'anno precedente e la variazione, dettaglio dei conti di ogni voce, avviso dei
|
||||
conti senza voce, stato patrimoniale finanziario e conto economico a valore aggiunto, undici indici, stampa PDF ed
|
||||
export ZIP per il commercialista (cinque CSV).
|
||||
- Dati di esempio di fine anno (#87): apertura dei conti al 1° gennaio con cespiti, rimanenze, banca e capitale,
|
||||
quattro cespiti, un risconto, la dichiarazione d'intento in uso e una cessione intracomunitaria; prova di
|
||||
integrazione che chiude l'anno demo dal passo 1 al blocco su SQLite e PostgreSQL.
|
||||
- Permessi `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post`, `intrastat.list.read`,
|
||||
`intrastat.list.write`, `intrastat.list.export`, `sales.intent.read`, `sales.intent.write`, `ledger.year.close`,
|
||||
`reports.accountant.export`.
|
||||
- Tabelle `fixed_asset_categories`, `fixed_assets`, `fixed_asset_movements`, `accruals`, `closing_runs`,
|
||||
`closing_steps`, `closing_prints`, `intrastat_lists`, `intrastat_list_lines`, `intent_declarations` (migrazione
|
||||
`create_year_end`).
|
||||
- ADR 0041, 0042 e 0043; pagine wiki *Cespiti*, *Intrastat*, *Dichiarazioni d'intento* e *Chiusura e bilancio* con
|
||||
le schermate.
|
||||
|
||||
### Changed
|
||||
- Menu *Contabilità* con *Ratei e risconti* e *Chiusura esercizio*; menu *Cespiti* con *Categorie*; *Intrastat* e
|
||||
*Dichiarazioni d'intento* attivi nel menu *Fatturazione elettronica*.
|
||||
- La dichiarazione d'intento nei dati fiscali del cliente è lo specchio di quella corrente del registro; quelle
|
||||
scritte prima della 0.10 entrano nel registro alla prima lettura.
|
||||
- Il pacchetto fiscale espone le regole di cespiti, chiusura, Intrastat, dichiarazioni d'intento e lo schema del
|
||||
bilancio CEE.
|
||||
|
||||
### Known issues
|
||||
- Il file `SCAMBI.CEE` non è ancora stato verificato con il software di controllo delle Dogane: controllarlo prima
|
||||
del primo invio.
|
||||
- Le differenze di cambio usano il residuo attuale della partita; il TFR della chiusura è una stima.
|
||||
|
||||
## [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<identificativo>_<progressivo>.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
|
||||
|
||||
@@ -76,8 +76,9 @@ validi.
|
||||
`docs/mockups/png/` più la galleria completa `000-galleria-mockup.png`; per **tutte le 88** esiste una miniatura
|
||||
401x241 ritagliata dalla galleria in `docs/mockups/thumbs/`. Per le schermate senza PNG ad alta risoluzione si
|
||||
lavora da miniatura + `mockup.css` + descrizione in SPEC §10-§12, scegliendo i mattoni della schermata più simile
|
||||
in alta risoluzione (§10.1 regola 4). I PNG mancanti vanno chiesti all'utente quando servono, senza bloccare il
|
||||
lavoro (issue con etichetta `Status/In attesa utente`).
|
||||
in alta risoluzione (§10.1 regola 4). Il titolare ha confermato il 2026-11-16 che altri PNG non esistono
|
||||
(ADR [0044](docs/adr/0044-schermate-senza-png-banche-e-canali-sdi.md)): la miniatura è la specifica finale e i dettagli
|
||||
che non mostra si decidono seguendo la grafica del gestionale già costruita, senza chiederli.
|
||||
|
||||
**E5 — Avvio dello sviluppo.** La specifica (§0, §23) dice di lavorare in autonomia senza chiedere conferme. Vale,
|
||||
**dopo** il via esplicito dell'utente: la documentazione e la pianificazione su Gitea sono state preparate il
|
||||
|
||||
@@ -733,6 +733,37 @@ 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)
|
||||
- `core` 20261113005 `create_year_end` (M20261113_005_CreateYearEnd)
|
||||
|
||||
#### `accruals`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `year` | Int32 | no | | |
|
||||
| `kind` | String(40) | no | | |
|
||||
| `description` | String(200) | no | | |
|
||||
| `account_id` | Int64 | no | | -> `gl_accounts` (Restrict) |
|
||||
| `amount` | Decimal(19,6) | no | `0` | |
|
||||
| `period_start` | Date | no | | |
|
||||
| `period_end` | Date | no | | |
|
||||
| `year_end` | Date | no | | |
|
||||
| `adjustment` | Decimal(19,6) | no | `0` | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_document_id` | Int64 | sì | | |
|
||||
| `document_number` | String(40) | sì | | |
|
||||
| `party_id` | Int64 | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) |
|
||||
| `reversal_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) |
|
||||
| `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_accruals_year` su `year`
|
||||
|
||||
#### `attachments`
|
||||
|
||||
@@ -908,6 +939,65 @@ Migrazioni applicate in ordine:
|
||||
|
||||
- indice unico `ux_carriers_code` su `code`
|
||||
|
||||
#### `closing_prints`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `run_id` | Int64 | no | | -> `closing_runs` (Cascade) |
|
||||
| `kind` | String(20) | no | | |
|
||||
| `file_name` | String(100) | no | | |
|
||||
| `pages` | Int32 | no | `0` | |
|
||||
| `content` | Bytes | no | | |
|
||||
| `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_closing_prints_run` su `run_id`
|
||||
|
||||
#### `closing_runs`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `fiscal_year_id` | Int64 | no | | -> `fiscal_years` (Restrict) |
|
||||
| `year_code` | String(10) | no | | |
|
||||
| `status` | String(40) | no | | |
|
||||
| `next_fiscal_year_id` | Int64 | sì | | |
|
||||
| `result` | Decimal(19,6) | no | `0` | |
|
||||
| `locked_at` | DateTimeUtc | sì | | |
|
||||
| `locked_by` | String(100) | sì | | |
|
||||
| `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_closing_runs_year` su `fiscal_year_id`
|
||||
|
||||
#### `closing_steps`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `run_id` | Int64 | no | | -> `closing_runs` (Cascade) |
|
||||
| `number` | Int32 | no | | |
|
||||
| `status` | String(40) | no | | |
|
||||
| `entries` | Int32 | no | `0` | |
|
||||
| `amount` | Decimal(19,6) | no | `0` | |
|
||||
| `messages` | Text | sì | | |
|
||||
| `executed_at` | DateTimeUtc | sì | | |
|
||||
| `executed_by` | String(100) | sì | | |
|
||||
| `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_closing_steps_number` su `run_id`, `number`
|
||||
|
||||
#### `code_sequences`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
@@ -1241,6 +1331,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 |
|
||||
@@ -1298,6 +1562,95 @@ Migrazioni applicate in ordine:
|
||||
- indice unico `ux_fiscal_years_code` su `code`
|
||||
- indice unico `ux_fiscal_years_start_date` su `start_date`
|
||||
|
||||
#### `fixed_asset_categories`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `code` | String(20) | no | | |
|
||||
| `description` | String(100) | no | | |
|
||||
| `disabled` | Bool | no | `false` | |
|
||||
| `class` | String(40) | no | | |
|
||||
| `ministerial_group` | String(20) | sì | | |
|
||||
| `civil_rate` | Decimal(19,6) | no | `0` | |
|
||||
| `fiscal_rate` | Decimal(19,6) | no | `0` | |
|
||||
| `civil_half_first_year` | Bool | no | `true` | |
|
||||
| `asset_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
|
||||
| `fund_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
|
||||
| `depreciation_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
|
||||
| `deductible_percent` | Decimal(19,6) | no | `100` | |
|
||||
| `cost_limit` | Decimal(19,6) | 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 unico `ux_fixed_asset_categories_code` su `code`
|
||||
|
||||
#### `fixed_asset_movements`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `asset_id` | Int64 | no | | -> `fixed_assets` (Cascade) |
|
||||
| `kind` | String(40) | no | | |
|
||||
| `movement_date` | Date | no | | |
|
||||
| `year` | Int32 | no | | |
|
||||
| `cost_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `civil_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `fiscal_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `proceeds` | Decimal(19,6) | no | `0` | |
|
||||
| `gain_loss` | Decimal(19,6) | no | `0` | |
|
||||
| `description` | String(200) | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) |
|
||||
| `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_fixed_asset_movements_asset` su `asset_id`, `movement_date`
|
||||
- indice `ix_fixed_asset_movements_year` su `year`, `kind`
|
||||
|
||||
#### `fixed_assets`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `code` | String(20) | no | | |
|
||||
| `description` | String(200) | no | | |
|
||||
| `category_id` | Int64 | no | | -> `fixed_asset_categories` (Restrict) |
|
||||
| `purchase_date` | Date | no | | |
|
||||
| `in_service_date` | Date | no | | |
|
||||
| `supplier_id` | Int64 | sì | | -> `parties` (Restrict) |
|
||||
| `document_reference` | String(60) | sì | | |
|
||||
| `location` | String(100) | sì | | |
|
||||
| `serial_number` | String(60) | sì | | |
|
||||
| `quantity` | Decimal(19,6) | no | `1` | |
|
||||
| `cost` | Decimal(19,6) | no | `0` | |
|
||||
| `civil_fund` | Decimal(19,6) | no | `0` | |
|
||||
| `fiscal_fund` | Decimal(19,6) | no | `0` | |
|
||||
| `civil_rate` | Decimal(19,6) | sì | | |
|
||||
| `fiscal_rate` | Decimal(19,6) | sì | | |
|
||||
| `residual_value` | Decimal(19,6) | no | `0` | |
|
||||
| `low_value` | Bool | no | `false` | |
|
||||
| `status` | String(40) | no | | |
|
||||
| `disposal_date` | Date | sì | | |
|
||||
| `last_depreciation_year` | Int32 | sì | | |
|
||||
| `notes` | 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_fixed_assets_category` su `category_id`
|
||||
- indice unico `ux_fixed_assets_code` su `code`
|
||||
|
||||
#### `gl_accounts`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
@@ -1364,6 +1717,7 @@ Migrazioni applicate in ordine:
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
| `closing_step` | Int32 | sì | | |
|
||||
|
||||
- indice `ix_gl_entries_date` su `entry_date`, `number`
|
||||
- indice `ix_gl_entries_register` su `vat_register_id`, `vat_date`
|
||||
@@ -1544,6 +1898,104 @@ Migrazioni applicate in ordine:
|
||||
|
||||
- indice unico `ux_goods_appearances_code` su `code`
|
||||
|
||||
#### `intent_declarations`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `direction` | String(40) | no | | |
|
||||
| `register_number` | Int32 | no | | |
|
||||
| `year` | Int32 | no | | |
|
||||
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
|
||||
| `number` | String(40) | no | | |
|
||||
| `declaration_date` | Date | no | | |
|
||||
| `protocol` | String(40) | no | | |
|
||||
| `ceiling` | Decimal(19,6) | no | `0` | |
|
||||
| `used` | Decimal(19,6) | no | `0` | |
|
||||
| `valid_from` | Date | no | | |
|
||||
| `valid_to` | Date | no | | |
|
||||
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `status` | String(40) | no | | |
|
||||
| `notes` | 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_intent_declarations_party` su `party_id`, `valid_from`
|
||||
- indice unico `ux_intent_declarations_register` su `direction`, `year`, `register_number`
|
||||
|
||||
#### `intrastat_list_lines`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `list_id` | Int64 | no | | -> `intrastat_lists` (Cascade) |
|
||||
| `section` | String(40) | no | | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_document_id` | Int64 | sì | | |
|
||||
| `document_number` | String(40) | sì | | |
|
||||
| `document_date` | Date | sì | | |
|
||||
| `party_id` | Int64 | sì | | |
|
||||
| `country_code` | String(2) | no | | |
|
||||
| `vat_number` | String(20) | sì | | |
|
||||
| `amount` | Decimal(19,6) | no | `0` | |
|
||||
| `currency_amount` | Decimal(19,6) | sì | | |
|
||||
| `statistical_value` | Decimal(19,6) | sì | | |
|
||||
| `nomenclature_code` | String(10) | sì | | |
|
||||
| `description` | String(200) | sì | | |
|
||||
| `transaction_nature` | String(2) | sì | | |
|
||||
| `delivery_terms` | String(3) | sì | | |
|
||||
| `transport_mode` | String(1) | sì | | |
|
||||
| `net_mass` | Decimal(19,6) | sì | | |
|
||||
| `supplementary_units` | Decimal(19,6) | sì | | |
|
||||
| `origin_country` | String(2) | sì | | |
|
||||
| `province` | String(2) | sì | | |
|
||||
| `supply_mode` | String(1) | sì | | |
|
||||
| `payment_mode` | String(1) | sì | | |
|
||||
| `payment_country` | String(2) | sì | | |
|
||||
| `corrected_year` | Int32 | sì | | |
|
||||
| `corrected_period` | Int32 | sì | | |
|
||||
| `correction_sign` | String(1) | sì | | |
|
||||
| `check` | String(40) | no | | |
|
||||
| `manual` | 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_intrastat_list_lines_list` su `list_id`, `section`
|
||||
|
||||
#### `intrastat_lists`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `flow` | String(40) | no | | |
|
||||
| `year` | Int32 | no | | |
|
||||
| `period` | Int32 | no | | |
|
||||
| `periodicity` | String(40) | no | | |
|
||||
| `status` | String(40) | no | | |
|
||||
| `progressive` | Int32 | no | `1` | |
|
||||
| `goods_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `services_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `problems` | Int32 | no | `0` | |
|
||||
| `file_name` | String(60) | sì | | |
|
||||
| `protocol` | String(40) | sì | | |
|
||||
| `generated_at` | DateTimeUtc | 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 unico `ux_intrastat_lists_period` su `flow`, `year`, `periodicity`, `period`
|
||||
|
||||
#### `inventory_document_lines`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|
||||
@@ -57,10 +57,11 @@ conservati; ogni accesso residuo risponde `module_not_licensed`.
|
||||
| Purchases | CORE | Documenti | [Acquisti](wiki/Acquisti.md) | M6 |
|
||||
| Inventory | CORE | Magazzino | [Magazzino](wiki/Magazzino.md) | M6 |
|
||||
| Ledger | ACCT | Contabilità | [Contabilita](wiki/Contabilita.md) | M7, M10 |
|
||||
| Vat | ACCT, INTRA | Contabilità | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md) | M7, M10 |
|
||||
| Vat | ACCT, INTRA | Contabilità | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md) | M7, M10 (Intrastat) |
|
||||
| YearEnd | ACCT (chiusura, bilancio), INTRA (Intrastat), CORE (dichiarazioni d'intento) | Contabilità | [Chiusura-e-bilancio](wiki/Chiusura-e-bilancio.md), [Dichiarazioni-d-intento](wiki/Dichiarazioni-d-intento.md) | M10 |
|
||||
| Assets | ASSET | Contabilità | [Cespiti](wiki/Cespiti.md) | M10 |
|
||||
| Finance | FIN | Contabilità (proposta) | [Scadenzario](wiki/Scadenzario.md) | M8 |
|
||||
| EInvoicing | EINV | SDI/e-invoicing; E-mail/PEC | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) | M9 (dichiarazioni d'intento: M10) |
|
||||
| EInvoicing | EINV | SDI/e-invoicing; E-mail/PEC | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) | M9 |
|
||||
| Crm | CRM | CRM | [CRM](wiki/CRM.md) | M11 |
|
||||
| Services | SVC | CRM (proposta) | [Servizi](wiki/Servizi.md) | M14 (fase 2) |
|
||||
| Channels | CHAN | Integrazioni | [Canali-e-commerce](wiki/Canali-e-commerce.md) | M14 (fase 2) |
|
||||
@@ -161,12 +162,12 @@ conservati; ogni accesso residuo risponde `module_not_licensed`.
|
||||
|---|---|
|
||||
| Licenza | `ACCT` |
|
||||
| Responsabilità | piano dei conti (precaricato e importabile CSV/XLSX/JSON), causali, prima nota con quadratura, contabilizzazione automatica, partitari e mastrini, registrazioni ricorrenti e in valuta, ritenute e casse, ratei/risconti, chiusura e apertura, libri definitivi, bilancio di verifica, CEE e riclassificati, export per il commercialista |
|
||||
| Entità | `GlAccount`, `JournalTemplate(+Line)`, `GlEntry`, `GlEntryLine`, `GlEntryVat`, `WithholdingTax`, `SocialSecurityCharge`, `AccrualDeferral`, `ClosingRun(+Step)`, `FinancialStatementLine`, `RecurringEntryTemplate` |
|
||||
| Servizi | `JournalService`, `PostingEngine`, `LedgerPoster`, `PeriodLockService`, `LedgerQueries`, `PartitarioService`, `WithholdingService`, `AccrualDeferralService`, `ClosingProcedure`, `TrialBalanceService`, `FinancialStatementsService`, `RecurringEntriesService`, `ExchangeDifferenceService`, `ChartOfAccountsImportService` |
|
||||
| Entità | `GlAccount`, `JournalTemplate(+Line)`, `GlEntry`, `GlEntryLine`, `GlEntryVat`, `WithholdingTax`, `SocialSecurityCharge`, `RecurringEntryTemplate`; dalla M10 (cartella `YearEnd`) `AccrualDeferral`, `ClosingRun`, `ClosingStep`, `ClosingPrint` |
|
||||
| Servizi | `JournalService`, `PostingEngine`, `LedgerPoster`, `PeriodLockService`, `LedgerQueries`, `PartitarioService`, `WithholdingService`, `TrialBalanceService`, `RecurringEntriesService`, `ChartOfAccountsImportService`; dalla M10 `AccrualService` (ratei, risconti, differenze di cambio), `ClosingService` (nove passi, stampe, blocco), `FinancialStatementsService` (CEE, riclassificati, indici, export); nel pacchetto paese `ClosingRulesIt`, `CeeSchemaIt` |
|
||||
| Maschere e mockup | prima nota (040, 041), piano dei conti e mastrino (042), causali (043), partitario/estratto conto (044), ritenute e F24 (047), chiusura esercizio (050), bilancio CEE (051), esercizi e periodi (052) |
|
||||
| Permessi | **`ledger.entry.finalize`**; proposte: `ledger.entry.read`, `ledger.entry.write`, `ledger.entry.reopen`, `ledger.account.write`, `ledger.closing.run` |
|
||||
| Permessi | **`ledger.entry.finalize`**, `ledger.entry.read`, `ledger.entry.write`, `ledger.account.write`; dalla M10 `ledger.year.close` (ratei e risconti, chiusura, blocco) e `reports.accountant.export` |
|
||||
| Log | Contabilità |
|
||||
| Wiki | [Contabilita](wiki/Contabilita.md) |
|
||||
| Wiki | [Contabilita](wiki/Contabilita.md), [Chiusura-e-bilancio](wiki/Chiusura-e-bilancio.md) |
|
||||
| Milestone | M7 `v0.7.0` (piano dei conti, causali, prima nota, partitari, ritenute, bilancio di verifica); M10 `v0.10.0` (ratei/risconti, chiusura/apertura, libri definitivi, bilancio CEE, export commercialista) |
|
||||
|
||||
### 3.8 Vat — IVA, adempimenti e Intrastat
|
||||
@@ -175,28 +176,29 @@ conservati; ogni accesso residuo risponde `module_not_licensed`.
|
||||
|---|---|
|
||||
| Licenza | `ACCT`; parte Intrastat `INTRA` |
|
||||
| Responsabilità | registri IVA con protocollo e stampe definitive, liquidazione periodica (differita, per cassa, pro-rata, acconto, interessi, minimo), dati F24 e LIPE XML, bollo virtuale (dati per F24), dichiarazioni d'intento, elenchi Intrastat |
|
||||
| Entità | `VatRegister`, `VatSettlement(+Line)`, `StampDutyEntry`, `IntentDeclaration`, `IntrastatDeclaration(+Line)` |
|
||||
| Entità | `VatRegister`, `VatSettlement(+Line)`, `StampDutyEntry`; dalla M10 `IntentDeclaration`, `IntrastatList(+Line)` |
|
||||
| Servizi | `VatRegisterService`, `VatSettlementService`, `StampDutyService`, `IntentDeclarationService`, `IntrastatService`; nel pacchetto paese `VatSettlementRules`, `VatAdvanceCalculator`, `LipeWriter`, `F24Exporter`, `IntrastatExporterIt` |
|
||||
| Maschere e mockup | registri IVA (045, `VatRegistersPage`), liquidazione IVA/F24/LIPE (046, `VatSettlementPage`), Intrastat (049, `IntrastatPage`) |
|
||||
| Permessi | **`vat.settlement.confirm`**; proposte: `vat.register.print`, `vat.register.finalize`, `vat.settlement.read`, `vat.intrastat.export` |
|
||||
| Permessi | **`vat.settlement.confirm`**; proposte: `vat.register.print`, `vat.register.finalize`, `vat.settlement.read`; dalla M10 `intrastat.list.read`, `intrastat.list.write`, `intrastat.list.export`, `sales.intent.read`, `sales.intent.write` |
|
||||
| Log | Contabilità |
|
||||
| Wiki | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md), [Fiscalita-italiana](wiki/Fiscalita-italiana.md) |
|
||||
| Milestone | M7 `v0.7.0` (registri, liquidazione, F24, LIPE, bollo); M10 `v0.10.0` (Intrastat, dichiarazioni d'intento) |
|
||||
|
||||
Nota: SPEC elenca bollo virtuale e dichiarazioni d'intento sia in `ACCT` sia in `EINV` (§8.1), e le loro maschere
|
||||
(060, 061) sotto *Fatturazione elettronica*. Proposta: i servizi stanno in `Vat`, le maschere sono raggiungibili dal
|
||||
menu *Fatturazione elettronica* se `EINV` è attivo e da *Contabilità* se è attivo solo `ACCT`. Da fissare con ADR.
|
||||
(060, 061) sotto *Fatturazione elettronica*. Deciso in M10 (ADR 0042): le dichiarazioni d'intento sono nel modulo base
|
||||
`CORE` perché riguardano la normale fatturazione, Intrastat in `INTRA`; entrambe le pagine stanno nel menu
|
||||
*Fatturazione elettronica* come nei mockup, i servizi in `Khaemhat.Application/YearEnd`.
|
||||
|
||||
### 3.9 Assets — Cespiti
|
||||
|
||||
| Voce | Contenuto |
|
||||
|---|---|
|
||||
| Licenza | `ASSET` |
|
||||
| Responsabilità | categorie con coefficienti ministeriali, registro beni ammortizzabili, piano di ammortamento (primo anno 50%, limiti autovetture, beni < €516,46), dismissioni con plus/minusvalenza (TD26), rivalutazioni, piano simulato, contabilizzazione annuale |
|
||||
| Responsabilità | categorie con coefficienti ministeriali, registro beni ammortizzabili, piano di ammortamento civilistico e fiscale (primo anno 50%, limiti autovetture, beni < €516,46), dismissioni totali e parziali con plus/minusvalenza, registrazione annuale per categoria annullabile, stampa del registro |
|
||||
| Entità | `FixedAsset`, `FixedAssetCategory`, `FixedAssetMovement` |
|
||||
| Servizi | `FixedAssetService`, `DepreciationService`; `DepreciationCalculator` (Core), `FixedAssetRulesIt`, `MinisterialCoefficients` |
|
||||
| Maschere e mockup | registro cespiti e piano di ammortamento (048, `FixedAssetsPage`) |
|
||||
| Permessi | proposte: `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post` |
|
||||
| Servizi | `FixedAssetService`; `DepreciationCalculator` (Core); nel pacchetto paese le regole dei cespiti e `MinisterialCoefficients` (ADR 0041) |
|
||||
| Maschere e mockup | registro cespiti e piano di ammortamento (048, `AssetsPage`), ammortamenti (`DepreciationPage`), categorie (`CategoriesPage`) |
|
||||
| Permessi | `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post` |
|
||||
| Log | Contabilità |
|
||||
| Wiki | [Cespiti](wiki/Cespiti.md) |
|
||||
| Milestone | M10 `v0.10.0` |
|
||||
@@ -220,14 +222,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
|
||||
|
||||
|
||||
@@ -2,26 +2,34 @@
|
||||
|
||||
> 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
|
||||
per le banche ABI/CAB (manca una fonte con licenza compatibile).
|
||||
**Ultimo aggiornamento:** 2026-11-16
|
||||
**Milestone corrente:** M11 — CRM e servizi (issue #88-#91), da iniziare. M10 chiusa: PR in `main`, tag `v0.10.0`,
|
||||
immagine e release.
|
||||
**Prossimo passo:** M11 dall'issue #88. Decisioni del titolare del 2026-11-16 (ADR 0044): le schermate senza PNG si
|
||||
disegnano dalla miniatura e dalla grafica del gestionale (#35 chiusa); niente elenco banche ABI/CAB precaricato (#45
|
||||
chiusa); intermediari, SdICoop e PEC reale rimandati (#78 nel backlog).
|
||||
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;
|
||||
logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e modelli e-mail per azienda (M12).
|
||||
Da M6: schermata dell'import fatture con file caricati (serve un caricamento via CDP); nei movimenti di un articolo il
|
||||
numero del fornitore al posto di *DDT fornitore* senza numero; FIFO e LIFO a lotti (dopo la 1.0).
|
||||
Da M7: schermata del bollo virtuale (la demo non ha fatture esenti sopra 77,47 euro); import di causali e voci di
|
||||
bilancio dal file `khaemhat-coa.json`; scritture delle rimanenze e libro inventari (M10); IVA per
|
||||
cassa (fase 2).
|
||||
bilancio dal file `khaemhat-coa.json`; libro inventari (M13); IVA per 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 nel backlog, ADR 0040 e 0044); conformità PDF/A-3 dichiarata della copia di cortesia;
|
||||
pulsanti *Carica* e *Rimuovi dati di esempio* nell'interfaccia (M12).
|
||||
Da M10: file `SCAMBI.CEE` da verificare con il software di controllo delle Dogane prima del primo invio (ADR 0042);
|
||||
differenze di cambio calcolate sul residuo attuale della partita (ADR 0043); TFR stimato (retribuzioni / 13,5);
|
||||
annullare il passo 2 della chiusura toglie tutti gli ammortamenti dell'anno (ADR 0041); il gruppo dichiarazione
|
||||
d'intento nei dati fiscali del cliente è ora uno specchio del registro (si potrebbe renderlo di sola lettura con un
|
||||
collegamento al registro); rivalutazioni senza regole guidate.
|
||||
|
||||
## Fatto
|
||||
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
|
||||
- ADR 0001-0038.
|
||||
- ADR 0001-0043.
|
||||
- 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 +104,23 @@ 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.
|
||||
- **M10 (chiusa, `v0.10.0`):** cespiti con categorie ministeriali, piano civilistico e fiscale, ammortamenti per
|
||||
categoria annullabili, dismissioni e registro (#82, ADR 0041); elenchi Intrastat dai documenti con periodicità dalle
|
||||
soglie e file `SCAMBI.CEE`, registro delle dichiarazioni d'intento con controllo del plafond alla conferma (#83,
|
||||
ADR 0042); ratei e risconti per giorni e differenze di cambio (#84); chiusura guidata in nove passi ripetibili e
|
||||
annullabili con riapertura, stampe definitive e blocco (#85); bilancio CEE ordinario, abbreviato e micro con
|
||||
riclassificato, indici, stampa ed export per il commercialista (#86, ADR 0043); dati di esempio di fine anno e
|
||||
chiusura completa dell'anno demo come prova di accettazione (#87); wiki *Cespiti*, *Intrastat*, *Dichiarazioni
|
||||
d'intento*, *Chiusura e bilancio* con le schermate. Test: 907 verdi in locale, anche quelli di PostgreSQL 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,
|
||||
@@ -114,8 +139,6 @@ Rilevato il 2026-11-11 sulla macchina di sviluppo (Windows 11, Git Bash per gli
|
||||
|
||||
## In attesa del titolare
|
||||
|
||||
- PNG ad alta risoluzione delle 66 schermate disponibili solo come miniatura (issue #35, non bloccante).
|
||||
- Scelta degli intermediari SDI e accreditamento SdICoop (issue #78, non bloccante).
|
||||
- Prova del template su Unraid (issue #106).
|
||||
- Un contatto privato per la segnalazione di vulnerabilità (vedi `SECURITY.md`).
|
||||
|
||||
@@ -145,8 +168,8 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
|
||||
12. Scadenza IVA di settembre: mockup 046 la mette al 16/10/2026, mockup 047 nell'F24 del 16/11/2026 (corretto: 16/10 per i mensili). **Deciso in M7: ADR 0037, il 16 del mese successivo.**
|
||||
13. Bollo sulle cessioni intracomunitarie: il mockup 060 lo addebita su N3.2, ma cessioni intra-UE ed esportazioni ne sono esenti; la regola del bollo va legata al codice IVA con esclusioni.
|
||||
14. Funzioni di fase 2 nelle schermate di M7: ventilazione dei corrispettivi (046) e IVA per cassa completa sono in M14 per §20. **Confermato in M7: non implementate.**
|
||||
15. Moduli ambigui: bollo e dichiarazioni d'intento sotto ACCT e EINV (§8.1); export commercialista sotto ACCT e REPORT; Intrastat e LIPE nel menu e-fattura nei mockup; §10.2 senza voce Intrastat.
|
||||
16. Stato "Provvisorio" dell'esercizio nel mockup 052, non previsto da SPEC (aperto / in chiusura / chiuso).
|
||||
15. Moduli ambigui: bollo e dichiarazioni d'intento sotto ACCT e EINV (§8.1); export commercialista sotto ACCT e REPORT; Intrastat e LIPE nel menu e-fattura nei mockup; §10.2 senza voce Intrastat. **Deciso in M10: dichiarazioni d'intento in CORE, Intrastat in INTRA nel menu e-fattura, export commercialista in ACCT con il permesso `reports.accountant.export` (ADR 0042, 0043).**
|
||||
16. Stato "Provvisorio" dell'esercizio nel mockup 052, non previsto da SPEC (aperto / in chiusura / chiuso). **Deciso in M10: restano i tre stati di SPEC; "in chiusura" dal passo 6, "chiuso" con il blocco (ADR 0043).**
|
||||
17. Codici conto incoerenti tra mockup (fornitori 05.02.001 in 040/043, 02.03.001 in 042). **Deciso in M7: ADR 0036, piano PMI standard (clienti 05.01.001, fornitori 14.01.001).**
|
||||
18. Regola R-005 del mockup 072 "riapre in bozza" una fattura scartata: contrasta con l'immutabilità della fattura emessa.
|
||||
19. Codice campagne `CMP-…` (068) non presente nelle maschere di §11.12.
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
|
||||
- Per le schermate con sola miniatura valgono SPEC §10.1 regola 4 (comporre con i mattoni della più simile) e le
|
||||
descrizioni testuali; se un dettaglio non è ricostruibile si chiede il PNG all'utente con un'issue
|
||||
`Status/In attesa utente`, senza fermare il resto.
|
||||
`Status/In attesa utente`, senza fermare il resto. *Aggiornato dall'ADR 0044:* altri PNG non esistono, i dettagli
|
||||
mancanti si decidono seguendo la grafica del gestionale.
|
||||
- Quando arrivano gli screenshot reali dell'applicazione sostituiscono progressivamente i mockup nella wiki
|
||||
(`docs/wiki/img/`), come da SPEC §17.
|
||||
@@ -37,6 +37,8 @@ grandi (8.000 comuni, decine di migliaia di sportelli) che non sono nel reposito
|
||||
via dell'utente al download. Fino ad allora le tabelle si riempiono a mano o con l'import CSV.
|
||||
*Aggiornato dall'ADR 0028:* province e comuni ISTAT, con i CAP di GeoNames, sono nei dati di base dalla
|
||||
versione `IT 2026.3`; le banche restano fuori.
|
||||
*Aggiornato dall'ADR 0044:* il titolare rinuncia all'elenco precaricato delle banche; nome e BIC si scrivono a mano
|
||||
o vengono da un conto dell'azienda presso la stessa banca.
|
||||
7. **Riga di comando.** `scripts/seed.sh --base [--company CODICE]` esegue la sequenza di avvio senza servire pagine
|
||||
(migrazioni, prima azienda) e aggiunge i dati di base a un'azienda o a tutte quelle attive. Nel container lo
|
||||
script è in `/app/scripts/` e passa da `entrypoint.sh` con il verbo `seed`; in sviluppo usa `dotnet run`.
|
||||
|
||||
@@ -41,6 +41,7 @@ caricati dopo il via dell'utente. Il via è arrivato il 2026-11-12 per due fonti
|
||||
6. **Strumento di rigenerazione.** `tools/Khaemhat.PlacesTool` (non distribuito, solo framework) legge il foglio ISTAT
|
||||
e `IT.zip` e riscrive `Data/province.csv` e `Data/comuni.csv`; i file scaricati restano fuori dal repository.
|
||||
7. **Banche ABI/CAB** restano fuori finché non c'è una fonte aperta con licenza chiara (ADR 0026, ADR 0027 punto 6).
|
||||
Il titolare ha rinunciato ai dati precaricati (ADR 0044).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
|
||||
@@ -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<identificativo>_<progressivo>.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.
|
||||
@@ -0,0 +1,45 @@
|
||||
# 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.
|
||||
*Aggiornato dall'ADR 0044:* la scelta dei fornitori e l'accreditamento sono rimandati; #78 resta nel backlog.
|
||||
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).
|
||||
@@ -0,0 +1,45 @@
|
||||
# ADR 0041 - Cespiti: piani paralleli, registrazione per categoria e dismissioni
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-13
|
||||
- **Modifica:** SPEC §11.7, §21; milestone M10, issue #82; mockup 048
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.7 chiede il registro dei beni ammortizzabili con piano civilistico e fiscale, il calcolo e la registrazione
|
||||
delle quote di fine anno, le dismissioni con plusvalenza o minusvalenza e la stampa del registro. Le regole italiane
|
||||
(coefficienti del DM 31/12/1988, primo anno al 50 % ai fini fiscali, limiti delle autovetture, beni fino a 516,46 €)
|
||||
devono restare nel pacchetto fiscale. La chiusura dell'esercizio (ADR 0043) deve poter registrare gli ammortamenti
|
||||
come suo passo 2 e annullarli.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Categorie con aliquote proprie.** Il pacchetto italiano espone `IFixedAssetRules` con le categorie standard
|
||||
(`MinisterialCoefficients`): materiali con i coefficienti comuni del DM 31/12/1988, immateriali con i limiti
|
||||
dell'art. 103 TUIR. La categoria dell'azienda conserva aliquota civilistica e fiscale, metà aliquota civilistica
|
||||
nel primo anno, limite di costo e deducibilità, conti di cespite, fondo e ammortamento: la tabella dipende dal
|
||||
settore e ogni azienda la adatta.
|
||||
2. **Due piani con la stessa regola.** `DepreciationCalculator` applica le quote costanti al costo, dimezzate nel
|
||||
primo anno quando richiesto, senza superare il residuo; i beni con aliquota 100 % si ammortizzano nel primo anno.
|
||||
Il piano fiscale dimezza sempre il primo anno dei beni materiali. Il bene conserva fondo civilistico e fiscale;
|
||||
l'aliquota del bene vuota segue la categoria.
|
||||
3. **Una registrazione per anno, una riga per categoria.** Gli ammortamenti si registrano al 31/12 con origine
|
||||
`FixedAsset` (quota in Dare, fondo in Avere, per categoria) e un movimento `Depreciation` per bene. L'annullamento
|
||||
toglie movimenti, fondi e registrazione finché la registrazione non è definitiva. Solo la quota civilistica va in
|
||||
contabilità: la differenza con la fiscale è una variazione in dichiarazione.
|
||||
4. **Beni già in uso.** Un bene acquistato prima dell'avvio porta i fondi iniziali e l'ultimo esercizio già
|
||||
ammortizzato con un movimento `Opening`; i fondi entrano in contabilità con la scrittura di apertura dei conti.
|
||||
5. **Dismissioni senza quota dell'anno.** La dismissione (totale o parziale) toglie il costo dismesso e la quota
|
||||
proporzionale del fondo, porta il prezzo sul conto *altri crediti* e la differenza a plusvalenza o minusvalenza.
|
||||
Nell'anno della dismissione **non** si calcola la quota: è la scelta prudente e più semplice da verificare; chi
|
||||
vuole la quota fino alla data la registra prima con una scrittura manuale. Gli ammortamenti di un anno non si
|
||||
registrano se esistono già quelli di un anno successivo (`assets.later-depreciation`).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il registro, gli ammortamenti e la stampa funzionano anche senza la chiusura guidata; il passo 2 della chiusura
|
||||
riusa lo stesso servizio e non duplica le quote.
|
||||
- L'annullamento del passo 2 rimuove tutti gli ammortamenti dell'anno, anche quelli registrati a mano dalla pagina
|
||||
Ammortamenti prima della chiusura.
|
||||
- Le rivalutazioni previste dalle singole leggi restano un movimento `Revaluation` senza regole guidate: si aggiungono
|
||||
quando servono.
|
||||
@@ -0,0 +1,46 @@
|
||||
# ADR 0042 - Intrastat e dichiarazioni d'intento
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-13
|
||||
- **Modifica:** SPEC §11.7, §8.1; milestone M10, issue #83; mockup 049 e 061
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.7 chiede gli elenchi Intrastat generati dai documenti con il file per le Dogane e le dichiarazioni d'intento
|
||||
degli esportatori abituali con il controllo del plafond. Fino a M9 la dichiarazione d'intento era un gruppo di campi
|
||||
nei dati fiscali del cliente (protocollo, data, plafond) usato solo dal file FatturaPA. Le soglie, il tracciato e il
|
||||
formato del protocollo sono regole italiane.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Intrastat dai documenti confermati.** `IntrastatService` legge fatture e note di credito (vendite e acquisti)
|
||||
confermate nel periodo verso soggetti di un altro Stato membro: i beni sono raggruppati per controparte,
|
||||
nomenclatura e natura della transazione, i servizi hanno una riga per fattura, le note di credito diventano
|
||||
rettifiche. Natura `11`, consegna `DAP` e trasporto `3` sono proposti e si correggono sulla riga. Le righe manuali
|
||||
sopravvivono alla rigenerazione.
|
||||
2. **Periodicità e file nel pacchetto.** `IIntrastatExporter` italiano (`IntrastatExporterIt`) calcola la
|
||||
periodicità dai quattro trimestri precedenti con le soglie dal 2022 (cessioni 50.000 € per categoria; acquisti di
|
||||
beni 350.000 € e di servizi 100.000 €, sotto le quali non sono dovuti) e scrive il file `SCAMBI.CEE` a record di
|
||||
lunghezza fissa. Un elenco con righe incomplete non si esporta; dopo l'invio, con il protocollo, è di sola lettura.
|
||||
3. **Il tracciato va validato.** Il file segue le specifiche pubblicate ma non è stato provato con il software di
|
||||
controllo delle Dogane: STATUS lo indica come attività aperta e la wiki chiede il controllo prima del primo invio.
|
||||
4. **Registro delle dichiarazioni.** Le dichiarazioni diventano una tabella (`intent_declarations`) con direzione
|
||||
(ricevute o emesse), numero di registro per anno, protocollo (`IIntentRules`: 17 cifre, trattino o barra, 6
|
||||
cifre), validità, plafond, utilizzato e stato. Il cliente conserva lo **specchio** della dichiarazione corrente
|
||||
nei dati fiscali, così documenti e FatturaPA (`AltriDatiGestionali` tipo `INTENTO`) non cambiano. Le dichiarazioni
|
||||
scritte nei dati fiscali prima della 0.10 vengono adottate nel registro alla prima lettura o al primo controllo.
|
||||
5. **Controllo alla conferma.** `DocumentEngine` chiama `IntentDeclarationService.CheckAsync` quando conferma una
|
||||
vendita con righe di natura N3.5: senza dichiarazione attiva che copre la data la conferma è rifiutata
|
||||
(`intent.no-declaration`), oltre il residuo pure (`intent.ceiling-exceeded`); le note di credito restituiscono
|
||||
plafond e non sono controllate. Dopo ogni conferma, annullamento o eliminazione l'utilizzato si **ricalcola** da
|
||||
tutte le vendite N3.5 del cliente, ognuna sulla dichiarazione più recente che ne copre la data; dal 90 % il
|
||||
registro mostra l'avviso.
|
||||
6. **Moduli.** Intrastat è nel modulo **INTRA**; le dichiarazioni d'intento nel modulo base **CORE**, perché
|
||||
riguardano la normale fatturazione.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il plafond è sempre coerente con le fatture, senza contatori da mantenere a mano; il costo è un ricalcolo per
|
||||
cliente a ogni conferma di una vendita in N3.5.
|
||||
- Il gruppo *dichiarazione d'intento* dei dati fiscali del cliente resta come specchio; il registro è la fonte.
|
||||
- La trasmissione telematica (Dogane, Agenzia delle Entrate) resta fuori da Khaemhat.
|
||||
@@ -0,0 +1,57 @@
|
||||
# ADR 0043 - Ratei e risconti, chiusura guidata e bilancio
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-13
|
||||
- **Modifica:** SPEC §11.7, §14; milestone M10, issue #84, #85, #86, #87; mockup 050 e 051
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.7 chiede ratei e risconti, differenze di cambio, la chiusura dell'esercizio guidata in passi ripetibili, la
|
||||
riapertura, le stampe definitive, il bilancio CEE con riclassificato e indici e l'esportazione per il commercialista.
|
||||
La chiusura scrive molte registrazioni che devono poter essere tolte finché i libri non sono definitivi; il bilancio
|
||||
deve leggere i saldi dell'anno anche dopo la chiusura dei conti.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Ratei e risconti per giorni.** `AccrualDeferral` conserva tipo, conto, importo e periodo di competenza; la
|
||||
rettifica è la parte del periodo fuori dall'esercizio (risconti) o dentro (ratei), in giorni. I risconti si
|
||||
propongono dalle fatture di acquisto registrate sui conti di costi tipicamente a cavallo dell'anno
|
||||
(`IClosingRules.PrepaidCandidates`) con un periodo di un anno dalla data: l'utente controlla il periodo.
|
||||
2. **Differenze di cambio sul residuo.** Le partite aperte in valuta si valutano al cambio dell'ultimo giorno
|
||||
dell'anno sul **residuo** attuale della partita, non su quello al 31/12: per la chiusura fatta a inizio anno nuovo
|
||||
la differenza è un'approssimazione accettata e documentata.
|
||||
3. **Nove passi in ordine.** `ClosingService` esegue controlli, ammortamenti (ADR 0041), ratei e risconti, rimanenze
|
||||
al costo medio ponderato, accantonamenti (svalutazione crediti 0,5 %, art. 106 TUIR; TFR stimato come retribuzioni
|
||||
/ 13,5 meno quanto già accantonato), chiusura dei conti economici con il risultato a patrimonio, chiusura dei conti
|
||||
patrimoniali per conto e soggetto, apertura dell'esercizio successivo con lo storno di ratei e risconti, stampe
|
||||
definitive. Ogni registrazione ha origine `Closing` (o `FixedAsset`, `Accrual`, `ExchangeDifference`) e il numero
|
||||
del passo, così l'ultimo passo eseguito si **ripete** o si **annulla** togliendo esattamente le sue scritture
|
||||
(prima i riferimenti, poi le registrazioni, per le chiavi esterne).
|
||||
4. **Il passo 9 è il punto di non ritorno.** Rende definitive tutte le registrazioni dell'anno (numerazione del
|
||||
libro giornale) e conserva i PDF di libro giornale, registri IVA, registro cespiti e bilancio CEE. Non si annulla.
|
||||
Le stampe dei registri IVA nella chiusura sono quelle dell'anno: vidimazione e numerazione delle pagine restano
|
||||
quelle della pagina IVA. Dopo il passo 9 il **blocco** porta l'esercizio a `Closed` e lo rende di sola lettura.
|
||||
5. **Conti del pacchetto.** I conti usati (rimanenze, ratei e risconti, fondi, conti di chiusura e apertura,
|
||||
risultato) sono in `IClosingRules.Accounts` del pacchetto italiano e corrispondono al piano *PMI standard*. Il
|
||||
risultato si riapre nel conto *utile (perdita) dell'esercizio* (`10.02.002`); la destinazione dell'utile è una
|
||||
registrazione dell'utente dopo l'approvazione.
|
||||
6. **Bilancio dai saldi mappati.** `CeeSchemaIt` (`IFinancialStatementsSchema`) descrive le voci degli art. 2424 e
|
||||
2425 c.c., l'abbreviato (2435-bis) e il micro (2435-ter, con le voci dell'abbreviato), e le riclassificazioni
|
||||
finanziaria e a valore aggiunto. Ogni conto porta la voce ordinaria; la natura del conto dice in quale prospetto
|
||||
va. `FinancialStatementsService` **esclude le scritture dei passi 6 e 7**, così un esercizio chiuso mostra i suoi
|
||||
saldi; segnala i conti con saldo senza voce. Gli indici sono undici, con formula e anno precedente.
|
||||
7. **Esportazione semplice.** L'export per il commercialista è uno ZIP di cinque CSV (piano dei conti, bilancio di
|
||||
verifica, movimenti, stato patrimoniale, conto economico) separati da punto e virgola: nessun formato proprietario
|
||||
di software terzi.
|
||||
8. **Prova di accettazione.** Il test di integrazione chiude l'anno demo su SQLite e PostgreSQL: bilancio quadrato
|
||||
prima e dopo l'assestamento, conti a zero dopo il passo 7, apertura quadrata con il patrimonio uguale all'anno
|
||||
precedente, stampe PDF, blocco ed export.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Una correzione dopo un passo avanzato richiede di annullare i passi a ritroso: è più lungo ma ogni stato intermedio
|
||||
resta coerente e verificabile.
|
||||
- L'annullamento del passo 2 toglie tutti gli ammortamenti dell'anno (ADR 0041).
|
||||
- Il TFR è una stima utile solo se le paghe non lo accantonano già; con le paghe esterne la chiusura non aggiunge
|
||||
nulla.
|
||||
- Il libro inventari non è tra le stampe: arriva con i report (M13).
|
||||
@@ -0,0 +1,54 @@
|
||||
# ADR 0044 - Schermate senza PNG, banche senza elenco, canali SDI rimandati
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-16
|
||||
- **Modifica:** emendamento E4 di `CLAUDE.md`; ADR 0011, 0026, 0027 punto 6, 0028 punto 7, 0040; issue #35, #45, #78
|
||||
|
||||
## Contesto
|
||||
|
||||
Tre issue aspettavano qualcosa dal titolare:
|
||||
|
||||
- **#35:** i PNG ad alta risoluzione delle 66 schermate che hanno solo la miniatura.
|
||||
- **#45:** una fonte con licenza compatibile per l'elenco delle banche ABI/CAB.
|
||||
- **#78:** la scelta degli intermediari SDI, l'accreditamento SdICoop e una casella PEC di prova.
|
||||
|
||||
Il 2026-11-16 il titolare ha risposto su tutte e tre:
|
||||
|
||||
- **#35:** il materiale consegnato è tutto quello che esiste. Sono 22 schermate ad alta risoluzione più la galleria,
|
||||
e nessun'altra fonte (repository, cartella privata, allegati delle issue) ne contiene altre.
|
||||
- **#45:** rinuncia ai dati precaricati delle banche. Indicherà una fonte se e quando la troverà.
|
||||
- **#78:** intermediari, SdICoop e PEC reale sono lasciati da parte per ora.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Le miniature sono la specifica finale delle schermate senza PNG.** Nessun PNG ad alta risoluzione verrà
|
||||
aggiunto alle 66 schermate *solo miniatura*. Le schermate si disegnano in base a tre fonti:
|
||||
- la miniatura, che fissa disposizione, gruppi e colonne;
|
||||
- SPEC §10-§12;
|
||||
- i componenti dell'applicazione già costruiti, con i token di `mockup.css` e i mattoni della schermata più
|
||||
simile (SPEC §10.1 regola 4).
|
||||
|
||||
Dove la miniatura non basta, decide chi sviluppa seguendo lo stile del gestionale, senza chiedere un PNG.
|
||||
I dettagli scelti così vanno nella pagina wiki della schermata.
|
||||
2. **Banche senza elenco precaricato.** I dati di base non contengono l'elenco ABI/CAB e `ItalianBankDirectory`
|
||||
resta vuoto. Dall'IBAN si leggono sempre ABI e CAB. Nome della banca e BIC vengono da un conto dell'azienda
|
||||
presso la stessa banca, oppure si scrivono a mano (ADR 0027 punto 6). Se il titolare indicherà una fonte con una
|
||||
licenza che permette di ridistribuirla in un repository pubblico, l'elenco entrerà come nuova versione dei dati di
|
||||
base, solo in aggiunta (ADR 0026 punto 3).
|
||||
3. **Canali SDI reali rimandati.** Lo sviluppo continua con i canali simulati dell'ADR 0040. Fino a una scelta del
|
||||
titolare valgono queste regole:
|
||||
- i connettori A e B restano generici;
|
||||
- l'endpoint SdICoop resta disponibile ma non accreditato;
|
||||
- la PEC si prova contro il server di posta finto dei test.
|
||||
|
||||
L'issue #78 resta aperta nel backlog, senza milestone e senza l'etichetta `Status/In attesa utente`.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le issue #35 e #45 si chiudono. L'issue #78 non blocca nessuna milestone.
|
||||
- Le schermate di M11-M14 non aspettano materiale dal titolare. Il rischio è che una di esse si discosti dall'idea
|
||||
originale in un dettaglio che la miniatura non mostra; si corregge con un'issue quando il titolare la vede.
|
||||
- Chi usa più conti presso banche diverse scrive nome e BIC una volta per banca. La compilazione automatica li
|
||||
riprende poi dal conto dell'azienda.
|
||||
- Prima di usare in produzione la fatturazione elettronica serve comunque una PEC o un intermediario reale. La guida
|
||||
*Fatturazione elettronica* della wiki lo dice già.
|
||||
@@ -20,10 +20,10 @@ I mockup sono la **specifica visiva vincolante** dell'interfaccia (SPEC §10.1).
|
||||
| `thumbs/` | Miniature 401x241 di **tutte** le 88 schermate, ritagliate dalla galleria, con lo stesso nome file |
|
||||
| `mockup.css` | Token (`--kh-*`) e classi dei componenti usati per disegnare i mockup |
|
||||
|
||||
Le schermate segnate *solo miniatura* non sono ancora disponibili in alta risoluzione: si lavora con la miniatura,
|
||||
`mockup.css` e le descrizioni di SPEC §10-§12 (regola 4). La richiesta dei PNG mancanti è tracciata da un'issue con
|
||||
etichetta `Status/In attesa utente` nella milestone M3. Quando un PNG arriva va copiato in `png/` con lo stesso nome
|
||||
e questa tabella va aggiornata.
|
||||
Le schermate segnate *solo miniatura* non hanno e non avranno un PNG ad alta risoluzione (ADR 0044, issue #35): si
|
||||
lavora con la miniatura, `mockup.css`, le descrizioni di SPEC §10-§12 e i mattoni della schermata più simile
|
||||
(regola 4). I dettagli che la miniatura non mostra si decidono seguendo la grafica dei componenti già costruiti e si
|
||||
descrivono nella pagina wiki della schermata.
|
||||
|
||||
Alcuni mockup contengono dettagli superati dagli emendamenti di `CLAUDE.md` (ad esempio 085 mostra ancora `ghcr.io`
|
||||
come registro): in quei casi prevale l'emendamento (registro pacchetti di Gitea).
|
||||
|
||||
@@ -87,7 +87,8 @@ fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota
|
||||

|
||||
|
||||
**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).
|
||||
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -1,113 +1,142 @@
|
||||
# Cespiti
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M10)
|
||||
> **Modulo di licenza:** ASSET · **Permessi principali:** `assets.asset.write`, `assets.depreciation.post`, `assets.asset.dispose` · **Specifica:** SPEC §11.7, §14
|
||||
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** ASSET · **Permessi principali:** `assets.asset.read` (registro, piano, stampe),
|
||||
> `assets.asset.write` (cespiti, categorie, dismissioni), `assets.depreciation.post` (registrare e annullare gli
|
||||
> ammortamenti) · **Specifica:** SPEC §11.7, §14, ADR 0041
|
||||
|
||||
## A cosa serve
|
||||
|
||||
Il modulo Cespiti tiene il **registro dei beni ammortizzabili**: anagrafica dei beni, categorie con coefficienti,
|
||||
piano di ammortamento civilistico e fiscale, calcolo e contabilizzazione delle quote annuali, dismissioni con
|
||||
plusvalenza o minusvalenza, rivalutazioni e stampa del registro.
|
||||
Il modulo Cespiti tiene il **registro dei beni ammortizzabili**: le categorie con i coefficienti ministeriali, i beni
|
||||
con il piano di ammortamento civilistico e fiscale, la registrazione delle quote di fine anno, le dismissioni con la
|
||||
plusvalenza o la minusvalenza e la stampa del **registro dei beni ammortizzabili** (libro cespiti).
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu laterale **Cespiti**, con le voci **Registro cespiti**, **Ammortamenti**, **Categorie**.
|
||||
|
||||
## Schermate
|
||||
|
||||

|
||||
*Mockup 048 — registro dei beni con categoria, coefficiente, data di acquisto, costo storico, fondo, residuo, quota dell'anno e stato; sotto, il piano di ammortamento del cespite selezionato (civilistico e fiscale) e la scheda con conti, fattura di acquisto, deducibilità e ubicazione (anteprima ridotta)*
|
||||
Menu laterale **Cespiti**, con tre voci: **Registro cespiti**, **Ammortamenti**, **Categorie**. Gli ammortamenti si
|
||||
registrano anche dal passo 2 della [chiusura dell'esercizio](Chiusura-e-bilancio).
|
||||
|
||||
## Il registro
|
||||
|
||||
| Colonna | Significato |
|
||||

|
||||
*Il registro dell'azienda demo: quattro beni con categoria, aliquota, entrata in funzione, costo storico, fondo e
|
||||
valore netto; sotto, il piano di ammortamento del furgone selezionato e il dettaglio con i movimenti.*
|
||||
|
||||
La striscia in alto riassume i cespiti **attivi**, il **costo storico**, il **fondo** e il **valore netto**. Si filtra
|
||||
per testo (codice, descrizione, matricola), esercizio, categoria e stato. Un clic sulla riga apre sotto:
|
||||
|
||||
- il **piano di ammortamento**: per ogni esercizio il fondo iniziale, l'aliquota, la quota civilistica e quella
|
||||
fiscale, il fondo e il valore netto a fine anno; l'anno scelto nei filtri è evidenziato;
|
||||
- il **dettaglio**: categoria, data di acquisto, fornitore e documento, ubicazione, fondo fiscale, ultimo esercizio
|
||||
ammortizzato e l'elenco dei **movimenti** (acquisto, apertura, incremento, rivalutazione, ammortamento,
|
||||
dismissione); da qui **Modifica**, **Dismetti** ed **Elimina**.
|
||||
|
||||
| Stato | Significato |
|
||||
|---|---|
|
||||
| **Codice** | automatico, maschera `CESP-{seq:0000}` (es. `CESP-0041`; vedi [Tabelle azienda](Tabelle-azienda)) |
|
||||
| Descrizione, Categoria, Coeff. | il coefficiente viene dalla categoria |
|
||||
| Acquisto | data di entrata in funzione / acquisto |
|
||||
| Costo storico, Fondo, Residuo | valori alla data |
|
||||
| Quota anno | quota di ammortamento dell'esercizio |
|
||||
| Stato | *In uso*, *Primo anno (50 %)*, *Limite fiscale raggiunto*, *Ammortizzato*, *Dismesso* (con plus o minusvalenza) |
|
||||
| **In ammortamento** | il bene ha ancora un valore da ammortizzare |
|
||||
| **Ammortizzato** | il fondo ha raggiunto il costo (meno l'eventuale valore residuo) |
|
||||
| **Dismesso** | il bene è uscito dal patrimonio; resta nel registro con il movimento di dismissione |
|
||||
|
||||
Filtri per esercizio, categoria e stato. In testa un avviso ricorda se gli ammortamenti dell'anno non sono ancora
|
||||
contabilizzati. Il pannello **Dati cespite** mostra categoria e coefficiente, **conto cespite**, **conto fondo**,
|
||||
**conto quota** (ammortamento), fattura di acquisto, percentuale di deducibilità e ubicazione.
|
||||
## Inserire un cespite
|
||||
|
||||
Un cespite nasce di solito dalla **fattura di acquisto** (righe con articolo di tipo *cespite*, vedi
|
||||
[Acquisti](Acquisti)) oppure si inserisce a mano con **+**.
|
||||
1. **Registro cespiti → Nuovo cespite**.
|
||||
2. Scegli la **categoria** (aliquote e conti vengono da lì) e scrivi la descrizione. Il **codice** vuoto prende il
|
||||
prossimo numero; la matricola e l'ubicazione sono facoltative.
|
||||
3. Indica **data di acquisto** e **data di entrata in funzione**: l'ammortamento parte dall'anno di entrata in
|
||||
funzione, che non può precedere l'acquisto.
|
||||
4. Scrivi il **costo** e, se serve, il valore residuo. Le aliquote civilistica e fiscale vuote seguono la categoria;
|
||||
compilale solo per il singolo bene.
|
||||
5. Per un bene acquistato **prima dell'avvio di Khaemhat** indica i **fondi iniziali** (civilistico e fiscale) e
|
||||
l'**ultimo esercizio già ammortizzato** fuori da Khaemhat: i fondi entrano con la scrittura di apertura dei conti.
|
||||
Facoltativi anche quantità, fornitore, documento di acquisto, ubicazione e matricola.
|
||||
6. Salva. Il piano si ricalcola subito.
|
||||
|
||||
Un cespite con ammortamenti già registrati non si elimina: si dismette.
|
||||
|
||||
## Categorie e coefficienti
|
||||
|
||||
Le **categorie** sono caricate con i dati di base e riportano i coefficienti della tabella ministeriale (**DM 31
|
||||
dicembre 1988**), per esempio fabbricati industriali, macchinari, automezzi, autovetture, macchine elettroniche
|
||||
d'ufficio. Per ogni categoria si impostano:
|
||||

|
||||
*Le categorie standard create dal pacchetto fiscale italiano, con le aliquote e i conti di cespite, fondo e quota.*
|
||||
|
||||
- coefficiente fiscale e coefficiente civilistico (possono differire);
|
||||
- conti contabili (cespite, fondo, quota, plus/minusvalenze);
|
||||
- eventuale **limite di costo fiscalmente rilevante** e **percentuale di deducibilità** (vedi autovetture);
|
||||
- se applicare la riduzione al 50 % nel primo esercizio.
|
||||
**Cespiti → Categorie → Categorie standard** crea le categorie più comuni con i coefficienti della tabella allegata
|
||||
al **DM 31/12/1988** (fabbricati, impianti, attrezzature, mobili, macchine d'ufficio elettroniche, autocarri,
|
||||
autovetture, software e altri beni immateriali con i limiti dell'art. 103 TUIR). La tabella dipende dal settore di
|
||||
attività: ogni aliquota si può cambiare sulla propria categoria.
|
||||
|
||||
## Regole di ammortamento
|
||||
| Campo | A cosa serve |
|
||||
|---|---|
|
||||
| **Tipo** | materiale o immateriale (decide la voce di bilancio del fondo) |
|
||||
| **Aliquota civilistica** e **fiscale** | la quota annua in percentuale; la fiscale non supera il coefficiente ministeriale |
|
||||
| **Metà aliquota civilistica nel primo esercizio** | applica la riduzione al 50 % anche al piano civilistico (quello fiscale la applica sempre) |
|
||||
| **Limite di costo** e **deducibilità %** | per le autovetture (art. 164 TUIR): ad esempio 18.075,99 di costo e 20 % di deducibilità |
|
||||
| **Conto del cespite**, **del fondo**, **dell'ammortamento** | i conti della scrittura di fine anno e della dismissione |
|
||||
|
||||
## Regole di calcolo
|
||||
|
||||
| Regola | Come la applica Khaemhat |
|
||||
|---|---|
|
||||
| **Primo anno al 50 %** | nell'esercizio di entrata in funzione la quota fiscale è la metà di quella ordinaria |
|
||||
| **Civilistico e fiscale** | due piani paralleli (quota e fondo civilistici, quota e fondo fiscali); le differenze restano visibili nel piano |
|
||||
| **Autovetture** | limite al costo fiscalmente rilevante e deducibilità ridotta secondo la normativa (art. 164 TUIR); i valori sono parametri della categoria, oggi € 18.075,99 di costo massimo per le autovetture a uso promiscuo, e vanno verificati a ogni aggiornamento normativo |
|
||||
| **Beni di costo non superiore a € 516,46** | possono essere ammortizzati interamente nell'esercizio di acquisto |
|
||||
| **Fine ammortamento** | la quota si azzera quando il residuo arriva a zero (stato *Ammortizzato*) |
|
||||
| **Quote costanti** | aliquota per costo, mai più di quanto resta da ammortizzare |
|
||||
| **Primo anno al 50 %** | nel piano fiscale sempre; nel civilistico se la categoria lo chiede |
|
||||
| **Civilistico e fiscale** | due piani paralleli; la differenza è una variazione in dichiarazione dei redditi e non genera scritture |
|
||||
| **Beni di costo unitario fino a 516,46 €** | si mettono in una categoria con aliquota 100 %: sono ammortizzati per intero nel primo anno |
|
||||
| **Fine ammortamento** | quando il fondo raggiunge il costo il bene passa a *Ammortizzato* |
|
||||
|
||||
Il **piano di ammortamento** (riquadro in basso nel mockup) elenca per ogni esercizio quota e fondo civilistici,
|
||||
quota e fondo fiscali, residuo e stato: *Contabilizzato* per gli anni registrati, *Simulato* per quelli futuri.
|
||||
## Ammortamenti di fine anno
|
||||
|
||||
## Piano simulato
|
||||

|
||||
*Gli ammortamenti 2026 dell'azienda demo prima della registrazione: quote civilistiche e fiscali per cespite e
|
||||
totali.*
|
||||
|
||||
Il piano degli esercizi futuri è sempre una **simulazione**: cambia se si modificano coefficiente, valore o date.
|
||||
Serve a prevedere le quote dei prossimi anni (budget, bilancio previsionale) senza produrre registrazioni.
|
||||
1. **Cespiti → Ammortamenti**, scegli l'esercizio.
|
||||
2. Controlla le quote: la striscia mostra il totale civilistico, quello fiscale e la loro differenza.
|
||||
3. **Registra ammortamenti** scrive una registrazione al 31/12 con una riga per categoria (quota in Dare sul conto di
|
||||
ammortamento, fondo in Avere) e aggiorna fondi e movimenti dei beni.
|
||||
4. Finché le registrazioni non sono definitive, **Annulla registrazione** toglie la scrittura e riporta i fondi
|
||||
indietro.
|
||||
|
||||
## Calcolo e contabilizzazione annuale
|
||||
|
||||
1. **Cespiti → Registro cespiti**, scegli l'esercizio e premi **Calcola ammortamenti AAAA**.
|
||||
2. Controlla le quote calcolate e gli stati (primo anno, limite fiscale raggiunto…).
|
||||
3. Premi **Contabilizza**: viene generata la registrazione con causale **AMM** (quote a costo, fondi in avere).
|
||||
4. Le quote dell'esercizio risultano *Contabilizzate* nel piano.
|
||||
|
||||
Il calcolo è anche il passo 2 della [chiusura dell'esercizio](Contabilita) e la procedura **Ammortamenti** del catalogo
|
||||
([Automazioni](Automazioni)). La procedura è idempotente: rieseguirla non duplica le quote.
|
||||
Il passo 2 della [chiusura](Chiusura-e-bilancio) registra gli ammortamenti se non sono già stati registrati qui.
|
||||
|
||||
## Dismissioni
|
||||
|
||||
1. Apri il cespite e scegli l'azione di dismissione (per esempio vendita o eliminazione; l'elenco dei tipi di
|
||||
movimento sarà fissato in sviluppo).
|
||||
2. Se è una **vendita**, Khaemhat propone la fattura di **cessione cespite (TD26)** in [Vendite](Vendite).
|
||||
3. Alla data di dismissione calcola la quota dell'anno, chiude fondo e costo e rileva la **plusvalenza** o la
|
||||
**minusvalenza** sui conti della categoria.
|
||||
4. Il cespite passa allo stato *Dismesso* e resta nel registro.
|
||||
1. Seleziona il cespite e premi **Dismetti**.
|
||||
2. Indica data e **prezzo** (la contropartita è il conto *altri crediti*, che si chiude con l'incasso o con la
|
||||
fattura). Il **costo dismesso** vuoto significa dismissione totale; un importo minore è una dismissione parziale.
|
||||
3. Khaemhat toglie dai conti il costo e la quota corrispondente del fondo, porta il prezzo sulla contropartita e la
|
||||
differenza a **plusvalenza** o **minusvalenza** (conti del pacchetto fiscale).
|
||||
4. Nell'anno della dismissione non si calcola la quota di ammortamento (scelta prudente spiegata nell'ADR 0041): se
|
||||
serve, registra prima gli ammortamenti fino alla data con una registrazione manuale.
|
||||
|
||||
## Rivalutazioni
|
||||
La fattura di vendita del bene si emette come una normale fattura in [Vendite](Vendite).
|
||||
|
||||
Le **rivalutazioni** aumentano il valore del bene (e, a seconda della norma, il fondo) da una data; il piano di
|
||||
ammortamento si ricalcola da quella data. Le modalità di ogni specifica legge di rivalutazione saranno definite in
|
||||
sviluppo quando servono.
|
||||
## Stampa del registro
|
||||
|
||||
## Registro dei beni ammortizzabili
|
||||
**Stampa registro** (dal registro o dagli ammortamenti) produce il PDF del registro dei beni ammortizzabili
|
||||
dell'esercizio, con costo, fondo, quota e valore netto per categoria. La stampa definitiva è una delle stampe del
|
||||
passo 9 della [chiusura](Chiusura-e-bilancio).
|
||||
|
||||
**Registro cespiti** stampa il registro dei beni ammortizzabili (provvisorio o definitivo). La stampa definitiva è
|
||||
uno dei passi della [chiusura dell'esercizio](Contabilita). Il registro si esporta anche in XLSX e PDF.
|
||||
## Dati di esempio
|
||||
|
||||
I dati dimostrativi creano le categorie standard e quattro beni (un furgone, scaffalature, arredi già in uso con i
|
||||
fondi iniziali, e un server acquistato nell'anno con la sua registrazione), così il registro, gli ammortamenti e la
|
||||
chiusura si possono provare subito. Vedi [Dati di base e di esempio](Dati-di-base-e-esempio).
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Serve il modulo **ASSET**; per contabilizzare servono anche ACCT e i permessi di prima nota. I codici dei permessi in
|
||||
testa sono indicativi (convenzione `modulo.entità.azione`, SPEC §7.2) e saranno fissati in sviluppo.
|
||||
| Permesso | Consente |
|
||||
|---|---|
|
||||
| `assets.asset.read` | registro, piano, ammortamenti (sola lettura), stampe |
|
||||
| `assets.asset.write` | inserire, modificare, eliminare e dismettere cespiti; categorie |
|
||||
| `assets.depreciation.post` | registrare e annullare gli ammortamenti |
|
||||
|
||||
Serve il modulo **ASSET**; le registrazioni richiedono anche **ACCT**.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
**Ho contabilizzato e poi corretto un coefficiente.** Annulla la registrazione AMM (storno) e rilancia il calcolo:
|
||||
la procedura ricalcola le quote dell'esercizio.
|
||||
**Ho registrato gli ammortamenti e poi corretto un'aliquota.** Annulla la registrazione, correggi e registra di nuovo:
|
||||
è possibile finché la registrazione non è definitiva.
|
||||
|
||||
**Il bene è in uso da metà anno: la quota fiscale è ridotta?** Sì, se la categoria applica il primo anno al 50 %.
|
||||
**Perché la quota fiscale è diversa dalla civilistica?** Le aliquote possono differire e il primo anno al 50 % vale
|
||||
sempre per il fiscale; la differenza si gestisce in dichiarazione dei redditi.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
[Contabilità](Contabilita) · [Acquisti](Acquisti) · [Vendite](Vendite) · [IVA](IVA) · [Automazioni](Automazioni) ·
|
||||
[Report](Report) · [Fiscalità italiana](Fiscalita-italiana)
|
||||
[Chiusura e bilancio](Chiusura-e-bilancio) · [Contabilità](Contabilita) · [Acquisti](Acquisti) · [Vendite](Vendite) ·
|
||||
[Fiscalità italiana](Fiscalita-italiana)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Changelog
|
||||
|
||||
> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13
|
||||
> **Stato:** completa per 0.10.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,9 @@ Le novità di ogni versione sono nel file
|
||||
|
||||
| Versione | Data | Contenuto |
|
||||
|---|---|---|
|
||||
| 0.10.0 | 2026-11-13 | M10 — Cespiti, Intrastat, chiusura, bilancio: categorie con i coefficienti ministeriali, registro cespiti con piano civilistico e fiscale, ammortamenti e dismissioni; elenchi Intrastat dai documenti con periodicità dalle soglie e file SCAMBI.CEE; registro delle dichiarazioni d'intento con plafond controllato alla conferma della fattura; ratei, risconti e differenze di cambio; chiusura guidata in nove passi con riapertura, stampe definitive e blocco; bilancio CEE ordinario, abbreviato e micro con riclassificato, indici ed export per il commercialista |
|
||||
| 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. |
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# Chiusura dell'esercizio e bilancio
|
||||
|
||||
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.year.close` (ratei e risconti, chiusura, blocco),
|
||||
> `ledger.entry.read` (bilancio), `reports.accountant.export` (esportazione per il commercialista) · **Specifica:**
|
||||
> SPEC §11.7, ADR 0043
|
||||
|
||||
A fine anno la contabilità va **assestata** (ammortamenti, ratei e risconti, rimanenze, accantonamenti), **chiusa**
|
||||
(conti economici e patrimoniali) e **riaperta** nell'esercizio successivo; poi si stampano i libri definitivi e si
|
||||
redige il **bilancio**. Khaemhat guida tutto in **nove passi**, ognuno ripetibile e annullabile fino alle stampe
|
||||
definitive, e mostra il bilancio CEE, il riclassificato e gli indici in ogni momento dell'anno.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu **Contabilità**: **Ratei e risconti**, **Chiusura esercizio**, **Bilancio** (schede *Verifica*, *CEE*,
|
||||
*Riclassificato*, *Indici*). Gli ammortamenti stanno in [Cespiti](Cespiti).
|
||||
|
||||
## Ratei e risconti
|
||||
|
||||

|
||||
*I ratei e risconti 2026 dell'azienda demo: il risconto attivo del premio di assicurazione del furgone, pagato il
|
||||
1° ottobre per dodici mesi, di cui 273 giorni su 365 sono di competenza del 2027.*
|
||||
|
||||
I costi e i ricavi che stanno a cavallo di due esercizi si ripartiscono **per giorni**:
|
||||
|
||||
| Tipo | Quando | Scrittura al 31/12 |
|
||||
|---|---|---|
|
||||
| **Rateo attivo** | ricavo di competenza dell'anno che si incasserà dopo | ratei attivi in Dare, ricavo in Avere |
|
||||
| **Rateo passivo** | costo di competenza dell'anno che si pagherà dopo | costo in Dare, ratei passivi in Avere |
|
||||
| **Risconto attivo** | costo già registrato, in parte di competenza dell'anno dopo | risconti attivi in Dare, costo in Avere |
|
||||
| **Risconto passivo** | ricavo già registrato, in parte di competenza dell'anno dopo | ricavo in Dare, risconti passivi in Avere |
|
||||
|
||||
1. **Contabilità → Ratei e risconti**, scegli l'esercizio.
|
||||
2. **Proponi dai documenti** crea i risconti delle fatture di acquisto registrate sui conti di costi che di solito
|
||||
stanno a cavallo dell'anno (assicurazioni, affitti, leasing, noleggi, software, abbonamenti), con un periodo di
|
||||
dodici mesi dalla data del documento: **controlla sempre il periodo**. Un costo già proposto non si ripropone.
|
||||
3. **Nuovo rateo o risconto** per inserirne uno a mano: tipo, conto, descrizione, importo totale e periodo di
|
||||
competenza. La **rettifica** si calcola subito (giorni fuori dall'esercizio su giorni totali).
|
||||
4. Un clic sulla riga la modifica o la elimina, finché la chiusura non l'ha registrata.
|
||||
|
||||
Sotto, **Differenze di cambio al 31/12** elenca le partite aperte in valuta con il residuo in valuta, il cambio del
|
||||
documento, il cambio dell'ultimo giorno dell'anno (da *Tabelle azienda → Valute*, aggiornato anche dai cambi BCE) e
|
||||
l'**utile o perdita su cambi**. Se il cambio manca la riga lo segnala.
|
||||
|
||||
Il **passo 3** della chiusura registra ratei, risconti e differenze di cambio; il **passo 8** li storna il primo giorno
|
||||
dell'esercizio successivo.
|
||||
|
||||
## La chiusura guidata
|
||||
|
||||

|
||||
*La chiusura 2026 dell'azienda demo con i nove passi eseguiti: per ognuno le registrazioni, l'importo, l'esito e chi
|
||||
l'ha eseguito; sotto, le stampe definitive da scaricare.*
|
||||
|
||||
**Contabilità → Chiusura esercizio**, scegli l'esercizio e premi **Esegui passo N**. I passi si eseguono **in
|
||||
ordine**; l'ultimo eseguito si può **ripetere** (dopo una correzione) o **annullare** (le sue registrazioni
|
||||
spariscono) finché non si arriva alle stampe definitive. In alto i badge mostrano lo stato degli esercizi (*aperto*,
|
||||
*in chiusura*, *chiuso*).
|
||||
|
||||
| # | Passo | Cosa fa |
|
||||
|---|---|---|
|
||||
| 1 | **Controlli preliminari** | nessuna registrazione provvisoria, registrazioni quadrate, bilancio di verifica in pareggio; segnala i conti con saldo senza voce di bilancio, l'esercizio non ancora terminato e gli esercizi precedenti ancora aperti. L'importo è il risultato provvisorio |
|
||||
| 2 | **Ammortamenti** | registra le quote civilistiche dei [cespiti](Cespiti), una riga per categoria, se non sono già registrate |
|
||||
| 3 | **Ratei e risconti** | registra ratei, risconti e differenze di cambio al 31/12 |
|
||||
| 4 | **Rimanenze finali** | storna le rimanenze iniziali a costo e carica le rimanenze finali di [magazzino](Magazzino) al **costo medio ponderato** |
|
||||
| 5 | **Accantonamenti** | svalutazione crediti dello **0,5 %** dei crediti verso clienti aperti (limite dell'art. 106 TUIR) e quota **TFR** dell'anno (retribuzioni diviso 13,5, meno quanto già accantonato dalle paghe) |
|
||||
| 6 | **Chiusura conti economici** | gira costi e ricavi a *Conto economico* e porta il **risultato** (utile o perdita) a patrimonio netto; l'esercizio passa a *in chiusura* |
|
||||
| 7 | **Chiusura conti patrimoniali** | chiude attività e passività a *Stato patrimoniale finale*, per conto e per cliente o fornitore |
|
||||
| 8 | **Apertura esercizio successivo** | crea l'esercizio se manca, riapre i conti con *Stato patrimoniale iniziale* (partite di clienti e fornitori comprese) e storna ratei e risconti |
|
||||
| 9 | **Stampe definitive** | rende **definitive** tutte le registrazioni dell'anno, numera il libro giornale e conserva le stampe: libro giornale, registri IVA, registro cespiti, bilancio CEE |
|
||||
|
||||
Accanto a ogni passo compaiono i messaggi: in grigio le informazioni, in arancione ciò che va verificato, in rosso gli
|
||||
errori che bloccano (il passo 1 con un errore non lascia proseguire).
|
||||
|
||||

|
||||
*Il passo 1 eseguito a novembre: tutto quadra, ma l'esercizio non è ancora terminato e la chiusura risulta
|
||||
anticipata (esito «Da verificare»).*
|
||||
|
||||
### Prima del passo 9
|
||||
|
||||
Il passo 9 **non si annulla**: prima controlla il bilancio, i registri IVA (le stampe dei registri dentro la chiusura
|
||||
sono quelle dell'anno; per la vidimazione e la numerazione delle pagine fa fede [IVA](IVA)), i cespiti e i ratei.
|
||||
Le registrazioni del nuovo esercizio si possono fare anche durante la chiusura.
|
||||
|
||||
### Blocco dell'esercizio
|
||||
|
||||
Dopo il passo 9 **Blocca esercizio** chiude definitivamente l'anno: diventa di **sola lettura** e non si può più
|
||||
registrare nulla con data fino al 31/12. L'esercizio passa a *chiuso*.
|
||||
|
||||
## Bilancio CEE
|
||||
|
||||

|
||||
*Il bilancio CEE 2026 dell'azienda demo, schema ordinario: stato patrimoniale e conto economico con l'anno
|
||||
precedente e la variazione percentuale.*
|
||||
|
||||
**Contabilità → Bilancio → CEE** costruisce lo **stato patrimoniale** (art. 2424 c.c.) e il **conto economico**
|
||||
(art. 2425 c.c.) dell'esercizio scelto, con l'anno precedente e la variazione, dai saldi dei conti a cui il piano dei
|
||||
conti associa una **voce di bilancio** (vedi [Contabilità](Contabilita#piano-dei-conti)).
|
||||
|
||||
- **Schema**: *Ordinario*, *Abbreviato* (art. 2435-bis) o *Micro-impresa* (art. 2435-ter, stesse voci
|
||||
dell'abbreviato).
|
||||
- La striscia mostra totale attivo e passivo, risultato d'esercizio e quadratura.
|
||||
- Se ci sono conti con saldo **senza voce**, un avviso li elenca: assegna la voce nel piano dei conti.
|
||||
- Un clic su una voce mostra i **conti** che la compongono con i saldi dei due anni.
|
||||
- Le scritture dei passi 6 e 7 della chiusura non entrano nel calcolo: un esercizio chiuso mostra comunque i suoi
|
||||
saldi.
|
||||
- **Stampa bilancio** produce il PDF; **Esporta per il commercialista** scarica uno ZIP con cinque file CSV (piano
|
||||
dei conti, bilancio di verifica, movimenti, stato patrimoniale, conto economico).
|
||||
|
||||
## Riclassificato e indici
|
||||
|
||||

|
||||
*Lo stato patrimoniale riclassificato secondo il criterio finanziario.*
|
||||
|
||||
La scheda **Riclassificato** propone lo **stato patrimoniale finanziario** (attivo per liquidità, passivo per
|
||||
esigibilità) e il **conto economico a valore aggiunto**.
|
||||
|
||||

|
||||
*Gli indici di bilancio con la formula e il valore dei due anni.*
|
||||
|
||||
La scheda **Indici** calcola redditività (ROE, ROI, ROS, rotazione del capitale investito), liquidità (indice di
|
||||
disponibilità e di liquidità), solidità (indipendenza finanziaria, leva, copertura delle immobilizzazioni) e i giorni
|
||||
medi di incasso e di pagamento. Un indice senza denominatore mostra un trattino.
|
||||
|
||||
## Prova con i dati di esempio
|
||||
|
||||
I dati dimostrativi aprono l'anno con una scrittura di apertura (cespiti e fondi, rimanenze, banca, capitale),
|
||||
registrano un premio di assicurazione da riscontare e i cespiti: la chiusura dell'anno demo si può eseguire dal
|
||||
passo 1 al 9 e verificare il bilancio. Le prove automatiche fanno proprio questo, su SQLite e su PostgreSQL.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
| Permesso | Consente |
|
||||
|---|---|
|
||||
| `ledger.entry.read` | bilancio CEE, riclassificato, indici, stampa |
|
||||
| `ledger.year.close` | ratei e risconti, chiusura guidata, blocco dell'esercizio |
|
||||
| `reports.accountant.export` | esportazione per il commercialista |
|
||||
|
||||
Serve il modulo **ACCT**; il passo 2 usa i cespiti se è attivo **ASSET**.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
**Il passo 1 è rosso.** Leggi i messaggi: di solito ci sono registrazioni provvisorie da registrare o eliminare in
|
||||
[Prima nota](Contabilita#prima-nota). Correggi e premi **Ripeti passo 1**.
|
||||
|
||||
**Ho dimenticato una fattura dopo il passo 6.** Annulla i passi dal più recente fino al 5 (uno alla volta), registra
|
||||
la fattura e riesegui i passi.
|
||||
|
||||
**Dove finisce il risultato?** Nel conto *utile (perdita) dell'esercizio* del patrimonio netto; la destinazione
|
||||
dell'utile si registra a mano nel nuovo esercizio dopo l'approvazione del bilancio.
|
||||
|
||||
**Il TFR è giusto?** È una stima (retribuzioni dell'anno diviso 13,5 meno quanto già accantonato): se le paghe sono
|
||||
elaborate fuori, registra la quota del consulente e la chiusura non aggiunge nulla.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
[Contabilità](Contabilita) · [Cespiti](Cespiti) · [IVA](IVA) · [Magazzino](Magazzino) · [Scadenzario](Scadenzario) ·
|
||||
[Fiscalità italiana](Fiscalita-italiana) · [Report](Report)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Contabilità generale
|
||||
|
||||
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
|
||||
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.account.read`/`write` (piano dei conti e causali), `ledger.entry.read`/`write` (prima nota, partitari, bilancio), `ledger.entry.finalize` (registrazioni definitive) · **Specifica:** SPEC §11.7, §14, ADR 0036, ADR 0037
|
||||
|
||||
Il modulo **Contabilità** tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
|
||||
@@ -17,9 +17,9 @@ nella pagina [IVA](IVA); le regole italiane usate (piano dei conti modello, codi
|
||||
> registrazioni ricorrenti, lo storno, le registrazioni definitive con il numero di libro giornale, i partitari con
|
||||
> estratto conto e partite, i mastrini, il bilancio di verifica e le stampe del bilancio e del libro giornale.
|
||||
> Dalla 0.8 incassi, pagamenti, distinte e riconciliazione bancaria scrivono le loro registrazioni dallo
|
||||
> [Scadenzario](Scadenzario). Arrivano più avanti: **chiusura
|
||||
> dell'esercizio**, ratei e risconti, **bilancio CEE** riclassificato e **cespiti** (M10). Non ci sono ancora
|
||||
> l'import del piano dei conti da file e l'export per il commercialista.
|
||||
> [Scadenzario](Scadenzario). Dalla 0.10 ci sono la **chiusura guidata dell'esercizio** con ratei e risconti, il
|
||||
> **bilancio CEE** con riclassificato e indici e l'export per il commercialista ([Chiusura e bilancio](Chiusura-e-bilancio)),
|
||||
> e i [Cespiti](Cespiti). Non c'è ancora l'import del piano dei conti da file.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
@@ -189,7 +189,7 @@ bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano
|
||||
| **Riclassificazione** | voce del riclassificato, facoltativa |
|
||||
| **Partitario** | le righe indicano il cliente o il fornitore |
|
||||
| **Rilevante IVA** | il conto entra nelle registrazioni con IVA |
|
||||
| **Chiuso in automatico a fine esercizio** | il conto sarà chiuso dalla procedura di fine esercizio (M10) |
|
||||
| **Chiuso in automatico a fine esercizio** | il conto è chiuso dalla [chiusura dell'esercizio](Chiusura-e-bilancio) |
|
||||
| **Disattivato** | il conto resta nello storico ma non si usa più |
|
||||
|
||||
A sinistra l'**albero** con la ricerca per codice o descrizione; a destra i dati del conto scelto e, per i
|
||||
@@ -271,8 +271,8 @@ Le stampe sono file PDF da scaricare:
|
||||
| **Libro giornale di prova** | registrazioni registrate e definitive del periodo, in ordine di data, con le righe |
|
||||
| **Libro giornale definitivo** | solo le registrazioni definitive, con il numero di libro giornale e le pagine numerate dall'inizio dell'anno |
|
||||
|
||||
Il bilancio CEE (stato patrimoniale e conto economico civilistici), il riclassificato e gli indici arrivano con la
|
||||
chiusura dell'esercizio (M10).
|
||||
Le altre schede della pagina, **CEE**, **Riclassificato** e **Indici**, mostrano il bilancio d'esercizio: sono
|
||||
spiegate in [Chiusura e bilancio](Chiusura-e-bilancio).
|
||||
|
||||
## Dati demo
|
||||
|
||||
|
||||
@@ -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.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14
|
||||
|
||||
## A cosa serve
|
||||
@@ -52,7 +52,6 @@ Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità it
|
||||
| **Cespiti** | categorie di beni con i coefficienti di ammortamento ministeriali |
|
||||
| **Codici tributo F24** | IVA, ritenute, bollo, acconti |
|
||||
| **Code list SDI** | tipi documento (TD), modalità di pagamento (MP), regimi fiscali (RF) e altre liste della FatturaPA; regime RF01 predefinito |
|
||||
| **Banche ABI/CAB** | tabella per ricavare banca e BIC dall'IBAN |
|
||||
| **CRM** | pipeline e fasi, modelli e-mail |
|
||||
| **Sistema** | ruoli predefiniti, regole di automazione predefinite, attività programmate di sistema |
|
||||
|
||||
@@ -76,11 +75,13 @@ intervallo come `10121-10156` per le città con più CAP.
|
||||
|
||||
Ai comuni rinominati o nati da fusioni recenti (ad esempio Sanremo) il CAP può mancare: si completa a mano nella
|
||||
tabella *Comuni* o con l'**Importa CSV** (colonne `Code` e `PostalCodes`, più CAP separati da virgola). La
|
||||
compilazione dal CAP propone solo i comuni che hanno il CAP scritto. Le **banche ABI/CAB** non sono ancora incluse: banca e BIC dall'IBAN vengono da un conto
|
||||
dell'azienda presso la stessa banca. Un comune soppresso per fusione resta nella tabella finché non lo disattivi.
|
||||
compilazione dal CAP propone solo i comuni che hanno il CAP scritto. L'**elenco delle banche ABI/CAB** non è incluso: dall'IBAN
|
||||
Khaemhat legge ABI e CAB, mentre nome della banca e BIC vengono da un conto dell'azienda presso la stessa banca o si
|
||||
scrivono a mano la prima volta. Un comune soppresso per fusione resta nella tabella finché non lo disattivi.
|
||||
|
||||
Le altre voci dell'elenco (piano dei conti, causali contabili, registri IVA, cespiti, codici tributo, CRM) arrivano con i
|
||||
moduli che le usano.
|
||||
Le categorie dei cespiti si creano da **Cespiti → Categorie → Categorie standard** (vedi [Cespiti](Cespiti)). Le altre
|
||||
voci dell'elenco (piano dei conti, causali contabili, registri IVA, codici tributo, CRM) arrivano con i moduli che le
|
||||
usano.
|
||||
|
||||
### Aggiorna tabelle di base
|
||||
|
||||
@@ -115,7 +116,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 +177,30 @@ 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 |
|
||||
|
||||
**Da M10** ci sono anche i dati di **fine anno** (vedi [Cespiti](Cespiti), [Intrastat](Intrastat),
|
||||
[Dichiarazioni d'intento](Dichiarazioni-d-intento) e [Chiusura e bilancio](Chiusura-e-bilancio)):
|
||||
|
||||
| Dati | Che cosa mostrano |
|
||||
|---|---|
|
||||
| Apertura dei conti | una registrazione al 1° gennaio con cespiti e fondi, rimanenze di magazzino, banca, capitale sociale e utili portati a nuovo |
|
||||
| Cespiti | le categorie standard e quattro beni: furgone, scaffalature e arredi già in uso con i fondi iniziali, un server acquistato nell'anno con la sua registrazione |
|
||||
| Risconto | il premio di assicurazione del furgone pagato il 1° ottobre per dodici mesi |
|
||||
| Dichiarazione d'intento | quella di Idrotermica Piemonte nel registro, con una fattura in N3.5 che consuma il plafond |
|
||||
| Intrastat | una fattura non imponibile art. 41 a Bergwerk Bau (Austria) con codici doganali e pesi, se la licenza comprende **INTRA** |
|
||||
|
||||
Con questi dati la chiusura dell'anno si esegue dal passo 1 al 9.
|
||||
|
||||
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 +216,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 +249,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 +259,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
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# Dichiarazioni d'intento
|
||||
|
||||
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `sales.intent.read` (registro e stampa), `sales.intent.write`
|
||||
> (inserire, modificare, revocare) · **Specifica:** SPEC §11.7, ADR 0042
|
||||
|
||||
Gli **esportatori abituali** acquistano senza IVA, entro un **plafond**, presentando al fornitore una **dichiarazione
|
||||
d'intento** trasmessa all'Agenzia delle Entrate. Khaemhat tiene il **registro cronologico** delle dichiarazioni
|
||||
ricevute dai clienti (e di quelle emesse verso i fornitori), aggiorna l'**utilizzato** con le fatture emesse,
|
||||
avvisa quando il plafond è quasi esaurito e **rifiuta la conferma** di una fattura senza dichiarazione valida o oltre
|
||||
il plafond.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
**Fatturazione elettronica → Dichiarazioni d'intento** (anche all'indirizzo `/vendite/dichiarazioni-intento`). La
|
||||
funzione è nel modulo base CORE.
|
||||
|
||||

|
||||
*Il registro delle dichiarazioni ricevute nel 2026: la dichiarazione di Idrotermica Piemonte con protocollo
|
||||
telematico, plafond, utilizzato, residuo e percentuale di utilizzo.*
|
||||
|
||||
## Il registro
|
||||
|
||||
Due schede: **Ricevute (clienti)** ed **Emesse (fornitori)**, filtrate per esercizio.
|
||||
|
||||
| Colonna | Significato |
|
||||
|---|---|
|
||||
| **Numero**, **Data** | numero progressivo del registro e data della dichiarazione |
|
||||
| **Cliente** / **Fornitore**, **Codice** | la controparte |
|
||||
| **Protocollo telematico** | protocollo della ricevuta dell'Agenzia: 17 cifre, trattino (o barra) e 6 cifre di progressivo |
|
||||
| **Plafond**, **Utilizzato**, **Residuo** | importo dichiarato, fatture già emesse, quanto resta |
|
||||
| **Esercizio** | anno di riferimento |
|
||||
| **Stato** | *Attiva* (con la percentuale di utilizzo, in arancione dal 90 %), *Esaurita*, *Revocata* |
|
||||
|
||||
**Stampa registro** produce il PDF del registro dell'anno.
|
||||
|
||||
## Registrare una dichiarazione ricevuta
|
||||
|
||||
1. **Nuova dichiarazione**, scheda *Ricevute*.
|
||||
2. Scegli il **cliente**, scrivi numero e data, il **protocollo telematico** e il **plafond**.
|
||||
3. Indica il periodo di validità (**valida dal**, **valida al**): ogni fattura va sulla dichiarazione più recente che ne copre la data.
|
||||
4. L'**utilizzato** si aggiorna da solo con le fatture: compilalo solo se una parte del plafond è già stata usata con
|
||||
fatture emesse fuori da Khaemhat.
|
||||
5. Salva. Il cliente riceve una copia della dichiarazione corrente nei suoi dati fiscali, usata dai documenti e dalla
|
||||
fattura elettronica.
|
||||
|
||||
Una dichiarazione si **revoca** (per esempio quando il cliente la annulla) e da quel momento non copre più le
|
||||
fatture. Il plafond non può scendere sotto l'utilizzato; una dichiarazione mai usata si può eliminare.
|
||||
|
||||
## Fatturare a un esportatore abituale
|
||||
|
||||
1. Nella fattura usa per le righe il codice IVA di **natura N3.5** (*non imponibile a seguito di dichiarazione
|
||||
d'intento*), di solito impostato come codice IVA preferito del cliente.
|
||||
2. Alla **conferma** Khaemhat cerca una dichiarazione attiva del cliente valida alla data della fattura:
|
||||
- se **non c'è**, la conferma è rifiutata con il messaggio *nessuna dichiarazione d'intento valida*;
|
||||
- se l'imponibile in N3.5 **supera il residuo**, la conferma è rifiutata indicando quanto resta;
|
||||
- altrimenti la fattura è confermata e l'importo si aggiunge all'**utilizzato**; dal 90 % compare l'avviso.
|
||||
3. La fattura elettronica riporta gli estremi della dichiarazione nel blocco *AltriDatiGestionali* con tipo
|
||||
`INTENTO` (vedi [Fatturazione elettronica](Fatturazione-elettronica)).
|
||||
|
||||
Le note di credito in N3.5 riducono l'utilizzato; eliminare o annullare una fattura lo ricalcola.
|
||||
|
||||
## Dichiarazioni emesse
|
||||
|
||||
Se l'azienda stessa è esportatore abituale registra nella scheda **Emesse** le dichiarazioni inviate ai propri
|
||||
fornitori, con lo stesso protocollo e plafond: servono come promemoria e per la stampa del registro.
|
||||
|
||||
## Dati di esempio
|
||||
|
||||
I dati dimostrativi registrano la dichiarazione di **Idrotermica Piemonte** (plafond 150.000 €) ed emettono una
|
||||
fattura in N3.5 che ne consuma una parte; una fattura in N3.5 a un cliente senza dichiarazione viene rifiutata.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
| Permesso | Consente |
|
||||
|---|---|
|
||||
| `sales.intent.read` | registro e stampa |
|
||||
| `sales.intent.write` | inserire, modificare e revocare le dichiarazioni |
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
**La fattura non si conferma: «plafond superato».** Il residuo della dichiarazione non basta. Chiedi al cliente una
|
||||
nuova dichiarazione (o un'integrazione del plafond) e registrala, oppure fattura la parte eccedente con IVA.
|
||||
|
||||
**Avevo scritto il protocollo nell'anagrafica del cliente.** Le dichiarazioni inserite nei dati fiscali del cliente
|
||||
prima della versione 0.10 diventano automaticamente righe del registro alla prima apertura.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
[Vendite](Vendite) · [Anagrafiche](Anagrafiche) · [IVA](IVA) · [Fatturazione elettronica](Fatturazione-elettronica) ·
|
||||
[Intrastat](Intrastat) · [Fiscalità italiana](Fiscalita-italiana)
|
||||
@@ -1,200 +1,329 @@
|
||||
# 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.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **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. Dalla 0.10 il menu comprende anche
|
||||
> [Intrastat](Intrastat) e le [dichiarazioni d'intento](Dichiarazioni-d-intento), i cui estremi entrano nel file
|
||||
> (`AltriDatiGestionali` di tipo `INTENTO`). Arriva più avanti 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.
|
||||
|
||||

|
||||
*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:
|
||||
|
||||

|
||||
*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 — 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 — 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 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 — esito della trasmissione di due file.*
|
||||
|
||||

|
||||
*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<identificativo fiscale del trasmittente>_<progressivo>.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 — 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: 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 — 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`.
|
||||
|
||||
> **Quale canale usare.** Per iniziare usa la **PEC**: non richiede accreditamento né contratti. *Intermediario A* e
|
||||
> *Intermediario B* sono connettori generici, provati con servizi simulati: per collegarli a un intermediario reale
|
||||
> servono le sue API, quindi vanno adattati al fornitore scelto. **SdICoop** richiede l'accreditamento dell'azienda
|
||||
> presso l'Agenzia delle Entrate, il certificato client e un reverse proxy con verifica reciproca dei certificati
|
||||
> (mTLS): conviene solo con volumi alti.
|
||||
|
||||
**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/<codice azienda>` 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 — 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
|
||||
|
||||
|
||||
@@ -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.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **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). Con la 0.10
|
||||
> sono in uso anche le regole di [Cespiti](Cespiti), [Intrastat](Intrastat),
|
||||
> [dichiarazioni d'intento](Dichiarazioni-d-intento) e lo schema del bilancio CEE ([Chiusura e bilancio](Chiusura-e-bilancio)).
|
||||
|
||||
> **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).
|
||||
@@ -320,16 +324,17 @@ si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermedia
|
||||
|---|---|---|
|
||||
| Split payment | IVA versata dalla PA cessionaria (esigibilità **S**): in contabilità l'IVA viene tolta subito al cliente | [Vendite](Vendite), [Contabilita](Contabilita) |
|
||||
| Reverse charge interno | IVA a carico del cessionario, registri RC vendite e acquisti (IVA neutra) | [Acquisti](Acquisti), [IVA](IVA) |
|
||||
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo (M10) | [Fatturazione-elettronica](Fatturazione-elettronica) |
|
||||
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo; protocollo di 17 + 6 cifre; avviso dal 90 % | [Dichiarazioni d'intento](Dichiarazioni-d-intento) |
|
||||
| Ritenuta e cassa previdenza | parcelle TD06: cassa (ad esempio 4%) e ritenuta d'acconto | [IVA](IVA#ritenute-dacconto) |
|
||||
| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 (M10) | [Cespiti](Cespiti) |
|
||||
| Intrastat | elenchi INTRA cessioni e acquisti, periodicità da soglie, nomenclatura NC8 (M10) | [Intrastat](Intrastat) |
|
||||
| Bilancio | schemi CEE art. 2424 (stato patrimoniale) e 2425 (conto economico): le voci sono già sui conti, gli schemi arrivano con M10 | [Contabilita](Contabilita) |
|
||||
| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 | [Cespiti](Cespiti) |
|
||||
| Intrastat | elenchi INTRA cessioni e acquisti, periodicità dalle soglie (50.000 € per le cessioni, 350.000 e 100.000 € per gli acquisti), nomenclatura NC8, file SCAMBI.CEE | [Intrastat](Intrastat) |
|
||||
| Bilancio | schemi CEE art. 2424 e 2425 c.c., abbreviato (art. 2435-bis) e micro (art. 2435-ter); svalutazione crediti allo 0,5 % (art. 106 TUIR) e TFR nella chiusura | [Chiusura e bilancio](Chiusura-e-bilancio) |
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -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.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
|
||||
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,21 @@ 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.10.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 |
|
||||
| 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 |
|
||||
| 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 | libro inventari M13 |
|
||||
| Contabilità | piano dei conti, causali, prima nota, contabilizzazione automatica dei documenti, registrazioni ricorrenti e definitive, partitari, mastrini, bilancio di verifica, libro giornale, ratei e risconti, chiusura guidata dell'esercizio, bilancio CEE con riclassificato e indici, export per il commercialista | — |
|
||||
| IVA | registri IVA, liquidazione con F24, acconto, file LIPE, ritenute d'acconto con prospetto F24 e dati CU, bollo virtuale, dichiarazioni d'intento con plafond, elenchi Intrastat | — |
|
||||
| Cespiti | categorie con i coefficienti ministeriali, registro con piano civilistico e fiscale, ammortamenti registrati e annullabili, dismissioni con plus e minusvalenze, stampa del registro | rivalutazioni guidate più avanti |
|
||||
| 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 | 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 |
|
||||
|
||||
@@ -162,8 +163,10 @@ confermati muovono il magazzino da soli: non serve registrare a parte carichi e
|
||||
Con il modulo contabile ogni fattura, nota e autofattura confermata scrive da sola la sua **registrazione** in
|
||||
partita doppia, con le righe IVA nel registro giusto e le **partite** da incassare o pagare. **Contabilità → Prima
|
||||
nota** elenca le registrazioni e serve per quelle manuali (giroconti, spese, versamenti); **Liquidazione IVA** calcola
|
||||
l'IVA del periodo e prepara l'F24; **Bilancio** dà il bilancio di verifica. Vedi [Contabilità](Contabilita) e
|
||||
[IVA](IVA).
|
||||
l'IVA del periodo e prepara l'F24; **Bilancio** dà il bilancio di verifica e, nelle altre schede, il bilancio CEE,
|
||||
il riclassificato e gli indici. A fine anno **Chiusura esercizio** guida ammortamenti, ratei e risconti, rimanenze,
|
||||
chiusura dei conti, riapertura e stampe definitive in nove passi. Vedi [Contabilità](Contabilita), [IVA](IVA),
|
||||
[Cespiti](Cespiti) e [Chiusura e bilancio](Chiusura-e-bilancio).
|
||||
|
||||
## 11. Incassare, pagare e la banca
|
||||
|
||||
|
||||
@@ -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.10.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10; sviluppo in corso)
|
||||
|
||||

|
||||
|
||||
@@ -37,7 +37,8 @@ Il nome viene da uno scriba dell'antico Egitto che sovrintendeva ai granai del r
|
||||
- **Anagrafiche e tabelle:** [Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) ·
|
||||
[Tabelle azienda](Tabelle-azienda)
|
||||
- **Ciclo attivo e passivo:** [Vendite](Vendite) · [Acquisti](Acquisti) · [Magazzino](Magazzino)
|
||||
- **Amministrazione e fisco:** [Contabilità](Contabilita) · [IVA](IVA) · [Cespiti](Cespiti) · [Intrastat](Intrastat) ·
|
||||
- **Amministrazione e fisco:** [Contabilità](Contabilita) · [Chiusura e bilancio](Chiusura-e-bilancio) · [IVA](IVA) ·
|
||||
[Cespiti](Cespiti) · [Intrastat](Intrastat) · [Dichiarazioni d'intento](Dichiarazioni-d-intento) ·
|
||||
[Scadenzario](Scadenzario) · [Fatturazione elettronica](Fatturazione-elettronica) ·
|
||||
[Fiscalità italiana](Fiscalita-italiana)
|
||||
- **Clienti e servizi:** [CRM](CRM) · [Servizi](Servizi) · [Canali e-commerce](Canali-e-commerce)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# IVA
|
||||
|
||||
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
|
||||
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** ACCT · **Permessi principali:** `vat.register.read` (registri IVA), `vat.settlement.read` (liquidazione, ritenute, bollo, F24), `vat.settlement.confirm` (conferme, versamenti, stampe definitive) · **Specifica:** SPEC §11.7, §11.9, §14, ADR 0037
|
||||
|
||||
Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabilità**:
|
||||
@@ -18,8 +18,8 @@ Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabil
|
||||
> **In questa versione** ci sono i cinque registri IVA con stampe di prova e definitive, la liquidazione con la sua
|
||||
> registrazione e il versamento F24, l'acconto IVA, il file LIPE, le ritenute con il prospetto F24 e il pagamento, i
|
||||
> dati della CU e il bollo virtuale. Dalla 0.8 il pagamento di una parcella dallo
|
||||
> [Scadenzario](Scadenzario) rende dovuta la ritenuta da solo. Arrivano più avanti: le **dichiarazioni d'intento** e il plafond e l'**Intrastat** (M10),
|
||||
> l'**IVA per cassa** completa (fase 2). Non ci sono ancora la **dichiarazione IVA annuale** e l'**invio
|
||||
> [Scadenzario](Scadenzario) rende dovuta la ritenuta da solo. Dalla 0.10 ci sono le [dichiarazioni d'intento](Dichiarazioni-d-intento) con il plafond e gli
|
||||
> elenchi [Intrastat](Intrastat). Arriva più avanti l'**IVA per cassa** completa (fase 2). Non ci sono ancora la **dichiarazione IVA annuale** e l'**invio
|
||||
> telematico** di F24, LIPE e CU.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
@@ -1,83 +1,105 @@
|
||||
# Intrastat
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M10)
|
||||
> **Modulo di licenza:** INTRA · **Permessi principali:** `intrastat.declaration.write`, `intrastat.declaration.export` · **Specifica:** SPEC §11.7, §8.1
|
||||
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** INTRA · **Permessi principali:** `intrastat.list.read` (elenchi), `intrastat.list.write`
|
||||
> (generare e correggere), `intrastat.list.export` (file e invio) · **Specifica:** SPEC §11.7, ADR 0042
|
||||
|
||||
## A cosa serve
|
||||
|
||||
Il modulo Intrastat prepara gli **elenchi riepilogativi delle operazioni intracomunitarie** a partire dalle fatture
|
||||
di vendita e di acquisto già registrate, controlla i dati mancanti e produce il **file nel tracciato dell'Agenzia
|
||||
delle Dogane**, da trasmettere con i canali telematici previsti (la trasmissione avviene fuori da Khaemhat).
|
||||
Gli **elenchi riepilogativi Intrastat** raccolgono le cessioni e gli acquisti di beni e servizi con soggetti di altri
|
||||
Paesi dell'Unione europea. Khaemhat li **genera dalle fatture e note di credito confermate**, controlla i dati di ogni
|
||||
riga, propone la **periodicità** dovuta e produce il file **SCAMBI.CEE** nel tracciato dell'Agenzia delle Dogane, da
|
||||
trasmettere con i servizi telematici (la trasmissione avviene fuori da Khaemhat).
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Nel mockup la voce è **Fatturazione elettronica → Intrastat**; il modulo di licenza è comunque **INTRA**, separato
|
||||
da EINV.
|
||||
**Fatturazione elettronica → Intrastat** (la voce compare con il modulo **INTRA**, separato da EINV).
|
||||
|
||||
## Schermate
|
||||

|
||||
*L'elenco delle cessioni di novembre 2026 dell'azienda demo: la fattura a Bergwerk Bau (Austria) con nomenclatura,
|
||||
natura della transazione, consegna, trasporto, ammontare e massa netta; sotto, gli elenchi dell'anno.*
|
||||
|
||||

|
||||
*Mockup 049 — elenchi di settembre (mensile): riquadri con i totali per sezione e le anomalie, elenco delle operazioni con paese, P.IVA, NC8, natura della transazione, consegna, trasporto, valore, massa e controllo; pulsanti Genera elenco e File SCAMBI.CEE*
|
||||
## Flussi e sezioni
|
||||
|
||||
## Gli elenchi
|
||||
| Flusso | Sezione | Modello |
|
||||
|---|---|---|
|
||||
| **Cessioni** | Beni · Rettifiche beni · Servizi · Rettifiche servizi | INTRA-1 bis, ter, quater, quinquies |
|
||||
| **Acquisti** | Beni · Rettifiche beni · Servizi · Rettifiche servizi | INTRA-2 bis, ter, quater, quinquies |
|
||||
|
||||
| Modello | Contenuto |
|
||||
|---|---|
|
||||
| **INTRA-1 bis** | cessioni di beni verso altri Paesi UE |
|
||||
| **INTRA-1 ter** | rettifiche alle cessioni di beni di periodi precedenti |
|
||||
| **INTRA-1 quater** | servizi resi a soggetti UE |
|
||||
| **INTRA-2 bis** | acquisti di beni da altri Paesi UE |
|
||||
| **INTRA-2 ter** | rettifiche agli acquisti di beni di periodi precedenti |
|
||||
| **INTRA-2 quater** | servizi ricevuti da soggetti UE |
|
||||
|
||||
I riquadri in testa mostrano il periodo e la periodicità, i totali di ogni sezione e il numero di **anomalie**.
|
||||
La striscia in alto riporta il **periodo**, i totali di cessioni e acquisti di beni, dei servizi resi e ricevuti e il
|
||||
numero di righe **da completare**.
|
||||
|
||||
## Periodicità
|
||||
|
||||
La periodicità (**mensile** o **trimestrale**) è determinata dalle **soglie di legge** in base agli importi delle
|
||||
operazioni, separatamente per cessioni e acquisti. Le soglie sono parametri del pacchetto fiscale italiano e vengono
|
||||
aggiornate con esso; Khaemhat propone la periodicità e la mostra nel riquadro *Periodo*.
|
||||
Sotto i filtri Khaemhat indica la **periodicità dovuta** in base agli importi dei quattro trimestri precedenti, per
|
||||
beni e servizi separatamente, con le soglie in vigore dal 2022:
|
||||
|
||||
## Dati richiesti per ogni operazione
|
||||
| Flusso | Mensile se in almeno un trimestre | Altrimenti |
|
||||
|---|---|---|
|
||||
| Cessioni (beni o servizi) | più di 50.000 € | trimestrale |
|
||||
| Acquisti di beni | più di 350.000 € | non dovuto |
|
||||
| Acquisti di servizi | più di 100.000 € | non dovuto |
|
||||
|
||||
| Dato | Da dove viene |
|
||||
La periodicità dell'elenco si sceglie nei filtri (mensile o trimestrale) insieme a esercizio e periodo.
|
||||
|
||||
## Generare l'elenco
|
||||
|
||||
1. Scegli **flusso**, **esercizio**, **periodicità** e **periodo**.
|
||||
2. Premi **Genera** *periodo*. Khaemhat legge le fatture e le note di credito confermate nel periodo verso soggetti con
|
||||
sede in un altro Paese UE:
|
||||
- i **beni** sono raggruppati per controparte, nomenclatura e natura della transazione;
|
||||
- i **servizi** hanno una riga per fattura, con il codice CPA;
|
||||
- le **note di credito** diventano righe di rettifica.
|
||||
3. Le righe aggiunte a mano con **Aggiungi riga** restano quando rigeneri l'elenco.
|
||||
|
||||
| Colonna | Da dove viene |
|
||||
|---|---|
|
||||
| Paese e partita IVA della controparte | anagrafica (P.IVA comunitaria verificata con VIES, vedi [Anagrafiche](Anagrafiche)) |
|
||||
| **NC8** (nomenclatura combinata a 8 cifre) | scheda articolo ([Articoli e listini](Articoli-e-listini)) |
|
||||
| Descrizione | riga del documento |
|
||||
| **Natura della transazione** | causale del documento, modificabile (es. `11` vendita) |
|
||||
| **Condizioni di consegna** | Incoterms del documento (es. DAP, FCA, EXW) |
|
||||
| **Modo di trasporto** | dal documento (es. 1 mare, 3 strada) |
|
||||
| Valore | imponibile in euro |
|
||||
| **Massa netta** e unità supplementare | peso dell'articolo x quantità |
|
||||
| Controparte, Paese, Partita IVA | anagrafica (vedi [Anagrafiche](Anagrafiche)) |
|
||||
| **Nomenclatura / CPA** | codice doganale della scheda articolo ([Articoli e listini](Articoli-e-listini)) |
|
||||
| **Natura** | proposta `11` (vendita o acquisto a titolo definitivo) |
|
||||
| **Consegna**, **Trasporto** | proposti `DAP` e `3` (strada) |
|
||||
| **Ammontare €** | imponibile della riga in euro |
|
||||
| **Massa netta kg** | peso netto dell'articolo per quantità |
|
||||
|
||||
La colonna **Controllo** segnala lo stato di ogni riga: *OK*, *Manca peso netto* (riga evidenziata), *Extra-UE:
|
||||
escluso* (la controparte non è comunitaria e la riga non entra negli elenchi), *INTRA-2 quater* (servizio ricevuto).
|
||||
I dati richiesti dipendono dal modello e dalla periodicità; il tracciato preciso segue le istruzioni dell'Agenzia
|
||||
delle Dogane in vigore.
|
||||
Un clic sulla riga apre la scheda per correggere sezione, paese, partita IVA, codice, descrizione, ammontare,
|
||||
massa, natura, consegna e trasporto; le righe si possono anche eliminare finché l'elenco non è inviato.
|
||||
|
||||
## Come si prepara l'elenco
|
||||
## Controlli
|
||||
|
||||
1. Apri **Intrastat**, scegli **Periodo** e **Sezione**.
|
||||
2. Premi **Genera elenco** del periodo: Khaemhat raccoglie le fatture intracomunitarie registrate.
|
||||
3. Correggi le **anomalie** aprendo l'articolo o il documento (NC8 o peso mancanti, P.IVA non valida…).
|
||||
4. Rigenera e controlla i totali con i registri IVA ([IVA](IVA)).
|
||||
5. Premi **File SCAMBI.CEE** per scaricare il file nel tracciato dell'Agenzia delle Dogane; il file resta come
|
||||
allegato della dichiarazione ([Allegati e file](Allegati-e-file)).
|
||||
6. Trasmetti il file con il servizio telematico e registra l'avvenuto invio.
|
||||
| Controllo | Cosa fare |
|
||||
|---|---|
|
||||
| **Completa** | niente |
|
||||
| **Manca la nomenclatura** | completa il codice doganale sull'articolo e rigenera |
|
||||
| **Manca la massa netta** | completa il peso netto sull'articolo, o la massa sulla riga |
|
||||
| **Manca la partita IVA** | completa la partita IVA comunitaria della controparte |
|
||||
| **Manca il codice CPA** | servizio senza codice: completalo sull'articolo |
|
||||
| **Fuori UE** | la controparte non è comunitaria: la riga non entra nell'elenco |
|
||||
|
||||
## File e invio
|
||||
|
||||
1. **File SCAMBI.CEE** scarica il file a lunghezza fissa (frontespizio e record per beni, servizi e rettifiche).
|
||||
Un elenco con righe da completare non si esporta. L'elenco passa a *File generato*.
|
||||
2. Controlla il file con il software di controllo delle Dogane e trasmettilo.
|
||||
3. **Segna come inviato** chiede il **protocollo di invio**: da quel momento l'elenco è di sola lettura.
|
||||
|
||||
> **Attenzione.** Il tracciato segue le specifiche pubblicate ma non è ancora stato verificato con il software di
|
||||
> controllo delle Dogane: prima del primo invio controlla sempre il file (vedi [Roadmap](Roadmap)).
|
||||
|
||||
## Dati di esempio
|
||||
|
||||
I dati dimostrativi emettono una fattura non imponibile (art. 41) a **Bergwerk Bau GmbH** (Austria) con articoli che
|
||||
hanno codice doganale e peso netto: generando l'elenco del mese corrente si vede una riga completa.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Serve il modulo **INTRA**. I codici dei permessi in testa sono indicativi (convenzione `modulo.entità.azione`, SPEC
|
||||
§7.2) e saranno fissati in sviluppo.
|
||||
| Permesso | Consente |
|
||||
|---|---|
|
||||
| `intrastat.list.read` | consultare gli elenchi |
|
||||
| `intrastat.list.write` | generare, aggiungere e correggere righe |
|
||||
| `intrastat.list.export` | scaricare il file e segnare l'invio |
|
||||
|
||||
## Attenzione
|
||||
|
||||
- Gli elenchi dipendono dalla qualità delle anagrafiche: NC8 e peso netto sugli articoli, P.IVA comunitarie valide.
|
||||
- Soglie, modelli e campi obbligatori cambiano con le determinazioni dell'Agenzia delle Dogane: verificare sempre le
|
||||
istruzioni in vigore prima dell'invio.
|
||||
Serve il modulo **INTRA**.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
[IVA](IVA) · [Vendite](Vendite) · [Acquisti](Acquisti) · [Articoli e listini](Articoli-e-listini) ·
|
||||
[Fatturazione elettronica](Fatturazione-elettronica) · [Fiscalità italiana](Fiscalita-italiana)
|
||||
[Fatturazione elettronica](Fatturazione-elettronica) · [Dichiarazioni d'intento](Dichiarazioni-d-intento) ·
|
||||
[Fiscalità italiana](Fiscalita-italiana)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Magazzino
|
||||
|
||||
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
|
||||
> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.stock.read` (giacenze), `inventory.entry.*` (movimenti, inventario), `inventory.entry.post` (conferma, rettifiche, ricostruzione), `items.cost.read` (costi e valori) · **Specifica:** SPEC §11.6, ADR 0035
|
||||
|
||||
Il **magazzino** tiene la quantità e il valore di ogni articolo in ogni **deposito**. Le giacenze si aggiornano da
|
||||
@@ -10,8 +10,9 @@ riordino** e calcoli la **valorizzazione** a una data.
|
||||
|
||||
> **In questa versione** ci sono giacenze per deposito, impegnato e ordinato, costo medio ponderato, movimenti per
|
||||
> articolo, movimenti manuali e trasferimenti, inventario fisico con import dei conteggi, proposta di riordino,
|
||||
> valorizzazione con analisi ABC e ricostruzione. Arrivano più avanti: le **scritture contabili** delle rimanenze e il
|
||||
> **libro inventari** con la chiusura dell'esercizio (M10), i report di magazzino stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0).
|
||||
> valorizzazione con analisi ABC e ricostruzione. Dalla 0.10 la [chiusura dell'esercizio](Chiusura-e-bilancio) registra le
|
||||
> rimanenze finali al costo medio ponderato. Arrivano più avanti: il **libro inventari** e i report di magazzino
|
||||
> stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0).
|
||||
|
||||
## Dove si trova
|
||||
|
||||
@@ -149,8 +150,8 @@ fornitore non vengono ordinate.
|
||||
- La **valorizzazione** (pulsante nelle giacenze) calcola quantità e valore **a una data** qualsiasi, anche passata,
|
||||
con il criterio scelto: *costo medio ponderato*, *ultimo costo* o *costo standard*. Divide gli articoli in **classi
|
||||
ABC**: A gli articoli che fanno l'80% del valore, B fino al 95%, C il resto.
|
||||
- FIFO e LIFO sono previsti con la gestione a lotti; le rimanenze alimenteranno la chiusura dell'esercizio e il libro
|
||||
inventari con la chiusura dell'esercizio (M10).
|
||||
- FIFO e LIFO sono previsti con la gestione a lotti. Il passo 4 della [chiusura](Chiusura-e-bilancio) registra le
|
||||
rimanenze finali al costo medio ponderato.
|
||||
|
||||
## Ricostruzione
|
||||
|
||||
|
||||
@@ -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), M10 (0.10.0). **Prossima:** M11.
|
||||
|
||||
| # | Milestone | Contenuto principale | Versione |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -221,7 +221,7 @@ Ogni opzione si accende o spegne con un interruttore; spenta, i campi restano da
|
||||
| Comune, provincia e regione dal CAP | scrivendo il CAP propone il comune (o i comuni) con provincia e regione; scrivendo il comune propone CAP e provincia | accesa |
|
||||
| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche da cognome, nome, data, sesso e comune di nascita | accesa |
|
||||
| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito (*valida*, *non valida*, *servizio non disponibile*) | accesa |
|
||||
| Banca e BIC dall'IBAN | legge ABI e CAB dall'IBAN; banca e BIC vengono dall'elenco ABI o, finché l'elenco non è caricato, da un conto dell'azienda presso la stessa banca | accesa |
|
||||
| Banca e BIC dall'IBAN | legge ABI e CAB dall'IBAN; banca e BIC vengono da un conto dell'azienda presso la stessa banca (l'elenco ABI non è precaricato) | accesa |
|
||||
| Cambi BCE giornalieri | l'attività di sistema scarica i cambi nei giorni lavorativi; spenta, l'azienda usa solo cambi manuali | accesa |
|
||||
| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento | accesa |
|
||||
| Ultimo prezzo praticato al cliente | lo mostra come riferimento | accesa |
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -28,9 +28,11 @@
|
||||
|
||||
**Contabilità e fisco**
|
||||
- [Contabilità](Contabilita)
|
||||
- [Chiusura e bilancio](Chiusura-e-bilancio)
|
||||
- [IVA](IVA)
|
||||
- [Cespiti](Cespiti)
|
||||
- [Intrastat](Intrastat)
|
||||
- [Dichiarazioni d'intento](Dichiarazioni-d-intento)
|
||||
- [Scadenzario](Scadenzario)
|
||||
- [Fatturazione elettronica](Fatturazione-elettronica)
|
||||
- [Fiscalità italiana](Fiscalita-italiana)
|
||||
|
||||
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 129 KiB |
|
After Width: | Height: | Size: 146 KiB |
|
After Width: | Height: | Size: 138 KiB |
|
After Width: | Height: | Size: 205 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 133 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 130 KiB |
|
After Width: | Height: | Size: 172 KiB |
|
After Width: | Height: | Size: 130 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 91 KiB |
@@ -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).
|
||||
|
||||
@@ -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",
|
||||
};
|
||||
|
||||
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
|
||||
|
||||
@@ -274,6 +274,7 @@ public sealed partial class DocumentEngine
|
||||
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
|
||||
await _ledger.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
|
||||
await SyncIntentAsync(uow, pack, record.Family, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -308,6 +309,7 @@ public sealed partial class DocumentEngine
|
||||
await _fiscal.DemandOpenAsync(company, draft.Header.DocumentDate, PeriodUse.Vat, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
|
||||
var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, definition.ConfirmAction);
|
||||
@@ -318,6 +320,11 @@ public sealed partial class DocumentEngine
|
||||
}
|
||||
|
||||
await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<Fiscal.Abstractions.IIntentRules>() is { } intent)
|
||||
{
|
||||
// A sale under a declaration of intent needs the declaration and the ceiling left (ADR 0042).
|
||||
await YearEnd.IntentDeclarationService.CheckAsync(uow, intent, definition.Behavior, record, errors, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (definition.Behavior.Has(DocumentEffects.Ledger))
|
||||
{
|
||||
@@ -363,6 +370,7 @@ public sealed partial class DocumentEngine
|
||||
await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await SyncIntentAsync(uow, pack, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName);
|
||||
}
|
||||
@@ -451,6 +459,48 @@ public sealed partial class DocumentEngine
|
||||
}, null, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="uow">The open unit of work.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="steps">The steps, in order, from the state the document is in.</param>
|
||||
/// <param name="userName">Who, for the history.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The state reached, or <see langword="null"/> when the document does not exist.</returns>
|
||||
internal async Task<DocumentStatus?> AdvanceExchangeAsync(
|
||||
IUnitOfWork uow, DocumentFamily family, long id, Func<DocumentStatus, IReadOnlyList<DocumentAction>> 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;
|
||||
}
|
||||
|
||||
/// <summary>Records that the document was printed (its PDF kept among the attachments); the state does not change.</summary>
|
||||
/// <param name="actor">Who prints: needs to read the document.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
@@ -686,6 +736,7 @@ public sealed partial class DocumentEngine
|
||||
{
|
||||
var company = Company(actor, companyCode);
|
||||
var store = DocumentStores.Of(family);
|
||||
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -710,6 +761,7 @@ public sealed partial class DocumentEngine
|
||||
// A cancelled delivery note gives its stock back; a closed or reopened order its open quantities.
|
||||
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await SyncIntentAsync(uow, pack, family, id, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName);
|
||||
}
|
||||
@@ -866,6 +918,11 @@ public sealed partial class DocumentEngine
|
||||
}
|
||||
|
||||
// Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date.
|
||||
private static Task SyncIntentAsync(IUnitOfWork uow, Fiscal.Abstractions.IFiscalPack pack, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
pack.GetFeature<Fiscal.Abstractions.IIntentRules>() is { } intent
|
||||
? YearEnd.IntentDeclarationService.SyncDocumentAsync(uow, intent, family, id, cancellationToken)
|
||||
: Task.CompletedTask;
|
||||
|
||||
private static bool IsRegistered(DocumentKind kind) => kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote;
|
||||
|
||||
// The rules of a supplier document (§11.5): its own number and date, the VAT date not before it, no duplicate of
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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, <c>/AF</c>).
|
||||
/// </summary>
|
||||
/// <param name="context">The document.</param>
|
||||
/// <param name="xmlName">The name of the XML file.</param>
|
||||
/// <param name="xml">The XML file.</param>
|
||||
/// <param name="output">The stream that receives the PDF.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A conservation package made.</summary>
|
||||
/// <param name="Export">The row that records it.</param>
|
||||
/// <param name="Content">The ZIP.</param>
|
||||
public sealed record ConservationPackage(ConservationExport Export, byte[] Content);
|
||||
|
||||
/// <summary>
|
||||
/// The package for the conservation of the e-invoices of a period (issue #79): a ZIP with the files sent
|
||||
/// (<c>emesse/</c>), their notifications (<c>notifiche/</c>) and the files received (<c>ricevute/</c>), each as it
|
||||
/// travelled, an index <c>indice.csv</c> with the SHA-256 of every file and a <c>LEGGIMI.txt</c>. It is what a
|
||||
/// conservation service (or the free service of the AdE) takes in; Khaemhat does not replace the conservation itself.
|
||||
/// </summary>
|
||||
/// <remarks>Permission: <c>einvoice.document.read</c>. Every package made is recorded with its hash.</remarks>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public ConservationExportService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The packages made, newest first.</summary>
|
||||
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<ConservationExport>> 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<ConservationExport, long>().ListAsync(Query.For<ConservationExport>().OrderByDescending(e => e.Id).Take(50), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>Makes the package of a period: e-invoices sent by date of the document, files received by date of arrival.</summary>
|
||||
/// <param name="actor">Who makes it: needs <c>einvoice.document.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="from">First day.</param>
|
||||
/// <param name="to">Last day.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The package.</returns>
|
||||
public async Task<ConservationPackage> 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<EInvoice, long>()
|
||||
.ListAsync(Query.For<EInvoice>().Where(e => e.DocumentDate >= from && e.DocumentDate <= to && e.Status != EInvoiceStatus.Generated).OrderBy(e => e.Progressive), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var notifications = new List<EInvoiceNotification>();
|
||||
foreach (var chunk in sent.Select(e => e.Id).Chunk(500))
|
||||
{
|
||||
var ids = chunk.Select(id => (long?)id).ToList();
|
||||
notifications.AddRange((await uow.Repository<EInvoiceNotification, long>()
|
||||
.ListAsync(Query.For<EInvoiceNotification>().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<EInvoiceInboxFile, long>()
|
||||
.ListAsync(Query.For<EInvoiceInboxFile>().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<string>(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<ConservationExport, long>().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<string> 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.
|
||||
""");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>Amounts follow the document as computed by Khaemhat: a footer discount becomes one discount line (<c>SC</c>)
|
||||
/// per rate, prices that include tax are taken back to their taxable amount, what is left by rounding goes in
|
||||
/// <c>Arrotondamento</c> of the summary. A stamp duty charged to the customer is a line excluded from VAT (N1).</para>
|
||||
/// <para>The file name is not set here: the service gives it with the progressive.</para>
|
||||
/// </remarks>
|
||||
internal static class EInvoiceBuilder
|
||||
{
|
||||
/// <summary>The country code of foreign customers without a VAT number (FatturaPA: eleven nines).</summary>
|
||||
public const string NoVatNumber = "99999999999";
|
||||
|
||||
/// <summary>The recipient code of a foreign customer.</summary>
|
||||
public const string ForeignRecipient = "XXXXXXX";
|
||||
|
||||
/// <summary>The recipient code when the file goes to a certified mailbox or to the tax drawer.</summary>
|
||||
public const string NoRecipient = "0000000";
|
||||
|
||||
/// <summary>The type of the format of a document: the one of its document type, otherwise the default of its kind.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <param name="type">The document type.</param>
|
||||
/// <returns>The type (TD01 …), or <see langword="null"/> when the kind has no e-invoice.</returns>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Whether a kind of document goes to the exchange system.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns><see langword="true"/> for invoices, credit and debit notes, fees and self-invoices.</returns>
|
||||
public static bool IsElectronic(DocumentKind kind) => DocumentBehaviors.Of(kind).Effects.HasFlag(DocumentEffects.EInvoice);
|
||||
|
||||
/// <summary>Builds the file of a document.</summary>
|
||||
/// <param name="uow">The unit of work of the company.</param>
|
||||
/// <param name="record">The document, with lines and figures.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The model (file name empty), the party and whether it is a public administration.</returns>
|
||||
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<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException([":" + EInvoiceErrors.CompanyProfileMissing]);
|
||||
var party = header.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (party is null)
|
||||
{
|
||||
throw new ValidationFailedException(["PartyId:" + DocumentErrors.PartyRequired]);
|
||||
}
|
||||
|
||||
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == party.Id), cancellationToken).ConfigureAwait(false);
|
||||
var type = await uow.Repository<DocumentType, long>().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);
|
||||
}
|
||||
|
||||
/// <summary>The company as it appears in the file.</summary>
|
||||
/// <param name="profile">The profile.</param>
|
||||
/// <returns>The party.</returns>
|
||||
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<EInvoiceBody> 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<long>().Distinct().ToList();
|
||||
var taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => taxIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false))
|
||||
.Items.ToDictionary(t => t.Id);
|
||||
var unitIds = record.Lines.Select(l => l.UnitOfMeasureId).OfType<long>().Distinct().ToList();
|
||||
var units = (await uow.Repository<UnitOfMeasure, long>().ListAsync(Query.For<UnitOfMeasure>().Where(u => unitIds.Contains(u.Id)), cancellationToken).ConfigureAwait(false))
|
||||
.Items.ToDictionary(u => u.Id);
|
||||
var itemIds = record.Lines.Select(l => l.ItemId).OfType<long>().Distinct().ToList();
|
||||
var items = itemIds.Count == 0
|
||||
? []
|
||||
: (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().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<EInvoiceLine>();
|
||||
var sourceLines = new Dictionary<int, DocumentLine>();
|
||||
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<EInvoiceTaxSummary>();
|
||||
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<EInvoiceDiscount> 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<EInvoiceReference> Orders, List<EInvoiceReference> Related, List<EInvoiceReference> Deliveries)> ReferencesAsync(
|
||||
IUnitOfWork uow, DocumentRecord record, Dictionary<int, DocumentLine> sourceLines, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = record.Header;
|
||||
var orders = new List<EInvoiceReference>();
|
||||
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<EInvoiceReference>();
|
||||
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<long, (DocumentHeader Note, List<int> 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<List<EInvoicePayment>> 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<long>().Distinct().ToList();
|
||||
var methods = methodIds.Count == 0
|
||||
? []
|
||||
: (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>().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<BankAccount, long>().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<EInvoicePayment>();
|
||||
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<EInvoiceTransport?> 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<Carrier, long>().GetAsync(carrierId, cancellationToken).ConfigureAwait(false) : null;
|
||||
var reason = header.TransportReasonId is { } reasonId ? await uow.Repository<TransportReason, long>().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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A channel as the configuration page shows it: secrets never leave the service, only whether they are set.</summary>
|
||||
/// <param name="Code">The code of the channel.</param>
|
||||
/// <param name="Name">Its name.</param>
|
||||
/// <param name="Polls">Whether Khaemhat reads it on a schedule (PEC, intermediaries) or receives a push (SdICoop).</param>
|
||||
/// <param name="Setting">The settings, secrets removed (a new row when never saved).</param>
|
||||
/// <param name="HasPassword">Whether a password is stored.</param>
|
||||
/// <param name="HasCertificate">Whether a client certificate is stored.</param>
|
||||
/// <param name="HasApiKey">Whether an API key is stored.</param>
|
||||
public sealed record EInvoiceChannelView(string Code, string Name, bool Polls, EInvoiceChannelSetting Setting, bool HasPassword, bool HasCertificate, bool HasApiKey);
|
||||
|
||||
/// <summary>
|
||||
/// What the user saves for a channel. Secrets: <see langword="null"/> keeps the stored one, an empty value removes it.
|
||||
/// </summary>
|
||||
public sealed record EInvoiceChannelInput
|
||||
{
|
||||
/// <summary>The code of the channel.</summary>
|
||||
public required string Code { get; init; }
|
||||
|
||||
/// <summary>Whether the channel is used.</summary>
|
||||
public bool Enabled { get; init; }
|
||||
|
||||
/// <summary>The certified mailbox.</summary>
|
||||
public string? Mailbox { get; init; }
|
||||
|
||||
/// <summary>The SMTP server.</summary>
|
||||
public string? SmtpHost { get; init; }
|
||||
|
||||
/// <summary>The SMTP port.</summary>
|
||||
public int SmtpPort { get; init; } = 465;
|
||||
|
||||
/// <summary>The IMAP server.</summary>
|
||||
public string? ImapHost { get; init; }
|
||||
|
||||
/// <summary>The IMAP port.</summary>
|
||||
public int ImapPort { get; init; } = 993;
|
||||
|
||||
/// <summary>Whether TLS is used.</summary>
|
||||
public bool Tls { get; init; } = true;
|
||||
|
||||
/// <summary>The user.</summary>
|
||||
public string? UserName { get; init; }
|
||||
|
||||
/// <summary>The password: <see langword="null"/> keeps it, empty removes it.</summary>
|
||||
public string? Password { get; init; }
|
||||
|
||||
/// <summary>The address of the SDI to write to.</summary>
|
||||
public string? ExchangeAddress { get; init; }
|
||||
|
||||
/// <summary>The folder the processed messages go to.</summary>
|
||||
public string? ArchiveFolder { get; init; }
|
||||
|
||||
/// <summary>The address of the web service or of the API.</summary>
|
||||
public string? Endpoint { get; init; }
|
||||
|
||||
/// <summary>The client certificate (PKCS#12): <see langword="null"/> keeps it, empty removes it.</summary>
|
||||
public byte[]? Certificate { get; init; }
|
||||
|
||||
/// <summary>The password of the certificate: <see langword="null"/> keeps it, empty removes it.</summary>
|
||||
public string? CertificatePassword { get; init; }
|
||||
|
||||
/// <summary>The API key: <see langword="null"/> keeps it, empty removes it.</summary>
|
||||
public string? ApiKey { get; init; }
|
||||
|
||||
/// <summary>Whether the test environment is used.</summary>
|
||||
public bool TestEnvironment { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>Permission: <c>einvoice.channel.manage</c>.</remarks>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="secrets">Protects the secrets.</param>
|
||||
/// <param name="audit">The history of the changes.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The channels of the pack with their settings.</summary>
|
||||
/// <param name="actor">Who looks: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The channels, in the order of the pack.</returns>
|
||||
public async Task<IReadOnlyList<EInvoiceChannelView>> 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<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>(), 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 }))];
|
||||
}
|
||||
|
||||
/// <summary>Saves the settings of a channel.</summary>
|
||||
/// <param name="actor">Who saves: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The settings.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The channel.</returns>
|
||||
public async Task<EInvoiceChannelView> 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<EInvoiceChannelSetting, long>();
|
||||
var code = channel.Code;
|
||||
var row = await repository.FindAsync(Query.For<EInvoiceChannelSetting>().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<EInvoiceChannelSetting>(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);
|
||||
}
|
||||
|
||||
/// <summary>Pauses or resumes a channel: a paused channel neither sends nor is read.</summary>
|
||||
/// <param name="actor">Who does it: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="code">The channel.</param>
|
||||
/// <param name="paused">Whether to pause.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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<EInvoiceChannelSetting, long>();
|
||||
var row = await repository.FindAsync(Query.For<EInvoiceChannelSetting>().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);
|
||||
}
|
||||
|
||||
/// <summary>Tries a channel with its saved settings (login to the mailbox, the service or the API) and keeps the outcome.</summary>
|
||||
/// <param name="actor">Who tries: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="code">The channel.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The outcome.</returns>
|
||||
public async Task<EInvoiceChannelCheck> 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<EInvoiceChannelSetting, long>().FindAsync(Query.For<EInvoiceChannelSetting>().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<EInvoiceChannelSetting, long>().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<EInvoiceChannelSetting, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return check;
|
||||
}
|
||||
|
||||
/// <summary>The routing rules, in order.</summary>
|
||||
/// <param name="actor">Who looks: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rules.</returns>
|
||||
public async Task<IReadOnlyList<SdiRoutingRule>> 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<SdiRoutingRule, long>().ListAsync(Query.For<SdiRoutingRule>().OrderBy(r => r.Position), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>Adds or changes a routing rule.</summary>
|
||||
/// <param name="actor">Who saves: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="rule">The rule (identifier 0 to add).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rule.</returns>
|
||||
public async Task<SdiRoutingRule> 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<string>();
|
||||
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<SdiRoutingRule, long>();
|
||||
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<SdiRoutingRule>().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<SdiRoutingRule>(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;
|
||||
}
|
||||
|
||||
/// <summary>Removes a routing rule.</summary>
|
||||
/// <param name="actor">Who removes: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The rule.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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<SdiRoutingRule, long>();
|
||||
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<SdiRoutingRule>(uow, AuditAction.Delete, row.Id, row, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<IEInvoiceChannels> ChannelsAsync(string company, CancellationToken cancellationToken) =>
|
||||
(await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<IEInvoiceChannels>()
|
||||
?? 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<string>();
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Khaemhat.Application.Dashboard;
|
||||
using Khaemhat.Application.Localization;
|
||||
using Khaemhat.Application.Security;
|
||||
|
||||
namespace Khaemhat.Application.EInvoicing;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="invoices">The e-invoices.</param>
|
||||
/// <param name="permissions">The permissions, licence included.</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
public sealed class EInvoiceFeedSource(EInvoiceService invoices, PermissionService permissions, ITexts texts) : ITodoSource
|
||||
{
|
||||
/// <summary>The text key of the area.</summary>
|
||||
public const string Area = "Dashboard.Areas.EInvoicing";
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FeedItem>> 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<FeedItem>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>What reading one channel brought.</summary>
|
||||
/// <param name="Channel">The channel.</param>
|
||||
/// <param name="Messages">Messages read.</param>
|
||||
/// <param name="Invoices">Invoices received and stored.</param>
|
||||
/// <param name="Receipts">Notifications applied.</param>
|
||||
/// <param name="Skipped">Files already known.</param>
|
||||
/// <param name="Error">Why the channel could not be read.</param>
|
||||
public sealed record EInvoicePollOutcome(string Channel, int Messages, int Invoices, int Receipts, int Skipped, string? Error);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<EInvoicePollingService> _logger;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="invoices">The e-invoices (notifications).</param>
|
||||
/// <param name="secrets">Opens the secrets of the channels.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log (section SDI).</param>
|
||||
public EInvoicePollingService(
|
||||
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, EInvoiceService invoices, ISecretProtector secrets, TimeProvider clock,
|
||||
ILogger<EInvoicePollingService> 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;
|
||||
}
|
||||
|
||||
/// <summary>Reads the channels of the company now (the button <i>Leggi ora</i>).</summary>
|
||||
/// <param name="actor">Who asks: needs <c>einvoice.channel.manage</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What each channel brought.</returns>
|
||||
public async Task<IReadOnlyList<EInvoicePollOutcome>> 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);
|
||||
}
|
||||
|
||||
/// <summary>Reads every enabled, not paused channel of a company that is read on a schedule.</summary>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What each channel brought.</returns>
|
||||
public async Task<IReadOnlyList<EInvoicePollOutcome>> PollCompanyAsync(string company, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<IEInvoiceChannels>() is not { } channels)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
List<EInvoiceChannelSetting> rows;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
rows = [.. (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Enabled && !c.Paused), cancellationToken)
|
||||
.ConfigureAwait(false)).Items];
|
||||
}
|
||||
|
||||
var result = new List<EInvoicePollOutcome>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Takes the files a channel pushed (SdICoop: <c>RiceviFatture</c>, <c>RiceviNotifica</c>) for a company.</summary>
|
||||
/// <param name="company">The company the endpoint belongs to.</param>
|
||||
/// <param name="channel">The channel.</param>
|
||||
/// <param name="files">The files.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What the files brought.</returns>
|
||||
public async Task<EInvoicePollOutcome> ReceivePushedAsync(string company, string channel, IReadOnlyList<EInvoiceIncoming> 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<EInvoicePollOutcome> 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<EInvoiceChannelSetting, long>().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<EInvoiceChannelSetting, long>().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<EInvoiceIncoming> Done)> ProcessAsync(
|
||||
string company, IFiscalPack pack, string channel, IReadOnlyList<EInvoiceIncoming> files, CancellationToken cancellationToken)
|
||||
{
|
||||
var reader = pack.GetFeature<IIncomingInvoiceReader>();
|
||||
var receiptReader = pack.GetFeature<IEInvoiceReceiptReader>();
|
||||
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<EInvoiceIncoming>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Reads the channels of the SDI of every company (job <c>einvoice.poll</c>, every 15 minutes).</summary>
|
||||
/// <param name="companies">The companies.</param>
|
||||
/// <param name="service">The reading of the channels.</param>
|
||||
/// <param name="license">The licence.</param>
|
||||
public sealed class EInvoicePollingJob(ICompanyRegistry companies, EInvoicePollingService service, ILicenseGate license) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "einvoice.poll";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> 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.");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Permissions: <c>einvoice.document.read</c> to see, <c>einvoice.document.send</c> 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.
|
||||
/// </remarks>
|
||||
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<EInvoiceService> _logger;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="secrets">Opens the secrets of the channels.</param>
|
||||
/// <param name="pdf">The print of the documents (courtesy copy).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log (section SDI).</param>
|
||||
public EInvoiceService(
|
||||
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, ISecretProtector secrets,
|
||||
DocumentPdfGenerator pdf, TimeProvider clock, ILogger<EInvoiceService> 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;
|
||||
}
|
||||
|
||||
/// <summary>The dashboard: the e-invoices of the view, the documents to generate, the counters.</summary>
|
||||
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="filter">The filter.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The dashboard.</returns>
|
||||
public async Task<EInvoiceDashboard> 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<EInvoice>().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<EInvoice, long>().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<EInvoiceInboxFile, long>().CountAsync(Query.For<EInvoiceInboxFile>().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<EInvoice> 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<long>(), 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);
|
||||
}
|
||||
|
||||
/// <summary>The e-invoices of a document with their notifications, newest first (the page of the document).</summary>
|
||||
/// <param name="actor">Who looks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The files and their notifications.</returns>
|
||||
public async Task<IReadOnlyList<(EInvoice Invoice, IReadOnlyList<EInvoiceNotification> 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<EInvoice, long>()
|
||||
.ListAsync(Query.For<EInvoice>().Where(e => e.Family == family && e.DocumentId == documentId).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var result = new List<(EInvoice, IReadOnlyList<EInvoiceNotification>)>();
|
||||
foreach (var invoice in invoices)
|
||||
{
|
||||
var id = invoice.Id;
|
||||
var notifications = (await uow.Repository<EInvoiceNotification, long>()
|
||||
.ListAsync(Query.For<EInvoiceNotification>().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;
|
||||
}
|
||||
|
||||
/// <summary>The notifications received in a period, newest first (files not loaded).</summary>
|
||||
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="from">From this day.</param>
|
||||
/// <param name="to">Up to this day.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The notifications.</returns>
|
||||
public async Task<IReadOnlyList<EInvoiceNotification>> 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<EInvoiceNotification, long>()
|
||||
.ListAsync(Query.For<EInvoiceNotification>().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;
|
||||
}
|
||||
|
||||
/// <summary>Checks the file a document would have, without writing it.</summary>
|
||||
/// <param name="actor">Who checks: needs <c>einvoice.document.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The problems, empty when the file can be sent.</returns>
|
||||
public async Task<IReadOnlyList<EInvoiceProblem>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <i>XML generato</i>. 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who generates: needs <c>einvoice.document.send</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The e-invoice, or the errors.</returns>
|
||||
public async Task<EInvoiceGeneration> 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;
|
||||
}
|
||||
|
||||
/// <summary>Generates the files of several documents and sends them (the button <i>Genera e invia</i>).</summary>
|
||||
/// <param name="actor">Who sends.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="documents">The documents.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>For each document, the generation and the sending.</returns>
|
||||
public async Task<IReadOnlyList<(PendingEInvoice? Document, EInvoiceGeneration Generation, EInvoiceSendOutcome? Sending)>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <i>Inviato</i> with its document; one no channel took keeps its
|
||||
/// state and the error.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who sends: needs <c>einvoice.document.send</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="ids">The e-invoices.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened to each.</returns>
|
||||
public async Task<IReadOnlyList<EInvoiceSendOutcome>> SendAsync(Actor actor, string companyCode, IReadOnlyList<long> 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<IEInvoiceChannels>();
|
||||
var result = new List<EInvoiceSendOutcome>();
|
||||
foreach (var id in ids.Distinct())
|
||||
{
|
||||
result.Add(await SendOneAsync(company, channels, id, actor.UserName, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Records that a generated file was sent outside Khaemhat (portal of the AdE, another program).</summary>
|
||||
/// <param name="actor">Who records it: needs <c>einvoice.document.send</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The e-invoice.</param>
|
||||
/// <param name="exchangeId">The identifier of the SDI, when known.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The e-invoice.</returns>
|
||||
public async Task<EInvoice> 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<EInvoice, long>().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);
|
||||
}
|
||||
|
||||
/// <summary>Imports notifications downloaded from the portal of the AdE or from another program.</summary>
|
||||
/// <param name="actor">Who imports: needs <c>einvoice.document.send</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="files">The files.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened to each.</returns>
|
||||
public async Task<IReadOnlyList<ReceiptOutcome>> 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<IEInvoiceReceiptReader>()
|
||||
?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]);
|
||||
var result = new List<ReceiptOutcome>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The file of an e-invoice, as sent.</summary>
|
||||
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The e-invoice.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Name and content.</returns>
|
||||
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<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
|
||||
return (invoice.FileName, invoice.Content);
|
||||
}
|
||||
|
||||
/// <summary>The file of a notification.</summary>
|
||||
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The notification.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Name and content.</returns>
|
||||
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<EInvoiceNotification, long>().GetAsync(id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
|
||||
return (notification.FileName, notification.Content);
|
||||
}
|
||||
|
||||
/// <summary>The courtesy copy: the print of the document with the XML of the e-invoice embedded.</summary>
|
||||
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c> and to read the document.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The e-invoice.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Name and content of the PDF.</returns>
|
||||
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<EInvoice, long>().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());
|
||||
}
|
||||
|
||||
/// <summary>The core of the generation, in the transaction of the caller (also the demo seed).</summary>
|
||||
internal async Task<EInvoiceGeneration> 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<EInvoice, long>();
|
||||
var active = await repository.FindAsync(Query.For<EInvoice>().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);
|
||||
}
|
||||
|
||||
/// <summary>A file taken by a channel: <i>Inviato</i>, with the document.</summary>
|
||||
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<EInvoice, long>().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
|
||||
await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Sent), userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal async Task<ReceiptOutcome> ApplyReceiptCoreAsync(
|
||||
IUnitOfWork uow, EInvoiceReceipt receipt, string? channel, string userName, bool demo, CancellationToken cancellationToken)
|
||||
{
|
||||
var notifications = uow.Repository<EInvoiceNotification, long>();
|
||||
var name = receipt.FileName;
|
||||
if (await notifications.FindAsync(Query.For<EInvoiceNotification>().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<EInvoice, long>().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<EInvoice?> FindInvoiceAsync(IUnitOfWork uow, EInvoiceReceipt receipt, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<EInvoice, long>();
|
||||
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<EInvoice>().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<EInvoice>().Where(e => e.ExchangeId == exchange).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task<EInvoiceSendOutcome> 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<EInvoice, long>().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<string>();
|
||||
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<EInvoice, long>().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<EInvoice, long>().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<List<(string Code, EInvoiceChannelSettings Settings)>> RouteAsync(IUnitOfWork uow, IEInvoiceChannels? channels, EInvoice invoice, CancellationToken cancellationToken)
|
||||
{
|
||||
if (channels is null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var rows = (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().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<SdiRoutingRule, long>().ListAsync(Query.For<SdiRoutingRule>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var party = invoice.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
|
||||
var today = _clock.GetUtcNow().UtcDateTime.Date;
|
||||
var sentToday = await uow.Repository<EInvoice, long>().CountAsync(Query.For<EInvoice>().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<string>().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<IEInvoiceWriter>();
|
||||
var validator = pack.GetFeature<IEInvoiceValidator>();
|
||||
return writer is null || validator is null ? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]) : (writer, validator, pack);
|
||||
}
|
||||
|
||||
private static async Task<long> NextProgressiveAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
var last = await uow.Repository<EInvoice, long>().FindAsync(Query.For<EInvoice>().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<List<PendingEInvoice>> PendingAsync(IUnitOfWork uow, EInvoiceFilter filter, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = Query.For<SaleDocument>().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<SaleDocument, long>().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<long>(), 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<Dictionary<long, Party>> PartiesAsync(IUnitOfWork uow, IEnumerable<long> ids, CancellationToken cancellationToken)
|
||||
{
|
||||
var set = ids.Distinct().ToList();
|
||||
var result = new Dictionary<long, Party>();
|
||||
foreach (var chunk in set.Chunk(500))
|
||||
{
|
||||
var list = chunk.ToList();
|
||||
foreach (var party in (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>The permissions of the electronic invoice (module EINV, <see cref="Modules.BuiltInModules"/>).</summary>
|
||||
public static class EInvoicePermissions
|
||||
{
|
||||
/// <summary>See the e-invoices, their notifications and the conservation packages.</summary>
|
||||
public const string Read = "einvoice.document.read";
|
||||
|
||||
/// <summary>Generate, send and send again; import notifications.</summary>
|
||||
public const string Send = "einvoice.document.send";
|
||||
|
||||
/// <summary>See the invoices received.</summary>
|
||||
public const string InboxRead = "einvoice.inbox.read";
|
||||
|
||||
/// <summary>Register, discard and upload the invoices received.</summary>
|
||||
public const string InboxImport = "einvoice.inbox.import";
|
||||
|
||||
/// <summary>Configure the channels and the routing; read the channels now.</summary>
|
||||
public const string ChannelManage = "einvoice.channel.manage";
|
||||
}
|
||||
|
||||
/// <summary>The error codes of the electronic invoice (texts in <c>EInvoicing.json</c>).</summary>
|
||||
public static class EInvoiceErrors
|
||||
{
|
||||
/// <summary>No e-invoice, notification or file with that identifier.</summary>
|
||||
public const string NotFound = "einvoice.not-found";
|
||||
|
||||
/// <summary>The kind of document does not go to the exchange system.</summary>
|
||||
public const string NotElectronic = "einvoice.not-electronic";
|
||||
|
||||
/// <summary>The document is not issued yet.</summary>
|
||||
public const string NotIssued = "einvoice.not-issued";
|
||||
|
||||
/// <summary>The file was already sent: it can only receive notifications.</summary>
|
||||
public const string AlreadySent = "einvoice.already-sent";
|
||||
|
||||
/// <summary>The profile of the company is missing.</summary>
|
||||
public const string CompanyProfileMissing = "einvoice.profile-missing";
|
||||
|
||||
/// <summary>The fiscal pack of the company does not write e-invoices.</summary>
|
||||
public const string NotSupported = "einvoice.not-supported";
|
||||
|
||||
/// <summary>No channel is enabled.</summary>
|
||||
public const string NoChannel = "einvoice.no-channel";
|
||||
|
||||
/// <summary>The file is not a notification of the exchange system.</summary>
|
||||
public const string NotAReceipt = "einvoice.not-a-receipt";
|
||||
|
||||
/// <summary>The notification is about a file Khaemhat did not send.</summary>
|
||||
public const string ReceiptUnmatched = "einvoice.receipt-unmatched";
|
||||
|
||||
/// <summary>The notification was already imported.</summary>
|
||||
public const string ReceiptDuplicate = "einvoice.receipt-duplicate";
|
||||
|
||||
/// <summary>The channel is not one of the pack.</summary>
|
||||
public const string ChannelUnknown = "einvoice.channel-unknown";
|
||||
|
||||
/// <summary>A port out of range.</summary>
|
||||
public const string PortInvalid = "einvoice.port-invalid";
|
||||
|
||||
/// <summary>The mailbox is not an e-mail address.</summary>
|
||||
public const string MailboxInvalid = "einvoice.mailbox-invalid";
|
||||
|
||||
/// <summary>The address of the service is not an https address.</summary>
|
||||
public const string EndpointInvalid = "einvoice.endpoint-invalid";
|
||||
|
||||
/// <summary>The value of a routing rule is missing or wrong.</summary>
|
||||
public const string RuleValueInvalid = "einvoice.rule-value";
|
||||
|
||||
/// <summary>The received file is already in the inbox.</summary>
|
||||
public const string InboxDuplicate = "einvoice.inbox-duplicate";
|
||||
|
||||
/// <summary>The received file is not in a state that allows the action.</summary>
|
||||
public const string InboxState = "einvoice.inbox-state";
|
||||
|
||||
/// <summary>The period of the conservation package is wrong.</summary>
|
||||
public const string PeriodInvalid = "einvoice.period-invalid";
|
||||
}
|
||||
|
||||
/// <summary>An e-invoice in the lists, with its counterpart.</summary>
|
||||
/// <param name="Invoice">The e-invoice (the file is not loaded for lists).</param>
|
||||
/// <param name="PartyCode">The code of the customer or supplier.</param>
|
||||
/// <param name="PartyName">The name.</param>
|
||||
public sealed record EInvoiceRow(EInvoice Invoice, string? PartyCode, string? PartyName);
|
||||
|
||||
/// <summary>An issued document without its file yet, or whose file was rejected.</summary>
|
||||
/// <param name="Family">The family.</param>
|
||||
/// <param name="DocumentId">The document.</param>
|
||||
/// <param name="Kind">The kind.</param>
|
||||
/// <param name="Number">The number.</param>
|
||||
/// <param name="Date">The date.</param>
|
||||
/// <param name="PartyName">The customer, or the supplier of a self-invoice.</param>
|
||||
/// <param name="Total">The total.</param>
|
||||
/// <param name="Status">The state of the document.</param>
|
||||
public sealed record PendingEInvoice(DocumentFamily Family, long DocumentId, DocumentKind Kind, string? Number, DateOnly Date, string? PartyName, decimal Total, DocumentStatus Status);
|
||||
|
||||
/// <summary>What the dashboard shows.</summary>
|
||||
public enum EInvoiceView
|
||||
{
|
||||
/// <summary>Invoices, notes and fees sent to customers.</summary>
|
||||
Issued = 0,
|
||||
|
||||
/// <summary>Self-invoices and integrations.</summary>
|
||||
SelfInvoices = 1,
|
||||
|
||||
/// <summary>Everything that needs the user: to generate, to send, rejected, refused.</summary>
|
||||
ToDo = 2,
|
||||
}
|
||||
|
||||
/// <summary>The filter of the dashboard.</summary>
|
||||
/// <param name="View">The view.</param>
|
||||
/// <param name="Status">Only this state.</param>
|
||||
/// <param name="From">From this date of the document.</param>
|
||||
/// <param name="To">Up to this date.</param>
|
||||
/// <param name="Search">Number, file name, identifier of the SDI or counterpart.</param>
|
||||
public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EInvoiceStatus? Status = null, DateOnly? From = null, DateOnly? To = null, string? Search = null);
|
||||
|
||||
/// <summary>The counters of the dashboard (mockup 058).</summary>
|
||||
/// <param name="ToGenerate">Issued documents without a file.</param>
|
||||
/// <param name="ToSend">Files generated and not sent.</param>
|
||||
/// <param name="Waiting">Sent, waiting for the receipt.</param>
|
||||
/// <param name="Delivered">Delivered or accepted (RC, NE EC01, DT).</param>
|
||||
/// <param name="Rejected">Rejected by the SDI or refused by a public administration.</param>
|
||||
/// <param name="NotDelivered">Issued but not delivered: in the reserved area of the customer (MC, AT).</param>
|
||||
/// <param name="Received">Invoices received to register.</param>
|
||||
public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int NotDelivered, int Received);
|
||||
|
||||
/// <summary>The dashboard.</summary>
|
||||
/// <param name="Rows">The e-invoices of the view.</param>
|
||||
/// <param name="Pending">The documents to generate (view <see cref="EInvoiceView.ToDo"/> and the counters).</param>
|
||||
/// <param name="Counters">The counters.</param>
|
||||
public sealed record EInvoiceDashboard(IReadOnlyList<EInvoiceRow> Rows, IReadOnlyList<PendingEInvoice> Pending, EInvoiceCounters Counters);
|
||||
|
||||
/// <summary>The outcome of a generation: the file, or why not.</summary>
|
||||
/// <param name="Invoice">The e-invoice written.</param>
|
||||
/// <param name="Problems">Errors (nothing written) and warnings.</param>
|
||||
public sealed record EInvoiceGeneration(EInvoice? Invoice, IReadOnlyList<EInvoiceProblem> Problems)
|
||||
{
|
||||
/// <summary>Whether the file was written.</summary>
|
||||
public bool Success => Invoice is not null;
|
||||
}
|
||||
|
||||
/// <summary>The outcome of sending one file.</summary>
|
||||
/// <param name="EInvoiceId">The e-invoice.</param>
|
||||
/// <param name="FileName">The file.</param>
|
||||
/// <param name="DocumentNumber">The document.</param>
|
||||
/// <param name="Sent">Whether a channel took it.</param>
|
||||
/// <param name="ChannelCode">The channel that took it, or the last one tried.</param>
|
||||
/// <param name="Error">Why not (a message of the channel, or an error code).</param>
|
||||
public sealed record EInvoiceSendOutcome(long EInvoiceId, string FileName, string? DocumentNumber, bool Sent, string? ChannelCode, string? Error);
|
||||
|
||||
/// <summary>The outcome of a notification imported or received.</summary>
|
||||
/// <param name="FileName">The notification.</param>
|
||||
/// <param name="Code">Its code (RC, NS …).</param>
|
||||
/// <param name="InvoiceFileName">The file it is about.</param>
|
||||
/// <param name="EInvoiceId">The e-invoice updated.</param>
|
||||
/// <param name="Status">The state it reached.</param>
|
||||
/// <param name="Error">Why it was not applied (error code).</param>
|
||||
public sealed record ReceiptOutcome(string FileName, string? Code, string? InvoiceFileName, long? EInvoiceId, EInvoiceStatus? Status, string? Error);
|
||||
|
||||
/// <summary>What the services of the electronic invoice share.</summary>
|
||||
internal static class EInvoiceStore
|
||||
{
|
||||
/// <summary>The channel of what the user uploads or sends from the portal of the AdE.</summary>
|
||||
public const string ManualChannel = "MANUAL";
|
||||
|
||||
/// <summary>The purpose of the protection of the secrets of the channels.</summary>
|
||||
public const string SecretPurpose = "einvoice.channel";
|
||||
|
||||
/// <summary>The SHA-256 of a file in lower-case hexadecimal.</summary>
|
||||
public static string Hash(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content));
|
||||
|
||||
/// <summary>A text cut to a length.</summary>
|
||||
public static string? Trim(string? text, int length) =>
|
||||
string.IsNullOrWhiteSpace(text) ? null : text.Trim().Length <= length ? text.Trim() : text.Trim()[..length];
|
||||
|
||||
/// <summary>The settings of a channel for its transport, secrets unprotected.</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The name of the invoice file a notification is about, from the name of the notification.</summary>
|
||||
/// <param name="receiptFileName">The notification (<c>IT01234567890_00001_RC_001.xml</c>).</param>
|
||||
/// <returns>The stem of the invoice file (<c>IT01234567890_00001</c>), or <see langword="null"/>.</returns>
|
||||
public static string? InvoiceStem(string receiptFileName)
|
||||
{
|
||||
var name = Path.GetFileName(receiptFileName);
|
||||
var parts = name.Split('_');
|
||||
return parts.Length >= 4 ? string.Join('_', parts[..^2]) : null;
|
||||
}
|
||||
|
||||
/// <summary>The stem of a file name: without <c>.xml</c> and <c>.p7m</c>.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A shallow copy of a row (public properties that can be written), for the history of a change.</summary>
|
||||
public static T Clone<T>(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;
|
||||
}
|
||||
|
||||
/// <summary>A copy without the file, for lists and history.</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>The filter of the invoices received.</summary>
|
||||
/// <param name="Status">Only this state.</param>
|
||||
/// <param name="Search">Supplier, VAT number, number or file name.</param>
|
||||
public sealed record InboxFilter(InboxFileStatus? Status = null, string? Search = null);
|
||||
|
||||
/// <summary>A received file stored, or why not.</summary>
|
||||
/// <param name="FileName">The file.</param>
|
||||
/// <param name="Id">The row of the inbox.</param>
|
||||
/// <param name="Status">Its state.</param>
|
||||
/// <param name="Error">Why it was not stored (error code).</param>
|
||||
public sealed record InboxStored(string FileName, long? Id, InboxFileStatus? Status, string? Error);
|
||||
|
||||
/// <summary>A received invoice registered as a supplier document, or why not.</summary>
|
||||
/// <param name="Id">The row of the inbox.</param>
|
||||
/// <param name="FileName">The file.</param>
|
||||
/// <param name="PurchaseDocumentId">The draft supplier document.</param>
|
||||
/// <param name="Error">Why it was not registered (error code).</param>
|
||||
/// <param name="Warnings">What to check on the draft (codes).</param>
|
||||
public sealed record InboxRegistered(long Id, string FileName, long? PurchaseDocumentId, string? Error, IReadOnlyList<string> Warnings);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions: <c>einvoice.inbox.read</c> to see, <c>einvoice.inbox.import</c> to upload, register and discard
|
||||
/// (registering also needs <c>purchases.invoice.write</c>).</remarks>
|
||||
public sealed class SdiInboxService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly PurchaseInvoiceImportService _import;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="import">The import of supplier invoices.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The invoices received, newest first (files not loaded).</summary>
|
||||
/// <param name="actor">Who looks: needs <c>einvoice.inbox.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="filter">The filter.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<EInvoiceInboxFile>> 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<EInvoiceInboxFile>();
|
||||
if (filter.Status is { } status)
|
||||
{
|
||||
query = query.Where(f => f.Status == status);
|
||||
}
|
||||
|
||||
var rows = (await uow.Repository<EInvoiceInboxFile, long>().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];
|
||||
}
|
||||
|
||||
/// <summary>The received file, as it arrived.</summary>
|
||||
/// <param name="actor">Who downloads: needs <c>einvoice.inbox.read</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The row.</param>
|
||||
/// <param name="metadata">The metadata file (MT) instead of the invoice.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Name and content.</returns>
|
||||
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<EInvoiceInboxFile, long>().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);
|
||||
}
|
||||
|
||||
/// <summary>Stores files the user uploads (downloaded from the portal of the AdE or received elsewhere).</summary>
|
||||
/// <param name="actor">Who uploads: needs <c>einvoice.inbox.import</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="files">The files.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened to each.</returns>
|
||||
public async Task<IReadOnlyList<InboxStored>> 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<IIncomingInvoiceReader>();
|
||||
var receipts = pack.GetFeature<IEInvoiceReceiptReader>();
|
||||
var result = new List<InboxStored>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who registers: needs <c>einvoice.inbox.import</c> and <c>purchases.invoice.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="ids">The rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened to each.</returns>
|
||||
public async Task<IReadOnlyList<InboxRegistered>> RegisterAsync(Actor actor, string companyCode, IReadOnlyList<long> 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<InboxRegistered>();
|
||||
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<EInvoiceInboxFile, long>().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<EInvoiceInboxFile, long>().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<EInvoiceInboxFile, long>().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;
|
||||
}
|
||||
|
||||
/// <summary>Discards a received invoice (a copy, a file not for the company), or takes it back.</summary>
|
||||
/// <param name="actor">Who does it: needs <c>einvoice.inbox.import</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The row.</param>
|
||||
/// <param name="discard">Discard, or take back.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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<EInvoiceInboxFile, long>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static async Task<InboxStored> StoreCoreAsync(
|
||||
IUnitOfWork uow, IIncomingInvoiceReader? reader, string fileName, byte[] content, DateTime receivedAt, string? channel, string? exchangeId, bool demo,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<EInvoiceInboxFile, long>();
|
||||
var hash = EInvoiceStore.Hash(content);
|
||||
if (await repository.FindAsync(Query.For<EInvoiceInboxFile>().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);
|
||||
}
|
||||
|
||||
/// <summary>Keeps the metadata file (MT) with the invoice it describes, by the name of the invoice file.</summary>
|
||||
internal static async Task<EInvoiceInboxFile?> AttachMetadataCoreAsync(IUnitOfWork uow, EInvoiceReceipt metadata, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<EInvoiceInboxFile, long>();
|
||||
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<EInvoiceInboxFile>().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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>The answer to a push of the exchange system.</summary>
|
||||
/// <param name="StatusCode">The HTTP status.</param>
|
||||
/// <param name="ContentType">The content type.</param>
|
||||
/// <param name="Body">The body.</param>
|
||||
public sealed record SdiPushAnswer(int StatusCode, string ContentType, string Body);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>X-Khaemhat-SdiCoop-Key</c>); 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.
|
||||
/// </summary>
|
||||
public sealed partial class SdiPushService
|
||||
{
|
||||
/// <summary>The header with the key of the channel.</summary>
|
||||
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<SdiPushService> _logger;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="companies">The companies.</param>
|
||||
/// <param name="license">The licence.</param>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="secrets">Opens the key of the channel.</param>
|
||||
/// <param name="polling">Sorts the files received.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log (section SDI).</param>
|
||||
public SdiPushService(
|
||||
ICompanyRegistry companies, ILicenseGate license, IUnitOfWorkFactory factory, CompanyFiscalContext packs, ISecretProtector secrets,
|
||||
EInvoicePollingService polling, TimeProvider clock, ILogger<SdiPushService> 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;
|
||||
}
|
||||
|
||||
/// <summary>Takes a push.</summary>
|
||||
/// <param name="companyCode">The company in the address.</param>
|
||||
/// <param name="key">The key in the header.</param>
|
||||
/// <param name="contentType">The content type.</param>
|
||||
/// <param name="body">The body.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The answer.</returns>
|
||||
public async Task<SdiPushAnswer> 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<IEInvoicePushReader>() 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<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().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);
|
||||
}
|
||||
@@ -268,6 +268,13 @@ public sealed class InventoryService
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
|
||||
await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ValuationAsync(uow, date, warehouseId, method, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The value of the stock at a date inside a unit of work (the closing values the inventory with it).</summary>
|
||||
internal static async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
|
||||
IUnitOfWork uow, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken)
|
||||
{
|
||||
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(
|
||||
Query.For<InventoryEntryLine>().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -33,6 +33,8 @@ public static class BuiltInModules
|
||||
("sales.invoice.delete", "Eliminare fatture in bozza"),
|
||||
("sales.invoice.print", "Stampare fatture di vendita"),
|
||||
("sales.invoice.export", "Esportare fatture di vendita"),
|
||||
("sales.intent.read", "Vedere le dichiarazioni d'intento"),
|
||||
("sales.intent.write", "Registrare le dichiarazioni d'intento"),
|
||||
("purchases.order.read", "Vedere ordini fornitore"),
|
||||
("purchases.order.write", "Creare e modificare ordini fornitore"),
|
||||
("purchases.invoice.read", "Vedere fatture di acquisto"),
|
||||
@@ -70,7 +72,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"),
|
||||
@@ -134,7 +137,7 @@ public static class PredefinedRoles
|
||||
[
|
||||
new(Administration, "Amministrazione", "Tutte le funzioni dell'azienda, compresi utenti e impostazioni.", ["*"]),
|
||||
new("ACCOUNTING", "Contabilità", "Contabilità, IVA, cespiti, tesoreria, fatturazione elettronica e Intrastat.",
|
||||
["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read",
|
||||
["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read", "sales.intent.*",
|
||||
"purchases.invoice.*", "reports.report.read", "attachments.read", "attachments.write"]),
|
||||
new("SALES", "Vendite", "Preventivi, ordini, DDT e fatture di vendita; anagrafiche clienti.",
|
||||
["sales.*", "parties.*", "items.item.read", "inventory.stock.read", "crm.lead.read", "crm.opportunity.read",
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace Khaemhat.Application.Purchases;
|
||||
/// <param name="ComputedTotal">Taxable plus tax of the summary, plus rounding: what the total should be.</param>
|
||||
/// <param name="Problems">What stops or warns (resource codes).</param>
|
||||
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<string> Problems)
|
||||
{
|
||||
/// <summary>Whether it can be registered.</summary>
|
||||
@@ -141,7 +141,7 @@ public sealed class PurchaseInvoiceImportService
|
||||
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var reader = pack.GetFeature<IIncomingInvoiceReader>();
|
||||
var rules = pack.GetFeature<IIncomingInvoiceRules>();
|
||||
var found = new List<(string Name, IncomingInvoiceFile File)>();
|
||||
var found = new List<(string Name, EInvoiceFile File)>();
|
||||
var rejected = new List<IncomingRejected>();
|
||||
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<long?> FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken)
|
||||
internal static async Task<long?> FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken)
|
||||
{
|
||||
var parties = uow.Repository<Party, long>();
|
||||
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<bool> IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken)
|
||||
private static async Task<bool> 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<long> CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken)
|
||||
private async Task<long> 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<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
|
||||
private static long? ItemOf(EInvoiceLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
|
||||
{
|
||||
foreach (var code in line.Codes.Select(c => c.Value.Trim()))
|
||||
{
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>What the removal of the demo data did.</summary>
|
||||
/// <param name="Removed">Rows removed, by table.</param>
|
||||
/// <param name="Blockers">Tables whose own rows (not demo) still refer to demo rows: nothing was removed.</param>
|
||||
public sealed record DemoRemoval(IReadOnlyDictionary<string, int> Removed, IReadOnlyList<string> Blockers)
|
||||
{
|
||||
/// <summary>Whether the demo data were removed.</summary>
|
||||
public bool Done => Blockers.Count == 0;
|
||||
|
||||
/// <summary>All the rows removed.</summary>
|
||||
public int Total => Removed.Values.Sum();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the demo data of a company, and only them (SPEC §14, issue #80): the rows marked <c>is_demo</c> 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.
|
||||
/// </summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
public sealed class DemoDataRemover(IUnitOfWorkFactory factory)
|
||||
{
|
||||
private const string DemoColumn = "is_demo";
|
||||
|
||||
/// <summary>Removes the demo data of a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was removed, or what stopped it.</returns>
|
||||
public async Task<DemoRemoval> 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<string, SqlFragment?>(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<string>();
|
||||
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<long>(
|
||||
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<string, int>(), blockers);
|
||||
}
|
||||
|
||||
var removed = new Dictionary<string, int>(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<string, TableDefinition> tables, Dictionary<string, SqlFragment?> doomed, HashSet<string> 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<SqlFragment>();
|
||||
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<TableDefinition> DeleteOrder(List<TableDefinition> tables)
|
||||
{
|
||||
var names = tables.Select(t => t.Name).ToHashSet(StringComparer.Ordinal);
|
||||
var result = new List<TableDefinition>();
|
||||
var placed = new HashSet<string>(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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="invoices">The e-invoices.</param>
|
||||
/// <param name="packs">The fiscal pack of the company.</param>
|
||||
/// <param name="secrets">Protects the demo password.</param>
|
||||
/// <param name="factory">Reads and writes the company.</param>
|
||||
/// <param name="licenses">Whether the electronic invoice is licensed.</param>
|
||||
public sealed class DemoEInvoiceSeeder(
|
||||
EInvoiceService invoices, CompanyFiscalContext packs, ISecretProtector secrets, IUnitOfWorkFactory factory, ILicenseGate licenses)
|
||||
: ICompanySeeder
|
||||
{
|
||||
/// <summary>The demo certified mailbox.</summary>
|
||||
public const string Mailbox = "fatture@pec.khaemhat-demo.it";
|
||||
|
||||
/// <summary>How many of the last invoices stay without a file (to generate).</summary>
|
||||
public const int LeftToGenerate = 1;
|
||||
|
||||
/// <summary>How many files stay generated and not sent.</summary>
|
||||
public const int LeftToSend = 1;
|
||||
|
||||
/// <summary>How many files sent stay waiting for the receipt.</summary>
|
||||
public const int LeftWaiting = 2;
|
||||
|
||||
private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0";
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 60;
|
||||
|
||||
/// <inheritdoc />
|
||||
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<IEInvoiceWriter>() is not { } writer || pack.GetFeature<IEInvoiceValidator>() is not { } validator
|
||||
|| pack.GetFeature<IEInvoiceReceiptReader>() is not { } receipts)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
List<SaleDocument> documents;
|
||||
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await uow.Repository<EInvoice, long>().CountAsync(Query.For<EInvoice>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<EInvoiceInboxFile, long>().CountAsync(Query.For<EInvoiceInboxFile>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), 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<SaleDocument, long>()
|
||||
.ListAsync(Query.For<SaleDocument>().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<EInvoice>();
|
||||
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<EInvoice, long>().GetAsync(invoice.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (current is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await invoices.MarkSentCoreAsync(uow, current, "PEC", null, "<demo-" + exchangeId + "@pec.khaemhat-demo.it>", 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<EInvoice, long>().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);
|
||||
}
|
||||
|
||||
/// <summary>A notification as the SDI writes it (<c>MessaggiTypes</c> v1.0).</summary>
|
||||
/// <param name="root">The root element.</param>
|
||||
/// <param name="body">The children.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes(
|
||||
$"""<?xml version="1.0" encoding="UTF-8"?><types:{root} xmlns:types="{Ns}" versione="1.0">{body}</types:{root}>""");
|
||||
|
||||
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) =>
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
|
||||
+ $"<DataOraConsegna>{Stamp(at)}</DataOraConsegna><MessageId>{exchangeId}1</MessageId>";
|
||||
|
||||
private static string Basic(string file, string exchangeId, DateTimeOffset at, string note) =>
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
|
||||
+ $"<Descrizione>{note}</Descrizione><MessageId>{exchangeId}2</MessageId><Note>{note}</Note>";
|
||||
|
||||
private static string Rejection(string file, string exchangeId, DateTimeOffset at) =>
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
|
||||
+ "<ListaErrori><Errore><Codice>00305</Codice><Descrizione>1.4.1.1.2 IdCodice del cessionario/committente non valido</Descrizione>"
|
||||
+ "<Suggerimento>Verificare la partita IVA del cliente in anagrafica</Suggerimento></Errore></ListaErrori>"
|
||||
+ $"<MessageId>{exchangeId}3</MessageId>";
|
||||
|
||||
private async Task ChannelsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
var channels = uow.Repository<EInvoiceChannelSetting, long>();
|
||||
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<SdiRoutingRule, long>();
|
||||
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<IIncomingInvoiceReader>() is not { } reader)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), 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<Party, long>().ListAsync(Query.For<Party>().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<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().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<EInvoiceInboxFile, long>().GetAsync(rowId, cancellationToken).ConfigureAwait(false);
|
||||
if (row is not null)
|
||||
{
|
||||
row.MetadataFileName = EInvoiceStore.Stem(name) + "_MT_001.xml";
|
||||
row.Metadata = Notification("FileMetadati",
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{name}</NomeFile><Hash>demo</Hash><CodiceDestinatario>{incoming.RecipientCode}</CodiceDestinatario>"
|
||||
+ $"<Formato>FPR12</Formato><TentativiInvio>1</TentativiInvio><MessageId>{exchangeId}9</MessageId>");
|
||||
await uow.Repository<EInvoiceInboxFile, long>().UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,15 @@ public sealed class DemoLedgerSeeder(
|
||||
public int Order => 40;
|
||||
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Migrations;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>is_demo</c> is taken before the
|
||||
/// seeder runs, and the rows after it are marked when it ends. So <see cref="DemoDataRemover"/> finds them all. A demo
|
||||
/// seed is an administrative operation: rows the users would write meanwhile in the same company would be marked too.
|
||||
/// </summary>
|
||||
internal sealed class DemoMarker
|
||||
{
|
||||
private const string DemoColumn = "is_demo";
|
||||
|
||||
private static readonly Lazy<IReadOnlyList<string>> 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<string, long> _last;
|
||||
|
||||
private DemoMarker(IUnitOfWorkFactory factory, string company, Dictionary<string, long> last)
|
||||
{
|
||||
_factory = factory;
|
||||
_company = company;
|
||||
_last = last;
|
||||
}
|
||||
|
||||
/// <summary>Runs a demo seeder and marks what it created.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="seed">The seeder.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task RunAsync(IUnitOfWorkFactory factory, string company, Func<Task> 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<DemoMarker> TakeAsync(IUnitOfWorkFactory factory, string company, CancellationToken cancellationToken)
|
||||
{
|
||||
var last = new Dictionary<string, long>(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<long?>(
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,15 @@ public sealed class DemoPurchasesSeeder(
|
||||
public int Order => 30;
|
||||
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
|
||||
@@ -43,7 +43,15 @@ public sealed class DemoSalesSeeder(
|
||||
public int Order => 20;
|
||||
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
|
||||
@@ -78,7 +78,15 @@ public sealed class DemoTreasurySeeder(
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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))
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Inventory;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Application.YearEnd;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// The demo data of the year end (SPEC §14, issue #87): the opening balances of the year (share capital, retained
|
||||
/// earnings, bank, the opening stock and the fixed assets bought in the years before with their funds), the standard categories and four assets, one of them
|
||||
/// bought this year; the declaration of intent of Idrotermica Piemonte taken into the register and an invoice under it
|
||||
/// (NI8C); an intra-EU sale of goods to Bergwerk Bau (Austria) with nomenclature and mass for the Intrastat list; the
|
||||
/// insurance premium paid in October with its prepaid share. With these the guided closing of the demo year runs from
|
||||
/// the first step to the last. Runs after the demo e-invoices and only once: when the company has fixed assets or
|
||||
/// accruals it adds nothing.
|
||||
/// </summary>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The document editor.</param>
|
||||
/// <param name="ledger">Posts the new invoices.</param>
|
||||
/// <param name="packs">The fiscal pack of the company.</param>
|
||||
/// <param name="factory">Reads and writes the company.</param>
|
||||
/// <param name="licenses">Which modules are licensed.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class DemoYearEndSeeder(
|
||||
DocumentEngine engine, DocumentEditor editor, LedgerService ledger, CompanyFiscalContext packs, IUnitOfWorkFactory factory, ILicenseGate licenses, TimeProvider clock)
|
||||
: ICompanySeeder
|
||||
{
|
||||
/// <summary>The share capital of the demo company.</summary>
|
||||
public const decimal ShareCapital = 50_000m;
|
||||
|
||||
/// <summary>The bank balance on the first of January.</summary>
|
||||
public const decimal OpeningBank = 25_000m;
|
||||
|
||||
/// <summary>The yearly insurance premium paid on the first of October.</summary>
|
||||
public const decimal InsurancePremium = 1_800m;
|
||||
|
||||
private const string InsuranceAccount = "21.03.005";
|
||||
|
||||
private const string RetainedEarnings = "10.02.001";
|
||||
|
||||
private static readonly Actor Seed = Actor.System;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 70;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return context.Demo
|
||||
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, cancellationToken), cancellationToken)
|
||||
: Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task SeedCoreAsync(string companyCode, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!licenses.IsModuleActive(ModuleCodes.Accounting))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var pack = await packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
var start = new DateOnly(today.Year, 1, 1);
|
||||
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await uow.Repository<GlAccount, long>().CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0
|
||||
|| await uow.Repository<FixedAsset, long>().CountAsync(Query.For<FixedAsset>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<AccrualDeferral, long>().CountAsync(Query.For<AccrualDeferral>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.EntryDate == start && e.Source == GlEntrySource.Manual), cancellationToken)
|
||||
.ConfigureAwait(false) > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await OpeningAsync(uow, pack, today, cancellationToken).ConfigureAwait(false);
|
||||
await InsuranceAsync(uow, today, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<IIntentRules>() is { } intent)
|
||||
{
|
||||
await IntentDeclarationService.AdoptAsync(uow, intent, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await InvoicesAsync(companyCode, today, cancellationToken).ConfigureAwait(false);
|
||||
await ledger.PostPendingAsync(Seed, companyCode, start, today, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The opening entry of the year and the fixed assets: three bought in the years before (cost and funds in the
|
||||
// opening entry) and the computers bought in March and paid by bank transfer.
|
||||
private async Task OpeningAsync(IUnitOfWork uow, IFiscalPack pack, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
if (pack.GetFeature<IClosingRules>() is not { } closing
|
||||
|| !accounts.TryGetValue(closing.Accounts.Capital, out var capital) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var year = today.Year;
|
||||
var start = new DateOnly(year, 1, 1);
|
||||
var lines = new List<EntryLineDraft>();
|
||||
var assets = new List<AssetInput>();
|
||||
if (licenses.IsModuleActive(ModuleCodes.Assets) && pack.GetFeature<IFixedAssetRules>() is { } rules)
|
||||
{
|
||||
await FixedAssetService.CreateStandardCategoriesAsync(uow, rules.Coefficients, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
|
||||
var categories = (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Code, StringComparer.Ordinal);
|
||||
void Add(string category, string description, int yearsBack, decimal cost, decimal fund, string? serial = null, string? location = null)
|
||||
{
|
||||
if (!categories.TryGetValue(category, out var c) || c.AssetAccountId is not { } asset || c.FundAccountId is not { } fundAccount)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var bought = new DateOnly(year - yearsBack, 3, 15);
|
||||
assets.Add(new AssetInput(null, null, description, c.Id, bought, bought, cost)
|
||||
{
|
||||
OpeningCivilFund = fund,
|
||||
OpeningFiscalFund = fund,
|
||||
LastDepreciationYear = yearsBack > 0 ? year - 1 : null,
|
||||
SerialNumber = serial,
|
||||
Location = location,
|
||||
});
|
||||
if (yearsBack > 0)
|
||||
{
|
||||
lines.Add(new EntryLineDraft(asset, null, description, cost, 0m));
|
||||
lines.Add(new EntryLineDraft(fundAccount, null, description, 0m, fund));
|
||||
}
|
||||
}
|
||||
|
||||
// Funds: the civil quotas of the years before, half in the first year.
|
||||
Add("AUC", "Furgone Fiat Ducato 2.3 Multijet", 3, 32_000m, 16_000m, "ZFA25000002K12345", "Sede");
|
||||
Add("ATT", "Scaffalature metalliche magazzino", 2, 18_400m, 4_140m, null, "Magazzino");
|
||||
Add("MOB", "Arredi ufficio commerciale", 4, 9_600m, 4_032m, null, "Uffici");
|
||||
Add("EDP", "Server e personal computer", 0, 6_500m, 0m, "SRV-2026-001", "Sala server");
|
||||
}
|
||||
|
||||
// The opening stock of the demo warehouse (the inventory entry of the first of January) at its cost.
|
||||
var stock = (await InventoryService.ValuationAsync(uow, start, null, StockValuationMethod.WeightedAverage, cancellationToken).ConfigureAwait(false)).Sum(r => r.Value);
|
||||
if (stock > 0m && accounts.TryGetValue(closing.Accounts.Inventory, out var inventory))
|
||||
{
|
||||
lines.Add(new EntryLineDraft(inventory.Id, null, "Rimanenze iniziali", Math.Round(stock, 2, MidpointRounding.AwayFromZero), 0m));
|
||||
}
|
||||
|
||||
lines.Add(new EntryLineDraft(bank.Id, null, null, OpeningBank, 0m));
|
||||
lines.Add(new EntryLineDraft(capital.Id, null, null, 0m, ShareCapital));
|
||||
if (accounts.TryGetValue(RetainedEarnings, out var retained))
|
||||
{
|
||||
var balance = lines.Sum(l => l.Debit - l.Credit);
|
||||
lines.Add(new EntryLineDraft(retained.Id, null, null, balance < 0m ? -balance : 0m, balance > 0m ? balance : 0m));
|
||||
}
|
||||
await YearEndLedger.PostAsync(uow, start, "Apertura conti (dati dimostrativi)", GlEntrySource.Manual, null, lines, true, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
foreach (var input in assets)
|
||||
{
|
||||
await FixedAssetService.SaveAsync(uow, pack.Require<IFixedAssetRules>(), input, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
|
||||
if (input.LastDepreciationYear is null
|
||||
&& (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).FirstOrDefault(c => c.Id == input.CategoryId) is { AssetAccountId: { } account })
|
||||
{
|
||||
// Bought this year: the purchase, paid by bank transfer (the invoice of the supplier is not part of the demo).
|
||||
var bought = input.PurchaseDate;
|
||||
await YearEndLedger.PostAsync(uow, bought <= today ? bought : today, "Acquisto " + input.Description.ToLowerInvariant(), GlEntrySource.Manual, null,
|
||||
[new EntryLineDraft(account, null, null, input.Cost, 0m), new EntryLineDraft(bank.Id, null, null, 0m, input.Cost)], true, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The insurance premium of the van, paid on the first of October for a year: three months fall in this year, nine
|
||||
// in the next (prepaid expense).
|
||||
private static async Task InsuranceAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var paid = new DateOnly(today.Year, 10, 1);
|
||||
if (paid > today || !accounts.TryGetValue(InsuranceAccount, out var insurance) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const string description = "Premio assicurazione furgone 01/10 - 30/09";
|
||||
await YearEndLedger.PostAsync(uow, paid, description, GlEntrySource.Manual, null,
|
||||
[new EntryLineDraft(insurance.Id, null, null, InsurancePremium, 0m), new EntryLineDraft(bank.Id, null, null, 0m, InsurancePremium)], true, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await AccrualService.SaveAsync(uow, new AccrualDeferral
|
||||
{
|
||||
Year = today.Year,
|
||||
Kind = AccrualKind.PrepaidExpense,
|
||||
Description = description,
|
||||
AccountId = insurance.Id,
|
||||
Amount = InsurancePremium,
|
||||
PeriodStart = paid,
|
||||
PeriodEnd = paid.AddYears(1).AddDays(-1),
|
||||
DocumentNumber = "POL-4471",
|
||||
}, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// An invoice under the declaration of intent of Idrotermica Piemonte (NI8C) and an intra-EU sale of goods to
|
||||
// Bergwerk Bau (NI41), both of today so that the numbering stays in date order.
|
||||
private async Task InvoicesAsync(string company, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
Dictionary<string, long> parties;
|
||||
List<Item> goods;
|
||||
Dictionary<string, long> taxCodes;
|
||||
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
|
||||
goods = [.. (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo && i.Kind == ItemKind.Goods), cancellationToken).ConfigureAwait(false)).Items
|
||||
.OrderBy(i => i.Id)];
|
||||
taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(t => t.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
|
||||
if (await uow.Repository<SaleDocument, long>().CountAsync(Query.For<SaleDocument>(), cancellationToken).ConfigureAwait(false) == 0)
|
||||
{
|
||||
return; // No demo sales: the documents would open the numbering.
|
||||
}
|
||||
}
|
||||
|
||||
var intrastat = goods.Where(i => !string.IsNullOrEmpty(i.CustomsCode) && i.NetWeight is > 0m).Take(2).ToList();
|
||||
if (parties.TryGetValue("Idrotermica Piemonte S.r.l.", out var idrotermica) && taxCodes.TryGetValue("NI8C", out var ni8c) && goods.Count > 3)
|
||||
{
|
||||
await InvoiceAsync(company, idrotermica, today, [(goods[1], 40m), (goods[3], 25m)], ni8c, "Fornitura in sospensione d'imposta", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (licenses.IsModuleActive(ModuleCodes.Intrastat) && parties.TryGetValue("Bergwerk Bau GmbH", out var bergwerk) && taxCodes.TryGetValue("NI41", out var ni41)
|
||||
&& intrastat.Count > 0)
|
||||
{
|
||||
await InvoiceAsync(company, bergwerk, today, [.. intrastat.Select(i => (i, 30m))], ni41, "Consegna franco destino Innsbruck", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task InvoiceAsync(
|
||||
string company, long partyId, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, long taxCodeId, string notes, CancellationToken cancellationToken)
|
||||
{
|
||||
var record = await engine.NewAsync(Seed, company, "FI", cancellationToken).ConfigureAwait(false);
|
||||
record.Header.IsDemo = true;
|
||||
record.Header.DocumentDate = date;
|
||||
record.Header.Notes = notes;
|
||||
await editor.ApplyPartyAsync(Seed, company, record, partyId, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var (item, quantity) in lines)
|
||||
{
|
||||
var line = DocumentStores.Of(record.Family).NewLine();
|
||||
line.Quantity = quantity;
|
||||
await editor.FillLineAsync(Seed, company, record, line, item.Id, cancellationToken).ConfigureAwait(false);
|
||||
line.TaxCodeId = taxCodeId;
|
||||
record.Lines.Add(line);
|
||||
}
|
||||
|
||||
record = await engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false);
|
||||
await engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>An accrual with the names of its account and party.</summary>
|
||||
/// <param name="Accrual">The accrual.</param>
|
||||
/// <param name="AccountCode">The code of the account.</param>
|
||||
/// <param name="AccountDescription">The description of the account.</param>
|
||||
/// <param name="PartyName">The customer or supplier.</param>
|
||||
public sealed record AccrualRow(AccrualDeferral Accrual, string AccountCode, string AccountDescription, string? PartyName);
|
||||
|
||||
/// <summary>The exchange difference of an open item in foreign currency at the year end.</summary>
|
||||
/// <param name="OpenItemId">The open item.</param>
|
||||
/// <param name="Direction">Receivable or payable.</param>
|
||||
/// <param name="PartyId">The customer or supplier.</param>
|
||||
/// <param name="PartyName">Its name.</param>
|
||||
/// <param name="AccountId">The control account.</param>
|
||||
/// <param name="DocumentNumber">The number of the document.</param>
|
||||
/// <param name="DocumentDate">The date of the document.</param>
|
||||
/// <param name="CurrencyCode">The currency.</param>
|
||||
/// <param name="DocumentRate">The rate of the document.</param>
|
||||
/// <param name="YearEndRate">The rate of the year end; <see langword="null"/> when none is known.</param>
|
||||
/// <param name="ResidualEuro">The residual in euro at the rate of the document.</param>
|
||||
/// <param name="ResidualCurrency">The residual in the currency.</param>
|
||||
/// <param name="Difference">The difference in euro.</param>
|
||||
public sealed record ExchangeDifferenceLine(
|
||||
long OpenItemId, OpenItemDirection Direction, long PartyId, string? PartyName, long AccountId, string? DocumentNumber, DateOnly DocumentDate, string CurrencyCode,
|
||||
decimal DocumentRate, decimal? YearEndRate, decimal ResidualEuro, decimal ResidualCurrency, decimal Difference)
|
||||
{
|
||||
/// <summary>Whether the difference is a gain.</summary>
|
||||
public bool Gain => ExchangeDifferenceCalculator.IsGain(Direction, Difference);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The accruals and deferrals and the exchange differences of the year end (SPEC §11.7, issue #84, ADR 0043): ratei and
|
||||
/// risconti typed or proposed from the costs that straddle the year end, the share computed by days; the open items in
|
||||
/// foreign currency valued at the rate of the last day. Step 3 of the closing posts both and step 8 reverses them on
|
||||
/// the first day of the next year.
|
||||
/// </summary>
|
||||
public sealed class AccrualService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly AuditTrail _audit;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
public AccrualService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
_audit = audit;
|
||||
}
|
||||
|
||||
/// <summary>The accruals of a year.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The fiscal year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The accruals.</returns>
|
||||
public async Task<IReadOnlyList<AccrualRow>> ListAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ListAsync(uow, year, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Saves an accrual: the share is computed by days; one posted by the closing is read only.</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The accrual; id 0 for a new one.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The accrual saved.</returns>
|
||||
public async Task<AccrualDeferral> SaveAsync(Actor actor, string companyCode, AccrualDeferral input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var saved = await SaveAsync(uow, input, actor.UserName, input.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, input.Id == 0 ? AuditAction.Insert : AuditAction.Update, saved.Id, null, saved, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return saved;
|
||||
}
|
||||
|
||||
/// <summary>Removes an accrual not posted yet.</summary>
|
||||
/// <param name="actor">Who removes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The accrual.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, 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<AccrualDeferral, long>();
|
||||
var accrual = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (accrual.GlEntryId is not null)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.AccrualPosted]);
|
||||
}
|
||||
|
||||
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, accrual, (AccrualDeferral?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Proposes the risconti of a year: the purchase invoices posted to the accounts of costs that usually straddle the
|
||||
/// year end (insurance, rents, leasing, software), as a period of a year from the date of the document; the user
|
||||
/// checks the period. A cost already proposed is not proposed again.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who proposes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The fiscal year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many were added.</returns>
|
||||
public async Task<int> ProposeAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IClosingRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var added = await ProposeAsync(uow, rules, year, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return added;
|
||||
}
|
||||
|
||||
/// <summary>The exchange differences of the open items in foreign currency at the end of a year.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The fiscal year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The differences.</returns>
|
||||
public async Task<IReadOnlyList<ExchangeDifferenceLine>> ExchangeDifferencesAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var fiscalYear = await YearAsync(uow, year, cancellationToken).ConfigureAwait(false);
|
||||
return await ExchangeDifferencesAsync(uow, fiscalYear.EndDate, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<FiscalYear> YearAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var code = year.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var last = new DateOnly(year, 12, 31);
|
||||
return await uow.Repository<FiscalYear, long>().FindAsync(Query.For<FiscalYear>().Where(y => y.Code == code), cancellationToken).ConfigureAwait(false)
|
||||
?? await uow.Repository<FiscalYear, long>().FindAsync(Query.For<FiscalYear>().Where(y => y.EndDate >= last && y.StartDate <= last), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
}
|
||||
|
||||
internal static async Task<IReadOnlyList<AccrualRow>> ListAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var accruals = (await uow.Repository<AccrualDeferral, long>().ListAsync(
|
||||
Query.For<AccrualDeferral>().Where(a => a.Year == year).OrderBy(a => a.Kind).OrderBy(a => a.PeriodStart).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var names = await JournalEntryService.PartyNamesAsync(uow, accruals.Select(a => a.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
return
|
||||
[
|
||||
.. accruals.Select(a => new AccrualRow(
|
||||
a,
|
||||
accounts.TryGetValue(a.AccountId, out var account) ? account.Code : string.Empty,
|
||||
account?.Description ?? string.Empty,
|
||||
a.PartyId is { } p && names.TryGetValue(p, out var name) ? name : null)),
|
||||
];
|
||||
}
|
||||
|
||||
internal static async Task<AccrualDeferral> SaveAsync(IUnitOfWork uow, AccrualDeferral input, string? userName, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
input.Description = (input.Description ?? string.Empty).Trim();
|
||||
if (input.Description.Length == 0)
|
||||
{
|
||||
errors.Add("Description:" + YearEndErrors.DescriptionRequired);
|
||||
}
|
||||
|
||||
var account = (await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false)).GetValueOrDefault(input.AccountId);
|
||||
var wanted = input.Kind is AccrualKind.AccruedIncome or AccrualKind.DeferredIncome ? AccountNature.Revenue : AccountNature.Cost;
|
||||
if (account is null || !account.Postable || account.Nature != wanted)
|
||||
{
|
||||
errors.Add("AccountId:" + YearEndErrors.AccountRequired);
|
||||
}
|
||||
|
||||
if (input.Amount <= 0m)
|
||||
{
|
||||
errors.Add("Amount:" + YearEndErrors.AmountRequired);
|
||||
}
|
||||
|
||||
if (input.PeriodEnd < input.PeriodStart)
|
||||
{
|
||||
errors.Add("PeriodEnd:" + YearEndErrors.PeriodOrder);
|
||||
}
|
||||
|
||||
var fiscalYear = await YearAsync(uow, input.Year, cancellationToken).ConfigureAwait(false);
|
||||
input.YearEnd = fiscalYear.EndDate;
|
||||
if (input.PeriodStart > input.YearEnd || input.PeriodEnd <= input.YearEnd)
|
||||
{
|
||||
// Only a period that straddles the year end has something to adjust.
|
||||
errors.Add("PeriodEnd:" + YearEndErrors.PeriodOutside);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
var repository = uow.Repository<AccrualDeferral, long>();
|
||||
input.Adjustment = AccrualDeferralCalculator.Share(input.Kind, input.Amount, input.PeriodStart, input.PeriodEnd, input.YearEnd);
|
||||
input.Description = LedgerStore.Trim(input.Description, 200)!;
|
||||
if (input.Id == 0)
|
||||
{
|
||||
input.IsDemo = isDemo;
|
||||
input.Id = await repository.InsertAsync(input, cancellationToken).ConfigureAwait(false);
|
||||
return input;
|
||||
}
|
||||
|
||||
var before = await repository.GetAsync(input.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (before.GlEntryId is not null)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.AccrualPosted]);
|
||||
}
|
||||
|
||||
input.RowVersion = before.RowVersion;
|
||||
input.IsDemo = before.IsDemo;
|
||||
input.SourceFamily = before.SourceFamily;
|
||||
input.SourceDocumentId = before.SourceDocumentId;
|
||||
_ = userName;
|
||||
await repository.UpdateAsync(input, cancellationToken).ConfigureAwait(false);
|
||||
return input;
|
||||
}
|
||||
|
||||
internal static async Task<int> ProposeAsync(IUnitOfWork uow, IClosingRules rules, int year, string? userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var fiscalYear = await YearAsync(uow, year, cancellationToken).ConfigureAwait(false);
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var candidates = rules.PrepaidCandidates.Where(accounts.ContainsKey).Select(c => accounts[c].Id).ToList();
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var from = fiscalYear.StartDate;
|
||||
var to = fiscalYear.EndDate;
|
||||
var draft = GlEntryStatus.Draft;
|
||||
var lines = (await uow.Repository<GlEntryLine, long>().ListAsync(
|
||||
Query.For<GlEntryLine>().Where(l => candidates.Contains(l.AccountId) && l.EntryDate >= from && l.EntryDate <= to && l.Status != draft && l.Debit > 0m),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var entryIds = lines.Select(l => l.EntryId).Distinct().ToList();
|
||||
var entries = (await uow.Repository<GlEntry, long>().ListAsync(Query.For<GlEntry>().Where(e => entryIds.Contains(e.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(e => e.Id);
|
||||
var existing = (await uow.Repository<AccrualDeferral, long>().ListAsync(Query.For<AccrualDeferral>().Where(a => a.Year == year), cancellationToken).ConfigureAwait(false))
|
||||
.Items.Where(a => a.SourceDocumentId is not null).Select(a => (a.SourceFamily, a.SourceDocumentId, a.AccountId)).ToHashSet();
|
||||
var added = 0;
|
||||
foreach (var line in lines.OrderBy(l => l.EntryDate).ThenBy(l => l.Id))
|
||||
{
|
||||
var entry = entries[line.EntryId];
|
||||
if (entry.Source is not GlEntrySource.Document || entry.SourceFamily is not DocumentFamily.PurchaseDocument || entry.ReversedById is not null
|
||||
|| !existing.Add((entry.SourceFamily, entry.SourceDocumentId, line.AccountId)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var start = entry.DocumentDate ?? entry.EntryDate;
|
||||
var end = start.AddYears(1).AddDays(-1);
|
||||
if (end <= to)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var accrual = new AccrualDeferral
|
||||
{
|
||||
Year = year,
|
||||
Kind = AccrualKind.PrepaidExpense,
|
||||
Description = LedgerStore.Trim(line.Description ?? entry.Description, 200)!,
|
||||
AccountId = line.AccountId,
|
||||
Amount = line.Debit,
|
||||
PeriodStart = start,
|
||||
PeriodEnd = end,
|
||||
SourceFamily = entry.SourceFamily,
|
||||
SourceDocumentId = entry.SourceDocumentId,
|
||||
DocumentNumber = entry.DocumentNumber,
|
||||
PartyId = entry.PartyId,
|
||||
};
|
||||
await SaveAsync(uow, accrual, userName, entry.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
added++;
|
||||
}
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
internal static async Task<IReadOnlyList<ExchangeDifferenceLine>> ExchangeDifferencesAsync(IUnitOfWork uow, DateOnly yearEnd, CancellationToken cancellationToken)
|
||||
{
|
||||
var items = (await uow.Repository<OpenItem, long>().ListAsync(
|
||||
Query.For<OpenItem>().Where(o => !o.Closed && o.DocumentDate <= yearEnd && o.SourceDocumentId != null), cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (items.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var currencies = new Dictionary<(DocumentFamily, long), (string Currency, decimal Rate)>();
|
||||
foreach (var group in items.Where(i => i.SourceFamily is DocumentFamily.SaleDocument or DocumentFamily.PurchaseDocument).GroupBy(i => i.SourceFamily!.Value))
|
||||
{
|
||||
var ids = group.Select(i => i.SourceDocumentId!.Value).Distinct().ToList();
|
||||
IEnumerable<DocumentHeader> headers = group.Key == DocumentFamily.SaleDocument
|
||||
? (await uow.Repository<SaleDocument, long>().ListAsync(Query.For<SaleDocument>().Where(d => ids.Contains(d.Id) && d.CurrencyCode != "EUR"), cancellationToken)
|
||||
.ConfigureAwait(false)).Items
|
||||
: (await uow.Repository<PurchaseDocument, long>().ListAsync(Query.For<PurchaseDocument>().Where(d => ids.Contains(d.Id) && d.CurrencyCode != "EUR"), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
foreach (var header in headers)
|
||||
{
|
||||
currencies[(group.Key, header.Id)] = (header.CurrencyCode, header.ExchangeRate);
|
||||
}
|
||||
}
|
||||
|
||||
if (currencies.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var rates = new Dictionary<string, decimal?>(StringComparer.Ordinal);
|
||||
foreach (var code in currencies.Values.Select(c => c.Currency).Distinct())
|
||||
{
|
||||
var rate = await uow.Repository<ExchangeRate, long>().FindAsync(
|
||||
Query.For<ExchangeRate>().Where(x => x.CurrencyCode == code && x.RateDate <= yearEnd).OrderByDescending(x => x.RateDate), cancellationToken).ConfigureAwait(false);
|
||||
rates[code] = rate?.Rate;
|
||||
}
|
||||
|
||||
var names = await JournalEntryService.PartyNamesAsync(uow, items.Select(i => (long?)i.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
var result = new List<ExchangeDifferenceLine>();
|
||||
foreach (var item in items.OrderBy(i => i.DocumentDate).ThenBy(i => i.Id))
|
||||
{
|
||||
if (item.Residual == 0m || !currencies.TryGetValue((item.SourceFamily!.Value, item.SourceDocumentId!.Value), out var currency))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var yearEndRate = rates[currency.Currency];
|
||||
var difference = yearEndRate is { } r ? ExchangeDifferenceCalculator.Difference(item.Residual, currency.Rate, r) : 0m;
|
||||
result.Add(new ExchangeDifferenceLine(
|
||||
item.Id, item.Direction, item.PartyId, names.TryGetValue(item.PartyId, out var name) ? name : null, item.AccountId, item.DocumentNumber, item.DocumentDate,
|
||||
currency.Currency, currency.Rate, yearEndRate, item.Residual, ExchangeDifferenceCalculator.InCurrency(item.Residual, currency.Rate), difference));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Step 3 of the closing: posts the accruals and the exchange differences of the year.</summary>
|
||||
/// <returns>The entries written and the amount adjusted.</returns>
|
||||
internal static async Task<(int Entries, decimal Amount, List<string> Messages)> PostAsync(
|
||||
IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear fiscalYear, int step, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var year = fiscalYear.EndDate.Year;
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var messages = new List<string>();
|
||||
var entries = 0;
|
||||
var amount = 0m;
|
||||
var repository = uow.Repository<AccrualDeferral, long>();
|
||||
var accruals = (await repository.ListAsync(Query.For<AccrualDeferral>().Where(a => a.Year == year && a.GlEntryId == null), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Where(a => a.Adjustment != 0m).ToList();
|
||||
if (accruals.Count > 0)
|
||||
{
|
||||
var lines = new List<EntryLineDraft>();
|
||||
foreach (var accrual in accruals)
|
||||
{
|
||||
var text = accrual.Description;
|
||||
switch (accrual.Kind)
|
||||
{
|
||||
case AccrualKind.AccruedIncome:
|
||||
lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.AccruedIncome).Id, accrual.Adjustment, text));
|
||||
lines.Add(YearEndLedger.Credit(accrual.AccountId, accrual.Adjustment, text));
|
||||
break;
|
||||
case AccrualKind.AccruedExpense:
|
||||
lines.Add(YearEndLedger.Debit(accrual.AccountId, accrual.Adjustment, text));
|
||||
lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.AccruedExpenses).Id, accrual.Adjustment, text));
|
||||
break;
|
||||
case AccrualKind.PrepaidExpense:
|
||||
lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.PrepaidExpenses).Id, accrual.Adjustment, text));
|
||||
lines.Add(YearEndLedger.Credit(accrual.AccountId, accrual.Adjustment, text));
|
||||
break;
|
||||
default:
|
||||
lines.Add(YearEndLedger.Debit(accrual.AccountId, accrual.Adjustment, text));
|
||||
lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.DeferredIncome).Id, accrual.Adjustment, text));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var entry = await YearEndLedger.PostAsync(uow, fiscalYear.EndDate, "Ratei e risconti " + fiscalYear.Code, GlEntrySource.Accrual, step, lines, isDemo, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
foreach (var accrual in accruals)
|
||||
{
|
||||
accrual.GlEntryId = entry!.Id;
|
||||
await repository.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
entries++;
|
||||
amount += accruals.Sum(a => a.Adjustment);
|
||||
messages.Add("closing.accruals-posted|" + accruals.Count);
|
||||
}
|
||||
|
||||
var differences = (await ExchangeDifferencesAsync(uow, fiscalYear.EndDate, cancellationToken).ConfigureAwait(false)).ToList();
|
||||
foreach (var missing in differences.Where(d => d.YearEndRate is null).Select(d => d.CurrencyCode).Distinct())
|
||||
{
|
||||
messages.Add("!closing.rate-missing|" + missing);
|
||||
}
|
||||
|
||||
var useful = differences.Where(d => d.Difference != 0m).ToList();
|
||||
if (useful.Count > 0)
|
||||
{
|
||||
var gains = YearEndLedger.Require(accounts, codes.ExchangeGains).Id;
|
||||
var losses = YearEndLedger.Require(accounts, codes.ExchangeLosses).Id;
|
||||
var lines = new List<EntryLineDraft>();
|
||||
foreach (var d in useful)
|
||||
{
|
||||
var text = "Differenza cambio " + d.CurrencyCode + " " + d.DocumentNumber;
|
||||
|
||||
// A receivable grows with a positive difference; a payable grows with it as well, on the other side.
|
||||
var control = d.Direction == OpenItemDirection.Receivable
|
||||
? YearEndLedger.Debit(d.AccountId, d.Difference, text, d.PartyId)
|
||||
: YearEndLedger.Credit(d.AccountId, d.Difference, text, d.PartyId);
|
||||
lines.Add(control);
|
||||
var abs = Math.Abs(d.Difference);
|
||||
lines.Add(d.Gain ? YearEndLedger.Credit(gains, abs, text) : YearEndLedger.Debit(losses, abs, text));
|
||||
}
|
||||
|
||||
await YearEndLedger.PostAsync(uow, fiscalYear.EndDate, "Differenze cambio " + fiscalYear.Code, GlEntrySource.ExchangeDifference, step, lines, isDemo, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
entries++;
|
||||
amount += useful.Sum(d => d.Gain ? Math.Abs(d.Difference) : -Math.Abs(d.Difference));
|
||||
messages.Add("closing.exchange-posted|" + useful.Count);
|
||||
}
|
||||
|
||||
if (entries == 0)
|
||||
{
|
||||
messages.Add("closing.nothing-to-post");
|
||||
}
|
||||
|
||||
return (entries, amount, messages);
|
||||
}
|
||||
|
||||
/// <summary>Undoes step 3: the accruals go back to not posted.</summary>
|
||||
internal static async Task UnpostAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<AccrualDeferral, long>();
|
||||
foreach (var accrual in (await repository.ListAsync(Query.For<AccrualDeferral>().Where(a => a.Year == year && a.GlEntryId != null), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
accrual.GlEntryId = null;
|
||||
accrual.ReversalEntryId = null;
|
||||
await repository.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,963 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Inventory;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>A final print of a closing, without its content.</summary>
|
||||
/// <param name="Id">The print.</param>
|
||||
/// <param name="Kind">What it is.</param>
|
||||
/// <param name="FileName">The file name.</param>
|
||||
/// <param name="Pages">The pages.</param>
|
||||
public sealed record ClosingPrintInfo(long Id, string Kind, string FileName, int Pages);
|
||||
|
||||
/// <summary>The guided closing of a year as the screen shows it (mockup 050).</summary>
|
||||
/// <param name="Year">The year.</param>
|
||||
/// <param name="Run">The closing, once started.</param>
|
||||
/// <param name="Steps">The nine steps (pending ones too).</param>
|
||||
/// <param name="Prints">The final prints.</param>
|
||||
/// <param name="Years">The years of the company, for the choice.</param>
|
||||
public sealed record ClosingView(FiscalYear Year, ClosingRun? Run, IReadOnlyList<ClosingStep> Steps, IReadOnlyList<ClosingPrintInfo> Prints, IReadOnlyList<FiscalYear> Years)
|
||||
{
|
||||
/// <summary>The next step to run, if any.</summary>
|
||||
public int? NextStep => Steps.FirstOrDefault(s => s.Status == ClosingStepStatus.Pending)?.Number;
|
||||
|
||||
/// <summary>The last step run, which can be repeated or undone.</summary>
|
||||
public int? LastDone => Steps.LastOrDefault(s => s.Status != ClosingStepStatus.Pending)?.Number;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The guided closing of a fiscal year (SPEC §11.7, issue #85, mockup 050, ADR 0043), in nine steps run in order:
|
||||
/// <list type="number">
|
||||
/// <item>checks (drafts, balance, accounts without a line of the statements, year not ended);</item>
|
||||
/// <item>depreciation of the fixed assets;</item>
|
||||
/// <item>accruals, deferrals and exchange differences;</item>
|
||||
/// <item>inventory: the opening stock to costs, the closing stock at weighted average cost;</item>
|
||||
/// <item>provisions: write-down of receivables and severance pay;</item>
|
||||
/// <item>closing of the income accounts and the result to equity (the year goes to <c>Closing</c>);</item>
|
||||
/// <item>closing of the balance-sheet accounts, by customer and supplier;</item>
|
||||
/// <item>the next year with its opening entry and the reversal of the accruals;</item>
|
||||
/// <item>the entries made final and the final prints.</item>
|
||||
/// </list>
|
||||
/// The last step run can be repeated or undone while its entries are not final; once every step is done the year is
|
||||
/// locked and becomes read only.
|
||||
/// </summary>
|
||||
public sealed class ClosingService
|
||||
{
|
||||
/// <summary>The number of steps.</summary>
|
||||
public const int StepCount = 9;
|
||||
|
||||
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly FiscalYearService _fiscal;
|
||||
private readonly LedgerQueryService _queries;
|
||||
private readonly VatService _vat;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
/// <param name="fiscal">The calendar.</param>
|
||||
/// <param name="queries">The prints of the journal.</param>
|
||||
/// <param name="vat">The prints of the VAT registers.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public ClosingService(
|
||||
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, FiscalYearService fiscal, LedgerQueryService queries, VatService vat,
|
||||
AuditTrail audit, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(fiscal);
|
||||
ArgumentNullException.ThrowIfNull(queries);
|
||||
ArgumentNullException.ThrowIfNull(vat);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
_fiscal = fiscal;
|
||||
_queries = queries;
|
||||
_vat = vat;
|
||||
_audit = audit;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The closing of a year: the first year not closed when none is given.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="fiscalYearId">The year, or none.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The closing.</returns>
|
||||
public async Task<ClosingView> GetAsync(Actor actor, string companyCode, long? fiscalYearId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ViewAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Runs a step (or runs again the last one run).</summary>
|
||||
/// <param name="actor">Who runs.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="fiscalYearId">The year.</param>
|
||||
/// <param name="number">The step, 1-9.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The closing.</returns>
|
||||
public async Task<ClosingView> RunStepAsync(Actor actor, string companyCode, long fiscalYearId, int number, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
if (number == StepCount)
|
||||
{
|
||||
await RunFinalStepAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await RunStepAsync(uow, pack, fiscalYearId, number, actor.UserName, _clock.GetUtcNow(), cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return await GetAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Undoes the last step run: its entries are removed (refused once final).</summary>
|
||||
/// <param name="actor">Who undoes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="fiscalYearId">The year.</param>
|
||||
/// <param name="number">The step.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The closing.</returns>
|
||||
public async Task<ClosingView> UndoStepAsync(Actor actor, string companyCode, long fiscalYearId, int number, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await UndoStepAsync(uow, fiscalYearId, number, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return await GetAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Locks the year once every step is done: it becomes read only.</summary>
|
||||
/// <param name="actor">Who locks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="fiscalYearId">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The closing.</returns>
|
||||
public async Task<ClosingView> LockAsync(Actor actor, string companyCode, long fiscalYearId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var (year, run, steps) = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
if (run is null || steps.Any(s => s.Status is ClosingStepStatus.Pending or ClosingStepStatus.Failed))
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.StepsPending]);
|
||||
}
|
||||
|
||||
if (run.Status == ClosingStatus.Locked)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]);
|
||||
}
|
||||
|
||||
var before = Copy(year);
|
||||
run.Status = ClosingStatus.Locked;
|
||||
run.LockedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
run.LockedBy = actor.UserName;
|
||||
await uow.Repository<ClosingRun, long>().UpdateAsync(run, cancellationToken).ConfigureAwait(false);
|
||||
year.Status = FiscalYearStatus.Closed;
|
||||
await uow.Repository<FiscalYear, long>().UpdateAsync(year, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, year.Id, before, year, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
return await GetAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A final print of a closing.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="printId">The print.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The PDF.</returns>
|
||||
public async Task<LedgerFile> PrintAsync(Actor actor, string companyCode, long printId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var print = await uow.Repository<ClosingPrint, long>().GetAsync(printId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
return new LedgerFile(print.FileName, Infrastructure.Files.PdfWriter.MediaType, print.Content);
|
||||
}
|
||||
|
||||
internal static async Task<ClosingView> ViewAsync(IUnitOfWork uow, long? fiscalYearId, CancellationToken cancellationToken)
|
||||
{
|
||||
var years = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>().OrderBy(y => y.StartDate), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var year = fiscalYearId is { } id
|
||||
? years.FirstOrDefault(y => y.Id == id) ?? throw new KeyNotFoundException(YearEndErrors.NotFound)
|
||||
: years.FirstOrDefault(y => y.Status != FiscalYearStatus.Closed) ?? (years.Count > 0 ? years[^1] : null) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
var (_, run, steps) = await LoadAsync(uow, year.Id, cancellationToken).ConfigureAwait(false);
|
||||
var prints = new List<ClosingPrintInfo>();
|
||||
if (run is not null)
|
||||
{
|
||||
var runId = run.Id;
|
||||
var rows = await uow.QueryAsync<PrintRow>(SqlFragment.Of($"SELECT id AS id, kind AS kind, file_name AS file_name, pages AS pages FROM closing_prints WHERE run_id = {runId} ORDER BY id"), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
prints.AddRange(rows.Select(r => new ClosingPrintInfo(r.Id, r.Kind, r.FileName, r.Pages)));
|
||||
}
|
||||
|
||||
return new ClosingView(year, run, steps, prints, years);
|
||||
}
|
||||
|
||||
internal static async Task RunStepAsync(IUnitOfWork uow, IFiscalPack pack, long fiscalYearId, int number, string? userName, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
if (number < 1 || number >= StepCount)
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.StepOrder]);
|
||||
}
|
||||
|
||||
var (year, run, steps) = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
run ??= await StartAsync(uow, year, cancellationToken).ConfigureAwait(false);
|
||||
steps = await StepsAsync(uow, run.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (run.Status == ClosingStatus.Locked)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]);
|
||||
}
|
||||
|
||||
var step = steps[number - 1];
|
||||
if (steps.Skip(number).Any(s => s.Status != ClosingStepStatus.Pending))
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.LaterStepDone]);
|
||||
}
|
||||
|
||||
if (steps.Take(number - 1).Any(s => s.Status == ClosingStepStatus.Pending))
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.StepOrder]);
|
||||
}
|
||||
|
||||
if (number > 1 && steps[0].Status == ClosingStepStatus.Failed)
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.ChecksFailed]);
|
||||
}
|
||||
|
||||
if (step.Status != ClosingStepStatus.Pending)
|
||||
{
|
||||
// Running a step again: what it wrote goes first.
|
||||
await UndoAsync(uow, year, run, step, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var isDemo = await IsDemoAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var codes = pack.Require<IClosingRules>().Accounts;
|
||||
var result = number switch
|
||||
{
|
||||
1 => await ChecksAsync(uow, pack, year, now, cancellationToken).ConfigureAwait(false),
|
||||
2 => await DepreciationAsync(uow, pack, year, userName, cancellationToken).ConfigureAwait(false),
|
||||
3 => await AccrualsAsync(uow, codes, year, isDemo, cancellationToken).ConfigureAwait(false),
|
||||
4 => await InventoryAsync(uow, codes, year, isDemo, cancellationToken).ConfigureAwait(false),
|
||||
5 => await ProvisionsAsync(uow, pack.Require<IClosingRules>(), year, isDemo, cancellationToken).ConfigureAwait(false),
|
||||
6 => await CloseIncomeAsync(uow, codes, year, run, isDemo, cancellationToken).ConfigureAwait(false),
|
||||
7 => await CloseBalanceSheetAsync(uow, codes, year, isDemo, cancellationToken).ConfigureAwait(false),
|
||||
_ => await OpenNextYearAsync(uow, codes, year, run, userName, isDemo, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
step.Status = result.Status;
|
||||
step.Entries = result.Entries;
|
||||
step.Amount = result.Amount;
|
||||
step.Messages = result.Messages.Count == 0 ? null : string.Join('\n', result.Messages);
|
||||
step.ExecutedAt = now.UtcDateTime;
|
||||
step.ExecutedBy = userName;
|
||||
await uow.Repository<ClosingStep, long>().UpdateAsync(step, cancellationToken).ConfigureAwait(false);
|
||||
if (number == 6)
|
||||
{
|
||||
year.Status = FiscalYearStatus.Closing;
|
||||
await uow.Repository<FiscalYear, long>().UpdateAsync(year, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.Repository<ClosingRun, long>().UpdateAsync(run, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task UndoStepAsync(IUnitOfWork uow, long fiscalYearId, int number, CancellationToken cancellationToken)
|
||||
{
|
||||
var (year, run, steps) = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
if (run is null)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.NoClosing]);
|
||||
}
|
||||
|
||||
if (run.Status == ClosingStatus.Locked)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]);
|
||||
}
|
||||
|
||||
if (number == StepCount)
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.StepIrreversible]);
|
||||
}
|
||||
|
||||
var step = steps.FirstOrDefault(s => s.Number == number) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (steps.Skip(number).Any(s => s.Status != ClosingStepStatus.Pending))
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.LaterStepDone]);
|
||||
}
|
||||
|
||||
if (step.Status == ClosingStepStatus.Pending)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await UndoAsync(uow, year, run, step, cancellationToken).ConfigureAwait(false);
|
||||
step.Status = ClosingStepStatus.Pending;
|
||||
step.Entries = 0;
|
||||
step.Amount = 0m;
|
||||
step.Messages = null;
|
||||
step.ExecutedAt = null;
|
||||
step.ExecutedBy = null;
|
||||
await uow.Repository<ClosingStep, long>().UpdateAsync(step, cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<ClosingRun, long>().UpdateAsync(run, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task UndoAsync(IUnitOfWork uow, FiscalYear year, ClosingRun run, ClosingStep step, CancellationToken cancellationToken)
|
||||
{
|
||||
switch (step.Number)
|
||||
{
|
||||
case 2:
|
||||
await FixedAssetService.UndoDepreciationAsync(uow, year.EndDate.Year, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case 3:
|
||||
// The accruals point to their entries: they let go first.
|
||||
await AccrualService.UnpostAsync(uow, year.EndDate.Year, cancellationToken).ConfigureAwait(false);
|
||||
await DeleteStepEntriesAsync(uow, year, 3, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case 6:
|
||||
await DeleteStepEntriesAsync(uow, year, 6, cancellationToken).ConfigureAwait(false);
|
||||
run.Result = 0m;
|
||||
year.Status = FiscalYearStatus.Open;
|
||||
await uow.Repository<FiscalYear, long>().UpdateAsync(year, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case 8:
|
||||
await UndoNextYearAsync(uow, year, run, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
await DeleteStepEntriesAsync(uow, year, step.Number, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DeleteStepEntriesAsync(IUnitOfWork uow, FiscalYear year, int number, CancellationToken cancellationToken)
|
||||
{
|
||||
var from = year.StartDate;
|
||||
var to = year.EndDate;
|
||||
var step = (int?)number;
|
||||
var ids = (await uow.Repository<GlEntry, long>().ListAsync(
|
||||
Query.For<GlEntry>().Where(e => e.ClosingStep == step && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items.Select(e => e.Id);
|
||||
await YearEndLedger.DeleteAsync(uow, ids, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task RunFinalStepAsync(Actor actor, string company, long fiscalYearId, CancellationToken cancellationToken)
|
||||
{
|
||||
FiscalYear year;
|
||||
ClosingRun run;
|
||||
var finalized = 0;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var loaded = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false);
|
||||
year = loaded.Year;
|
||||
run = loaded.Run ?? throw new ValidationFailedException(["Id:" + YearEndErrors.NoClosing]);
|
||||
if (run.Status == ClosingStatus.Locked)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]);
|
||||
}
|
||||
|
||||
if (loaded.Steps.Take(StepCount - 1).Any(s => s.Status is ClosingStepStatus.Pending or ClosingStepStatus.Failed))
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.StepOrder]);
|
||||
}
|
||||
|
||||
if (loaded.Steps[StepCount - 1].Status != ClosingStepStatus.Pending)
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.StepIrreversible]);
|
||||
}
|
||||
|
||||
finalized = await FinalizeAsync(uow, year.EndDate, actor.UserName, _clock.GetUtcNow().UtcDateTime, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The prints read what was committed: a failure here leaves the step to run again, the entries already final.
|
||||
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var prints = new List<ClosingPrint>();
|
||||
var journal = await _queries.PrintJournalAsync(actor, company, year.StartDate, year.EndDate, true, cancellationToken).ConfigureAwait(false);
|
||||
prints.Add(new ClosingPrint { Kind = "journal", FileName = journal.FileName, Content = journal.Content });
|
||||
var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFinancialStatementsSchema>();
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>().OrderBy(r => r.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var register in registers)
|
||||
{
|
||||
var file = await _vat.PrintRegisterAsync(actor, company, register.Id, year.StartDate, year.EndDate, false, cancellationToken).ConfigureAwait(false);
|
||||
prints.Add(new ClosingPrint { Kind = "vat-" + register.Code, FileName = file.FileName, Content = file.Content });
|
||||
}
|
||||
|
||||
var (assets, assetPages) = await FixedAssetService.PrintRegisterAsync(uow, year.EndDate.Year, 1, cancellationToken).ConfigureAwait(false);
|
||||
prints.Add(new ClosingPrint { Kind = "assets", FileName = assets.FileName, Content = assets.Content, Pages = assetPages });
|
||||
var (statements, statementPages) = await FinancialStatementsService.PrintAsync(uow, schema, year.EndDate.Year, FinancialStatementForm.Ordinary, 1, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
prints.Add(new ClosingPrint
|
||||
{
|
||||
Kind = "statements",
|
||||
FileName = string.Create(Invariant, $"bilancio-{year.Code.Replace('/', '-')}.pdf"),
|
||||
Content = statements,
|
||||
Pages = statementPages,
|
||||
});
|
||||
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var runId = run.Id;
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM closing_prints WHERE run_id = {runId}"), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var print in prints)
|
||||
{
|
||||
print.RunId = run.Id;
|
||||
print.Pages = print.Pages == 0 ? Pages(print.Content) : print.Pages;
|
||||
await uow.Repository<ClosingPrint, long>().InsertAsync(print, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var step = (await StepsAsync(uow, run.Id, cancellationToken).ConfigureAwait(false))[StepCount - 1];
|
||||
step.Status = ClosingStepStatus.Done;
|
||||
step.Entries = finalized;
|
||||
step.Amount = 0m;
|
||||
step.Messages = "closing.finalized|" + finalized.ToString(Invariant) + "\nclosing.prints|" + prints.Count.ToString(Invariant);
|
||||
step.ExecutedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
step.ExecutedBy = actor.UserName;
|
||||
await uow.Repository<ClosingStep, long>().UpdateAsync(step, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Makes final the posted entries up to a day, numbering them in the journal of their year.</summary>
|
||||
internal static async Task<int> FinalizeAsync(IUnitOfWork uow, DateOnly upTo, string? userName, DateTime now, CancellationToken cancellationToken)
|
||||
{
|
||||
var draft = GlEntryStatus.Draft;
|
||||
if (await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.Status == draft && e.EntryDate <= upTo), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["UpTo:" + LedgerErrors.DraftsBeforeFinal]);
|
||||
}
|
||||
|
||||
var posted = GlEntryStatus.Posted;
|
||||
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
|
||||
Query.For<GlEntry>().Where(e => e.Status == posted && e.EntryDate <= upTo).OrderBy(e => e.EntryDate).OrderBy(e => e.Number).OrderBy(e => e.Id),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var years = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
var year = years.FirstOrDefault(y => y.StartDate <= entry.EntryDate && y.EndDate >= entry.EntryDate)
|
||||
?? throw new ValidationFailedException(["UpTo:" + LedgerErrors.NoFiscalYear]);
|
||||
year.LastFinalEntryNumber++;
|
||||
year.LastFinalEntryDate = entry.EntryDate;
|
||||
entry.JournalNumber = year.LastFinalEntryNumber;
|
||||
entry.FinalizedAt = now;
|
||||
entry.FinalizedBy = userName;
|
||||
await LedgerStore.SetStatusAsync(uow, entry, GlEntryStatus.Final, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var year in years.Where(y => entries.Any(e => y.StartDate <= e.EntryDate && y.EndDate >= e.EntryDate)))
|
||||
{
|
||||
await uow.Repository<FiscalYear, long>().UpdateAsync(year, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return entries.Count;
|
||||
}
|
||||
|
||||
private static async Task<StepResult> ChecksAsync(IUnitOfWork uow, IFiscalPack pack, FiscalYear year, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var warnings = new List<string>();
|
||||
var from = year.StartDate;
|
||||
var to = year.EndDate;
|
||||
var draft = GlEntryStatus.Draft;
|
||||
var drafts = await uow.Repository<GlEntry, long>().CountAsync(
|
||||
Query.For<GlEntry>().Where(e => e.Status == draft && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false);
|
||||
if (drafts > 0)
|
||||
{
|
||||
errors.Add("-closing.check-drafts|" + drafts.ToString(Invariant));
|
||||
}
|
||||
|
||||
var unbalanced = (await uow.Repository<GlEntry, long>().ListAsync(
|
||||
Query.For<GlEntry>().Where(e => e.Status != draft && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items.Count(e => !e.Balanced);
|
||||
if (unbalanced > 0)
|
||||
{
|
||||
errors.Add("-closing.check-unbalanced|" + unbalanced.ToString(Invariant));
|
||||
}
|
||||
|
||||
var balance = await LedgerQueryService.TrialBalanceAsync(uow, from, to, null, false, cancellationToken).ConfigureAwait(false);
|
||||
if (balance.TotalDebit != balance.TotalCredit)
|
||||
{
|
||||
errors.Add("-closing.check-trial-balance|" + LedgerReport.Money(balance.TotalDebit - balance.TotalCredit));
|
||||
}
|
||||
|
||||
if (pack.GetFeature<IFinancialStatementsSchema>() is { } schema)
|
||||
{
|
||||
var raw = await FinancialStatementsService.RawAsync(uow, schema, to.Year, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var account in raw.Unmapped)
|
||||
{
|
||||
warnings.Add("!closing.check-unmapped|" + account.Code + "|" + LedgerReport.Money(account.Balance));
|
||||
}
|
||||
}
|
||||
|
||||
if (DateOnly.FromDateTime(now.UtcDateTime) <= to)
|
||||
{
|
||||
warnings.Add("!closing.check-year-not-ended|" + LedgerReport.Date(to));
|
||||
}
|
||||
|
||||
var earlier = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>().Where(y => y.EndDate < from), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Where(y => y.Status != FiscalYearStatus.Closed).ToList();
|
||||
foreach (var open in earlier)
|
||||
{
|
||||
warnings.Add("!closing.check-previous-open|" + open.Code);
|
||||
}
|
||||
|
||||
var messages = errors.Concat(warnings).ToList();
|
||||
if (messages.Count == 0)
|
||||
{
|
||||
messages.Add("closing.check-ok");
|
||||
}
|
||||
|
||||
var status = errors.Count > 0 ? ClosingStepStatus.Failed : warnings.Count > 0 ? ClosingStepStatus.ToVerify : ClosingStepStatus.Passed;
|
||||
return new StepResult(status, 0, balance.Result, messages);
|
||||
}
|
||||
|
||||
private static async Task<StepResult> DepreciationAsync(IUnitOfWork uow, IFiscalPack pack, FiscalYear year, string? userName, CancellationToken cancellationToken)
|
||||
{
|
||||
if (pack.GetFeature<IFixedAssetRules>() is not { } rules)
|
||||
{
|
||||
return new StepResult(ClosingStepStatus.Done, 0, 0m, ["closing.nothing-to-post"]);
|
||||
}
|
||||
|
||||
var (amount, entry) = await FixedAssetService.DepreciateAsync(uow, rules, year.EndDate.Year, year.EndDate, 2, userName, cancellationToken).ConfigureAwait(false);
|
||||
return entry is null
|
||||
? new StepResult(ClosingStepStatus.Done, 0, 0m, ["closing.depreciation-none"])
|
||||
: new StepResult(ClosingStepStatus.Done, 1, amount, ["closing.depreciation-posted|" + LedgerReport.Money(amount)]);
|
||||
}
|
||||
|
||||
private static async Task<StepResult> AccrualsAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var (entries, amount, messages) = await AccrualService.PostAsync(uow, codes, year, 3, isDemo, cancellationToken).ConfigureAwait(false);
|
||||
return new StepResult(messages.Any(m => m.StartsWith('!')) ? ClosingStepStatus.ToVerify : ClosingStepStatus.Done, entries, amount, messages);
|
||||
}
|
||||
|
||||
private static async Task<StepResult> InventoryAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var inventory = YearEndLedger.Require(accounts, codes.Inventory);
|
||||
var opening = YearEndLedger.Require(accounts, codes.OpeningInventory);
|
||||
var closing = YearEndLedger.Require(accounts, codes.ClosingInventory);
|
||||
var current = await BalanceAsync(uow, inventory.Id, year.EndDate, cancellationToken).ConfigureAwait(false);
|
||||
var rows = await InventoryService.ValuationAsync(uow, year.EndDate, null, StockValuationMethod.WeightedAverage, cancellationToken).ConfigureAwait(false);
|
||||
var value = Math.Round(rows.Sum(r => r.Value), 2, MidpointRounding.AwayFromZero);
|
||||
var lines = new List<EntryLineDraft>
|
||||
{
|
||||
YearEndLedger.Debit(opening.Id, current, "Storno rimanenze iniziali"),
|
||||
YearEndLedger.Credit(inventory.Id, current, "Storno rimanenze iniziali"),
|
||||
YearEndLedger.Debit(inventory.Id, value, "Rimanenze finali al costo medio ponderato"),
|
||||
YearEndLedger.Credit(closing.Id, value, "Rimanenze finali al costo medio ponderato"),
|
||||
};
|
||||
var entry = await YearEndLedger.PostAsync(uow, year.EndDate, "Rimanenze di magazzino " + year.Code, GlEntrySource.Closing, 4, lines, isDemo, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var messages = new List<string>
|
||||
{
|
||||
"closing.inventory-opening|" + LedgerReport.Money(current),
|
||||
"closing.inventory-closing|" + LedgerReport.Money(value) + "|" + rows.Count.ToString(Invariant),
|
||||
};
|
||||
return new StepResult(ClosingStepStatus.Done, entry is null ? 0 : 1, value, messages);
|
||||
}
|
||||
|
||||
private static async Task<StepResult> ProvisionsAsync(IUnitOfWork uow, IClosingRules rules, FiscalYear year, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var codes = rules.Accounts;
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var messages = new List<string>();
|
||||
var lines = new List<EntryLineDraft>();
|
||||
var end = year.EndDate;
|
||||
var receivable = OpenItemDirection.Receivable;
|
||||
var receivables = (await uow.Repository<OpenItem, long>().ListAsync(
|
||||
Query.For<OpenItem>().Where(o => o.Direction == receivable && !o.Closed && o.DocumentDate <= end), cancellationToken).ConfigureAwait(false)).Items.Sum(o => o.Residual);
|
||||
var badDebt = Math.Round(Math.Max(0m, receivables) * rules.BadDebtPercent / 100m, 2, MidpointRounding.AwayFromZero);
|
||||
if (badDebt > 0m)
|
||||
{
|
||||
var text = "Svalutazione crediti " + rules.BadDebtPercent.ToString("0.##", Invariant) + "%";
|
||||
lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.BadDebtCharge).Id, badDebt, text));
|
||||
lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.BadDebtFund).Id, badDebt, text));
|
||||
messages.Add("closing.bad-debt|" + LedgerReport.Money(badDebt) + "|" + LedgerReport.Money(receivables));
|
||||
}
|
||||
|
||||
// Severance pay of the year: the wages divided by 13.5 (art. 2120 c.c.), less what the payroll already set aside.
|
||||
var severance = YearEndLedger.Require(accounts, codes.SeveranceCharge);
|
||||
var wages = 0m;
|
||||
foreach (var account in accounts.Values.Where(a => a.Postable && a.Nature == AccountNature.Cost && a.StatementLine == "B.9.a"))
|
||||
{
|
||||
wages += await BalanceAsync(uow, account.Id, end, cancellationToken, year.StartDate).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var booked = await BalanceAsync(uow, severance.Id, end, cancellationToken, year.StartDate).ConfigureAwait(false);
|
||||
var due = Math.Round(wages / 13.5m, 2, MidpointRounding.AwayFromZero) - booked;
|
||||
if (due > 0m)
|
||||
{
|
||||
lines.Add(YearEndLedger.Debit(severance.Id, due, "Accantonamento TFR"));
|
||||
lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.SeveranceFund).Id, due, "Accantonamento TFR"));
|
||||
messages.Add("!closing.severance|" + LedgerReport.Money(due) + "|" + LedgerReport.Money(wages));
|
||||
}
|
||||
|
||||
var entry = await YearEndLedger.PostAsync(uow, end, "Accantonamenti " + year.Code, GlEntrySource.Closing, 5, lines, isDemo, cancellationToken).ConfigureAwait(false);
|
||||
if (entry is null)
|
||||
{
|
||||
messages.Add("closing.nothing-to-post");
|
||||
}
|
||||
|
||||
return new StepResult(messages.Any(m => m.StartsWith('!')) ? ClosingStepStatus.ToVerify : ClosingStepStatus.Done, entry is null ? 0 : 1, badDebt + Math.Max(0m, due), messages);
|
||||
}
|
||||
|
||||
private static async Task<StepResult> CloseIncomeAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, ClosingRun run, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var summary = YearEndLedger.Require(accounts, codes.IncomeSummary);
|
||||
var resultAccount = YearEndLedger.Require(accounts, codes.Result);
|
||||
var balances = await BalancesAsync(uow, year.StartDate, year.EndDate, byParty: false, cancellationToken).ConfigureAwait(false);
|
||||
var byId = accounts.Values.ToDictionary(a => a.Id);
|
||||
var lines = new List<EntryLineDraft>();
|
||||
var result = 0m;
|
||||
foreach (var (accountId, _, amount) in balances.OrderBy(b => byId[b.AccountId].Code, StringComparer.Ordinal))
|
||||
{
|
||||
var account = byId[accountId];
|
||||
if (account.Nature is not (AccountNature.Cost or AccountNature.Revenue) || amount == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The balance goes to the income summary: a cost (debit) is credited, a revenue debited.
|
||||
lines.Add(YearEndLedger.Credit(accountId, amount, account.Description));
|
||||
lines.Add(YearEndLedger.Debit(summary.Id, amount, account.Description));
|
||||
result -= amount;
|
||||
}
|
||||
|
||||
var entries = 0;
|
||||
if (await YearEndLedger.PostAsync(uow, year.EndDate, "Chiusura conti economici " + year.Code, GlEntrySource.Closing, 6, Merge(lines, summary.Id), isDemo, cancellationToken)
|
||||
.ConfigureAwait(false) is not null)
|
||||
{
|
||||
entries++;
|
||||
}
|
||||
|
||||
// A profit (revenues above costs) leaves the summary in credit and goes to equity in credit; a loss in debit.
|
||||
var text = result >= 0m ? "Utile dell'esercizio" : "Perdita dell'esercizio";
|
||||
if (await YearEndLedger.PostAsync(
|
||||
uow, year.EndDate, text + " " + year.Code, GlEntrySource.Closing, 6,
|
||||
[YearEndLedger.Debit(summary.Id, result, text), YearEndLedger.Credit(resultAccount.Id, result, text)], isDemo, cancellationToken).ConfigureAwait(false) is not null)
|
||||
{
|
||||
entries++;
|
||||
}
|
||||
|
||||
run.Result = result;
|
||||
return new StepResult(ClosingStepStatus.Done, entries, result, [(result >= 0m ? "closing.profit|" : "closing.loss|") + LedgerReport.Money(Math.Abs(result))]);
|
||||
}
|
||||
|
||||
private static async Task<StepResult> CloseBalanceSheetAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var closingBalance = YearEndLedger.Require(accounts, codes.ClosingBalance);
|
||||
var lines = await BalanceSheetLinesAsync(uow, accounts, year, cancellationToken).ConfigureAwait(false);
|
||||
var drafts = new List<EntryLineDraft>();
|
||||
foreach (var (accountId, partyId, amount) in lines)
|
||||
{
|
||||
drafts.Add(YearEndLedger.Credit(accountId, amount, null, partyId));
|
||||
}
|
||||
|
||||
var debit = lines.Where(l => l.Amount > 0m).Sum(l => l.Amount);
|
||||
var credit = -lines.Where(l => l.Amount < 0m).Sum(l => l.Amount);
|
||||
if (debit != credit)
|
||||
{
|
||||
throw new ValidationFailedException(["Number:" + YearEndErrors.ClosingUnbalanced + ":" + LedgerReport.Money(debit - credit)]);
|
||||
}
|
||||
|
||||
drafts.Add(YearEndLedger.Debit(closingBalance.Id, debit, "Attività"));
|
||||
drafts.Add(YearEndLedger.Credit(closingBalance.Id, credit, "Passività e patrimonio netto"));
|
||||
var entry = await YearEndLedger.PostAsync(uow, year.EndDate, "Stato patrimoniale finale " + year.Code, GlEntrySource.Closing, 7, drafts, isDemo, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new StepResult(ClosingStepStatus.Done, entry is null ? 0 : 1, debit, ["closing.balance-closed|" + lines.Count.ToString(Invariant) + "|" + LedgerReport.Money(debit)]);
|
||||
}
|
||||
|
||||
private static async Task<StepResult> OpenNextYearAsync(
|
||||
IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, ClosingRun run, string? userName, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var next = await uow.Repository<FiscalYear, long>().FindAsync(
|
||||
Query.For<FiscalYear>().Where(y => y.StartDate > year.EndDate).OrderBy(y => y.StartDate), cancellationToken).ConfigureAwait(false);
|
||||
var messages = new List<string>();
|
||||
if (next is null)
|
||||
{
|
||||
next = await CreateYearAsync(uow, year.EndDate.AddDays(1), cancellationToken).ConfigureAwait(false);
|
||||
messages.Add("closing.year-created|" + next.Code);
|
||||
}
|
||||
|
||||
run.NextFiscalYearId = next.Id;
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var openingBalance = YearEndLedger.Require(accounts, codes.OpeningBalance);
|
||||
|
||||
// The opening entry mirrors the closing one of step 7: the balances before it, by account and party.
|
||||
var closing = await ClosingEntryAsync(uow, year, cancellationToken).ConfigureAwait(false);
|
||||
var drafts = new List<EntryLineDraft>();
|
||||
var entries = 0;
|
||||
if (closing is not null)
|
||||
{
|
||||
var closingAccount = YearEndLedger.Require(accounts, codes.ClosingBalance).Id;
|
||||
var lines = (await LedgerStore.LinesAsync(uow, closing.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.AccountId != closingAccount).ToList();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
drafts.Add(new EntryLineDraft(line.AccountId, line.PartyId, line.Description, line.Credit, line.Debit));
|
||||
}
|
||||
|
||||
drafts.Add(YearEndLedger.Credit(openingBalance.Id, lines.Sum(l => l.Credit), "Attività"));
|
||||
drafts.Add(YearEndLedger.Debit(openingBalance.Id, lines.Sum(l => l.Debit), "Passività e patrimonio netto"));
|
||||
if (await YearEndLedger.PostAsync(uow, next.StartDate, "Stato patrimoniale iniziale " + next.Code, GlEntrySource.Closing, 8, drafts, isDemo, cancellationToken)
|
||||
.ConfigureAwait(false) is not null)
|
||||
{
|
||||
entries++;
|
||||
messages.Add("closing.opening-posted|" + next.Code);
|
||||
}
|
||||
}
|
||||
|
||||
// The accruals and the exchange differences of step 3 are reversed on the first day of the new year.
|
||||
var from = year.StartDate;
|
||||
var to = year.EndDate;
|
||||
var step3 = (int?)3;
|
||||
var adjustments = (await uow.Repository<GlEntry, long>().ListAsync(
|
||||
Query.For<GlEntry>().Where(e => e.ClosingStep == step3 && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var adjustment in adjustments)
|
||||
{
|
||||
var reversal = await JournalEntryService.ReverseAsync(uow, adjustment, next.StartDate, userName, cancellationToken).ConfigureAwait(false);
|
||||
reversal.ClosingStep = 8;
|
||||
await uow.Repository<GlEntry, long>().UpdateAsync(reversal, cancellationToken).ConfigureAwait(false);
|
||||
if (adjustment.Source == GlEntrySource.Accrual)
|
||||
{
|
||||
var repository = uow.Repository<AccrualDeferral, long>();
|
||||
var entryId = (long?)adjustment.Id;
|
||||
foreach (var accrual in (await repository.ListAsync(Query.For<AccrualDeferral>().Where(a => a.GlEntryId == entryId), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
accrual.ReversalEntryId = reversal.Id;
|
||||
await repository.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
entries++;
|
||||
}
|
||||
|
||||
if (adjustments.Count > 0)
|
||||
{
|
||||
messages.Add("closing.adjustments-reversed|" + adjustments.Count.ToString(Invariant));
|
||||
}
|
||||
|
||||
return new StepResult(ClosingStepStatus.Done, entries, closing?.TotalDebit ?? 0m, messages);
|
||||
}
|
||||
|
||||
private static async Task UndoNextYearAsync(IUnitOfWork uow, FiscalYear year, ClosingRun run, CancellationToken cancellationToken)
|
||||
{
|
||||
if (run.NextFiscalYearId is not { } nextId || await uow.Repository<FiscalYear, long>().GetAsync(nextId, cancellationToken).ConfigureAwait(false) is not { } next)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var from = next.StartDate;
|
||||
var to = next.EndDate;
|
||||
var step8 = (int?)8;
|
||||
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
|
||||
Query.For<GlEntry>().Where(e => e.ClosingStep == step8 && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items;
|
||||
|
||||
// The entries of step 3 can be reversed again: they and their accruals let go of the reversals first.
|
||||
foreach (var reversed in entries.Where(e => e.ReversalOfId is not null))
|
||||
{
|
||||
if (await uow.Repository<GlEntry, long>().GetAsync(reversed.ReversalOfId!.Value, cancellationToken).ConfigureAwait(false) is { } original)
|
||||
{
|
||||
original.ReversedById = null;
|
||||
await uow.Repository<GlEntry, long>().UpdateAsync(original, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var accruals = uow.Repository<AccrualDeferral, long>();
|
||||
var yearNumber = year.EndDate.Year;
|
||||
foreach (var accrual in (await accruals.ListAsync(Query.For<AccrualDeferral>().Where(a => a.Year == yearNumber && a.ReversalEntryId != null), cancellationToken)
|
||||
.ConfigureAwait(false)).Items)
|
||||
{
|
||||
accrual.ReversalEntryId = null;
|
||||
await accruals.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await YearEndLedger.DeleteAsync(uow, entries.Select(e => e.Id), cancellationToken).ConfigureAwait(false);
|
||||
run.NextFiscalYearId = null;
|
||||
}
|
||||
|
||||
private static async Task<GlEntry?> ClosingEntryAsync(IUnitOfWork uow, FiscalYear year, CancellationToken cancellationToken)
|
||||
{
|
||||
var from = year.StartDate;
|
||||
var to = year.EndDate;
|
||||
var step7 = (int?)7;
|
||||
return await uow.Repository<GlEntry, long>().FindAsync(
|
||||
Query.For<GlEntry>().Where(e => e.ClosingStep == step7 && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<List<(long AccountId, long? PartyId, decimal Amount)>> BalanceSheetLinesAsync(
|
||||
IUnitOfWork uow, Dictionary<string, GlAccount> accounts, FiscalYear year, CancellationToken cancellationToken)
|
||||
{
|
||||
var byId = accounts.Values.ToDictionary(a => a.Id);
|
||||
var balances = await BalancesAsync(uow, null, year.EndDate, byParty: true, cancellationToken).ConfigureAwait(false);
|
||||
return
|
||||
[
|
||||
.. balances
|
||||
.Where(b => b.Amount != 0m && byId.TryGetValue(b.AccountId, out var a) && a.Nature is AccountNature.Asset or AccountNature.Liability)
|
||||
.OrderBy(b => byId[b.AccountId].Code, StringComparer.Ordinal).ThenBy(b => b.PartyId),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>The balances (debit minus credit) of the posted entries, by account and optionally by party.</summary>
|
||||
private static async Task<List<(long AccountId, long? PartyId, decimal Amount)>> BalancesAsync(
|
||||
IUnitOfWork uow, DateOnly? from, DateOnly to, bool byParty, CancellationToken cancellationToken)
|
||||
{
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var start = from ?? DateOnly.MinValue;
|
||||
var rows = byParty
|
||||
? await uow.QueryAsync<BalanceRow>(SqlFragment.Of($"""
|
||||
SELECT l.account_id AS account_id, l.party_id AS party_id, SUM(l.debit - l.credit) AS amount
|
||||
FROM gl_entry_lines l
|
||||
WHERE l.entry_date >= {start} AND l.entry_date <= {to} AND l.status <> {draft}
|
||||
GROUP BY l.account_id, l.party_id
|
||||
"""), cancellationToken).ConfigureAwait(false)
|
||||
: await uow.QueryAsync<BalanceRow>(SqlFragment.Of($"""
|
||||
SELECT l.account_id AS account_id, NULL AS party_id, SUM(l.debit - l.credit) AS amount
|
||||
FROM gl_entry_lines l
|
||||
WHERE l.entry_date >= {start} AND l.entry_date <= {to} AND l.status <> {draft}
|
||||
GROUP BY l.account_id
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
return [.. rows.Select(r => (r.AccountId, r.PartyId, r.Amount ?? 0m))];
|
||||
}
|
||||
|
||||
private static async Task<decimal> BalanceAsync(IUnitOfWork uow, long accountId, DateOnly to, CancellationToken cancellationToken, DateOnly? from = null)
|
||||
{
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var start = from ?? DateOnly.MinValue;
|
||||
return await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"""
|
||||
SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l
|
||||
WHERE l.account_id = {accountId} AND l.entry_date >= {start} AND l.entry_date <= {to} AND l.status <> {draft}
|
||||
"""), cancellationToken).ConfigureAwait(false) ?? 0m;
|
||||
}
|
||||
|
||||
private static List<EntryLineDraft> Merge(List<EntryLineDraft> lines, long summaryId)
|
||||
{
|
||||
// One line for the income summary on each side, so the entry stays readable.
|
||||
var others = lines.Where(l => l.AccountId != summaryId).ToList();
|
||||
var net = lines.Where(l => l.AccountId == summaryId).ToList();
|
||||
var debit = net.Sum(l => Math.Max(0m, l.Debit - l.Credit));
|
||||
var credit = net.Sum(l => Math.Max(0m, l.Credit - l.Debit));
|
||||
others.Add(YearEndLedger.Debit(summaryId, debit, "Costi dell'esercizio"));
|
||||
others.Add(YearEndLedger.Credit(summaryId, credit, "Ricavi dell'esercizio"));
|
||||
return others;
|
||||
}
|
||||
|
||||
private static async Task<FiscalYear> CreateYearAsync(IUnitOfWork uow, DateOnly start, CancellationToken cancellationToken)
|
||||
{
|
||||
var end = start.AddYears(1).AddDays(-1);
|
||||
var year = new FiscalYear
|
||||
{
|
||||
Code = start.Year == end.Year ? start.Year.ToString(Invariant) : string.Create(Invariant, $"{start.Year}/{end.Year % 100:00}"),
|
||||
StartDate = start,
|
||||
EndDate = end,
|
||||
};
|
||||
year.Id = await uow.Repository<FiscalYear, long>().InsertAsync(year, cancellationToken).ConfigureAwait(false);
|
||||
for (var i = 0; i < 12; i++)
|
||||
{
|
||||
var first = start.AddMonths(i);
|
||||
await uow.Repository<FiscalPeriod, long>().InsertAsync(
|
||||
new FiscalPeriod { FiscalYearId = year.Id, Number = i + 1, StartDate = first, EndDate = first.AddMonths(1).AddDays(-1) }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return year;
|
||||
}
|
||||
|
||||
private static async Task<ClosingRun> StartAsync(IUnitOfWork uow, FiscalYear year, CancellationToken cancellationToken)
|
||||
{
|
||||
var run = new ClosingRun { FiscalYearId = year.Id, YearCode = year.Code, Status = ClosingStatus.InProgress };
|
||||
run.Id = await uow.Repository<ClosingRun, long>().InsertAsync(run, cancellationToken).ConfigureAwait(false);
|
||||
for (var number = 1; number <= StepCount; number++)
|
||||
{
|
||||
await uow.Repository<ClosingStep, long>().InsertAsync(new ClosingStep { RunId = run.Id, Number = number }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return run;
|
||||
}
|
||||
|
||||
private static async Task<(FiscalYear Year, ClosingRun? Run, IReadOnlyList<ClosingStep> Steps)> LoadAsync(IUnitOfWork uow, long fiscalYearId, CancellationToken cancellationToken)
|
||||
{
|
||||
var year = await uow.Repository<FiscalYear, long>().GetAsync(fiscalYearId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
var run = await uow.Repository<ClosingRun, long>().FindAsync(Query.For<ClosingRun>().Where(r => r.FiscalYearId == fiscalYearId), cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<ClosingStep> steps = run is null
|
||||
? [.. Enumerable.Range(1, StepCount).Select(n => new ClosingStep { Number = n })]
|
||||
: await StepsAsync(uow, run.Id, cancellationToken).ConfigureAwait(false);
|
||||
return (year, run, steps);
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<ClosingStep>> StepsAsync(IUnitOfWork uow, long runId, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<ClosingStep, long>().ListAsync(Query.For<ClosingStep>().Where(s => s.RunId == runId).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false)).Items;
|
||||
|
||||
private static async Task<bool> IsDemoAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.IsDemo), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static int Pages(byte[] pdf)
|
||||
{
|
||||
// The PDF writer marks every page with "/Type /Page"; the pages object is "/Type /Pages".
|
||||
var text = System.Text.Encoding.ASCII.GetString(pdf);
|
||||
var count = 0;
|
||||
for (var index = text.IndexOf("/Type /Page", StringComparison.Ordinal); index >= 0; index = text.IndexOf("/Type /Page", index + 1, StringComparison.Ordinal))
|
||||
{
|
||||
if (index + 11 >= text.Length || text[index + 11] != 's')
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.Max(1, count);
|
||||
}
|
||||
|
||||
private static FiscalYear Copy(FiscalYear year) => new()
|
||||
{
|
||||
Id = year.Id,
|
||||
Code = year.Code,
|
||||
StartDate = year.StartDate,
|
||||
EndDate = year.EndDate,
|
||||
Status = year.Status,
|
||||
JournalFirstPage = year.JournalFirstPage,
|
||||
LastFinalEntryNumber = year.LastFinalEntryNumber,
|
||||
LastFinalEntryDate = year.LastFinalEntryDate,
|
||||
};
|
||||
|
||||
private sealed record StepResult(ClosingStepStatus Status, int Entries, decimal Amount, List<string> Messages);
|
||||
|
||||
private sealed record BalanceRow(long AccountId, long? PartyId, decimal? Amount);
|
||||
|
||||
private sealed record PrintRow(long Id, string Kind, string FileName, int Pages);
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>A line of a statement with the amounts of the year and of the year before.</summary>
|
||||
/// <param name="Code">The code of the line.</param>
|
||||
/// <param name="Description">The legal description.</param>
|
||||
/// <param name="Depth">The depth, from 0.</param>
|
||||
/// <param name="Header">Whether it adds up other lines (shown in bold).</param>
|
||||
/// <param name="Current">The amount of the year.</param>
|
||||
/// <param name="Previous">The amount of the year before.</param>
|
||||
public sealed record StatementRow(string Code, string Description, int Depth, bool Header, decimal Current, decimal Previous);
|
||||
|
||||
/// <summary>An account whose balance has no line of the statements.</summary>
|
||||
/// <param name="AccountId">The account.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="Balance">Its balance, debit minus credit.</param>
|
||||
public sealed record UnmappedAccount(long AccountId, string Code, string Description, decimal Balance);
|
||||
|
||||
/// <summary>The financial statements of a year (mockup 051).</summary>
|
||||
/// <param name="Year">The year.</param>
|
||||
/// <param name="Form">Ordinary, abbreviated or micro.</param>
|
||||
/// <param name="Assets">The assets.</param>
|
||||
/// <param name="Liabilities">The liabilities and equity.</param>
|
||||
/// <param name="Income">The income statement.</param>
|
||||
/// <param name="TotalAssets">The total assets of the year and of the year before.</param>
|
||||
/// <param name="TotalLiabilities">The total liabilities of the year and of the year before.</param>
|
||||
/// <param name="Result">The result of the year and of the year before.</param>
|
||||
/// <param name="Unmapped">The accounts with a balance and no line.</param>
|
||||
public sealed record FinancialStatements(
|
||||
int Year, FinancialStatementForm Form, IReadOnlyList<StatementRow> Assets, IReadOnlyList<StatementRow> Liabilities, IReadOnlyList<StatementRow> Income,
|
||||
(decimal Current, decimal Previous) TotalAssets, (decimal Current, decimal Previous) TotalLiabilities, (decimal Current, decimal Previous) Result,
|
||||
IReadOnlyList<UnmappedAccount> Unmapped)
|
||||
{
|
||||
/// <summary>Whether assets and liabilities balance.</summary>
|
||||
public bool Balanced => TotalAssets.Current == TotalLiabilities.Current;
|
||||
}
|
||||
|
||||
/// <summary>A line of a reclassified statement.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">What it shows.</param>
|
||||
/// <param name="Subtotal">Whether it is a subtotal.</param>
|
||||
/// <param name="Current">The amount of the year.</param>
|
||||
/// <param name="Previous">The amount of the year before.</param>
|
||||
public sealed record ReclassifiedRow(string Code, string Description, bool Subtotal, decimal Current, decimal Previous);
|
||||
|
||||
/// <summary>A ratio of the year and of the year before.</summary>
|
||||
/// <param name="Current">The ratio of the year.</param>
|
||||
/// <param name="Previous">The ratio of the year before.</param>
|
||||
public sealed record RatioRow(FinancialRatio Current, FinancialRatio Previous);
|
||||
|
||||
/// <summary>An account of a line, for the drill-down.</summary>
|
||||
/// <param name="AccountId">The account.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="Current">The amount of the year, with the sign of the line.</param>
|
||||
/// <param name="Previous">The amount of the year before.</param>
|
||||
public sealed record StatementAccount(long AccountId, string Code, string Description, decimal Current, decimal Previous);
|
||||
|
||||
/// <summary>
|
||||
/// The financial statements (SPEC §11.7, issue #86, mockup 051, ADR 0043): the legal balance sheet and income statement
|
||||
/// in the ordinary, abbreviated or micro form with the year before, from the balances of the accounts mapped to the lines
|
||||
/// of the fiscal pack; the statements reclassified by liquidity and by value added, the ratios, the drill-down to the
|
||||
/// accounts, the print and the export for the accountant. The entries of steps 6 and 7 of the closing are left out, so
|
||||
/// a closed year shows its balances.
|
||||
/// </summary>
|
||||
public sealed class FinancialStatementsService
|
||||
{
|
||||
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
public FinancialStatementsService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
}
|
||||
|
||||
/// <summary>The financial statements of a year with the year before.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="form">The form.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The statements.</returns>
|
||||
public async Task<FinancialStatements> StatementsAsync(Actor actor, string companyCode, int year, FinancialStatementForm form, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFinancialStatementsSchema>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await StatementsAsync(uow, schema, year, form, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A reclassified statement of a year with the year before.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="kind">By liquidity or by value added.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lines.</returns>
|
||||
public async Task<IReadOnlyList<ReclassifiedRow>> ReclassifiedAsync(Actor actor, string companyCode, int year, ReclassificationKind kind, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFinancialStatementsSchema>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var current = await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false);
|
||||
var previous = await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false);
|
||||
var now = Reclassify(schema, current, kind);
|
||||
var before = Reclassify(schema, previous, kind);
|
||||
return [.. schema.Reclassification(kind).Select(l => new ReclassifiedRow(l.Code, l.Description, l.Subtotal, now[l.Code], before[l.Code]))];
|
||||
}
|
||||
|
||||
/// <summary>The ratios of a year with the year before.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The ratios.</returns>
|
||||
public async Task<IReadOnlyList<RatioRow>> RatiosAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFinancialStatementsSchema>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var current = FinancialRatios.Compute(Inputs(schema, await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false)));
|
||||
var previous = FinancialRatios.Compute(Inputs(schema, await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false)));
|
||||
return [.. current.Zip(previous, (c, p) => new RatioRow(c, p))];
|
||||
}
|
||||
|
||||
/// <summary>The accounts that make up a line, for the drill-down.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="kind">The statement.</param>
|
||||
/// <param name="code">The line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The accounts with a balance.</returns>
|
||||
public async Task<IReadOnlyList<StatementAccount>> AccountsAsync(
|
||||
Actor actor, string companyCode, int year, FinancialStatementKind kind, string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFinancialStatementsSchema>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var ordinary = schema.Lines(kind, FinancialStatementForm.Ordinary);
|
||||
var codes = Descendants(ordinary, code);
|
||||
var line = ordinary.FirstOrDefault(l => l.Code == code);
|
||||
var sign = line?.CreditNormal == true ? 1m : -1m;
|
||||
var current = await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false);
|
||||
var previous = await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false);
|
||||
return
|
||||
[
|
||||
.. current.Accounts.Values.Concat(previous.Accounts.Values).DistinctBy(a => a.AccountId)
|
||||
.Where(a => a.Kind == kind && codes.Contains(a.Line))
|
||||
.Select(a => new StatementAccount(
|
||||
a.AccountId, a.Code, a.Description,
|
||||
sign * (current.Accounts.TryGetValue(a.AccountId, out var c) ? c.Balance : 0m),
|
||||
sign * (previous.Accounts.TryGetValue(a.AccountId, out var p) ? p.Balance : 0m)))
|
||||
.Where(a => a.Current != 0m || a.Previous != 0m)
|
||||
.OrderBy(a => a.Code, StringComparer.Ordinal),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>Prints the statements of a year.</summary>
|
||||
/// <param name="actor">Who prints.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="form">The form.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The PDF.</returns>
|
||||
public async Task<LedgerFile> PrintAsync(Actor actor, string companyCode, int year, FinancialStatementForm form, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
|
||||
var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFinancialStatementsSchema>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
(byte[] file, int _) = await PrintAsync(uow, schema, year, form, 1, cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(string.Create(Invariant, $"bilancio-{year}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The export for the accountant: a ZIP of CSV files (semicolon, decimal comma, UTF-8) with the chart of accounts, the
|
||||
/// trial balance, the movements of the year and the statements.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who exports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The ZIP.</returns>
|
||||
public async Task<LedgerFile> AccountantExportAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AccountantExport, cancellationToken).ConfigureAwait(false);
|
||||
var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFinancialStatementsSchema>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var content = await AccountantExportAsync(uow, schema, year, cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(string.Create(Invariant, $"commercialista-{company}-{year}.zip"), "application/zip", content);
|
||||
}
|
||||
|
||||
internal static async Task<FinancialStatements> StatementsAsync(IUnitOfWork uow, IFinancialStatementsSchema schema, int year, FinancialStatementForm form, CancellationToken cancellationToken)
|
||||
{
|
||||
var current = await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false);
|
||||
var previous = await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false);
|
||||
var assets = Rows(schema, FinancialStatementKind.Assets, form, current, previous);
|
||||
var liabilities = Rows(schema, FinancialStatementKind.Liabilities, form, current, previous);
|
||||
var income = Rows(schema, FinancialStatementKind.IncomeStatement, form, current, previous);
|
||||
return new FinancialStatements(
|
||||
year, form, assets, liabilities, income,
|
||||
(-current.Total(FinancialStatementKind.Assets), -previous.Total(FinancialStatementKind.Assets)),
|
||||
(current.Total(FinancialStatementKind.Liabilities) + current.Result, previous.Total(FinancialStatementKind.Liabilities) + previous.Result),
|
||||
(current.Result, previous.Result),
|
||||
[.. current.Unmapped.Where(u => u.Balance != 0m)]);
|
||||
}
|
||||
|
||||
internal static async Task<(byte[] File, int Pages)> PrintAsync(
|
||||
IUnitOfWork uow, IFinancialStatementsSchema schema, int year, FinancialStatementForm form, int firstPage, CancellationToken cancellationToken)
|
||||
{
|
||||
var statements = await StatementsAsync(uow, schema, year, form, cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var rows = new List<IReadOnlyList<string?>>();
|
||||
void Section(string title, IReadOnlyList<StatementRow> lines, (decimal Current, decimal Previous)? total, string? totalTitle)
|
||||
{
|
||||
rows.Add(["**" + title, null, null, null]);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var text = new string(' ', line.Depth * 3) + line.Code + " " + line.Description;
|
||||
rows.Add([(line.Header ? "**" : string.Empty) + text, null, LedgerReport.Money(line.Current), LedgerReport.Money(line.Previous)]);
|
||||
}
|
||||
|
||||
if (total is { } t)
|
||||
{
|
||||
rows.Add(["**" + totalTitle, null, LedgerReport.Money(t.Current), LedgerReport.Money(t.Previous)]);
|
||||
}
|
||||
|
||||
rows.Add([null, null, null, null]);
|
||||
}
|
||||
|
||||
Section("STATO PATRIMONIALE - ATTIVO", statements.Assets, statements.TotalAssets, "Totale attivo");
|
||||
Section("STATO PATRIMONIALE - PASSIVO", statements.Liabilities, statements.TotalLiabilities, "Totale passivo");
|
||||
Section("CONTO ECONOMICO", statements.Income, null, null);
|
||||
var formText = form switch
|
||||
{
|
||||
FinancialStatementForm.Ordinary => "ordinario (artt. 2424-2425 c.c.)",
|
||||
FinancialStatementForm.Abbreviated => "abbreviato (art. 2435-bis c.c.)",
|
||||
_ => "micro-imprese (art. 2435-ter c.c.)",
|
||||
};
|
||||
return await LedgerReport.WriteAsync(
|
||||
VatService.CompanyLine(profile),
|
||||
"Bilancio d'esercizio " + year.ToString(Invariant),
|
||||
"Schema " + formText,
|
||||
[new ReportColumn("Voce", 520), new ReportColumn(string.Empty, 10), new ReportColumn(year.ToString(Invariant), 110, true), new ReportColumn((year - 1).ToString(Invariant), 110, true)],
|
||||
rows,
|
||||
year,
|
||||
firstPage,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<byte[]> AccountantExportAsync(IUnitOfWork uow, IFinancialStatementsSchema schema, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var fiscalYear = await AccrualService.YearAsync(uow, year, cancellationToken).ConfigureAwait(false);
|
||||
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var balance = await LedgerQueryService.TrialBalanceAsync(uow, fiscalYear.StartDate, fiscalYear.EndDate, null, false, cancellationToken).ConfigureAwait(false);
|
||||
var statements = await StatementsAsync(uow, schema, year, FinancialStatementForm.Ordinary, cancellationToken).ConfigureAwait(false);
|
||||
var from = fiscalYear.StartDate;
|
||||
var to = fiscalYear.EndDate;
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var movements = await uow.QueryAsync<ExportMovementRow>(SqlFragment.Of($"""
|
||||
SELECT e.entry_number AS entry_number, e.entry_date AS entry_date, e.description AS entry_description, e.document_number AS document_number,
|
||||
a.code AS account_code, p.code AS party_code, l.description AS description, l.debit AS debit, l.credit AS credit
|
||||
FROM gl_entry_lines l
|
||||
JOIN gl_entries e ON e.id = l.entry_id
|
||||
JOIN gl_accounts a ON a.id = l.account_id
|
||||
LEFT JOIN parties p ON p.id = l.party_id
|
||||
WHERE l.entry_date >= {from} AND l.entry_date <= {to} AND l.status <> {draft}
|
||||
ORDER BY e.entry_date, e.id, l.line_number
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
using var stream = new MemoryStream();
|
||||
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
Csv(zip, "piano-dei-conti.csv", ["Codice", "Descrizione", "Livello", "Natura", "Voce CEE", "Movimentabile"],
|
||||
accounts.Values.OrderBy(a => a.Code, StringComparer.Ordinal)
|
||||
.Select(a => (IReadOnlyList<string?>)[a.Code, a.Description, a.Level.ToString(Invariant), a.Nature.ToString(), a.StatementLine, a.Postable ? "S" : "N"]));
|
||||
Csv(zip, "bilancio-di-verifica.csv", ["Conto", "Descrizione", "Saldo iniziale", "Dare", "Avere", "Saldo finale"],
|
||||
balance.Lines.Where(l => accounts[l.AccountId].Postable)
|
||||
.Select(l => (IReadOnlyList<string?>)[l.Code, l.Description, Amount(l.Opening), Amount(l.Debit), Amount(l.Credit), Amount(l.Closing)]));
|
||||
Csv(zip, "movimenti.csv", ["Registrazione", "Data", "Descrizione", "Documento", "Conto", "Soggetto", "Descrizione riga", "Dare", "Avere"],
|
||||
movements.Select(m => (IReadOnlyList<string?>)[
|
||||
m.EntryNumber, m.EntryDate.ToString("yyyy-MM-dd", Invariant), m.EntryDescription, m.DocumentNumber, m.AccountCode, m.PartyCode, m.Description,
|
||||
Amount(m.Debit), Amount(m.Credit)]));
|
||||
Csv(zip, "stato-patrimoniale.csv", ["Sezione", "Voce", "Descrizione", year.ToString(Invariant), (year - 1).ToString(Invariant)],
|
||||
statements.Assets.Select(r => Row("Attivo", r)).Concat(statements.Liabilities.Select(r => Row("Passivo", r))));
|
||||
Csv(zip, "conto-economico.csv", ["Voce", "Descrizione", year.ToString(Invariant), (year - 1).ToString(Invariant)],
|
||||
statements.Income.Select(r => (IReadOnlyList<string?>)[r.Code, r.Description, Amount(r.Current), Amount(r.Previous)]));
|
||||
}
|
||||
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The balances of a year by account, with the line of the statements of each.</summary>
|
||||
internal static async Task<RawBalances> RawAsync(IUnitOfWork uow, IFinancialStatementsSchema schema, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var code = year.ToString(Invariant);
|
||||
var fiscalYear = await uow.Repository<FiscalYear, long>().FindAsync(Query.For<FiscalYear>().Where(y => y.Code == code), cancellationToken).ConfigureAwait(false);
|
||||
var from = fiscalYear?.StartDate ?? new DateOnly(year, 1, 1);
|
||||
var to = fiscalYear?.EndDate ?? new DateOnly(year, 12, 31);
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
|
||||
// Balance-sheet accounts carry their balance from the years before; income accounts count the year only. The
|
||||
// closing entries of the year (steps 6 and 7) are left out, so a closed year still shows its balances.
|
||||
var rows = await uow.QueryAsync<RawRow>(SqlFragment.Of($"""
|
||||
SELECT l.account_id AS account_id,
|
||||
SUM(CASE WHEN l.entry_date >= {from} THEN l.debit - l.credit ELSE 0 END) AS period_sum,
|
||||
SUM(l.debit - l.credit) AS total_sum
|
||||
FROM gl_entry_lines l
|
||||
JOIN gl_entries e ON e.id = l.entry_id
|
||||
WHERE l.entry_date <= {to} AND l.status <> {draft}
|
||||
AND (e.closing_step IS NULL OR e.closing_step < 6 OR e.closing_step > 7 OR l.entry_date < {from})
|
||||
GROUP BY l.account_id
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var result = new RawBalances();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (!accounts.TryGetValue(row.AccountId, out var account) || account.Nature == AccountNature.Memorandum)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var income = account.Nature is AccountNature.Cost or AccountNature.Revenue;
|
||||
var balance = income ? row.PeriodSum ?? 0m : row.TotalSum ?? 0m;
|
||||
if (balance == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var kind = account.Nature switch
|
||||
{
|
||||
AccountNature.Asset => FinancialStatementKind.Assets,
|
||||
AccountNature.Liability => FinancialStatementKind.Liabilities,
|
||||
_ => FinancialStatementKind.IncomeStatement,
|
||||
};
|
||||
if (income)
|
||||
{
|
||||
result.Result -= balance;
|
||||
}
|
||||
|
||||
var line = StatementLineOf(accounts, account);
|
||||
if (line is null || !schema.Lines(kind, FinancialStatementForm.Ordinary).Any(l => l.Code == line))
|
||||
{
|
||||
result.Unmapped.Add(new UnmappedAccount(account.Id, account.Code, account.Description, balance));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Raw amounts are credit minus debit, the sign every line turns as it needs.
|
||||
result.Accounts[account.Id] = new RawAccount(account.Id, account.Code, account.Description, kind, line, -balance);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static Dictionary<string, decimal> Reclassify(IFinancialStatementsSchema schema, RawBalances raw, ReclassificationKind kind)
|
||||
{
|
||||
var values = new Dictionary<string, decimal>(StringComparer.Ordinal);
|
||||
foreach (var line in schema.Reclassification(kind))
|
||||
{
|
||||
decimal value;
|
||||
if (line.Totals is { Count: > 0 } totals)
|
||||
{
|
||||
value = totals.Sum(t => t.StartsWith('-') ? -values.GetValueOrDefault(t[1..]) : values.GetValueOrDefault(t));
|
||||
}
|
||||
else
|
||||
{
|
||||
var ordinary = schema.Lines(line.Source, FinancialStatementForm.Ordinary);
|
||||
var codes = line.Lines.SelectMany(l => Descendants(ordinary, l)).ToHashSet(StringComparer.Ordinal);
|
||||
value = raw.Sum(line.Source, codes, schema.ResultLine);
|
||||
value = line.Negate ? -value : value;
|
||||
}
|
||||
|
||||
values[line.Code] = value;
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
internal static RatioInputs Inputs(IFinancialStatementsSchema schema, RawBalances raw)
|
||||
{
|
||||
var financial = Reclassify(schema, raw, ReclassificationKind.Financial);
|
||||
var added = Reclassify(schema, raw, ReclassificationKind.ValueAdded);
|
||||
return new RatioInputs(
|
||||
Equity: financial.GetValueOrDefault(ReclassifiedCodes.Equity),
|
||||
Result: raw.Result,
|
||||
OperatingResult: added.GetValueOrDefault(ReclassifiedCodes.OperatingResult),
|
||||
Revenue: added.GetValueOrDefault(ReclassifiedCodes.Revenue),
|
||||
TotalAssets: financial.GetValueOrDefault(ReclassifiedCodes.TotalAssets),
|
||||
FixedAssets: financial.GetValueOrDefault(ReclassifiedCodes.FixedAssets),
|
||||
CurrentAssets: financial.GetValueOrDefault(ReclassifiedCodes.CurrentAssets),
|
||||
Inventory: financial.GetValueOrDefault(ReclassifiedCodes.Inventory),
|
||||
Liquidity: financial.GetValueOrDefault(ReclassifiedCodes.Liquidity),
|
||||
Receivables: financial.GetValueOrDefault(ReclassifiedCodes.Receivables),
|
||||
CurrentLiabilities: financial.GetValueOrDefault(ReclassifiedCodes.CurrentLiabilities),
|
||||
LongTermLiabilities: financial.GetValueOrDefault(ReclassifiedCodes.LongTermLiabilities),
|
||||
Payables: financial.GetValueOrDefault(ReclassifiedCodes.Payables),
|
||||
Purchases: -added.GetValueOrDefault(ReclassifiedCodes.Purchases),
|
||||
Days: 365);
|
||||
}
|
||||
|
||||
private static string? StatementLineOf(Dictionary<long, GlAccount> accounts, GlAccount account)
|
||||
{
|
||||
// A sub-account without a line takes the one of its parent.
|
||||
var current = account;
|
||||
while (current is not null)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(current.StatementLine))
|
||||
{
|
||||
return current.StatementLine.Trim();
|
||||
}
|
||||
|
||||
current = current.ParentId is { } p && accounts.TryGetValue(p, out var parent) ? parent : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<StatementRow> Rows(IFinancialStatementsSchema schema, FinancialStatementKind kind, FinancialStatementForm form, RawBalances current, RawBalances previous)
|
||||
{
|
||||
var ordinary = schema.Lines(kind, FinancialStatementForm.Ordinary);
|
||||
var lines = schema.Lines(kind, form);
|
||||
var rows = new List<StatementRow>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var depth = 0;
|
||||
for (var parent = line.ParentCode; parent is not null; parent = lines.FirstOrDefault(l => l.Code == parent)?.ParentCode)
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
|
||||
decimal Value(RawBalances raw)
|
||||
{
|
||||
if (line.Totals is { Count: > 0 } totals)
|
||||
{
|
||||
var codes = totals.SelectMany(t => Descendants(ordinary, t)).ToHashSet(StringComparer.Ordinal);
|
||||
return raw.Sum(kind, codes, schema.ResultLine);
|
||||
}
|
||||
|
||||
var sum = raw.Sum(kind, Descendants(ordinary, line.Code), schema.ResultLine);
|
||||
return line.CreditNormal ? sum : -sum;
|
||||
}
|
||||
|
||||
var header = !line.Postable || line.Totals is not null || lines.Any(l => l.ParentCode == line.Code);
|
||||
rows.Add(new StatementRow(line.Code, line.Description, depth, header, Value(current), Value(previous)));
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static HashSet<string> Descendants(IReadOnlyList<FinancialStatementLine> ordinary, string code)
|
||||
{
|
||||
var result = new HashSet<string>(StringComparer.Ordinal) { code };
|
||||
var added = true;
|
||||
while (added)
|
||||
{
|
||||
added = false;
|
||||
foreach (var line in ordinary)
|
||||
{
|
||||
if (line.ParentCode is { } parent && result.Contains(parent) && result.Add(line.Code))
|
||||
{
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string Amount(decimal amount) => amount.ToString("0.00", Invariant).Replace('.', ',');
|
||||
|
||||
private static IReadOnlyList<string?> Row(string section, StatementRow row) => [section, row.Code, row.Description, Amount(row.Current), Amount(row.Previous)];
|
||||
|
||||
private static void Csv(ZipArchive zip, string name, IReadOnlyList<string> header, IEnumerable<IReadOnlyList<string?>> rows)
|
||||
{
|
||||
var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
|
||||
using var writer = new StreamWriter(entry.Open(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
|
||||
writer.Write(string.Join(';', header.Select(Quote)));
|
||||
writer.Write("\r\n");
|
||||
foreach (var row in rows)
|
||||
{
|
||||
writer.Write(string.Join(';', row.Select(Quote)));
|
||||
writer.Write("\r\n");
|
||||
}
|
||||
}
|
||||
|
||||
private static string Quote(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
|
||||
}
|
||||
|
||||
private sealed record RawRow(long AccountId, decimal? PeriodSum, decimal? TotalSum);
|
||||
|
||||
private sealed record ExportMovementRow(
|
||||
string? EntryNumber, DateOnly EntryDate, string? EntryDescription, string? DocumentNumber, string AccountCode, string? PartyCode, string? Description, decimal Debit,
|
||||
decimal Credit);
|
||||
}
|
||||
|
||||
/// <summary>A balance of an account for the statements: credit minus debit.</summary>
|
||||
/// <param name="AccountId">The account.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="Kind">Its statement.</param>
|
||||
/// <param name="Line">Its line (ordinary).</param>
|
||||
/// <param name="Balance">Credit minus debit.</param>
|
||||
internal sealed record RawAccount(long AccountId, string Code, string Description, FinancialStatementKind Kind, string Line, decimal Balance);
|
||||
|
||||
/// <summary>The balances of a year by account.</summary>
|
||||
internal sealed class RawBalances
|
||||
{
|
||||
/// <summary>The accounts with a line.</summary>
|
||||
public Dictionary<long, RawAccount> Accounts { get; } = [];
|
||||
|
||||
/// <summary>The accounts with a balance and no line.</summary>
|
||||
public List<UnmappedAccount> Unmapped { get; } = [];
|
||||
|
||||
/// <summary>The result of the year: revenues less costs.</summary>
|
||||
public decimal Result { get; set; }
|
||||
|
||||
/// <summary>The credit-minus-debit sum of a statement.</summary>
|
||||
public decimal Total(FinancialStatementKind kind) => Accounts.Values.Where(a => a.Kind == kind).Sum(a => a.Balance);
|
||||
|
||||
/// <summary>The credit-minus-debit sum of some lines; the result of the year goes into its line.</summary>
|
||||
public decimal Sum(FinancialStatementKind kind, IReadOnlySet<string> lines, string resultLine) =>
|
||||
Accounts.Values.Where(a => a.Kind == kind && lines.Contains(a.Line)).Sum(a => a.Balance)
|
||||
+ (kind == FinancialStatementKind.Liabilities && lines.Contains(resultLine) ? Result : 0m);
|
||||
}
|
||||
@@ -0,0 +1,935 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>An asset as the register lists it.</summary>
|
||||
/// <param name="Asset">The asset.</param>
|
||||
/// <param name="Category">Its category.</param>
|
||||
/// <param name="SupplierName">The supplier.</param>
|
||||
public sealed record AssetRow(FixedAsset Asset, FixedAssetCategory Category, string? SupplierName);
|
||||
|
||||
/// <summary>An asset with its history and its plans.</summary>
|
||||
/// <param name="Asset">The asset.</param>
|
||||
/// <param name="Category">Its category.</param>
|
||||
/// <param name="SupplierName">The supplier.</param>
|
||||
/// <param name="Movements">The movements, in date order.</param>
|
||||
/// <param name="CivilPlan">The civil plan from the first year.</param>
|
||||
/// <param name="FiscalPlan">The fiscal plan from the first year.</param>
|
||||
public sealed record AssetView(
|
||||
FixedAsset Asset, FixedAssetCategory Category, string? SupplierName, IReadOnlyList<FixedAssetMovement> Movements,
|
||||
IReadOnlyList<DepreciationYear> CivilPlan, IReadOnlyList<DepreciationYear> FiscalPlan);
|
||||
|
||||
/// <summary>A new or changed asset.</summary>
|
||||
/// <param name="Id">The asset, for a change.</param>
|
||||
/// <param name="Code">The code; empty for the next one.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="CategoryId">The category.</param>
|
||||
/// <param name="PurchaseDate">The day it was bought.</param>
|
||||
/// <param name="InServiceDate">The day it entered service (first year of depreciation).</param>
|
||||
/// <param name="Cost">The cost.</param>
|
||||
public sealed record AssetInput(long? Id, string? Code, string Description, long CategoryId, DateOnly PurchaseDate, DateOnly InServiceDate, decimal Cost)
|
||||
{
|
||||
/// <summary>The supplier.</summary>
|
||||
public long? SupplierId { get; init; }
|
||||
|
||||
/// <summary>The purchase invoice.</summary>
|
||||
public string? DocumentReference { get; init; }
|
||||
|
||||
/// <summary>Where it is.</summary>
|
||||
public string? Location { get; init; }
|
||||
|
||||
/// <summary>The serial number.</summary>
|
||||
public string? SerialNumber { get; init; }
|
||||
|
||||
/// <summary>How many.</summary>
|
||||
public decimal Quantity { get; init; } = 1m;
|
||||
|
||||
/// <summary>The civil fund at the start of the use in Khaemhat (assets bought in earlier years).</summary>
|
||||
public decimal OpeningCivilFund { get; init; }
|
||||
|
||||
/// <summary>The fiscal fund at the start of the use in Khaemhat.</summary>
|
||||
public decimal OpeningFiscalFund { get; init; }
|
||||
|
||||
/// <summary>The last year already depreciated outside Khaemhat.</summary>
|
||||
public int? LastDepreciationYear { get; init; }
|
||||
|
||||
/// <summary>A civil rate of its own.</summary>
|
||||
public decimal? CivilRate { get; init; }
|
||||
|
||||
/// <summary>A fiscal rate of its own.</summary>
|
||||
public decimal? FiscalRate { get; init; }
|
||||
|
||||
/// <summary>The value not depreciated.</summary>
|
||||
public decimal ResidualValue { get; init; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A disposal or partial disposal.</summary>
|
||||
/// <param name="Date">The day.</param>
|
||||
/// <param name="Proceeds">The price.</param>
|
||||
/// <param name="CostDisposed">The cost disposed of; <see langword="null"/> the whole asset.</param>
|
||||
/// <param name="CounterpartAccountId">The account of the price; <see langword="null"/> other receivables.</param>
|
||||
public sealed record DisposalInput(DateOnly Date, decimal Proceeds, decimal? CostDisposed = null, long? CounterpartAccountId = null);
|
||||
|
||||
/// <summary>The depreciation of an asset in a year.</summary>
|
||||
/// <param name="AssetId">The asset.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="CategoryCode">The category.</param>
|
||||
/// <param name="Cost">The cost.</param>
|
||||
/// <param name="CivilFund">The civil fund at the start of the year.</param>
|
||||
/// <param name="CivilRate">The civil rate of the year.</param>
|
||||
/// <param name="Civil">The civil depreciation.</param>
|
||||
/// <param name="FiscalRate">The fiscal rate of the year.</param>
|
||||
/// <param name="Fiscal">The fiscal depreciation.</param>
|
||||
/// <param name="Posted">Already posted.</param>
|
||||
public sealed record DepreciationLine(
|
||||
long AssetId, string Code, string Description, string CategoryCode, decimal Cost, decimal CivilFund, decimal CivilRate, decimal Civil, decimal FiscalRate,
|
||||
decimal Fiscal, bool Posted)
|
||||
{
|
||||
/// <summary>The civil depreciation not deductible (to add back in the tax return).</summary>
|
||||
public decimal Difference => Civil - Fiscal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The fixed assets (SPEC §11.7, issue #82, mockup 048, ADR 0041): categories with the ministerial coefficients and
|
||||
/// their accounts, the register with a civil and a fiscal plan, the yearly depreciation posted in one entry (charge to
|
||||
/// fund), the disposals with the gain or loss, and the print of the register (libro cespiti).
|
||||
/// </summary>
|
||||
public sealed class FixedAssetService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly FiscalYearService _fiscal;
|
||||
private readonly AuditTrail _audit;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
/// <param name="fiscal">The fiscal calendar.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
public FixedAssetService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, FiscalYearService fiscal, AuditTrail audit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(fiscal);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
_fiscal = fiscal;
|
||||
_audit = audit;
|
||||
}
|
||||
|
||||
/// <summary>The categories, by code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The categories.</returns>
|
||||
public async Task<IReadOnlyList<FixedAssetCategory>> CategoriesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The fiscal coefficients of the company's country, to start a category from.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The coefficients.</returns>
|
||||
public async Task<IReadOnlyList<DepreciationCoefficient>> CoefficientsAsync(string companyCode, CancellationToken cancellationToken = default) =>
|
||||
(await _packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false)).Require<IFixedAssetRules>().Coefficients;
|
||||
|
||||
/// <summary>Creates the categories of the coefficients that are missing.</summary>
|
||||
/// <param name="actor">Who creates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many were created.</returns>
|
||||
public async Task<int> CreateStandardCategoriesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false);
|
||||
var coefficients = await CoefficientsAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var created = await CreateStandardCategoriesAsync(uow, coefficients, actor.UserName, false, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return created;
|
||||
}
|
||||
|
||||
/// <summary>Creates or changes a category.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The category; id 0 for a new one.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The category as saved.</returns>
|
||||
public async Task<FixedAssetCategory> SaveCategoryAsync(Actor actor, string companyCode, FixedAssetCategory input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false);
|
||||
var errors = new List<string>();
|
||||
input.Code = (input.Code ?? string.Empty).Trim().ToUpperInvariant();
|
||||
input.Description = (input.Description ?? string.Empty).Trim();
|
||||
if (input.Code.Length == 0)
|
||||
{
|
||||
errors.Add("Code:" + YearEndErrors.CodeRequired);
|
||||
}
|
||||
|
||||
if (input.Description.Length == 0)
|
||||
{
|
||||
errors.Add("Description:" + YearEndErrors.DescriptionRequired);
|
||||
}
|
||||
|
||||
if (input.CivilRate is < 0m or > 100m)
|
||||
{
|
||||
errors.Add("CivilRate:" + YearEndErrors.RateRange);
|
||||
}
|
||||
|
||||
if (input.FiscalRate is < 0m or > 100m)
|
||||
{
|
||||
errors.Add("FiscalRate:" + YearEndErrors.RateRange);
|
||||
}
|
||||
|
||||
if (input.AssetAccountId is null || input.FundAccountId is null || input.DepreciationAccountId is null)
|
||||
{
|
||||
errors.Add("AssetAccountId:" + YearEndErrors.CategoryAccounts);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<FixedAssetCategory, long>();
|
||||
var code = input.Code;
|
||||
var id = input.Id;
|
||||
if (await repository.CountAsync(Query.For<FixedAssetCategory>().Where(c => c.Code == code && c.Id != id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
errors.Add("Code:" + YearEndErrors.CodeTaken);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
if (input.Id == 0)
|
||||
{
|
||||
input.Id = await repository.InsertAsync(input, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, input.Id, null, input, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var before = await repository.GetAsync(input.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
input.RowVersion = before.RowVersion;
|
||||
input.IsDemo = before.IsDemo;
|
||||
await repository.UpdateAsync(input, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, input.Id, before, input, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return input;
|
||||
}
|
||||
|
||||
/// <summary>The register, by code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="text">Text in the code, description, location or serial number.</param>
|
||||
/// <param name="categoryId">Only this category.</param>
|
||||
/// <param name="status">Only this state.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The assets.</returns>
|
||||
public async Task<IReadOnlyList<AssetRow>> ListAsync(
|
||||
Actor actor, string companyCode, string? text = null, long? categoryId = null, AssetStatus? status = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var query = Query.For<FixedAsset>();
|
||||
if (categoryId is { } c)
|
||||
{
|
||||
query = query.Where(a => a.CategoryId == c);
|
||||
}
|
||||
|
||||
if (status is { } s)
|
||||
{
|
||||
query = query.Where(a => a.Status == s);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
var t = text.Trim();
|
||||
query = query.Where(a => a.Code.Contains(t) || a.Description.Contains(t) || a.Location!.Contains(t) || a.SerialNumber!.Contains(t));
|
||||
}
|
||||
|
||||
var assets = (await uow.Repository<FixedAsset, long>().ListAsync(query.OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(x => x.Id);
|
||||
var names = await JournalEntryService.PartyNamesAsync(uow, assets.Select(a => a.SupplierId), cancellationToken).ConfigureAwait(false);
|
||||
return [.. assets.Select(a => new AssetRow(a, categories[a.CategoryId], a.SupplierId is { } p && names.TryGetValue(p, out var n) ? n : null))];
|
||||
}
|
||||
|
||||
/// <summary>An asset with its movements and plans.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The asset.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The asset, or none.</returns>
|
||||
public async Task<AssetView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFixedAssetRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ViewAsync(uow, rules, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a new asset or changes one. A new asset bought in an earlier year can bring the funds already
|
||||
/// depreciated (opening movement); cost, category and dates change only while nothing was posted.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The asset.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The asset as saved.</returns>
|
||||
public async Task<AssetView> SaveAsync(Actor actor, string companyCode, AssetInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFixedAssetRules>();
|
||||
long id;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var asset = await SaveAsync(uow, rules, input, actor.UserName, false, cancellationToken).ConfigureAwait(false);
|
||||
id = asset.Id;
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Removes an asset that has no posted movement.</summary>
|
||||
/// <param name="actor">Who removes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The asset.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var asset = await uow.Repository<FixedAsset, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (await uow.Repository<FixedAssetMovement, long>().CountAsync(
|
||||
Query.For<FixedAssetMovement>().Where(m => m.AssetId == id && m.GlEntryId != null), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.AssetPosted]);
|
||||
}
|
||||
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM fixed_asset_movements WHERE asset_id = {id}"), cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<FixedAsset, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, asset, (FixedAsset?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The depreciation of a year, asset by asset: what was posted and what would be.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lines, by code.</returns>
|
||||
public async Task<IReadOnlyList<DepreciationLine>> DepreciationAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFixedAssetRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await DepreciationAsync(uow, rules, year, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Posts the depreciation of a year (the closing does it as its step 2).</summary>
|
||||
/// <param name="actor">Who posts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The total civil depreciation posted.</returns>
|
||||
public async Task<decimal> PostDepreciationAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.DepreciationPost, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IFixedAssetRules>();
|
||||
var date = await YearEndDateAsync(company, year, cancellationToken).ConfigureAwait(false);
|
||||
await _fiscal.DemandOpenAsync(company, date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var (amount, _) = await DepreciateAsync(uow, rules, year, date, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return amount;
|
||||
}
|
||||
|
||||
/// <summary>Removes the depreciation of a year while its entry is not final.</summary>
|
||||
/// <param name="actor">Who removes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task UndoDepreciationAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.DepreciationPost, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await UndoDepreciationAsync(uow, year, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes of an asset or of part of it (cessione, eliminazione): the cost and its share of the fund leave the
|
||||
/// books, the price goes to the counterpart, the difference to gain or loss. No depreciation is computed for the year
|
||||
/// of the disposal (ADR 0041).
|
||||
/// </summary>
|
||||
/// <param name="actor">Who posts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The asset.</param>
|
||||
/// <param name="input">The disposal.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The asset after the disposal.</returns>
|
||||
public async Task<AssetView> DisposeAsync(Actor actor, string companyCode, long id, DisposalInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.DepreciationPost, cancellationToken).ConfigureAwait(false);
|
||||
await _fiscal.DemandOpenAsync(company, input.Date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
|
||||
var codes = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IClosingRules>().Accounts;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await DisposeAsync(uow, codes, id, input, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
}
|
||||
|
||||
/// <summary>The register of the assets of a year (libro cespiti) as PDF.</summary>
|
||||
/// <param name="actor">Who prints.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> PrintRegisterAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var (file, _) = await PrintRegisterAsync(uow, year, 1, cancellationToken).ConfigureAwait(false);
|
||||
return file;
|
||||
}
|
||||
|
||||
internal static async Task<(LedgerFile File, int Pages)> PrintRegisterAsync(IUnitOfWork uow, int year, int firstPage, CancellationToken cancellationToken)
|
||||
{
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Id);
|
||||
var assets = (await uow.Repository<FixedAsset, long>().ListAsync(Query.For<FixedAsset>().OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var movements = (await uow.Repository<FixedAssetMovement, long>().ListAsync(Query.For<FixedAssetMovement>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var yearEnd = new DateOnly(year, 12, 31);
|
||||
var rows = new List<IReadOnlyList<string?>>();
|
||||
decimal totalCost = 0m, totalOpening = 0m, totalYear = 0m, totalClosing = 0m;
|
||||
foreach (var group in assets.Where(a => a.PurchaseDate <= yearEnd).GroupBy(a => a.CategoryId).OrderBy(g => categories[g.Key].Code, StringComparer.Ordinal))
|
||||
{
|
||||
var category = categories[group.Key];
|
||||
rows.Add(["**" + category.Code, category.Description, null, null, null, null, null, null, null]);
|
||||
foreach (var asset in group)
|
||||
{
|
||||
var own = movements.Where(m => m.AssetId == asset.Id).ToList();
|
||||
var cost = own.Where(m => m.MovementDate <= yearEnd).Sum(m => m.CostAmount);
|
||||
var opening = own.Where(m => m.Year < year || (m.Kind == AssetMovementKind.Opening && m.Year <= year)).Sum(m => m.CivilAmount);
|
||||
var depreciation = own.Where(m => m.Year == year && m.Kind == AssetMovementKind.Depreciation).Sum(m => m.CivilAmount);
|
||||
var disposed = own.Where(m => m.Year == year && m.Kind is AssetMovementKind.Disposal or AssetMovementKind.PartialDisposal).Sum(m => m.CivilAmount);
|
||||
var closing = opening + depreciation + disposed;
|
||||
var rate = depreciation == 0m ? null : (asset.CivilRate ?? category.CivilRate).ToString("0.##", CultureInfo.InvariantCulture) + "%";
|
||||
rows.Add([asset.Code, asset.Description, LedgerReport.Date(asset.InServiceDate), LedgerReport.Money(cost), LedgerReport.Money(opening), rate,
|
||||
LedgerReport.Money(depreciation), LedgerReport.Money(closing), LedgerReport.Money(cost - closing)]);
|
||||
totalCost += cost;
|
||||
totalOpening += opening;
|
||||
totalYear += depreciation;
|
||||
totalClosing += closing;
|
||||
}
|
||||
}
|
||||
|
||||
rows.Add(["**Totali", null, null, LedgerReport.Money(totalCost), LedgerReport.Money(totalOpening), null, LedgerReport.Money(totalYear), LedgerReport.Money(totalClosing),
|
||||
LedgerReport.Money(totalCost - totalClosing)]);
|
||||
var (file, pages) = await LedgerReport.WriteAsync(
|
||||
VatService.CompanyLine(profile),
|
||||
"Registro dei beni ammortizzabili",
|
||||
"Esercizio " + year.ToString(CultureInfo.InvariantCulture) + " - ammortamenti civilistici",
|
||||
[new("Codice", 60), new("Descrizione", 230), new("In uso dal", 60), new("Costo", 80, true), new("Fondo iniziale", 80, true), new("Aliquota", 50, true),
|
||||
new("Ammortamento", 80, true), new("Fondo finale", 80, true), new("Residuo", 80, true)],
|
||||
rows,
|
||||
year,
|
||||
firstPage,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return (new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"registro_cespiti_{year}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file), pages);
|
||||
}
|
||||
|
||||
internal static async Task<IReadOnlyList<FixedAssetCategory>> CategoriesAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<FixedAssetCategory, long>().ListAsync(Query.For<FixedAssetCategory>().OrderBy(c => c.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
|
||||
internal static async Task<int> CreateStandardCategoriesAsync(
|
||||
IUnitOfWork uow, IReadOnlyList<DepreciationCoefficient> coefficients, string? userName, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var existing = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).Select(c => c.Code).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var created = 0;
|
||||
foreach (var c in coefficients.Where(c => !existing.Contains(c.Code)))
|
||||
{
|
||||
var category = new FixedAssetCategory
|
||||
{
|
||||
Code = c.Code,
|
||||
Description = c.Description,
|
||||
Class = c.Intangible ? AssetClass.Intangible : AssetClass.Tangible,
|
||||
MinisterialGroup = c.Group.Length <= 20 ? c.Group : c.Group[..20],
|
||||
CivilRate = c.Rate,
|
||||
FiscalRate = c.Rate,
|
||||
CivilHalfFirstYear = !c.Intangible && c.Rate < 100m,
|
||||
AssetAccountId = accounts.TryGetValue(c.AssetAccount, out var a) ? a.Id : null,
|
||||
FundAccountId = accounts.TryGetValue(c.FundAccount, out var f) ? f.Id : null,
|
||||
DepreciationAccountId = accounts.TryGetValue(c.DepreciationAccount, out var d) ? d.Id : null,
|
||||
DeductiblePercent = c.DeductiblePercent,
|
||||
CostLimit = c.CostLimit,
|
||||
IsDemo = isDemo,
|
||||
};
|
||||
category.Id = await uow.Repository<FixedAssetCategory, long>().InsertAsync(category, cancellationToken).ConfigureAwait(false);
|
||||
created++;
|
||||
}
|
||||
|
||||
_ = userName;
|
||||
return created;
|
||||
}
|
||||
|
||||
internal static async Task<FixedAsset> SaveAsync(IUnitOfWork uow, IFixedAssetRules rules, AssetInput input, string? userName, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var description = (input.Description ?? string.Empty).Trim();
|
||||
if (description.Length == 0)
|
||||
{
|
||||
errors.Add("Description:" + YearEndErrors.DescriptionRequired);
|
||||
}
|
||||
|
||||
if (input.Cost <= 0m)
|
||||
{
|
||||
errors.Add("Cost:" + YearEndErrors.CostRequired);
|
||||
}
|
||||
|
||||
if (input.InServiceDate < input.PurchaseDate)
|
||||
{
|
||||
errors.Add("InServiceDate:" + YearEndErrors.ServiceBeforePurchase);
|
||||
}
|
||||
|
||||
if (input.OpeningCivilFund > input.Cost || input.OpeningFiscalFund > input.Cost || input.OpeningCivilFund < 0m || input.OpeningFiscalFund < 0m)
|
||||
{
|
||||
errors.Add("OpeningCivilFund:" + YearEndErrors.FundTooHigh);
|
||||
}
|
||||
|
||||
if (input.CivilRate is < 0m or > 100m || input.FiscalRate is < 0m or > 100m)
|
||||
{
|
||||
errors.Add("CivilRate:" + YearEndErrors.RateRange);
|
||||
}
|
||||
|
||||
var category = await uow.Repository<FixedAssetCategory, long>().GetAsync(input.CategoryId, cancellationToken).ConfigureAwait(false);
|
||||
if (category is null)
|
||||
{
|
||||
errors.Add("CategoryId:" + YearEndErrors.CategoryRequired);
|
||||
}
|
||||
|
||||
var assets = uow.Repository<FixedAsset, long>();
|
||||
var code = (input.Code ?? string.Empty).Trim().ToUpperInvariant();
|
||||
if (code.Length == 0)
|
||||
{
|
||||
var count = await assets.CountAsync(Query.For<FixedAsset>(), cancellationToken).ConfigureAwait(false);
|
||||
code = string.Create(CultureInfo.InvariantCulture, $"CE{count + 1:00000}");
|
||||
while (await assets.CountAsync(Query.For<FixedAsset>().Where(a => a.Code == code), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
count++;
|
||||
code = string.Create(CultureInfo.InvariantCulture, $"CE{count + 1:00000}");
|
||||
}
|
||||
}
|
||||
|
||||
var id = input.Id ?? 0L;
|
||||
if (await assets.CountAsync(Query.For<FixedAsset>().Where(a => a.Code == code && a.Id != id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
errors.Add("Code:" + YearEndErrors.CodeTaken);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
FixedAsset? before = input.Id is { } existing
|
||||
? await assets.GetAsync(existing, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound)
|
||||
: null;
|
||||
var posted = before is not null && await uow.Repository<FixedAssetMovement, long>().CountAsync(
|
||||
Query.For<FixedAssetMovement>().Where(m => m.AssetId == id && m.Kind != AssetMovementKind.Purchase && m.Kind != AssetMovementKind.Opening), cancellationToken).ConfigureAwait(false) > 0;
|
||||
if (posted && (before!.Cost != input.Cost || before.CategoryId != input.CategoryId || before.InServiceDate != input.InServiceDate))
|
||||
{
|
||||
throw new ValidationFailedException(["Cost:" + YearEndErrors.AssetPosted]);
|
||||
}
|
||||
|
||||
var asset = before ?? new FixedAsset { Status = AssetStatus.Active, IsDemo = isDemo };
|
||||
asset.Code = code;
|
||||
asset.Description = LedgerStore.Trim(description, 200)!;
|
||||
asset.CategoryId = input.CategoryId;
|
||||
asset.PurchaseDate = input.PurchaseDate;
|
||||
asset.InServiceDate = input.InServiceDate;
|
||||
asset.SupplierId = input.SupplierId;
|
||||
asset.DocumentReference = LedgerStore.Trim(input.DocumentReference?.Trim(), 60);
|
||||
asset.Location = LedgerStore.Trim(input.Location?.Trim(), 100);
|
||||
asset.SerialNumber = LedgerStore.Trim(input.SerialNumber?.Trim(), 60);
|
||||
asset.Quantity = input.Quantity <= 0m ? 1m : input.Quantity;
|
||||
asset.CivilRate = input.CivilRate;
|
||||
asset.FiscalRate = input.FiscalRate;
|
||||
asset.ResidualValue = Math.Max(0m, input.ResidualValue);
|
||||
asset.LowValue = category!.CivilRate >= 100m;
|
||||
asset.Notes = LedgerStore.Trim(input.Notes?.Trim(), 500);
|
||||
if (!posted)
|
||||
{
|
||||
asset.Cost = input.Cost;
|
||||
asset.CivilFund = input.OpeningCivilFund;
|
||||
asset.FiscalFund = input.OpeningFiscalFund;
|
||||
asset.LastDepreciationYear = input.LastDepreciationYear;
|
||||
}
|
||||
|
||||
var movements = uow.Repository<FixedAssetMovement, long>();
|
||||
if (before is null)
|
||||
{
|
||||
asset.Id = await assets.InsertAsync(asset, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await assets.UpdateAsync(asset, cancellationToken).ConfigureAwait(false);
|
||||
if (!posted)
|
||||
{
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM fixed_asset_movements WHERE asset_id = {asset.Id} AND gl_entry_id IS NULL"), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!posted)
|
||||
{
|
||||
await movements.InsertAsync(new FixedAssetMovement
|
||||
{
|
||||
AssetId = asset.Id,
|
||||
Kind = AssetMovementKind.Purchase,
|
||||
MovementDate = asset.PurchaseDate,
|
||||
Year = asset.PurchaseDate.Year,
|
||||
CostAmount = asset.Cost,
|
||||
Description = asset.DocumentReference,
|
||||
IsDemo = asset.IsDemo,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
if (asset.CivilFund != 0m || asset.FiscalFund != 0m)
|
||||
{
|
||||
var year = asset.LastDepreciationYear ?? asset.PurchaseDate.Year;
|
||||
await movements.InsertAsync(new FixedAssetMovement
|
||||
{
|
||||
AssetId = asset.Id,
|
||||
Kind = AssetMovementKind.Opening,
|
||||
MovementDate = new DateOnly(year, 12, 31),
|
||||
Year = year,
|
||||
CivilAmount = asset.CivilFund,
|
||||
FiscalAmount = asset.FiscalFund,
|
||||
Description = "Fondo ammortamento iniziale",
|
||||
IsDemo = asset.IsDemo,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
_ = userName;
|
||||
return asset;
|
||||
}
|
||||
|
||||
internal static async Task<IReadOnlyList<DepreciationLine>> DepreciationAsync(IUnitOfWork uow, IFixedAssetRules rules, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Id);
|
||||
var assets = (await uow.Repository<FixedAsset, long>().ListAsync(Query.For<FixedAsset>().OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var kind = AssetMovementKind.Depreciation;
|
||||
var movements = (await uow.Repository<FixedAssetMovement, long>().ListAsync(
|
||||
Query.For<FixedAssetMovement>().Where(m => m.Year == year && m.Kind == kind), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var lines = new List<DepreciationLine>();
|
||||
foreach (var asset in assets)
|
||||
{
|
||||
var category = categories[asset.CategoryId];
|
||||
var done = movements.Where(m => m.AssetId == asset.Id).ToList();
|
||||
if (done.Count > 0)
|
||||
{
|
||||
var civil = done.Sum(m => m.CivilAmount);
|
||||
var fiscal = done.Sum(m => m.FiscalAmount);
|
||||
lines.Add(new DepreciationLine(asset.Id, asset.Code, asset.Description, category.Code, asset.Cost, asset.CivilFund - civil,
|
||||
DepreciationCalculator.RateOf(Civil(asset, category), year), civil, DepreciationCalculator.RateOf(Fiscal(asset, category, rules), year), fiscal, true));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (asset.Status == AssetStatus.Disposed || (asset.LastDepreciationYear is { } last && last >= year) || asset.InServiceDate.Year > year)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var civilBasis = Civil(asset, category);
|
||||
var fiscalBasis = Fiscal(asset, category, rules);
|
||||
var civilAmount = DepreciationCalculator.Yearly(civilBasis, year, asset.CivilFund);
|
||||
var fiscalAmount = DepreciationCalculator.Yearly(fiscalBasis, year, asset.FiscalFund);
|
||||
if (civilAmount == 0m && fiscalAmount == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
lines.Add(new DepreciationLine(asset.Id, asset.Code, asset.Description, category.Code, asset.Cost, asset.CivilFund,
|
||||
DepreciationCalculator.RateOf(civilBasis, year), civilAmount, DepreciationCalculator.RateOf(fiscalBasis, year), fiscalAmount, false));
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>Posts the depreciation not yet posted of a year in one entry; returns the amount and the entry.</summary>
|
||||
internal static async Task<(decimal Amount, GlEntry? Entry)> DepreciateAsync(
|
||||
IUnitOfWork uow, IFixedAssetRules rules, int year, DateOnly date, int? closingStep, string? userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var lines = (await DepreciationAsync(uow, rules, year, cancellationToken).ConfigureAwait(false)).Where(l => !l.Posted).ToList();
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
return (0m, null);
|
||||
}
|
||||
|
||||
var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Code, StringComparer.Ordinal);
|
||||
foreach (var category in lines.Select(l => categories[l.CategoryCode]).Distinct())
|
||||
{
|
||||
if (category.FundAccountId is null || category.DepreciationAccountId is null)
|
||||
{
|
||||
throw new ValidationFailedException(["CategoryId:" + YearEndErrors.CategoryAccounts + ":" + category.Code]);
|
||||
}
|
||||
}
|
||||
|
||||
var drafts = new List<EntryLineDraft>();
|
||||
foreach (var group in lines.Where(l => l.Civil != 0m).GroupBy(l => l.CategoryCode).OrderBy(g => g.Key, StringComparer.Ordinal))
|
||||
{
|
||||
var category = categories[group.Key];
|
||||
var amount = group.Sum(l => l.Civil);
|
||||
var text = "Ammortamento " + category.Description;
|
||||
drafts.Add(YearEndLedger.Debit(category.DepreciationAccountId!.Value, amount, text));
|
||||
drafts.Add(YearEndLedger.Credit(category.FundAccountId!.Value, amount, text));
|
||||
}
|
||||
|
||||
var assets = uow.Repository<FixedAsset, long>();
|
||||
var isDemo = false;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var asset = await assets.GetAsync(line.AssetId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
isDemo |= asset.IsDemo;
|
||||
}
|
||||
|
||||
var entry = await YearEndLedger.PostAsync(
|
||||
uow, date, "Ammortamenti dell'esercizio " + year.ToString(CultureInfo.InvariantCulture), GlEntrySource.FixedAsset, closingStep, drafts, isDemo, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var asset = await assets.GetAsync(line.AssetId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
asset.CivilFund += line.Civil;
|
||||
asset.FiscalFund += line.Fiscal;
|
||||
asset.LastDepreciationYear = year;
|
||||
if (asset.CivilFund >= asset.Cost - asset.ResidualValue)
|
||||
{
|
||||
asset.Status = AssetStatus.Depreciated;
|
||||
}
|
||||
|
||||
await assets.UpdateAsync(asset, cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<FixedAssetMovement, long>().InsertAsync(new FixedAssetMovement
|
||||
{
|
||||
AssetId = asset.Id,
|
||||
Kind = AssetMovementKind.Depreciation,
|
||||
MovementDate = date,
|
||||
Year = year,
|
||||
CivilAmount = line.Civil,
|
||||
FiscalAmount = line.Fiscal,
|
||||
Description = "Ammortamento " + year.ToString(CultureInfo.InvariantCulture),
|
||||
GlEntryId = entry?.Id,
|
||||
IsDemo = asset.IsDemo,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_ = userName;
|
||||
return (lines.Sum(l => l.Civil), entry);
|
||||
}
|
||||
|
||||
/// <summary>Removes the depreciation of a year: movements, funds and entry.</summary>
|
||||
internal static async Task UndoDepreciationAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var kind = AssetMovementKind.Depreciation;
|
||||
var later = await uow.Repository<FixedAssetMovement, long>().CountAsync(
|
||||
Query.For<FixedAssetMovement>().Where(m => m.Year > year && m.Kind == kind), cancellationToken).ConfigureAwait(false);
|
||||
if (later > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Year:" + YearEndErrors.LaterDepreciation]);
|
||||
}
|
||||
|
||||
var movements = (await uow.Repository<FixedAssetMovement, long>().ListAsync(
|
||||
Query.For<FixedAssetMovement>().Where(m => m.Year == year && m.Kind == kind), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var entries = movements.Where(m => m.GlEntryId is not null).Select(m => m.GlEntryId!.Value).Distinct().ToList();
|
||||
var assets = uow.Repository<FixedAsset, long>();
|
||||
foreach (var movement in movements)
|
||||
{
|
||||
var asset = await assets.GetAsync(movement.AssetId, cancellationToken).ConfigureAwait(false);
|
||||
if (asset is not null)
|
||||
{
|
||||
asset.CivilFund -= movement.CivilAmount;
|
||||
asset.FiscalFund -= movement.FiscalAmount;
|
||||
asset.LastDepreciationYear = year - 1 < asset.InServiceDate.Year ? null : year - 1;
|
||||
if (asset.Status == AssetStatus.Depreciated)
|
||||
{
|
||||
asset.Status = AssetStatus.Active;
|
||||
}
|
||||
|
||||
await assets.UpdateAsync(asset, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.Repository<FixedAssetMovement, long>().DeleteAsync(movement.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The movements pointed to the entries: these go last.
|
||||
await YearEndLedger.DeleteAsync(uow, entries, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task DisposeAsync(IUnitOfWork uow, YearEndAccountCodes codes, long id, DisposalInput input, string? userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var asset = await uow.Repository<FixedAsset, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (asset.Status == AssetStatus.Disposed)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.Disposed]);
|
||||
}
|
||||
|
||||
var costDisposed = input.CostDisposed ?? asset.Cost;
|
||||
if (costDisposed <= 0m || costDisposed > asset.Cost)
|
||||
{
|
||||
throw new ValidationFailedException(["CostDisposed:" + YearEndErrors.DisposalTooHigh]);
|
||||
}
|
||||
|
||||
if (input.Proceeds < 0m)
|
||||
{
|
||||
throw new ValidationFailedException(["Proceeds:" + YearEndErrors.AmountRequired]);
|
||||
}
|
||||
|
||||
var category = await uow.Repository<FixedAssetCategory, long>().GetAsync(asset.CategoryId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (category.AssetAccountId is null || category.FundAccountId is null)
|
||||
{
|
||||
throw new ValidationFailedException(["CategoryId:" + YearEndErrors.CategoryAccounts + ":" + category.Code]);
|
||||
}
|
||||
|
||||
var whole = costDisposed == asset.Cost;
|
||||
var civilFund = whole ? asset.CivilFund : DepreciationCalculator.FundShare(asset.Cost, asset.CivilFund, costDisposed);
|
||||
var fiscalFund = whole ? asset.FiscalFund : DepreciationCalculator.FundShare(asset.Cost, asset.FiscalFund, costDisposed);
|
||||
var gainLoss = DepreciationCalculator.GainLoss(costDisposed, civilFund, input.Proceeds);
|
||||
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var counterpart = input.CounterpartAccountId ?? YearEndLedger.Require(accounts, codes.OtherReceivables).Id;
|
||||
var text = (whole ? "Cessione cespite " : "Cessione parziale cespite ") + asset.Code + " " + asset.Description;
|
||||
var lines = new List<EntryLineDraft>
|
||||
{
|
||||
YearEndLedger.Debit(category.FundAccountId.Value, civilFund, text),
|
||||
YearEndLedger.Debit(counterpart, input.Proceeds, text),
|
||||
YearEndLedger.Credit(category.AssetAccountId.Value, costDisposed, text),
|
||||
};
|
||||
if (gainLoss > 0m)
|
||||
{
|
||||
lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.Gains).Id, gainLoss, "Plusvalenza " + asset.Code));
|
||||
}
|
||||
else if (gainLoss < 0m)
|
||||
{
|
||||
lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.Losses).Id, -gainLoss, "Minusvalenza " + asset.Code));
|
||||
}
|
||||
|
||||
var entry = await YearEndLedger.PostAsync(uow, input.Date, text, GlEntrySource.FixedAsset, null, lines, asset.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<FixedAssetMovement, long>().InsertAsync(new FixedAssetMovement
|
||||
{
|
||||
AssetId = asset.Id,
|
||||
Kind = whole ? AssetMovementKind.Disposal : AssetMovementKind.PartialDisposal,
|
||||
MovementDate = input.Date,
|
||||
Year = input.Date.Year,
|
||||
CostAmount = -costDisposed,
|
||||
CivilAmount = -civilFund,
|
||||
FiscalAmount = -fiscalFund,
|
||||
Proceeds = input.Proceeds,
|
||||
GainLoss = gainLoss,
|
||||
Description = text.Length <= 200 ? text : text[..200],
|
||||
GlEntryId = entry?.Id,
|
||||
IsDemo = asset.IsDemo,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
asset.Cost -= costDisposed;
|
||||
asset.CivilFund -= civilFund;
|
||||
asset.FiscalFund -= fiscalFund;
|
||||
if (whole)
|
||||
{
|
||||
asset.Status = AssetStatus.Disposed;
|
||||
asset.DisposalDate = input.Date;
|
||||
}
|
||||
|
||||
await uow.Repository<FixedAsset, long>().UpdateAsync(asset, cancellationToken).ConfigureAwait(false);
|
||||
_ = userName;
|
||||
}
|
||||
|
||||
private static async Task<AssetView?> ViewAsync(IUnitOfWork uow, IFixedAssetRules rules, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<FixedAsset, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } asset)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var category = await uow.Repository<FixedAssetCategory, long>().GetAsync(asset.CategoryId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
var movements = (await uow.Repository<FixedAssetMovement, long>().ListAsync(
|
||||
Query.For<FixedAssetMovement>().Where(m => m.AssetId == id).OrderBy(m => m.MovementDate).OrderBy(m => m.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var names = await JournalEntryService.PartyNamesAsync(uow, [asset.SupplierId], cancellationToken).ConfigureAwait(false);
|
||||
var opening = movements.Where(m => m.Kind == AssetMovementKind.Opening).ToList();
|
||||
var startYear = asset.InServiceDate.Year;
|
||||
var civilStart = 0m;
|
||||
var fiscalStart = 0m;
|
||||
if (opening.Count > 0)
|
||||
{
|
||||
startYear = opening.Max(m => m.Year) + 1;
|
||||
civilStart = opening.Sum(m => m.CivilAmount);
|
||||
fiscalStart = opening.Sum(m => m.FiscalAmount);
|
||||
}
|
||||
|
||||
var cost = movements.Where(m => m.Kind is AssetMovementKind.Purchase or AssetMovementKind.Increase or AssetMovementKind.Revaluation).Sum(m => m.CostAmount);
|
||||
var civil = Civil(asset, category) with { Cost = cost };
|
||||
var fiscal = Fiscal(asset, category, rules) with { Cost = Math.Min(cost, category.CostLimit ?? decimal.MaxValue) };
|
||||
return new AssetView(
|
||||
asset, category, asset.SupplierId is { } p && names.TryGetValue(p, out var n) ? n : null, movements,
|
||||
DepreciationCalculator.Plan(civil, startYear, civilStart), DepreciationCalculator.Plan(fiscal, startYear, fiscalStart));
|
||||
}
|
||||
|
||||
private static DepreciationBasis Civil(FixedAsset asset, FixedAssetCategory category) =>
|
||||
new(asset.Cost, asset.ResidualValue, asset.CivilRate ?? category.CivilRate, asset.InServiceDate.Year, category.CivilHalfFirstYear, asset.LowValue);
|
||||
|
||||
private static DepreciationBasis Fiscal(FixedAsset asset, FixedAssetCategory category, IFixedAssetRules rules) =>
|
||||
new(Math.Min(asset.Cost, category.CostLimit ?? decimal.MaxValue), 0m, asset.FiscalRate ?? category.FiscalRate, asset.InServiceDate.Year,
|
||||
category.Class == AssetClass.Tangible && rules.FirstYearFactor < 1m, asset.LowValue);
|
||||
|
||||
private async Task<DateOnly> YearEndDateAsync(string company, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var first = new DateOnly(year, 1, 1);
|
||||
var last = new DateOnly(year, 12, 31);
|
||||
var fiscalYear = await uow.Repository<FiscalYear, long>().FindAsync(
|
||||
Query.For<FiscalYear>().Where(y => y.EndDate >= first && y.EndDate <= last).OrderByDescending(y => y.EndDate), cancellationToken).ConfigureAwait(false);
|
||||
return fiscalYear?.EndDate ?? new DateOnly(year, 12, 31);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>A declaration with the name of its party.</summary>
|
||||
/// <param name="Declaration">The declaration.</param>
|
||||
/// <param name="PartyName">The customer or supplier.</param>
|
||||
/// <param name="PartyCode">Its code.</param>
|
||||
/// <param name="Warning">The ceiling used is above the warning share.</param>
|
||||
public sealed record IntentRow(IntentDeclaration Declaration, string PartyName, string PartyCode, bool Warning);
|
||||
|
||||
/// <summary>A declaration being recorded.</summary>
|
||||
/// <param name="Id">The declaration, for a change.</param>
|
||||
/// <param name="Direction">Received or issued.</param>
|
||||
/// <param name="PartyId">The customer or supplier.</param>
|
||||
/// <param name="Number">The number of the declarant.</param>
|
||||
/// <param name="DeclarationDate">The day of the declaration.</param>
|
||||
/// <param name="Protocol">The protocol of the receipt.</param>
|
||||
/// <param name="Ceiling">The ceiling.</param>
|
||||
/// <param name="ValidFrom">The first day it covers.</param>
|
||||
/// <param name="ValidTo">The last day it covers.</param>
|
||||
public sealed record IntentInput(
|
||||
long? Id, IntentDirection Direction, long PartyId, string Number, DateOnly DeclarationDate, string Protocol, decimal Ceiling, DateOnly ValidFrom, DateOnly ValidTo)
|
||||
{
|
||||
/// <summary>The VAT code of the sales (nature N3.5).</summary>
|
||||
public long? TaxCodeId { get; init; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; init; }
|
||||
|
||||
/// <summary>The ceiling used, for an issued declaration (the company's own plafond).</summary>
|
||||
public decimal Used { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What a declaration covers for a sale being written.</summary>
|
||||
/// <param name="Declaration">The declaration, if any covers the day.</param>
|
||||
/// <param name="Warning">The ceiling used is above the warning share.</param>
|
||||
public sealed record IntentCoverage(IntentDeclaration? Declaration, bool Warning);
|
||||
|
||||
/// <summary>
|
||||
/// The declarations of intent (SPEC §11.7, issue #83, mockup 061, ADR 0042): the chronological register of the
|
||||
/// declarations received from habitual exporters (and of those issued), the ceiling each declaration consumes with the
|
||||
/// sales of nature N3.5, the warning from 90% and the refusal of a sale above the ceiling when the invoice is issued. The
|
||||
/// party keeps a mirror of its current declaration for the documents and the e-invoice.
|
||||
/// </summary>
|
||||
public sealed class IntentDeclarationService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly AuditTrail _audit;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
public IntentDeclarationService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
_audit = audit;
|
||||
}
|
||||
|
||||
/// <summary>The register of a year, in chronological order.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="direction">Received or issued.</param>
|
||||
/// <param name="year">The year; every year when <see langword="null"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The declarations.</returns>
|
||||
public async Task<IReadOnlyList<IntentRow>> ListAsync(
|
||||
Actor actor, string companyCode, IntentDirection direction, int? year = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentRead, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
if (await PendingAdoptionAsync(uow, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// The declarations typed on the parties before the register existed join it the first time it is read.
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await AdoptAsync(uow, rules, null, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var query = Query.For<IntentDeclaration>().Where(d => d.Direction == direction);
|
||||
if (year is { } y)
|
||||
{
|
||||
query = query.Where(d => d.Year == y);
|
||||
}
|
||||
|
||||
var declarations = (await uow.Repository<IntentDeclaration, long>().ListAsync(
|
||||
query.OrderByDescending(d => d.Year).OrderByDescending(d => d.RegisterNumber), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var ids = declarations.Select(d => d.PartyId).Distinct().ToList();
|
||||
var parties = ids.Count == 0
|
||||
? []
|
||||
: (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => ids.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(p => p.Id);
|
||||
return [.. declarations.Select(d => new IntentRow(
|
||||
d, parties.TryGetValue(d.PartyId, out var p) ? p.Name : string.Empty, parties.TryGetValue(d.PartyId, out var q) ? q.Code : string.Empty,
|
||||
d.Status == IntentStatus.Active && d.UsedPercent >= rules.WarningPercent))];
|
||||
}
|
||||
|
||||
/// <summary>A declaration.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The declaration.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The declaration, or none.</returns>
|
||||
public async Task<IntentDeclaration?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await uow.Repository<IntentDeclaration, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The declaration that covers a sale of a customer on a day.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="partyId">The customer.</param>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The coverage.</returns>
|
||||
public async Task<IntentCoverage> CoverageAsync(Actor actor, string companyCode, long partyId, DateOnly date, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "sales.invoice.read", cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var declaration = Covering(await ReceivedAsync(uow, partyId, cancellationToken).ConfigureAwait(false), date);
|
||||
return new IntentCoverage(declaration, declaration is not null && declaration.UsedPercent >= rules.WarningPercent);
|
||||
}
|
||||
|
||||
/// <summary>Records a declaration or changes one; the register number follows the year.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The declaration.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The declaration as saved.</returns>
|
||||
public async Task<IntentDeclaration> SaveAsync(Actor actor, string companyCode, IntentInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentWrite, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var declaration = await SaveAsync(uow, rules, input, actor.UserName, false, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return declaration;
|
||||
}
|
||||
|
||||
/// <summary>Revokes a declaration: it no longer covers sales.</summary>
|
||||
/// <param name="actor">Who revokes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The declaration.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task RevokeAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentWrite, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<IntentDeclaration, long>();
|
||||
var declaration = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
var before = Copy(declaration);
|
||||
declaration.Status = IntentStatus.Revoked;
|
||||
await repository.UpdateAsync(declaration, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, id, before, declaration, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
if (declaration.Direction == IntentDirection.Received)
|
||||
{
|
||||
await SyncPartyAsync(uow, rules, declaration.PartyId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Removes a declaration that no sale used.</summary>
|
||||
/// <param name="actor">Who removes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The declaration.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentWrite, cancellationToken).ConfigureAwait(false);
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<IntentDeclaration, long>();
|
||||
var declaration = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (declaration.Used != 0m && declaration.Direction == IntentDirection.Received)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.DeclarationUsed]);
|
||||
}
|
||||
|
||||
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, declaration, (IntentDeclaration?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
if (declaration.Direction == IntentDirection.Received)
|
||||
{
|
||||
await SyncPartyAsync(uow, rules, declaration.PartyId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The register of a year as PDF.</summary>
|
||||
/// <param name="actor">Who prints.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="direction">Received or issued.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> PrintRegisterAsync(Actor actor, string companyCode, IntentDirection direction, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = (await ListAsync(actor, companyCode, direction, year, cancellationToken).ConfigureAwait(false)).OrderBy(r => r.Declaration.RegisterNumber).ToList();
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var lines = rows.Select(r => (IReadOnlyList<string?>)[
|
||||
r.Declaration.RegisterNumber.ToString(CultureInfo.InvariantCulture), LedgerReport.Date(r.Declaration.DeclarationDate), r.Declaration.Number,
|
||||
r.Declaration.Protocol, r.PartyName, LedgerReport.Date(r.Declaration.ValidFrom) + " - " + LedgerReport.Date(r.Declaration.ValidTo),
|
||||
LedgerReport.Money(r.Declaration.Ceiling), LedgerReport.Money(r.Declaration.Used), LedgerReport.Money(r.Declaration.Remaining),
|
||||
]).ToList();
|
||||
lines.Add(["**Totali", null, null, null, null, null, LedgerReport.Money(rows.Sum(r => r.Declaration.Ceiling)), LedgerReport.Money(rows.Sum(r => r.Declaration.Used)),
|
||||
LedgerReport.Money(rows.Sum(r => r.Declaration.Remaining))]);
|
||||
var (file, _) = await LedgerReport.WriteAsync(
|
||||
VatService.CompanyLine(profile),
|
||||
direction == IntentDirection.Received ? "Registro delle dichiarazioni d'intento ricevute" : "Registro delle dichiarazioni d'intento emesse",
|
||||
"Anno " + year.ToString(CultureInfo.InvariantCulture),
|
||||
[new("N.", 30), new("Data", 55), new("Numero", 70), new("Protocollo", 140), new("Controparte", 190), new("Validità", 115), new("Plafond", 75, true),
|
||||
new("Utilizzato", 75, true), new("Residuo", 75, true)],
|
||||
lines,
|
||||
year,
|
||||
1,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(
|
||||
string.Create(CultureInfo.InvariantCulture, $"dichiarazioni_intento_{(direction == IntentDirection.Received ? "ricevute" : "emesse")}_{year}.pdf"),
|
||||
Infrastructure.Files.PdfWriter.MediaType,
|
||||
file);
|
||||
}
|
||||
|
||||
internal static async Task<IntentDeclaration> SaveAsync(IUnitOfWork uow, IIntentRules rules, IntentInput input, string? userName, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var number = (input.Number ?? string.Empty).Trim();
|
||||
var protocol = (input.Protocol ?? string.Empty).Trim();
|
||||
if (input.PartyId <= 0)
|
||||
{
|
||||
errors.Add("PartyId:" + YearEndErrors.PartyRequired);
|
||||
}
|
||||
|
||||
if (number.Length == 0)
|
||||
{
|
||||
errors.Add("Number:" + YearEndErrors.NumberRequired);
|
||||
}
|
||||
|
||||
if (!rules.ValidProtocol(protocol))
|
||||
{
|
||||
errors.Add("Protocol:" + YearEndErrors.ProtocolInvalid);
|
||||
}
|
||||
|
||||
if (input.Ceiling <= 0m)
|
||||
{
|
||||
errors.Add("Ceiling:" + YearEndErrors.CeilingRequired);
|
||||
}
|
||||
|
||||
if (input.ValidTo < input.ValidFrom)
|
||||
{
|
||||
errors.Add("ValidTo:" + YearEndErrors.ValidityOrder);
|
||||
}
|
||||
|
||||
if (input.TaxCodeId is { } taxCodeId)
|
||||
{
|
||||
var taxCode = await uow.Repository<TaxCode, long>().GetAsync(taxCodeId, cancellationToken).ConfigureAwait(false);
|
||||
if (taxCode?.Nature != rules.Nature)
|
||||
{
|
||||
errors.Add("TaxCodeId:" + YearEndErrors.TaxCodeNature);
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
var repository = uow.Repository<IntentDeclaration, long>();
|
||||
IntentDeclaration? before = input.Id is { } id
|
||||
? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound)
|
||||
: null;
|
||||
var declaration = before is null ? new IntentDeclaration { Status = IntentStatus.Active, IsDemo = isDemo } : Copy(before);
|
||||
if (before is not null && input.Ceiling < before.Used && before.Direction == IntentDirection.Received)
|
||||
{
|
||||
throw new ValidationFailedException(["Ceiling:" + YearEndErrors.CeilingBelowUsed]);
|
||||
}
|
||||
|
||||
var year = input.DeclarationDate.Year;
|
||||
if (before is null || before.Year != year || before.Direction != input.Direction)
|
||||
{
|
||||
var direction = input.Direction;
|
||||
var last = await repository.FindAsync(
|
||||
Query.For<IntentDeclaration>().Where(d => d.Direction == direction && d.Year == year).OrderByDescending(d => d.RegisterNumber), cancellationToken).ConfigureAwait(false);
|
||||
declaration.RegisterNumber = (last?.RegisterNumber ?? 0) + 1;
|
||||
}
|
||||
|
||||
declaration.Direction = input.Direction;
|
||||
declaration.Year = year;
|
||||
declaration.PartyId = input.PartyId;
|
||||
declaration.Number = LedgerStore.Trim(number, 40)!;
|
||||
declaration.DeclarationDate = input.DeclarationDate;
|
||||
declaration.Protocol = protocol;
|
||||
declaration.Ceiling = input.Ceiling;
|
||||
declaration.ValidFrom = input.ValidFrom;
|
||||
declaration.ValidTo = input.ValidTo;
|
||||
declaration.TaxCodeId = input.TaxCodeId;
|
||||
declaration.Notes = LedgerStore.Trim(input.Notes?.Trim(), 500);
|
||||
if (input.Direction == IntentDirection.Issued)
|
||||
{
|
||||
declaration.Used = Math.Max(0m, input.Used);
|
||||
declaration.Status = declaration.Status == IntentStatus.Revoked ? IntentStatus.Revoked
|
||||
: declaration.Used >= declaration.Ceiling ? IntentStatus.Exhausted : IntentStatus.Active;
|
||||
}
|
||||
|
||||
if (before is null)
|
||||
{
|
||||
declaration.Id = await repository.InsertAsync(declaration, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await repository.UpdateAsync(declaration, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_ = userName;
|
||||
if (declaration.Direction == IntentDirection.Received)
|
||||
{
|
||||
await SyncPartyAsync(uow, rules, declaration.PartyId, cancellationToken).ConfigureAwait(false);
|
||||
if (before is not null && before.PartyId != declaration.PartyId)
|
||||
{
|
||||
await SyncPartyAsync(uow, rules, before.PartyId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return await repository.GetAsync(declaration.Id, cancellationToken).ConfigureAwait(false) ?? declaration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The check of a sale being confirmed (ADR 0042): the lines of nature N3.5 need a declaration that covers the date of
|
||||
/// the document, and the ceiling left must hold them. Credit notes give the ceiling back and are not checked.
|
||||
/// </summary>
|
||||
internal static async Task CheckAsync(IUnitOfWork uow, IIntentRules rules, DocumentBehavior behavior, DocumentRecord record, List<string> errors, CancellationToken cancellationToken)
|
||||
{
|
||||
if (behavior.Direction != DocumentDirection.Sale || record.Family != DocumentFamily.SaleDocument || record.Header.PartyId is not { } partyId
|
||||
|| Sign(record.Header.Kind) <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var amount = await AmountAsync(uow, rules, record.Lines, cancellationToken).ConfigureAwait(false);
|
||||
if (amount <= 0m)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await AdoptAsync(uow, rules, partyId, cancellationToken).ConfigureAwait(false);
|
||||
await SyncPartyAsync(uow, rules, partyId, cancellationToken).ConfigureAwait(false);
|
||||
var declaration = Covering(await ReceivedAsync(uow, partyId, cancellationToken).ConfigureAwait(false), record.Header.DocumentDate);
|
||||
if (declaration is null)
|
||||
{
|
||||
errors.Add("PartyId:" + YearEndErrors.NoDeclaration);
|
||||
}
|
||||
else if (declaration.Used + amount > declaration.Ceiling)
|
||||
{
|
||||
errors.Add("PartyId:" + YearEndErrors.CeilingExceeded);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Recomputes the ceiling used by the sales of a document's customer after it changed state.</summary>
|
||||
internal static async Task SyncDocumentAsync(IUnitOfWork uow, IIntentRules rules, DocumentFamily family, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (family != DocumentFamily.SaleDocument)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var partyId = await uow.QuerySingleAsync<long?>(SqlFragment.Of($"SELECT party_id FROM sale_documents WHERE id = {documentId}"), cancellationToken).ConfigureAwait(false);
|
||||
if (partyId is { } p && await uow.Repository<IntentDeclaration, long>().CountAsync(
|
||||
Query.For<IntentDeclaration>().Where(d => d.PartyId == p), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
await SyncPartyAsync(uow, rules, p, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes the ceiling used by every declaration received from a customer: each sale of nature N3.5 goes to the
|
||||
/// latest declaration that covers its date. Then the party mirrors its latest declaration.
|
||||
/// </summary>
|
||||
internal static async Task SyncPartyAsync(IUnitOfWork uow, IIntentRules rules, long partyId, CancellationToken cancellationToken)
|
||||
{
|
||||
var declarations = await ReceivedAsync(uow, partyId, cancellationToken).ConfigureAwait(false);
|
||||
var draft = nameof(DocumentStatus.Draft);
|
||||
var cancelled = nameof(DocumentStatus.Cancelled);
|
||||
var nature = rules.Nature;
|
||||
var sales = await uow.QueryAsync<UsageRow>(SqlFragment.Of($"""
|
||||
SELECT h.id AS document_id, h.document_date AS document_date, h.kind AS kind, SUM(l.taxable_amount) AS amount
|
||||
FROM sale_documents h JOIN sale_document_lines l ON l.document_id = h.id JOIN tax_codes t ON t.id = l.tax_code_id
|
||||
WHERE h.party_id = {partyId} AND t.nature = {nature} AND h.status <> {draft} AND h.status <> {cancelled}
|
||||
GROUP BY h.id, h.document_date, h.kind
|
||||
"""), cancellationToken).ConfigureAwait(false);
|
||||
var used = declarations.ToDictionary(d => d.Id, _ => 0m);
|
||||
foreach (var sale in sales)
|
||||
{
|
||||
if (Covering(declarations, sale.DocumentDate) is { } declaration)
|
||||
{
|
||||
used[declaration.Id] += Sign(sale.Kind) * (sale.Amount ?? 0m);
|
||||
}
|
||||
}
|
||||
|
||||
var repository = uow.Repository<IntentDeclaration, long>();
|
||||
foreach (var declaration in declarations)
|
||||
{
|
||||
var value = used[declaration.Id];
|
||||
var status = declaration.Status == IntentStatus.Revoked ? IntentStatus.Revoked
|
||||
: value >= declaration.Ceiling ? IntentStatus.Exhausted : IntentStatus.Active;
|
||||
if (declaration.Used != value || declaration.Status != status)
|
||||
{
|
||||
declaration.Used = value;
|
||||
declaration.Status = status;
|
||||
await repository.UpdateAsync(declaration, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == partyId), cancellationToken).ConfigureAwait(false);
|
||||
if (fiscal is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var current = declarations.Where(d => d.Status != IntentStatus.Revoked).OrderByDescending(d => d.ValidFrom).ThenByDescending(d => d.Id).FirstOrDefault();
|
||||
fiscal.IntentActive = current is not null;
|
||||
fiscal.IntentNumber = current?.Number;
|
||||
fiscal.IntentDate = current?.DeclarationDate;
|
||||
fiscal.IntentProtocol = current?.Protocol;
|
||||
fiscal.IntentTaxCodeId = current?.TaxCodeId ?? (current is null ? null : fiscal.IntentTaxCodeId);
|
||||
fiscal.IntentCeiling = current?.Ceiling;
|
||||
fiscal.IntentUsed = current?.Used ?? 0m;
|
||||
fiscal.IntentFrom = current?.ValidFrom;
|
||||
fiscal.IntentTo = current?.ValidTo;
|
||||
await uow.Repository<PartyFiscal, long>().UpdateAsync(fiscal, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns the declarations typed on the parties before the register existed (and those of the demo data) into
|
||||
/// declarations of the register.
|
||||
/// </summary>
|
||||
/// <param name="uow">The unit of work, in a transaction.</param>
|
||||
/// <param name="rules">The rules of the fiscal pack.</param>
|
||||
/// <param name="partyId">Only this party, or every one.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many were adopted.</returns>
|
||||
internal static async Task<int> AdoptAsync(IUnitOfWork uow, IIntentRules rules, long? partyId, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = Query.For<PartyFiscal>().Where(f => f.IntentActive);
|
||||
if (partyId is { } only)
|
||||
{
|
||||
query = query.Where(f => f.PartyId == only);
|
||||
}
|
||||
|
||||
var mirrors = (await uow.Repository<PartyFiscal, long>().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items;
|
||||
var adopted = 0;
|
||||
foreach (var fiscal in mirrors)
|
||||
{
|
||||
var mirrorParty = fiscal.PartyId;
|
||||
if (await uow.Repository<IntentDeclaration, long>().CountAsync(Query.For<IntentDeclaration>().Where(d => d.PartyId == mirrorParty), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var party = await uow.Repository<Party, long>().GetAsync(mirrorParty, cancellationToken).ConfigureAwait(false);
|
||||
var date = fiscal.IntentDate ?? fiscal.IntentFrom ?? new DateOnly(DateTime.UtcNow.Year, 1, 1);
|
||||
var protocol = rules.ValidProtocol(fiscal.IntentProtocol) ? fiscal.IntentProtocol! : new string('0', 17) + "-000000";
|
||||
await SaveAsync(uow, rules, new IntentInput(
|
||||
null, IntentDirection.Received, mirrorParty, fiscal.IntentNumber ?? "-", date, protocol, fiscal.IntentCeiling is > 0m ? fiscal.IntentCeiling.Value : 1m,
|
||||
fiscal.IntentFrom ?? new DateOnly(date.Year, 1, 1), fiscal.IntentTo ?? new DateOnly(date.Year, 12, 31))
|
||||
{
|
||||
TaxCodeId = await NatureCodeAsync(uow, rules, fiscal.IntentTaxCodeId, cancellationToken).ConfigureAwait(false),
|
||||
}, null, party?.IsDemo ?? false, cancellationToken).ConfigureAwait(false);
|
||||
adopted++;
|
||||
}
|
||||
|
||||
return adopted;
|
||||
}
|
||||
|
||||
private static async Task<bool> PendingAdoptionAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
var mirrors = (await uow.Repository<PartyFiscal, long>().ListAsync(Query.For<PartyFiscal>().Where(f => f.IntentActive), cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (mirrors.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var ids = mirrors.Select(f => f.PartyId).ToList();
|
||||
var adopted = (await uow.Repository<IntentDeclaration, long>().ListAsync(Query.For<IntentDeclaration>().Where(d => ids.Contains(d.PartyId)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.Select(d => d.PartyId).ToHashSet();
|
||||
return ids.Any(id => !adopted.Contains(id));
|
||||
}
|
||||
|
||||
private static async Task<long?> NatureCodeAsync(IUnitOfWork uow, IIntentRules rules, long? taxCodeId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (taxCodeId is { } id && (await uow.Repository<TaxCode, long>().GetAsync(id, cancellationToken).ConfigureAwait(false))?.Nature == rules.Nature)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
var nature = rules.Nature;
|
||||
return (await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Nature == nature && !t.Disabled).OrderBy(t => t.Code), cancellationToken)
|
||||
.ConfigureAwait(false))?.Id;
|
||||
}
|
||||
|
||||
private static async Task<decimal> AmountAsync(IUnitOfWork uow, IIntentRules rules, IReadOnlyList<DocumentLine> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
var nature = rules.Nature;
|
||||
var codes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => ids.Contains(t.Id) && t.Nature == nature), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.Select(t => t.Id).ToHashSet();
|
||||
return lines.Where(l => l.TaxCodeId is { } t && codes.Contains(t)).Sum(l => l.TaxableAmount);
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<IntentDeclaration>> ReceivedAsync(IUnitOfWork uow, long partyId, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<IntentDeclaration, long>().ListAsync(
|
||||
Query.For<IntentDeclaration>().Where(d => d.PartyId == partyId && d.Direction == IntentDirection.Received).OrderBy(d => d.ValidFrom).OrderBy(d => d.Id),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
|
||||
private static IntentDeclaration? Covering(IReadOnlyList<IntentDeclaration> declarations, DateOnly date) =>
|
||||
declarations.Where(d => d.Covers(date)).OrderByDescending(d => d.ValidFrom).ThenByDescending(d => d.Id).FirstOrDefault();
|
||||
|
||||
private static int Sign(DocumentKind kind) => kind switch
|
||||
{
|
||||
DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice or DocumentKind.DeferredInvoice or DocumentKind.DownPaymentInvoice or DocumentKind.Fee
|
||||
or DocumentKind.DebitNote => 1,
|
||||
DocumentKind.CreditNote => -1,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
private static IntentDeclaration Copy(IntentDeclaration d) => new()
|
||||
{
|
||||
Id = d.Id,
|
||||
Direction = d.Direction,
|
||||
RegisterNumber = d.RegisterNumber,
|
||||
Year = d.Year,
|
||||
PartyId = d.PartyId,
|
||||
Number = d.Number,
|
||||
DeclarationDate = d.DeclarationDate,
|
||||
Protocol = d.Protocol,
|
||||
Ceiling = d.Ceiling,
|
||||
Used = d.Used,
|
||||
ValidFrom = d.ValidFrom,
|
||||
ValidTo = d.ValidTo,
|
||||
TaxCodeId = d.TaxCodeId,
|
||||
Status = d.Status,
|
||||
Notes = d.Notes,
|
||||
IsDemo = d.IsDemo,
|
||||
RowVersion = d.RowVersion,
|
||||
CreatedAt = d.CreatedAt,
|
||||
CreatedBy = d.CreatedBy,
|
||||
UpdatedAt = d.UpdatedAt,
|
||||
UpdatedBy = d.UpdatedBy,
|
||||
};
|
||||
|
||||
private sealed record UsageRow(long DocumentId, DateOnly DocumentDate, DocumentKind Kind, decimal? Amount);
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>A list with its lines and the names of the parties.</summary>
|
||||
/// <param name="List">The list.</param>
|
||||
/// <param name="Lines">The lines, by section.</param>
|
||||
/// <param name="PartyNames">The names of the parties, by id.</param>
|
||||
public sealed record IntrastatListView(IntrastatList List, IReadOnlyList<IntrastatListLine> Lines, IReadOnlyDictionary<long, string> PartyNames);
|
||||
|
||||
/// <summary>
|
||||
/// The Intrastat lists (SPEC §11.7, issue #83, mockup 049, ADR 0042): the periodicity from the amounts of the four
|
||||
/// quarters before, the lists generated from the confirmed invoices and credit notes with the parties of the other member
|
||||
/// states (goods grouped by party, nomenclature and nature of the transaction; services one line per invoice), the lines
|
||||
/// typed by hand that a new generation keeps, the checks of every line and the file for the customs.
|
||||
/// </summary>
|
||||
public sealed class IntrastatService
|
||||
{
|
||||
private static readonly DocumentKind[] SaleKinds =
|
||||
[DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.DebitNote, DocumentKind.CreditNote];
|
||||
|
||||
private static readonly DocumentKind[] PurchaseKinds = [DocumentKind.PurchaseInvoice, DocumentKind.PurchaseCreditNote];
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public IntrastatService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
_audit = audit;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The lists of a year.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lists, the latest first.</returns>
|
||||
public async Task<IReadOnlyList<IntrastatList>> ListsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return (await uow.Repository<IntrastatList, long>().ListAsync(
|
||||
Query.For<IntrastatList>().Where(l => l.Year == year).OrderByDescending(l => l.Period).OrderBy(l => l.Flow), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>A list with its lines.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The list.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The list, or none.</returns>
|
||||
public async Task<IntrastatListView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>How often the lists of a flow are due in a period, from the four quarters before it.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="flow">Sales or purchases.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="quarter">The quarter, 1-4.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The periodicity of goods and services.</returns>
|
||||
public async Task<IntrastatDue> DueAsync(Actor actor, string companyCode, IntrastatFlow flow, int year, int quarter, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false);
|
||||
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await DueAsync(uow, exporter, flow, year, quarter, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates the list of a period from the documents, keeping the lines typed by hand; a sent list is read only.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who generates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="flow">Sales or purchases.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="periodicity">Monthly or quarterly.</param>
|
||||
/// <param name="period">The month or the quarter.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The list.</returns>
|
||||
public async Task<IntrastatListView> GenerateAsync(
|
||||
Actor actor, string companyCode, IntrastatFlow flow, int year, IntrastatPeriodicity periodicity, int period, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, cancellationToken).ConfigureAwait(false);
|
||||
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
||||
long id;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
id = (await GenerateAsync(uow, exporter, flow, year, periodicity, period, false, cancellationToken).ConfigureAwait(false)).Id;
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Adds or changes a line by hand: a new generation keeps it.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="line">The line; id 0 for a new one.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The list.</returns>
|
||||
public async Task<IntrastatListView> SaveLineAsync(Actor actor, string companyCode, IntrastatListLine line, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(line);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, cancellationToken).ConfigureAwait(false);
|
||||
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var list = await EditableAsync(uow, line.ListId, cancellationToken).ConfigureAwait(false);
|
||||
line.CountryCode = (line.CountryCode ?? string.Empty).Trim().ToUpperInvariant();
|
||||
if (!exporter.MemberStates.Contains(line.CountryCode))
|
||||
{
|
||||
throw new ValidationFailedException(["CountryCode:" + YearEndErrors.CountryNotMember]);
|
||||
}
|
||||
|
||||
if (line.Amount <= 0m)
|
||||
{
|
||||
throw new ValidationFailedException(["Amount:" + YearEndErrors.AmountRequired]);
|
||||
}
|
||||
|
||||
line.Manual = true;
|
||||
line.IsDemo = list.IsDemo;
|
||||
line.VatNumber = Clean(line.VatNumber, 20);
|
||||
line.NomenclatureCode = Clean(line.NomenclatureCode, 10);
|
||||
line.Check = CheckOf(exporter, line);
|
||||
var repository = uow.Repository<IntrastatListLine, long>();
|
||||
if (line.Id == 0)
|
||||
{
|
||||
line.Id = await repository.InsertAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Insert, line.Id, null, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var before = await repository.GetAsync(line.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
line.RowVersion = before.RowVersion;
|
||||
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, line.Id, before, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, line.ListId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Removes a line.</summary>
|
||||
/// <param name="actor">Who removes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteLineAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, 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<IntrastatListLine, long>();
|
||||
var line = await repository.GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
var list = await EditableAsync(uow, line.ListId, cancellationToken).ConfigureAwait(false);
|
||||
await repository.DeleteAsync(lineId, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, lineId, line, (IntrastatListLine?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Writes the file of a list for the customs; refused while lines are incomplete.</summary>
|
||||
/// <param name="actor">Who exports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The list.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> ExportAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatExport, cancellationToken).ConfigureAwait(false);
|
||||
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IIntrastatExporter>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var view = await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
if (view.List.Problems > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.ListIncomplete]);
|
||||
}
|
||||
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
if (string.IsNullOrWhiteSpace(profile?.VatNumber))
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.CompanyVatMissing]);
|
||||
}
|
||||
|
||||
var intrastatReturn = new IntrastatReturn(view.List, view.Lines, profile.VatNumber);
|
||||
var content = exporter.Write(intrastatReturn);
|
||||
var list = view.List;
|
||||
if (list.Status == IntrastatStatus.Draft)
|
||||
{
|
||||
list.Status = IntrastatStatus.Generated;
|
||||
}
|
||||
|
||||
list.GeneratedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
list.FileName = exporter.FileName(intrastatReturn);
|
||||
await uow.Repository<IntrastatList, long>().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(list.FileName, "text/plain", content);
|
||||
}
|
||||
|
||||
/// <summary>Records that a list was sent, with the protocol of the customs: from then on it is read only.</summary>
|
||||
/// <param name="actor">Who records.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The list.</param>
|
||||
/// <param name="protocol">The protocol.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task MarkSentAsync(Actor actor, string companyCode, long id, string? protocol, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatExport, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var list = await EditableAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
list.Status = IntrastatStatus.Sent;
|
||||
list.Protocol = Clean(protocol, 40);
|
||||
await uow.Repository<IntrastatList, long>().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<IntrastatDue> DueAsync(IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, int year, int quarter, CancellationToken cancellationToken)
|
||||
{
|
||||
var goods = 0m;
|
||||
var services = 0m;
|
||||
for (var back = 1; back <= 4; back++)
|
||||
{
|
||||
var q = quarter - back;
|
||||
var y = year;
|
||||
while (q < 1)
|
||||
{
|
||||
q += 4;
|
||||
y--;
|
||||
}
|
||||
|
||||
var from = new DateOnly(y, ((q - 1) * 3) + 1, 1);
|
||||
var lines = await CandidatesAsync(uow, exporter, flow, from, from.AddMonths(3).AddDays(-1), cancellationToken).ConfigureAwait(false);
|
||||
goods = Math.Max(goods, lines.Where(l => l.Section is IntrastatSection.Goods && l.Included).Sum(l => l.Amount));
|
||||
services = Math.Max(services, lines.Where(l => l.Section is IntrastatSection.Services && l.Included).Sum(l => l.Amount));
|
||||
}
|
||||
|
||||
return exporter.Due(flow, goods, services);
|
||||
}
|
||||
|
||||
internal static async Task<IntrastatList> GenerateAsync(
|
||||
IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, int year, IntrastatPeriodicity periodicity, int period, bool isDemo, CancellationToken cancellationToken)
|
||||
{
|
||||
if (periodicity == IntrastatPeriodicity.NotDue || period < 1 || period > (periodicity == IntrastatPeriodicity.Monthly ? 12 : 4))
|
||||
{
|
||||
throw new ValidationFailedException(["Period:" + YearEndErrors.PeriodInvalid]);
|
||||
}
|
||||
|
||||
var lists = uow.Repository<IntrastatList, long>();
|
||||
var list = await lists.FindAsync(
|
||||
Query.For<IntrastatList>().Where(l => l.Flow == flow && l.Year == year && l.Periodicity == periodicity && l.Period == period), cancellationToken).ConfigureAwait(false);
|
||||
if (list is { Status: IntrastatStatus.Sent })
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + YearEndErrors.ListSent]);
|
||||
}
|
||||
|
||||
if (list is null)
|
||||
{
|
||||
var last = await lists.FindAsync(Query.For<IntrastatList>().Where(l => l.Year == year).OrderByDescending(l => l.Progressive), cancellationToken).ConfigureAwait(false);
|
||||
list = new IntrastatList
|
||||
{
|
||||
Flow = flow,
|
||||
Year = year,
|
||||
Period = period,
|
||||
Periodicity = periodicity,
|
||||
Status = IntrastatStatus.Draft,
|
||||
Progressive = (last?.Progressive ?? 0) + 1,
|
||||
IsDemo = isDemo,
|
||||
};
|
||||
list.Id = await lists.InsertAsync(list, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var listId = list.Id;
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM intrastat_list_lines WHERE list_id = {listId} AND manual = {false}"), cancellationToken).ConfigureAwait(false);
|
||||
list.Status = IntrastatStatus.Draft;
|
||||
}
|
||||
|
||||
var from = periodicity == IntrastatPeriodicity.Monthly ? new DateOnly(year, period, 1) : new DateOnly(year, ((period - 1) * 3) + 1, 1);
|
||||
var to = from.AddMonths(periodicity == IntrastatPeriodicity.Monthly ? 1 : 3).AddDays(-1);
|
||||
var quarter = ((from.Month - 1) / 3) + 1;
|
||||
var due = await DueAsync(uow, exporter, flow, year, quarter, cancellationToken).ConfigureAwait(false);
|
||||
var candidates = await CandidatesAsync(uow, exporter, flow, from, to, cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<IntrastatListLine, long>();
|
||||
foreach (var line in candidates)
|
||||
{
|
||||
// A category not due (purchases below the threshold) stays out of the list.
|
||||
var category = line.Section is IntrastatSection.Goods or IntrastatSection.GoodsCorrection ? due.Goods : due.Services;
|
||||
if (category == IntrastatPeriodicity.NotDue && flow == IntrastatFlow.Purchases)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
line.ListId = list.Id;
|
||||
line.IsDemo = isDemo || line.IsDemo;
|
||||
await repository.InsertAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>The lines a period would have, from the documents (not written).</summary>
|
||||
internal static async Task<List<IntrastatListLine>> CandidatesAsync(
|
||||
IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, DateOnly from, DateOnly to, CancellationToken cancellationToken)
|
||||
{
|
||||
var documents = flow == IntrastatFlow.Sales
|
||||
? await DocumentsAsync<SaleDocument, SaleDocumentLine>(uow, SaleKinds, from, to, cancellationToken).ConfigureAwait(false)
|
||||
: await DocumentsAsync<PurchaseDocument, PurchaseDocumentLine>(uow, PurchaseKinds, from, to, cancellationToken).ConfigureAwait(false);
|
||||
if (documents.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var partyIds = documents.Select(d => d.Header.PartyId).Where(p => p is not null).Select(p => p!.Value).Distinct().ToList();
|
||||
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(p => p.Id);
|
||||
var foreign = documents.Where(d => d.Header.PartyId is { } p && parties.TryGetValue(p, out var party) && !string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList();
|
||||
var itemIds = foreign.SelectMany(d => d.Lines).Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList();
|
||||
var items = itemIds.Count == 0
|
||||
? []
|
||||
: (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var result = new List<IntrastatListLine>();
|
||||
var goods = new Dictionary<(long Party, string? Code), IntrastatListLine>();
|
||||
foreach (var (header, lines) in foreign.OrderBy(d => d.Header.DocumentDate).ThenBy(d => d.Header.Id))
|
||||
{
|
||||
var party = parties[header.PartyId!.Value];
|
||||
var country = string.Equals(party.CountryCode, "EL", StringComparison.OrdinalIgnoreCase) ? "GR" : party.CountryCode.ToUpperInvariant();
|
||||
var sign = header.Kind is DocumentKind.CreditNote or DocumentKind.PurchaseCreditNote ? -1m : 1m;
|
||||
var rate = header.ExchangeRate <= 0m ? 1m : header.ExchangeRate;
|
||||
var family = flow == IntrastatFlow.Sales ? DocumentFamily.SaleDocument : DocumentFamily.PurchaseDocument;
|
||||
var vat = VatOf(party.VatNumber, country);
|
||||
decimal services = 0m, servicesCurrency = 0m;
|
||||
string? serviceCode = null;
|
||||
string? serviceText = null;
|
||||
foreach (var line in lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free && l.TaxableAmount != 0m))
|
||||
{
|
||||
var item = line.ItemId is { } i && items.TryGetValue(i, out var it) ? it : null;
|
||||
var euro = Math.Round(line.TaxableAmount / rate, 2, MidpointRounding.AwayFromZero) * sign;
|
||||
if (item?.Kind == ItemKind.Service)
|
||||
{
|
||||
services += euro;
|
||||
servicesCurrency += line.TaxableAmount * sign;
|
||||
serviceCode ??= item.CustomsCode;
|
||||
serviceText ??= line.Description;
|
||||
continue;
|
||||
}
|
||||
|
||||
var code = item?.CustomsCode?.Trim();
|
||||
if (!goods.TryGetValue((party.Id, code), out var target))
|
||||
{
|
||||
target = new IntrastatListLine
|
||||
{
|
||||
Section = IntrastatSection.Goods,
|
||||
SourceFamily = family,
|
||||
SourceDocumentId = header.Id,
|
||||
DocumentNumber = header.DocumentNumber,
|
||||
DocumentDate = header.DocumentDate,
|
||||
PartyId = party.Id,
|
||||
CountryCode = country,
|
||||
VatNumber = vat,
|
||||
NomenclatureCode = code,
|
||||
Description = Clean(item?.Description ?? line.Description, 200),
|
||||
TransactionNature = "11",
|
||||
DeliveryTerms = "DAP",
|
||||
TransportMode = "3",
|
||||
OriginCountry = flow == IntrastatFlow.Purchases ? country : null,
|
||||
Province = Clean(profile?.ProvinceCode, 2),
|
||||
IsDemo = header.IsDemo,
|
||||
};
|
||||
goods[(party.Id, code)] = target;
|
||||
result.Add(target);
|
||||
}
|
||||
|
||||
target.Amount += euro;
|
||||
target.CurrencyAmount = flow == IntrastatFlow.Purchases && rate != 1m ? (target.CurrencyAmount ?? 0m) + (line.TaxableAmount * sign) : target.CurrencyAmount;
|
||||
if (item?.NetWeight is { } weight && weight > 0m)
|
||||
{
|
||||
target.NetMass = (target.NetMass ?? 0m) + Math.Round(weight * line.Quantity * sign, 3, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
}
|
||||
|
||||
if (services != 0m)
|
||||
{
|
||||
result.Add(new IntrastatListLine
|
||||
{
|
||||
Section = sign < 0m ? IntrastatSection.ServicesCorrection : IntrastatSection.Services,
|
||||
SourceFamily = family,
|
||||
SourceDocumentId = header.Id,
|
||||
DocumentNumber = header.DocumentNumber,
|
||||
DocumentDate = header.DocumentDate,
|
||||
PartyId = party.Id,
|
||||
CountryCode = country,
|
||||
VatNumber = vat,
|
||||
Amount = Math.Abs(services),
|
||||
CurrencyAmount = flow == IntrastatFlow.Purchases && rate != 1m ? Math.Abs(servicesCurrency) : null,
|
||||
NomenclatureCode = Clean(serviceCode, 10),
|
||||
Description = Clean(serviceText, 200),
|
||||
SupplyMode = "I",
|
||||
PaymentMode = "B",
|
||||
PaymentCountry = country,
|
||||
CorrectedYear = sign < 0m ? header.DocumentDate.Year : null,
|
||||
CorrectedPeriod = sign < 0m ? header.DocumentDate.Month : null,
|
||||
CorrectionSign = sign < 0m ? "-" : null,
|
||||
IsDemo = header.IsDemo,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var line in result.Where(l => l.Section == IntrastatSection.Goods && l.Amount < 0m))
|
||||
{
|
||||
// Credit notes beyond the sales of the period are corrections of an earlier one.
|
||||
line.Section = IntrastatSection.GoodsCorrection;
|
||||
line.Amount = -line.Amount;
|
||||
line.NetMass = line.NetMass is { } m ? Math.Abs(m) : null;
|
||||
line.CorrectionSign = "-";
|
||||
line.CorrectedYear = line.DocumentDate?.Year;
|
||||
line.CorrectedPeriod = line.DocumentDate?.Month;
|
||||
}
|
||||
|
||||
result.RemoveAll(l => l.Amount == 0m);
|
||||
foreach (var line in result)
|
||||
{
|
||||
line.Amount = Math.Round(line.Amount, 2, MidpointRounding.AwayFromZero);
|
||||
line.StatisticalValue = line.Section == IntrastatSection.Goods ? line.Amount : null;
|
||||
line.Check = exporter.MemberStates.Contains(line.CountryCode) && line.CountryCode != "IT" ? CheckOf(exporter, line) : IntrastatCheck.OutsideEu;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static async Task<List<(DocumentHeader Header, List<DocumentLine> Lines)>> DocumentsAsync<THeader, TLine>(
|
||||
IUnitOfWork uow, DocumentKind[] kinds, DateOnly from, DateOnly to, CancellationToken cancellationToken)
|
||||
where THeader : DocumentHeader, new()
|
||||
where TLine : DocumentLine, new()
|
||||
{
|
||||
var draft = DocumentStatus.Draft;
|
||||
var cancelled = DocumentStatus.Cancelled;
|
||||
List<DocumentKind> wanted = [.. kinds];
|
||||
var headers = (await uow.Repository<THeader, long>().ListAsync(
|
||||
Query.For<THeader>().Where(h => h.DocumentDate >= from && h.DocumentDate <= to && h.Status != draft && h.Status != cancelled && wanted.Contains(h.Kind)),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (headers.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var ids = headers.Select(h => h.Id).ToList();
|
||||
var lines = (await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(l => ids.Contains(l.DocumentId)).OrderBy(l => l.LineNumber), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
return [.. headers.Select(h => ((DocumentHeader)h, lines.Where(l => l.DocumentId == h.Id).Cast<DocumentLine>().ToList()))];
|
||||
}
|
||||
|
||||
private static IntrastatCheck CheckOf(IIntrastatExporter exporter, IntrastatListLine line)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line.VatNumber))
|
||||
{
|
||||
return IntrastatCheck.MissingVatNumber;
|
||||
}
|
||||
|
||||
if (line.Section is IntrastatSection.Goods or IntrastatSection.GoodsCorrection)
|
||||
{
|
||||
if (!exporter.ValidNomenclature(line.NomenclatureCode))
|
||||
{
|
||||
return IntrastatCheck.MissingNomenclature;
|
||||
}
|
||||
|
||||
if (line.Section == IntrastatSection.Goods && line.NetMass is null or <= 0m && line.SupplementaryUnits is null or <= 0m)
|
||||
{
|
||||
return IntrastatCheck.MissingMass;
|
||||
}
|
||||
}
|
||||
else if (line.NomenclatureCode is not { Length: >= 5 })
|
||||
{
|
||||
return IntrastatCheck.MissingServiceCode;
|
||||
}
|
||||
|
||||
return IntrastatCheck.Ok;
|
||||
}
|
||||
|
||||
private static async Task TotalsAsync(IUnitOfWork uow, IntrastatList list, CancellationToken cancellationToken)
|
||||
{
|
||||
var listId = list.Id;
|
||||
var lines = (await uow.Repository<IntrastatListLine, long>().ListAsync(Query.For<IntrastatListLine>().Where(l => l.ListId == listId), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
list.GoodsAmount = lines.Where(l => l.Included && l.Section is IntrastatSection.Goods).Sum(l => l.Amount)
|
||||
- lines.Where(l => l.Included && l.Section is IntrastatSection.GoodsCorrection && l.CorrectionSign == "-").Sum(l => l.Amount);
|
||||
list.ServicesAmount = lines.Where(l => l.Included && l.Section is IntrastatSection.Services).Sum(l => l.Amount)
|
||||
- lines.Where(l => l.Included && l.Section is IntrastatSection.ServicesCorrection && l.CorrectionSign == "-").Sum(l => l.Amount);
|
||||
list.Problems = lines.Count(l => l.Included && l.Check != IntrastatCheck.Ok);
|
||||
await uow.Repository<IntrastatList, long>().UpdateAsync(list, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<IntrastatList> EditableAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
var list = await uow.Repository<IntrastatList, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound);
|
||||
return list.Status == IntrastatStatus.Sent ? throw new ValidationFailedException(["Id:" + YearEndErrors.ListSent]) : list;
|
||||
}
|
||||
|
||||
private static async Task<IntrastatListView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<IntrastatList, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } list)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var lines = (await uow.Repository<IntrastatListLine, long>().ListAsync(
|
||||
Query.For<IntrastatListLine>().Where(l => l.ListId == id).OrderBy(l => l.Section).OrderBy(l => l.DocumentDate).OrderBy(l => l.Id), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var names = await JournalEntryService.PartyNamesAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
return new IntrastatListView(list, lines, names);
|
||||
}
|
||||
|
||||
private static string? VatOf(string? vatNumber, string country)
|
||||
{
|
||||
var vat = vatNumber?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
|
||||
if (string.IsNullOrEmpty(vat))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var prefix = country == "GR" ? "EL" : country;
|
||||
return vat.StartsWith(prefix, StringComparison.Ordinal) ? vat[prefix.Length..] : vat;
|
||||
}
|
||||
|
||||
private static string? Clean(string? text, int length)
|
||||
{
|
||||
var value = text?.Trim();
|
||||
return string.IsNullOrEmpty(value) ? null : value.Length <= length ? value : value[..length];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>
|
||||
/// The entries the year end writes (ADR 0041, ADR 0043): depreciation, disposals, accruals, exchange differences and the
|
||||
/// steps of the closing go into the journal as posted entries with their source, so the statements and the closing find
|
||||
/// them and an undo removes them while they are not final.
|
||||
/// </summary>
|
||||
internal static class YearEndLedger
|
||||
{
|
||||
/// <summary>Writes a posted entry, leaving out the empty lines; nothing when every line is empty.</summary>
|
||||
public static async Task<GlEntry?> PostAsync(
|
||||
IUnitOfWork uow, DateOnly date, string description, GlEntrySource source, int? closingStep, IReadOnlyList<EntryLineDraft> lines, bool isDemo,
|
||||
CancellationToken cancellationToken, long? partyId = null, string? documentNumber = null)
|
||||
{
|
||||
var useful = lines.Where(l => l.Debit != 0m || l.Credit != 0m).Select(Positive).ToList();
|
||||
if (useful.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var debit = useful.Sum(l => l.Debit);
|
||||
var credit = useful.Sum(l => l.Credit);
|
||||
if (debit != credit)
|
||||
{
|
||||
throw new InvalidOperationException("Unbalanced year-end entry: " + description);
|
||||
}
|
||||
|
||||
var entry = new GlEntry
|
||||
{
|
||||
EntryDate = date,
|
||||
Description = LedgerStore.Trim(description, 200)!,
|
||||
Status = GlEntryStatus.Posted,
|
||||
Source = source,
|
||||
ClosingStep = closingStep,
|
||||
PartyId = partyId,
|
||||
DocumentNumber = LedgerStore.Trim(documentNumber, 30),
|
||||
IsDemo = isDemo,
|
||||
};
|
||||
return await LedgerStore.InsertAsync(uow, entry, useful, [], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Removes entries that are not final.</summary>
|
||||
public static async Task DeleteAsync(IUnitOfWork uow, IEnumerable<long> entryIds, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = entryIds.Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var final = GlEntryStatus.Final;
|
||||
if (await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => ids.Contains(e.Id) && e.Status == final), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + YearEndErrors.EntriesFinal]);
|
||||
}
|
||||
|
||||
foreach (var id in ids)
|
||||
{
|
||||
await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The accounts by code.</summary>
|
||||
public static async Task<Dictionary<string, GlAccount>> AccountsByCodeAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
(await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false)).Values.ToDictionary(a => a.Code, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The account of a code, or an error naming it.</summary>
|
||||
public static GlAccount Require(IReadOnlyDictionary<string, GlAccount> accounts, string code) =>
|
||||
accounts.TryGetValue(code, out var account) ? account : throw new ValidationFailedException([YearEndErrors.ClosingAccount + ":" + code]);
|
||||
|
||||
/// <summary>A debit line (a negative amount goes to the credit).</summary>
|
||||
public static EntryLineDraft Debit(long accountId, decimal amount, string? description = null, long? partyId = null) =>
|
||||
new(accountId, partyId, description, amount, 0m);
|
||||
|
||||
/// <summary>A credit line (a negative amount goes to the debit).</summary>
|
||||
public static EntryLineDraft Credit(long accountId, decimal amount, string? description = null, long? partyId = null) =>
|
||||
new(accountId, partyId, description, 0m, amount);
|
||||
|
||||
private static EntryLineDraft Positive(EntryLineDraft line)
|
||||
{
|
||||
var net = line.Debit - line.Credit;
|
||||
return line with { Debit = net > 0m ? net : 0m, Credit = net < 0m ? -net : 0m };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
namespace Khaemhat.Application.YearEnd;
|
||||
|
||||
/// <summary>The permissions of the year end (modules ASSET, INTRA, ACCT, REPORT and CORE).</summary>
|
||||
public static class YearEndPermissions
|
||||
{
|
||||
/// <summary>See the fixed assets (ASSET).</summary>
|
||||
public const string AssetRead = "assets.asset.read";
|
||||
|
||||
/// <summary>Change the fixed assets and their categories (ASSET).</summary>
|
||||
public const string AssetWrite = "assets.asset.write";
|
||||
|
||||
/// <summary>Post the depreciation and the disposals (ASSET).</summary>
|
||||
public const string DepreciationPost = "assets.depreciation.post";
|
||||
|
||||
/// <summary>See the Intrastat lists (INTRA).</summary>
|
||||
public const string IntrastatRead = "intrastat.list.read";
|
||||
|
||||
/// <summary>Generate and complete the Intrastat lists (INTRA).</summary>
|
||||
public const string IntrastatWrite = "intrastat.list.write";
|
||||
|
||||
/// <summary>Write the file for the customs (INTRA).</summary>
|
||||
public const string IntrastatExport = "intrastat.list.export";
|
||||
|
||||
/// <summary>Run the closing of the year (ACCT).</summary>
|
||||
public const string YearClose = "ledger.year.close";
|
||||
|
||||
/// <summary>Export the data for the accountant (REPORT).</summary>
|
||||
public const string AccountantExport = "reports.accountant.export";
|
||||
|
||||
/// <summary>See the declarations of intent (CORE).</summary>
|
||||
public const string IntentRead = "sales.intent.read";
|
||||
|
||||
/// <summary>Record the declarations of intent (CORE).</summary>
|
||||
public const string IntentWrite = "sales.intent.write";
|
||||
}
|
||||
|
||||
/// <summary>The error codes of the year end; the interface translates them (<c>YearEnd.json</c>).</summary>
|
||||
public static class YearEndErrors
|
||||
{
|
||||
/// <summary>The record does not exist.</summary>
|
||||
public const string NotFound = "yearend.not-found";
|
||||
|
||||
/// <summary>A code is required.</summary>
|
||||
public const string CodeRequired = "yearend.code-required";
|
||||
|
||||
/// <summary>The code is used already.</summary>
|
||||
public const string CodeTaken = "yearend.code-taken";
|
||||
|
||||
/// <summary>A description is required.</summary>
|
||||
public const string DescriptionRequired = "yearend.description-required";
|
||||
|
||||
/// <summary>The category is required.</summary>
|
||||
public const string CategoryRequired = "assets.category-required";
|
||||
|
||||
/// <summary>The category lacks one of its accounts.</summary>
|
||||
public const string CategoryAccounts = "assets.category-accounts";
|
||||
|
||||
/// <summary>A rate outside 0-100.</summary>
|
||||
public const string RateRange = "assets.rate-range";
|
||||
|
||||
/// <summary>The cost must be positive.</summary>
|
||||
public const string CostRequired = "assets.cost-required";
|
||||
|
||||
/// <summary>The fund exceeds the cost.</summary>
|
||||
public const string FundTooHigh = "assets.fund-too-high";
|
||||
|
||||
/// <summary>The asset entered service before it was bought.</summary>
|
||||
public const string ServiceBeforePurchase = "assets.service-before-purchase";
|
||||
|
||||
/// <summary>The asset has postings: it cannot be removed.</summary>
|
||||
public const string AssetPosted = "assets.posted";
|
||||
|
||||
/// <summary>The asset was disposed of.</summary>
|
||||
public const string Disposed = "assets.disposed";
|
||||
|
||||
/// <summary>The cost disposed of exceeds the cost.</summary>
|
||||
public const string DisposalTooHigh = "assets.disposal-too-high";
|
||||
|
||||
/// <summary>The depreciation of a later year is posted: undo that first.</summary>
|
||||
public const string LaterDepreciation = "assets.later-depreciation";
|
||||
|
||||
/// <summary>The entries are final: nothing can be undone.</summary>
|
||||
public const string EntriesFinal = "yearend.entries-final";
|
||||
|
||||
/// <summary>The account is required.</summary>
|
||||
public const string AccountRequired = "accruals.account-required";
|
||||
|
||||
/// <summary>The period of an accrual ends before it starts.</summary>
|
||||
public const string PeriodOrder = "accruals.period-order";
|
||||
|
||||
/// <summary>The period of an accrual does not straddle the year end.</summary>
|
||||
public const string PeriodOutside = "accruals.period-outside";
|
||||
|
||||
/// <summary>The amount must be positive.</summary>
|
||||
public const string AmountRequired = "yearend.amount-required";
|
||||
|
||||
/// <summary>The accrual was posted: undo the step of the closing first.</summary>
|
||||
public const string AccrualPosted = "accruals.posted";
|
||||
|
||||
/// <summary>The party is required.</summary>
|
||||
public const string PartyRequired = "intent.party-required";
|
||||
|
||||
/// <summary>The number of the declaration is required.</summary>
|
||||
public const string NumberRequired = "intent.number-required";
|
||||
|
||||
/// <summary>The protocol is not of 17 digits, a dash and 6 digits.</summary>
|
||||
public const string ProtocolInvalid = "intent.protocol-invalid";
|
||||
|
||||
/// <summary>The validity ends before it starts.</summary>
|
||||
public const string ValidityOrder = "intent.validity-order";
|
||||
|
||||
/// <summary>The ceiling must be positive.</summary>
|
||||
public const string CeilingRequired = "intent.ceiling-required";
|
||||
|
||||
/// <summary>The ceiling is lower than what was used.</summary>
|
||||
public const string CeilingBelowUsed = "intent.ceiling-below-used";
|
||||
|
||||
/// <summary>The VAT code must have the nature N3.5.</summary>
|
||||
public const string TaxCodeNature = "intent.tax-code-nature";
|
||||
|
||||
/// <summary>A sale with nature N3.5 without a declaration covering its date.</summary>
|
||||
public const string NoDeclaration = "intent.no-declaration";
|
||||
|
||||
/// <summary>The sale exceeds the ceiling left.</summary>
|
||||
public const string CeilingExceeded = "intent.ceiling-exceeded";
|
||||
|
||||
/// <summary>The declaration was used: revoke it instead.</summary>
|
||||
public const string DeclarationUsed = "intent.used";
|
||||
|
||||
/// <summary>The list was sent: read only.</summary>
|
||||
public const string ListSent = "intrastat.sent";
|
||||
|
||||
/// <summary>The period is not valid for the periodicity.</summary>
|
||||
public const string PeriodInvalid = "intrastat.period-invalid";
|
||||
|
||||
/// <summary>The country is not a member state.</summary>
|
||||
public const string CountryNotMember = "intrastat.country-not-member";
|
||||
|
||||
/// <summary>The company has no VAT number.</summary>
|
||||
public const string CompanyVatMissing = "intrastat.company-vat-missing";
|
||||
|
||||
/// <summary>The list has lines to complete.</summary>
|
||||
public const string ListIncomplete = "intrastat.incomplete";
|
||||
|
||||
/// <summary>The year has no closing yet.</summary>
|
||||
public const string NoClosing = "closing.not-started";
|
||||
|
||||
/// <summary>The closing is locked.</summary>
|
||||
public const string ClosingLocked = "closing.locked";
|
||||
|
||||
/// <summary>A step before this one is not done.</summary>
|
||||
public const string StepOrder = "closing.step-order";
|
||||
|
||||
/// <summary>A later step is done: undo it first.</summary>
|
||||
public const string LaterStepDone = "closing.later-step-done";
|
||||
|
||||
/// <summary>The checks failed.</summary>
|
||||
public const string ChecksFailed = "closing.checks-failed";
|
||||
|
||||
/// <summary>The step cannot be undone (the entries are final).</summary>
|
||||
public const string StepIrreversible = "closing.step-irreversible";
|
||||
|
||||
/// <summary>A previous year is not closed.</summary>
|
||||
public const string PreviousOpen = "closing.previous-open";
|
||||
|
||||
/// <summary>The year has not ended.</summary>
|
||||
public const string YearNotEnded = "closing.year-not-ended";
|
||||
|
||||
/// <summary>The steps are not all done.</summary>
|
||||
public const string StepsPending = "closing.steps-pending";
|
||||
|
||||
/// <summary>An account of the closing is missing from the chart.</summary>
|
||||
public const string ClosingAccount = "closing.account-missing";
|
||||
|
||||
/// <summary>The balance-sheet accounts do not balance: the income accounts of earlier years are still open.</summary>
|
||||
public const string ClosingUnbalanced = "closing.unbalanced";
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Core.Accounting;
|
||||
|
||||
/// <summary>Whether a category holds tangible or intangible assets.</summary>
|
||||
public enum AssetClass
|
||||
{
|
||||
/// <summary>Immobilizzazioni materiali.</summary>
|
||||
Tangible = 0,
|
||||
|
||||
/// <summary>Immobilizzazioni immateriali.</summary>
|
||||
Intangible = 1,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A category of fixed assets (SPEC §11.7, mockup 048, <c>fixed_asset_categories</c>): the ministerial coefficient, the
|
||||
/// civil and fiscal rates and the accounts the depreciation posts to.
|
||||
/// </summary>
|
||||
public sealed class FixedAssetCategory : CodedEntity
|
||||
{
|
||||
/// <summary>Tangible or intangible.</summary>
|
||||
public AssetClass Class { get; set; }
|
||||
|
||||
/// <summary>The group and species of the ministerial table (DM 31/12/1988), such as <c>XXII.1</c>.</summary>
|
||||
public string? MinisterialGroup { get; set; }
|
||||
|
||||
/// <summary>The civil (economic-technical) yearly rate, percent.</summary>
|
||||
public decimal CivilRate { get; set; }
|
||||
|
||||
/// <summary>The fiscal yearly rate, percent: at most the ministerial coefficient.</summary>
|
||||
public decimal FiscalRate { get; set; }
|
||||
|
||||
/// <summary>Half the rate in the first year, for the civil plan too (the fiscal plan always halves it).</summary>
|
||||
public bool CivilHalfFirstYear { get; set; } = true;
|
||||
|
||||
/// <summary>The asset account (cost).</summary>
|
||||
public long? AssetAccountId { get; set; }
|
||||
|
||||
/// <summary>The accumulated depreciation account (fondo).</summary>
|
||||
public long? FundAccountId { get; set; }
|
||||
|
||||
/// <summary>The depreciation cost account.</summary>
|
||||
public long? DepreciationAccountId { get; set; }
|
||||
|
||||
/// <summary>The share of cost and depreciation deductible, percent (passenger cars: 20).</summary>
|
||||
public decimal DeductiblePercent { get; set; } = 100m;
|
||||
|
||||
/// <summary>The fiscal limit on the cost (passenger cars: 18,075.99), if any.</summary>
|
||||
public decimal? CostLimit { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a fixed asset.</summary>
|
||||
public enum AssetStatus
|
||||
{
|
||||
/// <summary>In use and being depreciated.</summary>
|
||||
Active = 0,
|
||||
|
||||
/// <summary>Fully depreciated, still in use.</summary>
|
||||
Depreciated = 1,
|
||||
|
||||
/// <summary>Sold or scrapped.</summary>
|
||||
Disposed = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A fixed asset (cespite, SPEC §11.7, mockup 048, <c>fixed_assets</c>): its cost, the rates (from the category unless
|
||||
/// changed), the depreciation already done and its state. The history of its values is in its movements.
|
||||
/// </summary>
|
||||
public sealed class FixedAsset : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The code, such as <c>CESP-0041</c>.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The description.</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The category.</summary>
|
||||
public long CategoryId { get; set; }
|
||||
|
||||
/// <summary>The day it was bought.</summary>
|
||||
public DateOnly PurchaseDate { get; set; }
|
||||
|
||||
/// <summary>The day it went into use: the depreciation starts in that year.</summary>
|
||||
public DateOnly InServiceDate { get; set; }
|
||||
|
||||
/// <summary>The supplier.</summary>
|
||||
public long? SupplierId { get; set; }
|
||||
|
||||
/// <summary>The purchase document, as text (the supplier's number and date).</summary>
|
||||
public string? DocumentReference { get; set; }
|
||||
|
||||
/// <summary>Where it is.</summary>
|
||||
public string? Location { get; set; }
|
||||
|
||||
/// <summary>The serial number.</summary>
|
||||
public string? SerialNumber { get; set; }
|
||||
|
||||
/// <summary>The quantity.</summary>
|
||||
public decimal Quantity { get; set; } = 1m;
|
||||
|
||||
/// <summary>The cost: purchase plus increases and revaluations, less disposals.</summary>
|
||||
public decimal Cost { get; set; }
|
||||
|
||||
/// <summary>The civil accumulated depreciation.</summary>
|
||||
public decimal CivilFund { get; set; }
|
||||
|
||||
/// <summary>The fiscal accumulated depreciation.</summary>
|
||||
public decimal FiscalFund { get; set; }
|
||||
|
||||
/// <summary>The civil rate, when different from the category.</summary>
|
||||
public decimal? CivilRate { get; set; }
|
||||
|
||||
/// <summary>The fiscal rate, when different from the category.</summary>
|
||||
public decimal? FiscalRate { get; set; }
|
||||
|
||||
/// <summary>The value left at the end of its life, not depreciated.</summary>
|
||||
public decimal ResidualValue { get; set; }
|
||||
|
||||
/// <summary>A good of unit cost up to the low-value threshold, depreciated in full in its first year.</summary>
|
||||
public bool LowValue { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public AssetStatus Status { get; set; }
|
||||
|
||||
/// <summary>The day it was disposed of.</summary>
|
||||
public DateOnly? DisposalDate { get; set; }
|
||||
|
||||
/// <summary>The last year depreciated.</summary>
|
||||
public int? LastDepreciationYear { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>The civil net book value.</summary>
|
||||
public decimal NetValue => Cost - CivilFund;
|
||||
}
|
||||
|
||||
/// <summary>What a movement of a fixed asset records.</summary>
|
||||
public enum AssetMovementKind
|
||||
{
|
||||
/// <summary>The purchase.</summary>
|
||||
Purchase = 0,
|
||||
|
||||
/// <summary>An increase of cost (improvement, extraordinary maintenance).</summary>
|
||||
Increase = 1,
|
||||
|
||||
/// <summary>A revaluation by law.</summary>
|
||||
Revaluation = 2,
|
||||
|
||||
/// <summary>The depreciation of a year.</summary>
|
||||
Depreciation = 3,
|
||||
|
||||
/// <summary>A disposal of part of the asset.</summary>
|
||||
PartialDisposal = 4,
|
||||
|
||||
/// <summary>The disposal of the whole asset (sale, scrapping).</summary>
|
||||
Disposal = 5,
|
||||
|
||||
/// <summary>The values brought in when the register starts (assets bought before Khaemhat).</summary>
|
||||
Opening = 6,
|
||||
}
|
||||
|
||||
/// <summary>A movement of a fixed asset (<c>fixed_asset_movements</c>): the history of its cost and depreciation.</summary>
|
||||
public sealed class FixedAssetMovement : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The asset.</summary>
|
||||
public long AssetId { get; set; }
|
||||
|
||||
/// <summary>What it records.</summary>
|
||||
public AssetMovementKind Kind { get; set; }
|
||||
|
||||
/// <summary>The day.</summary>
|
||||
public DateOnly MovementDate { get; set; }
|
||||
|
||||
/// <summary>The fiscal year of a depreciation.</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The change of cost (negative for disposals).</summary>
|
||||
public decimal CostAmount { get; set; }
|
||||
|
||||
/// <summary>The change of the civil fund (the depreciation, or negative for disposals).</summary>
|
||||
public decimal CivilAmount { get; set; }
|
||||
|
||||
/// <summary>The change of the fiscal fund.</summary>
|
||||
public decimal FiscalAmount { get; set; }
|
||||
|
||||
/// <summary>The price of a disposal.</summary>
|
||||
public decimal Proceeds { get; set; }
|
||||
|
||||
/// <summary>The gain (positive) or loss (negative) of a disposal.</summary>
|
||||
public decimal GainLoss { get; set; }
|
||||
|
||||
/// <summary>The description.</summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>The entry posted.</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The depreciation of one year of a plan.</summary>
|
||||
/// <param name="Year">The year.</param>
|
||||
/// <param name="Opening">The fund at the start of the year.</param>
|
||||
/// <param name="Rate">The rate applied, percent (halved in the first year).</param>
|
||||
/// <param name="Amount">The depreciation of the year.</param>
|
||||
/// <param name="Closing">The fund at the end of the year.</param>
|
||||
/// <param name="NetValue">The value left to depreciate.</param>
|
||||
public sealed record DepreciationYear(int Year, decimal Opening, decimal Rate, decimal Amount, decimal Closing, decimal NetValue);
|
||||
|
||||
/// <summary>What the depreciation of an asset needs.</summary>
|
||||
/// <param name="Cost">The cost.</param>
|
||||
/// <param name="Residual">The value not depreciated.</param>
|
||||
/// <param name="Rate">The yearly rate, percent.</param>
|
||||
/// <param name="FirstYear">The first year of use.</param>
|
||||
/// <param name="HalfFirstYear">Half the rate in the first year.</param>
|
||||
/// <param name="LowValue">Fully depreciated in its first year.</param>
|
||||
public sealed record DepreciationBasis(decimal Cost, decimal Residual, decimal Rate, int FirstYear, bool HalfFirstYear, bool LowValue);
|
||||
|
||||
/// <summary>
|
||||
/// The straight-line depreciation (SPEC §21, issue #82): the rate on the cost, halved in the first year when asked, never
|
||||
/// more than what is left; low-value goods in full in the first year. The same rules make the civil and the fiscal plan,
|
||||
/// with their own rates.
|
||||
/// </summary>
|
||||
public static class DepreciationCalculator
|
||||
{
|
||||
/// <summary>The depreciation of a year.</summary>
|
||||
/// <param name="basis">The asset.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="fund">The fund at the start of the year.</param>
|
||||
/// <returns>The amount, rounded to the cent; zero before the first year or when nothing is left.</returns>
|
||||
public static decimal Yearly(DepreciationBasis basis, int year, decimal fund)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
var depreciable = Math.Max(0m, basis.Cost - basis.Residual);
|
||||
var left = Math.Max(0m, depreciable - fund);
|
||||
if (year < basis.FirstYear || left == 0m)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
if (basis.LowValue)
|
||||
{
|
||||
return left;
|
||||
}
|
||||
|
||||
var amount = Math.Round(depreciable * RateOf(basis, year) / 100m, 2, MidpointRounding.AwayFromZero);
|
||||
return Math.Min(amount, left);
|
||||
}
|
||||
|
||||
/// <summary>The rate of a year: halved in the first year when asked.</summary>
|
||||
/// <param name="basis">The asset.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <returns>The rate, percent.</returns>
|
||||
public static decimal RateOf(DepreciationBasis basis, int year)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
if (basis.LowValue)
|
||||
{
|
||||
return year == basis.FirstYear ? 100m : 0m;
|
||||
}
|
||||
|
||||
return year == basis.FirstYear && basis.HalfFirstYear ? basis.Rate / 2m : basis.Rate;
|
||||
}
|
||||
|
||||
/// <summary>The whole plan from a year with its fund, to the end of the depreciation (at most 100 years).</summary>
|
||||
/// <param name="basis">The asset.</param>
|
||||
/// <param name="fromYear">The first year shown.</param>
|
||||
/// <param name="fund">The fund at the start of that year.</param>
|
||||
/// <returns>The years.</returns>
|
||||
public static IReadOnlyList<DepreciationYear> Plan(DepreciationBasis basis, int fromYear, decimal fund)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
var depreciable = Math.Max(0m, basis.Cost - basis.Residual);
|
||||
var years = new List<DepreciationYear>();
|
||||
var year = Math.Max(fromYear, basis.FirstYear);
|
||||
while (years.Count < 100)
|
||||
{
|
||||
var amount = Yearly(basis, year, fund);
|
||||
if (amount <= 0m)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
years.Add(new DepreciationYear(year, fund, RateOf(basis, year), amount, fund + amount, depreciable - fund - amount));
|
||||
fund += amount;
|
||||
year++;
|
||||
}
|
||||
|
||||
return years;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gain or loss of a disposal: the price less the net value of the part disposed of (cost less fund, both in the
|
||||
/// share disposed of).
|
||||
/// </summary>
|
||||
/// <param name="cost">The cost disposed of.</param>
|
||||
/// <param name="fund">The fund of the part disposed of.</param>
|
||||
/// <param name="proceeds">The price.</param>
|
||||
/// <returns>Positive a gain (plusvalenza), negative a loss (minusvalenza).</returns>
|
||||
public static decimal GainLoss(decimal cost, decimal fund, decimal proceeds) => proceeds - (cost - fund);
|
||||
|
||||
/// <summary>The share of a fund that follows a part of the cost disposed of.</summary>
|
||||
/// <param name="totalCost">The cost of the whole asset.</param>
|
||||
/// <param name="totalFund">Its fund.</param>
|
||||
/// <param name="costDisposed">The cost disposed of.</param>
|
||||
/// <returns>The fund of that part, rounded to the cent.</returns>
|
||||
public static decimal FundShare(decimal totalCost, decimal totalFund, decimal costDisposed) =>
|
||||
totalCost == 0m ? 0m : Math.Round(totalFund * costDisposed / totalCost, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Accounting;
|
||||
|
||||
/// <summary>Sales to or purchases from the other member states.</summary>
|
||||
public enum IntrastatFlow
|
||||
{
|
||||
/// <summary>Cessioni (INTRA-1).</summary>
|
||||
Sales = 0,
|
||||
|
||||
/// <summary>Acquisti (INTRA-2).</summary>
|
||||
Purchases = 1,
|
||||
}
|
||||
|
||||
/// <summary>How often the lists are due.</summary>
|
||||
public enum IntrastatPeriodicity
|
||||
{
|
||||
/// <summary>Every month.</summary>
|
||||
Monthly = 0,
|
||||
|
||||
/// <summary>Every quarter.</summary>
|
||||
Quarterly = 1,
|
||||
|
||||
/// <summary>Not due (purchases below the threshold).</summary>
|
||||
NotDue = 2,
|
||||
}
|
||||
|
||||
/// <summary>The section of a list.</summary>
|
||||
public enum IntrastatSection
|
||||
{
|
||||
/// <summary>Goods (INTRA-1 bis, INTRA-2 bis).</summary>
|
||||
Goods = 0,
|
||||
|
||||
/// <summary>Corrections of goods of earlier periods (ter).</summary>
|
||||
GoodsCorrection = 1,
|
||||
|
||||
/// <summary>Services (INTRA-1 quater, INTRA-2 quater).</summary>
|
||||
Services = 2,
|
||||
|
||||
/// <summary>Corrections of services of earlier periods (quinquies).</summary>
|
||||
ServicesCorrection = 3,
|
||||
}
|
||||
|
||||
/// <summary>The state of a list.</summary>
|
||||
public enum IntrastatStatus
|
||||
{
|
||||
/// <summary>Being prepared: can be generated again.</summary>
|
||||
Draft = 0,
|
||||
|
||||
/// <summary>The file was written.</summary>
|
||||
Generated = 1,
|
||||
|
||||
/// <summary>Sent to the customs: read only.</summary>
|
||||
Sent = 2,
|
||||
}
|
||||
|
||||
/// <summary>What the check of a line found.</summary>
|
||||
public enum IntrastatCheck
|
||||
{
|
||||
/// <summary>Complete.</summary>
|
||||
Ok = 0,
|
||||
|
||||
/// <summary>The combined nomenclature code is missing or not of 8 digits.</summary>
|
||||
MissingNomenclature = 1,
|
||||
|
||||
/// <summary>The net mass is missing.</summary>
|
||||
MissingMass = 2,
|
||||
|
||||
/// <summary>The VAT number of the counterparty is missing.</summary>
|
||||
MissingVatNumber = 3,
|
||||
|
||||
/// <summary>The counterparty is outside the European Union: left out.</summary>
|
||||
OutsideEu = 4,
|
||||
|
||||
/// <summary>The service code (CPA) is missing.</summary>
|
||||
MissingServiceCode = 5,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An Intrastat list of a period (SPEC §11.7, mockup 049, <c>intrastat_lists</c>): the sales or purchases of goods and
|
||||
/// services with the other member states, generated from the documents, completed by hand and written to the file
|
||||
/// of the customs (SCAMBI.CEE).
|
||||
/// </summary>
|
||||
public sealed class IntrastatList : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>Sales or purchases.</summary>
|
||||
public IntrastatFlow Flow { get; set; }
|
||||
|
||||
/// <summary>The year.</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The month (1-12) or the quarter (1-4).</summary>
|
||||
public int Period { get; set; }
|
||||
|
||||
/// <summary>Monthly or quarterly.</summary>
|
||||
public IntrastatPeriodicity Periodicity { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public IntrastatStatus Status { get; set; }
|
||||
|
||||
/// <summary>The progressive number of the list in the year, for the file.</summary>
|
||||
public int Progressive { get; set; } = 1;
|
||||
|
||||
/// <summary>The goods total.</summary>
|
||||
public decimal GoodsAmount { get; set; }
|
||||
|
||||
/// <summary>The services total.</summary>
|
||||
public decimal ServicesAmount { get; set; }
|
||||
|
||||
/// <summary>The lines with something missing.</summary>
|
||||
public int Problems { get; set; }
|
||||
|
||||
/// <summary>The name of the file written.</summary>
|
||||
public string? FileName { get; set; }
|
||||
|
||||
/// <summary>The protocol given by the customs.</summary>
|
||||
public string? Protocol { get; set; }
|
||||
|
||||
/// <summary>When it was generated.</summary>
|
||||
public DateTime? GeneratedAt { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A line of an Intrastat list (<c>intrastat_list_lines</c>).</summary>
|
||||
public sealed class IntrastatListLine : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The list.</summary>
|
||||
public long ListId { get; set; }
|
||||
|
||||
/// <summary>The section.</summary>
|
||||
public IntrastatSection Section { get; set; }
|
||||
|
||||
/// <summary>The family of the document.</summary>
|
||||
public DocumentFamily? SourceFamily { get; set; }
|
||||
|
||||
/// <summary>The document.</summary>
|
||||
public long? SourceDocumentId { get; set; }
|
||||
|
||||
/// <summary>The number of the document.</summary>
|
||||
public string? DocumentNumber { get; set; }
|
||||
|
||||
/// <summary>The date of the document.</summary>
|
||||
public DateOnly? DocumentDate { get; set; }
|
||||
|
||||
/// <summary>The customer or supplier.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The member state of the counterparty.</summary>
|
||||
public string CountryCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The VAT number of the counterparty, without the country.</summary>
|
||||
public string? VatNumber { get; set; }
|
||||
|
||||
/// <summary>The amount in euro.</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>The amount in the currency of the document, when not euro (purchases).</summary>
|
||||
public decimal? CurrencyAmount { get; set; }
|
||||
|
||||
/// <summary>The statistical value in euro.</summary>
|
||||
public decimal? StatisticalValue { get; set; }
|
||||
|
||||
/// <summary>The combined nomenclature code (goods, 8 digits) or the CPA code (services, 5-6 digits).</summary>
|
||||
public string? NomenclatureCode { get; set; }
|
||||
|
||||
/// <summary>What was sold or bought.</summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>The nature of the transaction (table B, such as <c>11</c>).</summary>
|
||||
public string? TransactionNature { get; set; }
|
||||
|
||||
/// <summary>The delivery terms (Incoterms, such as <c>DAP</c>).</summary>
|
||||
public string? DeliveryTerms { get; set; }
|
||||
|
||||
/// <summary>The mode of transport (1 sea, 2 rail, 3 road, 4 air, 5 post, 7 fixed installations, 8 inland waterway, 9 own propulsion).</summary>
|
||||
public string? TransportMode { get; set; }
|
||||
|
||||
/// <summary>The net mass in kilograms.</summary>
|
||||
public decimal? NetMass { get; set; }
|
||||
|
||||
/// <summary>The supplementary units.</summary>
|
||||
public decimal? SupplementaryUnits { get; set; }
|
||||
|
||||
/// <summary>The country of origin of the goods (purchases).</summary>
|
||||
public string? OriginCountry { get; set; }
|
||||
|
||||
/// <summary>The province of origin (sales) or destination (purchases).</summary>
|
||||
public string? Province { get; set; }
|
||||
|
||||
/// <summary>How the service is supplied: <c>I</c> once, <c>R</c> repeated.</summary>
|
||||
public string? SupplyMode { get; set; }
|
||||
|
||||
/// <summary>How it is paid: <c>B</c> transfer, <c>A</c> direct debit, <c>X</c> other.</summary>
|
||||
public string? PaymentMode { get; set; }
|
||||
|
||||
/// <summary>The country of the payment.</summary>
|
||||
public string? PaymentCountry { get; set; }
|
||||
|
||||
/// <summary>For corrections: the year of the list corrected.</summary>
|
||||
public int? CorrectedYear { get; set; }
|
||||
|
||||
/// <summary>For corrections: the period of the list corrected.</summary>
|
||||
public int? CorrectedPeriod { get; set; }
|
||||
|
||||
/// <summary>For corrections: the sign, <c>+</c> or <c>-</c>.</summary>
|
||||
public string? CorrectionSign { get; set; }
|
||||
|
||||
/// <summary>What the check found.</summary>
|
||||
public IntrastatCheck Check { get; set; }
|
||||
|
||||
/// <summary>Typed or changed by hand: generating again keeps it.</summary>
|
||||
public bool Manual { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>Whether it goes into the file and the totals.</summary>
|
||||
public bool Included => Check != IntrastatCheck.OutsideEu;
|
||||
}
|
||||
@@ -264,6 +264,18 @@ public enum GlEntrySource
|
||||
|
||||
/// <summary>A collection, a payment or a remittance of the schedule (M8).</summary>
|
||||
Treasury = 7,
|
||||
|
||||
/// <summary>The depreciation, a disposal or the opening values of a fixed asset (M10).</summary>
|
||||
FixedAsset = 8,
|
||||
|
||||
/// <summary>An accrual or deferral at the year end, or its reversal at the opening (M10).</summary>
|
||||
Accrual = 9,
|
||||
|
||||
/// <summary>The exchange differences of the open items at the year end (M10).</summary>
|
||||
ExchangeDifference = 10,
|
||||
|
||||
/// <summary>A step of the guided closing: inventory, provisions, closing and opening (M10).</summary>
|
||||
Closing = 11,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -353,6 +365,9 @@ public sealed class GlEntry : Entity<long>, IDemoMarkable
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>The step of the closing that wrote it (<c>closing/<step></c>), 1-9.</summary>
|
||||
public int? ClosingStep { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Accounting;
|
||||
|
||||
/// <summary>What an accrual or deferral adjusts at the year end.</summary>
|
||||
public enum AccrualKind
|
||||
{
|
||||
/// <summary>Rateo attivo: revenue of the year to be collected or invoiced next year.</summary>
|
||||
AccruedIncome = 0,
|
||||
|
||||
/// <summary>Rateo passivo: cost of the year to be paid or invoiced next year.</summary>
|
||||
AccruedExpense = 1,
|
||||
|
||||
/// <summary>Risconto attivo: cost recorded this year that belongs to the next (insurance paid in advance).</summary>
|
||||
PrepaidExpense = 2,
|
||||
|
||||
/// <summary>Risconto passivo: revenue recorded this year that belongs to the next.</summary>
|
||||
DeferredIncome = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An accrual or deferral (rateo o risconto, SPEC §11.7, issue #84, <c>accruals</c>): an amount of a cost or revenue
|
||||
/// spread over a period across the year end; the share of the year (ratei) or of the next years (risconti) is posted
|
||||
/// at the year end and reversed at the opening.
|
||||
/// </summary>
|
||||
public sealed class AccrualDeferral : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The fiscal year it adjusts (the year of its end date).</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The kind.</summary>
|
||||
public AccrualKind Kind { get; set; }
|
||||
|
||||
/// <summary>The description.</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The cost or revenue account.</summary>
|
||||
public long AccountId { get; set; }
|
||||
|
||||
/// <summary>The whole amount of the period.</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>The first day of the period.</summary>
|
||||
public DateOnly PeriodStart { get; set; }
|
||||
|
||||
/// <summary>The last day of the period.</summary>
|
||||
public DateOnly PeriodEnd { get; set; }
|
||||
|
||||
/// <summary>The last day of the year adjusted.</summary>
|
||||
public DateOnly YearEnd { get; set; }
|
||||
|
||||
/// <summary>The share posted at the year end.</summary>
|
||||
public decimal Adjustment { get; set; }
|
||||
|
||||
/// <summary>The family of the document it comes from.</summary>
|
||||
public DocumentFamily? SourceFamily { get; set; }
|
||||
|
||||
/// <summary>The document it comes from.</summary>
|
||||
public long? SourceDocumentId { get; set; }
|
||||
|
||||
/// <summary>The number of that document.</summary>
|
||||
public string? DocumentNumber { get; set; }
|
||||
|
||||
/// <summary>The customer or supplier.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The entry of the year end.</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <summary>The entry that reverses it at the opening of the next year.</summary>
|
||||
public long? ReversalEntryId { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The share of an amount by days (SPEC §21, issue #84): what belongs to the year up to its end (ratei) or after it
|
||||
/// (risconti), counting the days of the period both ends included.
|
||||
/// </summary>
|
||||
public static class AccrualDeferralCalculator
|
||||
{
|
||||
/// <summary>The share of an amount posted at the year end.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <param name="amount">The whole amount.</param>
|
||||
/// <param name="start">The first day of the period.</param>
|
||||
/// <param name="end">The last day of the period.</param>
|
||||
/// <param name="yearEnd">The last day of the year.</param>
|
||||
/// <returns>For ratei the days up to the year end, for risconti those after it, rounded to the cent.</returns>
|
||||
public static decimal Share(AccrualKind kind, decimal amount, DateOnly start, DateOnly end, DateOnly yearEnd)
|
||||
{
|
||||
if (end < start)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
var total = end.DayNumber - start.DayNumber + 1;
|
||||
var within = Math.Clamp(yearEnd.DayNumber - start.DayNumber + 1, 0, total);
|
||||
var days = kind is AccrualKind.AccruedIncome or AccrualKind.AccruedExpense ? within : total - within;
|
||||
return Math.Round(amount * days / total, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
/// <summary>The days of the period that belong to the year and to the next years.</summary>
|
||||
/// <param name="start">The first day of the period.</param>
|
||||
/// <param name="end">The last day of the period.</param>
|
||||
/// <param name="yearEnd">The last day of the year.</param>
|
||||
/// <returns>The days of the year, the days after, the total.</returns>
|
||||
public static (int Within, int After, int Total) Days(DateOnly start, DateOnly end, DateOnly yearEnd)
|
||||
{
|
||||
if (end < start)
|
||||
{
|
||||
return (0, 0, 0);
|
||||
}
|
||||
|
||||
var total = end.DayNumber - start.DayNumber + 1;
|
||||
var within = Math.Clamp(yearEnd.DayNumber - start.DayNumber + 1, 0, total);
|
||||
return (within, total - within, total);
|
||||
}
|
||||
|
||||
/// <summary>Whether the adjustment is a cost (ratei passivi, risconti attivi on cost accounts) or a revenue.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns><see langword="true"/> for costs.</returns>
|
||||
public static bool IsCost(AccrualKind kind) => kind is AccrualKind.AccruedExpense or AccrualKind.PrepaidExpense;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The exchange difference of an open item in foreign currency at the year end (SPEC §21, issue #84): the residual in
|
||||
/// the currency valued at the rate of the year end against its value in euro at the rate of the document.
|
||||
/// </summary>
|
||||
public static class ExchangeDifferenceCalculator
|
||||
{
|
||||
/// <summary>The residual in the currency of the document.</summary>
|
||||
/// <param name="residualEuro">The residual in euro, at the rate of the document.</param>
|
||||
/// <param name="documentRate">Units of the currency for one euro on the document.</param>
|
||||
/// <returns>The residual in the currency.</returns>
|
||||
public static decimal InCurrency(decimal residualEuro, decimal documentRate) => Math.Round(residualEuro * documentRate, 2, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>The difference in euro: positive increases the residual in euro.</summary>
|
||||
/// <param name="residualEuro">The residual in euro, at the rate of the document.</param>
|
||||
/// <param name="documentRate">Units of the currency for one euro on the document.</param>
|
||||
/// <param name="yearEndRate">Units of the currency for one euro at the year end.</param>
|
||||
/// <returns>The new value less the old one, rounded to the cent.</returns>
|
||||
public static decimal Difference(decimal residualEuro, decimal documentRate, decimal yearEndRate)
|
||||
{
|
||||
if (documentRate <= 0m || yearEndRate <= 0m)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
var revalued = Math.Round(residualEuro * documentRate / yearEndRate, 2, MidpointRounding.AwayFromZero);
|
||||
return revalued - residualEuro;
|
||||
}
|
||||
|
||||
/// <summary>Whether a difference is a gain for the company.</summary>
|
||||
/// <param name="direction">A receivable or a payable.</param>
|
||||
/// <param name="difference">The difference of the residual in euro.</param>
|
||||
/// <returns>A larger receivable or a smaller payable is a gain.</returns>
|
||||
public static bool IsGain(OpenItemDirection direction, decimal difference) =>
|
||||
direction == OpenItemDirection.Receivable ? difference > 0m : difference < 0m;
|
||||
}
|
||||
|
||||
/// <summary>The state of a year-end closing.</summary>
|
||||
public enum ClosingStatus
|
||||
{
|
||||
/// <summary>Steps being run.</summary>
|
||||
InProgress = 0,
|
||||
|
||||
/// <summary>Every step done and the year locked: read only.</summary>
|
||||
Locked = 1,
|
||||
}
|
||||
|
||||
/// <summary>The state of a step of the closing.</summary>
|
||||
public enum ClosingStepStatus
|
||||
{
|
||||
/// <summary>Not run yet.</summary>
|
||||
Pending = 0,
|
||||
|
||||
/// <summary>Run, with entries or without anything to do.</summary>
|
||||
Done = 1,
|
||||
|
||||
/// <summary>Checks passed.</summary>
|
||||
Passed = 2,
|
||||
|
||||
/// <summary>Run with something to look at (warnings).</summary>
|
||||
ToVerify = 3,
|
||||
|
||||
/// <summary>Checks failed: the next steps wait.</summary>
|
||||
Failed = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The guided closing of a fiscal year (SPEC §11.7, mockup 050, <c>closing_runs</c>): its steps, the year that
|
||||
/// follows and the lock.
|
||||
/// </summary>
|
||||
public sealed class ClosingRun : Entity<long>
|
||||
{
|
||||
/// <summary>The year closed.</summary>
|
||||
public long FiscalYearId { get; set; }
|
||||
|
||||
/// <summary>The code of the year, such as <c>2026</c>.</summary>
|
||||
public string YearCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public ClosingStatus Status { get; set; }
|
||||
|
||||
/// <summary>The year opened by the closing.</summary>
|
||||
public long? NextFiscalYearId { get; set; }
|
||||
|
||||
/// <summary>The result of the year: positive a profit.</summary>
|
||||
public decimal Result { get; set; }
|
||||
|
||||
/// <summary>When the year was locked.</summary>
|
||||
public DateTime? LockedAt { get; set; }
|
||||
|
||||
/// <summary>Who locked it.</summary>
|
||||
public string? LockedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A step of a closing (<c>closing_steps</c>): run, repeated or undone until the year is locked.</summary>
|
||||
public sealed class ClosingStep : Entity<long>
|
||||
{
|
||||
/// <summary>The closing.</summary>
|
||||
public long RunId { get; set; }
|
||||
|
||||
/// <summary>The number, 1-9.</summary>
|
||||
public int Number { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public ClosingStepStatus Status { get; set; }
|
||||
|
||||
/// <summary>The entries written by the step.</summary>
|
||||
public int Entries { get; set; }
|
||||
|
||||
/// <summary>The amount the step worked on (depreciation, inventory, result...).</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>What happened, one message per line (codes of texts with their values).</summary>
|
||||
public string? Messages { get; set; }
|
||||
|
||||
/// <summary>When it ran.</summary>
|
||||
public DateTime? ExecutedAt { get; set; }
|
||||
|
||||
/// <summary>Who ran it.</summary>
|
||||
public string? ExecutedBy { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A final print of a closing (<c>closing_prints</c>): the books of the year, kept with the closing.</summary>
|
||||
public sealed class ClosingPrint : Entity<long>
|
||||
{
|
||||
/// <summary>The closing.</summary>
|
||||
public long RunId { get; set; }
|
||||
|
||||
/// <summary>What the print is: <c>journal</c>, <c>inventory</c>, <c>vat</c>, <c>assets</c>.</summary>
|
||||
public string Kind { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The file name.</summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The pages.</summary>
|
||||
public int Pages { get; set; }
|
||||
|
||||
/// <summary>The PDF.</summary>
|
||||
public byte[] Content { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>The figures the financial ratios read, from the reclassified statements.</summary>
|
||||
/// <param name="Equity">Patrimonio netto, with the result of the year.</param>
|
||||
/// <param name="Result">The result of the year.</param>
|
||||
/// <param name="OperatingResult">The operating result (EBIT, A-B).</param>
|
||||
/// <param name="Revenue">The revenue of sales (A.1).</param>
|
||||
/// <param name="TotalAssets">The total assets (capitale investito).</param>
|
||||
/// <param name="FixedAssets">The fixed assets, net.</param>
|
||||
/// <param name="CurrentAssets">The current assets (with accruals).</param>
|
||||
/// <param name="Inventory">The inventory.</param>
|
||||
/// <param name="Liquidity">Cash and banks.</param>
|
||||
/// <param name="Receivables">Trade receivables.</param>
|
||||
/// <param name="CurrentLiabilities">Liabilities due within the year (with accruals).</param>
|
||||
/// <param name="LongTermLiabilities">Liabilities due later, funds and severance.</param>
|
||||
/// <param name="Payables">Trade payables.</param>
|
||||
/// <param name="Purchases">Purchases of materials and services (B.6, B.7).</param>
|
||||
/// <param name="Days">The days of the period (365 for a year).</param>
|
||||
public sealed record RatioInputs(
|
||||
decimal Equity, decimal Result, decimal OperatingResult, decimal Revenue, decimal TotalAssets, decimal FixedAssets, decimal CurrentAssets,
|
||||
decimal Inventory, decimal Liquidity, decimal Receivables, decimal CurrentLiabilities, decimal LongTermLiabilities, decimal Payables,
|
||||
decimal Purchases, int Days);
|
||||
|
||||
/// <summary>A financial ratio.</summary>
|
||||
/// <param name="Code">The code, such as <c>ROE</c>.</param>
|
||||
/// <param name="Value">The value; <see langword="null"/> when the denominator is zero.</param>
|
||||
/// <param name="Percent">Shown as a percent.</param>
|
||||
/// <param name="DaysUnit">Shown in days.</param>
|
||||
public sealed record FinancialRatio(string Code, decimal? Value, bool Percent = false, bool DaysUnit = false);
|
||||
|
||||
/// <summary>
|
||||
/// The financial ratios of the statements (SPEC §11.7, mockup 051): profitability (ROE, ROI, ROS), liquidity (current,
|
||||
/// quick), solidity (equity ratio, leverage, fixed asset coverage), rotation (days of customers and suppliers).
|
||||
/// </summary>
|
||||
public static class FinancialRatios
|
||||
{
|
||||
/// <summary>Computes the ratios.</summary>
|
||||
/// <param name="input">The figures.</param>
|
||||
/// <returns>The ratios, in display order.</returns>
|
||||
public static IReadOnlyList<FinancialRatio> Compute(RatioInputs input)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var days = input.Days <= 0 ? 365 : input.Days;
|
||||
return
|
||||
[
|
||||
new("ROE", Ratio(input.Result, input.Equity, 100m), Percent: true),
|
||||
new("ROI", Ratio(input.OperatingResult, input.TotalAssets, 100m), Percent: true),
|
||||
new("ROS", Ratio(input.OperatingResult, input.Revenue, 100m), Percent: true),
|
||||
new("TURNOVER", Ratio(input.Revenue, input.TotalAssets, 1m)),
|
||||
new("CURRENT", Ratio(input.CurrentAssets, input.CurrentLiabilities, 1m)),
|
||||
new("QUICK", Ratio(input.CurrentAssets - input.Inventory, input.CurrentLiabilities, 1m)),
|
||||
new("EQUITY", Ratio(input.Equity, input.TotalAssets, 100m), Percent: true),
|
||||
new("LEVERAGE", Ratio(input.TotalAssets, input.Equity, 1m)),
|
||||
new("COVERAGE", Ratio(input.Equity + input.LongTermLiabilities, input.FixedAssets, 1m)),
|
||||
new("DSO", Ratio(input.Receivables * days, input.Revenue, 1m), DaysUnit: true),
|
||||
new("DPO", Ratio(input.Payables * days, input.Purchases, 1m), DaysUnit: true),
|
||||
];
|
||||
}
|
||||
|
||||
private static decimal? Ratio(decimal numerator, decimal denominator, decimal factor) =>
|
||||
denominator == 0m ? null : Math.Round(numerator / denominator * factor, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.EInvoicing;
|
||||
|
||||
/// <summary>Where an e-invoice is in its exchange with the SDI (SPEC §11.9, mockup 058).</summary>
|
||||
public enum EInvoiceStatus
|
||||
{
|
||||
/// <summary>The file was written and checked; not sent yet.</summary>
|
||||
Generated = 0,
|
||||
|
||||
/// <summary>Taken by the channel; waiting for the receipt of the SDI.</summary>
|
||||
Sent = 1,
|
||||
|
||||
/// <summary>Delivered to the customer (RC).</summary>
|
||||
Delivered = 2,
|
||||
|
||||
/// <summary>Not delivered, but available in the customer's tax drawer (MC): the invoice is issued.</summary>
|
||||
NotDelivered = 3,
|
||||
|
||||
/// <summary>Rejected by the SDI (NS): the invoice is not issued; correct it and send it again.</summary>
|
||||
Rejected = 4,
|
||||
|
||||
/// <summary>Accepted by the public administration (NE EC01).</summary>
|
||||
Accepted = 5,
|
||||
|
||||
/// <summary>Refused by the public administration (NE EC02): a credit note is needed.</summary>
|
||||
Refused = 6,
|
||||
|
||||
/// <summary>The public administration did not answer within 15 days (DT).</summary>
|
||||
TermsElapsed = 7,
|
||||
|
||||
/// <summary>A public administration could not be reached (AT): the invoice is issued.</summary>
|
||||
Undeliverable = 8,
|
||||
}
|
||||
|
||||
/// <summary>What a notification of the SDI does to an e-invoice.</summary>
|
||||
public static class EInvoiceStates
|
||||
{
|
||||
/// <summary>The state after a notification, by its code (RC, NS, MC, NE, DT, AT); <see langword="null"/> when it does not change.</summary>
|
||||
/// <param name="code">The code of the notification.</param>
|
||||
/// <param name="outcome">The outcome of an NE (EC01, EC02).</param>
|
||||
/// <returns>The new state.</returns>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>The state of the document for a state of its e-invoice.</summary>
|
||||
/// <param name="status">The state of the e-invoice.</param>
|
||||
/// <returns>The state of the document.</returns>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>The steps of the document that lead from one state to another.</summary>
|
||||
/// <param name="current">The state of the document now.</param>
|
||||
/// <param name="target">The state of the e-invoice.</param>
|
||||
/// <returns>The actions, in order (empty when already there).</returns>
|
||||
public static IReadOnlyList<DocumentAction> StepsTo(DocumentStatus current, EInvoiceStatus target)
|
||||
{
|
||||
var steps = new List<DocumentAction>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Whether the invoice is legally issued in this state (everything after the SDI took it, except a rejection).</summary>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns><see langword="true"/> when issued.</returns>
|
||||
public static bool IsIssued(EInvoiceStatus status) => status is not (EInvoiceStatus.Generated or EInvoiceStatus.Sent or EInvoiceStatus.Rejected);
|
||||
|
||||
/// <summary>Whether the state needs the user (a rejection, a refusal).</summary>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns><see langword="true"/> when something must be done.</returns>
|
||||
public static bool NeedsAction(EInvoiceStatus status) => status is EInvoiceStatus.Rejected or EInvoiceStatus.Refused;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An e-invoice file of a document (SPEC §11.9, <c>e_invoices</c>): 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.
|
||||
/// </summary>
|
||||
public sealed class EInvoice : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The family of the document.</summary>
|
||||
public DocumentFamily Family { get; set; }
|
||||
|
||||
/// <summary>The document.</summary>
|
||||
public long DocumentId { get; set; }
|
||||
|
||||
/// <summary>The kind of the document.</summary>
|
||||
public DocumentKind Kind { get; set; }
|
||||
|
||||
/// <summary>The number of the document, for the lists.</summary>
|
||||
public string? DocumentNumber { get; set; }
|
||||
|
||||
/// <summary>The date of the document.</summary>
|
||||
public DateOnly DocumentDate { get; set; }
|
||||
|
||||
/// <summary>The customer, or the supplier of a self-invoice.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The type of the format (Italy: TD01 …).</summary>
|
||||
public string DocumentType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The name of the file (Italy: <c>IT01234567890_00001.xml</c>).</summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The progressive number of the file in the company.</summary>
|
||||
public long Progressive { get; set; }
|
||||
|
||||
/// <summary>The format (Italy: FPR12, FPA12).</summary>
|
||||
public string Format { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The recipient code.</summary>
|
||||
public string? RecipientCode { get; set; }
|
||||
|
||||
/// <summary>The certified mailbox of the recipient.</summary>
|
||||
public string? RecipientPec { get; set; }
|
||||
|
||||
/// <summary>The total of the document.</summary>
|
||||
public decimal TotalAmount { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public EInvoiceStatus Status { get; set; }
|
||||
|
||||
/// <summary>The channel it was sent through (<c>MANUAL</c> when sent from the portal of the AdE).</summary>
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>The identifier of the SDI.</summary>
|
||||
public string? ExchangeId { get; set; }
|
||||
|
||||
/// <summary>The identifier at the channel.</summary>
|
||||
public string? MessageId { get; set; }
|
||||
|
||||
/// <summary>When the file was written (UTC).</summary>
|
||||
public DateTime GeneratedAt { get; set; }
|
||||
|
||||
/// <summary>When it was sent (UTC).</summary>
|
||||
public DateTime? SentAt { get; set; }
|
||||
|
||||
/// <summary>When the last notification arrived (UTC).</summary>
|
||||
public DateTime? LastNotificationAt { get; set; }
|
||||
|
||||
/// <summary>The last message: the error of the channel, or the description of the last notification.</summary>
|
||||
public string? LastMessage { get; set; }
|
||||
|
||||
/// <summary>How many times sending failed.</summary>
|
||||
public int SendAttempts { get; set; }
|
||||
|
||||
/// <summary>The file.</summary>
|
||||
public byte[] Content { get; set; } = [];
|
||||
|
||||
/// <summary>Whether a newer file of the same document replaced it.</summary>
|
||||
public bool Superseded { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A notification of the SDI (<c>e_invoice_notifications</c>), kept as received.</summary>
|
||||
public sealed class EInvoiceNotification : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The e-invoice it is about, when found.</summary>
|
||||
public long? EInvoiceId { get; set; }
|
||||
|
||||
/// <summary>The code (RC, NS, MC, NE, DT, AT, SE).</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The name of the notification file.</summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The name of the invoice file it is about.</summary>
|
||||
public string? InvoiceFileName { get; set; }
|
||||
|
||||
/// <summary>The identifier of the SDI.</summary>
|
||||
public string? ExchangeId { get; set; }
|
||||
|
||||
/// <summary>When it was received (UTC).</summary>
|
||||
public DateTime ReceivedAt { get; set; }
|
||||
|
||||
/// <summary>The outcome of an NE (EC01, EC02).</summary>
|
||||
public string? Outcome { get; set; }
|
||||
|
||||
/// <summary>The description.</summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>The errors of a rejection, one per line: <c>code - description</c>.</summary>
|
||||
public string? Errors { get; set; }
|
||||
|
||||
/// <summary>The channel it came from (<c>MANUAL</c> when uploaded).</summary>
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>The file.</summary>
|
||||
public byte[] Content { get; set; } = [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Where a received invoice is.</summary>
|
||||
public enum InboxFileStatus
|
||||
{
|
||||
/// <summary>Received, to register.</summary>
|
||||
New = 0,
|
||||
|
||||
/// <summary>Registered as a supplier invoice or credit note.</summary>
|
||||
Registered = 1,
|
||||
|
||||
/// <summary>Set aside by the user (a duplicate, an invoice not for the company).</summary>
|
||||
Discarded = 2,
|
||||
|
||||
/// <summary>The file could not be read.</summary>
|
||||
Unreadable = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A supplier invoice received through a channel or uploaded (<c>e_invoice_inbox</c>, issue #79): the file with its
|
||||
/// metadata, what it says, and the purchase document that registers it. The same file never enters twice (hash).
|
||||
/// </summary>
|
||||
public sealed class EInvoiceInboxFile : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The name of the file.</summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The SHA-256 of the file, in hexadecimal.</summary>
|
||||
public string Hash { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The file.</summary>
|
||||
public byte[] Content { get; set; } = [];
|
||||
|
||||
/// <summary>The name of the metadata file (MT).</summary>
|
||||
public string? MetadataFileName { get; set; }
|
||||
|
||||
/// <summary>The metadata file.</summary>
|
||||
public byte[]? Metadata { get; set; }
|
||||
|
||||
/// <summary>The identifier of the SDI.</summary>
|
||||
public string? ExchangeId { get; set; }
|
||||
|
||||
/// <summary>When it was received (UTC).</summary>
|
||||
public DateTime ReceivedAt { get; set; }
|
||||
|
||||
/// <summary>The channel (<c>MANUAL</c> when uploaded).</summary>
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>The VAT number of the supplier.</summary>
|
||||
public string? SupplierVat { get; set; }
|
||||
|
||||
/// <summary>The name of the supplier.</summary>
|
||||
public string? SupplierName { get; set; }
|
||||
|
||||
/// <summary>The type of the document (TD01 …).</summary>
|
||||
public string? DocumentType { get; set; }
|
||||
|
||||
/// <summary>The number of the invoice.</summary>
|
||||
public string? Number { get; set; }
|
||||
|
||||
/// <summary>The date of the invoice.</summary>
|
||||
public DateOnly? DocumentDate { get; set; }
|
||||
|
||||
/// <summary>The total of the invoice.</summary>
|
||||
public decimal? TotalAmount { get; set; }
|
||||
|
||||
/// <summary>The supplier in the archive, when found.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public InboxFileStatus Status { get; set; }
|
||||
|
||||
/// <summary>The purchase document that registers it.</summary>
|
||||
public long? PurchaseDocumentId { get; set; }
|
||||
|
||||
/// <summary>Why it could not be read or registered.</summary>
|
||||
public string? Error { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings of a channel in a company (<c>e_invoice_channels</c>, mockup 059). Passwords, keys and certificates are
|
||||
/// stored protected (<c>ISecretProtector</c>, purpose <c>einvoice.channel</c>) and never shown again.
|
||||
/// </summary>
|
||||
public sealed class EInvoiceChannelSetting : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The code of the channel.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Whether it is used.</summary>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>Whether it is paused: no sending and no polling until resumed.</summary>
|
||||
public bool Paused { get; set; }
|
||||
|
||||
/// <summary>The certified mailbox (PEC).</summary>
|
||||
public string? Mailbox { get; set; }
|
||||
|
||||
/// <summary>The SMTP server.</summary>
|
||||
public string? SmtpHost { get; set; }
|
||||
|
||||
/// <summary>The SMTP port.</summary>
|
||||
public int SmtpPort { get; set; } = 465;
|
||||
|
||||
/// <summary>The IMAP server.</summary>
|
||||
public string? ImapHost { get; set; }
|
||||
|
||||
/// <summary>The IMAP port.</summary>
|
||||
public int ImapPort { get; set; } = 993;
|
||||
|
||||
/// <summary>Whether the connections use TLS.</summary>
|
||||
public bool Tls { get; set; } = true;
|
||||
|
||||
/// <summary>The user.</summary>
|
||||
public string? UserName { get; set; }
|
||||
|
||||
/// <summary>The password, protected.</summary>
|
||||
public string? ProtectedPassword { get; set; }
|
||||
|
||||
/// <summary>The address of the SDI to write to (PEC), learned from its messages.</summary>
|
||||
public string? ExchangeAddress { get; set; }
|
||||
|
||||
/// <summary>The folder of the mailbox for processed messages.</summary>
|
||||
public string? ArchiveFolder { get; set; }
|
||||
|
||||
/// <summary>The address of the web service or API.</summary>
|
||||
public string? Endpoint { get; set; }
|
||||
|
||||
/// <summary>The client certificate (PKCS#12, base64), protected.</summary>
|
||||
public string? ProtectedCertificate { get; set; }
|
||||
|
||||
/// <summary>The password of the certificate, protected.</summary>
|
||||
public string? ProtectedCertificatePassword { get; set; }
|
||||
|
||||
/// <summary>The API key, protected.</summary>
|
||||
public string? ProtectedApiKey { get; set; }
|
||||
|
||||
/// <summary>Whether the test environment is used.</summary>
|
||||
public bool TestEnvironment { get; set; }
|
||||
|
||||
/// <summary>When the connection was last tested (UTC).</summary>
|
||||
public DateTime? LastCheckAt { get; set; }
|
||||
|
||||
/// <summary>Whether the last test worked.</summary>
|
||||
public bool? LastCheckOk { get; set; }
|
||||
|
||||
/// <summary>What the last test said.</summary>
|
||||
public string? LastCheckMessage { get; set; }
|
||||
|
||||
/// <summary>When the channel was last read (UTC).</summary>
|
||||
public DateTime? LastPollAt { get; set; }
|
||||
|
||||
/// <summary>What the last reading found, or its error.</summary>
|
||||
public string? LastPollMessage { get; set; }
|
||||
|
||||
/// <summary>Whether the last reading failed.</summary>
|
||||
public bool LastPollFailed { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>When a routing rule applies.</summary>
|
||||
public enum SdiRoutingCondition
|
||||
{
|
||||
/// <summary>Always (the last rule, usually).</summary>
|
||||
Default = 0,
|
||||
|
||||
/// <summary>The customer is a public administration.</summary>
|
||||
PublicAdministration = 1,
|
||||
|
||||
/// <summary>The customer has the code in <see cref="SdiRoutingRule.Value"/>.</summary>
|
||||
Party = 2,
|
||||
|
||||
/// <summary>The type of the format is the one in <see cref="SdiRoutingRule.Value"/> (TD01, TD17 …).</summary>
|
||||
DocumentType = 3,
|
||||
|
||||
/// <summary>The files sent today are at least the number in <see cref="SdiRoutingRule.Value"/>.</summary>
|
||||
DailyVolume = 4,
|
||||
}
|
||||
|
||||
/// <summary>A rule of the router (<c>e_invoice_routing</c>, issue #77): the first enabled rule that applies chooses the channel.</summary>
|
||||
public sealed class SdiRoutingRule : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The order (lower first).</summary>
|
||||
public int Position { get; set; }
|
||||
|
||||
/// <summary>When it applies.</summary>
|
||||
public SdiRoutingCondition Condition { get; set; }
|
||||
|
||||
/// <summary>The value of the condition.</summary>
|
||||
public string? Value { get; set; }
|
||||
|
||||
/// <summary>The channel.</summary>
|
||||
public string ChannelCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The channel used when the first is paused, disabled or fails.</summary>
|
||||
public string? FallbackChannelCode { get; set; }
|
||||
|
||||
/// <summary>Whether the rule is ignored.</summary>
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>What the router knows of a file to send.</summary>
|
||||
/// <param name="DocumentType">The type of the format.</param>
|
||||
/// <param name="PartyCode">The code of the customer.</param>
|
||||
/// <param name="PublicAdministration">Whether the customer is a public administration.</param>
|
||||
/// <param name="SentToday">How many files were sent today.</param>
|
||||
public sealed record SdiRoutingInput(string DocumentType, string? PartyCode, bool PublicAdministration, int SentToday);
|
||||
|
||||
/// <summary>The channels chosen for a file.</summary>
|
||||
/// <param name="Channel">The channel to use.</param>
|
||||
/// <param name="Fallback">The channel to try when the first fails.</param>
|
||||
/// <param name="RuleId">The rule that chose them.</param>
|
||||
public sealed record SdiRoute(string Channel, string? Fallback, long? RuleId);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class SdiRouter
|
||||
{
|
||||
/// <summary>Chooses.</summary>
|
||||
/// <param name="input">The file.</param>
|
||||
/// <param name="rules">The rules.</param>
|
||||
/// <param name="usable">The codes of the channels enabled and not paused, in the order of the pack.</param>
|
||||
/// <returns>The route, or <see langword="null"/> when no channel can take the file.</returns>
|
||||
public static SdiRoute? Choose(SdiRoutingInput input, IEnumerable<SdiRoutingRule> rules, IReadOnlyList<string> 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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A conservation package exported (<c>e_invoice_conservation</c>, issue #79): what went out, and its fingerprint.</summary>
|
||||
public sealed class ConservationExport : Entity<long>
|
||||
{
|
||||
/// <summary>The first day.</summary>
|
||||
public DateOnly FromDate { get; set; }
|
||||
|
||||
/// <summary>The last day.</summary>
|
||||
public DateOnly ToDate { get; set; }
|
||||
|
||||
/// <summary>The files in the package.</summary>
|
||||
public int FileCount { get; set; }
|
||||
|
||||
/// <summary>The name of the package.</summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The SHA-256 of the package.</summary>
|
||||
public string Hash { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The size in bytes.</summary>
|
||||
public long Size { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Parties;
|
||||
|
||||
/// <summary>Whether a declaration of intent was received from a customer or issued by the company.</summary>
|
||||
public enum IntentDirection
|
||||
{
|
||||
/// <summary>Received from a habitual exporter customer: its sales go without VAT up to the ceiling.</summary>
|
||||
Received = 0,
|
||||
|
||||
/// <summary>Issued by the company to a supplier, on its own ceiling (plafond).</summary>
|
||||
Issued = 1,
|
||||
}
|
||||
|
||||
/// <summary>The state of a declaration of intent.</summary>
|
||||
public enum IntentStatus
|
||||
{
|
||||
/// <summary>In force.</summary>
|
||||
Active = 0,
|
||||
|
||||
/// <summary>The ceiling is used up.</summary>
|
||||
Exhausted = 1,
|
||||
|
||||
/// <summary>Revoked or replaced.</summary>
|
||||
Revoked = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A declaration of intent (dichiarazione d'intento, SPEC §11.7, mockup 061, <c>intent_declarations</c>): a habitual
|
||||
/// exporter buys without VAT (art. 8 c. 1 lett. c DPR 633/72) up to the ceiling it declares; the invoices carry the
|
||||
/// protocol of the Agenzia delle Entrate and the nature N3.5. The register keeps the declarations received and issued
|
||||
/// in chronological order with the ceiling used.
|
||||
/// </summary>
|
||||
public sealed class IntentDeclaration : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>Received or issued.</summary>
|
||||
public IntentDirection Direction { get; set; }
|
||||
|
||||
/// <summary>The progressive of the chronological register in the year.</summary>
|
||||
public int RegisterNumber { get; set; }
|
||||
|
||||
/// <summary>The year.</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The customer (received) or supplier (issued).</summary>
|
||||
public long PartyId { get; set; }
|
||||
|
||||
/// <summary>The number given by the declarant, such as <c>12345/2026</c>.</summary>
|
||||
public string Number { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The day of the declaration.</summary>
|
||||
public DateOnly DeclarationDate { get; set; }
|
||||
|
||||
/// <summary>The protocol of the receipt of the Agenzia delle Entrate (17 digits, dash, 6 digits).</summary>
|
||||
public string Protocol { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The ceiling declared.</summary>
|
||||
public decimal Ceiling { get; set; }
|
||||
|
||||
/// <summary>The ceiling used by the invoices.</summary>
|
||||
public decimal Used { get; set; }
|
||||
|
||||
/// <summary>The first day it covers.</summary>
|
||||
public DateOnly ValidFrom { get; set; }
|
||||
|
||||
/// <summary>The last day it covers.</summary>
|
||||
public DateOnly ValidTo { get; set; }
|
||||
|
||||
/// <summary>The VAT code the invoices use (nature N3.5).</summary>
|
||||
public long? TaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public IntentStatus Status { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>The ceiling left.</summary>
|
||||
public decimal Remaining => Ceiling - Used;
|
||||
|
||||
/// <summary>The share used, percent.</summary>
|
||||
public decimal UsedPercent => Ceiling <= 0m ? 0m : Math.Round(Used / Ceiling * 100m, 0, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>Whether it covers a day.</summary>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <returns><see langword="true"/> when active and the day is in its period.</returns>
|
||||
public bool Covers(DateOnly date) => Status != IntentStatus.Revoked && ValidFrom <= date && date <= ValidTo;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Khaemhat.Core.EInvoicing;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="EInvoice"/> to <c>e_invoices</c>.</summary>
|
||||
public sealed class EInvoiceMap : EntityMap<EInvoice>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="EInvoiceNotification"/> to <c>e_invoice_notifications</c>.</summary>
|
||||
public sealed class EInvoiceNotificationMap : EntityMap<EInvoiceNotification>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="EInvoiceInboxFile"/> to <c>e_invoice_inbox</c>.</summary>
|
||||
public sealed class EInvoiceInboxFileMap : EntityMap<EInvoiceInboxFile>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="EInvoiceChannelSetting"/> to <c>e_invoice_channels</c>.</summary>
|
||||
public sealed class EInvoiceChannelSettingMap : EntityMap<EInvoiceChannelSetting>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="SdiRoutingRule"/> to <c>e_invoice_routing</c>.</summary>
|
||||
public sealed class SdiRoutingRuleMap : EntityMap<SdiRoutingRule>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public SdiRoutingRuleMap()
|
||||
{
|
||||
ToTable("e_invoice_routing");
|
||||
Map(x => x.Value).MaxLength(40);
|
||||
Map(x => x.ChannelCode).MaxLength(20);
|
||||
Map(x => x.FallbackChannelCode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ConservationExport"/> to <c>e_invoice_conservation</c>.</summary>
|
||||
public sealed class ConservationExportMap : EntityMap<ConservationExport>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ConservationExportMap()
|
||||
{
|
||||
ToTable("e_invoice_conservation");
|
||||
Map(x => x.FileName).MaxLength(100);
|
||||
Map(x => x.Hash).MaxLength(64);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[Migration(20261113_004, "create_einvoicing")]
|
||||
public sealed class M20261113_004_CreateEInvoicing : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// The year end (SPEC §11.7, ADR 0041-0043, issues #82-#86): the fixed assets with their categories and movements, the
|
||||
/// accruals and deferrals, the guided closing with its steps and final prints, the Intrastat lists and the declarations
|
||||
/// of intent; the entries remember the step of the closing that wrote them.
|
||||
/// </summary>
|
||||
[Migration(20261113_005, "create_year_end")]
|
||||
public sealed class M20261113_005_CreateYearEnd : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.AlterTable("gl_entries", t => t.Int32("closing_step"));
|
||||
|
||||
schema.CreateTable("fixed_asset_categories", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 20).NotNull();
|
||||
t.String("description", 100).NotNull();
|
||||
t.Bool("disabled").NotNull().Default(false);
|
||||
t.String("class", 40).NotNull();
|
||||
t.String("ministerial_group", 20);
|
||||
t.Decimal("civil_rate").NotNull().Default(0m);
|
||||
t.Decimal("fiscal_rate").NotNull().Default(0m);
|
||||
t.Bool("civil_half_first_year").NotNull().Default(true);
|
||||
t.Int64("asset_account_id");
|
||||
t.Int64("fund_account_id");
|
||||
t.Int64("depreciation_account_id");
|
||||
t.Decimal("deductible_percent").NotNull().Default(100m);
|
||||
t.Decimal("cost_limit");
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_fixed_asset_categories_code", "code");
|
||||
t.ForeignKey("fk_fixed_asset_categories_asset", "asset_account_id", "gl_accounts", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_fixed_asset_categories_fund", "fund_account_id", "gl_accounts", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_fixed_asset_categories_depreciation", "depreciation_account_id", "gl_accounts", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("fixed_assets", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 20).NotNull();
|
||||
t.String("description", 200).NotNull();
|
||||
t.Int64("category_id").NotNull();
|
||||
t.Date("purchase_date").NotNull();
|
||||
t.Date("in_service_date").NotNull();
|
||||
t.Int64("supplier_id");
|
||||
t.String("document_reference", 60);
|
||||
t.String("location", 100);
|
||||
t.String("serial_number", 60);
|
||||
t.Decimal("quantity").NotNull().Default(1m);
|
||||
t.Decimal("cost").NotNull().Default(0m);
|
||||
t.Decimal("civil_fund").NotNull().Default(0m);
|
||||
t.Decimal("fiscal_fund").NotNull().Default(0m);
|
||||
t.Decimal("civil_rate");
|
||||
t.Decimal("fiscal_rate");
|
||||
t.Decimal("residual_value").NotNull().Default(0m);
|
||||
t.Bool("low_value").NotNull().Default(false);
|
||||
t.String("status", 40).NotNull();
|
||||
t.Date("disposal_date");
|
||||
t.Int32("last_depreciation_year");
|
||||
t.String("notes", 500);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_fixed_assets_code", "code");
|
||||
t.Index("ix_fixed_assets_category", "category_id");
|
||||
t.ForeignKey("fk_fixed_assets_category", "category_id", "fixed_asset_categories", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_fixed_assets_supplier", "supplier_id", "parties", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("fixed_asset_movements", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("asset_id").NotNull();
|
||||
t.String("kind", 40).NotNull();
|
||||
t.Date("movement_date").NotNull();
|
||||
t.Int32("year").NotNull();
|
||||
t.Decimal("cost_amount").NotNull().Default(0m);
|
||||
t.Decimal("civil_amount").NotNull().Default(0m);
|
||||
t.Decimal("fiscal_amount").NotNull().Default(0m);
|
||||
t.Decimal("proceeds").NotNull().Default(0m);
|
||||
t.Decimal("gain_loss").NotNull().Default(0m);
|
||||
t.String("description", 200);
|
||||
t.Int64("gl_entry_id");
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Index("ix_fixed_asset_movements_asset", "asset_id", "movement_date");
|
||||
t.Index("ix_fixed_asset_movements_year", "year", "kind");
|
||||
t.ForeignKey("fk_fixed_asset_movements_asset", "asset_id", "fixed_assets", ReferentialAction.Cascade);
|
||||
t.ForeignKey("fk_fixed_asset_movements_entry", "gl_entry_id", "gl_entries", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("accruals", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int32("year").NotNull();
|
||||
t.String("kind", 40).NotNull();
|
||||
t.String("description", 200).NotNull();
|
||||
t.Int64("account_id").NotNull();
|
||||
t.Decimal("amount").NotNull().Default(0m);
|
||||
t.Date("period_start").NotNull();
|
||||
t.Date("period_end").NotNull();
|
||||
t.Date("year_end").NotNull();
|
||||
t.Decimal("adjustment").NotNull().Default(0m);
|
||||
t.String("source_family", 40);
|
||||
t.Int64("source_document_id");
|
||||
t.String("document_number", 40);
|
||||
t.Int64("party_id");
|
||||
t.Int64("gl_entry_id");
|
||||
t.Int64("reversal_entry_id");
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Index("ix_accruals_year", "year");
|
||||
t.ForeignKey("fk_accruals_account", "account_id", "gl_accounts", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_accruals_entry", "gl_entry_id", "gl_entries", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_accruals_reversal", "reversal_entry_id", "gl_entries", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("closing_runs", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("fiscal_year_id").NotNull();
|
||||
t.String("year_code", 10).NotNull();
|
||||
t.String("status", 40).NotNull();
|
||||
t.Int64("next_fiscal_year_id");
|
||||
t.Decimal("result").NotNull().Default(0m);
|
||||
t.DateTimeUtc("locked_at");
|
||||
t.String("locked_by", 100);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_closing_runs_year", "fiscal_year_id");
|
||||
t.ForeignKey("fk_closing_runs_year", "fiscal_year_id", "fiscal_years", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("closing_steps", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("run_id").NotNull();
|
||||
t.Int32("number").NotNull();
|
||||
t.String("status", 40).NotNull();
|
||||
t.Int32("entries").NotNull().Default(0);
|
||||
t.Decimal("amount").NotNull().Default(0m);
|
||||
t.Text("messages");
|
||||
t.DateTimeUtc("executed_at");
|
||||
t.String("executed_by", 100);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_closing_steps_number", "run_id", "number");
|
||||
t.ForeignKey("fk_closing_steps_run", "run_id", "closing_runs", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("closing_prints", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("run_id").NotNull();
|
||||
t.String("kind", 20).NotNull();
|
||||
t.String("file_name", 100).NotNull();
|
||||
t.Int32("pages").NotNull().Default(0);
|
||||
t.Bytes("content").NotNull();
|
||||
t.AuditColumns();
|
||||
t.Index("ix_closing_prints_run", "run_id");
|
||||
t.ForeignKey("fk_closing_prints_run", "run_id", "closing_runs", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("intrastat_lists", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("flow", 40).NotNull();
|
||||
t.Int32("year").NotNull();
|
||||
t.Int32("period").NotNull();
|
||||
t.String("periodicity", 40).NotNull();
|
||||
t.String("status", 40).NotNull();
|
||||
t.Int32("progressive").NotNull().Default(1);
|
||||
t.Decimal("goods_amount").NotNull().Default(0m);
|
||||
t.Decimal("services_amount").NotNull().Default(0m);
|
||||
t.Int32("problems").NotNull().Default(0);
|
||||
t.String("file_name", 60);
|
||||
t.String("protocol", 40);
|
||||
t.DateTimeUtc("generated_at");
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_intrastat_lists_period", "flow", "year", "periodicity", "period");
|
||||
});
|
||||
|
||||
schema.CreateTable("intrastat_list_lines", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("list_id").NotNull();
|
||||
t.String("section", 40).NotNull();
|
||||
t.String("source_family", 40);
|
||||
t.Int64("source_document_id");
|
||||
t.String("document_number", 40);
|
||||
t.Date("document_date");
|
||||
t.Int64("party_id");
|
||||
t.String("country_code", 2).NotNull();
|
||||
t.String("vat_number", 20);
|
||||
t.Decimal("amount").NotNull().Default(0m);
|
||||
t.Decimal("currency_amount");
|
||||
t.Decimal("statistical_value");
|
||||
t.String("nomenclature_code", 10);
|
||||
t.String("description", 200);
|
||||
t.String("transaction_nature", 2);
|
||||
t.String("delivery_terms", 3);
|
||||
t.String("transport_mode", 1);
|
||||
t.Decimal("net_mass");
|
||||
t.Decimal("supplementary_units");
|
||||
t.String("origin_country", 2);
|
||||
t.String("province", 2);
|
||||
t.String("supply_mode", 1);
|
||||
t.String("payment_mode", 1);
|
||||
t.String("payment_country", 2);
|
||||
t.Int32("corrected_year");
|
||||
t.Int32("corrected_period");
|
||||
t.String("correction_sign", 1);
|
||||
t.String("check", 40).NotNull();
|
||||
t.Bool("manual").NotNull().Default(false);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Index("ix_intrastat_list_lines_list", "list_id", "section");
|
||||
t.ForeignKey("fk_intrastat_list_lines_list", "list_id", "intrastat_lists", ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
schema.CreateTable("intent_declarations", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("direction", 40).NotNull();
|
||||
t.Int32("register_number").NotNull();
|
||||
t.Int32("year").NotNull();
|
||||
t.Int64("party_id").NotNull();
|
||||
t.String("number", 40).NotNull();
|
||||
t.Date("declaration_date").NotNull();
|
||||
t.String("protocol", 40).NotNull();
|
||||
t.Decimal("ceiling").NotNull().Default(0m);
|
||||
t.Decimal("used").NotNull().Default(0m);
|
||||
t.Date("valid_from").NotNull();
|
||||
t.Date("valid_to").NotNull();
|
||||
t.Int64("tax_code_id");
|
||||
t.String("status", 40).NotNull();
|
||||
t.String("notes", 500);
|
||||
t.DemoColumn();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_intent_declarations_register", "direction", "year", "register_number");
|
||||
t.Index("ix_intent_declarations_party", "party_id", "valid_from");
|
||||
t.ForeignKey("fk_intent_declarations_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_intent_declarations_tax", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="FixedAssetCategory"/> to <c>fixed_asset_categories</c>.</summary>
|
||||
public sealed class FixedAssetCategoryMap : EntityMap<FixedAssetCategory>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public FixedAssetCategoryMap()
|
||||
{
|
||||
ToTable("fixed_asset_categories");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.MinisterialGroup).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="FixedAsset"/> to <c>fixed_assets</c>.</summary>
|
||||
public sealed class FixedAssetMap : EntityMap<FixedAsset>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public FixedAssetMap()
|
||||
{
|
||||
ToTable("fixed_assets");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(200);
|
||||
Map(x => x.DocumentReference).MaxLength(60);
|
||||
Map(x => x.Location).MaxLength(100);
|
||||
Map(x => x.SerialNumber).MaxLength(60);
|
||||
Map(x => x.Notes).MaxLength(500);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="FixedAssetMovement"/> to <c>fixed_asset_movements</c>.</summary>
|
||||
public sealed class FixedAssetMovementMap : EntityMap<FixedAssetMovement>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public FixedAssetMovementMap()
|
||||
{
|
||||
ToTable("fixed_asset_movements");
|
||||
Map(x => x.Description).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="AccrualDeferral"/> to <c>accruals</c>.</summary>
|
||||
public sealed class AccrualDeferralMap : EntityMap<AccrualDeferral>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public AccrualDeferralMap()
|
||||
{
|
||||
ToTable("accruals");
|
||||
Map(x => x.Description).MaxLength(200);
|
||||
Map(x => x.DocumentNumber).MaxLength(40);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ClosingRun"/> to <c>closing_runs</c>.</summary>
|
||||
public sealed class ClosingRunMap : EntityMap<ClosingRun>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ClosingRunMap()
|
||||
{
|
||||
ToTable("closing_runs");
|
||||
Map(x => x.YearCode).MaxLength(10);
|
||||
Map(x => x.LockedBy).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ClosingStep"/> to <c>closing_steps</c>.</summary>
|
||||
public sealed class ClosingStepMap : EntityMap<ClosingStep>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ClosingStepMap()
|
||||
{
|
||||
ToTable("closing_steps");
|
||||
Map(x => x.ExecutedBy).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ClosingPrint"/> to <c>closing_prints</c>.</summary>
|
||||
public sealed class ClosingPrintMap : EntityMap<ClosingPrint>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ClosingPrintMap()
|
||||
{
|
||||
ToTable("closing_prints");
|
||||
Map(x => x.Kind).MaxLength(20);
|
||||
Map(x => x.FileName).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="IntrastatList"/> to <c>intrastat_lists</c>.</summary>
|
||||
public sealed class IntrastatListMap : EntityMap<IntrastatList>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public IntrastatListMap()
|
||||
{
|
||||
ToTable("intrastat_lists");
|
||||
Map(x => x.FileName).MaxLength(60);
|
||||
Map(x => x.Protocol).MaxLength(40);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="IntrastatListLine"/> to <c>intrastat_list_lines</c>.</summary>
|
||||
public sealed class IntrastatListLineMap : EntityMap<IntrastatListLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public IntrastatListLineMap()
|
||||
{
|
||||
ToTable("intrastat_list_lines");
|
||||
Map(x => x.DocumentNumber).MaxLength(40);
|
||||
Map(x => x.CountryCode).MaxLength(2);
|
||||
Map(x => x.VatNumber).MaxLength(20);
|
||||
Map(x => x.NomenclatureCode).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(200);
|
||||
Map(x => x.TransactionNature).MaxLength(2);
|
||||
Map(x => x.DeliveryTerms).MaxLength(3);
|
||||
Map(x => x.TransportMode).MaxLength(1);
|
||||
Map(x => x.OriginCountry).MaxLength(2);
|
||||
Map(x => x.Province).MaxLength(2);
|
||||
Map(x => x.SupplyMode).MaxLength(1);
|
||||
Map(x => x.PaymentMode).MaxLength(1);
|
||||
Map(x => x.PaymentCountry).MaxLength(2);
|
||||
Map(x => x.CorrectionSign).MaxLength(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="IntentDeclaration"/> to <c>intent_declarations</c>.</summary>
|
||||
public sealed class IntentDeclarationMap : EntityMap<IntentDeclaration>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public IntentDeclarationMap()
|
||||
{
|
||||
ToTable("intent_declarations");
|
||||
Map(x => x.Number).MaxLength(40);
|
||||
Map(x => x.Protocol).MaxLength(40);
|
||||
Map(x => x.Notes).MaxLength(500);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
/// <summary>An e-invoice file: the transmission header, the two parties and one or more invoices.</summary>
|
||||
/// <param name="FileName">The name of the file, as received or as it will be sent.</param>
|
||||
/// <param name="TransmissionFormat">The transmission format (Italy: <c>FPR12</c>, <c>FPA12</c>, <c>FSM10</c>).</param>
|
||||
/// <param name="ProgressiveNumber">The progressive number of the transmission given by the sender.</param>
|
||||
/// <param name="RecipientCode">The recipient code of the transmission.</param>
|
||||
/// <param name="Supplier">The supplier who issued the invoices.</param>
|
||||
/// <param name="Customer">The customer the invoices are addressed to (normally the company).</param>
|
||||
/// <param name="Invoices">The invoices, one per body of the file (a batch has more than one).</param>
|
||||
/// <param name="Signature">The signature of the envelope, or <see langword="null"/> for an unsigned file.</param>
|
||||
/// <param name="Xml">The XML of the invoice, taken out of the envelope when the file was signed.</param>
|
||||
public sealed record EInvoiceFile(
|
||||
string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
|
||||
EInvoiceParty Supplier, EInvoiceParty Customer, IReadOnlyList<EInvoiceBody> Invoices,
|
||||
EInvoiceSignature? Signature, byte[] Xml)
|
||||
{
|
||||
/// <summary>The country of the transmitter (Italy: <c>IdTrasmittente/IdPaese</c>).</summary>
|
||||
public string? TransmitterCountry { get; init; }
|
||||
|
||||
/// <summary>The tax identifier of the transmitter (Italy: <c>IdTrasmittente/IdCodice</c>).</summary>
|
||||
public string? TransmitterId { get; init; }
|
||||
|
||||
/// <summary>The certified mailbox the invoice is delivered to, when there is no recipient code.</summary>
|
||||
public string? RecipientPec { get; init; }
|
||||
|
||||
/// <summary>The e-mail of the transmitter, for the exchange system (Italy: <c>ContattiTrasmittente/Email</c>).</summary>
|
||||
public string? TransmitterEmail { get; init; }
|
||||
|
||||
/// <summary>The third party that issues the invoice for the supplier, if any (Italy: <c>TerzoIntermediarioOSoggettoEmittente</c>).</summary>
|
||||
public EInvoiceParty? Intermediary { get; init; }
|
||||
|
||||
/// <summary>Who issues the document when not the supplier (Italy: <c>SoggettoEmittente</c>, <c>CC</c> customer, <c>TZ</c> third party).</summary>
|
||||
public string? IssuedBy { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The signature of a signed file. <see cref="Verified"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="Verified">Whether the digest and the signature match the content.</param>
|
||||
/// <param name="Signer">The name of the signer, from the certificate.</param>
|
||||
/// <param name="SignerTaxCode">The tax code of the signer, when the certificate carries it.</param>
|
||||
/// <param name="SignedAt">The signing time declared by the signer, if any (not a trusted timestamp).</param>
|
||||
/// <param name="CertificateNotBefore">The start of validity of the certificate.</param>
|
||||
/// <param name="CertificateNotAfter">The end of validity of the certificate.</param>
|
||||
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
|
||||
public sealed record EInvoiceSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
|
||||
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
|
||||
|
||||
/// <summary>A party of the invoice (supplier, customer or intermediary) as written in the file.</summary>
|
||||
/// <param name="CountryCode">The country of the VAT number.</param>
|
||||
/// <param name="VatNumber">The VAT number without the country prefix.</param>
|
||||
/// <param name="TaxCode">The tax code.</param>
|
||||
/// <param name="Name">The company name, when the party is a company.</param>
|
||||
/// <param name="FirstName">The first name, when the party is a person.</param>
|
||||
/// <param name="LastName">The last name, when the party is a person.</param>
|
||||
/// <param name="Address">The street of the registered office.</param>
|
||||
/// <param name="StreetNumber">The street number.</param>
|
||||
/// <param name="PostalCode">The postal code.</param>
|
||||
/// <param name="City">The city.</param>
|
||||
/// <param name="Province">The province.</param>
|
||||
/// <param name="Country">The country of the registered office.</param>
|
||||
/// <param name="TaxRegime">The tax regime (supplier only).</param>
|
||||
/// <param name="Email">The e-mail address (supplier only).</param>
|
||||
/// <param name="Phone">The phone number (supplier only).</param>
|
||||
/// <param name="ReaOffice">The office of the companies register.</param>
|
||||
/// <param name="ReaNumber">The number in the companies register.</param>
|
||||
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)
|
||||
{
|
||||
/// <summary>The company name, or first and last name of a person.</summary>
|
||||
public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||
|
||||
/// <summary>The share capital, for a company in the companies register.</summary>
|
||||
public decimal? ShareCapital { get; init; }
|
||||
|
||||
/// <summary>One or more shareholders (Italy: <c>SU</c> sole, <c>SM</c> several).</summary>
|
||||
public string? Shareholders { get; init; }
|
||||
|
||||
/// <summary>Whether the company is being wound up (Italy: <c>LS</c> yes, <c>LN</c> no).</summary>
|
||||
public string? LiquidationStatus { get; init; }
|
||||
|
||||
/// <summary>The reference of the administration, for the public administration (Italy: <c>RiferimentoAmministrazione</c>).</summary>
|
||||
public string? AdministrationReference { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>An invoice of the file (one body).</summary>
|
||||
/// <param name="DocumentType">The document type (Italy: <c>TD01</c>, <c>TD04</c>...).</param>
|
||||
/// <param name="Currency">The currency code.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="Number">The number of the document.</param>
|
||||
/// <param name="Total">The total amount declared by the supplier, if any.</param>
|
||||
/// <param name="Rounding">The rounding on the total, if any.</param>
|
||||
/// <param name="Causals">The free-text causals.</param>
|
||||
/// <param name="Art73">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).</param>
|
||||
/// <param name="Withholdings">The withholding taxes.</param>
|
||||
/// <param name="StampDuty">The stamp duty, if any.</param>
|
||||
/// <param name="SocialSecurity">The social security contributions.</param>
|
||||
/// <param name="Discounts">The discounts and surcharges on the whole document.</param>
|
||||
/// <param name="Orders">The purchase orders referred to.</param>
|
||||
/// <param name="Contracts">The contracts referred to.</param>
|
||||
/// <param name="RelatedInvoices">The invoices referred to (the invoice a credit note corrects).</param>
|
||||
/// <param name="DeliveryNotes">The delivery notes referred to.</param>
|
||||
/// <param name="Lines">The lines.</param>
|
||||
/// <param name="TaxSummary">The tax summary, one row per rate or nature.</param>
|
||||
/// <param name="Payments">The payment installments.</param>
|
||||
/// <param name="Attachments">The attached files.</param>
|
||||
public sealed record EInvoiceBody(
|
||||
string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
|
||||
IReadOnlyList<string> Causals, bool Art73,
|
||||
IReadOnlyList<EInvoiceWithholding> Withholdings, EInvoiceStampDuty? StampDuty,
|
||||
IReadOnlyList<EInvoiceSocialSecurity> SocialSecurity, IReadOnlyList<EInvoiceDiscount> Discounts,
|
||||
IReadOnlyList<EInvoiceReference> Orders, IReadOnlyList<EInvoiceReference> Contracts,
|
||||
IReadOnlyList<EInvoiceReference> RelatedInvoices, IReadOnlyList<EInvoiceReference> DeliveryNotes,
|
||||
IReadOnlyList<EInvoiceLine> Lines, IReadOnlyList<EInvoiceTaxSummary> TaxSummary,
|
||||
IReadOnlyList<EInvoicePayment> Payments, IReadOnlyList<EInvoiceAttachment> Attachments)
|
||||
{
|
||||
/// <summary>The transport data of an accompanying invoice, if any.</summary>
|
||||
public EInvoiceTransport? Transport { get; init; }
|
||||
|
||||
/// <summary>The payment conditions of the whole document (Italy: <c>TP01</c>, <c>TP02</c>, <c>TP03</c>).</summary>
|
||||
public string? PaymentConditions { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The transport data of an accompanying invoice (Italy: <c>DatiTrasporto</c>).</summary>
|
||||
/// <param name="CarrierName">The carrier.</param>
|
||||
/// <param name="CarrierCountry">The country of the VAT number of the carrier.</param>
|
||||
/// <param name="CarrierVat">The VAT number of the carrier.</param>
|
||||
/// <param name="Means">The means of transport.</param>
|
||||
/// <param name="Reason">The reason of the transport.</param>
|
||||
/// <param name="Packages">The number of packages.</param>
|
||||
/// <param name="Description">The appearance of the goods.</param>
|
||||
/// <param name="GrossWeight">The gross weight, kg.</param>
|
||||
/// <param name="NetWeight">The net weight, kg.</param>
|
||||
/// <param name="Start">When the transport starts.</param>
|
||||
/// <param name="ShippingTerms">The terms of delivery (Incoterms).</param>
|
||||
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);
|
||||
|
||||
/// <summary>A line of an invoice.</summary>
|
||||
/// <param name="Number">The line number.</param>
|
||||
/// <param name="Codes">The item codes (type and value).</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Quantity">The quantity, if given.</param>
|
||||
/// <param name="Unit">The unit of measure, if given.</param>
|
||||
/// <param name="UnitPrice">The unit price.</param>
|
||||
/// <param name="TotalPrice">The total of the line, net of tax.</param>
|
||||
/// <param name="TaxRate">The tax rate in percent (zero with a nature).</param>
|
||||
/// <param name="Nature">The reason of a zero rate (Italy: <c>N2.2</c>...).</param>
|
||||
/// <param name="Discounts">The discounts and surcharges of the line.</param>
|
||||
/// <param name="Withheld">Whether the line is subject to withholding tax.</param>
|
||||
/// <param name="LineType">The kind of line (Italy: <c>SC</c> discount, <c>PR</c> premium, <c>AB</c> rebate,
|
||||
/// <c>AC</c> ancillary cost).</param>
|
||||
/// <param name="PeriodStart">The start of the period the line refers to.</param>
|
||||
/// <param name="PeriodEnd">The end of the period the line refers to.</param>
|
||||
/// <param name="AdministrativeReference">The administrative reference (cost centre, internal code).</param>
|
||||
public sealed record EInvoiceLine(
|
||||
int Number, IReadOnlyList<EInvoiceItemCode> Codes, string Description, decimal? Quantity, string? Unit,
|
||||
decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList<EInvoiceDiscount> Discounts,
|
||||
bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference)
|
||||
{
|
||||
/// <summary>Further data of the line (Italy: <c>AltriDatiGestionali</c>, such as the declaration of intent).</summary>
|
||||
public IReadOnlyList<EInvoiceOtherData> OtherData { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Further data of a line (Italy: <c>AltriDatiGestionali</c>).</summary>
|
||||
/// <param name="Type">The kind of data (Italy: <c>TipoDato</c>, such as <c>INTENTO</c>).</param>
|
||||
/// <param name="Text">A text value.</param>
|
||||
/// <param name="Number">A number value.</param>
|
||||
/// <param name="Date">A date value.</param>
|
||||
public sealed record EInvoiceOtherData(string Type, string? Text, decimal? Number, DateOnly? Date);
|
||||
|
||||
/// <summary>A code of the item of a line.</summary>
|
||||
/// <param name="Type">The kind of code (<c>EAN</c>, <c>SKU</c>, the supplier's code...).</param>
|
||||
/// <param name="Value">The code.</param>
|
||||
public sealed record EInvoiceItemCode(string Type, string Value);
|
||||
|
||||
/// <summary>A discount or surcharge.</summary>
|
||||
/// <param name="IsSurcharge">Whether it is a surcharge (Italy: <c>MG</c>) instead of a discount (<c>SC</c>).</param>
|
||||
/// <param name="Percent">The percentage, if given.</param>
|
||||
/// <param name="Amount">The amount, if given.</param>
|
||||
public sealed record EInvoiceDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount);
|
||||
|
||||
/// <summary>A row of the tax summary.</summary>
|
||||
/// <param name="Rate">The tax rate in percent.</param>
|
||||
/// <param name="Nature">The reason of a zero rate.</param>
|
||||
/// <param name="Taxable">The taxable amount.</param>
|
||||
/// <param name="Tax">The tax.</param>
|
||||
/// <param name="Exigibility">When the tax is due (Italy: <c>I</c> immediate, <c>D</c> deferred, <c>S</c> split payment).</param>
|
||||
/// <param name="LegalReference">The law that justifies the nature.</param>
|
||||
/// <param name="ExpensesAmount">Ancillary expenses, if any.</param>
|
||||
/// <param name="Rounding">The rounding, if any.</param>
|
||||
public sealed record EInvoiceTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility,
|
||||
string? LegalReference, decimal? ExpensesAmount, decimal? Rounding);
|
||||
|
||||
/// <summary>A payment installment.</summary>
|
||||
/// <param name="Conditions">The payment conditions (Italy: <c>TP01</c> installments, <c>TP02</c> full, <c>TP03</c> advance).</param>
|
||||
/// <param name="Method">The payment method (Italy: <c>MP05</c> bank transfer...).</param>
|
||||
/// <param name="DueDate">The due date, if given.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
/// <param name="Iban">The IBAN to pay to, if given.</param>
|
||||
/// <param name="Bic">The BIC, if given.</param>
|
||||
/// <param name="Beneficiary">The beneficiary, if different from the supplier.</param>
|
||||
public sealed record EInvoicePayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount,
|
||||
string? Iban, string? Bic, string? Beneficiary);
|
||||
|
||||
/// <summary>A reference to another document (order, contract, invoice, delivery note).</summary>
|
||||
/// <param name="Id">The number of the document.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="LineNumbers">The lines of the invoice the reference applies to; empty when it applies to all.</param>
|
||||
/// <param name="Cig">The tender code, if any (public administration).</param>
|
||||
/// <param name="Cup">The project code, if any (public administration).</param>
|
||||
public sealed record EInvoiceReference(string? Id, DateOnly? Date, IReadOnlyList<int> LineNumbers, string? Cig, string? Cup);
|
||||
|
||||
/// <summary>A withholding tax.</summary>
|
||||
/// <param name="Type">The kind of withholding (Italy: <c>RT01</c>...).</param>
|
||||
/// <param name="Amount">The amount withheld.</param>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="Reason">The payment reason (Italy: <c>A</c>...), if given.</param>
|
||||
public sealed record EInvoiceWithholding(string Type, decimal Amount, decimal Rate, string? Reason);
|
||||
|
||||
/// <summary>The stamp duty of an invoice.</summary>
|
||||
/// <param name="Virtual">Whether it is paid virtually by the issuer.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
public sealed record EInvoiceStampDuty(bool Virtual, decimal Amount);
|
||||
|
||||
/// <summary>A social security contribution added to the invoice.</summary>
|
||||
/// <param name="Fund">The fund (Italy: <c>TC01</c>...).</param>
|
||||
/// <param name="Rate">The rate of the contribution in percent.</param>
|
||||
/// <param name="Amount">The amount of the contribution.</param>
|
||||
/// <param name="Taxable">The amount the contribution is computed on, if given.</param>
|
||||
/// <param name="TaxRate">The tax rate applied to the contribution.</param>
|
||||
/// <param name="Withheld">Whether the contribution is subject to withholding tax.</param>
|
||||
/// <param name="Nature">The reason of a zero tax rate.</param>
|
||||
public sealed record EInvoiceSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate,
|
||||
bool Withheld, string? Nature);
|
||||
|
||||
/// <summary>A file attached to the invoice.</summary>
|
||||
/// <param name="Name">The name of the attachment.</param>
|
||||
/// <param name="Format">The format declared by the supplier (such as <c>PDF</c>), if any.</param>
|
||||
/// <param name="Description">The description, if any.</param>
|
||||
/// <param name="Content">The decoded content.</param>
|
||||
public sealed record EInvoiceAttachment(string Name, string? Format, string? Description, byte[] Content);
|
||||
|
||||
@@ -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.
|
||||
|
||||
/// <summary>Writes the e-invoice file of the country's format (Italy: FatturaPA <c>FPR12</c>/<c>FPA12</c>).</summary>
|
||||
public interface IEInvoiceWriter
|
||||
{
|
||||
/// <summary>The name of the file to send (Italy: <c>IT01234567890_00A1Z.xml</c>).</summary>
|
||||
/// <param name="transmitterCountry">The country of the transmitter.</param>
|
||||
/// <param name="transmitterId">The tax identifier of the transmitter.</param>
|
||||
/// <param name="progressive">The progressive number of the file for this transmitter, from 1.</param>
|
||||
/// <returns>The file name.</returns>
|
||||
string FileName(string transmitterCountry, string transmitterId, long progressive);
|
||||
|
||||
/// <summary>The progressive written in the file for a progressive number (Italy: base 36, five characters).</summary>
|
||||
/// <param name="progressive">The progressive number, from 1.</param>
|
||||
/// <returns>The text.</returns>
|
||||
string Progressive(long progressive);
|
||||
|
||||
/// <summary>Writes the file.</summary>
|
||||
/// <param name="file">The content; <see cref="EInvoiceFile.Xml"/> and <see cref="EInvoiceFile.Signature"/> are ignored.</param>
|
||||
/// <returns>The XML, UTF-8.</returns>
|
||||
byte[] Write(EInvoiceFile file);
|
||||
}
|
||||
|
||||
/// <summary>How serious a problem found by <see cref="IEInvoiceValidator"/> is.</summary>
|
||||
public enum EInvoiceProblemSeverity
|
||||
{
|
||||
/// <summary>The exchange system would reject the file: it is not sent.</summary>
|
||||
Error = 0,
|
||||
|
||||
/// <summary>The file is accepted but something looks wrong.</summary>
|
||||
Warning = 1,
|
||||
}
|
||||
|
||||
/// <summary>A problem of an e-invoice found before sending.</summary>
|
||||
/// <param name="Code">The code: the check of the exchange system when there is one (Italy: <c>00423</c>), else a
|
||||
/// text code of Khaemhat (<c>einvoice.xml.schema</c>).</param>
|
||||
/// <param name="Path">Where: the element of the format, such as <c>DettaglioLinee[2]/PrezzoTotale</c>.</param>
|
||||
/// <param name="Message">What is wrong, in the language of the format's documentation (Italian for FatturaPA).</param>
|
||||
/// <param name="Severity">Error or warning.</param>
|
||||
public sealed record EInvoiceProblem(string Code, string Path, string Message, EInvoiceProblemSeverity Severity = EInvoiceProblemSeverity.Error);
|
||||
|
||||
/// <summary>Checks an e-invoice before it leaves: the rules of the exchange system and the schema of the format.</summary>
|
||||
public interface IEInvoiceValidator
|
||||
{
|
||||
/// <summary>The version of the rules checked, shown with the results.</summary>
|
||||
string RulesVersion { get; }
|
||||
|
||||
/// <summary>The checks on the content: code lists, lengths, totals, natures, recipient, references.</summary>
|
||||
/// <param name="file">The file content.</param>
|
||||
/// <returns>The problems, errors first; empty when the file can be sent.</returns>
|
||||
IReadOnlyList<EInvoiceProblem> Validate(EInvoiceFile file);
|
||||
|
||||
/// <summary>The checks on the XML: well formed and valid against the schema of the format.</summary>
|
||||
/// <param name="xml">The file.</param>
|
||||
/// <returns>The problems; empty when the file is valid.</returns>
|
||||
IReadOnlyList<EInvoiceProblem> ValidateXml(byte[] xml);
|
||||
}
|
||||
|
||||
/// <summary>What a receipt of the exchange system says (Italy: the SDI notifications).</summary>
|
||||
public enum EInvoiceReceiptKind
|
||||
{
|
||||
/// <summary>Delivered to the customer (Italy: <c>RC</c> ricevuta di consegna).</summary>
|
||||
Delivered = 0,
|
||||
|
||||
/// <summary>Rejected by the exchange system: the invoice is not issued (Italy: <c>NS</c> notifica di scarto).</summary>
|
||||
Rejected = 1,
|
||||
|
||||
/// <summary>Not delivered, made available to the customer (Italy: <c>MC</c> mancata consegna).</summary>
|
||||
NotDelivered = 2,
|
||||
|
||||
/// <summary>The outcome of a public administration: accepted or refused (Italy: <c>NE</c> notifica di esito).</summary>
|
||||
Outcome = 3,
|
||||
|
||||
/// <summary>The public administration did not answer in time (Italy: <c>DT</c> decorrenza termini).</summary>
|
||||
TermsElapsed = 4,
|
||||
|
||||
/// <summary>Sent to a public administration that could not receive it (Italy: <c>AT</c> attestazione).</summary>
|
||||
Undeliverable = 5,
|
||||
|
||||
/// <summary>The metadata that go with a received invoice (Italy: <c>MT</c> file metadati).</summary>
|
||||
Metadata = 6,
|
||||
|
||||
/// <summary>The exchange system rejected the outcome the company sent (Italy: <c>SE</c> scarto esito).</summary>
|
||||
OutcomeRejected = 7,
|
||||
}
|
||||
|
||||
/// <summary>An error listed in a rejection.</summary>
|
||||
/// <param name="Code">The code (Italy: <c>00311</c>).</param>
|
||||
/// <param name="Description">The description given by the exchange system.</param>
|
||||
/// <param name="Hint">The suggestion given with it, if any.</param>
|
||||
public sealed record EInvoiceReceiptError(string Code, string Description, string? Hint);
|
||||
|
||||
/// <summary>A receipt or notification of the exchange system about one file.</summary>
|
||||
/// <param name="Kind">What it says.</param>
|
||||
/// <param name="Code">The short code of the format (Italy: <c>RC</c>, <c>NS</c>...).</param>
|
||||
/// <param name="FileName">The name of the receipt file.</param>
|
||||
/// <param name="InvoiceFileName">The name of the invoice file it is about.</param>
|
||||
/// <param name="ExchangeId">The identifier the exchange system gave to the invoice file (Italy: <c>IdentificativoSdI</c>).</param>
|
||||
/// <param name="ReceivedAt">When the exchange system received the invoice file.</param>
|
||||
/// <param name="DeliveredAt">When it was delivered, for a delivery receipt.</param>
|
||||
/// <param name="Outcome">The outcome of the administration (Italy: <c>EC01</c> accepted, <c>EC02</c> refused).</param>
|
||||
/// <param name="Description">The free text of the notification.</param>
|
||||
/// <param name="Errors">The errors of a rejection.</param>
|
||||
/// <param name="MessageId">The identifier of the message.</param>
|
||||
/// <param name="RecipientCode">The recipient code, for the metadata of a received invoice.</param>
|
||||
/// <param name="Content">The file as received.</param>
|
||||
public sealed record EInvoiceReceipt(
|
||||
EInvoiceReceiptKind Kind, string Code, string FileName, string? InvoiceFileName, string? ExchangeId,
|
||||
DateTimeOffset? ReceivedAt, DateTimeOffset? DeliveredAt, string? Outcome, string? Description,
|
||||
IReadOnlyList<EInvoiceReceiptError> Errors, string? MessageId, string? RecipientCode, byte[] Content)
|
||||
{
|
||||
/// <summary>Whether an outcome says the administration refused the invoice.</summary>
|
||||
public bool Refused => Kind == EInvoiceReceiptKind.Outcome && string.Equals(Outcome, "EC02", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Reads the receipts of the exchange system (Italy: SDI notifications, <c>MessaggiTypes</c> v1.0).</summary>
|
||||
public interface IEInvoiceReceiptReader
|
||||
{
|
||||
/// <summary>Whether a file is a receipt, by its name or its root element.</summary>
|
||||
/// <param name="fileName">The name of the file.</param>
|
||||
/// <param name="content">The content.</param>
|
||||
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
|
||||
bool IsReceipt(string fileName, ReadOnlySpan<byte> content);
|
||||
|
||||
/// <summary>Reads a receipt.</summary>
|
||||
/// <param name="fileName">The name of the file.</param>
|
||||
/// <param name="content">The content.</param>
|
||||
/// <returns>The receipt.</returns>
|
||||
/// <exception cref="IncomingInvoiceException">The file is not a receipt.</exception>
|
||||
EInvoiceReceipt Read(string fileName, byte[] content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record EInvoiceChannelSettings
|
||||
{
|
||||
/// <summary>The channel code (Italy: <c>PEC</c>, <c>SDICOOP</c>, <c>INTA</c>, <c>INTB</c>).</summary>
|
||||
public required string Code { get; init; }
|
||||
|
||||
/// <summary>The certified mailbox of the company.</summary>
|
||||
public string? Mailbox { get; init; }
|
||||
|
||||
/// <summary>The SMTP server of the mailbox.</summary>
|
||||
public string? SmtpHost { get; init; }
|
||||
|
||||
/// <summary>The SMTP port (465 for TLS from the start, 587 for STARTTLS).</summary>
|
||||
public int SmtpPort { get; init; } = 465;
|
||||
|
||||
/// <summary>The IMAP server of the mailbox.</summary>
|
||||
public string? ImapHost { get; init; }
|
||||
|
||||
/// <summary>The IMAP port (993 for TLS).</summary>
|
||||
public int ImapPort { get; init; } = 993;
|
||||
|
||||
/// <summary>Whether the connections are protected by TLS (always, except in tests on the local machine).</summary>
|
||||
public bool Tls { get; init; } = true;
|
||||
|
||||
/// <summary>The user of the mailbox or of the service.</summary>
|
||||
public string? User { get; init; }
|
||||
|
||||
/// <summary>The password of the mailbox or of the service.</summary>
|
||||
public string? Password { get; init; }
|
||||
|
||||
/// <summary>The address of the exchange system to write to (Italy: <c>sdi01@pec.fatturapa.it</c>, then the one assigned).</summary>
|
||||
public string? ExchangeAddress { get; init; }
|
||||
|
||||
/// <summary>The folder of the mailbox the processed messages are moved to.</summary>
|
||||
public string? ArchiveFolder { get; init; }
|
||||
|
||||
/// <summary>The address of the web service or of the API.</summary>
|
||||
public string? Endpoint { get; init; }
|
||||
|
||||
/// <summary>The client certificate (PKCS#12) of the web service.</summary>
|
||||
public byte[]? Certificate { get; init; }
|
||||
|
||||
/// <summary>The password of the certificate.</summary>
|
||||
public string? CertificatePassword { get; init; }
|
||||
|
||||
/// <summary>The API key or token of an intermediary.</summary>
|
||||
public string? ApiKey { get; init; }
|
||||
|
||||
/// <summary>Whether the test environment of the service is used.</summary>
|
||||
public bool TestEnvironment { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A file to send.</summary>
|
||||
/// <param name="FileName">The name of the file.</param>
|
||||
/// <param name="Content">The content.</param>
|
||||
/// <param name="Reference">What it is, for messages and logs (the number of the document).</param>
|
||||
public sealed record EInvoiceOutgoing(string FileName, byte[] Content, string? Reference);
|
||||
|
||||
/// <summary>The answer of a channel to a file sent.</summary>
|
||||
/// <param name="Accepted">Whether the channel took the file.</param>
|
||||
/// <param name="ExchangeId">The identifier given by the exchange system, when the channel knows it at once (Italy: SdICoop).</param>
|
||||
/// <param name="MessageId">The identifier of the message or of the upload at the channel.</param>
|
||||
/// <param name="Error">Why the file was not taken.</param>
|
||||
public sealed record EInvoiceSendResult(bool Accepted, string? ExchangeId, string? MessageId, string? Error);
|
||||
|
||||
/// <summary>A file received from a channel: a receipt, a supplier invoice or its metadata.</summary>
|
||||
/// <param name="FileName">The name of the file.</param>
|
||||
/// <param name="Content">The content.</param>
|
||||
/// <param name="ReceivedAt">When the channel received it.</param>
|
||||
/// <param name="MessageKey">The key of the message at the channel, to acknowledge it once stored.</param>
|
||||
/// <param name="Sender">Who sent it (the address of the exchange system), if known.</param>
|
||||
public sealed record EInvoiceIncoming(string FileName, byte[] Content, DateTimeOffset ReceivedAt, string MessageKey, string? Sender);
|
||||
|
||||
/// <summary>What a channel had for the company.</summary>
|
||||
/// <param name="Files">The files received.</param>
|
||||
/// <param name="MessagesRead">How many messages the channel read, files or not.</param>
|
||||
/// <param name="ExchangeAddress">The address the exchange system assigned for the next files, if it changed (Italy: PEC).</param>
|
||||
public sealed record EInvoiceFetchResult(IReadOnlyList<EInvoiceIncoming> Files, int MessagesRead, string? ExchangeAddress);
|
||||
|
||||
/// <summary>The outcome of a connection test.</summary>
|
||||
/// <param name="Success">Whether every step worked.</param>
|
||||
/// <param name="Message">What was checked, or what failed.</param>
|
||||
public sealed record EInvoiceChannelCheck(bool Success, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// A channel to the exchange system (SPEC §11.9: <c>ISdiTransport</c>): 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.
|
||||
/// </summary>
|
||||
public interface IEInvoiceTransport
|
||||
{
|
||||
/// <summary>The code of the channel (Italy: <c>PEC</c>, <c>SDICOOP</c>, <c>INTA</c>, <c>INTB</c>).</summary>
|
||||
string Code { get; }
|
||||
|
||||
/// <summary>Whether receipts and invoices are fetched by polling (<see langword="false"/> when the exchange system pushes them).</summary>
|
||||
bool Polls { get; }
|
||||
|
||||
/// <summary>Sends a file.</summary>
|
||||
/// <param name="settings">The settings of the channel.</param>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The answer of the channel.</returns>
|
||||
Task<EInvoiceSendResult> SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Fetches the files waiting at the channel; nothing is removed until <see cref="AcknowledgeAsync"/>.</summary>
|
||||
/// <param name="settings">The settings of the channel.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The files.</returns>
|
||||
Task<EInvoiceFetchResult> FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Marks messages as processed (Italy, PEC: moved to the archive folder).</summary>
|
||||
/// <param name="settings">The settings of the channel.</param>
|
||||
/// <param name="messageKeys">The keys of <see cref="EInvoiceIncoming.MessageKey"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection<string> messageKeys, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Tests the connection without sending anything.</summary>
|
||||
/// <param name="settings">The settings of the channel.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The outcome.</returns>
|
||||
Task<EInvoiceChannelCheck> CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>A channel the pack offers, with its description for the configuration screen.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Name">The name shown.</param>
|
||||
/// <param name="Transport">The implementation.</param>
|
||||
public sealed record EInvoiceChannel(string Code, string Name, IEInvoiceTransport Transport);
|
||||
|
||||
/// <summary>The channels to the exchange system the pack offers (Italy: PEC, SdICoop, intermediary A and B).</summary>
|
||||
public interface IEInvoiceChannels
|
||||
{
|
||||
/// <summary>The channels, in the order of the configuration screen.</summary>
|
||||
IReadOnlyList<EInvoiceChannel> All { get; }
|
||||
|
||||
/// <summary>A channel by code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The channel, or <see langword="null"/>.</returns>
|
||||
EInvoiceChannel? Find(string code);
|
||||
}
|
||||
|
||||
/// <summary>What the exchange system pushed to the company over HTTP: the files and how to answer.</summary>
|
||||
/// <param name="ExchangeId">The identifier of the exchange system.</param>
|
||||
/// <param name="Files">The files: a notification, or an invoice with its metadata.</param>
|
||||
/// <param name="AnswerContentType">The content type of the answer.</param>
|
||||
/// <param name="Answer">The body of the answer.</param>
|
||||
public sealed record EInvoicePush(string? ExchangeId, IReadOnlyList<(string FileName, byte[] Content)> Files, string AnswerContentType, string Answer);
|
||||
|
||||
/// <summary>
|
||||
/// Reads what the exchange system sends to the web services of the company (Italy: the SdICoop operations
|
||||
/// <c>RiceviFatture</c>, <c>RicevutaConsegna</c>, <c>NotificaScarto</c> …), for the channel that receives them.
|
||||
/// </summary>
|
||||
public interface IEInvoicePushReader
|
||||
{
|
||||
/// <summary>The code of the channel the pushes belong to (Italy: <c>SDICOOP</c>).</summary>
|
||||
string Channel { get; }
|
||||
|
||||
/// <summary>Reads a request.</summary>
|
||||
/// <param name="contentType">The content type of the HTTP request.</param>
|
||||
/// <param name="body">The body.</param>
|
||||
/// <returns>The files with the answer, or <see langword="null"/> when the request is not one of the exchange system.</returns>
|
||||
EInvoicePush? Read(string? contentType, byte[] body);
|
||||
|
||||
/// <summary>The answer to a request that could not be read.</summary>
|
||||
/// <returns>The content type and the body.</returns>
|
||||
(string ContentType, string Body) Refusal();
|
||||
}
|
||||