Compare commits

...
Author SHA1 Message Date
Alby96andClaude Opus 5.5 cfca29d71c Merge M7 · Contabilità generale e IVA (v0.7.0) (#126)
Wiki / Publish the wiki (push) Successful in 14s
CI / PostgreSQL 16 integration (push) Successful in 1m44s
CI / Build and test (SQLite) (push) Successful in 4m3s
CI / Docker image (push) Skipped
CI / PostgreSQL 17 integration (push) Successful in 1m27s
CI / YAML check (push) Successful in 6s
Release / Image and release (push) Successful in 2m24s
General ledger, automatic posting of documents, VAT registers and settlement, withholdings, stamp duty and F24 (#62-#68). Gitea Actions created no run for this PR: build, the full suite (754) and the PostgreSQL 18 data tests (110) passed locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 03:49:32 +01:00
Alby96andClaude Opus 5.5 9e3ba92993 feat: general ledger, automatic posting, VAT settlement, withholdings and F24 (#62 #63 #64 #65 #66 #67 #68)
M7 adds the double-entry ledger so that the documents of M5 and M6 reach the
accounts without retyping, and the Italian VAT obligations can be prepared from
the same data.

- Chart of accounts on three levels with the Italian "PMI standard" model in the
  fiscal pack, journal templates with proposed lines, VAT registers; the chart
  import now writes the accounts and exports them (#62, ADR 0036).
- Journal entries: draft, posted, final with the libro giornale number,
  reversal; recurring entries with the nightly ledger.recurring job (#63).
- Documents post their entry inside the document transaction (PostingEngine,
  LedgerPoster) with VAT lines, open items and withholdings; a change rewrites
  the same entry, a cancellation removes or reverses it (#64, ADR 0037).
- VAT registers with final print, monthly or quarterly settlement with pro rata,
  interest, minimum and advance, confirmation with the LIQ entry, period lock
  and F24 line, LIPE file and F24 data (#65).
- Operated and suffered withholdings, CU data, stamp duty by quarter with the
  5,000 euro threshold, F24 summary with its payment entry (#66).
- Party ledgers, account ledgers, trial balance and libro giornale (#67).
- Demo accounting with the settlements of the past months confirmed and checked
  by hand in a test; wiki Contabilita, IVA, Fiscalita italiana completed with
  screenshots; CHANGELOG 0.7.0, STATUS, ADR 0036-0037 (#68).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:41:58 +01:00
Alby96 838362bfe1 Merge M6 · Acquisti e Magazzino (v0.6.0) (#125)
CI / YAML check (push) Failing after 58s
CI / Build and test (SQLite) (push) Successful in 4m11s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Failing after 1m19s
Purchase cycle, supplier e-invoice import, self-invoices and a warehouse posted from the documents, with the user guide in the wiki.

Closes #55 #56 #57 #58 #59 #60 #61
2026-11-12 22:37:36 +01:00
Alby96andClaude Opus 5.5 7f8cb57a08 docs: record M6 as closed (v0.6.0) and M7 as the current milestone (#61)
CI / Build and test (SQLite) (pull_request) Failing after 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / YAML check (pull_request) Successful in 1m1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:35:34 +01:00
Alby96andClaude Opus 5.5 4b759ee96e docs: purchases and warehouse guide with screenshots, ADR 0035 and the 0.6.0 changelog (#61)
CI / Build and test (SQLite) (pull_request) Canceled after 0s
CI / PostgreSQL 16 integration (pull_request) Canceled after 0s
CI / PostgreSQL 17 integration (pull_request) Canceled after 0s
CI / Docker image (pull_request) Canceled after 0s
CI / YAML check (pull_request) Canceled after 0s
The Acquisti and Magazzino wiki pages now describe what M6 delivers, with real
screenshots of the demo company: stock, item movements, valuation, stock take, reorder
proposal, receipts, price differences, e-invoice import and pending self-invoices. The
user guide gains the buying and warehouse steps; the pages that said "arriva con M6"
(sales, items, dashboard, import, scheduled jobs, demo data) are brought up to date.
ADR 0035 records how documents post to the warehouse, the recomputed weighted average,
the invoice cost correction, the rebuild, the stock take, the base tables of existing
companies and where the Italian self-invoice and import rules live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:24:43 +01:00
Alby96andClaude Opus 5.5 cd4cb85562 fix: tidy the warehouse screens and the supplier document labels (#55 #60)
Seen while checking M6 in the browser: the stock take toolbar crowded the panel title,
the reorder and stock take tables ran past their panel, and the movements dialog cut
the balance column. Confirmed supplier receipts have no number of their own and showed
"Bozza"; they now read "Senza numero". The self-invoice advice no longer doubles the
full stop, and a single price difference reads in the singular.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:24:43 +01:00
Alby96andClaude Opus 5.5 ced689b297 feat: warehouse and purchase screens, e-invoice import, demo purchases (#55 #56 #57 #58 #60)
Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the
movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP)
become draft purchase invoices with supplier, items and tax codes matched, the file attached
and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase
invoices show price differences against the order and the self-invoice still to issue,
with a pending list on the self-invoice screen. The opening stock import now writes an
opening movement. The demo company gets purchases, an opening stock, a pending
self-invoice and a stock take being counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:01:32 +01:00
Alby96andClaude Opus 5.5 eb301fa570 feat: stock take, reorder proposal and warehouse rebuild (#60)
A physical stock take freezes the book quantity and cost of a warehouse at a
date, takes counts typed or read from a scanner file, and posts the gains and
losses as INVP/INVN movements at that date. The reorder proposal lists the
items whose available and ordered quantity no longer covers the reorder point
and turns the accepted lines into draft supplier orders, one per supplier.
The warehouse can be rebuilt from its documents on demand and every Sunday
night, as a safety net after imports or corrections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:35:34 +01:00
Alby96andClaude Opus 5.5 f8b72f4d17 feat: purchase and warehouse documents on the document screens (#55 #56 #58)
The document radars and records now serve /acquisti and /magazzino too:
supplier orders, receipts, supplier invoices and credit notes, self-invoices
and warehouse movements, with the supplier in place of the customer, the
supplier's number and date, the protocol and VAT date of registered invoices,
and reason and warehouses of a movement. Supplier invoices take their
protocol from the purchase numbering, refuse a second document with the same
supplier number in the same year and show price differences against their
order or receipt. The Italian pack advises the self-invoice a received
invoice needs (TD16-TD19, TD28) with its deadline, and the purchase service
drafts it with the ordinary rate. A credit note of an invoice now moves its
goods back instead of being skipped as already moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:25:25 +01:00
Alby96andClaude Opus 5.5 eeabb12f96 feat: post documents to the warehouse at weighted average cost (#59)
Confirmed delivery notes, invoices that move goods, supplier receipts and
warehouse movements now write stock movements in the same transaction;
cancelling removes them. Each change re-runs the history of the items
touched, so balances per warehouse, committed and ordered quantities and
the average and last cost stay consistent even when an old document is
cancelled. Supplier invoices give their cost to the receipts they invoice.
Immediate invoices, supplier invoices and credit notes get their warehouse
reasons; the self-invoice types TD20-TD29 join the base tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:13:27 +01:00
Alby96 20b2421eea Merge branch 'refs/heads/worktree-agent-a350efc9cb07bc00b' into feat/55-acquisti-magazzino 2026-11-12 21:09:11 +01:00
Alby96andClaude Opus 5.5 9a40adecfe feat: read FatturaPA invoices and signed p7m files (#57)
The import of supplier e-invoices needs a reading layer that turns a
received file into plain records, whatever form the file arrives in.

- Fiscal.Abstractions: IIncomingInvoiceReader, an optional pack feature,
  with the IncomingInvoiceFile records and the incoming.* error codes the
  import service and screens build on.
- Infrastructure: CmsSignedData, a minimal CMS SignedData (CAdES .p7m)
  reader on System.Formats.Asn1, since System.Security.Cryptography.Pkcs
  is a separate package. It accepts DER, BER with indefinite lengths and
  chunked content, base64 text and nested envelopes; it checks the
  message digest and the RSA (PKCS#1, PSS) or ECDSA signature with the
  embedded certificate and reports signer, tax code, validity and signing
  time. No trust chain or revocation check: no trusted list offline.
- Fiscal.Italy: FatturaPaReader for FPR12/FPA12 v1.2.x and FSM10, matched
  by local name, DTD prohibited and no resolver, BOM/windows-1252/missing
  declaration tolerated, batches as one invoice per body, attachments
  decoded; registered in ItalyFiscalPack.
- Tests build every sample and signed envelope in code (AsnWriter and
  self-signed certificates), nothing downloaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:08:29 +01:00
Alby96 2c56c0dff0 Merge M5 · Motore documenti e vendite (v0.5.0) (#124)
Wiki / Publish the wiki (push) Successful in 7s
Release / Image and release (push) Successful in 3m12s
CI / PostgreSQL 16 integration (push) Successful in 2m6s
CI / Build and test (SQLite) (push) Successful in 2m55s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 9s
CI / PostgreSQL 17 integration (push) Successful in 1m47s
Document engine, sales cycle, printing and mail of documents, user guide in the wiki.

Closes #47 #48 #49 #50 #51 #52 #53 #54
2026-11-12 18:48:55 +01:00
152 changed files with 23865 additions and 882 deletions

No files matched your search

+105
View File
@@ -7,6 +7,111 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
## [Unreleased]
## [0.7.0] - 2026-11-13
M7 - Contabilità generale e IVA. Ogni fattura, nota e autofattura si contabilizza da sola nella stessa transazione,
con le righe IVA nel suo registro, le partite aperte e la ritenuta; la prima nota in partita doppia con registrazioni
provvisorie, definitive e storni; registri IVA, liquidazione periodica con F24 e LIPE, ritenute, bollo virtuale,
partitari, mastrini e bilancio di verifica.
### Added
- Piano dei conti a tre livelli (#62, ADR 0036): mastro, conto e sottoconto (`MM.CC.SSS`), natura, tipo, voce CEE,
partitario, rilevanza IVA; modello italiano *PMI standard* di 237 conti nel pacchetto fiscale
(`ItalianLedgerTemplate`), albero con ricerca, scheda e mastrino con saldo progressivo e stampa.
- Causali contabili con righe proposte, registro IVA, apertura delle partite e causale di storno (#62): `FV`, `NCV`,
`FA`, `NCA`, `AFRC`, `CORR`, `INC`, `PAG`, `RIT`, `RITS`, `LIQ`, `F24`, `GIRO`, `SPB`, `STO` e altre.
- Prima nota (#63): registrazioni in partita doppia con cliente o fornitore sui conti con partitario, centro di
costo e righe IVA; bozza, registrata (numero per anno) e definitiva (numero del libro giornale) con *Rendi
definitive*; storno; *Chiudi lo sbilancio*; filtri e paginazione.
- Registrazioni ricorrenti (#63): copia di una registrazione modello mensile, trimestrale, semestrale o annuale fino
a una data, job di sistema `ledger.recurring` ogni giorno alle 5:00 e *Genera ora*.
- Contabilizzazione automatica dei documenti (#64, ADR 0037): fatture, note di debito, parcelle, note di credito,
fatture e note fornitore, autofatture e integrazioni scrivono la registrazione alla conferma (`PostingEngine`,
`LedgerPoster`), la riscrivono con lo stesso numero alla modifica e la tolgono o la stornano all'annullamento;
scissione dei pagamenti, IVA indetraibile sul costo, rivalsa cassa e bollo; *Contabilizza documenti* per i
documenti confermati prima.
- Registri IVA vendite, acquisti, autofatture e corrispettivi (#65) con riepilogo per aliquota, stampa di prova e
definitiva con numerazione delle pagine.
- Liquidazione IVA mensile o trimestrale (#65): IVA a debito e a credito, pro rata, credito e debito riportati,
interessi trimestrali, minimo di versamento, acconto di dicembre (storico, previsionale, effettivo); conferma con la
registrazione `LIQ`, il blocco dei periodi e il versamento F24; riapertura; file della comunicazione LIPE
(`IVP18`) e dati F24. Regole e codici tributo nel pacchetto italiano (`VatSettlementRulesIt`).
- Ritenute d'acconto operate e subite (#66): da versare quando la fattura del professionista è pagata, registrazioni
`RIT` e `RITS`, codice 1040 al 16 del mese dopo; dati della certificazione unica in CSV.
- Bollo virtuale per trimestre (#66) con soglia dei 5.000 euro, codici 2521-2524 e scadenze.
- Prospetto F24 per scadenza (#66) con export dei dati e registrazione del pagamento `F24` sulla banca
dell'azienda.
- Partitari clienti e fornitori con estratto conto e partite aperte, bilancio di verifica per mastri, conti e
sottoconti con centro di costo e risultato del periodo, libro giornale di prova e definitivo in PDF (#67).
- Menu *Contabilità*; testi in `Resources/it-IT/Ledger.json`; permessi `ledger.account.*`, `ledger.entry.*`,
`vat.register.read`, `vat.settlement.*`.
- Contabilità nei dati di esempio (#68): documenti contabilizzati, fattura del professionista pagata, noleggio
mensile della stampante come ricorrente, liquidazioni dei mesi passati confermate e F24 scaduti pagati.
- Tabelle `gl_accounts`, `gl_journal_templates`, `gl_journal_template_lines`, `gl_entries`, `gl_entry_lines`,
`gl_entry_vat`, `gl_open_items`, `gl_recurring_entries`, `vat_registers`, `vat_register_prints`,
`vat_settlements`, `vat_settlement_lines`, `tax_payments`, `withholdings` (migrazione `M20261113_002`).
- ADR 0036 e 0037; pagine wiki *Contabilità*, *IVA* e *Fiscalità italiana* complete con le schermate.
### Changed
- *Bollo virtuale* passa dal menu *Fatturazione elettronica* al menu *Contabilità*.
- Il seed di base e *Aggiorna da tabelle base* aggiungono piano dei conti, causali e registri IVA alle aziende
esistenti.
## [0.6.0] - 2026-11-12
M6 — Acquisti e Magazzino. Il ciclo passivo dall'ordine al fornitore alla fattura protocollata, le fatture
elettroniche ricevute importate in bozza, le autofatture con la loro scadenza e un magazzino che si aggiorna da solo
con i documenti: giacenze per deposito, costo medio, inventario, riordino e valorizzazione.
### Added
- Movimenti di magazzino dai documenti (#59, ADR 0035): alla conferma DDT, fatture immediate e accompagnatorie, note,
DDT e fatture fornitore, note di credito fornitore e movimenti `MM` scrivono i loro movimenti nella stessa
transazione (`inventory_entries`, `inventory_entry_lines`); l'annullamento li toglie. La causale del tipo documento
decide carico, scarico o trasferimento; la fattura di un DDT non muove di nuovo la merce, la nota di credito la
muove all'inverso. Tabella `item_balances` con giacenza per deposito, impegnato (ordini clienti) e ordinato
(ordini fornitore).
- Costo medio ponderato per articolo ricalcolato dalla storia dei movimenti a ogni modifica, anche per documenti con
data passata; ultimo costo e date di ultimo carico e scarico; il prezzo della fattura fornitore corregge il costo
dei carichi che fattura.
- Documenti del ciclo passivo nelle maschere dei documenti (#55, #56, #58): ordini fornitori, ricevimenti merce (DDT
fornitore con il numero e la data del fornitore), fatture e note di credito fornitore con **protocollo** IVA alla
conferma e rifiuto del doppio numero del fornitore nello stesso anno, autofatture e movimenti di magazzino con
causale e depositi. Menu *Acquisti* e *Magazzino*.
- Controllo dei prezzi: sulla fattura fornitore un avviso elenca le righe con un prezzo diverso dall'ordine o dal
ricevimento e la differenza totale.
- Autofatture e integrazioni: il pacchetto italiano (`SelfInvoiceRulesIt`) riconosce dalla fattura del fornitore
l'integrazione dovuta (TD16, TD17, TD18, TD19, TD28) e la scadenza; la fattura lo mostra con **Crea autofattura**,
che prepara la bozza con l'aliquota ordinaria; *Acquisti → Autofatture* elenca le integrazioni da emettere. Tipi
`AF20`-`AF29` nelle tabelle di base.
- Lettura delle fatture elettroniche ricevute (#57): `FatturaPaReader` (FPR12, FPA12, FSM10, lotti, allegati) e
lettore CMS/CAdES dei file `.p7m` con verifica dell'impronta e della firma, scritti in casa.
- Import delle fatture passive (#57): *Acquisti → Importa fatture* legge XML, P7M e ZIP, trova o crea il fornitore,
segnala doppioni, tipi non d'acquisto, totali diversi e firme non verificate, e registra in bozza fatture (TD01,
TD02, TD03, TD05, TD06, TD24-TD27) e note di credito (TD04, TD08) con articoli abbinati per codice del fornitore,
EAN e codice, codice IVA per aliquota e natura, sconti di riga e file allegato. Le regole TD stanno nel pacchetto
fiscale (`IncomingInvoiceRulesIt`).
- Giacenze e disponibilità (#60): indicatori, filtri per deposito, categoria e stato (*Disponibile*, *Da riordinare*,
*Sottoscorta*, *Esaurito*), movimenti di un articolo con saldo progressivo.
- Inventario fisico (#60): apertura per deposito, data e categoria con la giacenza contabile congelata, conteggi
scritti o importati dal file del lettore, rettifiche `INVP` e `INVN` alla data del conteggio; tabelle `stock_takes`
e `stock_take_lines`.
- Proposta di riordino (#60): articoli sotto il punto di riordino o la scorta minima, quantità dal lotto o dalla
soglia con il minimo d'ordine del fornitore, fornitore preferito con prezzo e arrivo previsto, ordini fornitore in
bozza uno per fornitore.
- Valorizzazione a data con costo medio, ultimo costo o costo standard e classi ABC; ricostruzione del magazzino da
interfaccia con avanzamento e come job di sistema `inventory.rebuild` ogni domenica alle 2:15.
- Widget *Sottoscorta* della dashboard con i dati veri.
- Dati di esempio di acquisti e magazzino (#61): esistenze iniziali, ordini ricevuti per intero e in parte, fatture
con una differenza di prezzo e una integrazione AF18 da emettere, un inventario in conteggio.
- ADR 0035; pagine wiki *Acquisti* e *Magazzino* complete con le schermate, guida all'uso aggiornata.
### Changed
- Import *Giacenze iniziali*: non è più solo verifica, scrive e conferma un movimento `APE` per deposito.
- I documenti confermati senza numero interno (DDT fornitore) si presentano come *Senza numero* invece di *Bozza*.
- *Tipi documento*: fattura immediata, fattura e nota di credito fornitore ricevono la causale di magazzino (`SCA`,
`CAR`, `RESF`); la migrazione la assegna anche nelle aziende esistenti dove manca. I tipi `AF20`-`AF29` mancanti si
aggiungono con *Aggiorna da tabelle base* o `scripts/seed.sh --base`.
## [0.5.0] - 2026-11-12
M5 — Motore documenti e Vendite. Un solo motore per tutti i documenti, con numerazione, totali, scadenze e
+514
View File
@@ -730,6 +730,8 @@ Migrazioni applicate in ordine:
- `core` 20261112001 `create_parties` (M20261112_001_CreateParties)
- `core` 20261112002 `create_items` (M20261112_002_CreateItems)
- `core` 20261112003 `create_documents` (M20261112_003_CreateDocuments)
- `core` 20261113001 `create_inventory` (M20261113_001_CreateInventory)
- `core` 20261113002 `create_ledger` (M20261113_002_CreateLedger)
#### `attachments`
@@ -1164,6 +1166,225 @@ Migrazioni applicate in ordine:
- indice unico `ux_fiscal_years_code` su `code`
- indice unico `ux_fiscal_years_start_date` su `start_date`
#### `gl_accounts`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(20) | no | | |
| `description` | String(100) | no | | |
| `disabled` | Bool | no | `false` | |
| `level` | Int32 | no | `1` | |
| `parent_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
| `nature` | String(40) | no | | |
| `type` | String(40) | no | | |
| `statement_line` | String(20) | sì | | |
| `reclassification` | String(20) | sì | | |
| `sub_ledger` | Bool | no | `false` | |
| `vat_relevant` | Bool | no | `false` | |
| `closes_automatically` | Bool | no | `true` | |
| `postable` | 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_gl_accounts_parent` su `parent_id`
- indice unico `ux_gl_accounts_code` su `code`
#### `gl_entries`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `year` | Int32 | no | | |
| `number` | Int64 | sì | | |
| `entry_number` | String(20) | sì | | |
| `journal_number` | Int64 | sì | | |
| `entry_date` | Date | no | | |
| `competence_date` | Date | sì | | |
| `journal_template_id` | Int64 | sì | | -> `gl_journal_templates` (Restrict) |
| `template_code` | String(10) | sì | | |
| `description` | String(200) | no | | |
| `status` | String(40) | no | | |
| `source` | String(40) | no | | |
| `source_family` | String(40) | sì | | |
| `source_document_id` | Int64 | sì | | |
| `source_kind` | String(40) | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | sì | | |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `vat_register_id` | Int64 | sì | | -> `vat_registers` (Restrict) |
| `vat_protocol` | Int64 | sì | | |
| `vat_date` | Date | sì | | |
| `reversal_of_id` | Int64 | sì | | |
| `reversed_by_id` | Int64 | sì | | |
| `total_debit` | Decimal(19,6) | no | `0` | |
| `total_credit` | Decimal(19,6) | no | `0` | |
| `finalized_at` | DateTimeUtc | sì | | |
| `finalized_by` | String(100) | 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_gl_entries_date` su `entry_date`, `number`
- indice `ix_gl_entries_register` su `vat_register_id`, `vat_date`
- indice `ix_gl_entries_source` su `source_family`, `source_document_id`
- indice `ix_gl_entries_status` su `status`, `entry_date`
- indice unico `ux_gl_entries_number` su `year`, `number`
#### `gl_entry_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `entry_id` | Int64 | no | | -> `gl_entries` (Cascade) |
| `line_number` | Int32 | no | | |
| `entry_date` | Date | no | | |
| `status` | String(40) | no | | |
| `account_id` | Int64 | no | | -> `gl_accounts` (Restrict) |
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
| `description` | String(200) | sì | | |
| `debit` | Decimal(19,6) | no | `0` | |
| `credit` | Decimal(19,6) | no | `0` | |
| `cost_center_id` | Int64 | sì | | |
| `job_id` | Int64 | sì | | |
| `open_item_id` | Int64 | 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 `ix_gl_entry_lines_account` su `account_id`, `entry_date`
- indice `ix_gl_entry_lines_cost_center` su `cost_center_id`, `entry_date`
- indice `ix_gl_entry_lines_entry` su `entry_id`
- indice `ix_gl_entry_lines_party` su `party_id`, `account_id`, `entry_date`
#### `gl_entry_vat`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `entry_id` | Int64 | no | | -> `gl_entries` (Cascade) |
| `line_number` | Int32 | no | | |
| `vat_register_id` | Int64 | no | | -> `vat_registers` (Restrict) |
| `register_kind` | String(40) | no | | |
| `vat_date` | Date | no | | |
| `status` | String(40) | no | | |
| `tax_code_id` | Int64 | sì | | |
| `rate` | Decimal(19,6) | no | `0` | |
| `nature` | String(10) | sì | | |
| `exigibility` | String(40) | no | | |
| `taxable` | Decimal(19,6) | no | `0` | |
| `tax` | Decimal(19,6) | no | `0` | |
| `non_deductible_tax` | Decimal(19,6) | 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` | |
- indice `ix_gl_entry_vat_entry` su `entry_id`
- indice `ix_gl_entry_vat_register` su `vat_register_id`, `vat_date`
#### `gl_journal_template_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `journal_template_id` | Int64 | no | | -> `gl_journal_templates` (Cascade) |
| `sort_order` | Int32 | no | `0` | |
| `role` | String(40) | no | | |
| `side` | String(40) | no | | |
| `account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) |
| `description` | 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 `ix_gl_journal_template_lines_template` su `journal_template_id`
#### `gl_journal_templates`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(10) | no | | |
| `description` | String(100) | no | | |
| `disabled` | Bool | no | `false` | |
| `area` | String(40) | no | | |
| `vat_register_code` | String(10) | sì | | |
| `opens_items` | Bool | no | `false` | |
| `reverses` | 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_gl_journal_templates_code` su `code`
#### `gl_open_items`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `direction` | String(40) | no | | |
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
| `account_id` | Int64 | no | | -> `gl_accounts` (Restrict) |
| `entry_id` | Int64 | no | | -> `gl_entries` (Cascade) |
| `source_family` | String(40) | sì | | |
| `source_document_id` | Int64 | sì | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `installment` | Int32 | no | `1` | |
| `due_date` | Date | no | | |
| `amount` | Decimal(19,6) | no | `0` | |
| `paid_amount` | Decimal(19,6) | no | `0` | |
| `payment_method_id` | Int64 | sì | | |
| `closed` | 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_gl_open_items_due` su `closed`, `due_date`
- indice `ix_gl_open_items_entry` su `entry_id`
- indice `ix_gl_open_items_party` su `party_id`, `closed`, `due_date`
#### `gl_recurring_entries`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `description` | String(200) | no | | |
| `model_entry_id` | Int64 | no | | -> `gl_entries` (Restrict) |
| `frequency` | String(40) | no | | |
| `next_date` | Date | no | | |
| `end_date` | Date | sì | | |
| `last_entry_id` | Int64 | 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` | |
- indice `ix_gl_recurring_entries_next` su `disabled`, `next_date`
#### `goods_appearances`
| Colonna | Tipo | Null | Default | Note |
@@ -1306,12 +1527,61 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `to_warehouse_id` | Int64 | sì | | |
| `vat_date` | Date | sì | | |
- indice `ix_inventory_documents_date` su `document_date`
- indice `ix_inventory_documents_party` su `party_id`
- indice `ix_inventory_documents_status` su `status`
- indice unico `ux_inventory_documents_number` su `numerator_id`, `number`
#### `inventory_entries`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `entry_date` | Date | no | | |
| `source_family` | String(40) | sì | | |
| `source_document_id` | Int64 | sì | | |
| `source_kind` | String(40) | sì | | |
| `source_number` | String(30) | sì | | |
| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
| `party_id` | Int64 | 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_inventory_entries_date` su `entry_date`
- indice `ix_inventory_entries_source` su `source_family`, `source_document_id`
#### `inventory_entry_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `entry_id` | Int64 | no | | -> `inventory_entries` (Cascade) |
| `entry_date` | Date | no | | |
| `item_id` | Int64 | no | | -> `items` (Restrict) |
| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) |
| `quantity` | Decimal(19,6) | no | | |
| `valued` | Bool | no | `false` | |
| `unit_cost` | Decimal(19,6) | no | `0` | |
| `value` | Decimal(19,6) | no | `0` | |
| `source_line_id` | Int64 | sì | | |
| `sort_order` | Int32 | 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` | |
- indice `ix_inventory_entry_lines_entry` su `entry_id`
- indice `ix_inventory_entry_lines_item` su `item_id`, `entry_date`
- indice `ix_inventory_entry_lines_warehouse` su `warehouse_id`, `item_id`
#### `inventory_reasons`
| Colonna | Tipo | Null | Default | Note |
@@ -1332,6 +1602,31 @@ Migrazioni applicate in ordine:
- indice unico `ux_inventory_reasons_code` su `code`
#### `item_balances`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `item_id` | Int64 | no | | -> `items` (Cascade) |
| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) |
| `on_hand` | Decimal(19,6) | no | `0` | |
| `committed` | Decimal(19,6) | no | `0` | |
| `ordered` | Decimal(19,6) | no | `0` | |
| `in_transit` | Decimal(19,6) | no | `0` | |
| `average_cost` | Decimal(19,6) | no | `0` | |
| `value` | Decimal(19,6) | no | `0` | |
| `last_cost` | Decimal(19,6) | sì | | |
| `last_load_date` | Date | sì | | |
| `last_unload_date` | Date | 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 `ix_item_balances_warehouse` su `warehouse_id`
- indice unico `ux_item_balances_item_warehouse` su `item_id`, `warehouse_id`
#### `item_barcodes`
| Colonna | Tipo | Null | Default | Note |
@@ -2038,6 +2333,8 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `to_warehouse_id` | Int64 | sì | | |
| `vat_date` | Date | sì | | |
- indice `ix_purchase_documents_date` su `document_date`
- indice `ix_purchase_documents_party` su `party_id`
@@ -2169,6 +2466,8 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `to_warehouse_id` | Int64 | sì | | |
| `vat_date` | Date | sì | | |
- indice `ix_purchase_orders_date` su `document_date`
- indice `ix_purchase_orders_party` su `party_id`
@@ -2333,6 +2632,8 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `to_warehouse_id` | Int64 | sì | | |
| `vat_date` | Date | sì | | |
- indice `ix_sale_documents_date` su `document_date`
- indice `ix_sale_documents_party` su `party_id`
@@ -2464,6 +2765,8 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `to_warehouse_id` | Int64 | sì | | |
| `vat_date` | Date | sì | | |
- indice `ix_sale_orders_date` su `document_date`
- indice `ix_sale_orders_party` su `party_id`
@@ -2595,6 +2898,8 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
| `to_warehouse_id` | Int64 | sì | | |
| `vat_date` | Date | sì | | |
- indice `ix_sale_quotations_date` su `document_date`
- indice `ix_sale_quotations_party` su `party_id`
@@ -2651,6 +2956,50 @@ Chiave primaria: `module`, `version`.
- indice unico `ux_shipping_terms_code` su `code`
#### `stock_take_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `stock_take_id` | Int64 | no | | -> `stock_takes` (Cascade) |
| `item_id` | Int64 | no | | -> `items` (Restrict) |
| `book_quantity` | Decimal(19,6) | no | `0` | |
| `counted_quantity` | Decimal(19,6) | sì | | |
| `unit_cost` | Decimal(19,6) | no | `0` | |
| `notes` | String(200) | sì | | |
| `sort_order` | Int32 | 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` | |
- indice unico `ux_stock_take_lines_item` su `stock_take_id`, `item_id`
#### `stock_takes`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `take_date` | Date | no | | |
| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) |
| `description` | String(100) | no | | |
| `category_id` | Int64 | sì | | -> `item_categories` (Restrict) |
| `status` | String(40) | no | | |
| `adjustment_document_id` | Int64 | sì | | |
| `loss_document_id` | Int64 | sì | | |
| `posted_at` | DateTimeUtc | sì | | |
| `posted_by` | String(100) | sì | | |
| `notes` | Text | 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_stock_takes_date` su `take_date`
#### `tax_codes`
| Colonna | Tipo | Null | Default | Note |
@@ -2678,6 +3027,32 @@ Chiave primaria: `module`, `version`.
- indice unico `ux_tax_codes_code` su `code`
#### `tax_payments`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `due_date` | Date | no | | |
| `payment_code` | String(10) | no | | |
| `reference_year` | Int32 | no | | |
| `reference_period` | String(10) | sì | | |
| `description` | String(200) | no | | |
| `amount` | Decimal(19,6) | no | `0` | |
| `source` | String(40) | no | | |
| `source_id` | Int64 | sì | | |
| `paid_on` | Date | sì | | |
| `bank_account_id` | Int64 | sì | | |
| `gl_entry_id` | Int64 | 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_tax_payments_due` su `due_date`
- indice `ix_tax_payments_source` su `source`, `source_id`
#### `transport_means`
| Colonna | Tipo | Null | Default | Note |
@@ -2840,6 +3215,111 @@ Chiave primaria: `module`, `version`.
- indice unico `ux_users_user_name` su `user_name`
#### `vat_register_prints`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `vat_register_id` | Int64 | no | | -> `vat_registers` (Cascade) |
| `year` | Int32 | no | | |
| `from_date` | Date | no | | |
| `to_date` | Date | no | | |
| `first_page` | Int32 | no | | |
| `last_page` | Int32 | no | | |
| `attachment_id` | Int64 | sì | | |
| `printed_at` | DateTimeUtc | no | | |
| `printed_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 `ix_vat_register_prints_register` su `vat_register_id`, `year`
#### `vat_registers`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(10) | no | | |
| `description` | String(100) | no | | |
| `disabled` | Bool | no | `false` | |
| `kind` | String(40) | no | | |
| `reverse_charge` | Bool | no | `false` | |
| `print_year` | Int32 | sì | | |
| `last_page` | Int32 | no | `0` | |
| `last_printed_date` | Date | 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_vat_registers_code` su `code`
#### `vat_settlement_lines`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `settlement_id` | Int64 | no | | -> `vat_settlements` (Cascade) |
| `vat_register_id` | Int64 | no | | -> `vat_registers` (Restrict) |
| `register_kind` | String(40) | no | | |
| `documents` | Int32 | no | `0` | |
| `taxable` | Decimal(19,6) | no | `0` | |
| `tax` | Decimal(19,6) | no | `0` | |
| `non_deductible_tax` | Decimal(19,6) | no | `0` | |
| `deferred_tax` | Decimal(19,6) | 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` | |
- indice `ix_vat_settlement_lines_settlement` su `settlement_id`
#### `vat_settlements`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `year` | Int32 | no | | |
| `number` | Int32 | no | | |
| `periodicity` | String(40) | no | | |
| `start_date` | Date | no | | |
| `end_date` | Date | no | | |
| `settlement_date` | Date | no | | |
| `status` | String(40) | no | | |
| `sales_tax` | Decimal(19,6) | no | `0` | |
| `purchase_tax` | Decimal(19,6) | no | `0` | |
| `non_deductible_tax` | Decimal(19,6) | no | `0` | |
| `deferred_tax` | Decimal(19,6) | no | `0` | |
| `pro_rata_percent` | Decimal(19,6) | no | `100` | |
| `previous_credit` | Decimal(19,6) | no | `0` | |
| `previous_debit` | Decimal(19,6) | no | `0` | |
| `advance_paid` | Decimal(19,6) | no | `0` | |
| `interest_percent` | Decimal(19,6) | no | `0` | |
| `interest` | Decimal(19,6) | no | `0` | |
| `amount_due` | Decimal(19,6) | no | `0` | |
| `credit_carried` | Decimal(19,6) | no | `0` | |
| `debit_carried` | Decimal(19,6) | no | `0` | |
| `payment_code` | String(10) | sì | | |
| `due_date` | Date | sì | | |
| `gl_entry_id` | Int64 | sì | | |
| `tax_payment_id` | Int64 | sì | | |
| `confirmed_at` | DateTimeUtc | sì | | |
| `confirmed_by` | String(100) | 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_vat_settlements_period` su `year`, `periodicity`, `number`
#### `warehouses`
| Colonna | Tipo | Null | Default | Note |
@@ -2861,4 +3341,38 @@ Chiave primaria: `module`, `version`.
- indice unico `ux_warehouses_code` su `code`
#### `withholdings`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `direction` | String(40) | no | | |
| `source_family` | String(40) | no | | |
| `source_document_id` | Int64 | no | | |
| `document_number` | String(30) | sì | | |
| `document_date` | Date | no | | |
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
| `withholding_type` | String(10) | sì | | |
| `reason` | String(10) | sì | | |
| `taxable` | Decimal(19,6) | no | `0` | |
| `social_security_fund` | String(10) | sì | | |
| `social_security_amount` | Decimal(19,6) | no | `0` | |
| `rate` | Decimal(19,6) | no | `0` | |
| `base_percent` | Decimal(19,6) | no | `100` | |
| `amount` | Decimal(19,6) | no | `0` | |
| `payment_code` | String(10) | sì | | |
| `invoice_paid_on` | Date | sì | | |
| `status` | String(40) | no | | |
| `tax_payment_id` | Int64 | sì | | |
| `gl_entry_id` | Int64 | 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_withholdings_source` su `source_family`, `source_document_id`
- indice `ix_withholdings_status` su `direction`, `status`, `invoice_paid_on`
<!-- END GENERATED -->
+30 -8
View File
@@ -2,19 +2,24 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**Ultimo aggiornamento:** 2026-11-12
**Milestone corrente:** M6 — Acquisti e Magazzino (issue #55-#61), **non ancora iniziata**: si parte quando il
titolare lo dice. M5 chiusa: PR #124 in `main`, tag `v0.5.0`, immagine e release.
**Prossimo passo:** M6 dall'issue #55. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo
**Ultimo aggiornamento:** 2026-11-13
**Milestone corrente:** M8 — Scadenzario e tesoreria (issue #69-#73), da iniziare. M7 chiusa: PR in `main`, tag
`v0.7.0`, immagine e release.
**Prossimo passo:** M8 dall'issue #69. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo
per le banche ABI/CAB (manca una fonte con licenza compatibile).
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
password (mockup 003); schede *Layout salvati* e *Notifiche* del profilo; rinomina e filtro predefinito nei radar;
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); chiusura delle partite con
incassi e pagamenti e IVA per cassa (M8).
## Fatto
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
- ADR 0001-0034.
- ADR 0001-0037.
- 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`,
@@ -66,6 +71,23 @@ logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e mode
e-mail con SMTP e coda scritti in casa (#52, ADR 0034); log *Documenti*; profilo e un anno di vendite di esempio;
wiki con la *Guida all'uso* e le schermate reali, README come guida per sviluppatori (#53). Test: 660 verdi in
locale, 23 di PostgreSQL saltati (girano in CI).
- **M6 (chiusa, `v0.6.0`, PR #125):** movimenti di magazzino dai documenti nella
stessa transazione, costo medio ponderato ricalcolato dalla storia, impegnato e ordinato, correzione del costo dalla
fattura fornitore (#59, ADR 0035); ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo,
doppioni rifiutati, controllo dei prezzi, autofatture TD16-TD29 consigliate dal pacchetto italiano con scadenza
(#55, #56, #58); lettura FatturaPA e `.p7m` (CMS scritto in casa) e import delle fatture passive in bozza (#57);
giacenze, movimenti di un articolo, inventario fisico, proposta di riordino, valorizzazione con classi ABC,
ricostruzione anche come job settimanale, widget *Sottoscorta* (#60); giacenze iniziali da file con movimento `APE`;
acquisti e magazzino nei dati di esempio, wiki *Acquisti* e *Magazzino* con le schermate, guida all'uso (#61).
Test: 709 verdi in locale, 23 di PostgreSQL saltati (girano in CI).
- **M7 (chiusa, `v0.7.0`):** piano dei conti a tre livelli con il modello *PMI standard* di 237 conti, causali con righe
proposte (#62, ADR 0036); prima nota con bozze, registrazioni, definitive con numero del libro giornale e storni,
ricorrenti con job giornaliero (#63); contabilizzazione automatica di fatture, note, parcelle e autofatture nella
transazione del documento con righe IVA, partite e ritenute (#64, ADR 0037); registri IVA con stampa definitiva,
liquidazione mensile o trimestrale con pro rata, interessi, minimo, acconto, F24 e LIPE (#65); ritenute operate e
subite, dati CU, bollo virtuale con soglie, prospetto F24 con pagamento (#66); partitari, mastrini, bilancio di
verifica, libro giornale (#67); contabilità nei dati di esempio con la liquidazione verificata a mano in un test,
wiki *Contabilità*, *IVA* e *Fiscalità italiana* con le schermate (#68). Test: 754 verdi in locale, 23 di PostgreSQL saltati (girano in CI).
- 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,
@@ -112,12 +134,12 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
### Contabilità, IVA, e-fattura, CRM (dalla stesura delle pagine funzionali)
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).
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.
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).
17. Codici conto incoerenti tra mockup (fornitori 05.02.001 in 040/043, 02.03.001 in 042).
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.
20. Codice di scarto 00327 citato in §18 senza descrizione.
@@ -0,0 +1,80 @@
# ADR 0035 - Magazzino e ciclo passivo
- **Stato:** accettata
- **Data:** 2026-11-12
- **Modifica:** SPEC §11.5, §11.6, §12.12; milestone M6, issue #55-#61
## Contesto
SPEC §11.6 chiede giacenze per deposito con impegnato, ordinato e disponibile aggiornati nella stessa transazione del
documento, costo medio ponderato (FIFO e LIFO predisposti), inventario fisico, proposta di riordino, valorizzazione a
data e una ricostruzione; §11.5 il ciclo passivo con protocollo IVA, import delle fatture elettroniche ricevute,
controllo dei prezzi rispetto all'ordine e autofatture TD16-TD29. Il motore documenti di M5 (ADR 0032) sa già quali
generi hanno effetto *Inventory*; restavano aperti: come si registra un movimento, come si calcola il costo quando i
documenti arrivano fuori ordine di data, come non contare due volte la merce di una fattura nata da un DDT, come
portare le novità nelle aziende create prima, dove stanno le regole italiane di autofatture e import.
## Decisione
1. **La causale decide, il genere filtra.** Ogni tipo documento ha una causale di magazzino (`inventory_reasons`:
carico, scarico, nessun effetto; flag *trasferimento* e *muove il valore*). `StockEffectMatrix` (in `Khaemhat.Core`)
dice quali generi la applicano (DDT, fatture immediate e accompagnatorie, note, DDT e fatture fornitore, note di
credito fornitore, movimenti `MM`) e quali hanno costi d'acquisto che muovono la media (DDT fornitore, fattura
fornitore, movimento con prezzo). Ordini clienti e fornitori non muovono la giacenza: il loro **residuo** è
l'impegnato e l'ordinato. Le causali di base sono 12 (`CAR`, `SCA`, `RESC`, `RESF`, `TRA`, `INVP`, `INVN`, `CVU`,
`CVR`, `OMA`, `AUTO`, `APE`).
2. **Movimenti come righe derivate.** `InventoryPoster` gira dentro la transazione del motore documenti: alla conferma
scrive un `inventory_entries` per documento con una riga per articolo e deposito (`inventory_entry_lines`, quantità
nell'unità base, con segno); all'annullamento o alla modifica di un documento in vigore lo riscrive da capo. Le righe
che vengono da un documento che ha già mosso la merce nello stesso verso (la fattura di un DDT) sono saltate;
la nota di credito di una fattura la muove all'inverso.
3. **Storia ricalcolata, non saldi incrementali.** Dopo ogni modifica la storia degli articoli toccati viene
ripercorsa per data e ordine di registrazione (`StockCostCalculator`): giacenza per deposito, costo medio ponderato
dell'articolo su tutti i depositi, ultimo costo, date di ultimo carico e scarico, e i risultati vanno in
`item_balances` e nella scheda articolo. Così un documento con una data passata dà lo stesso risultato di uno
inserito in ordine. Ogni carico con valore sposta la media; gli altri movimenti escono alla media del momento; con
giacenza a zero o negativa il carico successivo fissa la media. La giacenza negativa non blocca la conferma (non
si fermano le consegne), si vede nelle giacenze e nella dashboard.
4. **La fattura corregge il costo del carico.** Il prezzo di una fattura fornitore confermata sostituisce, per la quota
fatturata, il costo dei carichi dei DDT fornitore che fattura; la differenza di prezzo rispetto a ordine e ricevimento
è anche mostrata come avviso sulla fattura (`PurchaseService.PriceDifferencesAsync`), senza bloccare.
5. **Ricostruzione.** `InventoryService.RebuildAsync` cancella i movimenti e riposta tutti i documenti in vigore,
dal più vecchio e, a parità di data, i DDT prima delle fatture, poi ricalcola ogni articolo; gira a mano (con
avanzamento) e ogni domenica come job di sistema `inventory.rebuild`.
6. **Inventario come documento a sé.** `stock_takes` e `stock_take_lines` fotografano la giacenza contabile alla
data del conteggio; la registrazione crea due movimenti `MM` (`INVP` e `INVN`) alla stessa data. Gli articoli non
contati non vengono toccati; non c'è blocco dei movimenti durante il conteggio, perché le rettifiche sono datate
e la storia ricalcolata tiene conto dei movimenti successivi.
7. **Valorizzazione.** Costo medio ponderato, ultimo costo e costo standard a qualsiasi data, con classi ABC (80% e
95% del valore). FIFO e LIFO restano **predisposti**: il criterio è un parametro del calcolo
(`StockValuationMethod`) e i movimenti conservano data, quantità e costo di ogni carico, ma i due metodi non sono
ancora offerti perché richiedono i lotti di carico, rimandati a dopo la 1.0.
8. **Tabelle di base nelle aziende esistenti.** La migrazione `M20261113_001_CreateInventory` crea le tabelle e
assegna la causale ai tipi di base che non l'hanno (`FI` → `SCA`, `FF` → `CAR`, `NCF` → `RESF`), senza toccare una
causale scelta dall'utente. I tipi nuovi (`AF20`-`AF29`) e le causali mancanti si aggiungono con *Aggiorna da
tabelle base* o `scripts/seed.sh --base`, che aggiungono i codici mancanti senza modificare quelli esistenti
(ADR 0026). Il tracciato
*Giacenze iniziali* scrive un movimento `APE` per deposito.
9. **Regole italiane nel pacchetto fiscale.** `ISelfInvoiceRules` (`SelfInvoiceRulesIt`) decide dall'anagrafica del
fornitore (paese, UE), dal genere delle righe (beni o servizi) e dalle nature IVA quale autofattura serve (TD16,
TD17, TD18, TD19, TD28) e la scadenza (15 del mese successivo; 90 giorni per TD20 e TD29).
`IIncomingInvoiceRules` (`IncomingInvoiceRulesIt`) traduce il tipo FatturaPA nel tipo documento d'acquisto (TD01,
TD02, TD03, TD05, TD06, TD24-TD27 in `FF`; TD04 e TD08 in `NCF`; gli altri sono rifiutati). L'applicazione non
conosce i codici TD.
10. **Import delle fatture ricevute.** `PurchaseInvoiceImportService` legge XML, P7M e ZIP con il lettore di #57, trova
il fornitore per partita IVA o codice fiscale (o lo crea), rifiuta i doppioni (stesso fornitore, numero, anno),
abbina le righe per codice del fornitore, EAN e codice articolo, il codice IVA per aliquota e natura, porta gli
sconti percentuali nello sconto di riga e gli altri nel prezzo netto, e salva una bozza con il file allegato.
Totale diverso, firma non verificata e sconti sul totale sono avvisi, non errori.
## Conseguenze
- Le quantità e i costi sono sempre ricostruibili dai documenti: i movimenti sono un dato derivato e la ricostruzione
è anche la verifica di coerenza.
- Ricalcolare la storia di un articolo costa più di un aggiornamento incrementale; con le dimensioni di una PMI
(migliaia di movimenti per articolo all'anno) resta nell'ordine dei millisecondi, e i documenti toccano pochi
articoli alla volta. Se servirà, un punto di partenza annuale (chiusura del magazzino) accorcia la storia.
- I documenti fornitore senza numero interno (`DDTF`) si riconoscono dal numero del fornitore; l'interfaccia li mostra
come *Senza numero*.
- Rimandati: lotti, matricole e ubicazioni; FIFO e LIFO; libro inventari e scritture delle rimanenze (M7); XML delle
autofatture e scarico dal canale SDI (M9); report di magazzino stampabili (M13).
+65
View File
@@ -0,0 +1,65 @@
# ADR 0036 - Contabilità generale
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.7, §12.11; milestone M7, issue #62, #63, #67, #68
## Contesto
SPEC §11.7 chiede un piano dei conti a tre livelli con un modello italiano, causali con righe proposte, prima nota
in partita doppia con registrazioni provvisorie e definitive, registrazioni ricorrenti, partitari di clienti e
fornitori, mastrini, bilancio di verifica e libro giornale. Restavano aperti: come si numerano le registrazioni,
quando una registrazione non si può più toccare, come si correggono gli errori, dove sta il modello del piano dei
conti, come si portano piano e causali nelle aziende create prima di M7.
## Decisione
1. **Piano dei conti a tre livelli.** `gl_accounts` con codice `MM.CC.SSS` (mastro, conto, sottoconto), padre,
natura (attività, passività, costo, ricavo, ordine), tipo (generico, clienti, fornitori, banca, cassa, IVA,
tributi), voce del bilancio CEE, flag *partitario*, *rilevante IVA* e *chiusura automatica*. Si registra solo sui
sottoconti; i conti con partitario chiedono il cliente o il fornitore sulla riga. Un conto con movimenti o con
sottoconti non si elimina (si disattiva). Le regole sui codici stanno in `AccountCodes` (`Khaemhat.Core`).
2. **Il modello sta nel pacchetto fiscale.** `ILedgerTemplate` (`ItalianLedgerTemplate`) dà il piano *PMI standard*
(237 conti, da `Data/piano-dei-conti.csv`), le causali, i registri IVA, il conto di ogni ruolo contabile
(`PostingRole`: clienti, fornitori, IVA vendite e acquisti, erario, ritenute, bollo, arrotondamenti...) e quale
causale usa ogni tipo documento. L'applicazione non conosce codici di conto italiani.
3. **Causali con righe proposte.** `gl_journal_templates` e `gl_journal_template_lines`: area, registro IVA,
*apre partite*, *causale di storno*, righe con ruolo o conto, segno e descrizione. La causale di storno non ha
righe: copia quelle della registrazione stornata a segni invertiti. Una causale usata non si elimina.
4. **Tre stati e due numeri.** Una registrazione (`gl_entries`, `gl_entry_lines`, `gl_entry_vat`) nasce *Bozza*
(può non quadrare, non entra nei saldi se non lo si chiede), diventa *Registrata* quando quadra (numero di
registrazione per anno, assegnato alla registrazione) e *Definitiva* con **Rendi definitive** fino a una data: le
registrazioni ricevono il numero del libro giornale in ordine di data e non si modificano né si eliminano più. Il
comando è rifiutato se prima di quella data restano bozze, e dopo non si registra più con una data anteriore
all'ultima definitiva. Gli errori su una definitiva si correggono solo con lo
**storno** (registrazione `STO` a segni invertiti, una sola per registrazione). `JournalEntryValidator`
(`Khaemhat.Core`) controlla quadratura, sottoconti, partitari, righe IVA.
5. **Partite aperte.** Le registrazioni con una causale che *apre partite* scrivono `gl_open_items` (una per rata,
con scadenza, importo, pagato); il partitario mostra saldo, estratto conto e partite, con le scadute evidenziate.
Incassi e pagamenti che chiudono le partite arrivano con la tesoreria (M8).
6. **Ricorrenti come copia di un modello.** `gl_recurring_entries` punta a una registrazione modello e ne crea una
copia a ogni data (mensile, trimestrale, semestrale, annuale, con la fine del mese mantenuta) fino alla data di
fine; il job di sistema `ledger.recurring` gira ogni giorno alle 05:00 e il pulsante *Genera ora* lo anticipa. Le
copie sono *Registrate* con origine *Ricorrente*.
7. **Saldi calcolati dalle righe.** Mastrini, partitari e bilancio di verifica (`LedgerQueryService`) sommano le
righe del periodo, con saldo di apertura dalle righe precedenti, senza tabelle di saldi: le registrazioni toccano
poche righe e i totali restano coerenti per costruzione. Il bilancio di verifica raggruppa per mastro, conto e
sottoconto, filtra per centro di costo e mostra il risultato del periodo (ricavi meno costi).
8. **Stampe.** Libro giornale di prova o definitivo, mastrini, estratti conto e bilancio di verifica sono PDF di
`LedgerReport` sul motore di stampa di M5 (ADR 0034).
9. **Aziende esistenti.** La migrazione `M20261113_002_CreateLedger` crea le tabelle; i documenti hanno già la
colonna *contabilizzato* da M5. Piano dei conti, causali e registri arrivano da `LedgerSeeder` (seed di base, *Aggiorna da tabelle
base* o `scripts/seed.sh --base`), che aggiunge i codici mancanti senza toccare quelli esistenti (ADR 0026). La
demo (`DemoLedgerSeeder`) contabilizza i documenti demo, paga la fattura del professionista, crea il noleggio
mensile della stampante come ricorrente, conferma le liquidazioni dei mesi passati e paga gli F24 scaduti.
10. **Permessi.** `ledger.account.read/write`, `ledger.entry.read/write/finalize`; tutto dietro il modulo `ACCT`.
## Conseguenze
- Un errore su una registrazione definitiva lascia sempre traccia (registrazione originale e storno), come chiede il
libro giornale.
- Sommare le righe a ogni richiesta costa più di un saldo memorizzato; con le dimensioni di una PMI (decine di
migliaia di righe l'anno) resta sotto il secondo, e gli indici su conto e data coprono le query. La chiusura
dell'esercizio (M10) porta i saldi di apertura e accorcia la storia.
- Rimandati: chiusura e riapertura dell'esercizio, bilancio CEE riclassificato, cespiti (M10); incassi, pagamenti e
riconciliazione bancaria (M8); budget per centro di costo.
+72
View File
@@ -0,0 +1,72 @@
# ADR 0037 - Contabilizzazione dei documenti, IVA e F24
- **Stato:** accettata
- **Data:** 2026-11-13
- **Modifica:** SPEC §11.7, §11.8, §12.11; milestone M7, issue #64, #65, #66
## Contesto
SPEC §11.7 e §11.8 chiedono che fatture, note e autofatture si contabilizzino da sole, con registri IVA,
liquidazione periodica, acconto, comunicazione LIPE, ritenute d'acconto, certificazione unica, bollo virtuale e
prospetto F24. Restavano aperti: quando si scrive la registrazione di un documento, come si corregge, come si
calcola la liquidazione, cosa succede se la si riapre, dove stanno codici tributo e scadenze italiane.
## Decisione
1. **Contabilizzazione nella transazione del documento.** `LedgerPoster` gira nel motore documenti, come
`InventoryPoster` (ADR 0035), e solo con il modulo `ACCT` attivo. Fatture (immediate, accompagnatorie,
differite, di acconto), note di debito e parcelle sono *vendite*; la nota di credito è una vendita a segni
invertiti; fattura e nota fornitore sono *acquisti*; autofatture e integrazioni vanno in entrambi i registri. La
modifica di un documento in vigore riscrive la sua registrazione **con lo stesso numero**; l'annullamento la
elimina o, se è definitiva, la storna. Una registrazione che viene da un documento non si modifica a mano: si
corregge il documento. I documenti confermati prima della licenza si contabilizzano in blocco
(`LedgerService.PostPendingAsync`, pulsante *Contabilizza documenti*).
2. **Regole di registrazione in `PostingEngine`** (`Khaemhat.Core`, senza accesso ai dati): vendita = cliente Dare
per il totale, ricavi Avere per conto dell'articolo o della riga, rivalsa cassa e bollo addebitato Avere, IVA
vendite Avere; scissione dei pagamenti = l'IVA torna dal cliente al conto dell'erario; acquisto = fornitore Avere,
costi Dare con l'IVA indetraibile sommata al costo, IVA acquisti Dare; autofattura = IVA acquisti Dare e IVA
vendite Avere. Sconti di testata e arrotondamenti vanno sulla riga più grande, così la registrazione quadra sempre
al centesimo. Un conto mancante blocca la conferma con un errore che dice quale ruolo configurare.
3. **Righe IVA e partite dal documento.** Il castelletto del documento diventa `gl_entry_vat` nel registro della
causale (`VEN1`, `VEN-RC`, `ACQ1`, `ACQ-RC`, `CORR`) con protocollo, data IVA, esigibilità e quota indetraibile;
le rate diventano partite aperte; la ritenuta del documento diventa una riga di `withholdings`.
4. **Registri e stampa definitiva.** I registri IVA si leggono per periodo con il riepilogo per aliquota; la stampa
definitiva (`vat_register_prints`) parte dal giorno dopo l'ultima stampa definitiva e continua la numerazione delle
pagine dell'anno. Il blocco del periodo viene dalla liquidazione (punto 5), non dalla stampa.
5. **Liquidazione in `VatSettlementCalculator`** (`Khaemhat.Core`): IVA a debito delle vendite e dei corrispettivi
esigibili (l'esigibilità differita resta fuori), IVA a credito degli acquisti al netto dell'indetraibile e del pro
rata, credito o debito del periodo precedente, acconto di dicembre, interessi dell'1% sul trimestrale (anche sul
quarto, versato a marzo con il codice 6099), minimo di versamento sotto il quale il debito passa al periodo dopo. Periodicità dal profilo
azienda. La liquidazione si **calcola** quante volte si vuole e si **conferma** in ordine: la conferma scrive la
registrazione `LIQ` (IVA vendite Dare, IVA acquisti Avere, interessi Dare, erario c/liquidazione Avere), segna i
periodi fiscali come liquidati (da lì documenti e registrazioni con IVA in quelle date sono rifiutati, ADR 0026
sui periodi) e crea il versamento F24 se c'è da pagare. La si può **riaprire** finché il suo F24
non è pagato e nessuna liquidazione successiva è confermata.
6. **Regole italiane nel pacchetto fiscale.** `IVatSettlementRules` (`VatSettlementRulesIt`) dà minimo (25,82),
interessi trimestrali, acconto (88%, minimo 103,29, metodi storico, previsionale ed effettivo), codici tributo
(6001-6012, 6031-6033, 6099 con rateazione 0101, 6013 e 6035 per l'acconto, 1040 per le ritenute, 2521-2524 per il
bollo), scadenze (16 del mese, agosto al 20, acconto al 27 dicembre, giorno lavorativo successivo) e soglie del
bollo virtuale (5.000 euro sul primo e secondo trimestre). `IPeriodicVatReturnWriter` (`LipeWriter`) scrive il
file LIPE (fornitura `IVP18`); `ITaxPaymentFormExporter` esporta i dati F24 in CSV.
7. **Tributi come versamenti.** `tax_payments` raccoglie ogni riga da versare (IVA, acconto, ritenute, bollo) con
codice, periodo e scadenza; il prospetto F24 le raggruppa per scadenza. *Registra pagamento* scrive la
registrazione `F24` (erario Dare per origine, banca Avere) e segna le righe come pagate; si annulla eliminando o
stornando quella registrazione.
8. **Ritenute.** Quelle *operate* nascono dalle fatture dei professionisti: in attesa finché la fattura non è
pagata, poi da versare (registrazione `RIT`, riga F24 al 16 del mese dopo); quelle *subite* nascono dalle
parcelle emesse (registrazione `RITS`, credito per ritenute). I dati della certificazione unica si esportano in
CSV per anno e percipiente.
9. **Nessun invio telematico.** Khaemhat prepara LIPE, dati F24 e dati CU; l'invio resta all'utente o
all'intermediario con i servizi dell'Agenzia delle Entrate.
10. **Permessi.** `vat.register.read`, `vat.settlement.read/confirm`, oltre a quelli di ADR 0036.
## Conseguenze
- Documenti e contabilità non divergono: la registrazione è un dato derivato, scritto nella stessa transazione, e
una contabilizzazione in blocco la ricostruisce.
- Correggere un documento di un periodo già liquidato è rifiutato dal blocco dei periodi: si corregge con una nota
di variazione, come prevede la norma, oppure si riapre la liquidazione.
- La verifica a mano della demo è un test (`DemoLedgerTests`): la prima liquidazione con IVA è ricalcolata dai
registri e confrontata con quella confermata.
- Rimandati: dichiarazione IVA annuale, Intrastat, F24 telematico, plafond e dichiarazioni d'intento, IVA per cassa
con chiusura automatica delle partite (con gli incassi di M8).
+122 -121
View File
@@ -1,178 +1,179 @@
# Acquisti
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
> **Modulo di licenza:** CORE (XML delle autofatture e canale SDI con EINV, registrazione con ACCT) · **Permessi principali:** famiglia `purchases.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.3, §11.5
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **Modulo di licenza:** CORE (XML delle autofatture con EINV, registrazione contabile con ACCT) · **Permessi principali:** `purchases.order.*` (ordini fornitore), `inventory.entry.*` (DDT fornitore), `purchases.invoice.*` (fatture, note di credito, import, autofatture) · **Specifica:** SPEC §11.3, §11.5, ADR 0035
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche generati dalla proposta di riordino),
**DDT di carico** con controllo delle quantità ricevute, **fatture di acquisto** con protocollo IVA e conti per riga,
**note di credito** dei fornitori, **import delle fatture passive** XML/P7M ricevute dallo SDI e le **autofatture e
integrazioni** (TD16-TD29) per reverse charge e acquisti dall'estero.
Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche dalla proposta di riordino),
**ricevimento della merce** con il DDT del fornitore, **fatture e note di credito dei fornitori** con il protocollo
IVA, **import delle fatture elettroniche** ricevute (XML, P7M, ZIP) e le **autofatture e integrazioni** (TD16-TD29)
per inversione contabile e acquisti dall'estero.
> **In questa versione** ci sono ordini, ricevimenti, fatture e note di credito fornitore con protocollo, carico a
> magazzino e costo medio, controllo dei prezzi rispetto a ordine e ricevimento, import delle fatture elettroniche e
> autofatture in bozza con la loro scadenza. Dalla 0.7 le fatture e le note fornitore **si contabilizzano** da sole
> con i registri IVA (vedi [Contabilità](Contabilita) e [IVA](IVA)). Arrivano più avanti: i **pagamenti** e lo scadenzario (M8), il **file XML** delle autofatture e lo scarico dal canale SDI (M9).
## Dove si trova
Menu **Acquisti** → *Ordini fornitori*, *DDT di carico*, *Fatture di acquisto*, *Import XML SDI*, *Autofatture*.
Menu **Acquisti** → *Ordini fornitori*, *Ricevimenti merce*, *Fatture passive*, *Importa fatture*, *Autofatture*.
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali):
vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) e [Vendite](Vendite) per il motore documenti.
Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali,
trasformazioni, stampa, allegati): vedi [Vendite](Vendite) per il funzionamento del motore documenti e
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) per la tastiera.
```
Proposta di riordino ──► Ordine fornitore ──ricevi merce──► DDT di carico ──registra fattura──► Fattura di acquisto
▲
Fattura passiva XML/P7M (SDI) ──import──┘ (abbinamento all'ordine o al DDT)
Proposta di riordino ──► Ordine fornitore ──Crea DDT fornitore (carico)──► Ricevimento ──Crea Fattura fornitore──► Fattura
▲
Fattura elettronica XML / P7M / ZIP ──Importa fatture──► Fattura in bozza ─┘
Fattura di un fornitore estero o in reverse charge ──Crea autofattura──► Autofattura / integrazione (TD16-TD29)
```
## Ordini fornitori
![031 · Ordine fornitore generato dalla proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/031-ordine-fornitore.png)
*Mockup 031 — ordine fornitore confermato, nato dalla proposta di riordino, con il pannello Origine del fabbisogno (anteprima ridotta).*
Un **ordine fornitore** (`OF`) dice al fornitore che cosa ti serve; non muove il magazzino ma, una volta
**confermato**, aumenta l'**ordinato** degli articoli finché non arriva la merce (vedi [Magazzino](Magazzino)).
Azioni: **Invia al fornitore** (e-mail con il PDF dell'ordine), **Ricevi merce (DDT carico)**, **Chiudi residuo**.
- Scegliendo il fornitore si applicano le sue condizioni (pagamento, banca, porto, valuta).
- Scegliendo un articolo, Khaemhat propone il **prezzo del fornitore** dalla scheda articolo (*Fornitori*).
- Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
[Magazzino](Magazzino#proposta-di-riordino)) o copiando un altro documento.
- Quando la merce arriva, **Crea DDT fornitore (carico)** porta le righe ancora da ricevere nel ricevimento: puoi scegliere
righe e quantità, così un ordine può essere ricevuto in più volte. Lo stato diventa *Evaso in parte* ed *Evaso*;
**Chiudi** chiude un residuo che non arriverà più.
- L'intestazione mostra la **data prevista** di consegna, calcolata come data dell'ordine + **lead time** del
fornitore, e lo stato di ricevimento (*Ricevuto 0%*…).
- Le righe riportano il **codice del fornitore** per l'articolo; il prezzo proposto è quello del fornitore.
- Il pannello **Origine del fabbisogno** spiega perché si ordina: sottoscorta, impegni da ordini clienti, lotto di
riordino.
- Schede: *Righe*, *Testata*, *Totali*, *Ricevimenti*, *Note*, *Allegati*, *Collegamenti*.
- Un ordine confermato aggiorna l'**ordinato** degli articoli (vedi [Magazzino](Magazzino)).
![Khaemhat 0.6.0 · ricevimento della merce](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-ricevimento.png)
Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi
[Magazzino](Magazzino)) o dall'azione **Ordina a fornitore** di un ordine cliente.
## Ricevimenti merce (DDT fornitore)
## DDT di carico
Il **DDT fornitore (carico)** (`DDTF`) registra la merce arrivata. Non ha un numero interno: nella testata scrivi il
**numero e la data del DDT del fornitore**, che lo identificano (nell'elenco compare come *Senza numero*).
![032 · DDT di carico con controllo quantità ricevute](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/032-ddt-di-carico.png)
*Mockup 032 — ricevimento con confronto ordinato/ricevuto, riga con 20 pezzi mancanti e aggiornamento del costo medio (anteprima ridotta).*
1. Dall'ordine premi **Crea DDT fornitore (carico)**, oppure crea un ricevimento e richiama l'ordine.
2. Controlla le **quantità ricevute** riga per riga e il **deposito** di arrivo.
3. **Conferma**: la merce viene **caricata a magazzino** con la causale `CAR` e aggiorna **costo medio** e **ultimo
costo** degli articoli; l'ordine segna le quantità evase.
Il **DDT di carico** registra la merce ricevuta. Azioni: **Registra fattura da questo DDT**, **Stampa etichette**,
**Riapri**.
Un ricevimento confermato resta modificabile finché non è fatturato; dal ricevimento **Crea Fattura fornitore**
prepara la fattura con le stesse righe.
1. Dall'ordine fornitore premi **Ricevi merce** oppure crea un DDT di carico e usa **Evadi da…** per richiamare
l'ordine.
2. Indica numero e data del **DDT del fornitore**.
3. Conta la merce: per ogni riga inserisci la quantità **ricevuta**; si può **scansionare l'EAN o il codice
fornitore** per contare. La colonna *Controllo* segnala le differenze (*OK*, *Mancanti 20*…).
4. **Conferma**: la merce viene **caricata a magazzino** (causale *Carico da fornitore*, deposito indicato), si
aggiornano **ultimo costo** e **costo medio ponderato** dell'articolo.
## Fatture passive
Se arriva meno del previsto, il **residuo** resta aperto sull'ordine; se non arriverà più si chiude con **Chiudi
residuo**. Un messaggio sotto le righe riassume differenze e variazioni del costo medio.
![Khaemhat 0.6.0 · fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png)
## Fatture di acquisto
![033 · Fattura di acquisto da XML con conti e centri di costo per riga](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/033-fattura-di-acquisto.png)
*Mockup 033 — fattura di acquisto in bozza nata da XML, con protocollo, flag Verifica prezzi, righe con conto e centro di costo, castelletto con IVA detraibile (anteprima ridotta).*
Azioni: **Registra (protocolla)**, **Contabilizza**, **Confronta con ordine**, **Apri XML**.
La **fattura fornitore** (`FF`) e la **nota di credito fornitore** (`NCF`) registrano i documenti del fornitore.
| Dato | Descrizione |
|---|---|
| **Data di registrazione** e **data/numero del documento** del fornitore | la registrazione determina il periodo IVA |
| **Protocollo** | numero progressivo del registro IVA acquisti (es. `ACQ/2026/000613`), assegnato alla registrazione |
| **Conto e centro di costo per riga** | ogni riga ha il proprio conto di costo e centro di costo (proposti da articolo, categoria o fornitore) |
| **Indetraibilità** | codici IVA con indetraibilità parziale o totale (es. telefonia 50%): il castelletto mostra imponibile, imposta e quota **detraibile** |
| **Ritenute e cassa** | per i professionisti: ritenuta d'acconto, cassa previdenza; il totale mostra il **netto a pagare** |
| **Registrazione contabile** | scheda con l'anteprima della registrazione (con modulo Contabilità) |
| **N. documento fornitore** e **data** | numero e data scritti dal fornitore (nella testata) |
| **Data** | data di registrazione: decide il periodo IVA |
| **Protocollo** | numero progressivo del registro IVA acquisti (numeratore `PRA`), assegnato alla **conferma**; nell'elenco compare nella colonna *Protocollo* |
| **Righe** | articoli, righe descrittive e spese con il codice IVA di ogni riga; per i professionisti ritenuta d'acconto e cassa come nelle vendite |
| **Scadenze** | calcolate dal pagamento del fornitore |
Schede: *Righe*, *Testata*, *Totali*, *Scadenze*, *Ritenute e cassa*, *Registrazione contabile*, *Note*,
*Allegati*, *Collegamenti*.
La fattura nasce dal ricevimento (**Crea Fattura fornitore**), dall'ordine (per servizi o merce senza DDT), dall'**import
della fattura elettronica** (vedi sotto) o a mano. **Conferma** assegna il protocollo e la rende definitiva; una
fattura confermata si corregge con una **nota di credito fornitore** (**Crea Nota di credito fornitore**).
**Registra (protocolla)** assegna il protocollo e rende la fattura definitiva; **Contabilizza** crea la registrazione
(automatica alla conferma o in batch, secondo le preferenze). La fattura può nascere:
**Magazzino.** Una fattura di merce senza DDT carica il magazzino alla conferma; una fattura nata da un ricevimento
non carica di nuovo, ma il suo **prezzo corregge il costo** del carico. La nota di credito fornitore scarica la merce
resa (causale `RESF`).
- dal **DDT di carico** (**Registra fattura da questo DDT**), che la collega ai carichi;
- dall'**import XML** (vedi sotto);
- a mano, ad esempio per fatture cartacee o estere.
**Controllo dei prezzi.** Se una riga della fattura ha un prezzo diverso da quello dell'ordine o del ricevimento da
cui viene, sopra le righe compare un avviso con la differenza totale e, riga per riga, il prezzo atteso e quello
fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota di credito.
Le **note di credito dei fornitori** si registrano allo stesso modo e chiudono le partite collegate.
## Importare le fatture elettroniche
## Import delle fatture passive XML/P7M
![Khaemhat 0.6.0 · import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png)
![034 · Import fatture passive XML/P7M](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/034-import-xml-sdi.png)
*Mockup 034 — quattro file in import (pronto, con ritenuta e cassa, fornitore da creare, duplicato) e mappatura delle righe sull'ordine con differenza di prezzo (anteprima ridotta).*
**Acquisti → Importa fatture** (o il link nell'elenco delle fatture passive) registra in bozza le fatture ricevute
dallo SDI o dal tuo intermediario.
1. Carica i file con **Carica XML / P7M / ZIP**, oppure **Leggi inbox** (cartella di ingresso dell'istanza) o
**Scarica dal canale SDI** (con il modulo Fatturazione elettronica).
2. Per ogni file Khaemhat legge fornitore, numero, data, tipo documento (TD) e totale e mostra un **esito**:
*Pronto*, *Fornitore da creare*, *Duplicato*, oppure avvisi (ad esempio *Ritenuta 20% · cassa 4%*).
3. Il **fornitore** viene riconosciuto da **partita IVA o codice fiscale**; se non esiste si crea al volo dai dati
dell'XML.
4. **Mappatura righe**: ogni riga XML viene abbinata a un articolo cercando, in ordine, il **codice del fornitore**,
l'**EAN** e la **descrizione** (ricerca approssimata). Le righe non abbinate diventano descrittive o si abbinano a
mano.
5. **Abbina a ordine**: confronta prezzi e quantità con l'ordine fornitore; le differenze sono evidenziate (es.
*+3,4%*).
6. **Salva bozza** o **Registra fattura di acquisto**. Se ci sono differenze la fattura nasce **in bozza** con il
flag *Verifica prezzi*.
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
motivo.
2. **Controllo**: per ogni fattura vedi fornitore (nuovo o già in anagrafica), numero, data, tipo, totale e un esito:
*Pronta*, oppure *Già registrata* (stesso fornitore, stesso numero, stesso anno), *Non è un acquisto* (per esempio
un'autofattura emessa dall'azienda stessa), *Totale diverso* (il totale del file non torna con le righe), *Firma non
verificata*, *Sconto sul totale*. **Leggi** mostra righe, riepilogo IVA e pagamento del file.
3. **Registrazione**: spunta le fatture e premi **Registra in bozza**. Per ognuna Khaemhat:
- trova il **fornitore** dalla partita IVA o dal codice fiscale, o lo **crea** dai dati del file;
- crea una **fattura fornitore** (tipi TD01, TD02, TD03, TD05, TD06, TD24-TD27) o una **nota di credito fornitore**
(TD04, TD08) in bozza, con numero e data del fornitore e la causale nelle note;
- abbina ogni riga a un **articolo** cercando il **codice del fornitore** (scheda articolo, *Fornitori*), poi l'**EAN**,
poi il **codice articolo**; le righe non abbinate diventano righe libere con descrizione, prezzo e IVA;
- riporta gli **sconti** percentuali come sconto di riga e gli altri nel prezzo netto;
- sceglie il **codice IVA** dell'azienda con la stessa aliquota e natura;
- **allega il file** originale alla fattura (scheda *Allegati*, tipo *Fattura elettronica*).
L'**XML originale** viene allegato alla fattura; per i file **P7M** la **firma CAdES** viene verificata. I file già
importati sono riconosciuti come duplicati.
Le fatture importate restano **in bozza**: controllale e confermale per protocollarle. Se un codice IVA manca (per
esempio una natura non usata finora), aggiungilo in [Tabelle azienda](Tabelle-azienda) → *Codici IVA* e ripeti
l'import.
## Autofatture e integrazioni (TD16-TD29)
![035 · Autofattura / integrazione reverse charge](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/035-autofattura-integrazione.png)
*Mockup 035 — integrazione TD17 per servizi da un fornitore estero: IVA integrata, effetto neutro, registri RC vendite e acquisti, scadenza di invio allo SDI (anteprima ridotta).*
![Khaemhat 0.6.0 · integrazione da emettere su una fattura intracomunitaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-autofattura.png)
Quando l'IVA è dovuta dall'acquirente (inversione contabile) l'azienda deve **integrare** la fattura ricevuta o
emettere un'**autofattura**, trasmettendola allo SDI. In Khaemhat questi documenti stanno in **Acquisti →
Autofatture** e nascono dalla fattura di acquisto d'origine.
Quando l'IVA è dovuta da chi compra (inversione contabile, acquisti dall'estero) l'azienda deve **integrare** la
fattura ricevuta o emettere un'**autofattura** e trasmetterla allo SDI. Khaemhat lo riconosce da solo dalla fattura
fornitore (paese del fornitore, beni o servizi, natura IVA delle righe) e mostra sopra le righe quale documento serve e **entro quando**:
| Codice | Documento | Quando si usa |
| Tipo | Quando | Scadenza |
|---|---|---|
| **TD16** | Integrazione fattura reverse charge interno | acquisti nazionali in inversione contabile (art. 17 c.6 DPR 633/72, es. subappalto edile) |
| **TD17** | Integrazione/autofattura per acquisto di servizi dall'estero | servizi da fornitori UE ed extra-UE |
| **TD18** | Integrazione per acquisto di beni intracomunitari | beni da fornitori UE |
| **TD19** | Integrazione/autofattura per acquisto di beni ex art. 17 c.2 DPR 633/72 | beni già in Italia acquistati da soggetti non residenti |
| **TD20** | Autofattura per regolarizzazione e integrazione delle fatture | regolarizzazione nei casi previsti (definizione aggiornata dalle specifiche v1.9) |
| **TD21** | Autofattura per splafonamento | acquisti oltre il plafond dell'esportatore abituale |
| **TD22** | Estrazione beni da deposito IVA | |
| **TD23** | Estrazione beni da deposito IVA con versamento dell'IVA | |
| **TD28** | Acquisti da San Marino con IVA | fatture cartacee con IVA da operatori sammarinesi |
| **TD29** | Comunicazione per omessa o irregolare fatturazione | introdotto con le specifiche v1.9 (dal 1° aprile 2025) |
| **AF16** (TD16) | inversione contabile interna: righe con natura N6.x (subappalti, rottami, cellulari…) | 15 del mese dopo il ricevimento |
| **AF17** (TD17) | servizi da un fornitore estero, UE o extra UE | 15 del mese dopo |
| **AF18** (TD18) | beni da un fornitore di un altro Paese UE | 15 del mese dopo |
| **AF19** (TD19) | beni già in Italia comprati da un soggetto non residente (art. 17 c.2) | 15 del mese dopo |
| **AF28** (TD28) | acquisti da San Marino con IVA in fattura | 15 del mese dopo |
| **AF20**, **AF29** | regolarizzazione di una fattura non ricevuta o irregolare | 90 giorni |
| AF21, AF22, AF23 | splafonamento, estrazione da deposito IVA | a mano, quando servono |
Come funziona (esempio TD17, mockup 035):
![Khaemhat 0.6.0 · integrazioni da emettere](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-autofatture-in-attesa.png)
1. La fattura estera viene registrata negli acquisti.
2. Si crea l'integrazione: le righe sono **riprese dalla fattura estera** con imponibile e aliquota; Khaemhat
calcola l'**IVA integrata**.
3. **Conferma e genera XML**: nell'XML il **fornitore estero** compare come cedente/prestatore e la **nostra azienda**
come cessionario/committente.
4. La registrazione va contemporaneamente nel **registro IVA vendite RC** e nel **registro IVA acquisti RC**: l'effetto
è **neutro** (IVA a debito = IVA a credito, salvo indetraibilità). Il pannello *Effetto contabile* mostra le due
righe.
5. L'XML va inviato **entro il 15 del mese successivo**: Khaemhat mostra la scadenza nel documento e un promemoria
nella dashboard.
**Acquisti → Autofatture** elenca in alto le **integrazioni da emettere**, la scadenza più vicina per prima. **Crea
autofattura** (qui o nella fattura fornitore) prepara il documento in bozza: le righe della fattura con il **codice IVA
ordinario** al posto della natura, il numero e la data della fattura del fornitore come documento collegato, la data
di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` delle autofatture.
Schede: *Righe*, *Testata*, *Registrazione IVA*, *XML SDI*, *Collegamenti*. Le definizioni ufficiali dei codici sono
in [Fiscalità italiana](Fiscalita-italiana).
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
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).
## Fatture da fornitori forfettari
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2 nell'XML del fornitore) e riportano il
**bollo** quando dovuto; non sono soggette a ritenuta d'acconto. Nella scheda del fornitore il flag *Regime
forfettario* (gruppo *Ritenute e contributi*) indica questa situazione; i controlli automatici sulla fattura
importata saranno definiti in sviluppo.
Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2) e riportano il **bollo** quando dovuto;
non sono soggette a ritenuta. All'import la riga prende il codice IVA dell'azienda con natura N2.2; non serve
nessuna autofattura.
## Stati
Ordini e DDT di carico seguono gli stati del motore documenti: *Bozza*, *Confermato*, *Ricevuto parzialmente* /
*Ricevuto*, *Chiuso*, *Annullato*. Le fatture di acquisto sono *Bozza* finché non vengono **registrate
(protocollate)**; i badge indicano anche *Da XML SDI*, *Verifica prezzi*, *Caricato a magazzino*, *Da fatturare*.
| Documento | Stati |
|---|---|
| Ordine fornitore, ricevimento | *Bozza*, *Confermato*, *Evaso in parte*, *Evaso*, *Chiuso*, *Annullato* |
| Fattura e nota di credito fornitore | *Bozza*, *Confermato* (protocollata), *Annullato* |
| Autofattura | *Bozza*, *Emessa* e, con la fatturazione elettronica, gli stati dello SDI |
## Permessi e licenza
Ordini, carichi, fatture di acquisto e import da file sono nel modulo **CORE**. La generazione e l'invio dell'XML
delle autofatture e lo scarico dal canale SDI richiedono **EINV**; la registrazione contabile e i registri IVA
**ACCT**; i pagamenti **FIN**. Costi e margini sono visibili solo a chi ha il permesso `items.cost.read`.
Ordini, ricevimenti, fatture, import e autofatture sono nel modulo **CORE**. Gli ordini richiedono
`purchases.order.read`/`write`; i ricevimenti, che muovono il magazzino, `inventory.entry.read`/`write` (e
`inventory.entry.post` per confermarli); fatture, note di credito, import e autofatture `purchases.invoice.read`/`write`.
L'XML delle autofatture richiederà **EINV**, la registrazione contabile **ACCT**, i pagamenti **FIN**. Costi e margini
sono visibili solo con `items.cost.read`.
## Domande frequenti
- **L'import segna "Duplicato".** La fattura risulta già importata: non va registrata una seconda volta (il
criterio esatto di riconoscimento sarà definito in sviluppo).
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice del fornitore nella scheda articolo (*Fornitori*):
la volta successiva l'abbinamento sarà automatico.
- **Ho ricevuto meno merce di quella ordinata.** Conferma il DDT con la quantità ricevuta: il residuo resta aperto
sull'ordine.
- **L'import dice "Già registrata".** Lo stesso fornitore ha già un documento con quel numero nello stesso anno: non
va registrata due volte.
- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice che usa il fornitore nella scheda articolo
(*Fornitori*, codice fornitore): dalla volta successiva l'abbinamento è automatico.
- **Ho ricevuto meno merce di quella ordinata.** Conferma il ricevimento con la quantità arrivata: il residuo resta
aperto sull'ordine e l'ordinato degli articoli lo tiene in conto.
- **La fattura ha un prezzo diverso dall'ordine.** L'avviso sopra le righe lo segnala; se la fattura è giusta
confermala e il costo medio si allinea al prezzo fatturato.
- **Non vedo l'avviso dell'autofattura.** Compare sulle fatture di fornitori esteri o con righe in natura N6.x,
finché non c'è un'autofattura collegata. L'elenco *Integrazioni da emettere* mostra solo le fatture **confermate**.
## Pagine correlate
+9 -7
View File
@@ -1,6 +1,6 @@
# Articoli e listini
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti con il magazzino, M6)
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti dalla 0.6.0, M6)
> **Modulo di licenza:** CORE · **Permessi principali:** `items.item.read` (consultare), `items.item.write` (inserire, modificare, disattivare, prezzi), `items.item.delete` (eliminare), `items.cost.read` (vedere costi e margini) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §14 · **Decisioni:** ADR 0030
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella
@@ -75,18 +75,20 @@ salvataggio.
### Costi
- **Costo standard**: valore scritto a mano.
- **Ultimo costo** e **costo medio**: li aggiornano i carichi di magazzino (DDT di carico, fatture di acquisto) che
arrivano con il magazzino (M6); fino ad allora sono valorizzati solo nei dati di esempio. Il costo medio è il
criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
- **Ultimo costo** e **costo medio**: li calcolano i carichi di magazzino (DDT fornitore, fatture fornitore, esistenze
iniziali, movimenti di carico) dalla versione 0.6.0. Il costo medio è il criterio di valorizzazione del magazzino
(vedi [Magazzino](Magazzino#costo-medio-e-valorizzazione)).
- Il **margine** è calcolato sul prezzo: (prezzo - costo) / prezzo.
- Chi non ha il permesso `items.cost.read` non vede i costi (né nella scheda né nell'elenco né nei listini) e,
quando salva, i costi in archivio restano quelli di prima.
### Giacenze e riordino
Con **Gestito a magazzino** l'articolo parteciperà a movimenti, giacenze per deposito (*Giacenza, Impegnato,
Ordinato, Disponibile, Valore*) e **proposta di riordino**: questi arrivano con il magazzino (M6). Scorta minima,
punto e lotto di riordino si possono già compilare.
Con **Gestito a magazzino** l'articolo partecipa a movimenti, giacenze per deposito (*Giacenza, Impegnato,
Ordinato, Disponibile, Valore*) e **proposta di riordino** (vedi [Magazzino](Magazzino)). **Scorta minima**, **punto
di riordino** e **lotto di riordino** decidono lo stato dell'articolo nelle giacenze e la quantità proposta; il
**fornitore preferito** della scheda *Fornitori*, con prezzo, minimo d'ordine e lead time, è quello a cui la
proposta ordina.
### Controlli al salvataggio
+5 -1
View File
@@ -137,13 +137,17 @@ il dettaglio dell'ultima. Le esecuzioni sono registrate nel database di sistema.
## Job di sistema
Nella versione 0.2.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`):
Nella versione 0.7.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`):
| Codice | Cosa fa | Quando |
|---|---|---|
| `system.sessions-cleanup` | elimina le sessioni scadute o revocate da più di 30 giorni, nel database di sistema e in ogni azienda non disattivata | al minuto 15 di ogni ora |
| `system.license-check` | ricalcola la licenza; avvisa gli amministratori a 30, 14, 7, 3 e 1 giorno dalla scadenza e quando è scaduta | ogni ora |
| `system.log-retention` | elimina gli eventi di log più vecchi della retention del loro livello | ogni notte alle 03:30 |
| `system.attachments-trash` | svuota il cestino degli allegati oltre i giorni di conservazione | ogni notte alle 03:45 |
| `system.ecb-rates` | scarica i cambi di riferimento della BCE (richiede la rete) | nei giorni feriali alle 16:30 |
| `inventory.rebuild` | ricostruisce il magazzino di ogni azienda attiva dai documenti in vigore (vedi [Magazzino](Magazzino#ricostruzione)) | la domenica alle 02:15 |
| `ledger.recurring` | crea le registrazioni ricorrenti arrivate alla loro data in ogni azienda con la contabilità (vedi [Contabilità](Contabilita)) | ogni giorno alle 05:00 |
Oltre alle attività degli amministratori, Khaemhat esegue sempre alcuni **job di sistema**: pulizia (log e sessioni
secondo la retention), controllo della licenza, aggiornamento dei cambi BCE, lettura dell'inbox e dei canali SDI,
+3 -1
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** completa per 0.5.0 · **Ultima revisione:** 2026-11-12
> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13
Le novità di ogni versione sono nel file
[`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository
@@ -11,6 +11,8 @@ Le novità di ogni versione sono nel file
| Versione | Data | Contenuto |
|---|---|---|
| 0.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.4.0 | 2026-11-12 | M4 — Tabelle, anagrafiche, articoli: pacchetto fiscale italiano, profilo azienda, esercizi e cambi, 26 tabelle azienda con province, comuni e CAP, clienti, fornitori e contatti con controlli e VIES, articoli e listini con prezzi a validità, codici automatici, import/export guidato (anche del piano dei conti, per ora solo verifica) e dati di esempio. |
| 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). |
+275 -227
View File
@@ -1,272 +1,320 @@
# Contabilità generale
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M7; chiusura esercizio e bilancio CEE in M10)
> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.entry.write`, `ledger.entry.finalize`, `ledger.entry.reopen`, `ledger.account.write`, `ledger.closing.run`, `ledger.export` · **Specifica:** SPEC §11.7, §11.1, §14
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **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
## A cosa serve
Il modulo **Contabilità** tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
prima nota, registrazioni ricorrenti, partitari di clienti e fornitori, mastrini, bilancio di verifica e libro
giornale. È collegato al resto del gestionale: ogni fattura, nota di credito o autofattura confermata scrive da sola
la sua registrazione, con le righe IVA e le partite.
Il modulo Contabilità tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali,
prima nota, partitari e mastrini, esercizi e periodi, chiusura dell'esercizio e bilancio. È collegato al resto del
gestionale: ogni documento confermato (fattura di vendita o di acquisto, nota di credito, incasso, pagamento,
ammortamento…) genera da solo la propria registrazione partendo dalla **causale contabile** del tipo di documento.
La parte fiscale (registri IVA, liquidazione, acconto, F24, LIPE, ritenute d'acconto, bollo virtuale) è descritta
nella pagina [IVA](IVA); le regole italiane usate (piano dei conti modello, codici tributo, scadenze) in
[Fiscalità italiana](Fiscalita-italiana).
La parte IVA (registri, liquidazione, F24, LIPE, ritenute, bollo, dichiarazioni d'intento) è descritta nella pagina
[IVA](IVA); i cespiti nella pagina [Cespiti](Cespiti); partite, incassi e banche nello [Scadenzario](Scadenzario).
> **In questa versione** ci sono il piano dei conti modello *PMI standard* con voci CEE, le causali contabili, la
> prima nota manuale con castelletto IVA, la **contabilizzazione automatica** di fatture, note e autofatture, le
> 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.
> Arrivano più avanti: **scadenzario**, incassi e pagamenti bancari e riconciliazione (M8), **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.
## Dove si trova
Menu laterale **Contabilità**, con le voci **Prima nota**, **Piano dei conti**, **Causali contabili**, **Registri IVA**,
**Liquidazione IVA**, **Ritenute**, **Chiusura esercizio**, **Bilancio**. Esercizi e periodi si gestiscono da
**Tabelle azienda → Esercizi** (mockup 052). Le voci compaiono solo se il modulo ACCT è licenziato e l'utente ha i
permessi (vedi [Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)).
Menu **Contabilità** → *Prima nota*, *Piano dei conti*, *Causali*, *Partitari*, *Registri IVA*, *Liquidazione IVA*,
*Ritenute e F24*, *Bollo virtuale*, *Bilancio*. Le ultime quattro voci fiscali sono spiegate in [IVA](IVA).
## Schermate
Il menu compare solo se la licenza dell'azienda comprende il modulo **ACCT** e l'utente ha i permessi (vedi
[Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)). Esercizi e periodi si gestiscono da
**Tabelle azienda → Esercizi** (vedi [Tabelle azienda](Tabelle-azienda)); periodicità IVA e pro rata sono nel
**profilo azienda**.
![040 · Prima nota](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/040-prima-nota.png)
*Mockup 040 — registrazione di prima nota generata da una fattura di acquisto: intestazione con causale FA, stato *Provvisoria* e *Quadrata*, righe in partita doppia con centro di costo e partita, riquadro delle righe IVA (anteprima ridotta)*
![041 · Prima nota manuale non quadrata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/041-prima-nota-manuale-non-quadrata.png)
*Mockup 041 — giroconto manuale in bozza con sbilancio di € 300,00 evidenziato e suggerimento "Ctrl+D quadra sull'ultima riga" (anteprima ridotta)*
![042 · Piano dei conti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/042-piano-dei-conti.png)
*Mockup 042 — albero dei conti con saldi, dettaglio del sottoconto (natura, tipo, conto padre, voce CEE, riclassificato, flag) e mastrino sotto (anteprima ridotta)*
![043 · Causali contabili](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/043-causali-contabili.png)
*Mockup 043 — elenco delle causali con area, registro IVA e "genera partita"; sotto, il modello righe della causale FA con ruoli, segno e base d'importo (anteprima ridotta)*
![044 · Partitario](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/044-partitario-estratto-conto.png)
*Mockup 044 — partitario di un cliente con saldo iniziale, dare/avere del periodo, saldo e scaduto; movimenti con saldo progressivo e stato della partita (anteprima ridotta)*
![050 · Chiusura esercizio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/050-chiusura-esercizio.png)
*Mockup 050 — procedura guidata di chiusura in nove passi raggruppati in cinque fasi (Controlli, Assestamento, Chiusura, Apertura, Stampe), con esito e autore di ogni passo*
![051 · Bilancio CEE](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/051-bilancio-cee.png)
*Mockup 051 — bilancio CEE con stato patrimoniale espandibile e conto economico a confronto con l'esercizio precedente (Δ %); viste Verifica, CEE, Riclassificato, Indici*
![052 · Esercizi e periodi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/052-esercizi-periodi.png)
*Mockup 052 — elenco degli esercizi con stato, registrazioni e ultimo periodo IVA liquidato; sotto, i periodi mensili con stato (Aperto, Liquidato, Bloccato) e interruttore di blocco*
## Piano dei conti
Il piano dei conti ha tre livelli con codice **`MM.CC.SSS`** (mastro, conto, sottoconto; per esempio `01.04.001`
*Clienti Italia*). Alla creazione dell'azienda viene **precaricato un piano standard per PMI** con le voci di bilancio
CEE già associate (nel mockup 042 l'intestazione mostra la versione del modello caricato).
| Campo | Significato |
|---|---|
| **Codice** | `MM.CC.SSS`, gerarchico; il conto padre è il livello superiore |
| **Descrizione** | obbligatoria |
| **Natura** | patrimoniale (attività/passività), economica (costi/ricavi), d'ordine |
| **Tipo** | mastro, conto, sottoconto |
| **Voce CEE** | voce dello schema di stato patrimoniale (art. 2424 c.c.) o conto economico (art. 2425 c.c.) |
| **Riclassificato** | voce del riclassificato finanziario/gestionale (es. *Crediti commerciali*) |
| **Partitario clienti/fornitori** | il conto si articola per controparte (vedi sotto) |
| **Rilevante IVA** | il conto entra nei controlli IVA |
| **Chiusura automatica** | il conto viene chiuso dalla procedura di fine esercizio |
| **Movimentabile** | si possono registrare movimenti (di norma solo i sottoconti) |
| **Attivo** | i conti disattivati restano nello storico ma non si propongono |
Selezionando un conto nell'albero si vedono a destra i suoi dati e sotto il **mastrino** (data, registrazione,
descrizione, dare, avere, saldo); il pulsante **Mastrino completo** apre la vista intera con i filtri.
### Importare un piano dei conti
Non esiste in Italia un formato standard per scambiare il piano dei conti, quindi Khaemhat accetta tre formati:
| Formato | Uso | Contenuto |
|---|---|---|
| **CSV** (separatore `;`) | import da altri gestionali o da foglio di calcolo | colonne `codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag` |
| **XLSX** | come il CSV | stesso tracciato, una riga per conto |
| **JSON** (`khaemhat-coa.json`) | export/import completo fra installazioni Khaemhat | conti, voci di bilancio, causali e mappature |
1. Apri **Contabilità → Piano dei conti** e premi **Importa piano dei conti** (oppure usa la procedura guidata di
[Import-Export](Import-Export)).
2. Scegli il file e verifica la **mappatura delle colonne**.
3. Controlla l'**anteprima**: Khaemhat verifica la coerenza gerarchica (ogni conto ha un padre esistente, il livello
corrisponde al codice, le voci CEE esistono) e segnala le righe errate.
4. Conferma. Il risultato e gli eventuali errori restano nel report dell'importazione.
I valori ammessi nelle colonne `natura`, `tipo` e `flag` saranno fissati in sviluppo e riportati qui.
## Causali contabili e ruoli
Una **causale contabile** è il modello di una registrazione. Ogni causale ha **righe modello** che non indicano un
conto fisso ma un **ruolo**; il ruolo viene risolto nel conto reale al momento della registrazione (il conto del
cliente, il conto di ricavo dell'articolo o della sua categoria, il conto IVA del codice IVA…).
| Ruolo | Esempio di conto risolto |
|---|---|
| cliente / fornitore | sottoconto del partitario della controparte |
| ricavo / costo | conto della riga, dell'articolo o della categoria |
| IVA vendite / IVA acquisti | conti IVA del codice IVA |
| banca / cassa | conto collegato al conto bancario o alla cassa |
| Erario ritenute, cassa previdenza, bollo | conti configurati per azienda |
| abbuoni, contropartita | conti configurati o indicati a mano |
Per ogni riga si indicano anche **dare/avere**, la base dell'importo (totale documento, imponibile riga, IVA
detraibile, IVA indetraibile, ritenuta, cassa…), il **registro IVA** e se la riga **genera una partita** nello
scadenzario. Il pulsante **Prova su documento** mostra la registrazione che la causale produrrebbe su un documento
esistente, senza salvarla.
Causali di base precaricate: **FV** fattura di vendita, **NCV** nota di credito a cliente, **FA** fattura di
acquisto, **NCA** nota di credito da fornitore, **AFRC** integrazione reverse charge (autofatture TD16-TD19),
**CORR** corrispettivi, **INC** incasso, **PAG** pagamento, **INS** insoluto, **GIRO** giroconto, **AMM**
ammortamenti, **RAT** ratei e risconti, **RIM** rimanenze, chiusura e apertura, **F24**, ritenute versate, stipendi
(da import), interessi e commissioni.
```
Fattura / nota / autofattura ──Conferma──► Registrazione "Da documento" (righe, castelletto IVA, partite)
Registrazione manuale ──Registra──► Registrata ──Rendi definitive──► Definitiva (n. libro giornale) ──Storna──► Storno
Ricorrente ──ogni notte alle 5:00──► Registrazione "Ricorrente" alla data prevista
```
## Prima nota
Ogni registrazione ha un numero per esercizio (es. `2026/001205`), data di registrazione, data di competenza,
causale, descrizione, documento d'origine, registro IVA e protocollo, stato, periodo e fonte.
![Khaemhat 0.7.0 · prima nota con le registrazioni dell'esercizio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-prima-nota.png)
*La prima nota dell'azienda demo: fatture di vendita (FV) e di acquisto (FA), nota di credito (NCV), liquidazioni IVA
(LIQ), versamenti F24, ritenuta (RIT) e il noleggio mensile ricorrente, tutte nello stato* Registrata.
### Registrare a mano
**Contabilità → Prima nota** elenca le registrazioni dell'esercizio, la più recente per prima, con numero, data,
causale, descrizione, documento, cliente o fornitore, importo e stato. In alto la ricerca (descrizione, numero o
documento) e i filtri **Dal**, **Al** e **Stato**; in fondo la paginazione. Un clic sul numero apre la registrazione.
1. **Contabilità → Prima nota**, premi **+** (Ctrl+N) e scegli la causale.
2. Nella scheda **Righe contabili** inserisci conto (F4 apre il piano dei conti), descrizione, controparte, dare o
avere, centro di costo, commessa e partita. Ctrl+↓ aggiunge una riga.
3. Se la registrazione ha IVA, compila la scheda **Righe IVA** (codice IVA, imponibile, aliquota, imposta, % di
indetraibilità, detraibile, natura).
4. Controlla la **quadratura** nell'intestazione: Dare, Avere e **Sbilancio**. Se c'è uno sbilancio, **Ctrl+D**
lo assegna all'ultima riga.
5. **Salva** (Ctrl+S). La registrazione resta *provvisoria*; quando è corretta premi **Rendi definitiva**.
La scheda **Registrazioni** contiene l'elenco; la scheda **Ricorrenti** le registrazioni che si ripetono (vedi
[sotto](#registrazioni-ricorrenti)). I pulsanti della barra:
Una registrazione che non quadra si può salvare **solo come bozza** (mockup 041: badge rosso con lo sbilancio) e non
può mai diventare definitiva.
### Stati e regole
| Stato | Cosa significa | Cosa si può fare |
| Pulsante | Cosa fa | Permesso |
|---|---|---|
| **Bozza / Provvisoria** | in lavorazione, entra nei saldi ma non sul libro giornale definitivo | modificare, eliminare, rendere definitiva (solo se quadra) |
| **Definitiva** | numerata in modo continuo sul libro giornale | **immutabile**: si corregge solo con uno **storno** collegato |
| **Nuova registrazione** | apre una registrazione vuota | `ledger.entry.write` |
| **Contabilizza documenti** | registra in prima nota i documenti di vendita e acquisto confermati di un periodo che non sono ancora contabilizzati | `ledger.entry.write` |
| **Rendi definitive** | rende definitive tutte le registrazioni fino a un giorno | `ledger.entry.finalize` |
- Le registrazioni **generate da un documento** si modificano solo stornando o correggendo il documento d'origine
(pulsante **Documento origine** per aprirlo).
- Le date sono ammesse solo in **periodi aperti**: un periodo liquidato o bloccato e un esercizio chiuso rifiutano
nuove registrazioni con data interna.
- **Storna** crea la registrazione inversa collegata all'originale (campo *storno di*).
- **Registrazioni ricorrenti**: da una registrazione manuale **Salva modello ricorrente** crea un modello riusabile
(affitti, canoni, stipendi…).
- **Valuta**: le righe possono essere in valuta estera con il cambio; le differenze cambio si rilevano alla chiusura
della partita (vedi [Scadenzario](Scadenzario)).
### Gli stati di una registrazione
| Stato | Significato | Cosa si può fare |
|---|---|---|
| **Bozza** | in lavorazione, senza numero; può non quadrare; non entra nei saldi | modificare, registrare, eliminare |
| **Registrata** | numerata (per esempio `2026/00011`), quadrata, entra nei saldi e nei registri IVA | modificare ed eliminare (se manuale), stornare, rendere definitiva |
| **Definitiva** | ha il numero di **libro giornale** | solo **stornare**: non si modifica né si elimina |
Ogni registrazione indica anche la sua **origine**: *Manuale*, *Da documento*, *Liquidazione IVA*, *Versamento F24*,
*Ricorrente*, *Storno*, *Ritenuta*.
## Registrare a mano
![Khaemhat 0.7.0 · registrazione generata da una fattura di acquisto](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-registrazione-fattura.png)
*La registrazione di una fattura di acquisto intracomunitaria: causale FA, registro ACQ1, fornitore in Avere e merci
in Dare; nel castelletto IVA il codice NI41 (natura N3.2). La striscia in alto riassume Dare, Avere, Sbilancio e
righe.*
1. **Contabilità → Prima nota → Nuova registrazione**.
2. Nella **Testata** scegli la **data** e la **causale**: la causale propone le righe con conti e segni e il
**registro IVA**. Scrivi la **descrizione** e, se serve, **numero** e **data del documento**.
3. Nelle **Righe** completa per ogni riga il **conto** (si registra solo sui **sottoconti**), il **cliente o
fornitore** (obbligatorio sui conti con partitario, come *Clienti Italia* e *Fornitori Italia*), la descrizione,
il **centro di costo** e l'importo in **Dare** oppure in **Avere**. **Aggiungi riga** e il cestino aggiungono e
tolgono righe.
4. Se la registrazione ha IVA, compila il **Castelletto IVA** con **Aggiungi aliquota**: codice IVA, imponibile,
imposta e parte indetraibile. Con righe IVA serve un registro IVA.
5. Controlla la striscia in alto: **Dare**, **Avere**, **Sbilancio** e numero di **righe**. **Chiudi lo
sbilancio** mette la differenza sull'ultima riga senza importo (o su una nuova riga, a cui dai il conto).
6. **Salva bozza** conserva il lavoro anche se non quadra; **Registra** salva la registrazione, che deve quadrare, e
le assegna il numero.
Una registrazione con righe IVA non si può datare in un periodo già **liquidato** (vedi [IVA](IVA#liquidazione-iva));
nessuna registrazione si può datare in un periodo **bloccato**, in un esercizio chiuso o **prima dell'ultima
registrazione definitiva**.
### Registrazioni che vengono dai documenti
Le registrazioni *Da documento* non si modificano né si eliminano dalla prima nota: si corregge il **documento** e
Khaemhat riscrive la registrazione con lo stesso numero. Se il documento viene annullato, la registrazione sparisce
oppure, se era già definitiva, viene stornata.
### Stornare ed eliminare
- **Storna** chiede la **data dello storno** e crea una nuova registrazione con Dare e Avere invertiti, collegata
all'originale (che diventa *Stornata*). Si stornano solo le registrazioni registrate o definitive, una volta sola.
- **Elimina** toglie una registrazione manuale non definitiva. Una registrazione usata come modello di una ricorrente
si elimina solo dopo aver tolto la ricorrente.
### Rendere definitive le registrazioni
**Rendi definitive** chiede un giorno e rende definitive tutte le registrazioni registrate fino a quel giorno: ognuna
riceve il **numero di libro giornale**, in ordine di data, e da quel momento si corregge solo con uno storno.
L'operazione non si annulla ed è rifiutata se nel periodo ci sono ancora **bozze** (registrale o eliminale prima).
Dopo, nessuna nuova registrazione può avere una data anteriore all'ultima definitiva.
## Contabilizzazione automatica dei documenti
Alla conferma di un documento (o in un secondo momento con la procedura **Contabilizzazione documenti**, vedi
[Automazioni](Automazioni)) Khaemhat applica la causale contabile del **tipo documento** e genera la registrazione
con le righe IVA e le partite di scadenzario, nella stessa transazione del documento. Il documento mostra il flag
*contabilizzato* e il collegamento alla registrazione; la registrazione mostra il documento d'origine.
Con il modulo ACCT attivo, quando **confermi** (o emetti) uno di questi documenti Khaemhat scrive la sua registrazione
**nella stessa operazione**, con le righe IVA nel suo registro, le **partite** dalle rate di scadenza e l'eventuale
**ritenuta d'acconto**:
## Partitari, mastrini ed estratti conto
Il **partitario** (mockup 044) mostra per un cliente o fornitore: saldo iniziale, dare e avere del periodo, saldo,
di cui scaduto e l'elenco dei movimenti con saldo progressivo e stato della partita. Filtri per periodo, conto,
stato e "solo definitive". Da qui:
- **Estratto conto**: genera il PDF da inviare al cliente (resta come allegato, vedi [Allegati e file](Allegati-e-file));
- **Sollecito**: apre i solleciti dello [Scadenzario](Scadenzario).
Il **drill-down** è completo: dal bilancio al conto, dal conto al mastrino, dal mastrino alla registrazione, dalla
registrazione al documento.
## Esercizi e periodi
In **Tabelle azienda → Esercizi** (mockup 052) ogni esercizio ha inizio, fine, stato, numero di registrazioni,
ultimo periodo IVA liquidato, data di blocco, prima pagina del libro giornale e ultima registrazione definitiva.
| Esercizio | Periodo (mese o trimestre) |
|---|---|
| **Aperto** — si registra normalmente | **Aperto** — accetta registrazioni |
| **In chiusura** — è in corso la procedura di chiusura | **Liquidato** — la liquidazione IVA è stata confermata |
| **Chiuso** — sola lettura | **Bloccato** — rifiuta ogni registrazione con data interna |
**Nuovo esercizio** crea l'esercizio successivo; di norma lo crea la chiusura stessa, in stato provvisorio, per
permettere di registrare nel nuovo anno prima di aver chiuso il vecchio. I periodi si bloccano e sbloccano con
l'interruttore **Blocco** (permesso di riapertura richiesto).
## Chiusura dell'esercizio guidata
**Contabilità → Chiusura esercizio** (mockup 050) guida la chiusura in nove passi. Ogni passo è **ripetibile e
annullabile**; le registrazioni generate sono marcate con la fonte `closing/<passo>` e restano provvisorie fino alle
stampe definitive.
| # | Passo | Cosa fa |
| Documento | Causale | Registro IVA |
|---|---|---|
| 1 | Controlli preliminari | nessuna registrazione provvisoria, partite quadrate, IVA liquidata, numerazioni continue |
| 2 | Ammortamenti | quote civilistiche e fiscali dei [Cespiti](Cespiti) |
| 3 | Ratei e risconti | da competenze dei documenti e inserimenti manuali (**Verifica ratei/risconti**) |
| 4 | Rimanenze finali | valorizzazione del [Magazzino](Magazzino) al 31/12 e storno delle iniziali |
| 5 | Accantonamenti | svalutazione crediti, TFR (da import) |
| 6 | Chiusura conti economici | giroconto a Conto economico e rilevazione del risultato |
| 7 | Chiusura conti patrimoniali | giroconto a Stato patrimoniale finale |
| 8 | Apertura nuovo esercizio | riporto dei saldi e delle partite aperte |
| 9 | Stampe definitive | libro giornale, libro inventari, registri IVA, registro cespiti |
| Fattura immediata, accompagnatoria, differita, di acconto; nota di debito; parcella | `FV` | `VEN1` |
| Nota di credito a cliente | `NCV` | `VEN1` |
| Fattura fornitore | `FA` | `ACQ1` |
| Nota di credito fornitore | `NCA` | `ACQ1` |
| Autofatture e integrazioni (AF16-AF29) | `AFRC` | `VEN-RC` e `ACQ-RC` |
1. Apri la procedura e premi **Esegui passo N**: il passo mostra il numero di registrazioni prodotte e l'esito
(*Superato*, *Eseguito*, *Da verificare*, *In attesa*).
2. Controlla i risultati con l'icona di anteprima e, se serve, torna indietro di un passo.
3. Dopo le stampe definitive premi **Blocca esercizio**: l'esercizio diventa **chiuso**, in sola lettura, e le date
precedenti al nuovo esercizio vengono rifiutate.
Come si formano le righe:
La chiusura è anche nel catalogo delle procedure ([Automazioni](Automazioni)).
- **Vendita**: il **cliente** in Dare per il totale; i **ricavi** in Avere, raggruppati per conto; la **rivalsa
della cassa previdenziale** e il **bollo addebitato** al cliente in Avere; l'**IVA vendite** in Avere. Con lo
**split payment** l'IVA viene subito tolta al cliente (il cliente paga solo l'imponibile).
- **Acquisto**: il **fornitore** in Avere; i **costi** in Dare, con l'**IVA indetraibile** aggiunta al costo;
l'**IVA acquisti** in Dare.
- **Autofattura e integrazione**: **IVA acquisti** in Dare e **IVA vendite** in Avere, senza cliente né fornitore;
il documento compare in entrambi i registri RC, con effetto neutro sulla liquidazione.
- **Note di credito**: le stesse righe con i segni invertiti.
- Lo **sconto in calce** e gli **arrotondamenti** si ripartiscono sulle righe; i centesimi di differenza vanno sulla
riga più grande.
## Bilancio
**Quale conto.** Per ogni riga Khaemhat usa il **Conto ricavi** o **Conto costi** dell'articolo (scheda articolo),
per gli acquisti il **Conto di costo** del fornitore, poi il conto del codice IVA e, se manca, quello della causale
(`30.01.001` *Ricavi per vendita di merci*, `20.01.001` *Merci c/acquisti*). Il cliente e il fornitore usano il
**Conto cliente** o **Conto fornitore** della loro scheda, altrimenti `05.01.001` *Clienti Italia* e `14.01.001`
*Fornitori Italia*. Se manca un conto la conferma del documento si ferma con un messaggio che lo dice.
**Contabilità → Bilancio** (mockup 051) offre quattro viste:
**Contabilizza documenti.** I documenti confermati quando ACCT non era attivo (o prima della versione 0.7) si
registrano in blocco: **Prima nota → Contabilizza documenti**, scegli **Dal** e **Al** e premi **Contabilizza**. La
casella *Ricontabilizza anche i documenti già registrati* riscrive anche le registrazioni esistenti, purché non
siano definitive.
| Vista | Contenuto |
## Registrazioni ricorrenti
![Khaemhat 0.7.0 · la scheda Ricorrenti della prima nota](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-ricorrenti.png)
*Il noleggio mensile della stampante dei dati demo: frequenza mensile, prossima data, registrazione modello e stato.*
Affitti, canoni, noleggi: una registrazione **ricorrente** copia una **registrazione modello** alle date previste.
1. Registra una volta la scrittura da ripetere (per esempio *Noleggi* in Dare e *Banca c/c* in Avere).
2. **Prima nota → Ricorrenti → Nuova ricorrente**: descrizione, **numero della registrazione modello** (il numero di
prima nota, per esempio `2026/00018`), **frequenza** (*Mensile*, *Trimestrale*, *Semestrale*, *Annuale*),
**prossima data**, data **Fino al** facoltativa, casella **Sospesa**.
3. Ogni notte alle **5:00** l'attività di sistema *Registrazioni ricorrenti* (vedi
[Attività programmate](Attivita-programmate)) scrive le registrazioni arrivate a scadenza, con origine
*Ricorrente*, e sposta in avanti la prossima data. **Genera ora** fa lo stesso subito.
Una data di fine mese resta di fine mese (31/01, poi 28/02, poi 31/03). **Apri il modello** apre la registrazione da
copiare; eliminando una ricorrente le registrazioni già generate restano.
## Piano dei conti
![Khaemhat 0.7.0 · piano dei conti con il mastrino di Clienti Italia](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-piano-dei-conti.png)
*L'albero dei 237 conti del modello PMI standard, il dettaglio del sottoconto 05.01.001 Clienti Italia (sottoconto,
attività, tipo Clienti, voce CEE C.II.1, con partitario) e il suo mastrino con il saldo progressivo.*
Il piano dei conti ha tre livelli con codice **`MM.CC.SSS`**: **mastro** (`05` *Crediti verso clienti*), **conto**
(`05.01` *Clienti*) e **sottoconto** (`05.01.001` *Clienti Italia*). Si registra solo sui sottoconti. Con le tabelle
di base dell'azienda viene caricato il modello **PMI standard** del pacchetto fiscale: 237 conti con le voci di
bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano-dei-conti-modello)).
| Campo | Significato |
|---|---|
| **Verifica** | bilancio di verifica per conto (dare, avere, saldo); bilancini per centro di costo e commessa |
| **CEE** | schema civilistico **ordinario**, **abbreviato** o **micro**, con confronto con l'esercizio precedente e Δ % |
| **Riclassificato** | riclassificato finanziario e gestionale |
| **Indici** | indici di bilancio |
| **Codice** | mastro, conto e sottoconto separati da punti; il conto padre deve esistere |
| **Descrizione** | obbligatoria |
| **Natura** | *Attività*, *Passività*, *Costo*, *Ricavo*, *Conto d'ordine* |
| **Tipo** | *Generico*, *Clienti*, *Fornitori*, *Banca*, *Cassa*, *IVA*, *Tributi*: dice alle registrazioni automatiche che cosa cercare |
| **Voce di bilancio CEE** | voce dello schema civilistico (art. 2424 e 2425 c.c.), per esempio `C.II.1` |
| **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) |
| **Disattivato** | il conto resta nello storico ma non si usa più |
L'intestazione indica la data di situazione (anche **infrannuale**) e se include le registrazioni provvisorie.
Doppio clic su una voce apre i conti, poi il mastrino, la registrazione e il documento. Il bilancio si stampa e si
esporta in XLSX e PDF; la **nota integrativa** è prodotta in bozza. Il formato XBRL è previsto in fase 2
([Roadmap](Roadmap)).
A sinistra l'**albero** con la ricerca per codice o descrizione; a destra i dati del conto scelto e, per i
sottoconti, il **mastrino**: i movimenti del periodo (**Dal**, **Al**) con saldo iniziale, Dare, Avere, **saldo
progressivo**, totali e paginazione. **Stampa** scarica il mastrino in PDF; il numero della registrazione la apre.
## Export per il commercialista
**Nuovo conto**, **Modifica** ed **Elimina** richiedono `ledger.account.write`. Un conto con **movimenti** non si
elimina (disattivalo); un conto con **sottoconti** si elimina solo dopo di loro.
Pacchetto **ZIP mensile** con libro giornale, registri IVA, partitari e bilancio in XLSX, CSV e PDF. Si genera a mano
o in automatico con la procedura **Export per il commercialista** pianificata ogni mese (vedi [Automazioni](Automazioni)
e [Attività programmate](Attivita-programmate)).
## Causali contabili
## Report del modulo
![Khaemhat 0.7.0 · causali contabili, la causale FA con le righe proposte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-causali.png)
*Le causali di base con il loro registro IVA; a destra la causale FA Fattura di acquisto: area Acquisti, registro
ACQ1, apre partite, e le righe proposte con ruolo, segno e conto.*
Libro giornale, mastrini, bilancini per centro di costo e commessa, registri IVA, liquidazioni, scadenzario IVA,
elenco clienti e fornitori per fatturato, riepilogo per natura IVA, dati dei quadri VE/VF, estratti conto, export per
il commercialista. Vedi [Report](Report).
Una **causale** è il modello di una registrazione: propone conti, segni e registro IVA. Ogni causale ha:
## Scorciatoie
| Tasto | Azione |
| Campo | Significato |
|---|---|
| Ctrl+N / Ctrl+S | nuova registrazione / salva |
| Ctrl+D | quadra la registrazione sull'ultima riga |
| F4 | ricerca nel piano dei conti dalla cella *Conto* |
| Ctrl+↓ | nuova riga |
| Ctrl+↑ / Ctrl+↓ (fuori dalla griglia) | registrazione precedente / successiva |
| Alt+1…9 | cambia scheda |
| **Codice**, **Descrizione** | per esempio `FA` *Fattura di acquisto* |
| **Area** | *Generale*, *Vendite*, *Acquisti*, *Tesoreria*, *Imposte*, *Chiusura esercizio* |
| **Registro IVA** | il registro delle registrazioni con IVA |
| **Apre partite** | le registrazioni aprono partite di clienti o fornitori |
| **Causale di storno** | note di credito: i segni del documento si invertono |
| **Disattivato** | la causale non si propone più |
| **Righe proposte** | per ogni riga **ruolo** (*Cliente*, *Fornitore*, *Ricavo*, *Costo*, *IVA vendite*, *IVA acquisti*, *Banca*, *Cassa*, *Ritenute da versare*, *Ritenute subite*, *Contributo cassa*, *Bollo*, *Arrotondamenti*, *Erario c/IVA*, *IVA split payment* o *Conto indicato*), **segno** Dare o Avere, **conto** e descrizione |
Elenco completo in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie).
Causali di base: **FV** fattura di vendita, **NCV** nota di credito a cliente, **FA** fattura di acquisto, **NCA**
nota di credito da fornitore, **AFRC** autofattura e integrazione reverse charge, **CORR** corrispettivi giornalieri,
**INC** incasso da cliente, **PAG** pagamento a fornitore, **RIT** ritenuta d'acconto operata, **RITS** ritenuta
d'acconto subita, **LIQ** liquidazione IVA periodica, **F24** versamento con modello F24, **GIRO** giroconto, **SPB**
spese e commissioni bancarie, **STO** storno di scrittura.
Le causali dei documenti, della liquidazione, delle ritenute e dell'F24 sono usate dalle registrazioni automatiche:
cambiarne i conti cambia le registrazioni future. Una causale usata da registrazioni non si elimina: disattivala.
Per un'azienda creata con una versione precedente, conti, causali e registri mancanti si aggiungono con
`scripts/seed.sh --base` (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)).
## Partitari ed estratto conto
![Khaemhat 0.7.0 · partitario clienti, estratto conto e partite](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-partitari.png)
*Il partitario clienti con Dare, Avere, saldo e partite aperte; a destra l'estratto conto di Edilizia Moderna S.p.A. e
le sue partite, con le scadenze passate in rosso.*
**Contabilità → Partitari** ha due schede, **Clienti** e **Fornitori**. L'elenco mostra per ogni soggetto con
movimenti Dare, Avere, **Saldo** e numero di partite **aperte**, con ricerca per nome o codice e il **saldo
complessivo**.
Scegliendo un soggetto si vedono:
- l'**estratto conto** del periodo (**Dal**, **Al**): saldo iniziale, movimenti con documento e saldo progressivo,
totali; **Stampa** lo scarica in PDF;
- le **partite**: una per rata di ogni documento, con data documento, numero della rata, **scadenza**, importo,
pagato e **residuo**; le scadenze superate sono in rosso. *Mostra anche le partite chiuse* aggiunge quelle saldate.
In questa versione le partite nascono dai documenti; gli incassi e i pagamenti che le chiudono, i solleciti e lo
scadenzario arrivano con lo [Scadenzario](Scadenzario) (M8).
## Bilancio di verifica e libro giornale
![Khaemhat 0.7.0 · bilancio di verifica](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-bilancio.png)
*Il bilancio di verifica dell'azienda demo al livello dei sottoconti, con i totali di conti e mastri; la striscia
riassume Dare, Avere, quadratura e risultato del periodo.*
**Contabilità → Bilancio** mostra i saldi di tutti i conti in un periodo:
- filtri **Dal** e **Al**, **Centro di costo** (tutti o uno), **Dettaglio** (*Mastri*, *Conti*, *Sottoconti*) e
**Comprendi le bozze**;
- per ogni conto **saldo iniziale**, **Dare**, **Avere**, **Saldo Dare** o **Saldo Avere**, con i totali di conti e
mastri;
- la striscia con i totali **Dare** e **Avere**, la **Quadratura** (*Dare e Avere quadrano* o no) e il **Risultato
del periodo** (ricavi meno costi: *Utile* o *Perdita*).
Le stampe sono file PDF da scaricare:
| Pulsante | Contenuto |
|---|---|
| **Stampa bilancio** | il bilancio di verifica del periodo e del centro di costo scelti |
| **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).
## Dati demo
Con i dati di esempio (`scripts/seed.sh --demo`) la contabilità parte già popolata: i documenti demo sono
contabilizzati, la fattura del professionista *Studio Rag. Neri Paola* è pagata e la sua ritenuta è da versare, il
noleggio mensile della stampante (45 euro, conto `22.01.003` *Noleggi* contro la banca) è una registrazione
ricorrente, le liquidazioni IVA dei mesi già finiti sono confermate e gli F24 già scaduti sono pagati. Vedi
[Dati di base e di esempio](Dati-di-base-e-esempio).
## Permessi e licenza
Serve il modulo **ACCT**. Il permesso `ledger.entry.finalize` è necessario per rendere definitiva una registrazione;
gli altri codici indicati in testa seguono la convenzione `modulo.entità.azione` (SPEC §7.2) e saranno fissati in
sviluppo. Il ruolo predefinito **Contabilità** li comprende. Senza licenza ACCT le voci del menu non compaiono, ma i
dati restano conservati.
Serve il modulo **ACCT**: senza, il menu Contabilità non compare, i documenti non vengono contabilizzati (si
recuperano dopo con **Contabilizza documenti**) e i dati già registrati restano conservati.
## Attenzione
| Permesso | Cosa consente |
|---|---|
| `ledger.account.read` | vedere piano dei conti e causali |
| `ledger.account.write` | creare, modificare ed eliminare conti e causali |
| `ledger.entry.read` | prima nota, mastrini, partitari, bilancio e stampe del libro giornale |
| `ledger.entry.write` | registrazioni manuali, storni, ricorrenti, contabilizzazione dei documenti |
| `ledger.entry.finalize` | rendere definitive le registrazioni |
- Una registrazione **definitiva** non si modifica: va stornata. Usa lo stato provvisorio finché non hai controllato.
- Confermare una liquidazione IVA blocca il periodo: correzioni successive richiedono la riapertura (permesso
dedicato) e vanno ricalcolate.
- I numeri del libro giornale definitivo sono continui; la procedura di chiusura verifica che non ci siano buchi.
I permessi della parte IVA (`vat.register.read`, `vat.settlement.read`, `vat.settlement.confirm`) sono in [IVA](IVA).
## Domande frequenti
- **Il pulsante Registra è spento.** Dare e Avere non quadrano: guarda lo *Sbilancio* nella striscia, correggi gli
importi o usa **Chiudi lo sbilancio**. Intanto puoi usare **Salva bozza**.
- **"Si registra solo sui sottoconti".** Hai scelto un mastro o un conto: scegli un sottoconto (codice a tre parti).
- **"Le righe su clienti e fornitori indicano il soggetto".** Il conto ha il partitario: indica il cliente o il
fornitore nella riga.
- **Non riesco a modificare la registrazione di una fattura.** Viene dal documento: correggi la fattura e la
registrazione si aggiorna. Se è già definitiva, la correzione del documento la storna e la riscrive.
- **"Manca un conto per contabilizzare il documento".** Una causale o il piano dei conti non hanno il conto che
serve (per esempio dopo aver cancellato un sottoconto): controlla la causale del documento e il conto dell'articolo.
- **La data è rifiutata.** Il periodo è liquidato (solo per registrazioni con IVA), bloccato, l'esercizio è chiuso o
c'è già una registrazione definitiva successiva.
- **La ricorrente non ha generato nulla.** È sospesa, la data *Fino al* è passata o la prossima data è nel futuro;
**Genera ora** mostra l'eventuale problema.
## Pagine correlate
[IVA](IVA) · [Cespiti](Cespiti) · [Scadenzario](Scadenzario) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
[Magazzino](Magazzino) · [Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Automazioni](Automazioni) ·
[Import-Export](Import-Export) · [Fiscalità italiana](Fiscalita-italiana) · [Glossario](Glossario)
[IVA](IVA) · [Fiscalità italiana](Fiscalita-italiana) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
[Scadenzario](Scadenzario) · [Cespiti](Cespiti) · [Tabelle azienda](Tabelle-azienda) ·
[Attività programmate](Attivita-programmate) · [Dati di base e di esempio](Dati-di-base-e-esempio) ·
[Glossario](Glossario)
+1 -1
View File
@@ -56,7 +56,7 @@ magazzino* M6, *CRM* M11), senza numeri finti.
| **Attività CRM** | le attività del giorno (chiamate, riunioni, visite) | richiede il modulo CRM |
| **Promemoria personali** | note libere, visibili solo a te | |
| **Scorciatoie** | pulsanti configurabili verso maschere e azioni frequenti | |
| **Sottoscorta** | articoli sotto la scorta minima | |
| **Sottoscorta** | gli articoli più urgenti da riordinare (esauriti, sottoscorta, sotto il punto di riordino) con disponibile e scorta; un clic apre i movimenti dell'articolo, **Riordina** la proposta di riordino | dalla 0.6.0 |
| **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM |
| **Ultimi documenti** | ultimi documenti aperti o creati | |
| **Stato del sistema** | versione, database, cache, licenza, aziende aperte, attività programmate di oggi, ognuno con un pallino verde, giallo o rosso | solo account di istanza |
+14 -2
View File
@@ -1,6 +1,6 @@
# Dati di base e di esempio
> **Stato:** completa per M5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (dati di esempio di acquisti, magazzino e contabilità con i moduli, completi in M9)
> **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)
> **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14
## A cosa serve
@@ -148,7 +148,19 @@ pagina delle stampe) e **un anno di vendite** costruite con il motore dei docume
Le fatture e la nota condividono il numeratore (`1/2026` … `7/2026`), senza buchi e in ordine di data. Tutti i
documenti sono marcati come dimostrativi e la stampa lo scrive in evidenza. Il caricamento non si ripete se
l'azienda ha già documenti di vendita. Il resto della tabella arriva con le milestone dei rispettivi moduli.
l'azienda ha già documenti di vendita.
**Da M6** ci sono anche **acquisti e magazzino**, costruiti allo stesso modo:
| Documenti | Che cosa mostrano |
|---|---|
| 1 movimento di esistenze iniziali al 1° gennaio (`APE`) | la giacenza di partenza di ogni articolo; un articolo su cinque parte con poca merce, così le vendite lo portano sotto scorta e la [proposta di riordino](Magazzino#proposta-di-riordino) ha qualcosa da proporre |
| 2 ordini fornitori | uno ricevuto per intero, uno ricevuto in parte (il resto è nell'*ordinato*) |
| 2 ricevimenti merce | i carichi dei due ordini |
| 3 fatture fornitore | una dal ricevimento con un prezzo più alto dell'ordine (vedi l'avviso sulle differenze), la parcella del commercialista, la fattura di un fornitore tedesco che aspetta la sua **integrazione AF18** |
| 1 inventario aperto | 12 articoli già contati, due con una differenza |
Il caricamento non si ripete se l'azienda ha già documenti di acquisto o di magazzino. 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.
+153 -49
View File
@@ -1,21 +1,29 @@
# Fiscalità italiana
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.4.0 (codici e regole di base; il resto con M5-M10)
> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14
> **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
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, codici tributo F24 e scadenze. Serve come
riferimento rapido mentre si compilano anagrafiche, codici IVA e documenti.
SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, il **piano dei conti modello**, i **codici
tributo F24** con le scadenze, la **LIPE**, le **ritenute d'acconto** e il **bollo virtuale**. Serve come riferimento
rapido mentre si compilano anagrafiche, codici IVA e documenti e mentre si liquida l'IVA.
Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da
**Amministrazione → Dati di base e di esempio** con **Aggiorna tabelle di base**. Le descrizioni ufficiali complete
sono quelle delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in
caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
Tutto ciò che è italiano sta nel **pacchetto fiscale Italia** del programma: le tabelle sono **caricate dai dati di
base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da **Amministrazione → Dati di base e di esempio**
con **Aggiorna tabelle di base** (o con `scripts/seed.sh --base`). Le descrizioni ufficiali complete sono quelle
delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in caso di dubbio
fa fede il testo mostrato dal programma, non questa pagina.
> **Attenzione.** Khaemhat calcola e prepara i dati (F24, LIPE, Intrastat, bollo) ma **non sostituisce il
> commercialista** né invia F24 e LIPE: l'invio telematico avviene tramite intermediario o home banking, come
> indicato nella maschera della liquidazione. Le norme cambiano: la versione delle specifiche SDI supportata è
> indicata nel programma ed è verificata a ogni rilascio.
> **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).
> **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.
## Dove si trovano questi codici nel programma
@@ -25,10 +33,12 @@ caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
| Nature IVA (N…) | **Tabelle azienda → Codici IVA** | [Tabelle-azienda](Tabelle-azienda), [IVA](IVA) |
| Modalità di pagamento (MP) | **Tabelle azienda → Metodi di pagamento** | [Tabelle-azienda](Tabelle-azienda) |
| Regime fiscale (RF) | **Tabelle azienda → Profilo azienda**, scheda fornitore | [Tabelle-azienda](Tabelle-azienda), [Anagrafiche](Anagrafiche) |
| Codici tributo F24 | liquidazione IVA, ritenute, bollo virtuale | [IVA](IVA), [Contabilita](Contabilita) |
| Piano dei conti, causali, registri IVA | **Contabilità → Piano dei conti**, *Causali*, *Registri IVA* | [Contabilita](Contabilita), [IVA](IVA) |
| Codici tributo F24 | liquidazione IVA, acconto, ritenute, bollo virtuale | [IVA](IVA) |
| Tipi di ritenuta (RT) e casse (TC) | scheda fiscale del fornitore e del cliente, parcelle, fatture dei professionisti | [Anagrafiche](Anagrafiche), [IVA](IVA#ritenute-dacconto) |
![076 · Codici IVA con nature SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/076-codici-iva.png)
*Mockup 076 — tabella dei codici IVA con aliquota, natura SDI, riferimento normativo ed esigibilità; sotto, il dettaglio del codice selezionato (anteprima ridotta).*
![Khaemhat · codici IVA con natura SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/tabelle-codici-iva.png)
*La tabella dei codici IVA dell'azienda in Tabelle azienda: ogni codice porta aliquota o natura SDI.*
## Tipi documento SDI (TD)
@@ -172,58 +182,149 @@ fatture passive. Il codice RF03 non esiste più nelle specifiche correnti.
I dettagli operativi sono in [Fatturazione-elettronica](Fatturazione-elettronica).
## Piano dei conti modello
Il pacchetto fiscale porta il piano dei conti **PMI standard**: **237 conti** in tre livelli con codice `MM.CC.SSS`
(mastro, conto, sottoconto), ognuno con natura, tipo e voce dello schema di bilancio civilistico (art. 2424 e 2425
c.c.). Si carica con le tabelle di base dell'azienda e si modifica liberamente da **Contabilità → Piano dei conti**
(vedi [Contabilità](Contabilita#piano-dei-conti)).
| Mastri | Natura | Contenuto |
|---|---|---|
| `01`-`09` | Attività | immobilizzazioni immateriali, materiali e finanziarie, rimanenze, crediti verso clienti, altri crediti (IVA, tributi), disponibilità liquide, ratei e risconti attivi, fondi di ammortamento |
| `10`-`17` | Passività | patrimonio netto, fondi rischi, TFR, debiti verso banche, fornitori, debiti tributari e previdenziali, altri debiti, ratei e risconti passivi |
| `20`-`29` | Costi | acquisti, servizi, godimento di beni di terzi, personale, ammortamenti, variazioni delle rimanenze, accantonamenti, oneri diversi, oneri finanziari, imposte sul reddito |
| `30`-`32` | Ricavi | vendite e prestazioni, altri ricavi e proventi, proventi finanziari |
| `90` | Conti d'ordine | conti di apertura e chiusura |
I conti usati dalle registrazioni automatiche:
| Conto | Uso |
|---|---|
| `05.01.001` Clienti Italia | cliente delle fatture di vendita (se la scheda cliente non indica un altro conto) |
| `14.01.001` Fornitori Italia | fornitore delle fatture di acquisto |
| `30.01.001` Ricavi per vendita di merci, `30.02.001` Resi e sconti su vendite | ricavi delle fatture e delle note di credito senza conto sull'articolo |
| `20.01.001` Merci c/acquisti, `20.02.001` Resi e sconti su acquisti | costi delle fatture e note di credito fornitore senza conto sull'articolo o sul fornitore |
| `06.02.001` IVA su acquisti, `15.01.001` IVA su vendite | IVA dei registri acquisti e vendite |
| `15.01.002` Erario c/liquidazione IVA | saldo della liquidazione periodica e suo versamento |
| `15.02.001` Erario c/ritenute lavoro autonomo, `06.03.001` Erario c/ritenute subite | ritenute operate e subite |
| `31.01.002` Rimborso spese di bollo, `27.01.002` Imposta di bollo | bollo addebitato al cliente (ricavo) e bollo a carico dell'azienda (costo) |
| `31.01.003` Rivalsa contributi previdenziali | rivalsa della cassa previdenziale sulle parcelle |
| `27.01.003` IVA indetraibile | IVA indetraibile delle autofatture e del pro rata |
| `28.01.003` Interessi sulla liquidazione IVA trimestrale | interessi dei contribuenti IVA trimestrali |
| `07.01.001` Banca c/c, `07.02.001` Cassa contanti | banca predefinita per i versamenti F24, cassa dei corrispettivi |
**Registri IVA di base:** `VEN1` fatture emesse, `ACQ1` fatture acquisti, `CORR` corrispettivi, `VEN-RC` e `ACQ-RC`
per autofatture e integrazioni. **Causali di base:** FV, NCV, FA, NCA, AFRC, CORR, INC, PAG, RIT, RITS, LIQ, F24,
GIRO, SPB, STO (vedi [Contabilità](Contabilita#causali-contabili)). Fatture, note di debito e parcelle si registrano
con FV su VEN1, le note di credito con NCV, le fatture fornitore con FA su ACQ1, le note di credito fornitore con NCA,
le autofatture AF16-AF29 con AFRC su VEN-RC e ACQ-RC.
## Codici tributo F24
Khaemhat propone il codice tributo e prepara i **dati F24** da passare a intermediario o home banking.
Khaemhat propone il codice tributo e prepara i **dati F24** da passare all'home banking o all'intermediario (vedi
[IVA](IVA#prospetto-f24-e-pagamento)).
| Codice | Uso | Maschera |
| Codice | Uso | Dove nasce |
|---|---|---|
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) | Liquidazione IVA (046) |
| 6031 … 6034 | IVA trimestrale, dal 1° (6031) al 4° trimestre (6034, contribuenti trimestrali "speciali") | Liquidazione IVA |
| 6013 | Acconto IVA mensili | Liquidazione IVA (acconto di dicembre) |
| 6035 | Acconto IVA trimestrali | Liquidazione IVA (acconto di dicembre) |
| 6099 | IVA dovuta in base alla dichiarazione annuale | Liquidazione IVA |
| 1040 | Ritenute su redditi di lavoro autonomo | Ritenute (047) |
| 1038 | Ritenute su provvigioni | Ritenute (047) |
| 2521 … 2524 | Imposta di bollo sulle fatture elettroniche, dal 1° (2521) al 4° trimestre (2524) | Bollo virtuale (060) |
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) | Liquidazione IVA |
| 6031, 6032, 6033 | IVA trimestrale del 1°, 2° e 3° trimestre | Liquidazione IVA |
| 6099, rateazione `0101` | saldo IVA del 4° trimestre dei trimestrali, versato con la dichiarazione annuale | Liquidazione IVA |
| 6013 | Acconto IVA mensili | Acconto IVA |
| 6035 | Acconto IVA trimestrali | Acconto IVA |
| 1040 | Ritenute su redditi di lavoro autonomo | Ritenute |
| 1038 | Ritenute su provvigioni | Ritenute |
| 1019 | Ritenute del 4% operate dal condominio | tabella dei codici |
| 1001 | Ritenute su retribuzioni e pensioni | tabella dei codici |
| 2521 … 2524 | Imposta di bollo sulle fatture elettroniche, dal 1° (2521) al 4° trimestre (2524) | Bollo virtuale |
![046 · Liquidazione IVA, F24, LIPE](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/046-liquidazione-iva.png)
*Mockup 046 — liquidazione periodica: registri del periodo con controlli, calcolo dell'IVA da versare, riquadro Versamento con codice tributo, scadenza e termine della LIPE.*
Il codice 6034 (4° trimestre dei trimestrali "speciali") non è usato: per i trimestrali ordinari il saldo del 4°
trimestre si versa con il 6099. Il file **Dati F24** è un CSV con separatore `;`: una riga di intestazione (scadenza,
codice fiscale e denominazione dell'azienda), poi una riga per codice della sezione Erario con rateazione o mese,
anno di riferimento, importo a debito, importo a credito e descrizione, e in fondo il saldo. Il tracciato telematico
degli intermediari non viene prodotto.
![047 · Ritenute, casse previdenza, prospetto F24](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/047-ritenute-parcelle-f24.png)
*Mockup 047 — ritenute operate su parcelle e provvigioni con cassa previdenziale ed ENASARCO; in basso il prospetto F24 con i codici 1040, 1038 e IVA.*
## Liquidazione e acconto IVA
| Regola | Valore in Khaemhat | Riferimento |
|---|---|---|
| Periodicità | mensile o trimestrale, dal profilo azienda | |
| Versamento minimo | se il dovuto (con gli interessi) è sotto **25,82 euro** non si versa e passa al periodo dopo | art. 1 c. 4 DPR 100/1998 |
| Interessi dei trimestrali | **1%** sul saldo a debito di ogni trimestre | |
| Pro rata | percentuale di detraibilità del profilo azienda, applicata all'IVA detraibile degli acquisti | art. 19-bis DPR 633/72 |
| Esigibilità differita e split payment | l'IVA resta fuori dal debito del periodo | |
| Acconto di dicembre | **88%** della base con i metodi storico e previsionale, tutto l'importo con il metodo effettivo (operazioni fino al 20 dicembre); non dovuto sotto **103,29 euro**; versamento entro il **27 dicembre** | L. 405/1990 |
## Comunicazione LIPE
La **comunicazione delle liquidazioni periodiche IVA** (art. 21-bis DL 78/2010) si prepara come file XML nel
tracciato **IVP18** dell'Agenzia delle Entrate: un file per trimestre, con un modulo per ogni mese (o uno per il
trimestre). Ogni modulo riporta totale delle operazioni attive e passive, IVA esigibile e detratta, IVA dovuta o a
credito, debito e credito del periodo precedente, interessi, acconto e importo da versare o a credito. Gli importi
hanno la virgola e due decimali. Il file si chiama `IT<codice fiscale>_LI_<anno>_T<trimestre>.xml`; va firmato e
inviato con i servizi dell'Agenzia o dall'intermediario.
| Trimestre | Scadenza della LIPE |
|---|---|
| 1° | 31 maggio |
| 2° | 16 settembre |
| 3° | 30 novembre |
| 4° | fine febbraio dell'anno dopo |
## Ritenute d'acconto e casse previdenziali
| Tipo | Aliquota | Su | Codice F24 | Tipo e causale nell'XML |
|---|---|---|---|---|
| Lavoro autonomo professionale | 20% | tutto il compenso | 1040 | RT01, causale A |
| Lavoro autonomo occasionale | 20% | tutto il compenso | 1040 | RT01, causale M |
| Provvigioni ad agenti e rappresentanti | 23% | 50% della provvigione | 1038 | RT01, causale R |
| Provvigioni ad agenti con dipendenti o terzi | 23% | 20% della provvigione | 1038 | RT01, causale R |
I tipi di ritenuta della fattura elettronica sono **RT01** (persone fisiche), **RT02** (persone giuridiche),
**RT03**-**RT06** (contributi INPS, ENASARCO, ENPAM, altri); le casse previdenziali vanno da **TC01** (avvocati) a
**TC22** (per esempio **TC04** ingegneri e architetti). La ritenuta operata diventa dovuta quando si **paga** la
fattura del professionista (criterio di cassa) e si versa entro il **16 del mese successivo** al pagamento. I dati
della **Certificazione Unica** (compenso lordo, somme non soggette, imponibile, ritenute per percipiente e causale)
si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermediario.
## Imposta di bollo
| Regola | Valore |
|---|---|
| Quando | fatture senza IVA (esenti, non imponibili, fuori campo) sopra **77,47 euro** |
| Importo | **2,00 euro** per fattura |
| Nature che contano | N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
| Versamento | per trimestre: 1° entro il **31 maggio** (2521), 2° entro il **30 settembre** (2522), 3° entro il **30 novembre** (2523), 4° entro **fine febbraio** dell'anno dopo (2524) |
| Importi bassi | se il bollo del 1° trimestre non supera **5.000 euro** si versa con il 2°; se 1° e 2° insieme non superano 5.000 euro, con il 3° (DM 4/12/2023) |
## Scadenze e regole principali
| Adempimento | Regola | Note in Khaemhat |
|---|---|---|
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione **blocca il periodo** |
| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale entro il 16 marzo | interessi calcolati in automatico |
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione segna il periodo come **liquidato** |
| Liquidazione IVA trimestrale | 1°-3° trimestre entro il 16 del secondo mese successivo al trimestre, con **interessi dell'1%**; il 4° trimestre entro il **16 marzo** con il codice 6099 | interessi calcolati in automatico |
| Scadenze in agosto e nei festivi | i versamenti fra il 1° e il 20 agosto slittano al **20 agosto**; una scadenza di sabato, domenica o festivo slitta al primo giorno lavorativo | festivi nazionali, Pasquetta e, dal 2026, il 4 ottobre |
| Versamento minimo | importo fino a **€ 25,82** non versato e riportato al periodo successivo | valore della specifica; da verificare in sviluppo rispetto alla norma vigente |
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **analitico** | scelta del metodo nella liquidazione di dicembre |
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio (o nella dichiarazione annuale) | XML LIPE generato dalla liquidazione |
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della parcella (1040/1038) | la ritenuta nasce al pagamento della fattura |
| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | contano le nature N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
| Bollo virtuale | versamento trimestrale: 1° trimestre entro 31 maggio, 2° entro 30 settembre, 3° entro 30 novembre, 4° entro fine febbraio; con importi bassi i primi trimestri possono slittare (soglia di € 5.000) | elenco da confrontare con quello proposto dall'Agenzia |
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nella dashboard |
| Versamento minimo IVA | importo sotto **25,82 euro** non versato e riportato al periodo successivo | *debito sotto la soglia* nella liquidazione |
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **effettivo**; non dovuto sotto 103,29 euro | riquadro *Acconto IVA* della liquidazione |
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio | file XML dalla liquidazione |
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della fattura (1040/1038) | la ritenuta diventa dovuta con **Fattura pagata** |
| Bollo virtuale | versamento trimestrale (vedi sopra), con la soglia dei 5.000 euro | elenco da confrontare con quello proposto dall'Agenzia |
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nelle autofatture |
| Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** |
| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali | calcolati nei solleciti |
![060 · Bollo virtuale trimestrale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/060-bollo-virtuale.png)
*Mockup 060 — imposta di bollo del trimestre: fatture con bollo, importo, codice tributo 2524 e scadenza; in fondo la regola dei € 77,47.*
| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali | con i solleciti dello scadenzario (M8) |
## Altri riferimenti usati dal programma
| Tema | Regola | Pagina |
|---|---|---|
| Split payment | IVA versata dalla PA cessionaria (esigibilità **S**) | [Vendite](Vendite) |
| 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 | [Fatturazione-elettronica](Fatturazione-elettronica) |
| Ritenuta e cassa previdenza | parcelle TD06: cassa (ad esempio 4%) e ritenuta d'acconto; ENASARCO per gli agenti | [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à da soglie, nomenclatura NC8 | [Intrastat](Intrastat) |
| Bilancio | schemi CEE art. 2424 (stato patrimoniale) e 2425 (conto economico), ordinario/abbreviato/micro | [Contabilita](Contabilita) |
| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo (M10) | [Fatturazione-elettronica](Fatturazione-elettronica) |
| 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) |
## Domande frequenti
@@ -233,7 +334,10 @@ SDI: è registrata nel programma e aggiornata con i rilasci.
**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.
**Khaemhat invia l'F24?** No: prepara i dati e la stampa; l'invio passa da intermediario o home banking.
**Posso usare un mio piano dei conti?** Sì: il modello *PMI standard* si modifica, si ampliano i sottoconti e si
disattivano quelli che non servono. L'import di un piano dei conti da file non c'è ancora.
**Khaemhat invia l'F24?** No: prepara i dati e il file; l'invio passa da home banking o intermediario.
## Pagine correlate
+46 -11
View File
@@ -1,6 +1,6 @@
# Guida all'uso
> **Stato:** completa per la versione 0.5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5)
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
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,18 +9,21 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c
## Che cosa c'è in questa versione
| Area | In 0.5.0 | Arriva con |
| Area | In 0.7.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 | giacenze: M6 |
| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail | magazzino M6, contabilità M7, partite M8, XML SDI M9 |
| Acquisti e magazzino | — | M6 |
| Contabilità, IVA, scadenzario | — | M7, M8 |
| 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 e scadenzario M8, 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 M8, 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 |
| Scadenzario | partite aperte dai documenti, visibili nei partitari | incassi, pagamenti, banche e solleciti M8 |
| Fatturazione elettronica | — | M9 |
| Import ed export | clienti, fornitori, articoli e prezzi da CSV, Excel e JSON; esportazione dai radar | giacenze iniziali M6, piano dei conti M7 |
| 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 |
Le voci di menu delle aree non ancora pronte aprono una pagina che dice che cosa conterranno.
@@ -121,22 +124,53 @@ La **stampante** della toolbar (`Ctrl+P`) apre l'anteprima: **Stampa** con la st
Dal menu **⋯** del documento, **Invia per e-mail** propone destinatario, oggetto e testo; il PDF parte in allegato e
l'esito finisce nel log. Vedi [Vendite](Vendite#invio-per-e-mail).
## 8. Allegati
## 8. Comprare
![Fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png)
Il ciclo passivo usa le stesse maschere delle vendite. In **Acquisti → Ordini fornitori** prepari l'ordine (il prezzo
è quello del fornitore nella scheda articolo); quando arriva la merce **Crea DDT fornitore (carico)** registra il
ricevimento, anche in più volte, e alla conferma carica il magazzino. **Crea Fattura fornitore** prepara la fattura:
alla conferma prende il **protocollo** IVA. Se il prezzo fatturato è diverso da quello dell'ordine o del ricevimento,
un avviso sopra le righe lo segnala.
![Import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png)
Le fatture elettroniche ricevute si caricano da **Acquisti → Importa fatture**: XML, P7M o ZIP, anche molti file
insieme. Khaemhat trova o crea il fornitore, abbina gli articoli, scarta i doppioni e registra le fatture in bozza con
il file allegato. Per le fatture di fornitori esteri o in inversione contabile indica quale **autofattura** serve ed
entro quando; **Acquisti → Autofatture** le elenca tutte. Vedi [Acquisti](Acquisti).
## 9. Il magazzino
![Giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png)
**Magazzino → Giacenze** mostra per ogni articolo giacenza, impegnato, ordinato, disponibile, costo medio e valore,
con lo stato rispetto a scorta minima e punto di riordino; apri una riga per vedere i movimenti. I documenti
confermati muovono il magazzino da soli: non serve registrare a parte carichi e scarichi.
![Proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png)
**Proposte di riordino** calcola che cosa ordinare e a quale fornitore e crea gli ordini in bozza, uno per fornitore.
**Inventario** guida il conteggio fisico (anche dal file del lettore di codici a barre) e registra le rettifiche;
**Valorizzazione** calcola il valore del magazzino a una data con le classi ABC. Vedi [Magazzino](Magazzino).
## 10. Allegati
![Pannello allegati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-pannello.png)
Ogni anagrafica e ogni documento ha la scheda **Allegati**: carichi file dal computer, li vedi in anteprima, scarichi tutto in un archivio ZIP. I PDF che Khaemhat genera sono **versionati**: ogni stampa salvata o
e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e file](Allegati-e-file).
## 9. Importare ed esportare
## 11. Importare ed esportare
![Mappatura delle colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png)
**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli e prezzi di listino da un file
**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli, prezzi di listino e giacenze iniziali da un file
CSV, Excel o JSON: scegli il file, abbini le colonne, guarda l'anteprima con gli errori riga per riga e conferma. Ogni radar
esporta le righe visibili. Vedi [Import/Export](Import-Export).
## 10. Personalizzare
## 12. Personalizzare
![Il mio profilo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/preferenze-profilo.png)
@@ -157,4 +191,5 @@ prezzi) sono in **Tabelle azienda → Preferenze**. Vedi [Preferenze utente](Pre
[Primi passi](Primi-passi) · [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) · [Anagrafiche](Anagrafiche) ·
[Articoli e listini](Articoli-e-listini) · [Tabelle azienda](Tabelle-azienda) · [Vendite](Vendite) ·
[Acquisti](Acquisti) · [Magazzino](Magazzino) · [Contabilità](Contabilita) · [IVA](IVA) ·
[Allegati e file](Allegati-e-file) · [Import/Export](Import-Export) · [Preferenze utente](Preferenze-utente)
+1 -1
View File
@@ -1,6 +1,6 @@
# Khaemhat
> **Stato:** completa per 0.5.0 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5; sviluppo in corso)
> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7; sviluppo in corso)
![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png)
+230 -142
View File
@@ -1,199 +1,287 @@
# IVA
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M7; dichiarazioni d'intento in M10)
> **Modulo di licenza:** ACCT (bollo virtuale e dichiarazioni d'intento anche con EINV) · **Permessi principali:** `vat.settlement.confirm`, `vat.register.print`, `vat.withholding.write`, `vat.intent.write` · **Specifica:** SPEC §11.7, §11.9, §11.3, §14
> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7)
> **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
## A cosa serve
Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabilità**:
Questa pagina descrive tutto ciò che riguarda l'IVA e i versamenti collegati:
- **registri IVA** con protocollo, stampa di prova e stampa definitiva;
- **liquidazione periodica** mensile o trimestrale, con credito e debito riportati, pro rata, interessi trimestrali e
minimo di versamento; **acconto di dicembre**; file della **comunicazione LIPE** e dati del modello **F24**;
- **ritenute d'acconto** operate e subite, **prospetto F24** con il suo pagamento e dati per la **Certificazione
Unica**;
- **imposta di bollo virtuale** sulle fatture elettroniche, per trimestre.
- **registri IVA** con protocollo e stampe definitive;
- **liquidazione periodica** con esigibilità differita, IVA per cassa, pro-rata, acconto di dicembre, interessi,
minimo di versamento, **dati F24** e **LIPE**;
- **ritenute d'acconto** e **casse previdenziali**, con prospetto F24 e dati per la **CU**;
- **imposta di bollo virtuale** sulle fatture elettroniche;
- **dichiarazioni d'intento** ricevute ed emesse, con plafond.
> **Khaemhat non trasmette nulla.** Prepara i file della LIPE, i dati dell'F24 e i dati della Certificazione Unica;
> l'invio telematico si fa con i servizi dell'Agenzia delle Entrate, con l'home banking o tramite l'intermediario.
Khaemhat **non trasmette** F24, LIPE e CU: prepara i dati, i file e le stampe; l'invio telematico avviene tramite
intermediario o home banking (avviso presente nel mockup 046).
> **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. Arrivano più avanti: i **pagamenti delle fatture** dallo scadenzario, che oggi
> per le ritenute si registrano a mano (M8), 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
> telematico** di F24, LIPE e CU.
## Dove si trova
- **Contabilità → Registri IVA**, **Contabilità → Liquidazione IVA**, **Contabilità → Ritenute**.
- **Fatturazione elettronica → Bollo virtuale**, **→ Dichiarazioni d'intento**, **→ LIPE**.
Menu **Contabilità** → *Registri IVA*, *Liquidazione IVA*, *Ritenute e F24*, *Bollo virtuale*. La **periodicità**
IVA (mensile o trimestrale) e la **percentuale di pro rata** si impostano nel **profilo azienda** (vedi
[Tabelle azienda](Tabelle-azienda)). Le registrazioni che queste pagine scrivono sono in **Prima nota** (vedi
[Contabilità](Contabilita)).
## Schermate
![045 · Registri IVA](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/045-registri-iva.png)
*Mockup 045 — registro Vendite 1 del mese con protocolli, imponibile, aliquota o natura, imposta ed esigibilità; in alto l'ultima stampa definitiva (anteprima ridotta)*
![046 · Liquidazione IVA](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/046-liquidazione-iva.png)
*Mockup 046 — liquidazione mensile provvisoria: parametri, registri del periodo con i controlli superati, calcolo dell'IVA da versare e riquadro del versamento (codice tributo, scadenza, export F24, scadenza LIPE)*
![047 · Ritenute e F24](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/047-ritenute-parcelle-f24.png)
*Mockup 047 — ritenute operate e subite con cassa previdenziale, periodo e stato del versamento; sotto, il prospetto F24 del 16 del mese con i tributi 1040, 1038 e 6009*
![060 · Bollo virtuale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/060-bollo-virtuale.png)
*Mockup 060 — fatture del trimestre soggette a bollo con natura, importo esente e addebito; riquadri con importo, codice tributo, scadenza e trimestre precedente*
![061 · Dichiarazioni d'intento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/061-dichiarazioni-intento.png)
*Mockup 061 — dichiarazioni d'intento ricevute con protocollo AdE, plafond, utilizzato, residuo e stato (attiva, avviso al 97 %, esaurita)*
```
Documenti confermati ──► Registri IVA ──Calcola──► Liquidazione ──Conferma──► registrazione LIQ + riga F24
Fattura del professionista ──Fattura pagata──► Ritenuta da versare ──► riga F24 (1040)
Fatture con bollo del trimestre ──Metti in F24──► riga F24 (2521-2524)
Righe F24 della scadenza ──► Prospetto F24 ──Registra pagamento──► registrazione F24
```
## Registri IVA
Registri previsti: **vendite**, **acquisti**, **corrispettivi**, **vendite reverse charge**, **acquisti reverse
charge** e i **sezionali** che servono (es. `VEN1`, `ACQ1`, `VEN-RC`, `ACQ-RC`, `ACQ-SP` per lo split payment,
`CORR`). Ogni documento registrato riceve un **protocollo** progressivo nel suo registro.
![Khaemhat 0.7.0 · registro IVA delle fatture emesse](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-registri-iva.png)
*Il registro VEN1 di ottobre: una scheda per registro, la striscia con tipo, imponibile, imposta, ultima stampa
definitiva e ultima pagina, le righe con protocollo e il riepilogo per aliquota.*
La griglia mostra protocollo, data di registrazione, documento, data del documento, controparte, P.IVA o codice
fiscale, imponibile, aliquota o natura, imposta, totale ed **esigibilità** (`I` immediata, `D` differita, `S`
scissione dei pagamenti).
**Contabilità → Registri IVA** ha una scheda per registro:
**Stampe**
| Stampa | Effetto |
| Registro | Contenuto |
|---|---|
| **Provvisoria** | in qualunque momento, senza effetti |
| **Stampa definitiva** del periodo | pagine numerate, totali per aliquota e natura; aggiorna "ultima stampa definitiva" |
| **Riepilogo aliquote** | totali del periodo per codice IVA e natura |
| **VEN1** Registro fatture emesse | fatture, note di debito, parcelle e note di credito di vendita |
| **VEN-RC** Registro fatture emesse - autofatture e integrazioni | il lato *vendite* delle autofatture e integrazioni (TD16-TD29) |
| **ACQ1** Registro fatture acquisti | fatture e note di credito dei fornitori |
| **ACQ-RC** Registro fatture acquisti - autofatture e integrazioni | il lato *acquisti* delle stesse autofatture |
| **CORR** Registro dei corrispettivi | le registrazioni dei corrispettivi (causale `CORR`) |
Le autofatture reverse charge (TD16-TD19) sono annotate sia nel registro vendite RC sia nel registro acquisti RC,
Scegli il periodo con **Dal** e **Al**. Ogni riga mostra **protocollo** (il link apre la registrazione), **data di
registrazione IVA**, documento e data, cliente o fornitore, **aliquota** o natura, **imponibile**, **imposta**,
**indetraibile** ed **esigibilità** (*Immediata*, *Differita*, *Scissione dei pagamenti*). Sotto, il **riepilogo per
aliquota** e il totale del registro.
Le autofatture e integrazioni compaiono in **VEN-RC** e in **ACQ-RC** con la stessa imposta: a debito e a credito,
con effetto neutro sulla liquidazione.
## Liquidazione IVA periodica
### Stampe
| Stampa | Effetto | Permesso |
|---|---|---|
| **Stampa di prova** | PDF del registro nel periodo scelto, in qualunque momento, senza effetti | `vat.register.read` |
| **Stampa definitiva** | PDF dal giorno dopo l'ultima stampa definitiva fino al giorno scelto, con le pagine numerate di seguito all'ultima pagina dell'anno | `vat.settlement.confirm` |
La stampa definitiva non si annulla: la striscia mostra la data dell'**ultima stampa definitiva** e l'**ultima
pagina**, e la stampa successiva riparte da lì (la prima dell'anno parte dal 1° gennaio e dalla pagina 1). La stampa
definitiva **non blocca** le registrazioni: a bloccare il periodo è la conferma della liquidazione (vedi sotto).
## Liquidazione IVA
![Khaemhat 0.7.0 · liquidazione IVA di ottobre confermata](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-liquidazione-iva.png)
*La liquidazione mensile di ottobre 2026 confermata: registri del periodo, calcolo con il credito di settembre,
riquadro del versamento (codice 6010, scadenza 16/11/2026, trimestre LIPE) e l'elenco delle liquidazioni dell'anno.*
### Come si fa
1. **Contabilità → Liquidazione IVA**. Controlla i parametri: **Periodicità** (mensile o trimestrale, dal profilo
azienda), **Periodo**, **Data liquidazione**, **Credito precedente**, **Pro-rata**.
2. Premi **Calcola**. Khaemhat esegue i **controlli preliminari** (mostrati con il segno di spunta sopra i registri):
numerazione continua, nessuna bozza, date coerenti, periodo precedente confermato.
3. Controlla la tabella **Registri del periodo** (documenti, imponibile, IVA, indetraibile, note come *neutra* per il
reverse charge) e il riquadro **Calcolo**.
4. Premi **Conferma**: la liquidazione diventa definitiva e il **periodo viene bloccato** (vedi
[Contabilità](Contabilita), esercizi e periodi). Serve il permesso `vat.settlement.confirm`.
5. Premi **Dati F24** per esportare i dati del versamento e **LIPE XML** per il file della comunicazione.
1. **Contabilità → Liquidazione IVA**. La **periodicità** viene dal profilo azienda; scegli **Anno** e **Periodo**
(mese o trimestre).
2. Premi **Calcola** (serve `vat.settlement.read`). Khaemhat legge i registri del periodo e mostra la tabella
**Registri del periodo** (documenti, imponibile, imposta, indetraibile, esigibilità differita), il riquadro
**Calcolo** e il riquadro **Versamento** con codice tributo, anno, importo, scadenza e trimestre LIPE. Puoi
ricalcolare quante volte vuoi finché la liquidazione non è confermata.
3. Premi **Conferma liquidazione** (serve `vat.settlement.confirm`). Le liquidazioni si confermano in ordine: se un
periodo precedente è calcolato ma non confermato, va confermato prima. Alla conferma Khaemhat:
- scrive in prima nota la registrazione **LIQ**: *IVA su vendite* in Dare, *IVA su acquisti* in Avere, gli
interessi trimestrali in Dare, l'eventuale IVA resa indetraibile dal pro rata a costo, e la differenza su
*Erario c/liquidazione IVA*;
- segna i periodi dell'esercizio come **liquidati**;
- se c'è da versare, aggiunge la riga del modello **F24** con codice tributo e scadenza (vedi
[Prospetto F24](#prospetto-f24-e-pagamento)).
4. **Dati F24** scarica i dati del modello F24 della scadenza; **Comunicazione LIPE** scarica il file del trimestre
(vedi [sotto](#comunicazione-lipe)).
**Riapri** annulla la conferma: la registrazione LIQ viene eliminata (o stornata, se è già definitiva), la riga F24
viene tolta e i periodi tornano aperti. Non si riapre se l'F24 della liquidazione è già **pagato** (annulla prima il
pagamento) né se una liquidazione **successiva** è confermata (riapri prima quella).
**Periodi liquidati.** Dopo la conferma, documenti e registrazioni **con IVA** datati nei periodi liquidati sono
rifiutati: per correggere bisogna riaprire la liquidazione. Le registrazioni senza IVA restano libere.
### Le voci del calcolo
| Voce | Regola |
| Voce | Regola in Khaemhat |
|---|---|
| IVA a debito | dai registri vendite e corrispettivi del periodo (esigibilità immediata) |
| IVA a credito | dai registri acquisti, al netto dell'**indetraibile** e del **pro-rata** |
| Esigibilità differita | l'IVA delle fatture a esigibilità differita entra quando si incassa (o alla scadenza di legge) |
| IVA per cassa | con il regime dell'IVA per cassa attivo nel profilo azienda, debito e credito seguono incassi e pagamenti; il regime completo è previsto in fase 2 ([Roadmap](Roadmap)) |
| Credito del periodo precedente | riportato automaticamente |
| Acconto versato | sottratto nella liquidazione di dicembre (o del 4° trimestre) |
| Interessi 1 % | maggiorazione dell'1 % per i contribuenti **trimestrali** |
| Minimo di versamento | se l'IVA dovuta non supera **€ 25,82** non si versa e si **riporta** al periodo successivo |
| **IVA a debito sulle vendite** | imposta dei registri vendite e corrispettivi del periodo, tolta quella a esigibilità differita e in scissione dei pagamenti |
| **IVA a credito sugli acquisti** | imposta dei registri acquisti, tolta la parte **indetraibile** dei codici IVA, poi ridotta dal **pro rata** del profilo azienda |
| **IVA indetraibile** | indetraibile per codice IVA più la parte tolta dal pro rata |
| **IVA a esigibilità differita** | mostrata a parte: non entra nel debito del periodo |
| **Credito / debito periodo precedente** | riportati dalla liquidazione confermata precedente |
| **Acconto versato** | l'acconto di dicembre registrato, tolto nell'ultima liquidazione dell'anno (dicembre o 4° trimestre) |
| **Interessi trimestrali 1%** | per i contribuenti trimestrali, sul saldo a debito |
| **Da versare** | se il totale (con gli interessi) è sotto **25,82 euro** non si versa: diventa *debito sotto la soglia* e passa al periodo dopo; se il saldo è a credito diventa *credito da riportare* |
### Acconto di dicembre
### Codici tributo e scadenze
L'acconto si calcola con uno dei tre metodi: **storico**, **previsionale**, **analitico**. Khaemhat propone gli
importi di tutti e tre e l'utente sceglie. Percentuali e scadenza seguono le regole in vigore (al momento della
stesura: 88 % per storico e previsionale, liquidazione al 20 dicembre per l'analitico, versamento entro il 27
dicembre) e sono aggiornate con il pacchetto fiscale. Codici tributo: **6013** (mensili) e **6035** (trimestrali).
| Periodo | Codice | Scadenza |
|---|---|---|
| Mese (gennaio-dicembre) | **6001**-**6012** | 16 del mese dopo |
| 1°, 2°, 3° trimestre | **6031**, **6032**, **6033** | 16 del secondo mese dopo il trimestre (16/5, 20/8, 16/11) |
| 4° trimestre | **6099**, rateazione **0101** | 16 marzo dell'anno dopo, con il saldo annuale |
### Codici tributo F24
Le scadenze di sabato, domenica o festivo passano al primo giorno lavorativo; i versamenti dal 1° al 20 agosto
passano al **20 agosto**. Codici e calendario sono in [Fiscalità italiana](Fiscalita-italiana#codici-tributo-f24).
| Codice | Versamento |
### Acconto IVA di dicembre
Il riquadro **Acconto IVA** (sotto l'elenco delle liquidazioni, con `vat.settlement.confirm`) calcola l'acconto da
versare entro il **27 dicembre** (primo giorno lavorativo successivo se festivo) con il codice **6013** (mensili) o
**6035** (trimestrali).
| Metodo | Base di calcolo | Acconto |
|---|---|---|
| **Storico** | l'IVA dell'ultimo periodo dell'anno prima (dicembre o 4° trimestre), al lordo dell'acconto di allora e senza interessi | 88% della base |
| **Previsionale** | l'IVA che prevedi per l'ultimo periodo dell'anno: la scrivi tu | 88% della base |
| **Effettivo** | l'IVA dall'inizio dell'ultimo periodo al **20 dicembre** | tutta la base |
1. Scegli il **metodo**: la **base di calcolo** si compila con il valore che Khaemhat conosce (il riquadro *Basi di
calcolo* mostra storico ed effettivo; **Ricalcola le basi** le rilegge). Per il previsionale scrivila tu.
2. **Registra acconto** aggiunge la riga F24 dell'acconto. Sotto **103,29 euro** l'acconto non è dovuto e non viene
registrato. Finché non è pagato puoi registrarlo di nuovo con un altro metodo: la riga si aggiorna.
L'acconto registrato viene tolto nella liquidazione di dicembre o del 4° trimestre.
### Comunicazione LIPE
**Comunicazione LIPE** scarica il file XML della **comunicazione delle liquidazioni periodiche IVA** di un trimestre,
nel tracciato **IVP18** dell'Agenzia delle Entrate: un modulo per ogni mese (o per il trimestre), con operazioni
attive e passive, IVA esigibile e detratta, debiti e crediti riportati, interessi, acconto e importo da versare o a
credito. Il pulsante si accende quando è confermata la liquidazione dell'ultimo mese del trimestre (o del trimestre).
Il file si chiama `IT<codice fiscale>_LI_<anno>_T<trimestre>.xml` e va firmato e inviato con i servizi dell'Agenzia
o dall'intermediario. Le scadenze sono in [Fiscalità italiana](Fiscalita-italiana#comunicazione-lipe).
## Ritenute d'acconto
![Khaemhat 0.7.0 · ritenute operate e prospetto F24](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-ritenute.png)
*La ritenuta operata sulla fattura dello Studio Rag. Neri Paola (RT01, causale A, cassa TC04, 20% di 450 euro) già
pagata e da versare; sotto, il prospetto F24 della scadenza del 16/11/2026 con l'IVA di ottobre.*
**Contabilità → Ritenute e F24** elenca le ritenute dei documenti di un **anno**, nelle schede **Operate**, **Subite**
e **Tutte**:
- **operate**: quelle che l'azienda trattiene sulle **fatture dei professionisti** e degli agenti (fatture fornitore
con ritenuta);
- **subite**: quelle che i clienti trattengono sulle **parcelle** e fatture emesse dall'azienda con ritenuta.
Le ritenute nascono da sole quando il documento viene contabilizzato. Per ognuna: documento (il link apre la
registrazione), data, cliente o fornitore, **tipo** e causale di pagamento (per esempio `RT01 · A`), imponibile,
**cassa** previdenziale e contributo, **aliquota** (con la quota dell'imponibile, per esempio *20% su 50%* per gli
agenti), importo, data di pagamento della fattura e **stato**:
| Stato | Significato |
|---|---|
| 6001 … 6012 | IVA mensile, da gennaio (6001) a dicembre (6012) |
| 6031 … 6034 | IVA trimestrale, dal 1° (6031) al 4° trimestre (6034); il 6034 riguarda i trimestrali "speciali", per gli altri il saldo del 4° trimestre si versa con la dichiarazione annuale (6099) |
| 6013 / 6035 | acconto IVA mensili / trimestrali |
| 6099 | IVA da dichiarazione annuale |
| 1040 | ritenute su redditi di lavoro autonomo |
| 1038 | ritenute su provvigioni (agenti e rappresentanti) |
| *In attesa del pagamento* | ritenuta operata su una fattura non ancora pagata |
| *Da versare* | la fattura è pagata: la ritenuta va versata con l'F24 |
| *Versata* | l'F24 che la contiene è pagato |
| *Subita* | ritenuta trattenuta dal cliente su una fattura dell'azienda |
I codici sono caricati con i dati di base ([Dati di base e di esempio](Dati-di-base-e-esempio)) e riepilogati in
[Fiscalità italiana](Fiscalita-italiana).
### Registrare il pagamento della fattura
### LIPE
La ritenuta operata diventa dovuta **quando paghi la fattura** del professionista (criterio di cassa). Finché i
pagamenti non arrivano con lo [Scadenzario](Scadenzario) (M8), si registra a mano:
La **Comunicazione delle liquidazioni periodiche IVA** si genera come file XML nel tracciato dell'Agenzia delle
Entrate dalle liquidazioni confermate del trimestre (voce di menu **Fatturazione elettronica → LIPE** o pulsante
**LIPE XML**). Il riquadro **Versamento** mostra il trimestre di riferimento e la scadenza.
1. Sulla riga della ritenuta premi **Fattura pagata** e indica la data di pagamento.
2. Khaemhat scrive la registrazione **RIT** (*fornitore* in Dare, *Erario c/ritenute lavoro autonomo* in Avere) e
aggiunge la ritenuta alla riga F24 del suo codice tributo (**1040** lavoro autonomo, **1038** provvigioni) e del
mese di pagamento, con scadenza il **16 del mese dopo**. Le ritenute dello stesso codice e mese si sommano.
3. Per una ritenuta **subita**, **Fattura pagata** chiede la data in cui il cliente ha pagato e scrive la registrazione
**RITS** (*Erario c/ritenute subite* in Dare, *cliente* in Avere): è un credito d'imposta.
## Ritenute d'acconto e casse previdenziali
Il pulsante con la freccia annulla il pagamento della fattura (e la sua registrazione) finché l'F24 non è pagato.
**Contabilità → Ritenute** (mockup 047) elenca le ritenute **operate** (sulle parcelle e provvigioni che paghiamo) e
quelle **subite** (sulle nostre fatture, ad esempio verso la PA), con i filtri **Operate / Subite / Tutte**.
### Dati per la Certificazione Unica
| Colonna | Significato |
|---|---|
| Tipo | professionista TD06, agente ENASARCO, ritenuta subita… |
| Imponibile, Cassa, Importo cassa | contributo previdenziale (es. 4 % INPS di rivalsa, 4 % cassa professionale) |
| Ritenuta | aliquota (es. 20 %; per gli agenti l'aliquota si applica a una quota della provvigione) |
| Periodo → F24 | mese di pagamento della fattura e data del modello F24 in cui confluisce |
| Stato | *Da versare*, *In F24*, *Versata*, *Subita* |
**Dati Certificazione Unica** scarica un file CSV con i **percipienti** dell'anno: una riga per professionista e
causale con codice fiscale, denominazione, causale, anno, compenso lordo, somme non soggette, imponibile, ritenute,
codice tributo e documenti. Contiene le ritenute operate sulle fatture pagate nell'anno. La CU si compila e si invia
con i servizi dell'Agenzia delle Entrate o dall'intermediario.
Regole:
## Prospetto F24 e pagamento
- La ritenuta nasce come **debito verso l'Erario al pagamento** della fattura (criterio di cassa) e confluisce nel
prospetto F24 del mese successivo (tributi **1040** e **1038**).
- Sulle **parcelle (TD06)** cassa previdenziale, ritenuta e netto a pagare sono calcolati in automatico; **ENASARCO**
si applica agli agenti con i relativi massimali.
- **Registra versamento** registra il pagamento del modello F24 e chiude le ritenute versate.
- **CU export** produce i dati della Certificazione Unica da consegnare all'intermediario.
Il riquadro **Prospetto F24** (nella pagina *Ritenute e F24*) raccoglie tutto ciò che va versato con l'F24: IVA della
liquidazione, acconto IVA, ritenute operate, bollo virtuale.
Il **Prospetto F24** del giorno di scadenza riepiloga tributi, periodi e importi (ritenute e IVA) con il totale.
1. Scegli la **scadenza** nell'elenco (si apre sulla prima non pagata).
2. Il prospetto mostra una riga per **codice tributo** e periodo con descrizione, periodo di riferimento, importo a
debito e a credito, e il **saldo** dell'F24.
3. **Dati F24** scarica un file CSV (separatore `;`, sezione Erario) con intestazione, una riga per codice tributo e il
saldo, da passare all'home banking o all'intermediario.
4. Pagato l'F24, **Registra pagamento** chiede la data: Khaemhat scrive la registrazione **F24** (*Erario
c/liquidazione IVA*, *Erario c/ritenute* e *imposta di bollo* in Dare secondo le righe, la **banca** in Avere) e
segna versate le righe e le ritenute. La banca è quella predefinita dell'azienda (il suo *conto contabile*), o
`07.01.001` *Banca c/c*.
**Annulla pagamento** toglie la registrazione del pagamento (o la storna, se è definitiva) e riporta le righe da
versare.
## Imposta di bollo virtuale
Sulle fatture con operazioni **esenti, non imponibili o fuori campo IVA** di importo **superiore a € 77,47** si
applica il bollo di **€ 2,00**, calcolato in automatico sul documento e indicato nell'XML (`DatiBollo`).
Sulle fatture elettroniche **senza IVA** (operazioni esenti, non imponibili o fuori campo) di importo **superiore a
77,47 euro** si applica il bollo di **2 euro**. Khaemhat lo calcola già sul documento di vendita (vedi
[Vendite](Vendite)), che dice anche se è **addebitato al cliente** o **a carico dell'azienda**.
**Fatturazione elettronica → Bollo virtuale** (mockup 060) mostra le fatture del trimestre con il bollo, la natura
IVA, l'importo esente e l'**addebito** (*addebitato al cliente*, *a carico azienda*; per le fatture ricevute *a
carico fornitore*). I riquadri riportano numero di fatture, importo, codice tributo del trimestre (**2521-2524**),
scadenza e stato del trimestre precedente.
**Contabilità → Bollo virtuale** riepiloga il bollo per **anno** e **trimestre**:
1. A fine trimestre controlla l'elenco e confrontalo con quello messo a disposizione dall'Agenzia delle Entrate.
2. **Esporta per F24** produce i dati del versamento.
3. A pagamento avvenuto premi **Segna versato**.
- la striscia del trimestre: numero di **fatture**, **importo**, **codice tributo**, **scadenza** e lo stato del
**trimestre precedente**;
- l'elenco delle fatture del trimestre con il bollo: documento (il link lo apre), data, cliente, imponibile, bollo e
**addebito**;
- il riepilogo dei quattro trimestri dell'anno con fatture, importo, scadenza e stato (*Da mettere in F24*, *In F24*,
*pagato il*).
> **Attenzione:** alcune operazioni non imponibili sono escluse dal bollo per legge (per esempio le cessioni
> intracomunitarie e le esportazioni). L'esclusione sarà gestita sul codice IVA; la regola precisa sarà verificata in
> sviluppo con la normativa vigente.
| Trimestre | Codice | Scadenza |
|---|---|---|
| 1° | **2521** | 31 maggio |
| 2° | **2522** | 30 settembre |
| 3° | **2523** | 30 novembre |
| 4° | **2524** | fine febbraio dell'anno dopo |
## Dichiarazioni d'intento e plafond
Se il bollo del **1° trimestre** non supera **5.000 euro** si versa con il 2° (30 settembre); se quello del 1° e del
2° insieme non supera 5.000 euro si versa con il 3° (30 novembre). Le scadenze festive passano al primo giorno
lavorativo.
**Fatturazione elettronica → Dichiarazioni d'intento** (mockup 061) gestisce:
- **Ricevute**: dichiarazioni degli esportatori abituali nostri clienti (numero, data, cliente, **protocollo AdE**,
plafond, utilizzato, residuo, anno, stato);
- **Emesse (plafond nostro)**: dichiarazioni che l'azienda presenta ai propri fornitori.
Regole:
- Il plafond si aggiorna a ogni fattura con codice IVA **N3.5** (non imponibile a seguito di dichiarazione d'intento).
- Al **90 %** di utilizzo compare un avviso (e la regola di automazione predefinita *Avviso plafond* avvisa
l'amministrazione, vedi [Automazioni](Automazioni)); al **100 %** la fattura è bloccata.
- Il protocollo della dichiarazione è riportato nell'XML della fattura (blocco `AltriDatiGestionali`).
- **Registro cronologico** stampa il registro delle dichiarazioni.
La dichiarazione è collegata alla scheda fiscale del cliente ([Anagrafiche](Anagrafiche)).
1. Scegli il trimestre e confronta l'elenco con quello che l'Agenzia delle Entrate mette a disposizione nell'area
riservata.
2. **Metti in F24** (serve `vat.settlement.confirm`) aggiunge la riga del bollo al prospetto F24 della scadenza. Se
il bollo del trimestre cambia (una fattura in più), premilo di nuovo: finché non è pagata la riga si aggiorna.
3. **Dati F24** scarica i dati dell'F24 di quella scadenza; il pagamento si registra dal
[Prospetto F24](#prospetto-f24-e-pagamento).
## Permessi e licenza
- Registri, liquidazione, F24, LIPE, ritenute: modulo **ACCT**.
- Bollo virtuale e dichiarazioni d'intento: compaiono nel menu Fatturazione elettronica e la specifica li elenca sia
in ACCT sia in EINV; l'abbinamento definitivo sarà fissato in sviluppo.
- `vat.settlement.confirm` è richiesto per confermare la liquidazione; gli altri codici in testa sono indicativi
(convenzione `modulo.entità.azione`, SPEC §7.2).
Tutto è nel modulo **ACCT**.
| Permesso | Cosa consente |
|---|---|
| `vat.register.read` | vedere i registri IVA e farne la stampa di prova |
| `vat.settlement.read` | calcolare e vedere le liquidazioni, ritenute, bollo, prospetto F24; scaricare LIPE, dati F24 e CU |
| `vat.settlement.confirm` | confermare e riaprire le liquidazioni, registrare acconto, pagamenti delle fatture, pagamenti F24, bollo in F24, stampa definitiva dei registri |
## Domande frequenti
**Ho trovato un errore in un periodo già liquidato.** Il periodo è bloccato: un utente con il permesso di
riapertura sblocca il periodo, si corregge, si ricalcola e si conferma di nuovo. Se l'F24 è già stato versato, la
differenza va gestita nella liquidazione successiva o con ravvedimento (fuori da Khaemhat).
**Khaemhat invia l'F24?** No. Prepara dati e stampe; l'invio è dell'intermediario o dell'home banking.
**Dove imposto la periodicità IVA e il pro-rata?** Nel profilo azienda ([Tabelle azienda](Tabelle-azienda)).
- **"Conferma prima la liquidazione del periodo precedente".** Un mese (o trimestre) precedente è calcolato ma non
confermato: confermalo prima. Il credito e il debito si riportano solo da una liquidazione confermata.
- **Ho trovato un errore in un periodo già liquidato.** Riapri la liquidazione (e prima quelle successive, se
confermate), correggi il documento, ricalcola e conferma di nuovo. Se l'F24 è già pagato, annulla prima il
pagamento; se l'hai davvero versato, la differenza va gestita nella liquidazione successiva o con il ravvedimento,
fuori da Khaemhat.
- **Il pulsante Comunicazione LIPE è spento.** Il trimestre non è finito o la liquidazione del suo ultimo mese non è
confermata.
- **La ritenuta non compare nel prospetto F24.** È *In attesa del pagamento*: registra **Fattura pagata**. La ritenuta
va nella scadenza del 16 del mese dopo il pagamento.
- **La stampa definitiva del registro è rifiutata.** Deve partire dal giorno dopo l'ultima stampa definitiva: la
striscia del registro mostra quale.
- **Khaemhat invia F24, LIPE o CU?** No: prepara i dati e i file; l'invio è dell'home banking, dei servizi
dell'Agenzia delle Entrate o dell'intermediario.
- **Dove imposto periodicità e pro rata?** Nel profilo azienda, in [Tabelle azienda](Tabelle-azienda).
## Pagine correlate
[Contabilità](Contabilita) · [Fatturazione elettronica](Fatturazione-elettronica) · [Vendite](Vendite) ·
[Acquisti](Acquisti) · [Intrastat](Intrastat) · [Scadenzario](Scadenzario) · [Fiscalità italiana](Fiscalita-italiana) ·
[Automazioni](Automazioni) · [Report](Report)
[Contabilità](Contabilita) · [Fiscalità italiana](Fiscalita-italiana) · [Vendite](Vendite) · [Acquisti](Acquisti) ·
[Scadenzario](Scadenzario) · [Fatturazione elettronica](Fatturazione-elettronica) · [Tabelle azienda](Tabelle-azienda) ·
[Glossario](Glossario)
+18 -12
View File
@@ -1,6 +1,6 @@
# Import/Export
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (scrittura di giacenze iniziali in M6, piano dei conti in M7; saldi e partite di apertura in M7 e M9)
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (giacenze iniziali dalla 0.6.0, piano dei conti dalla 0.7.0; saldi e partite di apertura più avanti)
> **Modulo di licenza:** CORE (piano dei conti: ACCT) · **Livello richiesto:** amministratore, oppure permesso di scrittura o di export dell'entità · **Specifica:** SPEC §11.7, §12.12 · **Decisione:** ADR 0031
## A cosa serve
@@ -94,13 +94,16 @@ obbligatoria. Unità alternative, codici alternativi, fornitori e sostitutivi re
netto), non entrambi. Stesso articolo, listino o cliente e data: il prezzo si sostituisce; una data nuova aggiunge
un prezzo che vale da quel giorno, come nella griglia dei listini. Le righe senza errori si scrivono tutte insieme.
### Giacenze iniziali (solo verifica fino a M6)
### Giacenze iniziali
`articolo`\*, `deposito` (vuoto: il deposito dell'articolo), `quantita`\* (maggiore di zero), `costo_unitario`.
L'articolo deve essere merce gestita a magazzino. Il controllo serve a preparare il file: la scrittura del movimento
di apertura arriva con il [Magazzino](Magazzino).
`articolo`\*, `deposito` (vuoto: il deposito dell'articolo, poi quello predefinito), `quantita`\* (maggiore di zero),
`costo_unitario` (vuoto: costo medio, standard o ultimo costo dell'articolo). L'articolo deve essere merce gestita a
magazzino e non può comparire due volte nello stesso deposito. Dalla 0.6.0 l'import scrive **un movimento di
magazzino per deposito** con la causale `APE` (esistenza iniziale) alla data dell'import e lo conferma: giacenze e
costo medio partono da lì (vedi [Magazzino](Magazzino#esistenze-iniziali)). Se la causale `APE` manca, le righe sono
saltate con un messaggio: aggiungila con *Aggiorna da tabelle base*.
### Piano dei conti (solo verifica fino a M7)
### Piano dei conti
Vedi il tracciato più sotto.
@@ -113,7 +116,7 @@ Vedi il tracciato più sotto.
| Opzione | Valori | Entità |
|---|---|---|
| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi |
| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi, piano dei conti |
| **Codice mancante** | *Genera automatico* con le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) oppure *Errore sulla riga* | clienti, fornitori, articoli |
| **Verifica P.IVA su VIES (UE)** | controlla su VIES le partite IVA dei soggetti UE durante l'import (più lento) | clienti, fornitori |
| **Completa comune da CAP** | completa comune e provincia da un CAP con un solo comune, o il CAP da un comune con un solo CAP (avviso) | clienti, fornitori |
@@ -158,8 +161,10 @@ farla sull'azienda reale.
## Tracciato del piano dei conti
In Italia non esiste uno standard per lo scambio del piano dei conti, perciò Khaemhat definisce il proprio
tracciato. Il piano standard per PMI sarà **precaricato** con la contabilità (M7); l'importazione serve a chi vuole
usare il piano del proprio commercialista o del gestionale precedente. Fino a M7 il file si **verifica** soltanto.
tracciato. Il piano standard per PMI è **precaricato** con la contabilità (dalla 0.7, vedi [Contabilità](Contabilita));
l'importazione serve a chi vuole usare il piano del proprio commercialista o del gestionale precedente. I conti nuovi
si aggiungono; quelli che esistono si aggiornano se l'opzione **Se il codice esiste** è *Aggiorna*, altrimenti si
saltano. Lo stesso tracciato si usa per esportare il piano dell'azienda.
### CSV e XLSX
@@ -210,7 +215,8 @@ Per lo scambio **completo** fra installazioni Khaemhat:
```
`accounts` ha le stesse colonne del CSV. Voci di bilancio (`statementLines`), causali (`journalTemplates`) e
mappature (`mappings`) si contano già nella mappatura e si importano con la contabilità (M7).
mappature (`mappings`) si contano nella mappatura ma non si importano ancora: le causali si gestiscono in
*Contabilità → Causali*.
### Controlli
@@ -231,8 +237,8 @@ Il riquadro **Esporta e modelli** usa l'entità scelta in alto:
(nome `clienti-2026-11-12.csv`). I codici delle tabelle sono esportati come codici.
L'export richiede il flag utente **Può esportare dati** e il permesso di export dell'entità (per le anagrafiche
*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Giacenze e piano dei conti hanno per ora solo
il modello. Le griglie esportano anche dal proprio menu (CSV/XLSX).
*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Le giacenze hanno per ora solo il
modello; il piano dei conti si esporta per intero. Le griglie esportano anche dal proprio menu (CSV/XLSX).
## Domande frequenti
+136 -90
View File
@@ -1,148 +1,194 @@
# Magazzino
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6)
> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.entry.post`, `items.cost.read`, famiglia `inventory.*` · **Specifica:** SPEC §11.6, §22
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **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
sole con i documenti (DDT, fatture accompagnatorie, carichi, resi) e con i movimenti manuali; da qui si fanno
trasferimenti tra depositi, inventari fisici, la proposta di riordino e la valorizzazione.
sole quando confermi un documento che muove la merce (DDT, fatture accompagnatorie, carichi dai fornitori, resi,
movimenti manuali); da qui consulti giacenze e movimenti, fai l'**inventario fisico**, generi la **proposta di
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).
## Dove si trova
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario fisico*, *Sottoscorta* (proposta di riordino),
*Trasferimenti*. I depositi e le causali di magazzino sono in [Tabelle azienda](Tabelle-azienda).
Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario*, *Proposte di riordino*. I **depositi** e le **causali
di magazzino** sono in [Tabelle azienda](Tabelle-azienda); scorta minima, punto e lotto di riordino e fornitori
abituali sono nella scheda dell'articolo (vedi [Articoli e listini](Articoli-e-listini)).
## Le quattro quantità
## Le quantità
| Quantità | Significato | Da dove nasce |
|---|---|---|
| **Giacenza** | merce fisicamente presente nel deposito | carichi e scarichi confermati |
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | ordini clienti, trasferimenti in bozza |
| **Ordinato** | merce in arrivo dai fornitori | ordini fornitore confermati e non ancora ricevuti |
| **Disponibile** | **giacenza - impegnato** | calcolata |
| **Giacenza** | merce presente nel deposito | movimenti dei documenti confermati |
| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | residuo degli ordini clienti |
| **Ordinato** | merce in arrivo dai fornitori | residuo degli ordini fornitore confermati |
| **Disponibile** | giacenza meno impegnato | calcolata |
Il sistema registra anche la merce **in transito** e il **valore medio** per articolo e deposito. Tutte queste
quantità sono aggiornate **nella stessa transazione** del documento che le muove: non c'è mai un momento in cui il
documento è confermato e la giacenza no.
Tutte si aggiornano **nella stessa operazione** che conferma il documento: non c'è mai un momento in cui il documento
è confermato e la giacenza no. Se annulli il documento, i suoi movimenti spariscono e le quantità tornano come prima.
## Quali documenti muovono il magazzino
Ogni tipo documento ha una **causale di magazzino** (in *Tabelle azienda → Tipi documento*) che decide se carica,
scarica o trasferisce. Con i tipi di base:
| Documento | Causale | Effetto |
|---|---|---|
| DDT, fattura immediata, fattura accompagnatoria | `SCA` scarico per vendita | scarica al costo medio |
| DDT fornitore (carico), fattura fornitore | `CAR` carico da acquisto | carica e aggiorna il costo medio |
| Nota di credito fornitore | `RESF` reso a fornitore | scarica |
| Movimento di magazzino (`MM`) | quella scelta nel movimento | carico, scarico o trasferimento |
| Ordini clienti e fornitori, preventivi, fatture differite | nessuna | solo impegnato e ordinato |
Una fattura nata da un DDT **non muove di nuovo** la merce: le sue righe trovano il carico o lo scarico già fatto
dal DDT. Il prezzo della fattura fornitore però **corregge il costo** del carico: se il fornitore fattura a un prezzo
diverso da quello del DDT, il costo medio viene ricalcolato con il prezzo fatturato.
Le causali di base sono: `CAR` carico da acquisto, `SCA` scarico per vendita, `RESC` reso da cliente, `RESF` reso a
fornitore, `TRA` trasferimento tra depositi, `INVP` e `INVN` rettifiche inventariali, `CVU` e `CVR` uscita e rientro
in conto visione (solo quantità), `OMA` omaggio, `AUTO` autoconsumo, `APE` esistenza iniziale. Per un'azienda creata
con una versione precedente le causali e i tipi documento mancanti si aggiungono con **Aggiorna da tabelle base** nel
menu `…` della tabella (vedi [Tabelle azienda](Tabelle-azienda)) o, per tutte le tabelle, con `scripts/seed.sh --base`.
## Giacenze e disponibilità
![036 · Giacenze, disponibilità, sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/036-giacenze.png)
*Mockup 036 — striscia di indicatori (valore magazzino, articoli gestiti, sottoscorta, sotto riordino, in arrivo) e griglia giacenze con stato (anteprima ridotta).*
![Khaemhat 0.6.0 · giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png)
In alto una **striscia di indicatori**: valore del magazzino, articoli gestiti, articoli **sottoscorta**, articoli
**sotto il punto di riordino**, valore **in arrivo** (ordinato).
In alto la striscia degli indicatori: **articoli in giacenza**, **sottoscorta**, **esauriti**, **articoli in
arrivo** (con ordini fornitore aperti) e **valore di magazzino** (visibile solo con `items.cost.read`).
La griglia mostra per ogni articolo: categoria, UM, **giacenza**, **impegnato**, **ordinato**, **disponibile**,
**scorta minima**, **punto di riordino**, **costo medio**, **valore** e uno **stato**:
Sotto, il filtro **Deposito** (tutti o uno solo) e la casella **Anche gli articoli senza giacenza**; poi il radar
con ricerca per codice o descrizione e i filtri rapidi **Categoria** e **Stato**. Per ogni articolo: categoria, unità,
giacenza, impegnato, ordinato, disponibile, scorta minima, costo medio, valore e uno **stato**:
| Stato | Quando |
|---|---|
| *OK* | disponibilità sopra il punto di riordino |
| *Sotto riordino* | disponibilità sotto il punto di riordino |
| *Sottoscorta* | disponibilità sotto la scorta minima (riga evidenziata) |
| *Esaurito · in arrivo* | giacenza a zero con ordini fornitore aperti |
| *Disponibile* | il disponibile più l'ordinato supera il punto di riordino |
| *Da riordinare* | disponibile più ordinato pari o sotto il punto di riordino |
| *Sottoscorta* | disponibile sotto la scorta minima |
| *Esaurito* | disponibile sotto zero, o a zero per un articolo con scorta minima o punto di riordino |
Filtri: ricerca (articolo, EAN, descrizione), **Deposito**, **Categoria**, **Mostra** (*Solo gestiti a magazzino*),
chip *Evidenzia sottoscorta*. Azioni: **Proposta di riordino**, **Inventario**. Il dettaglio per deposito di un
singolo articolo è anche nella scheda articolo (vedi [Articoli e listini](Articoli-e-listini)).
Le colonne *Ultimo carico* e *Ultimo scarico* si aggiungono dal selettore delle colonne del radar. I pulsanti
portano alla **proposta di riordino** e all'**inventario**, aprono la **valorizzazione** e la **ricostruzione**.
## Movimenti e trasferimenti
## Movimenti di un articolo
![037 · Movimento di magazzino manuale (trasferimento)](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/037-movimento-magazzino.png)
*Mockup 037 — trasferimento in bozza dal deposito SEDE al deposito furgone, con disponibilità all'origine e valore (anteprima ridotta).*
![Khaemhat 0.6.0 · movimenti di un articolo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-movimenti-articolo.png)
I **movimenti manuali** servono per tutto ciò che non passa da un documento di vendita o acquisto: carichi e scarichi
rettificativi, omaggi interni, consumi, **trasferimenti** tra depositi. Ogni movimento ha una **causale di
magazzino** che ne stabilisce l'effetto (carico, scarico, trasferimento).
Apri una riga delle giacenze (doppio clic o **Invio**) per vedere i movimenti dell'articolo in ordine di data: il
documento che li ha generati (il link lo apre), la causale, il cliente o fornitore, il deposito, la quantità, il
costo unitario e il **saldo progressivo**. **Apri l'articolo** porta alla scheda. Il widget *Sottoscorta* della
[Dashboard](Dashboard) apre direttamente questa finestra sull'articolo scelto.
Per un trasferimento:
## Movimenti manuali e trasferimenti
1. **Magazzino → Trasferimenti** (o *Movimenti*), **Nuovo**.
2. Scegli la causale di trasferimento, il **deposito di origine** e quello di **destinazione**.
3. Inserisci le righe: la colonna *Disp. origine* mostra quanto è disponibile nel deposito di partenza.
4. Se serve, **Stampa lista prelievo** per chi prepara la merce.
5. **Conferma**.
Per tutto ciò che non passa da un documento di vendita o acquisto (rettifiche, omaggi, autoconsumi, conto visione,
trasferimenti) usa **Magazzino → Movimenti** e crea un **Movimento di magazzino**: è un documento come gli altri
(vedi [Vendite](Vendite) per la maschera), con in più la **causale** e il **deposito**.
Un trasferimento genera **due movimenti collegati** (scarico dall'origine e carico nella destinazione) nella stessa
transazione. Finché il movimento è in bozza la merce dell'origine risulta **impegnata**.
1. Scegli la **causale**: decide se il movimento carica, scarica o trasferisce.
2. Indica il **deposito**; per un trasferimento anche il **deposito di destinazione**, diverso dall'origine.
3. Inserisci le righe con articolo e quantità; nei carichi il prezzo è il costo unitario.
4. **Conferma**: il magazzino si aggiorna. Un trasferimento scarica l'origine e carica la destinazione al costo medio,
senza cambiare il valore complessivo.
Un movimento confermato si può annullare: i suoi movimenti vengono tolti e le giacenze ricalcolate.
## Inventario fisico
![038 · Inventario fisico con conteggi e rettifiche](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/038-inventario-fisico.png)
*Mockup 038 — inventario guidato in cinque passi, griglia con giacenza teorica, contato, differenza, valore e rettifica (anteprima ridotta).*
![Khaemhat 0.6.0 · inventario fisico in conteggio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-inventario.png)
L'inventario è una procedura guidata:
L'inventario confronta la merce contata con la **giacenza contabile** e trasforma le differenze in rettifiche.
1. **Preparazione**: scegli il **deposito**, la **data** e il criterio di **valorizzazione** (es. costo medio);
l'opzione **Blocca movimenti durante il conteggio** congela le giacenze del deposito.
2. **Conteggio**: **Stampa liste di conteggio** (anche per ubicazione e squadra) e inserisci i quantitativi contati
nella griglia oppure **Importa conteggi CSV**.
3. **Verifica differenze**: la griglia confronta **giacenza teorica** e **contato** e mostra differenza e valore;
il filtro *Solo differenze e da contare* aiuta a chiudere il lavoro.
4. **Rettifiche**: **Genera rettifiche** crea i movimenti di carico o scarico per allineare la giacenza al contato.
5. **Chiusura**: sblocca il deposito.
1. **Apertura**: in **Magazzino → Inventario** scegli il **deposito**, la **data del conteggio**, se vuoi una
**categoria** e una descrizione, poi **Apri inventario**. Khaemhat fotografa la giacenza contabile di ogni articolo
gestito a magazzino a quella data.
2. **Conteggio**: scrivi le quantità contate nella colonna *Contato* e premi **Salva conteggi**, oppure **Importa
conteggi** da un file CSV o di testo del lettore di codici a barre: una riga per articolo con *codice articolo* e
*quantità*, separati da punto e virgola, tabulazione o virgola (con la virgola la quantità usa il punto decimale).
Una riga di intestazione viene saltata; i codici non in lista sono segnalati.
3. **Verifica differenze**: il filtro **Mostra** (*Tutti*, *Da contare*, *Con differenze*) aiuta a chiudere il
lavoro; le righe con differenza sono evidenziate e la striscia in alto riassume articoli contati, differenze e
valore delle differenze.
4. **Registrazione**: **Registra rettifiche** crea alla data del conteggio un movimento `INVP` per le eccedenze e uno
`INVN` per gli ammanchi, e chiude l'inventario. Gli articoli **non contati restano come sono**.
**Annulla inventario** lo chiude senza muovere il magazzino; i conteggi restano consultabili. I movimenti successivi
alla data del conteggio non disturbano: le rettifiche sono alla data del conteggio e la giacenza di oggi tiene conto
di entrambi.
## Proposta di riordino
![039 · Proposta di riordino fornitori dal sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/039-proposta-di-riordino.png)
*Mockup 039 — proposta di riordino: indicatori, criterio di calcolo, quantità proposta modificabile e fornitore per riga (anteprima ridotta).*
![Khaemhat 0.6.0 · proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png)
La proposta elenca gli articoli sotto il punto di riordino con giacenza, impegnato, ordinato, disponibile, scorta
minima, punto e **lotto** di riordino, **quantità proposta** (modificabile), **fornitore** abituale, lead time,
prezzo e valore. In alto gli indicatori: articoli sotto riordino, proposte, valore, fornitori coinvolti, articoli
già coperti da ordini.
La proposta elenca gli articoli il cui **disponibile più ordinato** non copre più il **punto di riordino** (o, se manca,
la **scorta minima**). Per ogni articolo propone:
1. Scegli **deposito**, **fornitore** (o tutti) e il **criterio di calcolo** (es. *disponibile + ordinato < punto
di riordino*, con o senza l'impegnato).
2. **Ricalcola**, controlla e correggi le quantità proposte, togli la spunta alle righe da non ordinare.
3. **Genera ordini fornitore**: Khaemhat crea **un ordine in bozza per fornitore** (vedi [Acquisti](Acquisti)).
- la **quantità**: il **lotto di riordino** dell'articolo se c'è, altrimenti quanto riporta al punto di riordino (o
alla scorta minima); mai meno del **minimo d'ordine** del fornitore;
- il **fornitore abituale** (il preferito nella scheda articolo, *Fornitori*) con il suo prezzo e la **data di arrivo
prevista** dal lead time.
Il mockup indica come fabbisogno il maggiore tra il lotto e la differenza fra punto di riordino e disponibile più
ordinato; la formula definitiva (compresi gli arrotondamenti al lotto) sarà fissata in sviluppo. La proposta può
anche essere eseguita da una procedura pianificata o alimentata da una regola di automazione (evento *articolo sotto
il punto di riordino*, vedi [Automazioni](Automazioni)).
Correggi le quantità, cambia il fornitore di una riga o togli la spunta alle righe da non ordinare; **Ricalcola**
rilegge le giacenze. **Genera ordini fornitore** crea **un ordine in bozza per fornitore** con prezzi e condizioni del
fornitore: controllali e confermali da **Acquisti → Ordini fornitori** (vedi [Acquisti](Acquisti)). Le righe senza
fornitore non vengono ordinate.
## Costo medio e valorizzazione
- Il criterio di valorizzazione è il **costo medio ponderato**: a ogni carico il nuovo costo medio è
(valore della giacenza esistente + valore del carico) / (giacenza esistente + quantità caricata). FIFO e LIFO sono
predisposti ma non attivi.
- Il **valore** di una giacenza è quantità x costo medio.
- La **valorizzazione a data** ricostruisce quantità e valore a una data passata (ad esempio al 31 dicembre).
- Le **rimanenze finali** valorizzate alimentano la chiusura dell'esercizio e il **libro inventari** (vedi
[Contabilità](Contabilita)); sono disponibili le **scritture ausiliarie di magazzino** e l'**analisi ABC**.
![Khaemhat 0.6.0 · valorizzazione con classi ABC](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-valorizzazione.png)
- Il criterio è il **costo medio ponderato** per articolo, su tutti i depositi: a ogni carico con valore il nuovo
costo medio è (valore della giacenza + valore del carico) / (giacenza + quantità caricata). Scarichi, trasferimenti
e conto visione escono al costo medio del momento e non lo cambiano.
- La scheda articolo mostra **costo medio** e **ultimo costo** calcolati dai movimenti.
- 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).
## Ricostruzione
Se le giacenze risultassero non allineate (ad esempio dopo un ripristino o un import), la **ricostruzione** ricalcola
giacenze, impegnato, ordinato e costi medi ripercorrendo tutti i movimenti. È una procedura eseguibile a mano o da
attività programmata e non modifica i documenti. Vedi [Automazioni](Automazioni) e
[Attività programmate](Attivita-programmate).
Se le giacenze sembrano non tornare (dopo un ripristino, un import diretto nel database, un cambio di causale su un
tipo documento), **Ricostruisci** nelle giacenze riscrive tutti i movimenti dai documenti in vigore, dal più vecchio,
e ricalcola giacenze, impegnato, ordinato e costi. I documenti non cambiano e i dati restano consultabili durante il
lavoro, che mostra l'avanzamento. Richiede `inventory.entry.post`.
## Stati dei movimenti
La stessa ricostruzione gira ogni **domenica alle 2:15** come attività di sistema *Ricostruzione del magazzino* (vedi
[Attività programmate](Attivita-programmate)), su tutte le aziende attive.
| Stato | Effetto |
|---|---|
| **Bozza** | nessun effetto sulla giacenza (nei trasferimenti l'origine è impegnata) |
| **Confermato** | giacenze aggiornate; righe non più modificabili |
| **Annullato** | movimenti stornati |
## Esistenze iniziali
Per partire con le giacenze di un altro gestionale importa il tracciato **Giacenze iniziali** da
[Import ed export](Import-Export): articolo, deposito, quantità e costo unitario. Khaemhat crea e conferma un
movimento con causale `APE` per deposito, alla data dell'import.
## Permessi e licenza
Il magazzino è nel modulo **CORE**. Confermare un movimento richiede `inventory.entry.post`; vedere costi e valori
richiede `items.cost.read`.
Il magazzino è nel modulo **CORE**. Vedere giacenze e movimenti richiede `inventory.stock.read`; scrivere movimenti
e conteggi `inventory.entry.write`; confermare i movimenti, registrare le rettifiche e ricostruire
`inventory.entry.post`. Costi, valori e valorizzazione sono visibili solo con `items.cost.read`.
## Domande frequenti
- **Il disponibile è negativo.** Gli ordini clienti confermati impegnano più merce di quella in giacenza: ordina al
fornitore o rivedi le consegne.
- **Il costo medio è cambiato dopo un carico.** È il comportamento previsto del costo medio ponderato; il messaggio
sul DDT di carico indica il vecchio e il nuovo valore.
- **Durante l'inventario non riesco a scaricare merce dal deposito.** È attivo il blocco dei movimenti: termina la
procedura o disattiva il blocco.
- **La giacenza è negativa.** È stato confermato uno scarico senza merce a sufficienza (Khaemhat non lo blocca, per
non fermare le consegne): registra il carico mancante o fai un inventario.
- **Il costo medio è cambiato dopo una fattura fornitore.** Il prezzo fatturato era diverso da quello del DDT di
carico: il costo del carico viene corretto con il prezzo della fattura.
- **Un articolo non compare nelle giacenze.** Non ha movimenti: spunta *Anche gli articoli senza giacenza*. Se non
compare comunque, nella scheda non è *gestito a magazzino* o non è un bene.
- **L'articolo non è nella proposta di riordino.** Non ha punto di riordino né scorta minima, oppure l'ordinato già
lo copre.
## Pagine correlate
[Articoli e listini](Articoli-e-listini) · [Acquisti](Acquisti) · [Vendite](Vendite) ·
[Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Contabilità](Contabilita) · [Automazioni](Automazioni)
[Tabelle azienda](Tabelle-azienda) · [Import ed export](Import-Export) · [Dashboard](Dashboard) ·
[Attività programmate](Attivita-programmate)
+1 -1
View File
@@ -289,7 +289,7 @@ Con l'azienda configurata puoi emettere la prima fattura:
![Khaemhat 0.5.0 · una fattura emessa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/vendite-documento.png)
La guida completa è in [Vendite](Vendite). La contabilizzazione arriva con M7 e l'XML FatturaPA per lo SDI con M9
La guida completa è in [Vendite](Vendite). Dalla 0.7 la fattura confermata è già in [Contabilità](Contabilita); l'XML FatturaPA per lo SDI con M9
(modulo EINV, vedi [Fatturazione elettronica](Fatturazione-elettronica)).
## Domande frequenti
+1 -1
View File
@@ -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). **Prossima:** M6.
**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). **Prossima:** M8.
| # | Milestone | Contenuto principale | Versione |
|---|---|---|---|
+1 -1
View File
@@ -81,7 +81,7 @@ liquidazione IVA (*provvisoria*, *confermata*), registrazioni, interruttore **Bl
Indirizzo: `/tabelle/esercizi`. **Nuovo esercizio** crea l'anno successivo all'ultimo con i suoi dodici mesi. Il
pulsante **Blocca** di un mese impedisce nuove registrazioni con date in quel mese; **Sblocca** chiede conferma. Un
mese *liquidato* si sblocca solo annullando la liquidazione IVA (M7).
mese *liquidato* si sblocca solo riaprendo la liquidazione IVA (vedi [IVA](IVA)).
Regola fondamentale: **si possono registrare documenti e movimenti contabili solo con data in un periodo aperto**. Un
periodo bloccato rifiuta ogni registrazione con data al suo interno; la conferma della liquidazione IVA blocca il
+6 -4
View File
@@ -9,8 +9,10 @@ accompagnatorie, differite, di acconto, parcelle), **note di credito e di debito
e si inviano per e-mail.
> **In questa versione** i documenti hanno numeri, totali, castelletto IVA, bollo, ritenute, scadenze, collegamenti
> riga per riga, stampa ed e-mail. Arrivano più avanti: lo **scarico di magazzino** e l'impegno (M6, con il
> magazzino), la **registrazione contabile** (M7), le **partite** e il controllo del fido (M8), il **file XML** per lo
> 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)). Arrivano più avanti: gli **incassi** e il controllo
> del fido (M8), il **file XML** per lo
> SDI (M9) e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la
> funzione c'è.
@@ -148,8 +150,8 @@ e CUP, riportati nella stampa.
Il DDT accompagna la merce: si compila la scheda *Trasporto* e si stampa con gli spazi per le firme. Un DDT confermato
non ancora fatturato compare nella **fatturazione differita**; un DDT fatturato risulta *Evaso*. Finché non è
fatturato le righe si possono ancora correggere; **Annulla documento** lo annulla con un motivo. Lo scarico del
magazzino arriva con M6.
fatturato le righe si possono ancora correggere; **Annulla documento** lo annulla con un motivo. Alla conferma il DDT
**scarica il magazzino** (causale `SCA`); la fattura differita che lo fattura non scarica di nuovo.
## Fatture
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

@@ -105,7 +105,7 @@ public static class WidgetCatalog
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read"),
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
@@ -1,4 +1,5 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
@@ -89,6 +90,15 @@ public static class DocumentErrors
/// <summary>Error: a line of an invoice without its VAT code.</summary>
public const string LineTaxRequired = "document.line.tax-required";
/// <summary>A supplier invoice needs the number and date the supplier gave it.</summary>
public const string SupplierNumberRequired = "document.purchase.number-required";
/// <summary>The same supplier already has a document of the kind with that number in that year.</summary>
public const string SupplierDuplicate = "document.purchase.duplicate";
/// <summary>The VAT date comes before the date of the supplier document.</summary>
public const string VatDateBefore = "document.purchase.vat-date-before";
}
/// <summary>
@@ -105,6 +115,7 @@ public sealed partial class DocumentEngine
private readonly CompanyFiscalContext _packs;
private readonly TimeProvider _clock;
private readonly ILogger<DocumentEngine> _logger;
private readonly Ledger.LedgerPoster _ledger;
/// <summary>Creates the engine.</summary>
/// <param name="factory">The units of work.</param>
@@ -114,10 +125,13 @@ public sealed partial class DocumentEngine
/// <param name="packs">The fiscal pack of each company (tax rounding, stamp duty).</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section Documenti): confirmations, changes of state, deletions.</param>
/// <param name="ledger">Posts the documents to the ledger (module ACCT).</param>
public DocumentEngine(
IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock,
ILogger<DocumentEngine> logger)
ILogger<DocumentEngine> logger, Ledger.LedgerPoster ledger)
{
ArgumentNullException.ThrowIfNull(ledger);
_ledger = ledger;
ArgumentNullException.ThrowIfNull(logger);
_logger = logger;
ArgumentNullException.ThrowIfNull(packs);
@@ -240,6 +254,7 @@ public sealed partial class DocumentEngine
}
var errors = Check(definition, record, before);
await CheckSupplierDocumentAsync(uow, record, confirming: false, errors, cancellationToken).ConfigureAwait(false);
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
@@ -257,6 +272,8 @@ public sealed partial class DocumentEngine
if (before is not null && DocumentStateMachine.IsInForce(header.Status))
{
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 uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -300,6 +317,8 @@ public sealed partial class DocumentEngine
errors.Add("Lines:" + DocumentErrors.LinesRequired);
}
await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false);
if (definition.Behavior.Has(DocumentEffects.Ledger))
{
// A document that goes to the VAT registers needs the VAT of every line with an amount.
@@ -329,12 +348,21 @@ public sealed partial class DocumentEngine
}
header.Year = header.DocumentDate.Year;
if (IsRegistered(header.Kind))
{
// A supplier invoice takes its protocol from the numbering of the purchase register (§11.5).
header.VatProtocol = header.Number;
header.VatDate ??= header.DocumentDate;
}
header.Status = next;
header.ConfirmedAt = _clock.GetUtcNow().UtcDateTime;
header.ConfirmedBy = actor.UserName;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false);
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 uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName);
}
@@ -679,6 +707,9 @@ public sealed partial class DocumentEngine
await after(uow, record, actor.UserName, cancellationToken).ConfigureAwait(false);
}
// 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 uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName);
}
@@ -834,6 +865,52 @@ public sealed partial class DocumentEngine
header.Revision = 0;
}
// Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date.
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
// the same supplier, kind, number and year among the documents in force or in draft.
private static async Task CheckSupplierDocumentAsync(IUnitOfWork uow, DocumentRecord record, bool confirming, List<string> errors, CancellationToken cancellationToken)
{
var header = record.Header;
if (!IsRegistered(header.Kind))
{
return;
}
var number = header.ExternalReference?.Trim();
if (confirming && string.IsNullOrEmpty(number))
{
errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierNumberRequired);
}
if (confirming && header.ExternalDate is null)
{
errors.Add(nameof(DocumentHeader.ExternalDate) + ":" + DocumentErrors.SupplierNumberRequired);
}
if (header.VatDate is { } vatDate && header.ExternalDate is { } supplierDate && vatDate < supplierDate)
{
errors.Add(nameof(DocumentHeader.VatDate) + ":" + DocumentErrors.VatDateBefore);
}
if (string.IsNullOrEmpty(number) || header.PartyId is not { } party)
{
return;
}
var year = (header.ExternalDate ?? header.DocumentDate).Year;
var kind = header.Kind;
var id = header.Id;
var others = (await uow.Repository<PurchaseDocument, long>().ListAsync(
Query.For<PurchaseDocument>().Where(d => d.PartyId == party && d.Kind == kind && d.ExternalReference == number && d.Id != id && d.Status != DocumentStatus.Cancelled),
cancellationToken).ConfigureAwait(false)).Items;
if (others.Any(d => (d.ExternalDate ?? d.DocumentDate).Year == year))
{
errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierDuplicate);
}
}
private static string Company(Actor actor, string companyCode)
{
ArgumentNullException.ThrowIfNull(actor);
@@ -40,6 +40,12 @@ internal interface IDocumentStore
/// <returns>The lines.</returns>
Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken);
/// <summary>Reads the headers of the documents in force (neither drafts nor cancelled).</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The headers.</returns>
Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken);
/// <summary>Reads a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The line.</param>
@@ -136,6 +142,11 @@ internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, strin
public async Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
await uow.Repository<THeader, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
[.. (await uow.Repository<THeader, long>().ListAsync(
Query.For<THeader>().Where(h => h.Status != DocumentStatus.Draft && h.Status != DocumentStatus.Cancelled), cancellationToken).ConfigureAwait(false)).Items];
/// <inheritdoc />
public async Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken)
{
@@ -2,10 +2,7 @@ using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
@@ -21,9 +18,11 @@ namespace Khaemhat.Application.ImportExport;
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
/// <param name="ClosesAutomatically">Closed by the year end.</param>
/// <param name="Disabled">Not used any more.</param>
/// <param name="StatementLine">The line of the legal statements (voce CEE).</param>
/// <param name="Reclassification">The line of the reclassified statements.</param>
public sealed record ImportedAccount(
string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger,
bool ClosesAutomatically, bool Disabled);
bool ClosesAutomatically, bool Disabled, string? StatementLine = null, string? Reclassification = null);
/// <summary>
/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by
@@ -149,7 +148,7 @@ public static class ChartOfAccountsImportValidator
if (messages.All(m => m.IsWarning) && nature is { } valid)
{
accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'),
flags.Contains('X')));
flags.Contains('X'), row["voce_cee"], row["riclassifica"]));
}
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
@@ -186,15 +185,26 @@ public static class ChartOfAccountsImportValidator
}
/// <summary>
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. Until the ledger exists (M7)
/// the file is only checked; M7 writes the accounts this check accepts.
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. The accounts the check
/// accepts are added; those that exist are updated when the options say so (M7, issue #62).
/// </summary>
/// <param name="permissions">Checks the permission.</param>
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
public sealed class ChartOfAccountsImportTarget : IImportTarget
{
/// <summary>The permission to change the chart of accounts.</summary>
public const string WritePermission = "ledger.account.write";
private readonly PermissionService _permissions;
private readonly IUnitOfWorkFactory? _factory;
/// <summary>Creates the target.</summary>
/// <param name="permissions">Checks the permission.</param>
/// <param name="factory">The units of work, to write the accounts.</param>
public ChartOfAccountsImportTarget(PermissionService permissions, IUnitOfWorkFactory? factory = null)
{
_permissions = permissions;
_factory = factory;
}
/// <inheritdoc />
public string Key => "piano-dei-conti";
@@ -208,10 +218,10 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
public string ExportPermission => "ledger.account.read";
/// <inheritdoc />
public bool CanApply => false;
public bool CanApply => _factory is not null;
/// <inheritdoc />
public bool CanExport => false;
public bool CanExport => _factory is not null;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
@@ -220,113 +230,46 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
return ChartOfAccountsImportValidator.Check(rows).Results;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>): item, warehouse, quantity and unit cost. Until the stock entries exist
/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
{
private static readonly ImportField[] StockFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => false;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
var byId = items.ToDictionary(i => i.Id);
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var seen = new HashSet<(long, long)>();
var results = new List<ImportRowResult>(rows.Count);
foreach (var row in rows)
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
var (results, accounts) = ChartOfAccountsImportValidator.Check(rows);
var update = context.Options.Existing == ExistingCodeAction.Update;
Dictionary<string, bool> written;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId);
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
{
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
}
if (item is not null && warehouse is null && !cells.Has("deposito"))
{
messages.Add(new("deposito", ImportErrors.Required));
}
if (cells.Number("quantita") is <= 0)
{
messages.Add(new("quantita", ImportErrors.Positive));
}
if (cells.Number("costo_unitario") is < 0)
{
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
}
var label = row["articolo"] ?? string.Empty;
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
}
results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
written = await Ledger.LedgerService.ImportAsync(uow, accounts, update, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return results;
return [.. results.Select(r => r.Action == ImportAction.Skip
? r
: r with { Action = written.TryGetValue(r.Key, out var created) ? (created ? ImportAction.Create : ImportAction.Update) : ImportAction.Skip })];
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
public async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var factory = _factory ?? throw new InvalidOperationException(ImportErrors.CheckOnly);
var company = await CompanyGuard.DemandAsync(_permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Data.Querying.Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(a => a.Code, StringComparer.Ordinal);
return [.. accounts.Select(a => (IReadOnlyList<object?>)
[
a.Code, a.Description, a.Level, ChartOfAccountsImportValidator.ParentOf(a.Code), ChartOfAccountsImportValidator.NatureWords[(int)a.Nature],
ChartOfAccountsImportValidator.TypeWords[(int)a.Type], a.StatementLine, a.Reclassification,
(a.Postable ? "M" : string.Empty) + (a.VatRelevant ? "I" : string.Empty) + (a.SubLedger ? "P" : string.Empty)
+ (a.ClosesAutomatically ? "C" : string.Empty) + (a.Disabled ? "X" : string.Empty),
])];
}
}
@@ -0,0 +1,191 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted
/// become one warehouse movement per warehouse with the reason <c>APE</c> (opening stock), confirmed at the day of the
/// import: the stock and the average cost start from there.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
/// <param name="engine">Writes the movements.</param>
/// <param name="clock">The day of the movements.</param>
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget
{
/// <summary>The reason of the opening stock.</summary>
public const string OpeningReason = "APE";
/// <summary>Error: the reason APE is missing.</summary>
public const string ReasonMissing = "import.stock.reason-missing";
private static readonly ImportField[] StockFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => true;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
[.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)];
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var read = await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
long? reason;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
reason = (await uow.Repository<InventoryReason, long>().FindAsync(Query.For<InventoryReason>().Where(r => r.Code == OpeningReason), cancellationToken)
.ConfigureAwait(false))?.Id;
}
var results = read.Select(r => r.Result).ToArray();
var good = read.Select((r, i) => (Row: r, Index: i)).Where(x => x.Row.Result.Action == ImportAction.Create && x.Row.Stock is not null).ToList();
if (reason is null)
{
foreach (var (_, index) in good)
{
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, new ImportMessage("articolo", ReasonMissing)] };
}
return results;
}
var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
foreach (var group in good.GroupBy(x => x.Row.Stock!.Value.WarehouseId))
{
var movement = await engine.NewAsync(context.Actor, company, "MM", cancellationToken).ConfigureAwait(false);
movement.Header.DocumentDate = today;
movement.Header.WarehouseId = group.Key;
movement.Header.InventoryReasonId = reason;
foreach (var (row, _) in group)
{
var stock = row.Stock!.Value;
movement.Lines.Add(new InventoryDocumentLine
{
Kind = DocumentLineKind.Item,
ItemId = stock.Item.Id,
Description = stock.Item.Description,
UnitOfMeasureId = stock.Item.UnitOfMeasureId,
Quantity = stock.Quantity,
Price = stock.Cost,
WarehouseId = group.Key,
});
}
try
{
var saved = await engine.SaveAsync(context.Actor, company, movement, cancellationToken).ConfigureAwait(false);
await engine.ConfirmAsync(context.Actor, company, saved.Family, saved.Header.Id, cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException ex)
{
var message = new ImportMessage("articolo", ex.Errors.Count > 0 ? ex.Errors[0].Split(':', 2)[^1] : ImportErrors.Required);
foreach (var (_, index) in group)
{
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, message] };
}
}
}
return results;
}
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
private async Task<List<(ImportRowResult Result, (Item Item, long WarehouseId, decimal Quantity, decimal Cost)? Stock)>> ReadAsync(
ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
var byId = items.ToDictionary(i => i.Id);
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var fallback = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items
.OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id;
var seen = new HashSet<(long, long)>();
var results = new List<(ImportRowResult, (Item, long, decimal, decimal)?)>(rows.Count);
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId ?? fallback);
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
{
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
}
if (item is not null && warehouse is null && !cells.Has("deposito"))
{
messages.Add(new("deposito", ImportErrors.Required));
}
var quantity = cells.Number("quantita");
if (quantity is <= 0)
{
messages.Add(new("quantita", ImportErrors.Positive));
}
var cost = cells.Number("costo_unitario");
if (cost is < 0)
{
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
}
var label = row["articolo"] ?? string.Empty;
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
}
var failed = messages.Any(m => !m.IsWarning);
(Item, long, decimal, decimal)? stock = !failed && item is not null && warehouse is { } where && quantity is { } q
? (item, where, q, cost ?? item.AverageCost ?? item.StandardCost ?? item.LastCost ?? 0m)
: null;
results.Add((new ImportRowResult(row.Line, label, failed ? ImportAction.Skip : ImportAction.Create, messages), stock));
}
return results;
}
}
@@ -0,0 +1,553 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>
/// Posts the documents to the warehouse (SPEC §11.6, ADR 0035) inside the transaction of the document engine: a
/// confirmed document that moves the stock writes one movement per stocked line; a cancelled one loses it. After every
/// change the history of the items touched runs again through the weighted average and gives the balances of each
/// warehouse, the committed and ordered quantities of the open orders and the costs on the item card.
/// </summary>
public static class InventoryPoster
{
/// <summary>A transfer needs a destination different from the origin.</summary>
public const string TransferDestination = "document.transfer.destination";
/// <summary>Writes again the movements of a document from its current state and refreshes its items.</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family of the document.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var items = new HashSet<long>();
await RemoveAsync(uow, family, documentId, items, cancellationToken).ConfigureAwait(false);
var header = await HeaderAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
if (header is null)
{
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
return;
}
var lines = await LinesAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
foreach (var line in lines.Where(l => l.ItemId is not null))
{
// Orders hold committed and ordered quantities; every state change of theirs moves the balances.
items.Add(line.ItemId!.Value);
}
if (DocumentStateMachine.IsInForce(header.Status) && StockEffectMatrix.MovesStock(header.Kind))
{
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
}
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Rebuilds the warehouse from the documents (SPEC §11.6, <i>ricostruzione</i>): removes every movement, posts
/// again every document in force that moves the stock, oldest first and the delivery notes before the invoices of
/// the same day, then runs the history of every item.
/// </summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="progress">Receives the documents posted and the total, then the items and their total.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents posted and the items computed.</returns>
public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entry_lines"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entries"), cancellationToken).ConfigureAwait(false);
var documents = new List<(DocumentFamily Family, DocumentHeader Header)>();
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
{
foreach (var header in await Documents.DocumentStores.Of(family).InForceAsync(uow, cancellationToken).ConfigureAwait(false))
{
if (StockEffectMatrix.MovesStock(header.Kind))
{
documents.Add((family, header));
}
}
}
// Delivery notes and receipts first: their invoices then find the goods already moved.
var ordered = documents
.OrderBy(d => d.Header.DocumentDate)
.ThenBy(d => d.Header.Kind is DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote or DocumentKind.InventoryEntry ? 0 : 1)
.ThenBy(d => d.Header.ConfirmedAt)
.ThenBy(d => d.Header.Id)
.ToList();
var items = new HashSet<long>();
for (var i = 0; i < ordered.Count; i++)
{
var (family, header) = ordered[i];
var lines = await LinesAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
progress?.Report(new RebuildProgress(RebuildPhase.Documents, i + 1, ordered.Count));
}
// Every stocked item, also those with only orders or with no movement left.
var all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id);
var balanced = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>(), cancellationToken).ConfigureAwait(false)).Items.Select(b => b.ItemId);
var ids = items.Concat(all).Concat(balanced).Distinct().ToList();
for (var i = 0; i < ids.Count; i += 50)
{
await RecomputeAsync(uow, ids.Skip(i).Take(50), cancellationToken).ConfigureAwait(false);
progress?.Report(new RebuildProgress(RebuildPhase.Items, Math.Min(i + 50, ids.Count), ids.Count));
}
return (ordered.Count, ids.Count);
}
/// <summary>
/// Runs again the history of items: the cost of every movement, the balances of each warehouse, the committed and
/// ordered quantities, the average and last cost on the item card.
/// </summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="itemIds">The items.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task RecomputeAsync(IUnitOfWork uow, IEnumerable<long> itemIds, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
ArgumentNullException.ThrowIfNull(itemIds);
var ids = itemIds.Distinct().ToList();
if (ids.Count == 0)
{
return;
}
var committed = await OpenQuantitiesAsync<SaleOrder, SaleOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
var ordered = await OpenQuantitiesAsync<PurchaseOrder, PurchaseOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
var defaultWarehouse = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
foreach (var itemId in ids)
{
await RecomputeItemAsync(uow, itemId, committed, ordered, defaultWarehouse, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>The default warehouse of the company: the one marked as such, or the first.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The warehouse, if any.</returns>
public static async Task<long?> DefaultWarehouseAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var warehouses = uow.Repository<Warehouse, long>();
var marked = await warehouses.FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
return marked?.Id ?? (await warehouses.FindAsync(Query.For<Warehouse>().Where(w => !w.Disabled).OrderBy(w => w.Code), cancellationToken).ConfigureAwait(false))?.Id;
}
/// <summary>The quantity of a line in the base unit of its item.</summary>
/// <param name="quantity">The quantity on the line.</param>
/// <param name="lineUnit">The unit of the line.</param>
/// <param name="item">The item.</param>
/// <param name="units">The alternative units of the item.</param>
/// <returns>The quantity in the base unit.</returns>
public static decimal ToBase(decimal quantity, long? lineUnit, Item item, IEnumerable<ItemUnit> units)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentNullException.ThrowIfNull(units);
if (lineUnit is null || lineUnit == item.UnitOfMeasureId)
{
return quantity;
}
var unit = units.FirstOrDefault(u => u.ItemId == item.Id && u.UnitOfMeasureId == lineUnit);
return unit is null || unit.Factor <= 0m ? quantity : quantity * unit.Factor;
}
private static async Task RemoveAsync(IUnitOfWork uow, DocumentFamily family, long documentId, HashSet<long> items, CancellationToken cancellationToken)
{
var entries = uow.Repository<InventoryEntry, long>();
var lines = uow.Repository<InventoryEntryLine, long>();
foreach (var entry in (await entries.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId), cancellationToken)
.ConfigureAwait(false)).Items)
{
foreach (var line in (await lines.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
{
items.Add(line.ItemId);
await lines.DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false);
}
await entries.DeleteAsync(entry.Id, cancellationToken).ConfigureAwait(false);
}
}
private static async Task PostAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, IReadOnlyList<DocumentLine> lines, HashSet<long> items, CancellationToken cancellationToken)
{
if (header.InventoryReasonId is not { } reasonId
|| await uow.Repository<InventoryReason, long>().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) is not { } reason)
{
return;
}
// A line that comes from a document that already moved its goods the same way (the invoice of a delivery note)
// does not move them again; a credit note of an invoice moves them back.
var sign = reason.IsTransfer ? 0 : reason.Effect switch { StockEffect.Load => 1, StockEffect.Unload => -1, _ => 0 };
var stockLines = await StockLinesAsync(uow, header, lines, sign, cancellationToken).ConfigureAwait(false);
IReadOnlyList<StockMovement> movements;
try
{
movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines);
}
catch (InvalidOperationException)
{
throw new ValidationFailedException([nameof(DocumentHeader.ToWarehouseId) + ":" + TransferDestination]);
}
if (movements.Count == 0)
{
return;
}
var entry = new InventoryEntry
{
EntryDate = header.DocumentDate,
SourceFamily = family,
SourceDocumentId = header.Id,
SourceKind = header.Kind,
SourceNumber = header.DocumentNumber,
InventoryReasonId = reason.Id,
PartyId = header.PartyId,
IsDemo = header.IsDemo,
};
await uow.Repository<InventoryEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<InventoryEntryLine, long>();
var order = 0;
foreach (var m in movements)
{
items.Add(m.ItemId);
await repository.InsertAsync(
new InventoryEntryLine
{
EntryId = entry.Id,
EntryDate = entry.EntryDate,
ItemId = m.ItemId,
WarehouseId = m.WarehouseId,
Quantity = m.Quantity,
Valued = m.Valued,
UnitCost = m.UnitCost,
Value = StockCostCalculator.Value(m.Quantity, m.UnitCost),
SourceLineId = m.SourceLineId,
SortOrder = ++order,
},
cancellationToken).ConfigureAwait(false);
}
}
// The stocked lines of a document in the base unit, with their warehouse and cost; the lines that come from a
// document that already moved the stock (the invoice of a delivery note) are left out.
private static async Task<List<StockLineInput>> StockLinesAsync(
IUnitOfWork uow, DocumentHeader header, IReadOnlyList<DocumentLine> lines, int sign, CancellationToken cancellationToken)
{
var result = new List<StockLineInput>();
var itemIds = lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null).Select(l => l.ItemId).Distinct().ToList();
if (itemIds.Count == 0)
{
return result;
}
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(i => i.Id);
var ids = catalog.Keys.ToList();
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => ids.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
var fallback = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false);
var moved = new Dictionary<(DocumentFamily, long), Dictionary<long, int>>();
foreach (var line in lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null && l.Quantity != 0m))
{
if (!catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked || item.Kind != ItemKind.Goods)
{
continue;
}
if (sign != 0 && line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId
&& await MovedSignAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false) == sign)
{
continue;
}
var warehouse = line.WarehouseId ?? header.WarehouseId ?? item.WarehouseId ?? fallback;
if (warehouse is null)
{
continue;
}
var quantity = ToBase(Math.Abs(line.Quantity), line.UnitOfMeasureId, item, units);
result.Add(new StockLineInput(line.Id, item.Id, quantity, warehouse.Value, UnitCost(header, line, quantity)));
}
return result;
}
// The cost per base unit in euro of a line: its taxable amount over the quantity, at the exchange rate of the document.
private static decimal? UnitCost(DocumentHeader header, DocumentLine line, decimal baseQuantity)
{
if (baseQuantity == 0m || line.TaxableAmount == 0m)
{
return null;
}
var amount = Math.Abs(line.TaxableAmount);
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
{
amount /= header.ExchangeRate;
}
return Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
}
// How a line of another document moved the stock: 1 loaded, -1 unloaded, 0 not at all.
private static async Task<int> MovedSignAsync(
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary<long, int>> moved, CancellationToken cancellationToken)
{
var source = await StoreLineAsync(uow, sourceFamily, sourceLineId, cancellationToken).ConfigureAwait(false);
if (source is null)
{
return 0;
}
var key = (sourceFamily, source.DocumentId);
if (!moved.TryGetValue(key, out var lines))
{
lines = [];
var entries = (await uow.Repository<InventoryEntry, long>()
.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == sourceFamily && e.SourceDocumentId == source.DocumentId), cancellationToken).ConfigureAwait(false)).Items;
foreach (var entry in entries)
{
foreach (var line in (await uow.Repository<InventoryEntryLine, long>()
.ListAsync(Query.For<InventoryEntryLine>().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items)
{
if (line.SourceLineId is { } id)
{
lines[id] = Math.Sign(line.Quantity);
}
}
}
moved[key] = lines;
}
return lines.GetValueOrDefault(sourceLineId);
}
private static async Task RecomputeItemAsync(
IUnitOfWork uow, long itemId, IReadOnlyDictionary<(long, long?), decimal> committed, IReadOnlyDictionary<(long, long?), decimal> ordered, long? defaultWarehouse,
CancellationToken cancellationToken)
{
if (await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) is not { } item)
{
return;
}
var repository = uow.Repository<InventoryEntryLine, long>();
var lines = (await repository.ListAsync(
Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var invoiced = await InvoicedCostsAsync(uow, lines, cancellationToken).ConfigureAwait(false);
var history = StockCostCalculator.Run(
lines.Select(l => new CostedMovement(
l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued || invoiced.ContainsKey(l.Id), invoiced.TryGetValue(l.Id, out var cost) ? cost : l.UnitCost)),
item.StandardCost ?? 0m);
foreach (var line in lines)
{
var unitCost = history.UnitCosts[line.Id];
var value = StockCostCalculator.Value(line.Quantity, unitCost);
if (line.UnitCost != unitCost || line.Value != value)
{
line.UnitCost = unitCost;
line.Value = value;
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
}
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM item_balances WHERE item_id = {itemId}"), cancellationToken).ConfigureAwait(false);
var warehouses = history.Warehouses.Keys
.Concat(committed.Keys.Concat(ordered.Keys).Where(k => k.Item1 == itemId).Select(k => k.Item2 ?? item.WarehouseId ?? defaultWarehouse).OfType<long>())
.Distinct();
var balances = uow.Repository<ItemBalance, long>();
foreach (var warehouseId in warehouses)
{
var stock = history.Warehouses.GetValueOrDefault(warehouseId) ?? new WarehouseStock(0m, null, null);
await balances.InsertAsync(
new ItemBalance
{
ItemId = itemId,
WarehouseId = warehouseId,
OnHand = stock.OnHand,
Committed = Open(committed, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
Ordered = Open(ordered, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse),
AverageCost = history.AverageCost,
Value = StockCostCalculator.Value(stock.OnHand, history.AverageCost),
LastCost = history.LastCost,
LastLoadDate = stock.LastLoad,
LastUnloadDate = stock.LastUnload,
},
cancellationToken).ConfigureAwait(false);
}
// Only the costs: the card keeps its version, so whoever is editing it does not collide with a posting.
decimal? average = lines.Count == 0 ? item.AverageCost : history.AverageCost;
var last = history.LastCost ?? item.LastCost;
if (average != item.AverageCost || last != item.LastCost)
{
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE items SET average_cost = {average}, last_cost = {last} WHERE id = {itemId}"), cancellationToken).ConfigureAwait(false);
}
}
// The quantity still open of an item in a warehouse; the lines without a warehouse count in the usual one.
private static decimal Open(IReadOnlyDictionary<(long, long?), decimal> open, long itemId, long warehouseId, long? usual)
{
var total = open.GetValueOrDefault((itemId, warehouseId));
if (usual == warehouseId)
{
total += open.GetValueOrDefault((itemId, null));
}
return total;
}
// The cost a supplier invoice gives to the loads of the delivery notes it invoices (the difference of price, §11.5).
private static async Task<Dictionary<long, decimal>> InvoicedCostsAsync(IUnitOfWork uow, IReadOnlyList<InventoryEntryLine> lines, CancellationToken cancellationToken)
{
var result = new Dictionary<long, decimal>();
var loads = lines.Where(l => l.Quantity > 0m && l.SourceLineId is not null).ToList();
if (loads.Count == 0)
{
return result;
}
var entryIds = loads.Select(l => l.EntryId).Distinct().ToList();
var receipts = (await uow.Repository<InventoryEntry, long>()
.ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id) && e.SourceKind == DocumentKind.PurchaseDeliveryNote), cancellationToken).ConfigureAwait(false))
.Items.Select(e => e.Id).ToHashSet();
var receiptLines = loads.Where(l => receipts.Contains(l.EntryId)).ToList();
if (receiptLines.Count == 0)
{
return result;
}
var sourceIds = receiptLines.Select(l => l.SourceLineId!.Value).Distinct().ToList();
var links = (await uow.Repository<DocumentLink, long>().ListAsync(
Query.For<DocumentLink>().Where(k => k.SourceFamily == DocumentFamily.PurchaseDocument && k.TargetFamily == DocumentFamily.PurchaseDocument && sourceIds.Contains(k.SourceLineId)),
cancellationToken).ConfigureAwait(false)).Items;
foreach (var load in receiptLines)
{
decimal amount = 0m, quantity = 0m;
foreach (var link in links.Where(k => k.SourceLineId == load.SourceLineId))
{
var target = await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, link.TargetLineId, cancellationToken).ConfigureAwait(false);
var header = target is null ? null : await HeaderAsync(uow, DocumentFamily.PurchaseDocument, target.DocumentId, cancellationToken).ConfigureAwait(false);
if (target is null || header is null || header.Kind != DocumentKind.PurchaseInvoice || !DocumentStateMachine.IsInForce(header.Status) || target.Quantity == 0m)
{
continue;
}
var lineAmount = Math.Abs(target.TaxableAmount);
if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m)
{
lineAmount /= header.ExchangeRate;
}
// The invoice line in the unit of the delivery note: its share of the load is the linked quantity.
var share = Math.Abs(link.Quantity / target.Quantity);
amount += lineAmount * share;
quantity += Math.Abs(link.Quantity);
}
var source = quantity == 0m ? null : await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, load.SourceLineId!.Value, cancellationToken).ConfigureAwait(false);
if (source is null || source.Quantity == 0m)
{
continue;
}
// The load is in the base unit; the invoiced part of the delivery line is quantity / source.Quantity of it.
var baseQuantity = load.Quantity * (quantity / Math.Abs(source.Quantity));
if (baseQuantity > 0m && amount > 0m)
{
result[load.Id] = Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero);
}
}
return result;
}
// The quantities still to deliver of the open orders of a family, by item and warehouse of the line.
private static async Task<Dictionary<(long, long?), decimal>> OpenQuantitiesAsync<THeader, TLine>(IUnitOfWork uow, List<long> itemIds, CancellationToken cancellationToken)
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
var result = new Dictionary<(long, long?), decimal>();
var ids = itemIds.Select(i => (long?)i).ToList();
var lines = (await uow.Repository<TLine, long>().ListAsync(
Query.For<TLine>().Where(l => ids.Contains(l.ItemId) && !l.FulfillmentClosed), cancellationToken).ConfigureAwait(false)).Items;
if (lines.Count == 0)
{
return result;
}
var documentIds = lines.Select(l => l.DocumentId).Distinct().ToList();
var open = (await uow.Repository<THeader, long>().ListAsync(
Query.For<THeader>().Where(h => documentIds.Contains(h.Id) && (h.Status == DocumentStatus.Confirmed || h.Status == DocumentStatus.PartiallyFulfilled)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(h => h.Id);
if (open.Count == 0)
{
return result;
}
var catalog = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(i => i.Id);
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => itemIds.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items;
foreach (var line in lines)
{
if (!open.TryGetValue(line.DocumentId, out var header) || !catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked)
{
continue;
}
var residual = line.Quantity - line.FulfilledQuantity;
if (residual <= 0m)
{
continue;
}
var key = (item.Id, line.WarehouseId ?? header.WarehouseId);
result[key] = result.GetValueOrDefault(key) + ToBase(residual, line.UnitOfMeasureId, item, units);
}
return result;
}
private static Task<DocumentHeader?> HeaderAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).GetAsync(uow, id, cancellationToken);
private static Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).LinesAsync(uow, id, cancellationToken);
private static Task<DocumentLine?> StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken);
}
/// <summary>The step of a rebuild.</summary>
public enum RebuildPhase
{
/// <summary>Posting the documents.</summary>
Documents = 0,
/// <summary>Computing the items.</summary>
Items = 1,
}
/// <summary>How far a rebuild is.</summary>
/// <param name="Phase">The step.</param>
/// <param name="Done">How many done.</param>
/// <param name="Total">How many in all.</param>
public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total);
@@ -0,0 +1,42 @@
using System.Globalization;
using Khaemhat.Application.Jobs;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Inventory;
/// <summary>
/// Rebuilds the warehouse of every active company from its documents, once a week at night (SPEC §11.6): a safety net
/// that brings balances and costs back in line after imports or corrections made outside the screens.
/// </summary>
/// <param name="factory">The units of work.</param>
/// <param name="companies">The companies.</param>
public sealed class InventoryRebuildJob(IUnitOfWorkFactory factory, ICompanyRegistry companies) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "inventory.rebuild";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
int documents = 0, items = 0, done = 0;
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is CompanyStatus.Disabled)
{
continue;
}
var (d, i) = await InventoryService.RebuildCompanyAsync(factory, company.Code, null, cancellationToken).ConfigureAwait(false);
documents += d;
items += i;
done++;
}
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {documents} documenti, {items} articoli ricalcolati.");
}
}
@@ -0,0 +1,422 @@
using Khaemhat.Application.Items;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
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;
namespace Khaemhat.Application.Inventory;
/// <summary>What the stock screen asks (mockup 036).</summary>
public sealed record StockFilter
{
/// <summary>Code, description or brand.</summary>
public string? Search { get; init; }
/// <summary>One warehouse, or all together.</summary>
public long? WarehouseId { get; init; }
/// <summary>One category.</summary>
public long? CategoryId { get; init; }
/// <summary>Only the items under their minimum stock or reorder point.</summary>
public bool UnderstockOnly { get; init; }
/// <summary>Also the items with nothing on hand, committed or ordered.</summary>
public bool IncludeEmpty { get; init; }
}
/// <summary>The state of an item under its thresholds.</summary>
public enum StockLevel
{
/// <summary>Enough.</summary>
Ok = 0,
/// <summary>The available quantity reached the reorder point.</summary>
Reorder = 1,
/// <summary>The available quantity is under the minimum stock.</summary>
Understock = 2,
/// <summary>Nothing left, or less than nothing.</summary>
Out = 3,
}
/// <summary>A row of the stock screen: an item in one warehouse or in all.</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="CategoryId">Its category.</param>
/// <param name="UnitOfMeasureId">Its base unit.</param>
/// <param name="OnHand">On hand.</param>
/// <param name="Committed">Committed to customers.</param>
/// <param name="Ordered">Ordered from suppliers.</param>
/// <param name="Available">On hand less committed.</param>
/// <param name="MinimumStock">The minimum stock.</param>
/// <param name="ReorderPoint">The reorder point.</param>
/// <param name="AverageCost">The weighted average cost (none without the permission on costs).</param>
/// <param name="Value">The value at the average (none without the permission).</param>
/// <param name="LastLoad">The last load.</param>
/// <param name="LastUnload">The last unload.</param>
/// <param name="Level">The state under the thresholds.</param>
public sealed record StockRow(
long ItemId, string Code, string Description, long? CategoryId, long? UnitOfMeasureId, decimal OnHand, decimal Committed, decimal Ordered, decimal Available,
decimal? MinimumStock, decimal? ReorderPoint, decimal? AverageCost, decimal? Value, DateOnly? LastLoad, DateOnly? LastUnload, StockLevel Level);
/// <summary>A movement of an item, with the balance after it.</summary>
/// <param name="Id">The movement.</param>
/// <param name="Date">The date.</param>
/// <param name="Family">The family of the document.</param>
/// <param name="DocumentId">The document.</param>
/// <param name="Kind">Its kind.</param>
/// <param name="Number">Its number.</param>
/// <param name="ReasonCode">The warehouse reason.</param>
/// <param name="PartyName">The customer or supplier.</param>
/// <param name="WarehouseId">The warehouse.</param>
/// <param name="Quantity">Positive loads, negative unloads.</param>
/// <param name="UnitCost">The cost (none without the permission).</param>
/// <param name="Value">The value (none without the permission).</param>
/// <param name="Balance">The balance after the movement, in the warehouses shown.</param>
public sealed record MovementRow(
long Id, DateOnly Date, DocumentFamily? Family, long? DocumentId, DocumentKind? Kind, string? Number, string? ReasonCode, string? PartyName, long WarehouseId,
decimal Quantity, decimal? UnitCost, decimal? Value, decimal Balance);
/// <summary>The value of an item at a date (closing stock, libro inventari).</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="Quantity">On hand at the date.</param>
/// <param name="UnitCost">The cost of the method.</param>
/// <param name="Value">Quantity times cost.</param>
/// <param name="AbcClass">A (the first 80% of the value), B (up to 95%) or C.</param>
public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass);
/// <summary>
/// The warehouse as people read it (SPEC §11.6, mockups 036-037): stock and availability, the movements of an item,
/// the value at a date. The balances are kept by <see cref="InventoryPoster"/>; this service only reads them.
/// </summary>
/// <remarks>Permission <c>inventory.stock.read</c>, movements <c>inventory.entry.read</c>; costs only with <c>items.cost.read</c>.</remarks>
public sealed class InventoryService
{
/// <summary>Permission to read the stock.</summary>
public const string StockPermission = "inventory.stock.read";
/// <summary>Permission to read the movements.</summary>
public const string EntryReadPermission = "inventory.entry.read";
/// <summary>Permission to post movements, stock takes and the rebuild.</summary>
public const string PostPermission = "inventory.entry.post";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
_factory = factory;
_permissions = permissions;
}
/// <summary>The stock of the items, in a warehouse or in all.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">What to show.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, by code.</returns>
public async Task<IReadOnlyList<StockRow>> StockAsync(Actor actor, string companyCode, StockFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
if (filter.CategoryId is { } category)
{
query = query.Where(i => i.CategoryId == category);
}
if (filter.Search?.Trim() is { Length: > 0 } text)
{
query = query.Where(i => i.Code.Contains(text) || i.Description.Contains(text) || (i.Brand != null && i.Brand.Contains(text)));
}
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false);
var rows = new List<StockRow>();
foreach (var item in items)
{
var mine = balances.GetValueOrDefault(item.Id) ?? [];
var row = RowOf(item, mine, costs);
if (!filter.IncludeEmpty && mine.Count == 0)
{
// No movement and no order: shown only when asked, or when it has a minimum to keep.
if (row.Level == StockLevel.Ok)
{
continue;
}
}
if (filter.UnderstockOnly && row.Level == StockLevel.Ok)
{
continue;
}
rows.Add(row);
}
return rows;
}
/// <summary>The balances of an item in each warehouse.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="itemId">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The balances, costs hidden without the permission.</returns>
public async Task<IReadOnlyList<ItemBalance>> BalancesAsync(Actor actor, string companyCode, long itemId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items;
if (!costs)
{
foreach (var row in rows)
{
row.AverageCost = 0m;
row.Value = 0m;
row.LastCost = null;
}
}
return rows;
}
/// <summary>The movements of an item in a period, with the running balance (mockup 036, dialog of the item).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="itemId">The item.</param>
/// <param name="warehouseId">One warehouse, or all.</param>
/// <param name="from">The first day, or the beginning.</param>
/// <param name="to">The last day, or today.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movements, oldest first; the balance starts from what was on hand before <paramref name="from"/>.</returns>
public async Task<IReadOnlyList<MovementRow>> MovementsAsync(
Actor actor, string companyCode, long itemId, long? warehouseId, DateOnly? from, DateOnly? to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EntryReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId);
if (warehouseId is { } warehouse)
{
query = query.Where(l => l.WarehouseId == warehouse);
}
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(query.OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var entryIds = lines.Select(l => l.EntryId).Distinct().ToList();
var entries = entryIds.Count == 0 ? [] : (await uow.Repository<InventoryEntry, long>().ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(e => e.Id);
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id, r => r.Code);
var partyIds = entries.Values.Where(e => e.PartyId is not null).Select(e => e.PartyId!.Value).Distinct().ToList();
var parties = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
var result = new List<MovementRow>();
var balance = 0m;
foreach (var line in lines)
{
balance += line.Quantity;
if ((from is { } first && line.EntryDate < first) || (to is { } last && line.EntryDate > last))
{
continue;
}
var entry = entries.GetValueOrDefault(line.EntryId);
result.Add(new MovementRow(
line.Id, line.EntryDate, entry?.SourceFamily, entry?.SourceDocumentId, entry?.SourceKind, entry?.SourceNumber,
entry?.InventoryReasonId is { } r ? reasons.GetValueOrDefault(r) : null,
entry?.PartyId is { } p ? parties.GetValueOrDefault(p) : null,
line.WarehouseId, line.Quantity, costs ? line.UnitCost : null, costs ? line.Value : null, balance));
}
return result;
}
/// <summary>
/// The value of the stock at a date (closing stock, libro inventari): the history of each item up to that day,
/// valued with a method, with its ABC class by value.
/// </summary>
/// <param name="actor">Who reads: needs the permission on costs too.</param>
/// <param name="companyCode">The company.</param>
/// <param name="date">The day.</param>
/// <param name="warehouseId">One warehouse, or all.</param>
/// <param name="method">The cost used.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The items with something on hand, by value.</returns>
public async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
Actor actor, string companyCode, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken = default)
{
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);
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;
var itemIds = lines.Select(l => l.ItemId).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 rows = new List<ValuationRow>();
foreach (var group in lines.GroupBy(l => l.ItemId))
{
if (!items.TryGetValue(group.Key, out var item))
{
continue;
}
// The costs written on the movements are those of the last run: the history up to the day gives the average then.
var history = StockCostCalculator.Run(group.Select(l => new CostedMovement(l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued, l.Valued ? l.UnitCost : 0m)), item.StandardCost ?? 0m);
var quantity = warehouseId is { } w ? history.Warehouses.GetValueOrDefault(w)?.OnHand ?? 0m : history.OnHand;
if (quantity == 0m)
{
continue;
}
var cost = method switch
{
StockValuationMethod.LastCost => history.LastCost ?? history.AverageCost,
StockValuationMethod.StandardCost => item.StandardCost ?? history.AverageCost,
_ => history.AverageCost,
};
rows.Add(new ValuationRow(item.Id, item.Code, item.Description, quantity, cost, StockCostCalculator.Value(quantity, cost), 'C'));
}
return Classify(rows);
}
/// <summary>The items under their thresholds, the most urgent first (dashboard widget and reorder).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="limit">How many.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<StockRow>> UnderstockAsync(Actor actor, string companyCode, int limit = 10, CancellationToken cancellationToken = default)
{
var rows = await StockAsync(actor, companyCode, new StockFilter { UnderstockOnly = true }, cancellationToken).ConfigureAwait(false);
return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)];
}
/// <summary>
/// Rebuilds the warehouse of the company from its documents (SPEC §11.6): every movement is written again and every
/// item computed again, in one transaction.
/// </summary>
/// <param name="actor">Who rebuilds: needs <c>inventory.entry.post</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="progress">How far it is.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents posted and the items computed.</returns>
public async Task<(int Documents, int Items)> RebuildAsync(Actor actor, string companyCode, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PostPermission, cancellationToken).ConfigureAwait(false);
return await RebuildCompanyAsync(_factory, company, progress, cancellationToken).ConfigureAwait(false);
}
/// <summary>Rebuilds the warehouse of a company, without checks (the scheduled job).</summary>
/// <param name="factory">The units of work.</param>
/// <param name="company">The company.</param>
/// <param name="progress">How far it is.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The documents posted and the items computed.</returns>
internal static async Task<(int Documents, int Items)> RebuildCompanyAsync(
IUnitOfWorkFactory factory, string company, IProgress<RebuildProgress>? progress, CancellationToken cancellationToken)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var result = await InventoryPoster.RebuildAsync(uow, progress, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return result;
}
/// <summary>
/// The level of an item: out when nothing is available (or less than nothing), under stock below the minimum,
/// to reorder when what is available and on order no longer covers the reorder point.
/// </summary>
/// <param name="available">On hand less committed.</param>
/// <param name="ordered">Ordered from suppliers.</param>
/// <param name="minimum">The minimum stock.</param>
/// <param name="reorderPoint">The reorder point.</param>
/// <returns>The level.</returns>
public static StockLevel LevelOf(decimal available, decimal ordered, decimal? minimum, decimal? reorderPoint)
{
var watched = minimum is not null || reorderPoint is not null;
if (available < 0m || (watched && available <= 0m))
{
return StockLevel.Out;
}
if (minimum is { } min && available < min)
{
return StockLevel.Understock;
}
return reorderPoint is { } point && available + ordered <= point ? StockLevel.Reorder : StockLevel.Ok;
}
/// <summary>Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest.</summary>
/// <param name="rows">The rows.</param>
/// <returns>The rows by value, with their class.</returns>
public static IReadOnlyList<ValuationRow> Classify(IEnumerable<ValuationRow> rows)
{
ArgumentNullException.ThrowIfNull(rows);
var sorted = rows.OrderByDescending(r => r.Value).ThenBy(r => r.Code, StringComparer.Ordinal).ToList();
var total = sorted.Where(r => r.Value > 0m).Sum(r => r.Value);
var running = 0m;
var result = new List<ValuationRow>(sorted.Count);
foreach (var row in sorted)
{
// The class of an item is where its value starts: the first item is always A.
var share = total <= 0m ? 1m : running / total;
running += Math.Max(row.Value, 0m);
result.Add(row with { AbcClass = share < 0.80m ? 'A' : share < 0.95m ? 'B' : 'C' });
}
return result;
}
internal static StockRow RowOf(Item item, IReadOnlyList<ItemBalance> balances, bool costs)
{
var onHand = balances.Sum(b => b.OnHand);
var committed = balances.Sum(b => b.Committed);
var ordered = balances.Sum(b => b.Ordered);
var available = onHand - committed;
var average = balances.Count > 0 ? balances[0].AverageCost : item.AverageCost ?? 0m;
return new StockRow(
item.Id, item.Code, item.Description, item.CategoryId, item.UnitOfMeasureId, onHand, committed, ordered, available, item.MinimumStock, item.ReorderPoint,
costs ? average : null, costs ? balances.Sum(b => b.Value) : null,
balances.Max(b => b.LastLoadDate), balances.Max(b => b.LastUnloadDate),
LevelOf(available, ordered, item.MinimumStock, item.ReorderPoint));
}
internal static async Task<Dictionary<long, List<ItemBalance>>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken)
{
var query = Query.For<ItemBalance>();
if (warehouseId is { } warehouse)
{
query = query.Where(b => b.WarehouseId == warehouse);
}
return (await uow.Repository<ItemBalance, long>().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items
.GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList());
}
private async Task<bool> CostsAsync(Actor actor, CancellationToken cancellationToken) =>
(await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
}
@@ -0,0 +1,183 @@
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.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>An item to reorder (mockup 039).</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="UnitOfMeasureId">Its unit.</param>
/// <param name="Available">On hand less committed.</param>
/// <param name="Ordered">Already ordered.</param>
/// <param name="MinimumStock">The minimum stock.</param>
/// <param name="ReorderPoint">The reorder point.</param>
/// <param name="Quantity">The quantity proposed.</param>
/// <param name="SupplierId">The usual supplier, if any.</param>
/// <param name="SupplierName">Its name.</param>
/// <param name="Price">Its price.</param>
/// <param name="ExpectedDate">When it would arrive, from the lead time.</param>
public sealed record ReorderProposal(
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal Available, decimal Ordered, decimal? MinimumStock, decimal? ReorderPoint,
decimal Quantity, long? SupplierId, string? SupplierName, decimal? Price, DateOnly? ExpectedDate);
/// <summary>A proposal the user accepts, perhaps with another quantity or supplier.</summary>
/// <param name="ItemId">The item.</param>
/// <param name="SupplierId">The supplier.</param>
/// <param name="Quantity">The quantity.</param>
public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity);
/// <summary>
/// The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the
/// reorder point (or the minimum stock), with the quantity to order (the lot, or what brings back to the threshold, at
/// least the minimum of the supplier) and the usual supplier; accepted, the proposals become draft supplier orders,
/// one per supplier.
/// </summary>
public sealed class ReorderService
{
/// <summary>Error: a chosen line without a supplier or a quantity.</summary>
public const string ChoiceInvalid = "inventory.reorder.choice-invalid";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly DocumentEngine _engine;
private readonly DocumentEditor _editor;
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="engine">The document engine.</param>
/// <param name="editor">The editor (prices and terms of the supplier).</param>
/// <param name="clock">The clock.</param>
public ReorderService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, DocumentEditor editor, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(editor);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_engine = engine;
_editor = editor;
_clock = clock;
}
/// <summary>The items to reorder, by supplier and code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The proposals.</returns>
public async Task<IReadOnlyList<ReorderProposal>> ProposalsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.StockPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(
Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled && (i.MinimumStock != null || i.ReorderPoint != null)).OrderBy(i => i.Code), cancellationToken)
.ConfigureAwait(false)).Items;
if (items.Count == 0)
{
return [];
}
var balances = await InventoryService.BalancesByItemAsync(uow, null, cancellationToken).ConfigureAwait(false);
var ids = items.Select(i => i.Id).ToList();
var suppliers = (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => ids.Contains(s.ItemId)), cancellationToken)
.ConfigureAwait(false)).Items.GroupBy(s => s.ItemId).ToDictionary(g => g.Key, g => g.OrderByDescending(s => s.IsDefault).ThenBy(s => s.Id).First());
var partyIds = suppliers.Values.Select(s => s.PartyId).Distinct().ToList();
var names = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
var result = new List<ReorderProposal>();
foreach (var item in items)
{
var mine = balances.GetValueOrDefault(item.Id) ?? [];
var available = mine.Sum(b => b.OnHand - b.Committed);
var ordered = mine.Sum(b => b.Ordered);
var supplier = suppliers.GetValueOrDefault(item.Id);
var quantity = Quantity(available + ordered, item.MinimumStock, item.ReorderPoint, item.ReorderLot, supplier?.MinimumQuantity);
if (quantity <= 0m)
{
continue;
}
result.Add(new ReorderProposal(
item.Id, item.Code, item.Description, item.UnitOfMeasureId, available, ordered, item.MinimumStock, item.ReorderPoint, quantity,
supplier?.PartyId, supplier is null ? null : names.GetValueOrDefault(supplier.PartyId), supplier?.Price ?? item.LastCost,
supplier?.LeadTimeDays is { } days ? today.AddDays(days) : null));
}
return [.. result.OrderBy(r => r.SupplierName is null).ThenBy(r => r.SupplierName, StringComparer.CurrentCulture).ThenBy(r => r.Code, StringComparer.Ordinal)];
}
/// <summary>
/// The quantity to order: nothing while what is available and ordered covers the reorder point (or the minimum);
/// otherwise the lot of the item, or what brings back to the higher of the two thresholds, at least the minimum
/// quantity of the supplier.
/// </summary>
/// <param name="cover">Available plus ordered.</param>
/// <param name="minimum">The minimum stock.</param>
/// <param name="reorderPoint">The reorder point.</param>
/// <param name="lot">The reorder lot.</param>
/// <param name="supplierMinimum">The minimum of the supplier.</param>
/// <returns>The quantity.</returns>
public static decimal Quantity(decimal cover, decimal? minimum, decimal? reorderPoint, decimal? lot, decimal? supplierMinimum)
{
var threshold = reorderPoint ?? minimum;
if (threshold is not { } point || cover > point || (reorderPoint is null && cover >= point))
{
return 0m;
}
var target = Math.Max(minimum ?? 0m, reorderPoint ?? 0m);
var quantity = lot is > 0m ? lot.Value : Math.Max(target - cover, 0m);
if (lot is > 0m && cover + quantity < target)
{
// One lot is not enough: as many lots as it takes.
quantity = Math.Ceiling((target - cover) / lot.Value) * lot.Value;
}
return Math.Max(quantity, supplierMinimum ?? 0m);
}
/// <summary>Creates the draft supplier orders of the chosen proposals, one per supplier.</summary>
/// <param name="actor">Who orders: needs <c>purchases.order.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="choices">The proposals accepted.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The orders, saved as drafts.</returns>
public async Task<IReadOnlyList<DocumentRecord>> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList<ReorderChoice> choices, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(choices);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "purchases.order.write", cancellationToken).ConfigureAwait(false);
if (choices.Any(c => c.Quantity <= 0m || c.SupplierId <= 0))
{
throw new ValidationFailedException([":" + ChoiceInvalid]);
}
var result = new List<DocumentRecord>();
foreach (var group in choices.GroupBy(c => c.SupplierId))
{
var order = await _engine.NewAsync(actor, company, "OF", cancellationToken).ConfigureAwait(false);
await _editor.ApplyPartyAsync(actor, company, order, group.Key, cancellationToken).ConfigureAwait(false);
foreach (var choice in group)
{
var line = new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = choice.ItemId, Quantity = choice.Quantity };
order.Lines.Add(line);
await _editor.FillLineAsync(actor, company, order, line, choice.ItemId, cancellationToken).ConfigureAwait(false);
line.Quantity = choice.Quantity;
}
result.Add(await _engine.SaveAsync(actor, company, order, cancellationToken).ConfigureAwait(false));
}
return result;
}
}
@@ -0,0 +1,405 @@
using System.Globalization;
using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Inventory;
/// <summary>A line of a stock take with its item.</summary>
/// <param name="Line">The line.</param>
/// <param name="Code">The code of the item.</param>
/// <param name="Description">Its description.</param>
/// <param name="UnitOfMeasureId">Its base unit.</param>
public sealed record StockTakeLineView(StockTakeLine Line, string Code, string Description, long? UnitOfMeasureId);
/// <summary>A stock take with its lines.</summary>
/// <param name="Take">The stock take.</param>
/// <param name="Lines">Its lines, by code.</param>
public sealed record StockTakeView(StockTake Take, IReadOnlyList<StockTakeLineView> Lines)
{
/// <summary>How many lines are counted.</summary>
public int Counted => Lines.Count(l => l.Line.CountedQuantity is not null);
/// <summary>The value of the differences at the cost of the lines.</summary>
public decimal DifferenceValue => Lines.Sum(l => StockCostCalculator.Value(l.Line.Difference, l.Line.UnitCost));
}
/// <summary>What the import of the counts found.</summary>
/// <param name="Applied">The lines counted.</param>
/// <param name="Unknown">The codes not on the list, with their row.</param>
public sealed record StockCountImport(int Applied, IReadOnlyList<string> Unknown);
/// <summary>
/// The physical inventory (SPEC §11.6, mockup 038): a list of the items of a warehouse with what the books say at the
/// date, the counts typed or read from a file, and the posting that writes the differences as two warehouse movements
/// (gains with reason INVP, losses with INVN) through the document engine.
/// </summary>
/// <remarks>Permissions <c>inventory.entry.read</c>, <c>write</c> (lists and counts) and <c>post</c>.</remarks>
public sealed class StockTakeService
{
/// <summary>Error: the stock take is no longer open.</summary>
public const string NotOpen = "inventory.stock-take.not-open";
/// <summary>Error: nothing is counted.</summary>
public const string NothingCounted = "inventory.stock-take.nothing-counted";
/// <summary>Error: a counted quantity below zero.</summary>
public const string NegativeCount = "inventory.stock-take.negative";
/// <summary>Error: the reasons of the adjustments are missing from the base tables.</summary>
public const string ReasonMissing = "inventory.stock-take.reason-missing";
/// <summary>The reason of the gains.</summary>
public const string GainReason = "INVP";
/// <summary>The reason of the losses.</summary>
public const string LossReason = "INVN";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly DocumentEngine _engine;
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="engine">The document engine, for the adjustments.</param>
/// <param name="clock">The clock.</param>
public StockTakeService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_engine = engine;
_clock = clock;
}
/// <summary>The stock takes, the latest first.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock takes.</returns>
public async Task<IReadOnlyList<StockTake>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<StockTake, long>().ListAsync(Query.For<StockTake>().OrderByDescending(t => t.TakeDate).OrderByDescending(t => t.Id), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// <summary>A stock take with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock take, or none.</returns>
public async Task<StockTakeView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, 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>
/// Opens a stock take: the stocked goods of the warehouse (of a category, if given) with the quantity the books
/// give at the date and the average cost.
/// </summary>
/// <param name="actor">Who opens it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="warehouseId">The warehouse.</param>
/// <param name="date">The day of the count.</param>
/// <param name="categoryId">Only a category.</param>
/// <param name="description">A description; the warehouse and date when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new stock take.</returns>
public async Task<StockTakeView> CreateAsync(
Actor actor, string companyCode, long warehouseId, DateOnly date, long? categoryId, string? description, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var warehouse = await uow.Repository<Warehouse, long>().GetAsync(warehouseId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(StockTake.WarehouseId) + ":" + "inventory.warehouse.missing"]);
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
if (categoryId is { } category)
{
query = query.Where(i => i.CategoryId == category);
}
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
var book = await BookAsync(uow, warehouseId, date, cancellationToken).ConfigureAwait(false);
var balances = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.WarehouseId == warehouseId), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(b => b.ItemId);
var take = new StockTake
{
TakeDate = date,
WarehouseId = warehouseId,
CategoryId = categoryId,
Description = string.IsNullOrWhiteSpace(description)
? "Inventario " + warehouse.Code + " al " + date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
: description.Trim()[..Math.Min(description.Trim().Length, 100)],
Status = StockTakeStatus.Open,
};
await uow.Repository<StockTake, long>().InsertAsync(take, cancellationToken).ConfigureAwait(false);
var lines = uow.Repository<StockTakeLine, long>();
var order = 0;
foreach (var item in items)
{
await lines.InsertAsync(
new StockTakeLine
{
StockTakeId = take.Id,
ItemId = item.Id,
BookQuantity = book.GetValueOrDefault(item.Id),
UnitCost = balances.TryGetValue(item.Id, out var balance) ? balance.AverageCost : item.AverageCost ?? item.StandardCost ?? 0m,
SortOrder = ++order,
},
cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return (await ViewAsync(uow, take.Id, cancellationToken).ConfigureAwait(false))!;
}
/// <summary>Writes the counts typed on the list; an empty count means not counted yet.</summary>
/// <param name="actor">Who counts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="counts">The counted quantity of each line, by line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock take.</returns>
public async Task<StockTakeView> SaveCountsAsync(
Actor actor, string companyCode, long id, IReadOnlyDictionary<long, decimal?> counts, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(counts);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
if (counts.Values.Any(v => v < 0m))
{
throw new ValidationFailedException(["CountedQuantity:" + NegativeCount]);
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<StockTakeLine, long>();
foreach (var line in (await repository.ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id), cancellationToken).ConfigureAwait(false)).Items)
{
if (counts.TryGetValue(line.Id, out var counted) && counted != line.CountedQuantity)
{
line.CountedQuantity = counted;
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
}
/// <summary>
/// Reads the counts from a text file (from a barcode reader or a spreadsheet): one row per item, the code and the
/// quantity separated by semicolon, tab or comma; a header and empty rows are skipped; the same code twice adds up.
/// </summary>
/// <param name="actor">Who counts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="content">The file.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many lines were counted and the codes not on the list.</returns>
public async Task<StockCountImport> ImportCountsAsync(Actor actor, string companyCode, long id, Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
var byCode = view.Lines.ToDictionary(l => l.Code, l => l.Line.Id, StringComparer.OrdinalIgnoreCase);
var counts = new Dictionary<long, decimal?>();
var unknown = new List<string>();
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
var row = 0;
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } text)
{
row++;
if (ParseCount(text) is not { } parsed)
{
continue;
}
var (code, quantity) = parsed;
if (byCode.TryGetValue(code, out var lineId))
{
counts[lineId] = (counts.GetValueOrDefault(lineId) ?? 0m) + quantity;
}
else
{
unknown.Add(row.ToString(CultureInfo.InvariantCulture) + ": " + code);
}
}
if (counts.Count > 0)
{
await SaveCountsAsync(actor, companyCode, id, counts, cancellationToken).ConfigureAwait(false);
}
return new StockCountImport(counts.Count, unknown);
}
/// <summary>
/// Posts a stock take: the counted lines that differ from the books become a movement of gains (INVP, at the cost
/// of the line) and one of losses (INVN), confirmed at the date of the count. The lines not counted are left as
/// they are.
/// </summary>
/// <param name="actor">Who posts: needs <c>inventory.entry.post</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stock take as posted.</returns>
public async Task<StockTakeView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.PostPermission, cancellationToken).ConfigureAwait(false);
StockTakeView view;
long? gainReason, lossReason;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
view = (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items;
gainReason = reasons.FirstOrDefault(r => r.Code == GainReason)?.Id;
lossReason = reasons.FirstOrDefault(r => r.Code == LossReason)?.Id;
}
if (view.Counted == 0)
{
throw new ValidationFailedException([":" + NothingCounted]);
}
if (gainReason is null || lossReason is null)
{
throw new ValidationFailedException([":" + ReasonMissing]);
}
var take = view.Take;
var gains = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference > 0m).ToList();
var losses = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference < 0m).ToList();
take.AdjustmentDocumentId = await AdjustAsync(actor, company, take, gainReason.Value, gains, cancellationToken).ConfigureAwait(false);
take.LossDocumentId = await AdjustAsync(actor, company, take, lossReason.Value, losses, cancellationToken).ConfigureAwait(false);
take.Status = StockTakeStatus.Posted;
take.PostedAt = _clock.GetUtcNow().UtcDateTime;
take.PostedBy = actor.UserName;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
}
}
/// <summary>Cancels an open stock take; its counts stay for the record.</summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The stock take.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var take = await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
take.Status = StockTakeStatus.Cancelled;
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
}
/// <summary>A code and a quantity from a row of a count file, or none for a header or an empty row.</summary>
/// <param name="text">The row.</param>
/// <returns>The code and the quantity.</returns>
public static (string Code, decimal Quantity)? ParseCount(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
var separator = text.Contains(';', StringComparison.Ordinal) ? ';' : text.Contains('\t', StringComparison.Ordinal) ? '\t' : ',';
var parts = text.Split(separator, StringSplitOptions.TrimEntries);
if (parts.Length < 2 || parts[0].Length == 0)
{
return null;
}
var number = parts[1].Trim('"');
// With a comma as separator the quantity is in the invariant form; otherwise the Italian one is accepted too.
var parsed = separator == ','
? decimal.TryParse(number, NumberStyles.Number, CultureInfo.InvariantCulture, out var value)
: decimal.TryParse(number.Replace(".", string.Empty, StringComparison.Ordinal), NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"), out value);
return parsed && value >= 0m ? (parts[0].Trim('"'), value) : null;
}
// The quantity of each item in a warehouse at the end of a day.
internal static async Task<Dictionary<long, decimal>> BookAsync(IUnitOfWork uow, long warehouseId, DateOnly date, CancellationToken cancellationToken) =>
(await uow.Repository<InventoryEntryLine, long>().ListAsync(
Query.For<InventoryEntryLine>().Where(l => l.WarehouseId == warehouseId && l.EntryDate <= date), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(l => l.ItemId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity));
private async Task<long?> AdjustAsync(
Actor actor, string company, StockTake take, long reasonId, List<StockTakeLineView> lines, CancellationToken cancellationToken)
{
if (lines.Count == 0)
{
return null;
}
var entry = await _engine.NewAsync(actor, company, "MM", cancellationToken).ConfigureAwait(false);
entry.Header.DocumentDate = take.TakeDate;
entry.Header.InventoryReasonId = reasonId;
entry.Header.WarehouseId = take.WarehouseId;
entry.Header.ExternalReference = take.Description.Length > 40 ? take.Description[..40] : take.Description;
entry.Header.IsDemo = take.IsDemo;
foreach (var line in lines)
{
entry.Lines.Add(new InventoryDocumentLine
{
Kind = DocumentLineKind.Item,
ItemId = line.Line.ItemId,
Description = line.Description,
UnitOfMeasureId = line.UnitOfMeasureId,
Quantity = Math.Abs(line.Line.Difference),
Price = line.Line.UnitCost,
WarehouseId = take.WarehouseId,
});
}
entry = await _engine.SaveAsync(actor, company, entry, cancellationToken).ConfigureAwait(false);
return (await _engine.ConfirmAsync(actor, company, DocumentFamily.InventoryDocument, entry.Header.Id, cancellationToken).ConfigureAwait(false)).Header.Id;
}
private static async Task<StockTake> OpenTakeAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
var take = await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
return take.Status == StockTakeStatus.Open ? take : throw new ValidationFailedException([":" + NotOpen]);
}
private static async Task<StockTakeView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } take)
{
return null;
}
var lines = (await uow.Repository<StockTakeLine, long>().ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id).OrderBy(l => l.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
var ids = lines.Select(l => l.ItemId).Distinct().ToList();
var items = ids.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(i => i.Id);
return new StockTakeView(take, [.. lines.Select(l => items.TryGetValue(l.ItemId, out var item)
? new StockTakeLineView(l, item.Code, item.Description, item.UnitOfMeasureId)
: new StockTakeLineView(l, "?", string.Empty, null))]);
}
}
@@ -50,7 +50,7 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
/// </summary>
public sealed class JobScheduler
{
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4, warehouse rebuild from M6).</summary>
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
[
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
@@ -58,6 +58,8 @@ public sealed class JobScheduler
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600),
new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800),
];
private readonly IUnitOfWorkFactory _factory;
@@ -0,0 +1,562 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>An entry with its lines and VAT lines.</summary>
/// <param name="Entry">The entry.</param>
/// <param name="Lines">The lines.</param>
/// <param name="Vat">The VAT lines.</param>
/// <param name="PartyName">The name of the customer or supplier of the entry.</param>
public sealed record EntryView(GlEntry Entry, IReadOnlyList<GlEntryLine> Lines, IReadOnlyList<GlEntryVat> Vat, string? PartyName)
{
/// <summary>Debit minus credit.</summary>
public decimal Difference => Lines.Sum(l => l.Debit - l.Credit);
}
/// <summary>An entry as the journal lists it.</summary>
/// <param name="Entry">The entry.</param>
/// <param name="PartyName">The customer or supplier.</param>
public sealed record EntryRow(GlEntry Entry, string? PartyName);
/// <summary>What the journal list shows.</summary>
/// <param name="From">From this day.</param>
/// <param name="To">Up to this day.</param>
/// <param name="Status">Only this state.</param>
/// <param name="TemplateCode">Only this template.</param>
/// <param name="Text">Text in the description or the document number.</param>
/// <param name="Offset">The first row.</param>
/// <param name="Limit">How many rows.</param>
public sealed record EntryFilter(
DateOnly? From = null, DateOnly? To = null, GlEntryStatus? Status = null, string? TemplateCode = null, string? Text = null, int Offset = 0, int Limit = 50);
/// <summary>An entry typed in the journal.</summary>
/// <param name="Id">The entry, for a change.</param>
/// <param name="EntryDate">The date of registration.</param>
/// <param name="Description">The description.</param>
/// <param name="Lines">The lines.</param>
public sealed record EntryInput(long? Id, DateOnly EntryDate, string Description, IReadOnlyList<EntryLineDraft> Lines)
{
/// <summary>The template.</summary>
public long? JournalTemplateId { get; init; }
/// <summary>The date of competence.</summary>
public DateOnly? CompetenceDate { get; init; }
/// <summary>The number of the document.</summary>
public string? DocumentNumber { get; init; }
/// <summary>The date of the document.</summary>
public DateOnly? DocumentDate { get; init; }
/// <summary>The customer or supplier.</summary>
public long? PartyId { get; init; }
/// <summary>The VAT register.</summary>
public long? VatRegisterId { get; init; }
/// <summary>The VAT date.</summary>
public DateOnly? VatDate { get; init; }
/// <summary>The VAT lines.</summary>
public IReadOnlyList<EntryVatDraft> Vat { get; init; } = [];
/// <summary>Notes.</summary>
public string? Notes { get; init; }
/// <summary>Post it (it must balance) rather than keep it as a draft.</summary>
public bool Post { get; init; }
}
/// <summary>A journal template with its lines, for the guided entry.</summary>
/// <param name="Template">The template.</param>
/// <param name="Lines">Its lines.</param>
public sealed record TemplateView(JournalTemplate Template, IReadOnlyList<JournalTemplateLine> Lines);
/// <summary>
/// The journal (prima nota, SPEC §11.7, issue #63, mockups 040-041, ADR 0036): drafts that may not balance, posted
/// entries (provvisorie) numbered per year in the order of registration, final entries (definitive) numbered on the
/// general journal in date order and never changed again; a reversal corrects them. The guided entry starts from the
/// lines of a template; the manual one shows the imbalance while it is typed. The period must be open (for VAT too when
/// the entry has VAT lines). Entries of documents change only through their document.
/// </summary>
public sealed class JournalEntryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly FiscalYearService _fiscal;
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="fiscal">The fiscal calendar.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public JournalEntryService(IUnitOfWorkFactory factory, PermissionService permissions, FiscalYearService fiscal, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_fiscal = fiscal;
_audit = audit;
_clock = clock;
}
/// <summary>The entries, the latest first.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter and the page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page and the total.</returns>
public async Task<(IReadOnlyList<EntryRow> Rows, int Total)> ListAsync(Actor actor, string companyCode, EntryFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<GlEntry>();
if (filter.From is { } from)
{
query = query.Where(e => e.EntryDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(e => e.EntryDate <= to);
}
if (filter.Status is { } status)
{
query = query.Where(e => e.Status == status);
}
if (!string.IsNullOrWhiteSpace(filter.TemplateCode))
{
var code = filter.TemplateCode;
query = query.Where(e => e.TemplateCode == code);
}
if (!string.IsNullOrWhiteSpace(filter.Text))
{
var text = filter.Text.Trim();
query = query.Where(e => e.Description.Contains(text) || e.DocumentNumber!.Contains(text) || e.EntryNumber!.Contains(text));
}
var repository = uow.Repository<GlEntry, long>();
var total = await repository.CountAsync(query, cancellationToken).ConfigureAwait(false);
var page = (await repository.ListAsync(
query.OrderByDescending(e => e.EntryDate).OrderByDescending(e => e.Id).Page(Math.Max(0, filter.Offset), Math.Clamp(filter.Limit, 1, 500)),
cancellationToken).ConfigureAwait(false)).Items;
var names = await PartyNamesAsync(uow, page.Select(e => e.PartyId), cancellationToken).ConfigureAwait(false);
return ([.. page.Select(e => new EntryRow(e, e.PartyId is { } p && names.TryGetValue(p, out var n) ? n : null))], total);
}
/// <summary>An entry with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or none.</returns>
public async Task<EntryView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, 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>The journal templates with their lines, for the guided entry.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The active templates, by code.</returns>
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().Where(t => !t.Disabled).OrderBy(t => t.Code), cancellationToken)
.ConfigureAwait(false)).Items;
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
}
/// <summary>
/// Saves an entry typed in the journal: a draft may not balance, a posted entry must and gets its number. Final
/// entries and entries of documents cannot change.
/// </summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry as saved.</returns>
public async Task<EntryView> SaveAsync(Actor actor, string companyCode, EntryInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
if (input.EntryDate == default)
{
throw new ValidationFailedException(["EntryDate:" + LedgerErrors.DateRequired]);
}
if (input.Post)
{
await _fiscal.DemandOpenAsync(company, input.EntryDate, input.Vat.Count > 0 ? PeriodUse.Vat : PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
}
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entries = uow.Repository<GlEntry, long>();
GlEntry? before = null;
if (input.Id is { } existingId)
{
before = await entries.GetAsync(existingId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (before.Status == GlEntryStatus.Final)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
}
if (before.Source == GlEntrySource.Document)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
}
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
var lines = input.Lines.Where(l => l.AccountId is not null || l.Debit != 0m || l.Credit != 0m).ToList();
var errors = JournalEntryValidator.Check(
input.Description,
[.. lines.Select(l => new EntryLineCheck(l.AccountId, l.PartyId, l.Debit, l.Credit))],
input.Vat.Count,
input.VatRegisterId is not null,
LedgerStore.Rules(accounts),
input.Post).ToList();
if (input.Post)
{
await CheckFinalOrderAsync(uow, input.EntryDate, errors, cancellationToken).ConfigureAwait(false);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var template = input.JournalTemplateId is { } templateId
? await uow.Repository<JournalTemplate, long>().GetAsync(templateId, cancellationToken).ConfigureAwait(false)
: null;
var entry = before is null ? new GlEntry { Source = GlEntrySource.Manual } : Clone(before);
entry.EntryDate = input.EntryDate;
entry.CompetenceDate = input.CompetenceDate;
entry.JournalTemplateId = template?.Id;
entry.TemplateCode = template?.Code;
entry.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
entry.DocumentNumber = LedgerStore.Trim(input.DocumentNumber, 30);
entry.DocumentDate = input.DocumentDate;
entry.PartyId = input.PartyId;
entry.VatRegisterId = input.VatRegisterId;
entry.VatDate = input.VatRegisterId is null ? null : input.VatDate ?? input.EntryDate;
entry.Notes = LedgerStore.Trim(input.Notes, 500);
entry.Status = input.Post ? GlEntryStatus.Posted : before?.Status ?? GlEntryStatus.Draft;
if (before is not null && before.Number is not null && before.Year != input.EntryDate.Year)
{
entry.Number = null;
entry.EntryNumber = null;
}
if (before is null)
{
entry = await LedgerStore.InsertAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, entry.Id, null, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.UpdateAsync(uow, entry, lines, input.Vat, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, entry.Id, before, entry, actor.UserName, cancellationToken).ConfigureAwait(false);
}
id = entry.Id;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>Removes an entry that is not final and does not come from a document.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</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, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (entry.Status == GlEntryStatus.Final)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.Final]);
}
if (entry.Source == GlEntrySource.Document)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_recurring_entries SET last_entry_id = NULL WHERE last_entry_id = {id}"), cancellationToken).ConfigureAwait(false);
if (await uow.Repository<RecurringEntry, long>().CountAsync(Query.For<RecurringEntry>().Where(r => r.ModelEntryId == id), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.RecurringModel]);
}
await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, entry, (GlEntry?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Reverses an entry (storno): a new posted entry with the same lines on the other side and the VAT with the
/// opposite sign; the open items of the entry not yet settled are removed.
/// </summary>
/// <param name="actor">Who reverses.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="date">The date of the reversal.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reversal.</returns>
public async Task<EntryView> ReverseAsync(Actor actor, string companyCode, long id, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await _fiscal.DemandOpenAsync(company, date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false);
long reversalId;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var entry = await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (entry.Source == GlEntrySource.Document && entry.Status != GlEntryStatus.Final)
{
throw new ValidationFailedException(["Source:" + LedgerErrors.FromDocument]);
}
var reversal = await ReverseAsync(uow, entry, date, actor.UserName, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, reversal.Id, null, reversal, actor.UserName, cancellationToken).ConfigureAwait(false);
reversalId = reversal.Id;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, reversalId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Makes final the posted entries up to a day (stampa definitiva del libro giornale): in date order each gets the
/// next number of the journal of its fiscal year, then never changes again.
/// </summary>
/// <param name="actor">Who does it: needs <c>ledger.entry.finalize</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="upTo">The last day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many entries became final.</returns>
public async Task<int> FinalizeAsync(Actor actor, string companyCode, DateOnly upTo, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryFinalize, cancellationToken).ConfigureAwait(false);
var done = 0;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var drafts = await uow.Repository<GlEntry, long>().CountAsync(
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.Draft && e.EntryDate <= upTo), cancellationToken).ConfigureAwait(false);
if (drafts > 0)
{
throw new ValidationFailedException(["UpTo:" + LedgerErrors.DraftsBeforeFinal]);
}
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
Query.For<GlEntry>().Where(e => e.Status == GlEntryStatus.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;
var now = _clock.GetUtcNow().UtcDateTime;
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 = actor.UserName;
await LedgerStore.SetStatusAsync(uow, entry, GlEntryStatus.Final, cancellationToken).ConfigureAwait(false);
done++;
}
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);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return done;
}
/// <summary>Posts a draft: it must balance.</summary>
/// <param name="actor">Who posts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry as posted.</returns>
public async Task<EntryView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
var e = view.Entry;
return await SaveAsync(actor, companyCode, new EntryInput(e.Id, e.EntryDate, e.Description, [.. view.Lines.Select(Draft)])
{
JournalTemplateId = e.JournalTemplateId,
CompetenceDate = e.CompetenceDate,
DocumentNumber = e.DocumentNumber,
DocumentDate = e.DocumentDate,
PartyId = e.PartyId,
VatRegisterId = e.VatRegisterId,
VatDate = e.VatDate,
Vat = [.. view.Vat.Select(Draft)],
Notes = e.Notes,
Post = true,
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>A line of an entry as a draft line.</summary>
/// <param name="line">The line.</param>
/// <returns>The draft.</returns>
public static EntryLineDraft Draft(GlEntryLine line)
{
ArgumentNullException.ThrowIfNull(line);
return new EntryLineDraft(line.AccountId, line.PartyId, line.Description, line.Debit, line.Credit, line.CostCenterId, line.JobId);
}
/// <summary>A VAT line of an entry as a draft line.</summary>
/// <param name="line">The line.</param>
/// <returns>The draft.</returns>
public static EntryVatDraft Draft(GlEntryVat line)
{
ArgumentNullException.ThrowIfNull(line);
return new EntryVatDraft(line.TaxCodeId, line.Rate, line.Nature, line.Taxable, line.Tax, line.NonDeductibleTax, line.Exigibility, line.VatRegisterId);
}
/// <summary>Writes the reversal of an entry in the open transaction.</summary>
internal static async Task<GlEntry> ReverseAsync(IUnitOfWork uow, GlEntry entry, DateOnly date, string? userName, CancellationToken cancellationToken)
{
if (entry.ReversedById is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AlreadyReversed]);
}
if (entry.Status == GlEntryStatus.Draft)
{
throw new ValidationFailedException(["Status:" + LedgerErrors.NotPosted]);
}
var lines = await LedgerStore.LinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
var vat = await LedgerStore.VatAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
var reversal = new GlEntry
{
EntryDate = date < entry.EntryDate ? entry.EntryDate : date,
JournalTemplateId = entry.JournalTemplateId,
TemplateCode = entry.TemplateCode,
Description = LedgerStore.Trim("Storno " + (entry.EntryNumber ?? string.Empty) + " " + entry.Description, 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Reversal,
SourceFamily = entry.SourceFamily,
SourceDocumentId = entry.SourceDocumentId,
SourceKind = entry.SourceKind,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate,
PartyId = entry.PartyId,
VatRegisterId = entry.VatRegisterId,
VatProtocol = entry.VatProtocol,
VatDate = date < entry.EntryDate ? entry.VatDate : date,
ReversalOfId = entry.Id,
IsDemo = entry.IsDemo,
Notes = userName is null ? null : "Storno di " + userName,
};
reversal = await LedgerStore.InsertAsync(
uow,
reversal,
[.. lines.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, l.Description, l.Credit, l.Debit, l.CostCenterId, l.JobId))],
[.. vat.Select(v => new EntryVatDraft(v.TaxCodeId, v.Rate, v.Nature, -v.Taxable, -v.Tax, -v.NonDeductibleTax, v.Exigibility, v.VatRegisterId))],
cancellationToken).ConfigureAwait(false);
entry.ReversedById = reversal.Id;
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0"), cancellationToken).ConfigureAwait(false);
return reversal;
}
internal static async Task<EntryView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } entry)
{
return null;
}
var lines = await LedgerStore.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false);
var vat = await LedgerStore.VatAsync(uow, id, cancellationToken).ConfigureAwait(false);
var names = await PartyNamesAsync(uow, [entry.PartyId], cancellationToken).ConfigureAwait(false);
return new EntryView(entry, lines, vat, entry.PartyId is { } p && names.TryGetValue(p, out var name) ? name : null);
}
internal static async Task<Dictionary<long, string>> PartyNamesAsync(IUnitOfWork uow, IEnumerable<long?> ids, CancellationToken cancellationToken)
{
var list = ids.Where(i => i is not null).Select(i => i!.Value).Distinct().ToList();
if (list.Count == 0)
{
return [];
}
return (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(p => p.Id, p => p.Name);
}
private static async Task CheckFinalOrderAsync(IUnitOfWork uow, DateOnly date, List<string> errors, CancellationToken cancellationToken)
{
var year = await uow.Repository<FiscalYear, long>().FindAsync(
Query.For<FiscalYear>().Where(y => y.StartDate <= date && y.EndDate >= date), cancellationToken).ConfigureAwait(false);
if (year?.LastFinalEntryDate is { } last && date < last)
{
errors.Add("EntryDate:" + LedgerErrors.FinalOrder);
}
}
private static GlEntry Clone(GlEntry entry) => new()
{
Id = entry.Id,
Year = entry.Year,
Number = entry.Number,
EntryNumber = entry.EntryNumber,
JournalNumber = entry.JournalNumber,
EntryDate = entry.EntryDate,
Description = entry.Description,
Status = entry.Status,
Source = entry.Source,
IsDemo = entry.IsDemo,
RowVersion = entry.RowVersion,
CreatedAt = entry.CreatedAt,
CreatedBy = entry.CreatedBy,
UpdatedAt = entry.UpdatedAt,
UpdatedBy = entry.UpdatedBy,
};
}
@@ -0,0 +1,448 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
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;
namespace Khaemhat.Application.Ledger;
/// <summary>
/// Posts the documents to the ledger (SPEC §11.7, issue #64, ADR 0037) inside the transaction of the document engine,
/// like <see cref="Inventory.InventoryPoster"/> does with the warehouse: an invoice, credit note or self-invoice in
/// force writes its entry (with the VAT lines of its register, the open items of its installments and its
/// withholding); a change writes it again with the same number; a cancelled document loses it, or gets a reversal when
/// its entry is already final. Nothing is posted while the module ACCT is not licensed: the documents can be posted
/// later in bulk (<see cref="LedgerService.PostPendingAsync"/>).
/// </summary>
public sealed class LedgerPoster
{
private readonly ILicenseGate _licence;
/// <summary>Creates the poster.</summary>
/// <param name="licence">The licence (module ACCT).</param>
public LedgerPoster(ILicenseGate licence)
{
ArgumentNullException.ThrowIfNull(licence);
_licence = licence;
}
/// <summary>Whether the documents post to the ledger.</summary>
public bool Active => _licence.IsModuleActive(ModuleCodes.Accounting);
/// <summary>What a kind of document posts, if anything.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The posting kind and whether the sides are reversed, or <see langword="null"/>.</returns>
public static (PostingKind Kind, bool Reverse)? PostingOf(DocumentKind kind) => kind switch
{
DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice or DocumentKind.DeferredInvoice or DocumentKind.DownPaymentInvoice
or DocumentKind.DebitNote or DocumentKind.Fee => (PostingKind.Sale, false),
DocumentKind.CreditNote => (PostingKind.Sale, true),
DocumentKind.SelfInvoice => (PostingKind.SelfInvoice, false),
DocumentKind.PurchaseInvoice => (PostingKind.Purchase, false),
DocumentKind.PurchaseCreditNote => (PostingKind.Purchase, true),
_ => null,
};
/// <summary>Writes again the entry of a document from its current state.</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or <see langword="null"/> when the document posts nothing.</returns>
public async Task<GlEntry?> SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
if (!Active || family is not (DocumentFamily.SaleDocument or DocumentFamily.PurchaseDocument))
{
return null;
}
return await PostAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
}
/// <summary>Posts or removes the entry of a document whatever the licence (bulk posting, tests).</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entry, or <see langword="null"/>.</returns>
internal static async Task<GlEntry?> PostAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var header = await store.GetAsync(uow, documentId, cancellationToken).ConfigureAwait(false);
var existing = await CurrentEntryAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
var posting = header is null ? null : PostingOf(header.Kind);
if (header is null || posting is null || !DocumentStateMachine.IsInForce(header.Status))
{
await RemoveAsync(uow, existing, cancellationToken).ConfigureAwait(false);
await RemoveWithholdingsAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false);
if (header is not null && (header.Posted || header.GlEntryId is not null))
{
header.Posted = false;
header.GlEntryId = null;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
}
return null;
}
var built = await BuildAsync(uow, family, header, posting.Value, cancellationToken).ConfigureAwait(false);
if (built is null)
{
return null;
}
var (entry, lines, vat) = built.Value;
GlEntry result;
if (existing is null)
{
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
else if (existing.Status != GlEntryStatus.Final)
{
Copy(entry, existing);
await LedgerStore.UpdateAsync(uow, existing, lines, vat, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {existing.Id}"), cancellationToken).ConfigureAwait(false);
result = existing;
}
else if (await SameAsync(uow, existing, lines, cancellationToken).ConfigureAwait(false))
{
return existing;
}
else
{
// A final entry never changes: the reversal cancels it and a new entry posts the document as it is now.
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
result = await LedgerStore.InsertAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
await OpenItemsAsync(uow, family, header, posting.Value, result, lines, cancellationToken).ConfigureAwait(false);
await WithholdingAsync(uow, family, header, result, cancellationToken).ConfigureAwait(false);
if (!header.Posted || header.GlEntryId != result.Id)
{
header.Posted = true;
header.GlEntryId = result.Id;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
}
return result;
}
/// <summary>The entry of a document that is not reversed, if any.</summary>
internal static async Task<GlEntry?> CurrentEntryAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var entries = (await uow.Repository<GlEntry, long>().ListAsync(
Query.For<GlEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId && e.Source == GlEntrySource.Document)
.OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
return entries.FirstOrDefault(e => e.ReversedById is null);
}
private static async Task RemoveAsync(IUnitOfWork uow, GlEntry? existing, CancellationToken cancellationToken)
{
if (existing is null)
{
return;
}
if (existing.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
}
}
private static async Task RemoveWithholdingsAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
{
var waiting = nameof(WithholdingStatus.Waiting);
var suffered = nameof(WithholdingStatus.Suffered);
var text = family.ToString();
await uow.ExecuteAsync(
SqlFragment.Of($"DELETE FROM withholdings WHERE source_family = {text} AND source_document_id = {documentId} AND status IN ({waiting}, {suffered})"),
cancellationToken).ConfigureAwait(false);
}
private static void Copy(GlEntry from, GlEntry to)
{
to.EntryDate = from.EntryDate;
to.JournalTemplateId = from.JournalTemplateId;
to.TemplateCode = from.TemplateCode;
to.Description = from.Description;
to.SourceKind = from.SourceKind;
to.DocumentNumber = from.DocumentNumber;
to.DocumentDate = from.DocumentDate;
to.PartyId = from.PartyId;
to.VatRegisterId = from.VatRegisterId;
to.VatProtocol = from.VatProtocol;
to.VatDate = from.VatDate;
to.IsDemo = from.IsDemo;
if (to.Year != from.EntryDate.Year)
{
// A new year means a new number.
to.Number = null;
to.EntryNumber = null;
}
}
private static async Task<bool> SameAsync(IUnitOfWork uow, GlEntry existing, IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
{
var stored = await LedgerStore.LinesAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
static string Key(long? account, long? party, decimal debit, decimal credit) => $"{account}|{party}|{debit:0.00}|{credit:0.00}";
var left = stored.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
var right = lines.Select(l => Key(l.AccountId, l.PartyId, l.Debit, l.Credit)).Order(StringComparer.Ordinal);
return left.SequenceEqual(right, StringComparer.Ordinal);
}
private static async Task<(GlEntry Entry, List<EntryLineDraft> Lines, List<EntryVatDraft> Vat)?> BuildAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, CancellationToken cancellationToken)
{
var type = await uow.Repository<DocumentType, long>().GetAsync(header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var templateCode = type?.JournalTemplateCode ?? DefaultTemplate(posting);
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
PartyPurchaseTerms? purchaseTerms = null;
if (posting.Kind == PostingKind.Purchase && header.PartyId is { } supplierId)
{
purchaseTerms = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(
Query.For<PartyPurchaseTerms>().Where(t => t.PartyId == supplierId), cancellationToken).ConfigureAwait(false);
}
var registerCode = purchaseTerms?.VatRegisterCode ?? type?.VatRegisterCode ?? template.VatRegisterCode;
var register = await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false);
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items;
var byCode = accounts.ToDictionary(a => a.Code, StringComparer.Ordinal);
long? Of(string? code) => code is not null && byCode.TryGetValue(code, out var account) && account.Postable ? account.Id : null;
long? Role(PostingRole role) => templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId;
var party = header.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var record = await DocumentEngine.LoadAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
if (record is null)
{
return null;
}
var sale = posting.Kind == PostingKind.Sale;
var items = await ItemsAsync(uow, record.Lines, cancellationToken).ConfigureAwait(false);
var taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id);
var inputLines = new List<PostingLineInput>();
foreach (var line in record.Lines.Where(l => l.Kind != DocumentLineKind.Description && l.TaxableAmount != 0m))
{
var item = line.ItemId is { } itemId && items.TryGetValue(itemId, out var found2) ? found2 : null;
var tax = line.TaxCodeId is { } taxId && taxCodes.TryGetValue(taxId, out var code) ? code : null;
var account = Of(line.AccountCode)
?? Of(sale ? item?.RevenueAccountCode : item?.CostAccountCode)
?? Of(purchaseTerms?.CostAccountCode)
?? Of(sale ? tax?.SalesAccountCode : tax?.PurchaseAccountCode);
inputLines.Add(new PostingLineInput(account, line.TaxableAmount, line.TaxCodeId, line.CostCenterId, line.JobId));
}
var taxes = record.Figures.Summary
.Select(s => new PostingTaxInput(s.TaxCodeId, s.Rate, s.Nature, s.Exigibility, s.Taxable, s.Tax, s.NonDeductibleTax))
.ToList();
var stamp = header.StampDutyCharged ? header.StampDuty : 0m;
var total = taxes.Sum(t => t.Taxable) + taxes.Sum(t => t.Tax) + stamp;
var partyAccount = posting.Kind switch
{
PostingKind.Sale => Of(party?.CustomerAccountCode) ?? Role(PostingRole.Customer),
PostingKind.Purchase => Of(party?.SupplierAccountCode) ?? Role(PostingRole.Supplier),
_ => null,
};
var accountsOfPosting = new PostingAccounts(
partyAccount,
Role(sale ? PostingRole.Revenue : PostingRole.Cost),
Role(PostingRole.SalesVat),
Role(PostingRole.PurchaseVat),
Role(PostingRole.StampDuty),
Role(PostingRole.SocialSecurity));
PostingResult result;
try
{
result = PostingEngine.Post(
new PostingInput(posting.Kind, posting.Reverse, header.PartyId, inputLines, taxes, total, stamp, sale ? header.SocialSecurityAmount : 0m),
accountsOfPosting);
}
catch (PostingAccountMissingException exception)
{
throw new ValidationFailedException("Ledger:" + LedgerErrors.RoleAccountMissing, exception);
}
if (result.Vat.Count > 0 && register is null)
{
throw new ValidationFailedException(["VatRegisterId:" + LedgerErrors.VatRegisterRequired]);
}
// A self-invoice is annotated also in the purchase register of reverse charge (double annotation, §11.5).
VatRegister? purchaseRegister = null;
if (posting.Kind == PostingKind.SelfInvoice)
{
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
purchaseRegister = registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && r.ReverseCharge && !r.Disabled)
?? registers.FirstOrDefault(r => r.Kind == VatRegisterKind.Purchases && !r.Disabled);
}
var purchase = family == DocumentFamily.PurchaseDocument;
var documentNumber = purchase ? header.ExternalReference ?? header.DocumentNumber : header.DocumentNumber;
var documentDate = purchase ? header.ExternalDate ?? header.DocumentDate : header.DocumentDate;
var entryDate = purchase ? header.VatDate ?? header.DocumentDate : header.DocumentDate;
var entry = new GlEntry
{
EntryDate = entryDate,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(Describe(template.Description, documentNumber, documentDate, party), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Document,
SourceFamily = family,
SourceDocumentId = header.Id,
SourceKind = header.Kind,
DocumentNumber = LedgerStore.Trim(documentNumber, 30),
DocumentDate = documentDate,
PartyId = header.PartyId,
VatRegisterId = result.Vat.Count > 0 ? register?.Id : null,
VatProtocol = purchase ? header.VatProtocol ?? header.Number : header.Number,
VatDate = header.VatDate ?? entryDate,
IsDemo = header.IsDemo,
};
var description = LedgerStore.Trim(documentNumber is null ? template.Description : template.Description + " " + documentNumber, 200);
var lines = result.Lines
.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, description, l.Debit, l.Credit, l.CostCenterId, l.JobId))
.ToList();
var vat = result.Vat
.Select(v => new EntryVatDraft(
v.Tax.TaxCodeId, v.Tax.Rate, v.Tax.Nature, v.Tax.Taxable, v.Tax.Tax, v.Tax.NonDeductibleTax, v.Tax.Exigibility,
v.RegisterKind == VatRegisterKind.Purchases && purchaseRegister is not null ? purchaseRegister.Id : register?.Id))
.ToList();
return (entry, lines, vat);
}
private static string DefaultTemplate((PostingKind Kind, bool Reverse) posting) => posting switch
{
(PostingKind.Sale, false) => "FV",
(PostingKind.Sale, true) => "NCV",
(PostingKind.Purchase, false) => "FA",
(PostingKind.Purchase, true) => "NCA",
_ => "AFRC",
};
private static string Describe(string template, string? number, DateOnly date, Party? party)
{
var text = template;
if (number is not null)
{
text += " n. " + number;
}
text += " del " + date.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (party is not null)
{
text += " - " + party.Name;
}
return text;
}
private static async Task<Dictionary<long, Item>> ItemsAsync(IUnitOfWork uow, IReadOnlyList<DocumentLine> lines, CancellationToken cancellationToken)
{
var ids = lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList();
if (ids.Count == 0)
{
return [];
}
return (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
}
private static async Task OpenItemsAsync(
IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, GlEntry entry,
IReadOnlyList<EntryLineDraft> lines, CancellationToken cancellationToken)
{
if (posting.Kind == PostingKind.SelfInvoice || header.PartyId is not { } partyId)
{
return;
}
var partyLine = lines.FirstOrDefault(l => l.PartyId == partyId);
if (partyLine?.AccountId is not { } accountId)
{
return;
}
var installments = (await uow.Repository<DocumentInstallment, long>().ListAsync(
Query.For<DocumentInstallment>().Where(i => i.Family == family && i.DocumentId == header.Id).OrderBy(i => i.Number), cancellationToken).ConfigureAwait(false)).Items;
var sign = posting.Reverse ? -1m : 1m;
var rows = installments.Count > 0
? installments.Select(i => (i.Number, i.DueDate, i.Amount, i.PaymentMethodId)).ToList()
: [(1, header.DocumentDate, header.NetAmount != 0m ? header.NetAmount : header.TotalAmount, header.PaymentMethodId)];
var repository = uow.Repository<OpenItem, long>();
foreach (var (number, due, amount, method) in rows)
{
await repository.InsertAsync(new OpenItem
{
Direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable,
PartyId = partyId,
AccountId = accountId,
EntryId = entry.Id,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
Installment = number,
DueDate = due,
Amount = sign * amount,
PaymentMethodId = method,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
}
}
private static async Task WithholdingAsync(IUnitOfWork uow, DocumentFamily family, DocumentHeader header, GlEntry entry, CancellationToken cancellationToken)
{
await RemoveWithholdingsAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
if (header.WithholdingAmount == 0m || header.PartyId is not { } partyId)
{
return;
}
var existing = await uow.Repository<Withholding, long>().CountAsync(
Query.For<Withholding>().Where(w => w.SourceFamily == family && w.SourceDocumentId == header.Id), cancellationToken).ConfigureAwait(false);
if (existing > 0)
{
// Already due or paid: the payment stays as it was.
return;
}
var operated = family == DocumentFamily.PurchaseDocument;
var sign = header.Kind is DocumentKind.CreditNote or DocumentKind.PurchaseCreditNote ? -1m : 1m;
await uow.Repository<Withholding, long>().InsertAsync(new Withholding
{
Direction = operated ? WithholdingDirection.Operated : WithholdingDirection.Suffered,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
PartyId = partyId,
WithholdingType = header.WithholdingType,
Reason = header.WithholdingReason,
Taxable = sign * (header.TaxableAmount - header.SocialSecurityAmount),
SocialSecurityFund = header.SocialSecurityFund,
SocialSecurityAmount = sign * header.SocialSecurityAmount,
Rate = header.WithholdingRate ?? 0m,
BasePercent = header.WithholdingBasePercent,
Amount = sign * header.WithholdingAmount,
Status = operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,436 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>A movement of an account (or of a party on an account), with the running balance.</summary>
/// <param name="EntryId">The entry, for the drill-down.</param>
/// <param name="EntryNumber">The number of the entry.</param>
/// <param name="EntryDate">The date.</param>
/// <param name="Description">The description of the line, or of the entry.</param>
/// <param name="DocumentNumber">The number of the document.</param>
/// <param name="DocumentDate">The date of the document.</param>
/// <param name="TemplateCode">The journal template.</param>
/// <param name="AccountCode">The account (when the view is of a party).</param>
/// <param name="Debit">The debit.</param>
/// <param name="Credit">The credit.</param>
/// <param name="Balance">The balance after the movement, debit positive.</param>
/// <param name="Status">The state of the entry.</param>
public sealed record LedgerMovement(
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
decimal Debit, decimal Credit, decimal Balance, GlEntryStatus Status);
/// <summary>A page of the movements of an account or a party.</summary>
/// <param name="Opening">The balance before the period.</param>
/// <param name="Movements">The movements of the page.</param>
/// <param name="TotalCount">How many movements the period has.</param>
/// <param name="TotalDebit">The debits of the period.</param>
/// <param name="TotalCredit">The credits of the period.</param>
/// <param name="Closing">The balance at the end of the period.</param>
public sealed record LedgerPage(decimal Opening, IReadOnlyList<LedgerMovement> Movements, long TotalCount, decimal TotalDebit, decimal TotalCredit, decimal Closing);
/// <summary>What the movements are asked for.</summary>
/// <param name="AccountId">The account; with <paramref name="PartyId"/>, its sub-ledger.</param>
/// <param name="PartyId">The customer or supplier (partitario, estratto conto).</param>
/// <param name="From">From this day.</param>
/// <param name="To">Up to this day.</param>
/// <param name="IncludeDrafts">Count the drafts too.</param>
/// <param name="Offset">The first movement of the page.</param>
/// <param name="Limit">The size of the page.</param>
public sealed record LedgerFilter(long? AccountId, long? PartyId, DateOnly From, DateOnly To, bool IncludeDrafts = false, int Offset = 0, int Limit = 50);
/// <summary>A line of the trial balance.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Level">The level (1 mastro, 2 conto, 3 sottoconto).</param>
/// <param name="Nature">The nature.</param>
/// <param name="Opening">The balance before the period.</param>
/// <param name="Debit">The debits of the period.</param>
/// <param name="Credit">The credits of the period.</param>
/// <param name="Closing">The balance at the end, debit positive.</param>
public sealed record TrialBalanceLine(long AccountId, string Code, string Description, int Level, AccountNature Nature, decimal Opening, decimal Debit, decimal Credit, decimal Closing);
/// <summary>The trial balance of a period.</summary>
/// <param name="Lines">The accounts with movements or a balance, with the totals of their parents.</param>
/// <param name="TotalDebit">The debits of the period.</param>
/// <param name="TotalCredit">The credits of the period.</param>
/// <param name="Result">The result of the period (revenues minus costs).</param>
public sealed record TrialBalance(IReadOnlyList<TrialBalanceLine> Lines, decimal TotalDebit, decimal TotalCredit, decimal Result)
{
/// <summary>Whether debits and credits match.</summary>
public bool Balanced => TotalDebit == TotalCredit;
}
/// <summary>A party with a balance on the customer or supplier accounts.</summary>
/// <param name="PartyId">The party.</param>
/// <param name="Name">The name.</param>
/// <param name="Debit">The debits.</param>
/// <param name="Credit">The credits.</param>
/// <param name="Balance">The balance, debit positive.</param>
/// <param name="OpenItems">The open items not closed.</param>
public sealed record PartyBalance(long PartyId, string Name, decimal Debit, decimal Credit, decimal Balance, int OpenItems);
/// <summary>
/// What the ledger tells (SPEC §11.7, issue #67, mockup 044): the movements of an account (mastrino) and of a customer
/// or supplier (partitario, estratto conto) with the running balance and the way to the entry; the open items; the
/// trial balance of a period, by cost center too, with the balances of the parents; the general journal (libro
/// giornale), provisional or as numbered. All the lists are paged in the database.
/// </summary>
public sealed class LedgerQueryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public LedgerQueryService(IUnitOfWorkFactory factory, PermissionService permissions)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
_factory = factory;
_permissions = permissions;
}
/// <summary>The movements of an account or of a party in a period, with the running balance.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The account or party, the period, the page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public async Task<LedgerPage> MovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await MovementsAsync(uow, filter, cancellationToken).ConfigureAwait(false);
}
/// <summary>The customers or suppliers with their balance on the sub-ledger accounts.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="type">Customers or suppliers.</param>
/// <param name="to">Up to this day.</param>
/// <param name="search">Part of the name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The parties, by name.</returns>
public async Task<IReadOnlyList<PartyBalance>> PartyBalancesAsync(
Actor actor, string companyCode, AccountType type, DateOnly to, string? search = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var draft = nameof(GlEntryStatus.Draft);
var typeText = type.ToString();
var direction = (type == AccountType.Suppliers ? OpenItemDirection.Payable : OpenItemDirection.Receivable).ToString();
var like = "%" + (search ?? string.Empty).Trim().ToUpperInvariant() + "%";
var rows = await uow.QueryAsync<PartyRow>(SqlFragment.Of($"""
SELECT l.party_id AS party_id, p.name AS name, SUM(l.debit) AS debit, SUM(l.credit) AS credit,
(SELECT COUNT(*) FROM gl_open_items o WHERE o.party_id = l.party_id AND o.direction = {direction} AND o.closed = {false}) AS open_items
FROM gl_entry_lines l JOIN gl_accounts a ON a.id = l.account_id JOIN parties p ON p.id = l.party_id
WHERE a.type = {typeText} AND l.status <> {draft} AND l.entry_date <= {to} AND UPPER(p.name) LIKE {like}
GROUP BY l.party_id, p.name
ORDER BY p.name
"""), cancellationToken).ConfigureAwait(false);
return [.. rows.Select(r => new PartyBalance(r.PartyId, r.Name, r.Debit ?? 0m, r.Credit ?? 0m, (r.Debit ?? 0m) - (r.Credit ?? 0m), (int)r.OpenItems))];
}
/// <summary>The open items of a party (or of all), by due date.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">The party, or <see langword="null"/> for all.</param>
/// <param name="direction">Receivables or payables.</param>
/// <param name="includeClosed">Show the closed items too.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The items.</returns>
public async Task<IReadOnlyList<OpenItem>> OpenItemsAsync(
Actor actor, string companyCode, long? partyId, OpenItemDirection direction, bool includeClosed = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<OpenItem>().Where(o => o.Direction == direction);
if (partyId is { } id)
{
query = query.Where(o => o.PartyId == id);
}
if (!includeClosed)
{
query = query.Where(o => !o.Closed);
}
return (await uow.Repository<OpenItem, long>().ListAsync(query.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>The trial balance of a period (bilancio di verifica), optionally of one cost center.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="costCenterId">Only the lines of this cost center.</param>
/// <param name="includeDrafts">Count the drafts too.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The trial balance.</returns>
public async Task<TrialBalance> TrialBalanceAsync(
Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, bool includeDrafts = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts, cancellationToken).ConfigureAwait(false);
}
/// <summary>The trial balance as PDF.</summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="costCenterId">Only the lines of this cost center.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintTrialBalanceAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, long? costCenterId = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var balance = await TrialBalanceAsync(uow, from, to, costCenterId, includeDrafts: false, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var center = costCenterId is { } c ? await uow.Repository<CostCenter, long>().GetAsync(c, cancellationToken).ConfigureAwait(false) : null;
var rows = new List<IReadOnlyList<string?>>();
foreach (var line in balance.Lines)
{
var bold = line.Level < 3 ? "**" : string.Empty;
rows.Add([
bold + line.Code, new string(' ', (line.Level - 1) * 2) + line.Description, LedgerReport.Money(line.Opening), LedgerReport.Money(line.Debit),
LedgerReport.Money(line.Credit), line.Closing > 0m ? LedgerReport.Money(line.Closing) : null, line.Closing < 0m ? LedgerReport.Money(-line.Closing) : null,
]);
}
rows.Add(["**Totali", null, null, LedgerReport.Money(balance.TotalDebit), LedgerReport.Money(balance.TotalCredit), null, null]);
rows.Add(["**Risultato", balance.Result >= 0m ? "Utile del periodo" : "Perdita del periodo", null, null, null, null, LedgerReport.Money(Math.Abs(balance.Result))]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile),
"Bilancio di verifica" + (center is null ? string.Empty : " - centro di costo " + center.Code + " " + center.Description),
"Dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Conto", 70), new("Descrizione", 260), new("Saldo iniziale", 85, true), new("Dare", 85, true), new("Avere", 85, true), new("Saldo dare", 85, true),
new("Saldo avere", 85, true)],
rows,
to.Year,
1,
cancellationToken).ConfigureAwait(false);
return new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"bilancio_verifica_{from:yyyyMMdd}_{to:yyyyMMdd}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file);
}
/// <summary>The movements of an account or party as PDF (mastrino, estratto conto).</summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The account or party and the period (the page is ignored).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintMovementsAsync(Actor actor, string companyCode, LedgerFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var page = await MovementsAsync(uow, filter with { Offset = 0, Limit = 100_000 }, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var account = filter.AccountId is { } a ? await uow.Repository<GlAccount, long>().GetAsync(a, cancellationToken).ConfigureAwait(false) : null;
var party = filter.PartyId is { } p ? await uow.Repository<Core.Parties.Party, long>().GetAsync(p, cancellationToken).ConfigureAwait(false) : null;
var title = party is not null ? "Estratto conto " + party.Name : "Mastrino " + account?.Code + " " + account?.Description;
var rows = new List<IReadOnlyList<string?>> { new[] { "**Saldo iniziale", null, null, null, null, null, Signed(page.Opening) } };
foreach (var m in page.Movements)
{
rows.Add([LedgerReport.Date(m.EntryDate), m.EntryNumber, m.DocumentNumber, m.Description, LedgerReport.Money(m.Debit), LedgerReport.Money(m.Credit), Signed(m.Balance)]);
}
rows.Add(["**Totali", null, null, null, LedgerReport.Money(page.TotalDebit), LedgerReport.Money(page.TotalCredit), Signed(page.Closing)]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile), title, "Dal " + LedgerReport.Date(filter.From) + " al " + LedgerReport.Date(filter.To),
[new("Data", 55), new("Registrazione", 70), new("Documento", 80), new("Descrizione", 300), new("Dare", 80, true), new("Avere", 80, true), new("Saldo", 90, true)],
rows, filter.To.Year, 1, cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"{(party is not null ? "estratto_conto_" + party.Code : "mastrino_" + account?.Code)}_{filter.To:yyyyMMdd}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>
/// The general journal (libro giornale) of a period: every entry in date order with its lines. The provisional
/// print shows the posted entries too; the final one only the final entries, with their journal numbers and the
/// pages numbered from the first page of the year.
/// </summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="final">Only the final entries.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PrintJournalAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool final = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
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 fiscalYear = await uow.Repository<FiscalYear, long>().FindAsync(Query.For<FiscalYear>().Where(y => y.StartDate <= to && y.EndDate >= to), cancellationToken).ConfigureAwait(false);
var draft = nameof(GlEntryStatus.Draft);
var finalText = nameof(GlEntryStatus.Final);
var condition = final ? SqlFragment.Of($"e.status = {finalText}") : SqlFragment.Of($"e.status <> {draft}");
var lines = await uow.QueryAsync<JournalRow>(SqlFragment.Of($"""
SELECT e.id AS entry_id, e.entry_number AS entry_number, e.journal_number AS journal_number, e.entry_date AS entry_date, e.description AS entry_description,
e.document_number AS document_number, a.code AS account_code, a.description AS account_description, p.name AS party_name,
l.description AS description, l.debit AS debit, l.credit AS credit
FROM gl_entries e JOIN gl_entry_lines l ON l.entry_id = e.id JOIN gl_accounts a ON a.id = l.account_id LEFT JOIN parties p ON p.id = l.party_id
WHERE e.entry_date >= {from} AND e.entry_date <= {to} AND {condition}
ORDER BY e.entry_date, e.journal_number, e.number, e.id, l.line_number
"""), cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<string?>>();
long? current = null;
foreach (var line in lines)
{
if (line.EntryId != current)
{
current = line.EntryId;
rows.Add([
"**" + LedgerReport.Date(line.EntryDate), line.JournalNumber?.ToString(CultureInfo.InvariantCulture) ?? line.EntryNumber, null,
line.EntryDescription + (line.DocumentNumber is { Length: > 0 } d ? " - doc. " + d : string.Empty), null, null,
]);
}
rows.Add([null, null, line.AccountCode, line.AccountDescription + (line.PartyName is { Length: > 0 } n ? " - " + n : string.Empty) + (line.Description is { Length: > 0 } t && t != line.EntryDescription ? " (" + t + ")" : string.Empty),
LedgerReport.Money(line.Debit), LedgerReport.Money(line.Credit)]);
}
rows.Add(["**Totali del periodo", null, null, null, LedgerReport.Money(lines.Sum(l => l.Debit)), LedgerReport.Money(lines.Sum(l => l.Credit))]);
var (file, _) = await LedgerReport.WriteAsync(
VatService.CompanyLine(profile),
"Libro giornale",
(final ? "Registrazioni definitive" : "Stampa provvisoria") + " dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Data", 60), new("Numero", 65), new("Conto", 65), new("Descrizione", 400), new("Dare", 90, true), new("Avere", 90, true)],
rows,
to.Year,
final ? Math.Max(1, fiscalYear?.JournalFirstPage ?? 1) : 1,
cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"libro_giornale_{from:yyyyMMdd}_{to:yyyyMMdd}{(final ? "_definitivo" : "_provvisorio")}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>The movements of an account or party, paged in the database, with the running balance.</summary>
internal static async Task<LedgerPage> MovementsAsync(IUnitOfWork uow, LedgerFilter filter, CancellationToken cancellationToken)
{
if (filter.AccountId is null && filter.PartyId is null)
{
throw new ValidationFailedException(["AccountId:" + LedgerErrors.AccountRequired]);
}
var where = Condition(filter);
var from = filter.From;
var to = filter.To;
var opening = await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l WHERE {where} AND l.entry_date < {from}"), cancellationToken)
.ConfigureAwait(false) ?? 0m;
var totals = (await uow.QueryAsync<TotalsRow>(SqlFragment.Of($"""
SELECT COUNT(*) AS lines, SUM(l.debit) AS debit, SUM(l.credit) AS credit FROM gl_entry_lines l
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
"""), cancellationToken).ConfigureAwait(false))[0];
var offset = Math.Max(0, filter.Offset);
var limit = Math.Clamp(filter.Limit, 1, 100_000);
var before = offset == 0
? 0m
: await uow.QuerySingleAsync<decimal?>(SqlFragment.Of($"""
SELECT SUM(x.amount) FROM (
SELECT l.debit - l.credit AS amount FROM gl_entry_lines l JOIN gl_entries e ON e.id = l.entry_id
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number LIMIT {offset}) x
"""), cancellationToken).ConfigureAwait(false) ?? 0m;
var rows = await uow.QueryAsync<MovementRow>(SqlFragment.Of($"""
SELECT l.entry_id AS entry_id, e.entry_number AS entry_number, l.entry_date AS entry_date, COALESCE(l.description, e.description) AS description,
e.document_number AS document_number, e.document_date AS document_date, e.template_code AS template_code, a.code AS account_code,
l.debit AS debit, l.credit AS credit, l.status AS status
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
WHERE {where} AND l.entry_date >= {from} AND l.entry_date <= {to}
ORDER BY l.entry_date, e.number, l.entry_id, l.line_number
LIMIT {limit} OFFSET {offset}
"""), cancellationToken).ConfigureAwait(false);
var balance = opening + before;
var movements = new List<LedgerMovement>(rows.Count);
foreach (var r in rows)
{
balance += r.Debit - r.Credit;
movements.Add(new LedgerMovement(r.EntryId, r.EntryNumber, r.EntryDate, r.Description, r.DocumentNumber, r.DocumentDate, r.TemplateCode, r.AccountCode, r.Debit, r.Credit, balance, r.Status));
}
var debit = totals.Debit ?? 0m;
var credit = totals.Credit ?? 0m;
return new LedgerPage(opening, movements, totals.Lines, debit, credit, opening + debit - credit);
}
/// <summary>The trial balance, with the totals of the parent accounts.</summary>
internal static async Task<TrialBalance> TrialBalanceAsync(IUnitOfWork uow, DateOnly from, DateOnly to, long? costCenterId, bool includeDrafts, CancellationToken cancellationToken)
{
var draft = nameof(GlEntryStatus.Draft);
var status = includeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
var center = costCenterId is { } c ? SqlFragment.Of($"l.cost_center_id = {c}") : SqlFragment.Literal("1 = 1");
var sums = await uow.QueryAsync<BalanceRow>(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 opening,
SUM(CASE WHEN l.entry_date >= {from} THEN l.debit ELSE 0 END) AS debit,
SUM(CASE WHEN l.entry_date >= {from} THEN l.credit ELSE 0 END) AS credit
FROM gl_entry_lines l
WHERE l.entry_date <= {to} AND {status} AND {center}
GROUP BY l.account_id
"""), cancellationToken).ConfigureAwait(false);
var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false);
var totals = new Dictionary<long, (decimal Opening, decimal Debit, decimal Credit)>();
foreach (var s in sums)
{
var id = (long?)s.AccountId;
while (id is { } current && accounts.TryGetValue(current, out var account))
{
totals.TryGetValue(current, out var t);
totals[current] = (t.Opening + (s.Opening ?? 0m), t.Debit + (s.Debit ?? 0m), t.Credit + (s.Credit ?? 0m));
id = account.ParentId;
}
}
var lines = totals
.Select(kv => (Account: accounts[kv.Key], kv.Value))
.Where(x => x.Value.Opening != 0m || x.Value.Debit != 0m || x.Value.Credit != 0m)
.OrderBy(x => x.Account.Code, StringComparer.Ordinal)
.Select(x => new TrialBalanceLine(
x.Account.Id, x.Account.Code, x.Account.Description, x.Account.Level, x.Account.Nature, x.Value.Opening, x.Value.Debit, x.Value.Credit,
x.Value.Opening + x.Value.Debit - x.Value.Credit))
.ToList();
var leaves = lines.Where(l => accounts[l.AccountId].Postable).ToList();
var result = -leaves.Where(l => l.Nature is AccountNature.Revenue or AccountNature.Cost).Sum(l => l.Debit - l.Credit);
return new TrialBalance(lines, leaves.Sum(l => l.Debit), leaves.Sum(l => l.Credit), result);
}
private static SqlFragment Condition(LedgerFilter filter)
{
var draft = nameof(GlEntryStatus.Draft);
var status = filter.IncludeDrafts ? SqlFragment.Literal("1 = 1") : SqlFragment.Of($"l.status <> {draft}");
var account = filter.AccountId is { } a ? SqlFragment.Of($"l.account_id = {a}") : SqlFragment.Literal("1 = 1");
var party = filter.PartyId is { } p ? SqlFragment.Of($"l.party_id = {p}") : SqlFragment.Literal("1 = 1");
return SqlFragment.Of($"{status} AND {account} AND {party}");
}
private static string? Signed(decimal amount) => amount == 0m ? "0,00" : LedgerReport.Money(Math.Abs(amount)) + (amount > 0m ? " D" : " A");
private sealed record MovementRow(
long EntryId, string? EntryNumber, DateOnly EntryDate, string? Description, string? DocumentNumber, DateOnly? DocumentDate, string? TemplateCode, string? AccountCode,
decimal Debit, decimal Credit, GlEntryStatus Status);
private sealed record TotalsRow(long Lines, decimal? Debit, decimal? Credit);
private sealed record BalanceRow(long AccountId, decimal? Opening, decimal? Debit, decimal? Credit);
private sealed record PartyRow(long PartyId, string Name, decimal? Debit, decimal? Credit, long OpenItems);
private sealed record JournalRow(
long EntryId, string? EntryNumber, long? JournalNumber, DateOnly EntryDate, string EntryDescription, string? DocumentNumber, string AccountCode, string AccountDescription,
string? PartyName, string? Description, decimal Debit, decimal Credit);
}
@@ -0,0 +1,138 @@
using System.Globalization;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Ledger;
/// <summary>A column of a ledger print.</summary>
/// <param name="Title">The heading.</param>
/// <param name="Width">The width in points.</param>
/// <param name="Right">Aligned on the right (amounts).</param>
public sealed record ReportColumn(string Title, double Width, bool Right = false);
/// <summary>
/// The prints of the ledger (VAT registers, general journal, ledgers, trial balance, issue #65 and #67): A4 landscape,
/// the company and the title on every page, the headings repeated, the pages numbered from a first page in the form
/// <c>year/page</c> as the final prints of the books want (art. 2215-bis c.c., numbering by year).
/// </summary>
internal static class LedgerReport
{
private const double Margin = 28;
private const double LineHeight = 11;
private static readonly PdfColor Rule = PdfColor.Gray(180);
/// <summary>Writes a print.</summary>
/// <param name="company">The name, VAT number and address of the company.</param>
/// <param name="title">The title, such as <c>Registro IVA vendite</c>.</param>
/// <param name="subtitle">The period and the kind of print.</param>
/// <param name="columns">The columns.</param>
/// <param name="rows">The rows; a row whose first cell starts with <c>**</c> is a bold total.</param>
/// <param name="year">The year of the page numbers.</param>
/// <param name="firstPage">The number of the first page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file and the number of pages.</returns>
public static async Task<(byte[] File, int Pages)> WriteAsync(
string company, string title, string subtitle, IReadOnlyList<ReportColumn> columns, IReadOnlyList<IReadOnlyList<string?>> rows, int year, int firstPage,
CancellationToken cancellationToken)
{
using var buffer = new MemoryStream();
int pages;
await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = title }, leaveOpen: true))
{
var width = PdfWriter.A4Height;
var height = PdfWriter.A4Width;
var scale = Math.Min(1d, (width - (2 * Margin)) / Math.Max(1d, columns.Sum(c => c.Width)));
PdfPage? page = null;
var y = 0d;
var number = firstPage;
async Task NewPageAsync()
{
page = await pdf.AddPageAsync(width, height, cancellationToken).ConfigureAwait(false);
y = height - Margin;
page.DrawText(company, Margin, y, PdfFont.HelveticaBold, 9);
page.DrawTextRight(year.ToString(CultureInfo.InvariantCulture) + "/" + number.ToString(CultureInfo.InvariantCulture), width - Margin, y, PdfFont.Helvetica, 9);
y -= 14;
page.DrawText(title, Margin, y, PdfFont.HelveticaBold, 12);
y -= 12;
page.DrawText(subtitle, Margin, y, PdfFont.Helvetica, 8.5);
y -= 16;
var x = Margin;
foreach (var column in columns)
{
var w = column.Width * scale;
if (column.Right)
{
page.DrawTextRight(column.Title, x + w - 2, y, PdfFont.HelveticaBold, 7.5);
}
else
{
page.DrawText(column.Title, x + 2, y, PdfFont.HelveticaBold, 7.5);
}
x += w;
}
page.DrawLine(Margin, y - 3, width - Margin, y - 3, 0.6, Rule);
y -= LineHeight + 2;
number++;
}
await NewPageAsync().ConfigureAwait(false);
foreach (var row in rows)
{
if (y < Margin + LineHeight)
{
await NewPageAsync().ConfigureAwait(false);
}
var bold = row.Count > 0 && row[0] is { } first && first.StartsWith("**", StringComparison.Ordinal);
var font = bold ? PdfFont.HelveticaBold : PdfFont.Helvetica;
var x = Margin;
for (var i = 0; i < columns.Count; i++)
{
var w = columns[i].Width * scale;
var text = i < row.Count ? row[i] : null;
if (i == 0 && bold)
{
text = text![2..];
}
text = PdfTextLayout.Fit(text, font, 7.5, w - 4);
if (columns[i].Right)
{
page!.DrawTextRight(text, x + w - 2, y, font, 7.5);
}
else
{
page!.DrawText(text, x + 2, y, font, 7.5);
}
x += w;
}
if (bold)
{
page!.DrawLine(Margin, y + LineHeight - 2, width - Margin, y + LineHeight - 2, 0.4, Rule);
}
y -= LineHeight;
}
pages = pdf.PageCount;
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
return (buffer.ToArray(), pages);
}
/// <summary>An amount as the prints show it, with the Italian separators.</summary>
/// <param name="amount">The amount.</param>
/// <returns>The text; empty for zero.</returns>
public static string Money(decimal amount) => amount == 0m ? string.Empty : amount.ToString("#,##0.00", Italian);
/// <summary>A date as the prints show it.</summary>
/// <param name="date">The date.</param>
/// <returns>The text.</returns>
public static string Date(DateOnly? date) => date?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) ?? string.Empty;
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
}
@@ -0,0 +1,508 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Documents;
using Khaemhat.Application.ImportExport;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>An account typed in the chart.</summary>
/// <param name="Id">The account, for a change.</param>
/// <param name="Code">The code, such as <c>05.01.003</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="Nature">The statement it ends up in (taken from the parent below the first level).</param>
/// <param name="Type">What the automatic postings look for.</param>
public sealed record AccountInput(long? Id, string Code, string Description, AccountNature Nature, AccountType Type = AccountType.Generic)
{
/// <summary>The line of the legal statements.</summary>
public string? StatementLine { get; init; }
/// <summary>The line of the reclassified statements.</summary>
public string? Reclassification { get; init; }
/// <summary>The lines carry a customer or supplier.</summary>
public bool SubLedger { get; init; }
/// <summary>Relevant for VAT.</summary>
public bool VatRelevant { get; init; }
/// <summary>Closed at the year end.</summary>
public bool ClosesAutomatically { get; init; } = true;
/// <summary>No longer used.</summary>
public bool Disabled { get; init; }
}
/// <summary>A line of a journal template typed on its screen.</summary>
/// <param name="Role">What it stands for.</param>
/// <param name="Side">Debit or credit.</param>
/// <param name="AccountId">The account.</param>
/// <param name="Description">The description proposed.</param>
public sealed record TemplateLineInput(PostingRole Role, AccountSide Side, long? AccountId, string? Description);
/// <summary>A journal template typed on its screen (mockup 043).</summary>
/// <param name="Id">The template, for a change.</param>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Area">The kind of operations.</param>
/// <param name="Lines">The model of the lines.</param>
public sealed record TemplateInput(long? Id, string Code, string Description, JournalArea Area, IReadOnlyList<TemplateLineInput> Lines)
{
/// <summary>The VAT register.</summary>
public string? VatRegisterCode { get; init; }
/// <summary>Opens items of customers or suppliers.</summary>
public bool OpensItems { get; init; }
/// <summary>Reverses the sides (credit notes).</summary>
public bool Reverses { get; init; }
/// <summary>No longer used.</summary>
public bool Disabled { get; init; }
}
/// <summary>What a bulk posting did.</summary>
/// <param name="Posted">Documents posted or posted again.</param>
/// <param name="Failed">Documents that could not be posted, with the reason.</param>
public sealed record PostingReport(int Posted, IReadOnlyList<string> Failed);
/// <summary>
/// The chart of accounts and the journal templates (SPEC §11.7, issue #62, mockups 042-043, ADR 0036): three levels
/// where only the leaves receive postings, the nature inherited from the mastro, no removal of accounts with postings or
/// children; the import of a chart (CSV, XLSX, JSON) through the guided import; the bulk posting of the documents not yet
/// posted and the posting again of a period (issue #64).
/// </summary>
public sealed class LedgerService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
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="audit">The history.</param>
public LedgerService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_permissions = permissions;
_audit = audit;
}
/// <summary>The chart of accounts, by code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every account.</returns>
public async Task<IReadOnlyList<GlAccount>> AccountsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return [.. (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.OrderBy(a => a.Code, StringComparer.Ordinal)];
}
/// <summary>The VAT registers, by code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every register.</returns>
public async Task<IReadOnlyList<VatRegister>> RegistersAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
// Sales first, then purchases and receipts; the ordinary register before the reverse charge one (enums are stored as text).
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items;
return [.. registers.OrderBy(r => r.Kind).ThenBy(r => r.ReverseCharge).ThenBy(r => r.Code, StringComparer.Ordinal)];
}
/// <summary>Saves an account: a new one under a leaf with postings is refused, the parent stops being postable.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account as saved.</returns>
public async Task<GlAccount> SaveAccountAsync(Actor actor, string companyCode, AccountInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, 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<GlAccount, long>();
var code = (input.Code ?? string.Empty).Trim();
var errors = new List<string>();
var level = AccountCodes.LevelOf(code);
if (level == 0)
{
errors.Add("Code:" + LedgerErrors.AccountCode);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
GlAccount? before = null;
if (input.Id is { } id)
{
before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
if (!string.Equals(before.Code, code, StringComparison.Ordinal))
{
errors.Add("Code:" + LedgerErrors.AccountUsed);
}
}
else if (level > 0 && await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == code), cancellationToken).ConfigureAwait(false) is not null)
{
errors.Add("Code:" + LedgerErrors.AccountDuplicate);
}
GlAccount? parent = null;
if (level > 1)
{
var parentCode = AccountCodes.ParentOf(code);
parent = await repository.FindAsync(Query.For<GlAccount>().Where(a => a.Code == parentCode), cancellationToken).ConfigureAwait(false);
if (parent is null)
{
errors.Add("Code:" + LedgerErrors.AccountParent);
}
else if (before is null && parent.Postable && await UsedAsync(uow, parent.Id, cancellationToken).ConfigureAwait(false))
{
errors.Add("Code:" + LedgerErrors.AccountUsed);
}
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var account = before is null ? new GlAccount { Code = code, Level = level, ParentId = parent?.Id } : Clone(before);
account.Description = input.Description.Trim();
account.Nature = parent?.Nature ?? input.Nature;
account.Type = input.Type;
account.StatementLine = LedgerStore.Trim(input.StatementLine?.Trim(), 20);
account.Reclassification = LedgerStore.Trim(input.Reclassification?.Trim(), 20);
account.SubLedger = input.SubLedger;
account.VatRelevant = input.VatRelevant;
account.ClosesAutomatically = input.ClosesAutomatically;
account.Disabled = input.Disabled;
if (before is null)
{
account.Postable = level > 1;
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, account.Id, null, account, actor.UserName, cancellationToken).ConfigureAwait(false);
if (parent is { Postable: true })
{
parent.Postable = false;
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
}
}
else
{
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, account.Id, before, account, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return account;
}
/// <summary>Removes an account without children, postings or use in the templates.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAccountAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, 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<GlAccount, long>();
var account = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing);
if (await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == id), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountHasChildren]);
}
var inTemplates = await uow.Repository<JournalTemplateLine, long>().CountAsync(Query.For<JournalTemplateLine>().Where(l => l.AccountId == id), cancellationToken)
.ConfigureAwait(false);
if (inTemplates > 0 || await UsedAsync(uow, id, cancellationToken).ConfigureAwait(false))
{
throw new ValidationFailedException(["Id:" + LedgerErrors.AccountUsed]);
}
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, account, (GlAccount?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
if (account.ParentId is { } parentId
&& await repository.CountAsync(Query.For<GlAccount>().Where(a => a.ParentId == parentId), cancellationToken).ConfigureAwait(false) == 0
&& await repository.GetAsync(parentId, cancellationToken).ConfigureAwait(false) is { Level: > 1 } parent)
{
parent.Postable = true;
await repository.UpdateAsync(parent, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The journal templates with their lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Every template, by code.</returns>
public async Task<IReadOnlyList<TemplateView>> TemplatesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var templates = (await uow.Repository<JournalTemplate, long>().ListAsync(Query.For<JournalTemplate>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false)).Items;
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(Query.For<JournalTemplateLine>().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))];
}
/// <summary>Saves a journal template with its lines.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The template.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The template as saved.</returns>
public async Task<TemplateView> SaveTemplateAsync(Actor actor, string companyCode, TemplateInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, 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<JournalTemplate, long>();
var code = (input.Code ?? string.Empty).Trim().ToUpperInvariant();
var errors = new List<string>();
if (code.Length is 0 or > 10)
{
errors.Add("Code:" + LedgerErrors.TemplateCode);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
var other = await repository.FindAsync(Query.For<JournalTemplate>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
if (other is not null && other.Id != input.Id)
{
errors.Add("Code:" + LedgerErrors.TemplateDuplicate);
}
if (input.VatRegisterCode is { Length: > 0 } registerCode && await LedgerStore.RegisterAsync(uow, registerCode, cancellationToken).ConfigureAwait(false) is null)
{
errors.Add("VatRegisterCode:" + LedgerErrors.VatRegisterRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
JournalTemplate? before = input.Id is { } id ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
var template = before is null ? new JournalTemplate() : new JournalTemplate { Id = before.Id, RowVersion = before.RowVersion, CreatedAt = before.CreatedAt, CreatedBy = before.CreatedBy, IsDemo = before.IsDemo };
template.Code = code;
template.Description = input.Description.Trim();
template.Area = input.Area;
template.VatRegisterCode = string.IsNullOrWhiteSpace(input.VatRegisterCode) ? null : input.VatRegisterCode.Trim();
template.OpensItems = input.OpensItems;
template.Reverses = input.Reverses;
template.Disabled = input.Disabled;
if (before is null)
{
template.Id = await repository.InsertAsync(template, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, template.Id, null, template, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(template, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, template.Id, before, template, actor.UserName, cancellationToken).ConfigureAwait(false);
}
var templateId = template.Id;
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {templateId}"), cancellationToken).ConfigureAwait(false);
var lines = new List<JournalTemplateLine>();
for (var i = 0; i < input.Lines.Count; i++)
{
var line = input.Lines[i];
var row = new JournalTemplateLine
{
JournalTemplateId = templateId,
SortOrder = (i + 1) * 10,
Role = line.Role,
Side = line.Side,
AccountId = line.AccountId,
Description = LedgerStore.Trim(line.Description, 100),
};
row.Id = await uow.Repository<JournalTemplateLine, long>().InsertAsync(row, cancellationToken).ConfigureAwait(false);
lines.Add(row);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new TemplateView(template, lines);
}
/// <summary>Removes a template that no entry or document type uses.</summary>
/// <param name="actor">Who removes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The template.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteTemplateAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.AccountWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var template = await uow.Repository<JournalTemplate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.TemplateMissing);
var code = template.Code;
var entries = await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().Where(e => e.JournalTemplateId == id), cancellationToken).ConfigureAwait(false);
var types = await uow.Repository<Core.Tables.DocumentType, long>().CountAsync(Query.For<Core.Tables.DocumentType>().Where(t => t.JournalTemplateCode == code), cancellationToken)
.ConfigureAwait(false);
if (entries > 0 || types > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.TemplateUsed]);
}
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_journal_template_lines WHERE journal_template_id = {id}"), cancellationToken).ConfigureAwait(false);
await uow.Repository<JournalTemplate, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, template, (JournalTemplate?)null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Posts the documents in force of a period that have no entry (issue #64: posting in bulk, for instance after the
/// module is licensed), or with <paramref name="again"/> writes again the entries that are not final.
/// </summary>
/// <param name="actor">Who posts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="again">Post again also the documents already posted.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was posted.</returns>
public async Task<PostingReport> PostPendingAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, bool again = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
var posted = 0;
var failed = new List<string>();
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument })
{
List<DocumentHeader> headers;
await using (var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
headers = [.. (await DocumentStores.Of(family).InForceAsync(read, cancellationToken).ConfigureAwait(false))
.Where(h => h.DocumentDate >= from && h.DocumentDate <= to && LedgerPoster.PostingOf(h.Kind) is not null && (again || !h.Posted))
.OrderBy(h => h.DocumentDate).ThenBy(h => h.Id)];
}
foreach (var header in headers)
{
// One transaction per document: one that cannot post does not stop the others.
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
if (await LedgerPoster.PostAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false) is not null)
{
posted++;
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException exception)
{
failed.Add((header.DocumentNumber ?? header.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)) + ": " + string.Join(", ", exception.Errors));
}
}
}
return new PostingReport(posted, failed);
}
/// <summary>Writes the accounts the import of a chart accepted: new codes are added, existing ones updated.</summary>
/// <param name="uow">The unit of work, in a transaction.</param>
/// <param name="accounts">The accounts, parents first or in any order.</param>
/// <param name="update">Update the accounts that exist.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>For each code, whether it was created (<see langword="true"/>) or updated.</returns>
internal static async Task<Dictionary<string, bool>> ImportAsync(IUnitOfWork uow, IReadOnlyList<ImportedAccount> accounts, bool update, CancellationToken cancellationToken)
{
var repository = uow.Repository<GlAccount, long>();
var existing = (await repository.ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Code, StringComparer.OrdinalIgnoreCase);
var result = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (var imported in accounts.OrderBy(a => a.Level).ThenBy(a => a.Code, StringComparer.Ordinal))
{
if (existing.TryGetValue(imported.Code, out var account))
{
if (!update)
{
continue;
}
account.Description = LedgerStore.Trim(imported.Description, 100)!;
account.Nature = imported.Nature;
account.Type = imported.Type;
account.StatementLine = LedgerStore.Trim(imported.StatementLine, 20) ?? account.StatementLine;
account.Reclassification = LedgerStore.Trim(imported.Reclassification, 20) ?? account.Reclassification;
account.VatRelevant = imported.VatRelevant;
account.SubLedger = imported.SubLedger;
account.ClosesAutomatically = imported.ClosesAutomatically;
account.Disabled = imported.Disabled;
await repository.UpdateAsync(account, cancellationToken).ConfigureAwait(false);
result[imported.Code] = false;
continue;
}
account = new GlAccount
{
Code = imported.Code,
Description = LedgerStore.Trim(imported.Description, 100)!,
Level = imported.Level,
ParentId = imported.ParentCode is { } parent && existing.TryGetValue(parent, out var found) ? found.Id : null,
Nature = imported.Nature,
Type = imported.Type,
StatementLine = LedgerStore.Trim(imported.StatementLine, 20),
Reclassification = LedgerStore.Trim(imported.Reclassification, 20),
SubLedger = imported.SubLedger,
VatRelevant = imported.VatRelevant,
ClosesAutomatically = imported.ClosesAutomatically,
Disabled = imported.Disabled,
Postable = imported.Postable,
};
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
existing[account.Code] = account;
result[imported.Code] = true;
}
return result;
}
internal static async Task<bool> UsedAsync(IUnitOfWork uow, long accountId, CancellationToken cancellationToken) =>
await uow.Repository<GlEntryLine, long>().CountAsync(Query.For<GlEntryLine>().Where(l => l.AccountId == accountId), cancellationToken).ConfigureAwait(false) > 0;
private static GlAccount Clone(GlAccount a) => new()
{
Id = a.Id,
Code = a.Code,
Level = a.Level,
ParentId = a.ParentId,
Postable = a.Postable,
IsDemo = a.IsDemo,
RowVersion = a.RowVersion,
CreatedAt = a.CreatedAt,
CreatedBy = a.CreatedBy,
UpdatedAt = a.UpdatedAt,
UpdatedBy = a.UpdatedBy,
};
}
@@ -0,0 +1,257 @@
using System.Globalization;
using Khaemhat.Core.Accounting;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>The permissions of the ledger (module ACCT, <see cref="Modules.BuiltInModules"/>).</summary>
public static class LedgerPermissions
{
/// <summary>See the chart of accounts and the journal templates.</summary>
public const string AccountRead = "ledger.account.read";
/// <summary>Change the chart of accounts and the journal templates.</summary>
public const string AccountWrite = "ledger.account.write";
/// <summary>See the journal, the ledgers and the balances.</summary>
public const string EntryRead = "ledger.entry.read";
/// <summary>Write entries and post documents.</summary>
public const string EntryWrite = "ledger.entry.write";
/// <summary>Make entries final (libro giornale).</summary>
public const string EntryFinalize = "ledger.entry.finalize";
/// <summary>See the VAT registers.</summary>
public const string VatRegisterRead = "vat.register.read";
/// <summary>See the settlements, withholdings, stamp duty and F24.</summary>
public const string SettlementRead = "vat.settlement.read";
/// <summary>Confirm settlements and record tax payments.</summary>
public const string SettlementConfirm = "vat.settlement.confirm";
}
/// <summary>A line of an entry being written.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Description">The description.</param>
/// <param name="Debit">The debit.</param>
/// <param name="Credit">The credit.</param>
/// <param name="CostCenterId">The cost center.</param>
/// <param name="JobId">The job.</param>
public sealed record EntryLineDraft(long? AccountId, long? PartyId, string? Description, decimal Debit, decimal Credit, long? CostCenterId = null, long? JobId = null);
/// <summary>A VAT line of an entry being written.</summary>
/// <param name="TaxCodeId">The VAT code.</param>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Taxable">The taxable amount, with sign.</param>
/// <param name="Tax">The VAT, with sign.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
/// <param name="Exigibility">When the VAT is due.</param>
/// <param name="RegisterId">The register, when different from the one of the entry (self-invoices).</param>
public sealed record EntryVatDraft(
long? TaxCodeId, decimal Rate, string? Nature, decimal Taxable, decimal Tax, decimal NonDeductibleTax = 0m,
Core.Tax.TaxExigibility Exigibility = Core.Tax.TaxExigibility.Immediate, long? RegisterId = null);
/// <summary>
/// What every writer of the ledger shares (ADR 0036): the numbering of the entries in each year, the
/// writing of an entry with its lines and VAT lines (which keep its date and state), the removal of an entry and the
/// lookups of accounts, templates and registers.
/// </summary>
internal static class LedgerStore
{
/// <summary>Writes a new entry with its lines and VAT lines; posted entries get their number.</summary>
public static async Task<GlEntry> InsertAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
entry.Year = entry.EntryDate.Year;
entry.TotalDebit = lines.Sum(l => l.Debit);
entry.TotalCredit = lines.Sum(l => l.Credit);
if (entry.Status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
entry.Id = await uow.Repository<GlEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
return entry;
}
/// <summary>Replaces the lines of an entry and updates it.</summary>
public static async Task UpdateAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
entry.Year = entry.Number is null ? entry.EntryDate.Year : entry.Year;
entry.TotalDebit = lines.Sum(l => l.Debit);
entry.TotalCredit = lines.Sum(l => l.Credit);
if (entry.Status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await RemoveLinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false);
await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false);
}
/// <summary>Changes the state of an entry and of its lines.</summary>
public static async Task SetStatusAsync(IUnitOfWork uow, GlEntry entry, GlEntryStatus status, CancellationToken cancellationToken)
{
entry.Status = status;
if (status != GlEntryStatus.Draft && entry.Number is null)
{
await NumberAsync(uow, entry, cancellationToken).ConfigureAwait(false);
}
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
var text = status.ToString();
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entry_lines SET status = {text} WHERE entry_id = {entry.Id}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entry_vat SET status = {text} WHERE entry_id = {entry.Id}"), cancellationToken).ConfigureAwait(false);
}
/// <summary>Removes an entry with its lines, VAT lines and open items.</summary>
public static async Task DeleteAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await RemoveLinesAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET reversed_by_id = NULL WHERE reversed_by_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.Repository<GlEntry, long>().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>The lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryLine>> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryLine, long>().ListAsync(Query.For<GlEntryLine>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
.ConfigureAwait(false)).Items;
/// <summary>The VAT lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryVat>> VatAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryVat, long>().ListAsync(Query.For<GlEntryVat>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
.ConfigureAwait(false)).Items;
/// <summary>Every account, by id.</summary>
public static async Task<Dictionary<long, GlAccount>> AccountsAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
(await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id);
/// <summary>The rules the validator reads, by id.</summary>
public static Dictionary<long, AccountRule> Rules(IReadOnlyDictionary<long, GlAccount> accounts) =>
accounts.Values.ToDictionary(a => a.Id, a => new AccountRule(a.Id, a.Postable, a.Disabled, a.SubLedger));
/// <summary>A journal template with its lines, by code.</summary>
public static async Task<(JournalTemplate Template, IReadOnlyList<JournalTemplateLine> Lines)?> TemplateAsync(
IUnitOfWork uow, string? code, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(code))
{
return null;
}
var template = await uow.Repository<JournalTemplate, long>().FindAsync(Query.For<JournalTemplate>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
if (template is null)
{
return null;
}
var lines = (await uow.Repository<JournalTemplateLine, long>().ListAsync(
Query.For<JournalTemplateLine>().Where(l => l.JournalTemplateId == template.Id).OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items;
return (template, lines);
}
/// <summary>A VAT register by code.</summary>
public static Task<VatRegister?> RegisterAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(code)
? Task.FromResult<VatRegister?>(null)
: uow.Repository<VatRegister, long>().FindAsync(Query.For<VatRegister>().Where(r => r.Code == code), cancellationToken);
/// <summary>The account of a code, if any.</summary>
public static Task<GlAccount?> AccountAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(code)
? Task.FromResult<GlAccount?>(null)
: uow.Repository<GlAccount, long>().FindAsync(Query.For<GlAccount>().Where(a => a.Code == code), cancellationToken);
/// <summary>
/// Gives the entry the next number of its year (protocollo di prima nota). The numbers follow the order of
/// registration, not of the dates: the date order is the one of the journal, given when entries become final.
/// </summary>
public static async Task NumberAsync(IUnitOfWork uow, GlEntry entry, CancellationToken cancellationToken)
{
entry.Year = entry.EntryDate.Year;
var year = entry.Year;
var number = (await uow.QuerySingleAsync<long?>(SqlFragment.Of($"SELECT MAX(number) FROM gl_entries WHERE year = {year}"), cancellationToken).ConfigureAwait(false) ?? 0L) + 1L;
entry.Number = number;
entry.EntryNumber = Format(entry.Year, number);
}
/// <summary>The number of an entry as shown.</summary>
public static string Format(int year, long number) =>
year.ToString(CultureInfo.InvariantCulture) + "/" + number.ToString("D5", CultureInfo.InvariantCulture);
private static async Task RemoveLinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_entry_lines WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_entry_vat WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
}
private static async Task WriteLinesAsync(
IUnitOfWork uow, GlEntry entry, IReadOnlyList<EntryLineDraft> lines, IReadOnlyList<EntryVatDraft> vat, CancellationToken cancellationToken)
{
var repository = uow.Repository<GlEntryLine, long>();
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
await repository.InsertAsync(new GlEntryLine
{
EntryId = entry.Id,
LineNumber = i + 1,
EntryDate = entry.EntryDate,
Status = entry.Status,
AccountId = line.AccountId ?? 0,
PartyId = line.PartyId,
Description = Trim(line.Description, 200),
Debit = line.Debit,
Credit = line.Credit,
CostCenterId = line.CostCenterId,
JobId = line.JobId,
}, cancellationToken).ConfigureAwait(false);
}
if (vat.Count == 0)
{
return;
}
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id);
var vatRepository = uow.Repository<GlEntryVat, long>();
for (var i = 0; i < vat.Count; i++)
{
var line = vat[i];
var registerId = line.RegisterId ?? entry.VatRegisterId ?? 0;
if (!registers.TryGetValue(registerId, out var register))
{
continue;
}
await vatRepository.InsertAsync(new GlEntryVat
{
EntryId = entry.Id,
LineNumber = i + 1,
VatRegisterId = register.Id,
RegisterKind = register.Kind,
VatDate = entry.VatDate ?? entry.EntryDate,
Status = entry.Status,
TaxCodeId = line.TaxCodeId,
Rate = line.Rate,
Nature = line.Nature,
Exigibility = line.Exigibility,
Taxable = line.Taxable,
Tax = line.Tax,
NonDeductibleTax = line.NonDeductibleTax,
}, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>A text cut to a length.</summary>
public static string? Trim(string? text, int length) => text is null || text.Length <= length ? text : text[..length];
}
@@ -0,0 +1,288 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Ledger;
/// <summary>A recurring entry being written.</summary>
/// <param name="Id">The recurring entry, or <see langword="null"/> for a new one.</param>
/// <param name="Description">What it is (rent, leasing, insurance).</param>
/// <param name="ModelEntryId">The entry copied each time (usually a draft kept as model).</param>
/// <param name="Frequency">How often.</param>
/// <param name="NextDate">The date of the next entry.</param>
/// <param name="EndDate">The last date, if any.</param>
/// <param name="Disabled">Suspended.</param>
public sealed record RecurringEntryInput(long? Id, string Description, long ModelEntryId, RecurrenceFrequency Frequency, DateOnly NextDate, DateOnly? EndDate, bool Disabled = false);
/// <summary>
/// The recurring entries (SPEC §11.7, issue #63): a model entry copied at each due date, posted with the date of the
/// due date; the job <c>ledger.recurring</c> writes those due every morning, and the screen can write them on demand.
/// An entry that cannot be posted (closed period, final journal after the date) stops its recurrence at that date
/// and is reported in the run.
/// </summary>
public sealed class RecurringEntryService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly JournalEntryService _journal;
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="journal">The journal.</param>
/// <param name="audit">The history.</param>
public RecurringEntryService(IUnitOfWorkFactory factory, PermissionService permissions, JournalEntryService journal, AuditTrail audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(journal);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_permissions = permissions;
_journal = journal;
_audit = audit;
}
/// <summary>The recurring entries, by next date.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The recurring entries.</returns>
public async Task<IReadOnlyList<RecurringEntry>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<RecurringEntry, long>().ListAsync(Query.For<RecurringEntry>().OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Writes a recurring entry.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The recurring entry.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The recurring entry.</returns>
public async Task<RecurringEntry> SaveAsync(Actor actor, string companyCode, RecurringEntryInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
var model = await uow.Repository<GlEntry, long>().GetAsync(input.ModelEntryId, cancellationToken).ConfigureAwait(false);
if (model is null || model.Source == GlEntrySource.Document || model.VatRegisterId is not null)
{
errors.Add("ModelEntryId:" + LedgerErrors.RecurringModel);
}
if (input.NextDate == default)
{
errors.Add("NextDate:" + LedgerErrors.DateRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var repository = uow.Repository<RecurringEntry, long>();
RecurringEntry? before = null;
RecurringEntry recurring;
if (input.Id is { } id)
{
recurring = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
before = new RecurringEntry { Id = recurring.Id, Description = recurring.Description, NextDate = recurring.NextDate, Frequency = recurring.Frequency, Disabled = recurring.Disabled };
}
else
{
recurring = new RecurringEntry();
}
recurring.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
recurring.ModelEntryId = input.ModelEntryId;
recurring.Frequency = input.Frequency;
recurring.NextDate = input.NextDate;
recurring.EndDate = input.EndDate;
recurring.Disabled = input.Disabled;
if (before is null)
{
recurring.Id = await repository.InsertAsync(recurring, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(recurring, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, recurring.Id, before, recurring, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return recurring;
}
/// <summary>Deletes a recurring entry (the entries already written stay).</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The recurring entry.</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, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var recurring = await uow.Repository<RecurringEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
await uow.Repository<RecurringEntry, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, recurring, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Writes the recurring entries due up to a day.</summary>
/// <param name="actor">Who writes them.</param>
/// <param name="companyCode">The company.</param>
/// <param name="upTo">Up to this day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The entries written and the problems met.</returns>
public async Task<(int Written, IReadOnlyList<string> Problems)> GenerateAsync(Actor actor, string companyCode, DateOnly upTo, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryWrite, cancellationToken).ConfigureAwait(false);
IReadOnlyList<RecurringEntry> due;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
due = (await uow.Repository<RecurringEntry, long>().ListAsync(
Query.For<RecurringEntry>().Where(r => !r.Disabled && r.NextDate <= upTo).OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items;
}
var written = 0;
var problems = new List<string>();
foreach (var recurring in due)
{
while (recurring.NextDate <= upTo && (recurring.EndDate is null || recurring.NextDate <= recurring.EndDate))
{
var model = await _journal.GetAsync(actor, company, recurring.ModelEntryId, cancellationToken).ConfigureAwait(false);
if (model is null)
{
problems.Add(recurring.Description + ": " + LedgerErrors.RecurringModel);
break;
}
EntryView entry;
try
{
entry = await _journal.SaveAsync(actor, company, new EntryInput(
null,
recurring.NextDate,
model.Entry.Description,
[.. model.Lines.Select(JournalEntryService.Draft)])
{
JournalTemplateId = model.Entry.JournalTemplateId,
PartyId = model.Entry.PartyId,
Notes = recurring.Description,
Post = true,
}, cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException ex)
{
problems.Add(recurring.Description + " " + LedgerReport.Date(recurring.NextDate) + ": " + string.Join(", ", ex.Errors));
break;
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var source = nameof(GlEntrySource.Recurring);
var entryId = entry.Entry.Id;
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET source = {source} WHERE id = {entryId}"), cancellationToken).ConfigureAwait(false);
recurring.LastEntryId = entryId;
recurring.NextDate = Next(recurring.NextDate, recurring.Frequency);
if (recurring.EndDate is { } end && recurring.NextDate > end)
{
recurring.Disabled = true;
}
await uow.Repository<RecurringEntry, long>().UpdateAsync(recurring, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
written++;
}
}
return (written, problems);
}
/// <summary>The date after a due date.</summary>
/// <param name="date">The due date.</param>
/// <param name="frequency">How often.</param>
/// <returns>The next due date (the end of the month stays the end of the month).</returns>
public static DateOnly Next(DateOnly date, RecurrenceFrequency frequency)
{
var months = frequency switch
{
RecurrenceFrequency.Quarterly => 3,
RecurrenceFrequency.HalfYearly => 6,
RecurrenceFrequency.Yearly => 12,
_ => 1,
};
var endOfMonth = date.Day == DateTime.DaysInMonth(date.Year, date.Month);
var next = date.AddMonths(months);
return endOfMonth ? new DateOnly(next.Year, next.Month, DateTime.DaysInMonth(next.Year, next.Month)) : next;
}
}
/// <summary>Writes the recurring entries due of every active company with the ledger, every morning.</summary>
/// <param name="companies">The companies.</param>
/// <param name="service">The recurring entries.</param>
/// <param name="license">The licence.</param>
/// <param name="clock">The clock.</param>
public sealed class RecurringEntriesJob(ICompanyRegistry companies, RecurringEntryService service, ILicenseGate license, TimeProvider clock) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "ledger.recurring";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
if (!license.IsModuleActive(ModuleCodes.Accounting))
{
return "Modulo contabilità non attivo.";
}
var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
int written = 0, done = 0;
var problems = new List<string>();
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is CompanyStatus.Disabled)
{
continue;
}
var (w, p) = await service.GenerateAsync(Actor.System, company.Code, today, cancellationToken).ConfigureAwait(false);
written += w;
problems.AddRange(p.Select(x => company.Code + " - " + x));
done++;
}
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {written} registrazioni ricorrenti scritte.")
+ (problems.Count > 0 ? " Non scritte: " + string.Join("; ", problems) : string.Empty);
}
}
@@ -0,0 +1,848 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Ledger;
/// <summary>A withholding with the name of its party.</summary>
/// <param name="Withholding">The withholding.</param>
/// <param name="PartyName">The supplier or customer.</param>
/// <param name="PartyTaxCode">Its tax code (or VAT number).</param>
public sealed record WithholdingRow(Withholding Withholding, string PartyName, string? PartyTaxCode);
/// <summary>The stamp duty on the e-invoices of a quarter.</summary>
/// <param name="Year">The year.</param>
/// <param name="Quarter">The quarter.</param>
/// <param name="Documents">The invoices with stamp duty.</param>
/// <param name="Amount">The duty.</param>
/// <param name="DueDate">When it is paid (moved to a later quarter below the threshold).</param>
/// <param name="Payment">The F24 line, once recorded.</param>
public sealed record StampDutyQuarter(int Year, int Quarter, int Documents, decimal Amount, DateOnly DueDate, TaxPayment? Payment);
/// <summary>An invoice with stamp duty.</summary>
/// <param name="DocumentId">The invoice.</param>
/// <param name="DocumentNumber">Its number.</param>
/// <param name="DocumentDate">Its date.</param>
/// <param name="PartyName">The customer.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="StampDuty">The duty.</param>
/// <param name="Charged">Charged to the customer (otherwise borne by the company).</param>
/// <param name="Kind">The kind of document.</param>
public sealed record StampDutyDocument(long DocumentId, string? DocumentNumber, DateOnly DocumentDate, string? PartyName, decimal Taxable, decimal StampDuty, bool Charged, DocumentKind Kind);
/// <summary>A line of the F24 written by hand.</summary>
/// <param name="Id">The line, or <see langword="null"/> for a new one.</param>
/// <param name="DueDate">The due date.</param>
/// <param name="PaymentCode">The payment code.</param>
/// <param name="ReferenceYear">The reference year.</param>
/// <param name="ReferencePeriod">The month or installment.</param>
/// <param name="Description">What it pays.</param>
/// <param name="Amount">The amount (negative for a credit used in compensation).</param>
public sealed record TaxPaymentInput(long? Id, DateOnly DueDate, string PaymentCode, int ReferenceYear, string? ReferencePeriod, string Description, decimal Amount);
/// <summary>
/// The taxes that the ledger pays and keeps (SPEC §11.7, issues #65-#66, mockups 047 and 060, ADR 0037): the lines of
/// the F24 with their data file and their payment entry; the withholdings operated on the fees received (due when the
/// invoice is paid, by the 16th of the next month) and suffered on the fees issued, with the data for the CU; the
/// quarterly stamp duty on the e-invoices.
/// </summary>
public sealed class TaxService
{
/// <summary>The stamp duty of a quarter at or below this moves to the next due date (DM 4/12/2023).</summary>
public const decimal StampDutyThreshold = 5000m;
// The sale documents that carry the stamp duty of the quarter: invoices, fees, debit and credit notes.
private static readonly SqlFragment StampKinds = SqlFragment.Join(", ", new[]
{
DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.Fee,
}.Select(k => SqlFragment.Parameter(k.ToString())));
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 pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public TaxService(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 F24 lines due in a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the due dates.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines, by due date and code.</returns>
public async Task<IReadOnlyList<TaxPayment>> PaymentsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
return (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate >= from && t.DueDate <= to).OrderBy(t => t.DueDate).OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Writes a line of the F24 by hand (a tax the ledger does not compute, or a credit used in compensation).</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line.</returns>
public async Task<TaxPayment> SavePaymentAsync(Actor actor, string companyCode, TaxPaymentInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(input.PaymentCode) || input.PaymentCode.Trim().Length > 10)
{
errors.Add("PaymentCode:" + LedgerErrors.AmountRequired);
}
if (string.IsNullOrWhiteSpace(input.Description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
if (input.Amount == 0m)
{
errors.Add("Amount:" + LedgerErrors.AmountRequired);
}
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 payments = uow.Repository<TaxPayment, long>();
TaxPayment? before = null;
TaxPayment payment;
if (input.Id is { } id)
{
payment = await payments.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (payment.PaidOn is not null || payment.Source != TaxPaymentSource.Manual)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
before = Copy(payment);
}
else
{
payment = new TaxPayment { Source = TaxPaymentSource.Manual };
}
payment.DueDate = input.DueDate;
payment.PaymentCode = input.PaymentCode.Trim();
payment.ReferenceYear = input.ReferenceYear;
payment.ReferencePeriod = LedgerStore.Trim(input.ReferencePeriod?.Trim(), 10);
payment.Description = LedgerStore.Trim(input.Description.Trim(), 200)!;
payment.Amount = input.Amount;
if (before is null)
{
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>Deletes a line written by hand and not paid.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeletePaymentAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payment = await uow.Repository<TaxPayment, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (payment.PaidOn is not null || payment.Source != TaxPaymentSource.Manual)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
await uow.Repository<TaxPayment, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, payment, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The F24 of a due date: its unpaid lines, one per code and period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The form.</returns>
public async Task<TaxPaymentForm> FormAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await FormAsync(uow, dueDate, paid: false, cancellationToken).ConfigureAwait(false);
}
/// <summary>The data file of the F24 of a due date.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> ExportFormAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<ITaxPaymentFormExporter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var form = await FormAsync(uow, dueDate, paid: null, cancellationToken).ConfigureAwait(false);
return new LedgerFile(exporter.FileName(form), "text/csv", exporter.Export(form));
}
/// <summary>
/// Records the payment of the F24 of a due date: its lines are paid, the withholdings in it are paid, and the entry
/// <c>F24</c> moves the tax accounts against the bank.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="paidOn">The day of payment.</param>
/// <param name="bankAccountId">The bank account debited; <see langword="null"/> for the default one.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The payment entry, if the ledger has the template.</returns>
public async Task<GlEntry?> PayAsync(Actor actor, string companyCode, DateOnly dueDate, DateOnly paidOn, long? bankAccountId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate == dueDate && t.PaidOn == null).OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
if (payments.Count == 0)
{
throw new ValidationFailedException(["DueDate:" + LedgerErrors.PaymentPaid]);
}
var bank = await BankAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false);
GlEntry? entry = null;
if (await LedgerStore.TemplateAsync(uow, "F24", cancellationToken).ConfigureAwait(false) is { } found)
{
var (template, templateLines) = found;
long? Role(PostingRole role) => templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId;
var stampAccount = templateLines.FirstOrDefault(l => l.Role == PostingRole.Account && l.AccountId is not null)?.AccountId;
var bankAccount = (await LedgerStore.AccountAsync(uow, bank?.AccountCode, cancellationToken).ConfigureAwait(false))?.Id ?? Role(PostingRole.Bank);
var lines = new List<EntryLineDraft>();
foreach (var payment in payments)
{
var account = payment.Source switch
{
TaxPaymentSource.Withholding => Role(PostingRole.WithholdingPayable),
TaxPaymentSource.StampDuty => stampAccount,
_ => Role(PostingRole.VatSettlement),
};
if (account is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var text = LedgerStore.Trim(payment.PaymentCode + " " + payment.Description, 200);
lines.Add(payment.Amount >= 0m
? new EntryLineDraft(account, null, text, payment.Amount, 0m)
: new EntryLineDraft(account, null, text, 0m, -payment.Amount));
}
var total = payments.Sum(p => p.Amount);
if (bankAccount is null)
{
throw new ValidationFailedException(["BankAccountId:" + LedgerErrors.BankAccountMissing]);
}
if (total != 0m)
{
lines.Add(total > 0m ? new EntryLineDraft(bankAccount, null, "Addebito F24", 0m, total) : new EntryLineDraft(bankAccount, null, "Addebito F24", -total, 0m));
}
entry = await LedgerStore.InsertAsync(uow, new GlEntry
{
EntryDate = paidOn,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " scadenza " + LedgerReport.Date(dueDate), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.TaxPayment,
IsDemo = payments.All(p => p.IsDemo),
}, lines, [], cancellationToken).ConfigureAwait(false);
}
foreach (var payment in payments)
{
var before = Copy(payment);
payment.PaidOn = paidOn;
payment.BankAccountId = bank?.Id;
payment.GlEntryId = entry?.Id;
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
if (payment.Source == TaxPaymentSource.Withholding)
{
var paymentId = payment.Id;
var paidStatus = nameof(WithholdingStatus.Paid);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE withholdings SET status = {paidStatus} WHERE tax_payment_id = {paymentId}"), cancellationToken).ConfigureAwait(false);
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return entry;
}
/// <summary>Takes back the payment of an F24: the entry goes (or is reversed when final), the lines are unpaid.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task UnpayAsync(Actor actor, string companyCode, DateOnly dueDate, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.DueDate == dueDate && t.PaidOn != null), cancellationToken).ConfigureAwait(false)).Items;
foreach (var entryId in payments.Select(p => p.GlEntryId).OfType<long>().Distinct())
{
if (await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is not { } entry)
{
continue;
}
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
foreach (var payment in payments)
{
var before = Copy(payment);
payment.PaidOn = null;
payment.GlEntryId = null;
payment.BankAccountId = null;
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
var paymentId = payment.Id;
var due = nameof(WithholdingStatus.Due);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE withholdings SET status = {due} WHERE tax_payment_id = {paymentId}"), cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The withholdings of the documents of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the documents.</param>
/// <param name="direction">Operated or suffered; <see langword="null"/> for both.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholdings, by date.</returns>
public async Task<IReadOnlyList<WithholdingRow>> WithholdingsAsync(
Actor actor, string companyCode, int year, WithholdingDirection? direction = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var query = Query.For<Withholding>().Where(w => w.DocumentDate >= from && w.DocumentDate <= to);
if (direction is { } d)
{
query = query.Where(w => w.Direction == d);
}
var items = (await uow.Repository<Withholding, long>().ListAsync(query.OrderBy(w => w.DocumentDate), cancellationToken).ConfigureAwait(false)).Items;
return await RowsAsync(uow, items, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Records that the invoice of a withholding has been paid. An operated withholding becomes due: the entry
/// <c>RIT</c> moves it from the supplier to the tax authority, and it joins the F24 line of its code due on the
/// 16th of the next month. A suffered withholding: the entry <c>RITS</c> moves it from the customer to the tax credit.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The withholding.</param>
/// <param name="paidOn">The day the invoice was paid.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholding.</returns>
public async Task<Withholding> InvoicePaidAsync(Actor actor, string companyCode, long id, DateOnly paidOn, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var settlementRules = pack.Require<IVatSettlementRules>();
var withholdingRules = pack.GetFeature<IWithholdingRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var withholding = await uow.Repository<Withholding, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (withholding.InvoicePaidOn is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
var before = Copy(withholding);
var operated = withholding.Direction == WithholdingDirection.Operated;
var entry = await PostWithholdingAsync(uow, withholding, paidOn, operated ? "RIT" : "RITS", cancellationToken).ConfigureAwait(false);
withholding.InvoicePaidOn = paidOn;
withholding.GlEntryId = entry?.Id;
if (operated)
{
withholding.Status = WithholdingStatus.Due;
withholding.PaymentCode ??= PaymentCodeOf(withholding, withholdingRules);
var due = settlementRules.WithholdingDue(paidOn.Year, paidOn.Month);
var code = withholding.PaymentCode;
var payments = uow.Repository<TaxPayment, long>();
var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture);
var year = paidOn.Year;
var payment = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year
&& t.ReferencePeriod == period && t.PaidOn == null),
cancellationToken).ConfigureAwait(false);
if (payment is null)
{
payment = new TaxPayment
{
DueDate = due,
PaymentCode = code,
ReferenceYear = year,
ReferencePeriod = period,
Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!,
Amount = withholding.Amount,
Source = TaxPaymentSource.Withholding,
IsDemo = withholding.IsDemo,
};
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
payment.Amount += withholding.Amount;
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
withholding.TaxPaymentId = payment.Id;
}
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return withholding;
}
/// <summary>Takes back the payment of the invoice of a withholding while its F24 line is not paid.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The withholding.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The withholding.</returns>
public async Task<Withholding> UndoInvoicePaidAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var withholding = await uow.Repository<Withholding, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (withholding.Status == WithholdingStatus.Paid)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
var before = Copy(withholding);
if (withholding.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
payment.Amount -= withholding.Amount;
if (payment.Amount == 0m)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
}
if (withholding.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
withholding.InvoicePaidOn = null;
withholding.GlEntryId = null;
withholding.TaxPaymentId = null;
withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered;
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return withholding;
}
/// <summary>
/// The data for the single certifications (CU) of a year: one row per payee with the fees paid in the year, the
/// taxable amount, the withholdings and the reason, as the intermediary needs them to fill the model.
/// </summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The CSV file.</returns>
public async Task<LedgerFile> CertificationsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var items = (await uow.Repository<Withholding, long>().ListAsync(
Query.For<Withholding>().Where(w => w.Direction == WithholdingDirection.Operated && w.InvoicePaidOn >= from && w.InvoicePaidOn <= to).OrderBy(w => w.PartyId),
cancellationToken).ConfigureAwait(false)).Items;
var rows = await RowsAsync(uow, items, cancellationToken).ConfigureAwait(false);
using var buffer = new MemoryStream();
await using (var csv = new CsvWriter(buffer, CsvOptions.Italian, leaveOpen: true))
{
await csv.WriteRowAsync(
["codice_fiscale", "denominazione", "causale", "anno", "compenso_lordo", "somme_non_soggette", "imponibile", "ritenute", "codice_tributo", "documenti"],
cancellationToken).ConfigureAwait(false);
foreach (var group in rows.GroupBy(r => (r.Withholding.PartyId, r.Withholding.Reason, r.Withholding.PaymentCode)))
{
var first = group.First();
var gross = group.Sum(r => r.Withholding.Taxable);
var taxable = group.Sum(r => Math.Round(r.Withholding.Taxable * r.Withholding.BasePercent / 100m, 2, MidpointRounding.AwayFromZero));
await csv.WriteRowAsync(
[first.PartyTaxCode, first.PartyName, group.Key.Reason, year, gross, gross - taxable, taxable, group.Sum(r => r.Withholding.Amount), group.Key.PaymentCode,
string.Join(' ', group.Select(r => r.Withholding.DocumentNumber))],
cancellationToken).ConfigureAwait(false);
}
}
return new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"CU_{year}.csv"), "text/csv", buffer.ToArray());
}
/// <summary>The stamp duty on the e-invoices of each quarter 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>Four quarters.</returns>
public async Task<IReadOnlyList<StampDutyQuarter>> StampDutyAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<IVatSettlementRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await StampDutyAsync(uow, rules, year, cancellationToken).ConfigureAwait(false);
}
/// <summary>The sale invoices with stamp duty of a quarter.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices, by date.</returns>
public async Task<IReadOnlyList<StampDutyDocument>> StampDutyDocumentsAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var from = new DateOnly(year, ((quarter - 1) * 3) + 1, 1);
var to = from.AddMonths(3).AddDays(-1);
var draft = nameof(DocumentStatus.Draft);
var cancelled = nameof(DocumentStatus.Cancelled);
return await uow.QueryAsync<StampDutyDocument>(SqlFragment.Of($"""
SELECT d.id AS document_id, d.document_number AS document_number, d.document_date AS document_date, p.name AS party_name,
d.taxable_amount AS taxable, d.stamp_duty AS stamp_duty, d.stamp_duty_charged AS charged, d.kind AS kind
FROM sale_documents d LEFT JOIN parties p ON p.id = d.party_id
WHERE d.stamp_duty > 0 AND d.document_date >= {from} AND d.document_date <= {to} AND d.status <> {draft} AND d.status <> {cancelled} AND d.kind IN ({StampKinds})
ORDER BY d.document_date, d.number
"""), cancellationToken).ConfigureAwait(false);
}
/// <summary>Records the F24 line of the stamp duty of a quarter (or updates it while unpaid).</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line, or <see langword="null"/> when no duty is due.</returns>
public async Task<TaxPayment?> StampDutyPaymentAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentOutOfRangeException.ThrowIfLessThan(quarter, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(quarter, 4);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.Require<ITaxPaymentFormExporter>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var data = (await StampDutyAsync(uow, rules, year, cancellationToken).ConfigureAwait(false))[quarter - 1];
if (data.Payment is { PaidOn: not null })
{
throw new ValidationFailedException(["Quarter:" + LedgerErrors.PaymentPaid]);
}
if (data.Amount == 0m)
{
if (data.Payment is { } stale)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(stale.Id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return null;
}
var payment = data.Payment ?? new TaxPayment { Source = TaxPaymentSource.StampDuty, SourceId = (year * 10L) + quarter, ReferenceYear = year };
var before = data.Payment is null ? null : Copy(payment);
payment.DueDate = data.DueDate;
payment.PaymentCode = form.StampDutyCode(quarter);
payment.Description = string.Create(CultureInfo.InvariantCulture, $"Imposta di bollo fatture elettroniche {quarter}° trimestre {year} ({data.Documents} fatture)");
payment.Amount = data.Amount;
if (before is null)
{
payment.Id = await uow.Repository<TaxPayment, long>().InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, before is null ? AuditAction.Insert : AuditAction.Update, payment.Id, before, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>
/// The stamp duty of each quarter from the issued sale invoices with the duty, with the due date moved when the
/// amount stays below the threshold: the first quarter with the second, the first two with the third.
/// </summary>
internal static async Task<IReadOnlyList<StampDutyQuarter>> StampDutyAsync(IUnitOfWork uow, IVatSettlementRules rules, int year, CancellationToken cancellationToken)
{
var from = new DateOnly(year, 1, 1);
var to = new DateOnly(year, 12, 31);
var draft = nameof(DocumentStatus.Draft);
var cancelled = nameof(DocumentStatus.Cancelled);
var rows = await uow.QueryAsync<StampRow>(SqlFragment.Of($"""
SELECT document_date AS document_date, stamp_duty AS stamp_duty FROM sale_documents
WHERE stamp_duty > 0 AND document_date >= {from} AND document_date <= {to} AND status <> {draft} AND status <> {cancelled} AND kind IN ({StampKinds})
"""), cancellationToken).ConfigureAwait(false);
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.StampDuty && t.ReferenceYear == year), cancellationToken).ConfigureAwait(false)).Items;
var result = new List<StampDutyQuarter>();
var carried = 0m;
for (var q = 1; q <= 4; q++)
{
var quarter = rows.Where(r => ((r.DocumentDate.Month - 1) / 3) + 1 == q).ToList();
var amount = quarter.Sum(r => r.StampDuty);
var due = rules.StampDutyDue(year, q);
if (q == 1 && amount <= StampDutyThreshold)
{
due = rules.StampDutyDue(year, 2);
carried = amount;
}
else if (q == 2 && carried > 0m && carried + amount <= StampDutyThreshold)
{
due = rules.StampDutyDue(year, 3);
carried += amount;
}
else
{
carried = 0m;
}
var sourceId = (year * 10L) + q;
result.Add(new StampDutyQuarter(year, q, quarter.Count, amount, due, payments.FirstOrDefault(p => p.SourceId == sourceId)));
}
// A first quarter moved to the second, when the second goes over the threshold, keeps the due date of the second.
if (result[0].DueDate == rules.StampDutyDue(year, 2) && result[1].DueDate == rules.StampDutyDue(year, 3))
{
result[0] = result[0] with { DueDate = rules.StampDutyDue(year, 3) };
}
return result;
}
private static async Task<TaxPaymentForm> FormAsync(IUnitOfWork uow, DateOnly dueDate, bool? paid, CancellationToken cancellationToken)
{
var query = Query.For<TaxPayment>().Where(t => t.DueDate == dueDate);
query = paid switch
{
true => query.Where(t => t.PaidOn != null),
false => query.Where(t => t.PaidOn == null),
_ => query,
};
var payments = (await uow.Repository<TaxPayment, long>().ListAsync(query.OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items;
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var lines = payments
.GroupBy(p => (p.PaymentCode, p.ReferencePeriod, p.ReferenceYear))
.Select(g =>
{
var amount = g.Sum(p => p.Amount);
return new TaxPaymentFormLine(g.Key.PaymentCode, g.Key.ReferencePeriod, g.Key.ReferenceYear, Math.Max(0m, amount), Math.Max(0m, -amount), g.First().Description);
})
.ToList();
return new TaxPaymentForm(dueDate, profile?.TaxCode ?? profile?.VatNumber ?? string.Empty, profile?.LegalName ?? string.Empty, lines);
}
private static async Task<BankAccount?> BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken)
{
var banks = uow.Repository<BankAccount, long>();
if (id is { } bankId)
{
return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["BankAccountId:" + LedgerErrors.BankAccountMissing]);
}
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
if (profile?.DefaultBankAccountId is { } defaultId && await banks.GetAsync(defaultId, cancellationToken).ConfigureAwait(false) is { } preferred)
{
return preferred;
}
return await banks.FindAsync(Query.For<BankAccount>().Where(b => b.IsDefault), cancellationToken).ConfigureAwait(false);
}
// The entry of a withholding when its invoice is paid: operated, supplier debit / withholdings payable credit;
// suffered, withholdings credit debit / customer credit. The party keeps its own account when it has one.
private static async Task<GlEntry?> PostWithholdingAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string templateCode, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
var operated = withholding.Direction == WithholdingDirection.Operated;
var party = await uow.Repository<Party, long>().GetAsync(withholding.PartyId, cancellationToken).ConfigureAwait(false);
var partyRole = operated ? PostingRole.Supplier : PostingRole.Customer;
var taxRole = operated ? PostingRole.WithholdingPayable : PostingRole.WithholdingCredit;
var partyAccount = (await LedgerStore.AccountAsync(uow, operated ? party?.SupplierAccountCode : party?.CustomerAccountCode, cancellationToken).ConfigureAwait(false))?.Id
?? templateLines.FirstOrDefault(l => l.Role == partyRole)?.AccountId;
var taxAccount = templateLines.FirstOrDefault(l => l.Role == taxRole)?.AccountId;
if (partyAccount is null || taxAccount is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var amount = Math.Abs(withholding.Amount);
var credit = withholding.Amount < 0m;
var text = LedgerStore.Trim("Ritenuta fattura " + withholding.DocumentNumber, 200);
EntryLineDraft Line(long account, long? partyId, bool debit) =>
debit != credit ? new EntryLineDraft(account, partyId, text, amount, 0m) : new EntryLineDraft(account, partyId, text, 0m, amount);
IReadOnlyList<EntryLineDraft> lines = operated
? [Line(partyAccount.Value, withholding.PartyId, debit: true), Line(taxAccount.Value, null, debit: false)]
: [Line(taxAccount.Value, null, debit: true), Line(partyAccount.Value, withholding.PartyId, debit: false)];
return await LedgerStore.InsertAsync(uow, new GlEntry
{
EntryDate = date,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " " + withholding.DocumentNumber, 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Withholding,
SourceFamily = withholding.SourceFamily,
SourceDocumentId = withholding.SourceDocumentId,
DocumentNumber = withholding.DocumentNumber,
DocumentDate = withholding.DocumentDate,
PartyId = withholding.PartyId,
IsDemo = withholding.IsDemo,
}, lines, [], cancellationToken).ConfigureAwait(false);
}
private static string PaymentCodeOf(Withholding withholding, IWithholdingRules? rules)
{
var kinds = rules?.Kinds ?? [];
var kind = kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType && k.Rate == withholding.Rate && k.PaymentReason == withholding.Reason)
?? kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType && k.PaymentReason == withholding.Reason)
?? kinds.FirstOrDefault(k => k.InvoiceType == withholding.WithholdingType);
return kind?.PaymentCode ?? "1040";
}
private static async Task<IReadOnlyList<WithholdingRow>> RowsAsync(IUnitOfWork uow, IReadOnlyList<Withholding> items, CancellationToken cancellationToken)
{
var ids = items.Select(w => w.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 [.. items.Select(w => parties.TryGetValue(w.PartyId, out var p)
? new WithholdingRow(w, p.Name, p.TaxCode ?? p.VatNumber)
: new WithholdingRow(w, string.Empty, null))];
}
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
private static TaxPayment Copy(TaxPayment p) => new()
{
Id = p.Id,
DueDate = p.DueDate,
PaymentCode = p.PaymentCode,
ReferenceYear = p.ReferenceYear,
ReferencePeriod = p.ReferencePeriod,
Description = p.Description,
Amount = p.Amount,
Source = p.Source,
PaidOn = p.PaidOn,
GlEntryId = p.GlEntryId,
};
private static Withholding Copy(Withholding w) => new()
{
Id = w.Id,
Direction = w.Direction,
DocumentNumber = w.DocumentNumber,
Amount = w.Amount,
Status = w.Status,
InvoicePaidOn = w.InvoicePaidOn,
TaxPaymentId = w.TaxPaymentId,
GlEntryId = w.GlEntryId,
};
private sealed record StampRow(DateOnly DocumentDate, decimal StampDuty);
}
@@ -0,0 +1,770 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Ledger;
/// <summary>A line of a VAT register.</summary>
/// <param name="EntryId">The entry.</param>
/// <param name="EntryNumber">The number of the entry.</param>
/// <param name="VatProtocol">The protocol.</param>
/// <param name="VatDate">The VAT date.</param>
/// <param name="DocumentNumber">The number of the document.</param>
/// <param name="DocumentDate">The date of the document.</param>
/// <param name="PartyName">The customer or supplier.</param>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Exigibility">When the VAT is due.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
/// <param name="Status">The state of the entry.</param>
public sealed record VatRegisterRow(
long EntryId, string? EntryNumber, long? VatProtocol, DateOnly VatDate, string? DocumentNumber, DateOnly? DocumentDate, string? PartyName,
decimal Rate, string? Nature, TaxExigibility Exigibility, decimal Taxable, decimal Tax, decimal NonDeductibleTax, GlEntryStatus Status);
/// <summary>A total by rate of a VAT register.</summary>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
public sealed record VatRateTotal(decimal Rate, string? Nature, decimal Taxable, decimal Tax, decimal NonDeductibleTax);
/// <summary>A VAT register in a period.</summary>
/// <param name="Register">The register.</param>
/// <param name="Rows">The lines, by date and protocol.</param>
/// <param name="Totals">The totals by rate.</param>
public sealed record VatRegisterView(VatRegister Register, IReadOnlyList<VatRegisterRow> Rows, IReadOnlyList<VatRateTotal> Totals);
/// <summary>A settlement with its lines and the names of its registers.</summary>
/// <param name="Settlement">The settlement.</param>
/// <param name="Lines">One line per register.</param>
/// <param name="Registers">The registers, by id.</param>
public sealed record VatSettlementView(VatSettlement Settlement, IReadOnlyList<VatSettlementLine> Lines, IReadOnlyDictionary<long, VatRegister> Registers);
/// <summary>A file produced by the ledger.</summary>
/// <param name="FileName">The name proposed.</param>
/// <param name="MediaType">The media type.</param>
/// <param name="Content">The content.</param>
public sealed record LedgerFile(string FileName, string MediaType, byte[] Content);
/// <summary>
/// The VAT of the ledger (SPEC §11.7, issue #65, mockups 045-046, ADR 0037): the registers read from the VAT lines of
/// the posted entries, their provisional print and their final print with the pages numbered by year; the periodic
/// settlement, monthly or quarterly as the company profile says, with the credit and the debit below the minimum
/// carried, the interest of quarterly payers, the pro rata and the December advance; its confirmation settles the
/// periods (no more VAT documents in them), posts the entry that closes the VAT accounts and writes the F24 line; the
/// communication of the settlements (LIPE) of a quarter.
/// </summary>
public sealed class VatService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly FiscalYearService _fiscal;
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="fiscal">The fiscal calendar.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public VatService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, FiscalYearService fiscal, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_fiscal = fiscal;
_audit = audit;
_clock = clock;
}
/// <summary>A VAT register in a period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="registerId">The register.</param>
/// <param name="from">From this VAT date.</param>
/// <param name="to">Up to this VAT date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The register.</returns>
public async Task<VatRegisterView> RegisterAsync(Actor actor, string companyCode, long registerId, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.VatRegisterRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await RegisterAsync(uow, registerId, from, to, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The print of a register: provisional (any period, nothing recorded) or final (from the day after the last final
/// print, numbering the pages after the last page of the year).
/// </summary>
/// <param name="actor">Who prints.</param>
/// <param name="companyCode">The company.</param>
/// <param name="registerId">The register.</param>
/// <param name="from">From this day (for a final print, the day after the last one).</param>
/// <param name="to">Up to this day.</param>
/// <param name="final">A final print.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The PDF.</returns>
public async Task<LedgerFile> PrintRegisterAsync(Actor actor, string companyCode, long registerId, DateOnly from, DateOnly to, bool final, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(
_permissions, actor, companyCode, final ? LedgerPermissions.SettlementConfirm : LedgerPermissions.VatRegisterRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var register = await uow.Repository<VatRegister, long>().GetAsync(registerId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.VatRegisterRequired);
var firstPage = 1;
if (final)
{
var expected = register.LastPrintedDate is { } last && last.Year == to.Year ? last.AddDays(1) : new DateOnly(to.Year, 1, 1);
if (from != expected || to < from || to.Year != from.Year)
{
throw new ValidationFailedException(["From:" + LedgerErrors.PrintOrder]);
}
firstPage = register.PrintYear == to.Year ? register.LastPage + 1 : 1;
}
var view = await RegisterAsync(uow, registerId, from, to, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<string?>>();
foreach (var row in view.Rows)
{
rows.Add([
row.VatProtocol?.ToString(CultureInfo.InvariantCulture), LedgerReport.Date(row.VatDate), row.DocumentNumber, LedgerReport.Date(row.DocumentDate), row.PartyName,
row.Nature ?? row.Rate.ToString("0.##", CultureInfo.InvariantCulture) + "%", LedgerReport.Money(row.Taxable), LedgerReport.Money(row.Tax),
LedgerReport.Money(row.NonDeductibleTax),
]);
}
foreach (var total in view.Totals)
{
rows.Add(["**Totale", null, null, null, null, total.Nature ?? total.Rate.ToString("0.##", CultureInfo.InvariantCulture) + "%",
LedgerReport.Money(total.Taxable), LedgerReport.Money(total.Tax), LedgerReport.Money(total.NonDeductibleTax)]);
}
rows.Add(["**Totale registro", null, null, null, null, null, LedgerReport.Money(view.Totals.Sum(t => t.Taxable)), LedgerReport.Money(view.Totals.Sum(t => t.Tax)),
LedgerReport.Money(view.Totals.Sum(t => t.NonDeductibleTax))]);
var (file, pages) = await LedgerReport.WriteAsync(
CompanyLine(profile),
register.Code + " - " + register.Description,
(final ? "Stampa definitiva" : "Stampa provvisoria") + " dal " + LedgerReport.Date(from) + " al " + LedgerReport.Date(to),
[new("Prot.", 40), new("Data reg.", 55), new("Documento", 75), new("Data doc.", 55), new("Controparte", 210), new("Aliquota", 50), new("Imponibile", 85, true),
new("Imposta", 75, true), new("Indetraibile", 70, true)],
rows,
to.Year,
firstPage,
cancellationToken).ConfigureAwait(false);
if (final)
{
var before = new VatRegister { Id = register.Id, Code = register.Code, PrintYear = register.PrintYear, LastPage = register.LastPage, LastPrintedDate = register.LastPrintedDate };
register.PrintYear = to.Year;
register.LastPage = firstPage + pages - 1;
register.LastPrintedDate = to;
await uow.Repository<VatRegister, long>().UpdateAsync(register, cancellationToken).ConfigureAwait(false);
await uow.Repository<VatRegisterPrint, long>().InsertAsync(new VatRegisterPrint
{
VatRegisterId = register.Id,
Year = to.Year,
FromDate = from,
ToDate = to,
FirstPage = firstPage,
LastPage = register.LastPage,
PrintedAt = _clock.GetUtcNow().UtcDateTime,
PrintedBy = actor.UserName,
}, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, register.Id, before, register, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new LedgerFile(
string.Create(CultureInfo.InvariantCulture, $"{register.Code}_{from:yyyyMMdd}_{to:yyyyMMdd}{(final ? "_definitivo" : string.Empty)}.pdf"),
Infrastructure.Files.PdfWriter.MediaType,
file);
}
/// <summary>The settlements 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 settlements, by period.</returns>
public async Task<IReadOnlyList<VatSettlement>> SettlementsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<VatSettlement, long>().ListAsync(Query.For<VatSettlement>().Where(s => s.Year == year).OrderBy(s => s.Number), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// <summary>A settlement with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement, or none.</returns>
public async Task<VatSettlementView?> SettlementAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, 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>
/// Computes (again) the settlement of a period from the registers: the VAT due and deductible, the credit and the
/// debit carried from the previous settlement, the advance for the last period, interest and minimum.
/// </summary>
/// <param name="actor">Who computes: needs <c>vat.settlement.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="number">The month or quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement, as a draft.</returns>
public async Task<VatSettlementView> ComputeAsync(Actor actor, string companyCode, int year, int number, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var periodicity = profile?.VatPeriodicity ?? VatPeriodicity.Monthly;
var period = TaxPeriod.Of(year, number, periodicity);
var settlements = uow.Repository<VatSettlement, long>();
var existing = await settlements.FindAsync(
Query.For<VatSettlement>().Where(s => s.Year == year && s.Number == number && s.Periodicity == periodicity), cancellationToken).ConfigureAwait(false);
if (existing is { Status: VatSettlementStatus.Confirmed })
{
throw new ValidationFailedException(["Number:" + LedgerErrors.SettlementConfirmed]);
}
var later = await settlements.CountAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate > period.End), cancellationToken).ConfigureAwait(false);
if (later > 0)
{
throw new ValidationFailedException(["Number:" + LedgerErrors.SettlementLater]);
}
var previousList = (await settlements.ListAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.EndDate < period.Start).OrderByDescending(s => s.EndDate).Take(1),
cancellationToken).ConfigureAwait(false)).Items;
var previous = previousList.Count > 0 ? previousList[0] : null;
var last = number == (periodicity == VatPeriodicity.Monthly ? 12 : 4);
var advance = 0m;
if (last)
{
advance = await uow.QuerySingleAsync<decimal?>(
SqlFragment.Of($"SELECT SUM(amount) FROM tax_payments WHERE source = {nameof(TaxPaymentSource.VatAdvance)} AND reference_year = {year}"),
cancellationToken).ConfigureAwait(false) ?? 0m;
}
var totals = await TotalsAsync(uow, period.Start, period.End, cancellationToken).ConfigureAwait(false);
var terms = new VatSettlementTerms(
ProRataPercent: profile?.ProRataPercent is > 0m and var p ? p : 100m,
PreviousCredit: previous?.CreditCarried ?? 0m,
PreviousDebit: previous?.DebitCarried ?? 0m,
AdvancePaid: advance,
InterestPercent: pack.Calendar.VatInterestRate(periodicity),
MinimumPayment: rules.MinimumPayment);
var result = VatSettlementCalculator.Compute(totals, terms);
var settlement = existing ?? new VatSettlement { Year = year, Number = number, Periodicity = periodicity };
settlement.StartDate = period.Start;
settlement.EndDate = period.End;
settlement.SettlementDate = period.End;
settlement.Status = VatSettlementStatus.Draft;
settlement.SalesTax = result.SalesTax;
settlement.PurchaseTax = result.PurchaseTax;
settlement.NonDeductibleTax = result.NonDeductibleTax;
settlement.DeferredTax = result.DeferredTax;
settlement.ProRataPercent = terms.ProRataPercent;
settlement.PreviousCredit = terms.PreviousCredit;
settlement.PreviousDebit = terms.PreviousDebit;
settlement.AdvancePaid = terms.AdvancePaid;
settlement.InterestPercent = terms.InterestPercent;
settlement.Interest = result.Interest;
settlement.AmountDue = result.AmountDue;
settlement.CreditCarried = result.CreditCarried;
settlement.DebitCarried = result.DebitCarried;
settlement.PaymentCode = rules.PaymentCode(period);
settlement.DueDate = pack.Calendar.VatPaymentDue(period);
if (existing is null)
{
settlement.Id = await settlements.InsertAsync(settlement, cancellationToken).ConfigureAwait(false);
}
else
{
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
}
var settlementId = settlement.Id;
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM vat_settlement_lines WHERE settlement_id = {settlementId}"), cancellationToken).ConfigureAwait(false);
foreach (var total in totals)
{
await uow.Repository<VatSettlementLine, long>().InsertAsync(new VatSettlementLine
{
SettlementId = settlementId,
VatRegisterId = total.RegisterId,
RegisterKind = total.Kind,
Documents = total.Documents,
Taxable = total.Taxable,
Tax = total.Tax,
NonDeductibleTax = total.NonDeductibleTax,
DeferredTax = total.DeferredTax,
}, cancellationToken).ConfigureAwait(false);
}
id = settlementId;
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Confirms a settlement: the periods become settled, the entry <c>LIQ</c> closes the VAT accounts into the VAT
/// settlement account (with the interest and the pro rata) and the amount due becomes an F24 line.
/// </summary>
/// <param name="actor">Who confirms: needs <c>vat.settlement.confirm</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement as confirmed.</returns>
public async Task<VatSettlementView> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.GetFeature<ITaxPaymentFormExporter>();
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var settlements = uow.Repository<VatSettlement, long>();
var settlement = await settlements.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
if (settlement.Status == VatSettlementStatus.Confirmed)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementConfirmed]);
}
var start = settlement.StartDate;
var earlier = await settlements.CountAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Draft && s.StartDate < start), cancellationToken).ConfigureAwait(false);
if (earlier > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementPrevious]);
}
var before = Copy(settlement);
var entry = await PostSettlementAsync(uow, settlement, cancellationToken).ConfigureAwait(false);
settlement.GlEntryId = entry?.Id;
if (settlement.AmountDue > 0m)
{
var period = TaxPeriod.Of(settlement.Year, settlement.Number, settlement.Periodicity);
var paymentId = await uow.Repository<TaxPayment, long>().InsertAsync(new TaxPayment
{
DueDate = settlement.DueDate ?? settlement.EndDate,
PaymentCode = settlement.PaymentCode ?? rules.PaymentCode(period),
ReferenceYear = settlement.Year,
ReferencePeriod = rules.PaymentPeriod(period),
Description = Describe(settlement, form),
Amount = settlement.AmountDue,
Source = TaxPaymentSource.VatSettlement,
SourceId = settlement.Id,
IsDemo = settlement.IsDemo,
}, cancellationToken).ConfigureAwait(false);
settlement.TaxPaymentId = paymentId;
}
settlement.Status = VatSettlementStatus.Confirmed;
settlement.ConfirmedAt = _clock.GetUtcNow().UtcDateTime;
settlement.ConfirmedBy = actor.UserName;
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
var end = settlement.EndDate;
var open = nameof(FiscalPeriodStatus.Open);
var settled = nameof(FiscalPeriodStatus.Settled);
await uow.ExecuteAsync(
SqlFragment.Of($"UPDATE fiscal_periods SET status = {settled} WHERE start_date >= {start} AND end_date <= {end} AND status = {open}"),
cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, settlement.Id, before, settlement, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>
/// Takes back the last confirmed settlement while its F24 line is not paid: the entry goes (or is reversed when
/// final), the periods open again, the settlement becomes a draft.
/// </summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The settlement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The settlement as a draft.</returns>
public async Task<VatSettlementView> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var settlements = uow.Repository<VatSettlement, long>();
var settlement = await settlements.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
var end = settlement.EndDate;
if (await settlements.CountAsync(Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate > end), cancellationToken)
.ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.SettlementLater]);
}
if (settlement.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
if (payment.PaidOn is not null)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
if (settlement.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, DateOnly.FromDateTime(_clock.GetLocalNow().DateTime), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
var before = Copy(settlement);
settlement.Status = VatSettlementStatus.Draft;
settlement.GlEntryId = null;
settlement.TaxPaymentId = null;
settlement.ConfirmedAt = null;
settlement.ConfirmedBy = null;
await settlements.UpdateAsync(settlement, cancellationToken).ConfigureAwait(false);
var start = settlement.StartDate;
var open = nameof(FiscalPeriodStatus.Open);
var settled = nameof(FiscalPeriodStatus.Settled);
await uow.ExecuteAsync(
SqlFragment.Of($"UPDATE fiscal_periods SET status = {open} WHERE start_date >= {start} AND end_date <= {end} AND status = {settled}"),
cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, settlement.Id, before, settlement, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return await SettlementAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound);
}
/// <summary>The base of the December advance for each method, as the ledger knows it.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year of the advance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The historical base (last period of the previous year, before its advance) and the actual one (VAT due from the start of the last period to 20 December).</returns>
public async Task<(decimal Historical, decimal Actual)> AdvanceBasisAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
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 periodicity = profile?.VatPeriodicity ?? VatPeriodicity.Monthly;
var lastNumber = periodicity == VatPeriodicity.Monthly ? 12 : 4;
var previousYear = year - 1;
var previous = await uow.Repository<VatSettlement, long>().FindAsync(
Query.For<VatSettlement>().Where(s => s.Year == previousYear && s.Number == lastNumber && s.Status == VatSettlementStatus.Confirmed), cancellationToken).ConfigureAwait(false);
var historical = previous is null ? 0m : previous.AmountDue - previous.Interest + previous.AdvancePaid;
var period = TaxPeriod.Of(year, lastNumber, periodicity);
var totals = await TotalsAsync(uow, period.Start, new DateOnly(year, 12, 20), cancellationToken).ConfigureAwait(false);
var actual = VatSettlementCalculator.Compute(totals, new VatSettlementTerms(profile?.ProRataPercent is > 0m and var p ? p : 100m)).Balance;
return (Math.Max(0m, historical), Math.Max(0m, actual));
}
/// <summary>Records the December advance as an F24 line due on 27 December.</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="method">The method.</param>
/// <param name="basis">The base of the method.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The F24 line, or <see langword="null"/> when nothing is due.</returns>
public async Task<TaxPayment?> AdvanceAsync(Actor actor, string companyCode, int year, VatAdvanceMethod method, decimal basis, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementConfirm, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var rules = pack.Require<IVatSettlementRules>();
var form = pack.Require<ITaxPaymentFormExporter>();
var amount = VatAdvanceCalculator.Compute(method, basis, rules.AdvancePercent, rules.AdvanceMinimum);
if (amount == 0m)
{
return null;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var payments = uow.Repository<TaxPayment, long>();
var existing = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.VatAdvance && t.ReferenceYear == year), cancellationToken).ConfigureAwait(false);
if (existing is { PaidOn: not null })
{
throw new ValidationFailedException(["Year:" + LedgerErrors.PaymentPaid]);
}
var payment = existing ?? new TaxPayment { Source = TaxPaymentSource.VatAdvance, ReferenceYear = year };
payment.DueDate = rules.AdvanceDue(year);
payment.PaymentCode = form.VatAdvanceCode(profile?.VatPeriodicity ?? VatPeriodicity.Monthly);
payment.Description = "Acconto IVA " + year.ToString(CultureInfo.InvariantCulture) + " (metodo " + method switch
{
VatAdvanceMethod.Historical => "storico",
VatAdvanceMethod.Forecast => "previsionale",
_ => "analitico",
} + ")";
payment.Amount = amount;
if (existing is null)
{
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
await _audit.RecordAsync(uow, existing is null ? AuditAction.Insert : AuditAction.Update, payment.Id, existing, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>The communication of the settlements of a quarter (LIPE) from its confirmed settlements.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> PeriodicReturnAsync(Actor actor, string companyCode, int year, int quarter, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.SettlementRead, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var writer = pack.Require<IPeriodicVatReturnWriter>();
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 first = new DateOnly(year, ((quarter - 1) * 3) + 1, 1);
var last = first.AddMonths(3).AddDays(-1);
var settlements = (await uow.Repository<VatSettlement, long>().ListAsync(
Query.For<VatSettlement>().Where(s => s.Status == VatSettlementStatus.Confirmed && s.StartDate >= first && s.EndDate <= last).OrderBy(s => s.StartDate),
cancellationToken).ConfigureAwait(false)).Items;
if (settlements.Count == 0)
{
throw new ValidationFailedException(["Quarter:" + LedgerErrors.SettlementPrevious]);
}
var modules = new List<PeriodicVatReturnModule>();
foreach (var s in settlements)
{
var settlementId = s.Id;
var lines = (await uow.Repository<VatSettlementLine, long>().ListAsync(Query.For<VatSettlementLine>().Where(l => l.SettlementId == settlementId), cancellationToken)
.ConfigureAwait(false)).Items;
var balance = s.AmountDue > 0m ? s.AmountDue : s.DebitCarried > 0m ? 0m : -s.CreditCarried;
modules.Add(new PeriodicVatReturnModule(
TaxPeriod.Of(s.Year, s.Number, s.Periodicity),
lines.Where(l => l.RegisterKind != VatRegisterKind.Purchases).Sum(l => l.Taxable),
lines.Where(l => l.RegisterKind == VatRegisterKind.Purchases).Sum(l => l.Taxable),
s.SalesTax,
s.PurchaseTax,
s.PreviousDebit,
s.PreviousCredit,
s.Interest,
s.AdvancePaid,
balance));
}
var data = new PeriodicVatReturn(
year, quarter, profile?.TaxCode ?? profile?.VatNumber ?? string.Empty, profile?.VatNumber ?? string.Empty, null, profile?.IntermediaryTaxCode,
DateOnly.FromDateTime(_clock.GetLocalNow().DateTime), modules);
return new LedgerFile(writer.FileName(data), "application/xml", writer.Write(data));
}
/// <summary>The VAT of each register in a period, from the posted entries.</summary>
internal static async Task<IReadOnlyList<VatRegisterTotals>> TotalsAsync(IUnitOfWork uow, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
var draft = nameof(GlEntryStatus.Draft);
var immediate = nameof(TaxExigibility.Immediate);
var rows = await uow.QueryAsync<TotalsRow>(SqlFragment.Of($"""
SELECT v.vat_register_id AS register_id, r.kind AS kind, COUNT(DISTINCT v.entry_id) AS documents,
SUM(v.taxable) AS taxable, SUM(v.tax) AS tax, SUM(v.non_deductible_tax) AS non_deductible_tax,
SUM(CASE WHEN v.exigibility <> {immediate} THEN v.tax ELSE 0 END) AS deferred_tax
FROM gl_entry_vat v JOIN vat_registers r ON r.id = v.vat_register_id
WHERE v.status <> {draft} AND v.vat_date >= {from} AND v.vat_date <= {to}
GROUP BY v.vat_register_id, r.kind
"""), cancellationToken).ConfigureAwait(false);
return [.. rows.Select(r => new VatRegisterTotals(r.RegisterId, r.Kind, (int)r.Documents, r.Taxable ?? 0m, r.Tax ?? 0m, r.NonDeductibleTax ?? 0m, r.DeferredTax ?? 0m))];
}
/// <summary>The lines and totals of a register in a period.</summary>
internal static async Task<VatRegisterView> RegisterAsync(IUnitOfWork uow, long registerId, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
var register = await uow.Repository<VatRegister, long>().GetAsync(registerId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.VatRegisterRequired);
var draft = nameof(GlEntryStatus.Draft);
var rows = await uow.QueryAsync<VatRegisterRow>(SqlFragment.Of($"""
SELECT v.entry_id AS entry_id, e.entry_number AS entry_number, e.vat_protocol AS vat_protocol, v.vat_date AS vat_date,
e.document_number AS document_number, e.document_date AS document_date, p.name AS party_name, v.rate AS rate, v.nature AS nature,
v.exigibility AS exigibility, v.taxable AS taxable, v.tax AS tax, v.non_deductible_tax AS non_deductible_tax, v.status AS status
FROM gl_entry_vat v JOIN gl_entries e ON e.id = v.entry_id LEFT JOIN parties p ON p.id = e.party_id
WHERE v.vat_register_id = {registerId} AND v.status <> {draft} AND v.vat_date >= {from} AND v.vat_date <= {to}
ORDER BY v.vat_date, e.vat_protocol, e.id, v.line_number
"""), cancellationToken).ConfigureAwait(false);
var totals = rows.GroupBy(r => (r.Rate, r.Nature))
.Select(g => new VatRateTotal(g.Key.Rate, g.Key.Nature, g.Sum(r => r.Taxable), g.Sum(r => r.Tax), g.Sum(r => r.NonDeductibleTax)))
.OrderByDescending(t => t.Rate).ThenBy(t => t.Nature, StringComparer.Ordinal)
.ToList();
return new VatRegisterView(register, rows, totals);
}
/// <summary>The name and VAT number of the company for the heading of the prints.</summary>
internal static string CompanyLine(CompanyProfile? profile) =>
profile is null ? string.Empty : profile.LegalName + (profile.VatNumber is { Length: > 0 } vat ? " - P.IVA " + vat : string.Empty);
private static async Task<VatSettlementView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<VatSettlement, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } settlement)
{
return null;
}
var lines = (await uow.Repository<VatSettlementLine, long>().ListAsync(Query.For<VatSettlementLine>().Where(l => l.SettlementId == id), cancellationToken)
.ConfigureAwait(false)).Items;
var registers = (await uow.Repository<VatRegister, long>().ListAsync(Query.For<VatRegister>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id);
return new VatSettlementView(settlement, [.. lines.OrderBy(l => l.RegisterKind).ThenBy(l => registers.TryGetValue(l.VatRegisterId, out var r) ? r.Code : string.Empty, StringComparer.Ordinal)], registers);
}
// The entry LIQ: VAT on sales debit, VAT on purchases credit (what is deducted and the share lost to the pro rata),
// the pro rata to its cost, the interest debit, the balance to the VAT settlement account.
private static async Task<GlEntry?> PostSettlementAsync(IUnitOfWork uow, VatSettlement settlement, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, "LIQ", cancellationToken).ConfigureAwait(false) is not { } found)
{
return null;
}
var (template, templateLines) = found;
long? Role(PostingRole role, string? description = null) =>
templateLines.FirstOrDefault(l => l.Role == role && l.AccountId is not null && (description is null || l.Description == description))?.AccountId;
var salesVat = Role(PostingRole.SalesVat);
var purchaseVat = Role(PostingRole.PurchaseVat);
var settlementAccount = Role(PostingRole.VatSettlement);
var interestAccount = templateLines.FirstOrDefault(l => l.Role == PostingRole.Account && l.AccountId is not null)?.AccountId;
var proRataAccount = Role(PostingRole.Cost);
if (salesVat is null || purchaseVat is null || settlementAccount is null)
{
throw new ValidationFailedException(["Ledger:" + LedgerErrors.RoleAccountMissing]);
}
var proRata = await ProRataShareAsync(uow, settlement, cancellationToken).ConfigureAwait(false);
var lines = new List<EntryLineDraft>();
void Add(long? account, decimal amount, AccountSide side, string description)
{
if (amount == 0m || account is null)
{
return;
}
if (amount < 0m)
{
amount = -amount;
side = side == AccountSide.Debit ? AccountSide.Credit : AccountSide.Debit;
}
lines.Add(new EntryLineDraft(account, null, description, side == AccountSide.Debit ? amount : 0m, side == AccountSide.Debit ? 0m : amount));
}
Add(salesVat, settlement.SalesTax, AccountSide.Debit, "IVA a debito del periodo");
Add(purchaseVat, settlement.PurchaseTax + proRata, AccountSide.Credit, "IVA a credito del periodo");
Add(proRata == 0m ? null : proRataAccount ?? settlementAccount, proRata, AccountSide.Debit, "IVA indetraibile da pro rata");
var interest = interestAccount is null ? 0m : settlement.Interest;
Add(interestAccount, interest, AccountSide.Debit, "Interessi trimestrali");
Add(settlementAccount, settlement.SalesTax - settlement.PurchaseTax + interest, AccountSide.Credit, "Saldo della liquidazione");
if (lines.Count == 0)
{
return null;
}
var entry = new GlEntry
{
EntryDate = settlement.EndDate,
JournalTemplateId = template.Id,
TemplateCode = template.Code,
Description = LedgerStore.Trim(template.Description + " " + PeriodText(settlement), 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.VatSettlement,
IsDemo = settlement.IsDemo,
};
return await LedgerStore.InsertAsync(uow, entry, lines, [], cancellationToken).ConfigureAwait(false);
}
// The VAT of the purchase registers lost to the pro rata (beyond what the codes already make non-deductible).
private static async Task<decimal> ProRataShareAsync(IUnitOfWork uow, VatSettlement settlement, CancellationToken cancellationToken)
{
if (settlement.ProRataPercent >= 100m)
{
return 0m;
}
var totals = await TotalsAsync(uow, settlement.StartDate, settlement.EndDate, cancellationToken).ConfigureAwait(false);
var byCode = totals.Where(t => t.Kind == VatRegisterKind.Purchases).Sum(t => t.NonDeductibleTax);
return settlement.NonDeductibleTax - byCode;
}
private static string PeriodText(VatSettlement settlement) =>
settlement.Periodicity == VatPeriodicity.Monthly
? settlement.StartDate.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT"))
: settlement.Number.ToString(CultureInfo.InvariantCulture) + "° trimestre " + settlement.Year.ToString(CultureInfo.InvariantCulture);
private static string Describe(VatSettlement settlement, ITaxPaymentFormExporter? form)
{
var code = settlement.PaymentCode;
// The description of the code already names the month or the quarter: only the year is added.
var text = form?.Codes.FirstOrDefault(c => c.Code == code)?.Description;
return LedgerStore.Trim(text is null ? "Versamento IVA " + PeriodText(settlement) : text + " " + settlement.Year.ToString(CultureInfo.InvariantCulture), 200)!;
}
private static VatSettlement Copy(VatSettlement s) => new()
{
Id = s.Id,
Year = s.Year,
Number = s.Number,
Status = s.Status,
AmountDue = s.AmountDue,
CreditCarried = s.CreditCarried,
GlEntryId = s.GlEntryId,
TaxPaymentId = s.TaxPaymentId,
};
private sealed record TotalsRow(long RegisterId, VatRegisterKind Kind, long Documents, decimal? Taxable, decimal? Tax, decimal? NonDeductibleTax, decimal? DeferredTax);
}
@@ -0,0 +1,522 @@
using System.IO.Compression;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Files;
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.Purchases;
/// <summary>An invoice found in a received file, as the import screen shows it before registering (mockup 034).</summary>
/// <param name="FileName">The file (inside a ZIP, its entry).</param>
/// <param name="File">The file as read.</param>
/// <param name="Invoice">The invoice (a file may hold several).</param>
/// <param name="DocumentTypeCode">The purchase document type that registers it, or none.</param>
/// <param name="SupplierId">The supplier already in the archive, by VAT number or tax code.</param>
/// <param name="Duplicate">Whether the supplier already has a document with this number in this year.</param>
/// <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,
IReadOnlyList<string> Problems)
{
/// <summary>Whether it can be registered.</summary>
public bool CanImport => DocumentTypeCode is not null && !Duplicate;
/// <summary>The total in the file, or the computed one.</summary>
public decimal Total => Invoice.Total ?? ComputedTotal;
}
/// <summary>A file that could not be read.</summary>
/// <param name="FileName">The file.</param>
/// <param name="Error">Why (resource code).</param>
public sealed record IncomingRejected(string FileName, string Error);
/// <summary>What the files hold.</summary>
/// <param name="Invoices">The invoices found.</param>
/// <param name="Rejected">The files not read.</param>
public sealed record IncomingReading(IReadOnlyList<IncomingCandidate> Invoices, IReadOnlyList<IncomingRejected> Rejected);
/// <summary>An invoice registered, or why not.</summary>
/// <param name="Candidate">The invoice.</param>
/// <param name="Record">The draft document.</param>
/// <param name="SupplierCreated">Whether the supplier was added to the archive.</param>
/// <param name="Error">Why it was not registered (resource code).</param>
/// <param name="Warnings">What to check on the draft (resource codes).</param>
public sealed record IncomingImported(IncomingCandidate Candidate, DocumentRecord? Record, bool SupplierCreated, string? Error, IReadOnlyList<string> Warnings);
/// <summary>
/// The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files are read by the fiscal pack;
/// each invoice finds its supplier by VAT number or tax code (or adds it), its items by the supplier code, bar code or
/// code, its tax codes by rate and nature; it becomes a draft supplier invoice or credit note with the file attached, to
/// check and confirm. Duplicates (same supplier, number and year) are refused; a total that does not match the lines is
/// reported.
/// </summary>
public sealed class PurchaseInvoiceImportService
{
/// <summary>The largest file accepted, ZIP included.</summary>
public const int MaxFileSize = 50 * 1024 * 1024;
/// <summary>Problem: the type of the invoice is not a purchase (a self-invoice).</summary>
public const string UnsupportedType = "purchase.import.unsupported-type";
/// <summary>Problem: already registered.</summary>
public const string DuplicateProblem = "purchase.import.duplicate";
/// <summary>Warning: the total in the file differs from the lines.</summary>
public const string TotalMismatch = "purchase.import.total-mismatch";
/// <summary>Warning: the signature of the file could not be verified.</summary>
public const string SignatureNotVerified = "purchase.import.signature";
/// <summary>Warning: the discounts of the whole document are not carried to the lines.</summary>
public const string DocumentDiscount = "purchase.import.document-discount";
/// <summary>Error: no tax code of the company has the rate and nature of a line.</summary>
public const string TaxCodeMissing = "purchase.import.tax-code";
/// <summary>Error: the archive is empty of invoices.</summary>
public const string EmptyArchive = "purchase.import.empty";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly DocumentEngine _engine;
private readonly DocumentEditor _editor;
private readonly PartyService _parties;
private readonly AttachmentService _attachments;
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="engine">The document engine.</param>
/// <param name="editor">The editor (terms of the supplier).</param>
/// <param name="parties">The parties (new suppliers).</param>
/// <param name="attachments">The attachments (the file).</param>
/// <param name="clock">The clock.</param>
public PurchaseInvoiceImportService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, DocumentEditor editor, PartyService parties,
AttachmentService attachments, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(editor);
ArgumentNullException.ThrowIfNull(parties);
ArgumentNullException.ThrowIfNull(attachments);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_engine = engine;
_editor = editor;
_parties = parties;
_attachments = attachments;
_clock = clock;
}
/// <summary>Reads files: each XML or P7M, and those inside a ZIP.</summary>
/// <param name="actor">Who imports: needs <c>purchases.invoice.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="files">The files, by name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices found and the files not read.</returns>
public async Task<IncomingReading> ReadAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false);
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 rejected = new List<IncomingRejected>();
foreach (var (name, content) in Expand(files, rejected))
{
if (reader is null || !reader.CanRead(name, content))
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
continue;
}
try
{
found.Add((name, reader.Read(name, content)));
}
catch (IncomingInvoiceException ex)
{
rejected.Add(new(name, ex.Code));
}
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var result = new List<IncomingCandidate>();
foreach (var (name, file) in found)
{
var supplierId = await FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false);
foreach (var invoice in file.Invoices)
{
var problems = new List<string>();
var typeCode = rules?.DocumentTypeCode(invoice.DocumentType);
if (typeCode is null)
{
problems.Add(UnsupportedType);
}
var duplicate = supplierId is { } supplier && await IsDuplicateAsync(uow, supplier, invoice, cancellationToken).ConfigureAwait(false);
if (duplicate)
{
problems.Add(DuplicateProblem);
}
var computed = invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) + (invoice.Rounding ?? 0m);
if (invoice.Total is { } total && Math.Abs(total - computed) > 0.01m && invoice.Discounts.Count == 0)
{
problems.Add(TotalMismatch);
}
if (invoice.Discounts.Count > 0)
{
problems.Add(DocumentDiscount);
}
if (file.Signature is { Verified: false })
{
problems.Add(SignatureNotVerified);
}
result.Add(new IncomingCandidate(name, file, invoice, typeCode, supplierId, duplicate, computed, problems));
}
}
if (result.Count == 0 && rejected.Count == 0)
{
rejected.Add(new(files.Count == 1 ? files[0].FileName : string.Empty, EmptyArchive));
}
return new IncomingReading([.. result.OrderBy(c => c.Invoice.Date).ThenBy(c => c.File.Supplier.DisplayName, StringComparer.CurrentCulture)], rejected);
}
/// <summary>
/// Registers the invoices as drafts: the supplier is found or added, each line takes its item and tax code, the
/// file is attached. One invoice that fails does not stop the others.
/// </summary>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="candidates">The invoices to register.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<IncomingImported>> ImportAsync(
Actor actor, string companyCode, IReadOnlyList<IncomingCandidate> candidates, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(candidates);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
var created = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
var result = new List<IncomingImported>();
foreach (var candidate in candidates)
{
if (candidate.DocumentTypeCode is not { } typeCode)
{
result.Add(new(candidate, null, false, UnsupportedType, []));
continue;
}
var supplierCreated = false;
try
{
long supplierId;
var key = KeyOf(candidate.File.Supplier);
if (candidate.SupplierId is { } known)
{
supplierId = known;
}
else if (key.Length > 0 && created.TryGetValue(key, out var made))
{
supplierId = made;
}
else
{
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
supplierId = await FindSupplierAsync(uow, candidate.File.Supplier, cancellationToken).ConfigureAwait(false) ?? 0;
}
if (supplierId == 0)
{
supplierId = await CreateSupplierAsync(actor, company, candidate.File.Supplier, cancellationToken).ConfigureAwait(false);
supplierCreated = true;
}
if (key.Length > 0)
{
created[key] = supplierId;
}
}
var (record, warnings) = await DraftAsync(actor, company, candidate, typeCode, supplierId, today, cancellationToken).ConfigureAwait(false);
result.Add(new(candidate, record, supplierCreated, null, warnings));
}
catch (ValidationFailedException ex)
{
result.Add(new(candidate, null, supplierCreated, (ex.Errors.Count > 0 ? ex.Errors[0] : null)?.Split(':', 2)[^1] ?? IncomingInvoiceErrors.Invalid, []));
}
}
return result;
}
// ZIP archives are opened (one level, entries .xml and .p7m); other files pass as they are.
private static List<(string Name, byte[] Content)> Expand(IReadOnlyList<(string FileName, byte[] Content)> files, List<IncomingRejected> rejected)
{
var result = new List<(string, byte[])>();
foreach (var (name, content) in files)
{
if (content.Length > MaxFileSize)
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
continue;
}
if (content.Length < 4 || content[0] != (byte)'P' || content[1] != (byte)'K')
{
result.Add((name, content));
continue;
}
try
{
using var archive = new ZipArchive(new MemoryStream(content, writable: false), ZipArchiveMode.Read);
long total = 0;
foreach (var entry in archive.Entries.Where(e => e.Length > 0 && !e.FullName.EndsWith('/')))
{
var entryName = Path.GetFileName(entry.FullName);
if (!entryName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && !entryName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase))
{
continue;
}
total += entry.Length;
if (entry.Length > MaxFileSize || total > 4L * MaxFileSize)
{
rejected.Add(new(entryName, IncomingInvoiceErrors.NotReadable));
continue;
}
using var stream = entry.Open();
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
result.Add((entryName, buffer.ToArray()));
}
}
catch (InvalidDataException)
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
}
}
return result;
}
private static string KeyOf(IncomingParty 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) =>
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)
{
var parties = uow.Repository<Party, long>();
if (VatOf(party) is { } vat)
{
var bare = party.VatNumber!;
var byVat = (await parties.ListAsync(Query.For<Party>().Where(p => p.VatNumber == vat || p.VatNumber == bare), cancellationToken).ConfigureAwait(false)).Items;
if (Pick(byVat) is { } found)
{
return found;
}
}
if (party.TaxCode is { Length: > 0 } taxCode)
{
var byTaxCode = (await parties.ListAsync(Query.For<Party>().Where(p => p.TaxCode == taxCode), cancellationToken).ConfigureAwait(false)).Items;
return Pick(byTaxCode);
}
return null;
// A supplier first, then a customer that is also a supplier, then any party; the enabled ones first.
static long? Pick(IReadOnlyList<Party> parties) => parties
.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)
{
var number = invoice.Number.Trim();
var from = new DateOnly(invoice.Date.Year, 1, 1);
var to = new DateOnly(invoice.Date.Year, 12, 31);
return await uow.Repository<PurchaseDocument, long>().CountAsync(
Query.For<PurchaseDocument>().Where(d => d.PartyId == supplierId && d.ExternalReference == number && d.ExternalDate >= from && d.ExternalDate <= to
&& d.Status != DocumentStatus.Cancelled
&& (d.Kind == DocumentKind.PurchaseInvoice || d.Kind == DocumentKind.PurchaseCreditNote)),
cancellationToken).ConfigureAwait(false) > 0;
}
private async Task<long> CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken)
{
var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false);
var p = record.Party;
var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant();
bool inEu;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
inEu = (await uow.Repository<Country, long>().FindAsync(Query.For<Country>().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false;
}
p.CountryCode = country;
p.SubjectType = country == "IT"
? (party.Name is null && party.VatNumber is null ? SubjectType.Person : SubjectType.Company)
: inEu ? SubjectType.EuCompany : SubjectType.NonEuCompany;
p.Name = Limit(party.DisplayName, 200) ?? string.Empty;
p.FirstName = p.SubjectType == SubjectType.Person ? Limit(party.FirstName, 100) : null;
p.LastName = p.SubjectType == SubjectType.Person ? Limit(party.LastName, 100) : null;
p.VatNumber = VatOf(party);
p.TaxCode = Limit(party.TaxCode, 16);
p.Address = Limit(party.Address, 200);
p.StreetNumber = Limit(party.StreetNumber, 20);
p.PostalCode = Limit(party.PostalCode, 10);
p.City = Limit(party.City, 100);
p.Province = country == "IT" ? Limit(party.Province, 2) : null;
p.Email = Limit(party.Email, 200);
p.Phone = Limit(party.Phone, 40);
p.Rea = party.ReaOffice is null || party.ReaNumber is null ? null : Limit(party.ReaOffice + "-" + party.ReaNumber, 30);
return (await _parties.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false)).Party.Id;
}
private static string? Limit(string? text, int length) =>
string.IsNullOrWhiteSpace(text) ? null : text.Trim() is var trimmed && trimmed.Length > length ? trimmed[..length] : text.Trim();
private async Task<(DocumentRecord Record, IReadOnlyList<string> Warnings)> DraftAsync(
Actor actor, string company, IncomingCandidate candidate, string typeCode, long supplierId, DateOnly today, CancellationToken cancellationToken)
{
var invoice = candidate.Invoice;
var record = await _engine.NewAsync(actor, company, typeCode, cancellationToken).ConfigureAwait(false);
await _editor.ApplyPartyAsync(actor, company, record, supplierId, cancellationToken).ConfigureAwait(false);
var header = record.Header;
header.DocumentDate = invoice.Date > today ? invoice.Date : today;
header.ExternalReference = Limit(invoice.Number, 50);
header.ExternalDate = invoice.Date;
if (invoice.Causals.Count > 0)
{
header.Notes = Limit(string.Join(Environment.NewLine, invoice.Causals), 2000);
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
var codes = invoice.Lines.SelectMany(l => l.Codes).Select(c => c.Value.Trim()).Where(v => v.Length > 0).Distinct(StringComparer.Ordinal).ToList();
var bySupplierCode = codes.Count == 0 ? [] : (await uow.Repository<ItemSupplier, long>().ListAsync(
Query.For<ItemSupplier>().Where(s => s.PartyId == supplierId && codes.Contains(s.SupplierCode!)), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(s => s.SupplierCode!, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal);
var byBarcode = codes.Count == 0 ? [] : (await uow.Repository<ItemBarcode, long>().ListAsync(
Query.For<ItemBarcode>().Where(b => codes.Contains(b.Code)), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(b => b.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal);
var byCode = codes.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(
Query.For<Item>().Where(i => codes.Contains(i.Code)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Code, StringComparer.Ordinal);
var itemIds = bySupplierCode.Values.Concat(byBarcode.Values).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);
foreach (var item in byCode.Values)
{
items.TryAdd(item.Id, item);
}
var credit = record.Header.Kind == DocumentKind.PurchaseCreditNote;
foreach (var source in invoice.Lines.OrderBy(l => l.Number))
{
var line = new PurchaseDocumentLine();
line.Kind = DocumentLineKind.Free;
line.Description = Limit(source.Description, 1000) ?? "-";
line.TaxCodeId = TaxCodeOf(taxes, source.TaxRate, source.Nature)
?? throw new ValidationFailedException([":" + TaxCodeMissing]);
var quantity = source.Quantity is { } q && q != 0m ? q : 1m;
var price = source.UnitPrice;
var discounts = source.Discounts;
if (discounts.Count > 0 && discounts.All(d => d.Percent is > 0m and <= 100m && !d.IsSurcharge))
{
line.DiscountFormula = string.Join('+', discounts.Select(d => d.Percent!.Value.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)));
}
else if (discounts.Count > 0 || (source.Quantity is null && source.TotalPrice != source.UnitPrice))
{
// Amounts or surcharges: the net price keeps the total of the line.
price = Math.Round(source.TotalPrice / quantity, 6);
}
line.Quantity = credit ? Math.Abs(quantity) : quantity;
line.Price = credit && quantity < 0m ? -price : price;
if (ItemOf(source, bySupplierCode, byBarcode, byCode) is { } itemId && items.TryGetValue(itemId, out var item) && !item.Disabled)
{
line.Kind = DocumentLineKind.Item;
line.ItemId = item.Id;
line.UnitOfMeasureId = item.UnitOfMeasureId;
}
record.Lines.Add(line);
}
}
var saved = await _engine.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false);
await _attachments.AddAsync(
actor, company, DocumentPrintService.EntityOf(saved.Family), saved.Header.Id, new AttachmentFile(AttachmentKind.EInvoice, candidate.File.FileName, null),
(stream, ct) => stream.WriteAsync(candidate.File.Xml, ct).AsTask(), cancellationToken).ConfigureAwait(false);
var warnings = candidate.Problems.Where(p => p is TotalMismatch or SignatureNotVerified or DocumentDiscount).ToList();
if (invoice.Total is { } total && Math.Abs(total - saved.Header.TotalAmount) > 0.01m && !warnings.Contains(TotalMismatch))
{
warnings.Add(TotalMismatch);
}
return (saved, warnings);
}
private static long? ItemOf(IncomingLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
{
foreach (var code in line.Codes.Select(c => c.Value.Trim()))
{
if (bySupplierCode.TryGetValue(code, out var id) || byBarcode.TryGetValue(code, out id))
{
return id;
}
}
return line.Codes.Select(c => c.Value.Trim()).FirstOrDefault(byCode.ContainsKey) is { } own ? byCode[own].Id : null;
}
// The tax code with the rate and nature of the line: the exact nature first, then the family of the nature (N3 for
// N3.2), then for an ordinary rate the ordinary codes before the others.
private static long? TaxCodeOf(IReadOnlyList<TaxCode> taxes, decimal rate, string? nature)
{
var withRate = taxes.Where(t => t.Rate == rate).OrderBy(t => t.ValidTo is not null).ThenBy(t => t.Code, StringComparer.Ordinal).ToList();
if (nature is null)
{
return (withRate.FirstOrDefault(t => t.Nature is null && t.Kind == TaxCodeKind.Taxable) ?? withRate.FirstOrDefault(t => t.Nature is null))?.Id;
}
return (withRate.FirstOrDefault(t => string.Equals(t.Nature, nature, StringComparison.OrdinalIgnoreCase))
?? withRate.FirstOrDefault(t => t.Nature is not null && t.Nature.StartsWith(nature.Split('.')[0], StringComparison.OrdinalIgnoreCase)))?.Id;
}
}
@@ -0,0 +1,267 @@
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.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Purchases;
/// <summary>A line of a supplier invoice whose price differs from the order or receipt it comes from (§11.5).</summary>
/// <param name="LineNumber">The line of the invoice.</param>
/// <param name="Description">Its description.</param>
/// <param name="SourceKind">The kind of the document it comes from.</param>
/// <param name="SourceNumber">Its number.</param>
/// <param name="SourcePrice">The net unit price there.</param>
/// <param name="InvoicePrice">The net unit price on the invoice.</param>
/// <param name="Quantity">The quantity of the invoice line.</param>
public sealed record PriceDifference(
int LineNumber, string Description, DocumentKind SourceKind, string? SourceNumber, decimal SourcePrice, decimal InvoicePrice, decimal Quantity)
{
/// <summary>The difference on the whole line: positive when the invoice costs more.</summary>
public decimal Amount => Math.Round((InvoicePrice - SourcePrice) * Quantity, 2, MidpointRounding.AwayFromZero);
}
/// <summary>A supplier invoice that waits for its self-invoice (mockup 035).</summary>
/// <param name="Invoice">The invoice.</param>
/// <param name="Advice">The self-invoice it needs and by when.</param>
public sealed record PendingSelfInvoice(DocumentRow Invoice, SelfInvoiceAdvice Advice);
/// <summary>
/// The rules of purchases beyond the document engine (SPEC §11.5): price differences against orders and receipts,
/// the self-invoice a supplier invoice needs (reverse charge, purchases from abroad) and its draft.
/// </summary>
/// <remarks>Permissions <c>purchases.invoice.read</c> and <c>write</c>.</remarks>
public sealed class PurchaseService
{
/// <summary>Permission to read supplier invoices.</summary>
public const string ReadPermission = "purchases.invoice.read";
/// <summary>Permission to register supplier invoices and self-invoices.</summary>
public const string WritePermission = "purchases.invoice.write";
/// <summary>The supplier invoice does not need a self-invoice.</summary>
public const string SelfInvoiceNotNeeded = "purchase.self-invoice.not-needed";
private readonly DocumentEngine _engine;
private readonly DocumentCopyService _copies;
private readonly DocumentEditor _editor;
private readonly CompanyFiscalContext _packs;
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
/// <summary>Creates the service.</summary>
/// <param name="engine">The document engine.</param>
/// <param name="copies">Copies and transformations.</param>
/// <param name="editor">The editor (radars).</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public PurchaseService(
DocumentEngine engine, DocumentCopyService copies, DocumentEditor editor, CompanyFiscalContext packs, IUnitOfWorkFactory factory, PermissionService permissions)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(copies);
ArgumentNullException.ThrowIfNull(editor);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
_engine = engine;
_copies = copies;
_editor = editor;
_packs = packs;
_factory = factory;
_permissions = permissions;
}
/// <summary>The lines of a supplier invoice whose net price differs from their order or receipt.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The invoice, as on screen.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The differences.</returns>
public async Task<IReadOnlyList<PriceDifference>> PriceDifferencesAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var result = new List<PriceDifference>();
if (record.Header.Kind is not (DocumentKind.PurchaseInvoice or DocumentKind.PurchaseDeliveryNote))
{
return result;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var headers = new Dictionary<(DocumentFamily, long), DocumentHeader?>();
for (var i = 0; i < record.Lines.Count; i++)
{
var line = record.Lines[i];
if (line.SourceFamily is not { } family || line.SourceLineId is not { } sourceId || line.Quantity == 0m)
{
continue;
}
var source = await DocumentStores.Of(family).GetLineAsync(uow, sourceId, cancellationToken).ConfigureAwait(false);
if (source is null || source.Quantity == 0m)
{
continue;
}
if (!headers.TryGetValue((family, source.DocumentId), out var header))
{
header = await DocumentStores.Of(family).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false);
headers[(family, source.DocumentId)] = header;
}
if (header is null)
{
continue;
}
var before = Math.Round(source.TaxableAmount / source.Quantity, 4, MidpointRounding.AwayFromZero);
var now = Math.Round(line.TaxableAmount / line.Quantity, 4, MidpointRounding.AwayFromZero);
if (before != now)
{
result.Add(new PriceDifference(i + 1, line.Description, header.Kind, header.DocumentNumber ?? header.ExternalReference, before, now, line.Quantity));
}
}
return result;
}
/// <summary>The self-invoice a supplier invoice needs, if any (reverse charge, purchase from abroad).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The advice, or <see langword="null"/>.</returns>
public async Task<SelfInvoiceAdvice?> AdviseAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
if (record.Header.Kind != DocumentKind.PurchaseInvoice || record.Header.PartyId is null)
{
return null;
}
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<ISelfInvoiceRules>();
if (rules is null)
{
return null;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The confirmed supplier invoices that need a self-invoice and have none yet, the nearest deadline first.
/// </summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices with their advice.</returns>
public async Task<IReadOnlyList<PendingSelfInvoice>> PendingSelfInvoicesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<ISelfInvoiceRules>();
if (rules is null)
{
return [];
}
var rows = await _editor.ListAsync(actor, company, DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseInvoice], new Querying.ListQuery { Limit = 500 }, cancellationToken)
.ConfigureAwait(false);
var result = new List<PendingSelfInvoice>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var integrated = (await uow.Repository<DocumentLink, long>().ListAsync(
Query.For<DocumentLink>().Where(l => l.SourceFamily == DocumentFamily.PurchaseDocument && l.TargetFamily == DocumentFamily.SaleDocument), cancellationToken)
.ConfigureAwait(false)).Items.Select(l => l.SourceDocumentId).ToHashSet();
foreach (var row in rows.Items.Where(r => DocumentStateMachine.IsInForce(r.Status) && !integrated.Contains(r.Id)))
{
var record = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, row.Id, cancellationToken).ConfigureAwait(false);
if (record is not null && await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false) is { } advice)
{
result.Add(new PendingSelfInvoice(row, advice));
}
}
return [.. result.OrderBy(p => p.Advice.Deadline).ThenBy(p => p.Invoice.Date)];
}
/// <summary>
/// The draft self-invoice of a supplier invoice: its lines with the ordinary VAT code where the supplier wrote a
/// nature, the supplier's number and date as the related invoice, today as date.
/// </summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="purchaseInvoiceId">The supplier invoice.</param>
/// <param name="typeCode">The type, such as <c>AF17</c>; the advised one when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft, saved.</returns>
/// <exception cref="ValidationFailedException">No type was given and none is advised.</exception>
public async Task<DocumentRecord> CreateSelfInvoiceAsync(Actor actor, string companyCode, long purchaseInvoiceId, string? typeCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
var invoice = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require<ISelfInvoiceRules>();
var code = typeCode;
if (string.IsNullOrWhiteSpace(code))
{
await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
code = (await AdviseAsync(read, rules, invoice, cancellationToken).ConfigureAwait(false))?.DocumentTypeCode
?? throw new ValidationFailedException([":" + SelfInvoiceNotNeeded]);
}
var draft = await _copies.CopyAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, code, null, cancellationToken).ConfigureAwait(false);
var header = draft.Header;
header.RelatedDocumentId = invoice.Header.Id;
header.RelatedNumber = invoice.Header.ExternalReference;
header.RelatedDate = invoice.Header.ExternalDate;
header.ExternalReference = null;
header.ExternalDate = null;
header.InventoryReasonId = null;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
var ordinary = taxes.FirstOrDefault(t => t.Code == rules.OrdinaryTaxCode)?.Id;
foreach (var line in draft.Lines)
{
// The supplier invoiced without VAT (a nature): the integration applies the rate.
if (line.TaxCodeId is { } id && taxes.FirstOrDefault(t => t.Id == id) is { Nature: not null } && ordinary is not null)
{
line.TaxCodeId = ordinary;
}
}
}
return await _engine.SaveAsync(actor, company, draft, cancellationToken).ConfigureAwait(false);
}
private static async Task<SelfInvoiceAdvice?> AdviseAsync(IUnitOfWork uow, ISelfInvoiceRules rules, DocumentRecord record, CancellationToken cancellationToken)
{
if (record.Header.PartyId is not { } partyId || await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { } party)
{
return null;
}
var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant();
var inEu = (await uow.Repository<Country, long>().FindAsync(Query.For<Country>().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false;
var taxIds = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).Distinct().ToList();
var natures = taxIds.Count == 0 ? [] : (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => taxIds.Contains(t.Id)), cancellationToken)
.ConfigureAwait(false)).Items.Where(t => t.Nature is not null).Select(t => t.Nature!).Distinct().ToList();
var itemIds = record.Lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList();
var kinds = 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, i => i.Kind);
// Goods when the item lines of goods weigh more than the rest; free lines count as services.
var goods = record.Lines.Where(l => l.ItemId is { } id && kinds.GetValueOrDefault(id) == ItemKind.Goods).Sum(l => Math.Abs(l.TaxableAmount));
var other = record.Lines.Where(l => l.Kind != DocumentLineKind.Description).Sum(l => Math.Abs(l.TaxableAmount)) - goods;
var received = record.Header.VatDate ?? record.Header.DocumentDate;
return rules.Advise(new SelfInvoiceCase(country, inEu && country != "IT", goods > other, natures, received));
}
}
@@ -0,0 +1,123 @@
using Khaemhat.Application.Instance;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The demo accounting (SPEC §14, issue #68): the demo documents posted, the professional's invoice paid so that its
/// withholding is due, the monthly rental of the office printer as a recurring entry, the VAT settlements of the periods already
/// ended confirmed, and the F24 already due paid. It runs after the demo sales and purchases and only once: when
/// the company has typed or settled anything in the ledger it adds nothing.
/// </summary>
/// <param name="ledger">Posts the documents.</param>
/// <param name="journal">Writes the model entry of the rental.</param>
/// <param name="vat">Computes and confirms the settlements.</param>
/// <param name="taxes">Withholdings, stamp duty and F24.</param>
/// <param name="recurring">The recurring rental.</param>
/// <param name="factory">Reads the ledger.</param>
/// <param name="clock">Today.</param>
public sealed class DemoLedgerSeeder(
LedgerService ledger, JournalEntryService journal, VatService vat, TaxService taxes, RecurringEntryService recurring, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The account of the rental, from the Italian chart of accounts (Noleggi).</summary>
public const string RentAccount = "22.01.003";
/// <summary>The bank account that pays it.</summary>
public const string BankAccount = "07.01.001";
/// <summary>The monthly rental of the demo office printer.</summary>
public const decimal Rent = 45m;
private static readonly Actor Seed = Actor.System;
/// <inheritdoc />
public int Order => 40;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
var start = new DateOnly(today.Year, 1, 1);
long? rentId;
long? bankId;
VatPeriodicity periodicity;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
var accounts = uow.Repository<GlAccount, long>();
if (await accounts.CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0)
{
return; // No chart of accounts: the company has no accounting module.
}
if (await uow.Repository<GlEntry, long>().CountAsync(
Query.For<GlEntry>().Where(e => e.Source == GlEntrySource.Manual || e.Source == GlEntrySource.VatSettlement), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<VatSettlement, long>().CountAsync(Query.For<VatSettlement>(), cancellationToken).ConfigureAwait(false) > 0)
{
return;
}
rentId = (await accounts.FindAsync(Query.For<GlAccount>().Where(a => a.Code == RentAccount), cancellationToken).ConfigureAwait(false))?.Id;
bankId = (await accounts.FindAsync(Query.For<GlAccount>().Where(a => a.Code == BankAccount), cancellationToken).ConfigureAwait(false))?.Id;
periodicity = (await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false))?.VatPeriodicity
?? VatPeriodicity.Monthly;
}
// The documents confirmed before the ledger existed.
await ledger.PostPendingAsync(Seed, companyCode, start, today, cancellationToken: cancellationToken).ConfigureAwait(false);
// The professionals' invoices paid ten days after their date: their withholdings become due.
foreach (var row in await taxes.WithholdingsAsync(Seed, companyCode, today.Year, WithholdingDirection.Operated, cancellationToken).ConfigureAwait(false))
{
if (row.Withholding.Status == WithholdingStatus.Waiting)
{
var paid = row.Withholding.DocumentDate.AddDays(10);
await taxes.InvoicePaidAsync(Seed, companyCode, row.Withholding.Id, paid > today ? today : paid, cancellationToken).ConfigureAwait(false);
}
}
// The printer rental of January, and the same entry every month after as a recurring entry.
if (rentId is { } rent && bankId is { } bank)
{
var first = new DateOnly(today.Year, 1, 5);
var model = await journal.SaveAsync(Seed, companyCode, new EntryInput(null, first, "Noleggio stampante multifunzione",
[new EntryLineDraft(rent, null, null, Rent, 0m), new EntryLineDraft(bank, null, null, 0m, Rent)]) { Post = true }, cancellationToken).ConfigureAwait(false);
await recurring.SaveAsync(Seed, companyCode, new RecurringEntryInput(null, "Noleggio mensile stampante", model.Entry.Id, RecurrenceFrequency.Monthly,
RecurringEntryService.Next(first, RecurrenceFrequency.Monthly), null, false), cancellationToken).ConfigureAwait(false);
await recurring.GenerateAsync(Seed, companyCode, today, cancellationToken).ConfigureAwait(false);
}
// The settlements of the periods already ended, in order, and the stamp duty of the quarters ended.
var periods = periodicity == VatPeriodicity.Quarterly ? (today.Month - 1) / 3 : today.Month - 1;
for (var number = 1; number <= periods; number++)
{
var computed = await vat.ComputeAsync(Seed, companyCode, today.Year, number, cancellationToken).ConfigureAwait(false);
await vat.ConfirmAsync(Seed, companyCode, computed.Settlement.Id, cancellationToken).ConfigureAwait(false);
}
for (var quarter = 1; quarter <= (today.Month - 1) / 3; quarter++)
{
await taxes.StampDutyPaymentAsync(Seed, companyCode, today.Year, quarter, cancellationToken).ConfigureAwait(false);
}
// The F24 already due are paid on their day; those still to come stay to pay.
var dues = (await taxes.PaymentsAsync(Seed, companyCode, today.Year, cancellationToken).ConfigureAwait(false))
.Where(p => p.PaidOn is null && p.DueDate < today).Select(p => p.DueDate).Distinct().Order().ToList();
foreach (var due in dues)
{
await taxes.PayAsync(Seed, companyCode, due, due, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,260 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The purchases and the warehouse of the demo company (SPEC §14, issue #61), made through the document engine like a
/// user makes them: the opening stock on the first of January, supplier orders received in full and in part, the
/// supplier invoice of a receipt with a price that differs from the order, a professional's invoice, an invoice from a
/// German supplier still waiting for its self-invoice, and a stock take being counted. Some items start low, so that the
/// sales bring them under their minimum and the reorder proposal has something to propose. Runs only when the demo data
/// are asked and the company has no purchase documents yet; every document is marked as demo.
/// </summary>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The document editor (supplier terms, item costs).</param>
/// <param name="copies">The transformations between documents.</param>
/// <param name="stockTakes">The stock takes.</param>
/// <param name="factory">The units of work.</param>
/// <param name="clock">The clock.</param>
public sealed class DemoPurchasesSeeder(
DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, StockTakeService stockTakes, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
private static readonly Actor Seed = Actor.System;
private DocumentEngine Engine { get; } = engine;
private DocumentEditor Editor { get; } = editor;
private DocumentCopyService Copies { get; } = copies;
private StockTakeService StockTakes { get; } = stockTakes;
/// <inheritdoc />
public int Order => 30;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
{
return;
}
var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (data is null)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
var run = new Run(this, companyCode, data, today, cancellationToken);
await run.ExecuteAsync().ConfigureAwait(false);
}
// The suppliers, goods and reasons the documents use; null when the company already has purchases or lacks them.
private async Task<DemoData?> ReadAsync(string companyCode, CancellationToken cancellationToken)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
if (await uow.Repository<PurchaseOrder, long>().CountAsync(Query.For<PurchaseOrder>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<PurchaseDocument, long>().CountAsync(Query.For<PurchaseDocument>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<InventoryDocument, long>().CountAsync(Query.For<InventoryDocument>(), cancellationToken).ConfigureAwait(false) > 0)
{
return null;
}
var 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);
var goods = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo && i.Kind == ItemKind.Goods && i.Stocked), cancellationToken)
.ConfigureAwait(false)).Items.OrderBy(i => i.Id).ToList();
var goodIds = goods.Select(g => g.Id).ToList();
var suppliers = (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => goodIds.Contains(s.ItemId)), cancellationToken)
.ConfigureAwait(false)).Items.GroupBy(s => s.PartyId).ToDictionary(g => g.Key, g => (IReadOnlyList<long>)[.. g.Select(s => s.ItemId).Distinct()]);
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(r => r.Code, r => r.Id, StringComparer.Ordinal);
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
var warehouse = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items
.OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id;
string[] names = ["Metalli Nord S.p.A.", "Plastica Sud S.r.l.", "Studio Rag. Neri Paola", "Elektro Werke Süd GmbH"];
var ordinary = taxes.FirstOrDefault(t => t.Code == "22")?.Id;
var intraEu = taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N3.2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault()
?? taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault();
if (goods.Count < 12 || !names.All(parties.ContainsKey) || !reasons.TryGetValue("APE", out var opening) || warehouse is null || ordinary is null || intraEu is null)
{
return null;
}
return new DemoData(parties, goods, suppliers, opening, warehouse.Value, ordinary.Value, intraEu.Value);
}
private sealed record DemoData(
IReadOnlyDictionary<string, long> Parties, IReadOnlyList<Item> Goods, IReadOnlyDictionary<long, IReadOnlyList<long>> ItemsBySupplier, long OpeningReason,
long Warehouse, long Ordinary, long IntraEu);
// One seeding, with its company and dates.
private sealed class Run(DemoPurchasesSeeder owner, string company, DemoData data, DateOnly today, CancellationToken cancellationToken)
{
private long Party(string name) => data.Parties[name];
// A date some months before today, kept between the first of January and today (as the sales do).
private DateOnly D(int monthsBack, int day)
{
var month = today.AddMonths(-monthsBack);
var date = new DateOnly(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month)));
var first = new DateOnly(today.Year, 1, 1);
return date < first ? first : date > today ? today : date;
}
// The goods a supplier sells, else the first goods.
private List<Item> GoodsOf(string supplier, int count)
{
var ids = data.ItemsBySupplier.GetValueOrDefault(Party(supplier)) ?? [];
var own = data.Goods.Where(g => ids.Contains(g.Id)).Take(count).ToList();
return own.Count >= count ? own : [.. own, .. data.Goods.Where(g => !own.Contains(g)).Take(count - own.Count)];
}
public async Task ExecuteAsync()
{
await OpeningAsync().ConfigureAwait(false);
// Metalli Nord: an order received in full, invoiced at a higher price on one line.
var metals = GoodsOf("Metalli Nord S.p.A.", 3);
var o1 = await OrderAsync("Metalli Nord S.p.A.", D(4, 5), [(metals[0], 30m), (metals[1], 20m), (metals[2], 50m)], "Riordino trimestrale").ConfigureAwait(false);
var r1 = await ReceiveAsync(o1, D(4, 15), "DDT 1184", null).ConfigureAwait(false);
var f1 = await CopyAsync(r1, "FF", D(4, 30)).ConfigureAwait(false);
var dearer = f1.Lines.First(l => l.Kind == DocumentLineKind.Item);
dearer.Price = Math.Round(dearer.Price * 1.04m, 2);
f1.Header.ExternalReference = "MN/2026/0311";
f1.Header.ExternalDate = D(4, 28);
await ConfirmAsync(await SaveAsync(f1).ConfigureAwait(false)).ConfigureAwait(false);
// Plastica Sud: an order received in part; the rest is still on its way.
var plastics = GoodsOf("Plastica Sud S.r.l.", 3);
var o2 = await OrderAsync("Plastica Sud S.r.l.", D(2, 3), [(plastics[0], 40m), (plastics[1], 60m), (plastics[2], 25m)], null).ConfigureAwait(false);
await ReceiveAsync(o2, D(1, 10), "Bolla 552", [o2.Lines[0].Id, o2.Lines[1].Id]).ConfigureAwait(false);
// The accountant's fees, with withholding tax.
await InvoiceAsync("Studio Rag. Neri Paola", D(1, 28), "12/2026", D(1, 27), "Tenuta contabilità e dichiarativi", 450m, data.Ordinary).ConfigureAwait(false);
// Goods from Germany: no Italian VAT on the invoice, the self-invoice is still to issue.
var german = data.Goods[^1];
await InvoiceAsync("Elektro Werke Süd GmbH", D(0, 3), "RE-2026-08841", D(0, 1), german.Description, 1280m, data.IntraEu, german).ConfigureAwait(false);
// A stock take being counted: half of the list, two items differ from the books.
var take = await owner.StockTakes.CreateAsync(Seed, company, data.Warehouse, today, null, null, cancellationToken).ConfigureAwait(false);
var counts = new Dictionary<long, decimal?>();
foreach (var (line, index) in take.Lines.Take(Math.Min(12, take.Lines.Count)).Select((l, i) => (l, i)))
{
counts[line.Line.Id] = Math.Max(0m, line.Line.BookQuantity + index switch { 2 => -2m, 7 => 1m, _ => 0m });
}
await owner.StockTakes.SaveCountsAsync(Seed, company, take.Take.Id, counts, cancellationToken).ConfigureAwait(false);
}
// The opening stock: plenty of most goods, little of one in five, so that the year's sales bring them under.
private async Task OpeningAsync()
{
var movement = await owner.Engine.NewAsync(Seed, company, "MM", cancellationToken).ConfigureAwait(false);
movement.Header.IsDemo = true;
movement.Header.DocumentDate = new DateOnly(today.Year, 1, 1);
movement.Header.WarehouseId = data.Warehouse;
movement.Header.InventoryReasonId = data.OpeningReason;
movement.Header.Notes = "Esistenze iniziali dall'inventario di fine anno.";
foreach (var (item, index) in data.Goods.Select((g, i) => (g, i)))
{
var bulk = item.ReorderPoint is null;
movement.Lines.Add(new InventoryDocumentLine
{
Kind = DocumentLineKind.Item,
ItemId = item.Id,
Description = item.Description,
UnitOfMeasureId = item.UnitOfMeasureId,
Quantity = index % 5 == 0 ? (bulk ? 30m : 6m) : bulk ? 400m : 60m,
Price = item.StandardCost ?? 0m,
WarehouseId = data.Warehouse,
});
}
await ConfirmAsync(await SaveAsync(movement).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task<DocumentRecord> OrderAsync(string supplier, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, string? notes)
{
var order = await owner.Engine.NewAsync(Seed, company, "OF", cancellationToken).ConfigureAwait(false);
order.Header.IsDemo = true;
order.Header.DocumentDate = date;
order.Header.Notes = notes;
await owner.Editor.ApplyPartyAsync(Seed, company, order, Party(supplier), cancellationToken).ConfigureAwait(false);
foreach (var (item, quantity) in lines)
{
var line = new PurchaseOrderLine { Quantity = quantity };
await owner.Editor.FillLineAsync(Seed, company, order, line, item.Id, cancellationToken).ConfigureAwait(false);
line.Quantity = quantity;
order.Lines.Add(line);
}
return await ConfirmAsync(await SaveAsync(order).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task<DocumentRecord> ReceiveAsync(DocumentRecord order, DateOnly date, string reference, IReadOnlyCollection<long>? lines)
{
var receipt = await CopyAsync(order, "DDTF", date, lines).ConfigureAwait(false);
receipt.Header.ExternalReference = reference;
receipt.Header.ExternalDate = date;
return await ConfirmAsync(await SaveAsync(receipt).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task InvoiceAsync(string supplier, DateOnly date, string number, DateOnly numberDate, string description, decimal amount, long taxCode, Item? item = null)
{
var invoice = await owner.Engine.NewAsync(Seed, company, "FF", cancellationToken).ConfigureAwait(false);
invoice.Header.IsDemo = true;
invoice.Header.DocumentDate = date;
invoice.Header.ExternalReference = number;
invoice.Header.ExternalDate = numberDate;
await owner.Editor.ApplyPartyAsync(Seed, company, invoice, Party(supplier), cancellationToken).ConfigureAwait(false);
var line = new PurchaseDocumentLine { Quantity = 1m };
if (item is not null)
{
await owner.Editor.FillLineAsync(Seed, company, invoice, line, item.Id, cancellationToken).ConfigureAwait(false);
line.Quantity = 10m;
line.Price = Math.Round(amount / 10m, 2);
}
else
{
line.Kind = DocumentLineKind.Free;
line.Description = description;
line.Price = amount;
}
line.TaxCodeId = taxCode;
invoice.Lines.Add(line);
await ConfirmAsync(await SaveAsync(invoice).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task<DocumentRecord> CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection<long>? lines = null)
{
var copy = await owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken).ConfigureAwait(false);
copy.Header.IsDemo = true;
return copy;
}
private Task<DocumentRecord> SaveAsync(DocumentRecord record)
{
record.Header.IsDemo = true;
return owner.Engine.SaveAsync(Seed, company, record, cancellationToken);
}
private Task<DocumentRecord> ConfirmAsync(DocumentRecord record) =>
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
}
}
@@ -0,0 +1,124 @@
using Khaemhat.Application.Modules;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The ledger of the base data (SPEC §14, issue #62): the model chart of accounts of the country pack in three levels,
/// the VAT registers, the journal templates with their lines and, on the document types that have none, the template
/// and the register they post with. Like every base seeder it adds only what is missing.
/// </summary>
public sealed class LedgerSeeder : ISeeder
{
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Accounting;
/// <inheritdoc />
public SeedKind Kind => SeedKind.Base;
/// <inheritdoc />
public int Order => 50;
/// <inheritdoc />
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Pack.GetFeature<ILedgerTemplate>() is not { } ledger)
{
return;
}
var accounts = await SeedAccountsAsync(context, ledger, cancellationToken).ConfigureAwait(false);
await context.EnsureAsync(
"vat_registers",
ledger.VatRegisters.Select(r => new VatRegister { Code = r.Code, Description = r.Description, Kind = r.Kind, ReverseCharge = r.ReverseCharge }),
cancellationToken).ConfigureAwait(false);
await SeedTemplatesAsync(context, ledger, accounts, cancellationToken).ConfigureAwait(false);
var types = context.UnitOfWork.Repository<DocumentType, long>();
foreach (var posting in ledger.DocumentPostings)
{
var type = await types.FindAsync(Query.For<DocumentType>().Where(t => t.Code == posting.DocumentTypeCode), cancellationToken).ConfigureAwait(false);
if (type is not null && type.JournalTemplateCode is null && type.VatRegisterCode is null)
{
type.JournalTemplateCode = posting.JournalTemplateCode;
type.VatRegisterCode = posting.VatRegisterCode;
await types.UpdateAsync(type, cancellationToken).ConfigureAwait(false);
context.Count("document_types");
}
}
}
private static async Task<Dictionary<string, GlAccount>> SeedAccountsAsync(SeedContext context, ILedgerTemplate ledger, CancellationToken cancellationToken)
{
var repository = context.UnitOfWork.Repository<GlAccount, long>();
var existing = (await repository.ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(a => a.Code, StringComparer.Ordinal);
var parents = ledger.Accounts.Where(a => a.ParentCode is not null).Select(a => a.ParentCode!).ToHashSet(StringComparer.Ordinal);
foreach (var template in ledger.Accounts.OrderBy(a => a.Level).ThenBy(a => a.Code, StringComparer.Ordinal))
{
if (existing.ContainsKey(template.Code))
{
continue;
}
var account = new GlAccount
{
Code = template.Code,
Description = template.Description,
Level = template.Level,
ParentId = template.ParentCode is { } parent && existing.TryGetValue(parent, out var found) ? found.Id : null,
Nature = template.Nature,
Type = template.Type,
StatementLine = template.StatementLine,
SubLedger = template.SubLedger,
VatRelevant = template.VatRelevant,
ClosesAutomatically = template.Nature != AccountNature.Memorandum,
Postable = !parents.Contains(template.Code),
};
account.Id = await repository.InsertAsync(account, cancellationToken).ConfigureAwait(false);
existing[account.Code] = account;
context.Count("gl_accounts");
}
return existing;
}
private static async Task SeedTemplatesAsync(
SeedContext context, ILedgerTemplate ledger, Dictionary<string, GlAccount> accounts, CancellationToken cancellationToken)
{
var repository = context.UnitOfWork.Repository<JournalTemplate, long>();
var lines = context.UnitOfWork.Repository<JournalTemplateLine, long>();
var existing = (await repository.ListAsync(Query.For<JournalTemplate>(), cancellationToken).ConfigureAwait(false)).Items
.Select(t => t.Code).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var template in ledger.JournalTemplates.Where(t => !existing.Contains(t.Code)))
{
var id = await repository.InsertAsync(new JournalTemplate
{
Code = template.Code,
Description = template.Description,
Area = template.Area,
VatRegisterCode = template.VatRegisterCode,
OpensItems = template.OpensItems,
Reverses = template.Reverses,
}, cancellationToken).ConfigureAwait(false);
context.Count("gl_journal_templates");
for (var i = 0; i < template.Lines.Count; i++)
{
var line = template.Lines[i];
await lines.InsertAsync(new JournalTemplateLine
{
JournalTemplateId = id,
SortOrder = (i + 1) * 10,
Role = line.Role,
Side = line.Side,
AccountId = line.AccountCode is { } code && accounts.TryGetValue(code, out var account) ? account.Id : null,
Description = line.Description,
}, cancellationToken).ConfigureAwait(false);
}
}
}
}
@@ -0,0 +1,264 @@
using System.Globalization;
namespace Khaemhat.Core.Accounting;
/// <summary>The error codes of the journal; the interface translates them (<c>Ledger.json</c>).</summary>
public static class LedgerErrors
{
/// <summary>The entry does not exist.</summary>
public const string NotFound = "ledger.entry.not-found";
/// <summary>The entry has no description.</summary>
public const string DescriptionRequired = "ledger.entry.description-required";
/// <summary>The entry has no date.</summary>
public const string DateRequired = "ledger.entry.date-required";
/// <summary>The entry has no lines.</summary>
public const string LinesRequired = "ledger.entry.lines-required";
/// <summary>Debit and credit differ.</summary>
public const string Unbalanced = "ledger.entry.unbalanced";
/// <summary>A line without account.</summary>
public const string AccountRequired = "ledger.line.account-required";
/// <summary>A line on an account that does not exist.</summary>
public const string AccountMissing = "ledger.line.account-missing";
/// <summary>A line on a level that does not receive postings (mastro or conto with children).</summary>
public const string AccountNotPostable = "ledger.line.account-not-postable";
/// <summary>A line on an account no longer used.</summary>
public const string AccountDisabled = "ledger.line.account-disabled";
/// <summary>A line of a sub-ledger account without customer or supplier.</summary>
public const string PartyRequired = "ledger.line.party-required";
/// <summary>A line with neither debit nor credit.</summary>
public const string AmountRequired = "ledger.line.amount-required";
/// <summary>A line with both debit and credit.</summary>
public const string BothSides = "ledger.line.both-sides";
/// <summary>A negative amount.</summary>
public const string Negative = "ledger.line.negative";
/// <summary>VAT lines without the VAT register.</summary>
public const string VatRegisterRequired = "ledger.entry.vat-register-required";
/// <summary>A VAT line without VAT code.</summary>
public const string VatCodeRequired = "ledger.vat.code-required";
/// <summary>A final entry cannot change: reverse it.</summary>
public const string Final = "ledger.entry.final";
/// <summary>An entry of a document changes only through the document.</summary>
public const string FromDocument = "ledger.entry.from-document";
/// <summary>The entry was already reversed.</summary>
public const string AlreadyReversed = "ledger.entry.already-reversed";
/// <summary>Only posted or final entries are reversed.</summary>
public const string NotPosted = "ledger.entry.not-posted";
/// <summary>Entries become final in date order: an earlier date is already final.</summary>
public const string FinalOrder = "ledger.entry.final-order";
/// <summary>A role of the journal template has no account.</summary>
public const string RoleAccountMissing = "ledger.posting.account-missing";
/// <summary>The journal template does not exist.</summary>
public const string TemplateMissing = "ledger.template.missing";
/// <summary>The account has postings: disable it instead.</summary>
public const string AccountUsed = "ledger.account.used";
/// <summary>The account has children.</summary>
public const string AccountHasChildren = "ledger.account.has-children";
/// <summary>The code of the account does not fit its parent.</summary>
public const string AccountParent = "ledger.account.parent";
/// <summary>Another account has the code.</summary>
public const string AccountDuplicate = "ledger.account.duplicate";
/// <summary>The code of the account is not one to three groups of digits separated by points.</summary>
public const string AccountCode = "ledger.account.code";
/// <summary>The entry is the model of a recurring entry.</summary>
public const string RecurringModel = "ledger.entry.recurring-model";
/// <summary>Drafts are left before the day to make final.</summary>
public const string DraftsBeforeFinal = "ledger.entry.drafts-before-final";
/// <summary>No fiscal year contains the day.</summary>
public const string NoFiscalYear = "ledger.entry.no-fiscal-year";
/// <summary>The code of a template is missing or longer than 10.</summary>
public const string TemplateCode = "ledger.template.code";
/// <summary>Another template has the code.</summary>
public const string TemplateDuplicate = "ledger.template.duplicate";
/// <summary>The template is used by entries or document types.</summary>
public const string TemplateUsed = "ledger.template.used";
/// <summary>The settlement of the period is already confirmed.</summary>
public const string SettlementConfirmed = "vat.settlement.confirmed";
/// <summary>The previous period is not settled.</summary>
public const string SettlementPrevious = "vat.settlement.previous";
/// <summary>A later period is already settled.</summary>
public const string SettlementLater = "vat.settlement.later";
/// <summary>The tax payment is already paid.</summary>
public const string PaymentPaid = "tax.payment.paid";
/// <summary>The withholding is not due or already paid.</summary>
public const string WithholdingNotDue = "withholding.not-due";
/// <summary>The account of the bank is missing.</summary>
public const string BankAccountMissing = "ledger.bank.account-missing";
/// <summary>The final print of a VAT register must follow the last one.</summary>
public const string PrintOrder = "vat.register.print-order";
}
/// <summary>An account as the validator needs it.</summary>
/// <param name="Id">The account.</param>
/// <param name="Postable">Receives postings.</param>
/// <param name="Disabled">No longer used.</param>
/// <param name="SubLedger">Its lines need a customer or supplier.</param>
public sealed record AccountRule(long Id, bool Postable, bool Disabled, bool SubLedger);
/// <summary>A line as the validator reads it.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Debit">The debit.</param>
/// <param name="Credit">The credit.</param>
public sealed record EntryLineCheck(long? AccountId, long? PartyId, decimal Debit, decimal Credit);
/// <summary>
/// The rules of an entry (SPEC §11.7, issue #63): a draft may not balance, a posted entry must; every line on an
/// active leaf account, with the party on sub-ledger accounts, one side only and no negative amounts; VAT lines need
/// the register. The open period is checked by the service, which knows the calendar.
/// </summary>
public static class JournalEntryValidator
{
/// <summary>Checks an entry.</summary>
/// <param name="description">The description.</param>
/// <param name="lines">The lines.</param>
/// <param name="vatLines">The number of VAT lines.</param>
/// <param name="hasVatRegister">Whether the entry has its VAT register.</param>
/// <param name="accounts">The accounts, by id.</param>
/// <param name="posting">Whether the entry is being posted (it must balance) or saved as a draft.</param>
/// <returns>The errors, as <c>field:code</c>; empty when valid.</returns>
public static IReadOnlyList<string> Check(
string? description, IReadOnlyList<EntryLineCheck> lines, int vatLines, bool hasVatRegister, IReadOnlyDictionary<long, AccountRule> accounts, bool posting)
{
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(accounts);
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(description))
{
errors.Add("Description:" + LedgerErrors.DescriptionRequired);
}
if (posting && lines.Count == 0 && vatLines == 0)
{
errors.Add("Lines:" + LedgerErrors.LinesRequired);
}
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
var field = "Lines." + i.ToString(CultureInfo.InvariantCulture) + ".";
if (line.AccountId is not { } accountId)
{
errors.Add(field + "AccountId:" + LedgerErrors.AccountRequired);
}
else if (!accounts.TryGetValue(accountId, out var account))
{
errors.Add(field + "AccountId:" + LedgerErrors.AccountMissing);
}
else
{
if (!account.Postable)
{
errors.Add(field + "AccountId:" + LedgerErrors.AccountNotPostable);
}
if (account.Disabled)
{
errors.Add(field + "AccountId:" + LedgerErrors.AccountDisabled);
}
if (account.SubLedger && line.PartyId is null && posting)
{
errors.Add(field + "PartyId:" + LedgerErrors.PartyRequired);
}
}
if (line.Debit < 0m || line.Credit < 0m)
{
errors.Add(field + "Debit:" + LedgerErrors.Negative);
}
else if (line.Debit != 0m && line.Credit != 0m)
{
errors.Add(field + "Credit:" + LedgerErrors.BothSides);
}
else if (line.Debit == 0m && line.Credit == 0m && posting)
{
errors.Add(field + "Debit:" + LedgerErrors.AmountRequired);
}
}
if (posting && Difference(lines) != 0m)
{
errors.Add("Lines:" + LedgerErrors.Unbalanced);
}
if (vatLines > 0 && !hasVatRegister)
{
errors.Add("VatRegisterId:" + LedgerErrors.VatRegisterRequired);
}
return errors;
}
/// <summary>Debit minus credit of the lines.</summary>
/// <param name="lines">The lines.</param>
/// <returns>The difference; zero when the entry balances.</returns>
public static decimal Difference(IEnumerable<EntryLineCheck> lines) =>
lines?.Sum(l => l.Debit - l.Credit) ?? throw new ArgumentNullException(nameof(lines));
}
/// <summary>Codes of accounts in the form <c>MM.CC.SSS</c>.</summary>
public static class AccountCodes
{
/// <summary>The level of a code (number of parts), or zero when the code is not valid.</summary>
/// <param name="code">The code.</param>
/// <returns>1 to 3, or 0.</returns>
public static int LevelOf(string? code)
{
if (string.IsNullOrWhiteSpace(code))
{
return 0;
}
var parts = code.Trim().Split('.');
return parts.Length is >= 1 and <= 3 && parts.All(p => p.Length is >= 1 and <= 6 && p.All(char.IsAsciiLetterOrDigit)) ? parts.Length : 0;
}
/// <summary>The code of the parent: the code without its last part.</summary>
/// <param name="code">The code.</param>
/// <returns>The parent code, or <see langword="null"/> for a mastro.</returns>
public static string? ParentOf(string code)
{
ArgumentNullException.ThrowIfNull(code);
var dot = code.LastIndexOf('.');
return dot < 0 ? null : code[..dot];
}
}
+837
View File
@@ -0,0 +1,837 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Entities;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
namespace Khaemhat.Core.Accounting;
/// <summary>The side of a posting.</summary>
public enum AccountSide
{
/// <summary>Dare.</summary>
Debit = 0,
/// <summary>Avere.</summary>
Credit = 1,
}
/// <summary>
/// An account of the chart (SPEC §11.7, mockup 042, <c>gl_accounts</c>): three levels, mastro (<c>05</c>), conto
/// (<c>05.01</c>) and sottoconto (<c>05.01.001</c>); only the leaves receive postings. Customers and suppliers are not
/// accounts of their own: their sub-ledger is the control account plus the party on each line (ADR 0036).
/// </summary>
public sealed class GlAccount : CodedEntity
{
/// <summary>The level, 1 to 3: the number of parts of the code.</summary>
public int Level { get; set; }
/// <summary>The account it adds up into.</summary>
public long? ParentId { get; set; }
/// <summary>The statement it ends up in.</summary>
public AccountNature Nature { get; set; }
/// <summary>What the automatic postings look for in it.</summary>
public AccountType Type { get; set; }
/// <summary>The line of the legal financial statements (voce CEE, art. 2424/2425), such as <c>C.II.1</c>.</summary>
public string? StatementLine { get; set; }
/// <summary>The line of the reclassified statements.</summary>
public string? Reclassification { get; set; }
/// <summary>The lines carry a customer or supplier: the account has a sub-ledger (partitario).</summary>
public bool SubLedger { get; set; }
/// <summary>Relevant for VAT (revenues and costs that go to the VAT registers).</summary>
public bool VatRelevant { get; set; }
/// <summary>Closed by the year end into the income statement or the balance sheet.</summary>
public bool ClosesAutomatically { get; set; }
/// <summary>Postings go on it: only the leaves.</summary>
public bool Postable { get; set; }
}
/// <summary>What a VAT register records.</summary>
public enum VatRegisterKind
{
/// <summary>Invoices issued: VAT due.</summary>
Sales = 0,
/// <summary>Invoices received: VAT deductible.</summary>
Purchases = 1,
/// <summary>Daily receipts of retail sales (corrispettivi): VAT due.</summary>
Receipts = 2,
}
/// <summary>
/// A VAT register (SPEC §11.7, mockup 045, <c>vat_registers</c>): sales, purchases or receipts, with sections for
/// the self-invoices of reverse charge (the same operation annotated in a sales and a purchase register).
/// </summary>
public sealed class VatRegister : CodedEntity
{
/// <summary>What it records.</summary>
public VatRegisterKind Kind { get; set; }
/// <summary>A section for reverse-charge self-invoices: the VAT is due and deducted together (neutral).</summary>
public bool ReverseCharge { get; set; }
/// <summary>The year of the last final print.</summary>
public int? PrintYear { get; set; }
/// <summary>The last page of the last final print of <see cref="PrintYear"/>.</summary>
public int LastPage { get; set; }
/// <summary>The last day printed in final form.</summary>
public DateOnly? LastPrintedDate { get; set; }
}
/// <summary>The kind of operations a journal template records.</summary>
public enum JournalArea
{
/// <summary>Anything else.</summary>
General = 0,
/// <summary>Invoices issued and their notes.</summary>
Sales = 1,
/// <summary>Invoices received and their notes.</summary>
Purchases = 2,
/// <summary>Collections, payments, transfers.</summary>
Treasury = 3,
/// <summary>VAT settlements and tax payments.</summary>
Taxes = 4,
/// <summary>Year end: accruals, depreciation, closing and opening.</summary>
YearEnd = 5,
}
/// <summary>
/// A journal template (causale contabile, SPEC §11.7, mockup 043, <c>gl_journal_templates</c>): what an entry is,
/// which VAT register it uses and the model of its lines.
/// </summary>
public sealed class JournalTemplate : CodedEntity
{
/// <summary>The kind of operations.</summary>
public JournalArea Area { get; set; }
/// <summary>The VAT register, by code, for entries with VAT.</summary>
public string? VatRegisterCode { get; set; }
/// <summary>The entries open items of customers or suppliers (scadenze).</summary>
public bool OpensItems { get; set; }
/// <summary>The sign of the document is reversed (credit notes).</summary>
public bool Reverses { get; set; }
}
/// <summary>What a line of a journal template stands for, so that the automatic postings find its account.</summary>
public enum PostingRole
{
/// <summary>A fixed account (contropartita).</summary>
Account = 0,
/// <summary>The customer: the customers control account with the party.</summary>
Customer = 1,
/// <summary>The supplier: the suppliers control account with the party.</summary>
Supplier = 2,
/// <summary>Revenues, by line.</summary>
Revenue = 3,
/// <summary>Costs, by line.</summary>
Cost = 4,
/// <summary>VAT on sales.</summary>
SalesVat = 5,
/// <summary>VAT on purchases.</summary>
PurchaseVat = 6,
/// <summary>A bank account.</summary>
Bank = 7,
/// <summary>Cash.</summary>
Cash = 8,
/// <summary>Withholding taxes to pay (Erario c/ritenute).</summary>
WithholdingPayable = 9,
/// <summary>Withholding taxes suffered (Erario c/ritenute subite).</summary>
WithholdingCredit = 10,
/// <summary>Social security contributions charged on fees (rivalsa cassa previdenza).</summary>
SocialSecurity = 11,
/// <summary>Stamp duty charged to the customer, or paid.</summary>
StampDuty = 12,
/// <summary>Roundings and small differences (abbuoni).</summary>
Rounding = 13,
/// <summary>The VAT settlement account (Erario c/IVA).</summary>
VatSettlement = 14,
/// <summary>VAT of split payment, due by the public customer.</summary>
SplitPaymentVat = 15,
}
/// <summary>A line of a journal template (<c>gl_journal_template_lines</c>).</summary>
public sealed class JournalTemplateLine : Entity<long>
{
/// <summary>The template.</summary>
public long JournalTemplateId { get; set; }
/// <summary>The order.</summary>
public int SortOrder { get; set; }
/// <summary>What the line stands for.</summary>
public PostingRole Role { get; set; }
/// <summary>Debit or credit, for an invoice (a credit note reverses it).</summary>
public AccountSide Side { get; set; }
/// <summary>The account: fixed for <see cref="PostingRole.Account"/>, the default for the other roles.</summary>
public long? AccountId { get; set; }
/// <summary>The description proposed on the line.</summary>
public string? Description { get; set; }
}
/// <summary>The state of an entry.</summary>
public enum GlEntryStatus
{
/// <summary>Being written: may not balance, counts nowhere.</summary>
Draft = 0,
/// <summary>Posted (provvisoria): balanced, counts in balances and registers, can still change.</summary>
Posted = 1,
/// <summary>Final (definitiva): numbered on the journal, immutable; only a reversal corrects it.</summary>
Final = 2,
}
/// <summary>Where an entry comes from.</summary>
public enum GlEntrySource
{
/// <summary>Typed in the journal.</summary>
Manual = 0,
/// <summary>Posted by a document (invoice, credit note, self-invoice).</summary>
Document = 1,
/// <summary>A VAT settlement.</summary>
VatSettlement = 2,
/// <summary>A tax payment (F24).</summary>
TaxPayment = 3,
/// <summary>Generated from a recurring entry.</summary>
Recurring = 4,
/// <summary>The reversal of another entry.</summary>
Reversal = 5,
/// <summary>The payment of an invoice with a withholding.</summary>
Withholding = 6,
}
/// <summary>
/// An entry of the journal (registrazione di prima nota, SPEC §11.7, mockups 040-041, <c>gl_entries</c>): numbered
/// per year when posted, numbered on the journal (libro giornale) when final.
/// </summary>
public sealed class GlEntry : Entity<long>, IDemoMarkable
{
/// <summary>The year of the number.</summary>
public int Year { get; set; }
/// <summary>The number in the year, once posted.</summary>
public long? Number { get; set; }
/// <summary>The number as shown, such as <c>2026/00125</c>.</summary>
public string? EntryNumber { get; set; }
/// <summary>The progressive number on the journal, once final.</summary>
public long? JournalNumber { get; set; }
/// <summary>The date of registration.</summary>
public DateOnly EntryDate { get; set; }
/// <summary>The date of economic competence, when different.</summary>
public DateOnly? CompetenceDate { get; set; }
/// <summary>The journal template.</summary>
public long? JournalTemplateId { get; set; }
/// <summary>The code of the template, as it was.</summary>
public string? TemplateCode { get; set; }
/// <summary>The description.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The state.</summary>
public GlEntryStatus Status { get; set; }
/// <summary>Where it comes from.</summary>
public GlEntrySource Source { get; set; }
/// <summary>The family of the document that posted it.</summary>
public DocumentFamily? SourceFamily { get; set; }
/// <summary>The document that posted it.</summary>
public long? SourceDocumentId { get; set; }
/// <summary>The kind of that document.</summary>
public DocumentKind? SourceKind { get; set; }
/// <summary>The number of the document (the supplier's number for purchases).</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 VAT register, for entries with VAT.</summary>
public long? VatRegisterId { get; set; }
/// <summary>The protocol in the VAT register.</summary>
public long? VatProtocol { get; set; }
/// <summary>The date the VAT counts from (registration for purchases).</summary>
public DateOnly? VatDate { get; set; }
/// <summary>The entry this one reverses.</summary>
public long? ReversalOfId { get; set; }
/// <summary>The entry that reversed this one.</summary>
public long? ReversedById { get; set; }
/// <summary>The total debit (equal to the credit once posted).</summary>
public decimal TotalDebit { get; set; }
/// <summary>The total credit.</summary>
public decimal TotalCredit { get; set; }
/// <summary>When it became final.</summary>
public DateTime? FinalizedAt { get; set; }
/// <summary>Who made it final.</summary>
public string? FinalizedBy { get; set; }
/// <summary>Notes.</summary>
public string? Notes { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
/// <summary>Whether it balances.</summary>
public bool Balanced => TotalDebit == TotalCredit;
}
/// <summary>A line of an entry (<c>gl_entry_lines</c>).</summary>
public sealed class GlEntryLine : Entity<long>
{
/// <summary>The entry.</summary>
public long EntryId { get; set; }
/// <summary>The order, from 1.</summary>
public int LineNumber { get; set; }
/// <summary>The date of the entry (kept here to read balances without joins).</summary>
public DateOnly EntryDate { get; set; }
/// <summary>The state of the entry (kept here: drafts count nowhere).</summary>
public GlEntryStatus Status { get; set; }
/// <summary>The account.</summary>
public long AccountId { get; set; }
/// <summary>The customer or supplier, on sub-ledger accounts.</summary>
public long? PartyId { get; set; }
/// <summary>The description.</summary>
public string? Description { get; set; }
/// <summary>The debit.</summary>
public decimal Debit { get; set; }
/// <summary>The credit.</summary>
public decimal Credit { get; set; }
/// <summary>The cost center.</summary>
public long? CostCenterId { get; set; }
/// <summary>The job.</summary>
public long? JobId { get; set; }
/// <summary>The open item it settles or creates.</summary>
public long? OpenItemId { get; set; }
}
/// <summary>A VAT line of an entry (<c>gl_entry_vat</c>): what the VAT registers and the settlement read.</summary>
public sealed class GlEntryVat : Entity<long>
{
/// <summary>The entry.</summary>
public long EntryId { get; set; }
/// <summary>The order, from 1.</summary>
public int LineNumber { get; set; }
/// <summary>The register.</summary>
public long VatRegisterId { get; set; }
/// <summary>The kind of the register (kept here for the settlement).</summary>
public VatRegisterKind RegisterKind { get; set; }
/// <summary>The VAT date of the entry (kept here: the registers and the settlement read by it).</summary>
public DateOnly VatDate { get; set; }
/// <summary>The state of the entry (kept here).</summary>
public GlEntryStatus Status { get; set; }
/// <summary>The VAT code.</summary>
public long? TaxCodeId { get; set; }
/// <summary>The rate in percent.</summary>
public decimal Rate { get; set; }
/// <summary>The nature of operations without VAT.</summary>
public string? Nature { get; set; }
/// <summary>When the VAT becomes due.</summary>
public TaxExigibility Exigibility { get; set; }
/// <summary>The taxable amount, with the sign of the operation (negative for credit notes).</summary>
public decimal Taxable { get; set; }
/// <summary>The VAT, with the sign of the operation.</summary>
public decimal Tax { get; set; }
/// <summary>The part of the VAT that cannot be deducted.</summary>
public decimal NonDeductibleTax { get; set; }
}
/// <summary>Whether an open item is to collect or to pay.</summary>
public enum OpenItemDirection
{
/// <summary>From a customer.</summary>
Receivable = 0,
/// <summary>To a supplier.</summary>
Payable = 1,
}
/// <summary>
/// An open item (partita aperta, <c>gl_open_items</c>): an installment of an invoice posted to the ledger, which the
/// schedule of collections and payments (M8) settles.
/// </summary>
public sealed class OpenItem : Entity<long>, IDemoMarkable
{
/// <summary>To collect or to pay.</summary>
public OpenItemDirection Direction { get; set; }
/// <summary>The customer or supplier.</summary>
public long PartyId { get; set; }
/// <summary>The control account.</summary>
public long AccountId { get; set; }
/// <summary>The entry that opened it.</summary>
public long EntryId { 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 installment, from 1.</summary>
public int Installment { get; set; }
/// <summary>The due date.</summary>
public DateOnly DueDate { get; set; }
/// <summary>The amount, negative for credit notes.</summary>
public decimal Amount { get; set; }
/// <summary>What was collected or paid.</summary>
public decimal PaidAmount { get; set; }
/// <summary>The payment method.</summary>
public long? PaymentMethodId { get; set; }
/// <summary>Fully settled.</summary>
public bool Closed { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>How often a recurring entry repeats.</summary>
public enum RecurrenceFrequency
{
/// <summary>Every month.</summary>
Monthly = 0,
/// <summary>Every three months.</summary>
Quarterly = 1,
/// <summary>Every six months.</summary>
HalfYearly = 2,
/// <summary>Every year.</summary>
Yearly = 3,
}
/// <summary>
/// A recurring entry (<c>gl_recurring_entries</c>): an entry used as model, copied as a draft at each due date (rents,
/// leases, fees).
/// </summary>
public sealed class RecurringEntry : Entity<long>, IDemoMarkable
{
/// <summary>The description.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The entry copied.</summary>
public long ModelEntryId { get; set; }
/// <summary>How often.</summary>
public RecurrenceFrequency Frequency { get; set; }
/// <summary>The date of the next copy.</summary>
public DateOnly NextDate { get; set; }
/// <summary>No copies after this day.</summary>
public DateOnly? EndDate { get; set; }
/// <summary>The last entry made.</summary>
public long? LastEntryId { get; set; }
/// <summary>Suspended.</summary>
public bool Disabled { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>The state of a VAT settlement.</summary>
public enum VatSettlementStatus
{
/// <summary>Computed, can be computed again.</summary>
Draft = 0,
/// <summary>Confirmed: the period is settled and the entry posted.</summary>
Confirmed = 1,
}
/// <summary>A periodic VAT settlement (SPEC §11.7, mockup 046, <c>vat_settlements</c>).</summary>
public sealed class VatSettlement : Entity<long>, IDemoMarkable
{
/// <summary>The year.</summary>
public int Year { get; set; }
/// <summary>The month (1-12) or the quarter (1-4).</summary>
public int Number { get; set; }
/// <summary>Monthly or quarterly.</summary>
public VatPeriodicity Periodicity { get; set; }
/// <summary>The first day.</summary>
public DateOnly StartDate { get; set; }
/// <summary>The last day.</summary>
public DateOnly EndDate { get; set; }
/// <summary>The day of the settlement.</summary>
public DateOnly SettlementDate { get; set; }
/// <summary>The state.</summary>
public VatSettlementStatus Status { get; set; }
/// <summary>The VAT due on sales of the period.</summary>
public decimal SalesTax { get; set; }
/// <summary>The VAT deductible on purchases, after the pro rata.</summary>
public decimal PurchaseTax { get; set; }
/// <summary>The VAT on purchases that cannot be deducted.</summary>
public decimal NonDeductibleTax { get; set; }
/// <summary>The VAT of the period not yet due (deferred, split payment, cash accounting).</summary>
public decimal DeferredTax { get; set; }
/// <summary>The pro rata applied, percent.</summary>
public decimal ProRataPercent { get; set; } = 100m;
/// <summary>The credit of the previous period.</summary>
public decimal PreviousCredit { get; set; }
/// <summary>The debit of the previous period below the minimum, carried here.</summary>
public decimal PreviousDebit { get; set; }
/// <summary>The advance paid in December, deducted from the last period.</summary>
public decimal AdvancePaid { get; set; }
/// <summary>The interest rate for quarterly payers, percent.</summary>
public decimal InterestPercent { get; set; }
/// <summary>The interest.</summary>
public decimal Interest { get; set; }
/// <summary>The VAT to pay (zero when below the minimum or in credit).</summary>
public decimal AmountDue { get; set; }
/// <summary>The credit carried to the next period.</summary>
public decimal CreditCarried { get; set; }
/// <summary>The debit below the minimum, carried to the next period.</summary>
public decimal DebitCarried { get; set; }
/// <summary>The F24 payment code.</summary>
public string? PaymentCode { get; set; }
/// <summary>The day the payment is due.</summary>
public DateOnly? DueDate { get; set; }
/// <summary>The entry that closes the VAT accounts.</summary>
public long? GlEntryId { get; set; }
/// <summary>The tax payment created.</summary>
public long? TaxPaymentId { get; set; }
/// <summary>When it was confirmed.</summary>
public DateTime? ConfirmedAt { get; set; }
/// <summary>Who confirmed it.</summary>
public string? ConfirmedBy { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>A line of a VAT settlement: one register (<c>vat_settlement_lines</c>).</summary>
public sealed class VatSettlementLine : Entity<long>
{
/// <summary>The settlement.</summary>
public long SettlementId { get; set; }
/// <summary>The register.</summary>
public long VatRegisterId { get; set; }
/// <summary>The kind of the register.</summary>
public VatRegisterKind RegisterKind { get; set; }
/// <summary>The number of entries.</summary>
public int Documents { get; set; }
/// <summary>The taxable amount.</summary>
public decimal Taxable { get; set; }
/// <summary>The VAT.</summary>
public decimal Tax { get; set; }
/// <summary>The VAT not deductible.</summary>
public decimal NonDeductibleTax { get; set; }
/// <summary>The VAT not yet due.</summary>
public decimal DeferredTax { get; set; }
}
/// <summary>What a tax payment pays.</summary>
public enum TaxPaymentSource
{
/// <summary>Typed by hand.</summary>
Manual = 0,
/// <summary>A VAT settlement.</summary>
VatSettlement = 1,
/// <summary>The VAT advance of December.</summary>
VatAdvance = 2,
/// <summary>Withholding taxes.</summary>
Withholding = 3,
/// <summary>Stamp duty on e-invoices.</summary>
StampDuty = 4,
}
/// <summary>
/// A line of a tax payment form (rigo F24, <c>tax_payments</c>): a payment code, the period it refers to and the
/// amount; paid lines post the payment entry.
/// </summary>
public sealed class TaxPayment : Entity<long>, IDemoMarkable
{
/// <summary>The day it is due.</summary>
public DateOnly DueDate { get; set; }
/// <summary>The payment code, such as <c>6009</c>.</summary>
public string PaymentCode { get; set; } = string.Empty;
/// <summary>The year the payment refers to.</summary>
public int ReferenceYear { get; set; }
/// <summary>The month or installment it refers to, as the form wants it (<c>0009</c>, <c>0003</c>).</summary>
public string? ReferencePeriod { get; set; }
/// <summary>The description.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The amount due.</summary>
public decimal Amount { get; set; }
/// <summary>What it pays.</summary>
public TaxPaymentSource Source { get; set; }
/// <summary>The record it pays (settlement), when one.</summary>
public long? SourceId { get; set; }
/// <summary>The day it was paid.</summary>
public DateOnly? PaidOn { get; set; }
/// <summary>The bank account used.</summary>
public long? BankAccountId { get; set; }
/// <summary>The entry of the payment.</summary>
public long? GlEntryId { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>Whether the company withheld a tax or suffered it.</summary>
public enum WithholdingDirection
{
/// <summary>Withheld by the company on fees it pays (operata): to pay with F24.</summary>
Operated = 0,
/// <summary>Withheld by a customer on the company's fees (subita): a tax credit.</summary>
Suffered = 1,
}
/// <summary>The state of a withholding.</summary>
public enum WithholdingStatus
{
/// <summary>The invoice is not paid yet: nothing is due.</summary>
Waiting = 0,
/// <summary>The invoice is paid: due by the 16th of the next month.</summary>
Due = 1,
/// <summary>Paid with F24.</summary>
Paid = 2,
/// <summary>Suffered: a credit for the tax return.</summary>
Suffered = 3,
}
/// <summary>
/// A withholding tax of an invoice (ritenuta d'acconto, SPEC §11.7, mockup 047, <c>withholdings</c>): operated on the
/// fees and commissions received, suffered on the fees issued.
/// </summary>
public sealed class Withholding : Entity<long>, IDemoMarkable
{
/// <summary>Operated or suffered.</summary>
public WithholdingDirection Direction { get; set; }
/// <summary>The family of the invoice.</summary>
public DocumentFamily SourceFamily { get; set; }
/// <summary>The invoice.</summary>
public long SourceDocumentId { get; set; }
/// <summary>The number of the invoice.</summary>
public string? DocumentNumber { get; set; }
/// <summary>The date of the invoice.</summary>
public DateOnly DocumentDate { get; set; }
/// <summary>The supplier (operated) or customer (suffered).</summary>
public long PartyId { get; set; }
/// <summary>The type of the e-invoice, such as <c>RT01</c>.</summary>
public string? WithholdingType { get; set; }
/// <summary>The reason of the payment (<c>A</c>, <c>R</c>...).</summary>
public string? Reason { get; set; }
/// <summary>The fee or commission.</summary>
public decimal Taxable { get; set; }
/// <summary>The social security fund, such as <c>TC22</c>.</summary>
public string? SocialSecurityFund { get; set; }
/// <summary>The social security contribution charged.</summary>
public decimal SocialSecurityAmount { get; set; }
/// <summary>The rate, percent.</summary>
public decimal Rate { get; set; }
/// <summary>The share of the fee the rate applies to, percent.</summary>
public decimal BasePercent { get; set; } = 100m;
/// <summary>The tax withheld.</summary>
public decimal Amount { get; set; }
/// <summary>The F24 payment code.</summary>
public string? PaymentCode { get; set; }
/// <summary>The day the invoice was paid: the withholding is due from that month.</summary>
public DateOnly? InvoicePaidOn { get; set; }
/// <summary>The state.</summary>
public WithholdingStatus Status { get; set; }
/// <summary>The F24 line that paid it.</summary>
public long? TaxPaymentId { get; set; }
/// <summary>The entry that moved it to the tax authority when the invoice was paid.</summary>
public long? GlEntryId { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>A print of a VAT register (<c>vat_register_prints</c>): final prints number the pages of the year.</summary>
public sealed class VatRegisterPrint : Entity<long>
{
/// <summary>The register.</summary>
public long VatRegisterId { get; set; }
/// <summary>The year.</summary>
public int Year { get; set; }
/// <summary>The first day.</summary>
public DateOnly FromDate { get; set; }
/// <summary>The last day.</summary>
public DateOnly ToDate { get; set; }
/// <summary>The first page.</summary>
public int FirstPage { get; set; }
/// <summary>The last page.</summary>
public int LastPage { get; set; }
/// <summary>The attachment with the PDF.</summary>
public long? AttachmentId { get; set; }
/// <summary>When.</summary>
public DateTime PrintedAt { get; set; }
/// <summary>Who.</summary>
public string? PrintedBy { get; set; }
}
@@ -0,0 +1,276 @@
using Khaemhat.Core.Tax;
namespace Khaemhat.Core.Accounting;
/// <summary>What a document posts.</summary>
public enum PostingKind
{
/// <summary>An invoice issued, a debit note, a fee: customer, revenues, VAT on sales.</summary>
Sale = 0,
/// <summary>An invoice received: supplier, costs, VAT on purchases.</summary>
Purchase = 1,
/// <summary>A self-invoice or integration (reverse charge): VAT due and VAT deducted, no customer or supplier.</summary>
SelfInvoice = 2,
}
/// <summary>A revenue or cost line of a document, after discounts.</summary>
/// <param name="AccountId">The account of the line (from the line, the item, the party or the template).</param>
/// <param name="Amount">The taxable amount of the line, positive.</param>
/// <param name="TaxCodeId">The VAT code of the line (non-deductible VAT goes to its cost).</param>
/// <param name="CostCenterId">The cost center.</param>
/// <param name="JobId">The job.</param>
public sealed record PostingLineInput(long? AccountId, decimal Amount, long? TaxCodeId = null, long? CostCenterId = null, long? JobId = null);
/// <summary>A line of the tax summary of a document.</summary>
/// <param name="TaxCodeId">The VAT code.</param>
/// <param name="Rate">The rate.</param>
/// <param name="Nature">The nature, for operations without VAT.</param>
/// <param name="Exigibility">When the VAT is due.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="NonDeductibleTax">The VAT not deductible.</param>
public sealed record PostingTaxInput(long? TaxCodeId, decimal Rate, string? Nature, TaxExigibility Exigibility, decimal Taxable, decimal Tax, decimal NonDeductibleTax);
/// <summary>A document to post, with its amounts as computed by the documents engine.</summary>
/// <param name="Kind">Sale, purchase or self-invoice.</param>
/// <param name="Reverse">A credit note: every side is reversed and the VAT is negative.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Lines">The revenue or cost lines.</param>
/// <param name="Taxes">The tax summary.</param>
/// <param name="Total">The total of the document (taxable, VAT and stamp duty charged).</param>
/// <param name="StampDuty">The stamp duty charged on the document (zero when the company bears it).</param>
/// <param name="SocialSecurity">The social security contribution charged on a fee (rivalsa).</param>
public sealed record PostingInput(
PostingKind Kind,
bool Reverse,
long? PartyId,
IReadOnlyList<PostingLineInput> Lines,
IReadOnlyList<PostingTaxInput> Taxes,
decimal Total,
decimal StampDuty = 0m,
decimal SocialSecurity = 0m);
/// <summary>The accounts a posting needs besides those of the lines.</summary>
/// <param name="Party">The control account of the customer or supplier.</param>
/// <param name="DefaultLine">The revenue or cost when a line has none (and the non-deductible VAT of a self-invoice).</param>
/// <param name="SalesVat">VAT on sales.</param>
/// <param name="PurchaseVat">VAT on purchases.</param>
/// <param name="StampDuty">Stamp duty (revenue when charged to a customer, cost when charged by a supplier).</param>
/// <param name="SocialSecurity">Social security charged on fees (revenue on sales).</param>
public sealed record PostingAccounts(long? Party, long? DefaultLine, long? SalesVat, long? PurchaseVat, long? StampDuty = null, long? SocialSecurity = null);
/// <summary>A line of the entry produced.</summary>
/// <param name="Role">What the line stands for.</param>
/// <param name="AccountId">The account.</param>
/// <param name="PartyId">The customer or supplier, on their line.</param>
/// <param name="Side">Debit or credit.</param>
/// <param name="Amount">The amount, positive.</param>
/// <param name="CostCenterId">The cost center.</param>
/// <param name="JobId">The job.</param>
public sealed record PostedLine(PostingRole Role, long AccountId, long? PartyId, AccountSide Side, decimal Amount, long? CostCenterId = null, long? JobId = null)
{
/// <summary>The debit.</summary>
public decimal Debit => Side == AccountSide.Debit ? Amount : 0m;
/// <summary>The credit.</summary>
public decimal Credit => Side == AccountSide.Credit ? Amount : 0m;
}
/// <summary>A VAT line of the entry produced, for a register of the given kind.</summary>
/// <param name="RegisterKind">Sales or purchases (a self-invoice writes one of each).</param>
/// <param name="Tax">The tax line, with the sign of the operation.</param>
public sealed record PostedVat(VatRegisterKind RegisterKind, PostingTaxInput Tax);
/// <summary>The entry of a document.</summary>
/// <param name="Lines">The lines.</param>
/// <param name="Vat">The VAT lines.</param>
public sealed record PostingResult(IReadOnlyList<PostedLine> Lines, IReadOnlyList<PostedVat> Vat)
{
/// <summary>The total debit.</summary>
public decimal Debit => Lines.Sum(l => l.Debit);
/// <summary>The total credit.</summary>
public decimal Credit => Lines.Sum(l => l.Credit);
}
/// <summary>An account a posting needs is not configured.</summary>
/// <param name="role">The role without account.</param>
public sealed class PostingAccountMissingException(PostingRole role) : Exception("No account for " + role + ".")
{
/// <summary>The role without account.</summary>
public PostingRole Role { get; } = role;
}
/// <summary>
/// The posting rules of the documents (SPEC §11.7, issue #64, ADR 0037): pure, from the amounts the documents engine
/// computed to a balanced entry.
/// <list type="bullet">
/// <item>Sale: customer debit for the total; revenues credit by account; social security and stamp duty charged to their
/// accounts; VAT on sales credit. Split payment: the VAT goes back from the customer (the public body pays it).</item>
/// <item>Purchase: supplier credit for the total; costs debit by account, with the non-deductible VAT of their code;
/// VAT on purchases debit for the deductible part; stamp duty charged by the supplier to its account.</item>
/// <item>Self-invoice: VAT on purchases debit (deductible part), its non-deductible part to the default cost, VAT on
/// sales credit; one VAT line in a sales register and one in a purchase register for each rate.</item>
/// </list>
/// A credit note reverses every side; the differences between the lines and the taxable amount of the summary (footer
/// discount, roundings) go to the largest line.
/// </summary>
public static class PostingEngine
{
/// <summary>Posts a document.</summary>
/// <param name="input">The document.</param>
/// <param name="accounts">The accounts.</param>
/// <returns>The entry.</returns>
/// <exception cref="PostingAccountMissingException">An account the document needs is missing.</exception>
public static PostingResult Post(PostingInput input, PostingAccounts accounts)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(accounts);
var lines = new List<PostedLine>();
var vat = new List<PostedVat>();
var sign = input.Reverse ? -1m : 1m;
var taxable = input.Taxes.Sum(t => t.Taxable);
var tax = input.Taxes.Sum(t => t.Tax);
var nonDeductible = input.Taxes.Sum(t => t.NonDeductibleTax);
switch (input.Kind)
{
case PostingKind.Sale:
Add(lines, PostingRole.Customer, Need(accounts.Party, PostingRole.Customer), input.PartyId, AccountSide.Debit, input.Total);
AddRevenues(lines, input, accounts, taxable, AccountSide.Credit, PostingRole.Revenue);
if (input.SocialSecurity != 0m)
{
Add(lines, PostingRole.SocialSecurity, accounts.SocialSecurity ?? Need(accounts.DefaultLine, PostingRole.SocialSecurity), null, AccountSide.Credit, input.SocialSecurity);
}
if (input.StampDuty != 0m)
{
Add(lines, PostingRole.StampDuty, Need(accounts.StampDuty, PostingRole.StampDuty), null, AccountSide.Credit, input.StampDuty);
}
Add(lines, PostingRole.SalesVat, tax == 0m ? 0 : Need(accounts.SalesVat, PostingRole.SalesVat), null, AccountSide.Credit, tax);
var split = input.Taxes.Where(t => t.Exigibility == TaxExigibility.SplitPayment).Sum(t => t.Tax);
if (split != 0m)
{
Add(lines, PostingRole.SplitPaymentVat, Need(accounts.SalesVat, PostingRole.SalesVat), null, AccountSide.Debit, split);
Add(lines, PostingRole.Customer, Need(accounts.Party, PostingRole.Customer), input.PartyId, AccountSide.Credit, split);
}
vat.AddRange(input.Taxes.Select(t => new PostedVat(VatRegisterKind.Sales, Signed(t, sign))));
break;
case PostingKind.Purchase:
Add(lines, PostingRole.Supplier, Need(accounts.Party, PostingRole.Supplier), input.PartyId, AccountSide.Credit, input.Total);
AddRevenues(lines, input, accounts, taxable, AccountSide.Debit, PostingRole.Cost);
if (input.StampDuty != 0m)
{
Add(lines, PostingRole.StampDuty, Need(accounts.StampDuty, PostingRole.StampDuty), null, AccountSide.Debit, input.StampDuty);
}
Add(lines, PostingRole.PurchaseVat, tax - nonDeductible == 0m ? 0 : Need(accounts.PurchaseVat, PostingRole.PurchaseVat), null, AccountSide.Debit, tax - nonDeductible);
vat.AddRange(input.Taxes.Select(t => new PostedVat(VatRegisterKind.Purchases, Signed(t, sign))));
break;
default:
Add(lines, PostingRole.PurchaseVat, tax - nonDeductible == 0m ? 0 : Need(accounts.PurchaseVat, PostingRole.PurchaseVat), null, AccountSide.Debit, tax - nonDeductible);
Add(lines, PostingRole.Cost, nonDeductible == 0m ? 0 : Need(accounts.DefaultLine, PostingRole.Cost), null, AccountSide.Debit, nonDeductible);
Add(lines, PostingRole.SalesVat, tax == 0m ? 0 : Need(accounts.SalesVat, PostingRole.SalesVat), null, AccountSide.Credit, tax);
vat.AddRange(input.Taxes.Select(t => new PostedVat(VatRegisterKind.Sales, Signed(t with { NonDeductibleTax = 0m }, sign))));
vat.AddRange(input.Taxes.Select(t => new PostedVat(VatRegisterKind.Purchases, Signed(t, sign))));
break;
}
// A credit note posts the other way round; a negative amount moves to the other side.
var result = lines
.Select(l => input.Reverse ? l with { Side = Other(l.Side) } : l)
.Select(l => l.Amount < 0m ? l with { Side = Other(l.Side), Amount = -l.Amount } : l)
.ToList();
return new PostingResult(result, vat);
}
// Revenues or costs by account, cost center and job; the non-deductible VAT of a purchase to the lines of its code;
// what the lines do not explain (footer discount, roundings, contributions on purchases) to the largest group.
private static void AddRevenues(List<PostedLine> lines, PostingInput input, PostingAccounts accounts, decimal taxable, AccountSide side, PostingRole role)
{
var groups = new List<(long Account, long? CostCenter, long? Job, decimal Amount, long? TaxCode)>();
foreach (var line in input.Lines.Where(l => l.Amount != 0m))
{
var account = line.AccountId ?? Need(accounts.DefaultLine, role);
var index = groups.FindIndex(g => g.Account == account && g.CostCenter == line.CostCenterId && g.Job == line.JobId && g.TaxCode == line.TaxCodeId);
if (index < 0)
{
groups.Add((account, line.CostCenterId, line.JobId, line.Amount, line.TaxCodeId));
}
else
{
groups[index] = groups[index] with { Amount = groups[index].Amount + line.Amount };
}
}
var explained = groups.Sum(g => g.Amount) + (input.Kind == PostingKind.Sale ? input.SocialSecurity : 0m);
var rest = taxable - explained;
if (input.Kind == PostingKind.Purchase)
{
foreach (var tax in input.Taxes.Where(t => t.NonDeductibleTax != 0m))
{
var index = Largest(groups, tax.TaxCodeId);
if (index < 0)
{
rest += tax.NonDeductibleTax;
}
else
{
groups[index] = groups[index] with { Amount = groups[index].Amount + tax.NonDeductibleTax };
}
}
}
if (rest != 0m)
{
var index = Largest(groups, null);
if (index < 0)
{
groups.Add((Need(accounts.DefaultLine, role), null, null, rest, null));
}
else
{
groups[index] = groups[index] with { Amount = groups[index].Amount + rest };
}
}
foreach (var group in groups)
{
Add(lines, role, group.Account, null, side, group.Amount, group.CostCenter, group.Job);
}
}
private static int Largest(List<(long Account, long? CostCenter, long? Job, decimal Amount, long? TaxCode)> groups, long? taxCode)
{
var best = -1;
for (var i = 0; i < groups.Count; i++)
{
if ((taxCode is null || groups[i].TaxCode == taxCode) && (best < 0 || Math.Abs(groups[i].Amount) > Math.Abs(groups[best].Amount)))
{
best = i;
}
}
return best;
}
private static void Add(List<PostedLine> lines, PostingRole role, long account, long? party, AccountSide side, decimal amount, long? costCenter = null, long? job = null)
{
if (amount != 0m)
{
lines.Add(new PostedLine(role, account, party, side, amount, costCenter, job));
}
}
private static long Need(long? account, PostingRole role) => account ?? throw new PostingAccountMissingException(role);
private static PostingTaxInput Signed(PostingTaxInput tax, decimal sign) =>
sign == 1m ? tax : tax with { Taxable = -tax.Taxable, Tax = -tax.Tax, NonDeductibleTax = -tax.NonDeductibleTax };
private static AccountSide Other(AccountSide side) => side == AccountSide.Debit ? AccountSide.Credit : AccountSide.Debit;
}
@@ -0,0 +1,150 @@
namespace Khaemhat.Core.Accounting;
/// <summary>The VAT of one register in a period, as the settlement reads it.</summary>
/// <param name="RegisterId">The register.</param>
/// <param name="Kind">Sales, purchases or receipts.</param>
/// <param name="Documents">The number of entries.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT of the period.</param>
/// <param name="NonDeductibleTax">The VAT on purchases that cannot be deducted by its code.</param>
/// <param name="DeferredTax">The VAT not due in the period (deferred, split payment).</param>
public sealed record VatRegisterTotals(long RegisterId, VatRegisterKind Kind, int Documents, decimal Taxable, decimal Tax, decimal NonDeductibleTax, decimal DeferredTax);
/// <summary>What the settlement needs besides the registers.</summary>
/// <param name="ProRataPercent">The share of VAT on purchases that can be deducted (pro rata), percent.</param>
/// <param name="PreviousCredit">The credit carried from the previous period.</param>
/// <param name="PreviousDebit">The debit below the minimum carried from the previous period.</param>
/// <param name="AdvancePaid">The December advance, deducted from the last period of the year.</param>
/// <param name="InterestPercent">The interest of quarterly payers, percent (zero for monthly).</param>
/// <param name="MinimumPayment">The smallest amount paid; below it the debit is carried (Italy: 25.82).</param>
public sealed record VatSettlementTerms(
decimal ProRataPercent = 100m,
decimal PreviousCredit = 0m,
decimal PreviousDebit = 0m,
decimal AdvancePaid = 0m,
decimal InterestPercent = 0m,
decimal MinimumPayment = 0m);
/// <summary>The result of a settlement.</summary>
/// <param name="SalesTax">The VAT due on sales and receipts.</param>
/// <param name="PurchaseTax">The VAT deducted on purchases, after the pro rata.</param>
/// <param name="NonDeductibleTax">The VAT on purchases not deducted (by code and by pro rata).</param>
/// <param name="DeferredTax">The VAT of the period not yet due.</param>
/// <param name="Balance">Due minus deducted, minus the credit and the advance, plus the debit carried: positive to pay.</param>
/// <param name="Interest">The interest of quarterly payers.</param>
/// <param name="AmountDue">What to pay; zero below the minimum or in credit.</param>
/// <param name="CreditCarried">The credit for the next period.</param>
/// <param name="DebitCarried">The debit below the minimum, for the next period.</param>
public sealed record VatSettlementResult(
decimal SalesTax,
decimal PurchaseTax,
decimal NonDeductibleTax,
decimal DeferredTax,
decimal Balance,
decimal Interest,
decimal AmountDue,
decimal CreditCarried,
decimal DebitCarried);
/// <summary>
/// The periodic VAT settlement (SPEC §11.7, issue #65, mockup 046): VAT due on the sales and receipts registers minus
/// the VAT deductible on the purchase registers (after the pro rata), minus the credit of the previous period and the
/// December advance, plus the debit carried; quarterly payers add the interest; below the minimum nothing is paid and
/// the debit moves to the next period.
/// </summary>
public static class VatSettlementCalculator
{
/// <summary>Computes a settlement.</summary>
/// <param name="registers">The VAT of each register in the period.</param>
/// <param name="terms">Pro rata, carried amounts, advance, interest and minimum.</param>
/// <returns>The result, rounded to the cent.</returns>
public static VatSettlementResult Compute(IReadOnlyList<VatRegisterTotals> registers, VatSettlementTerms terms)
{
ArgumentNullException.ThrowIfNull(registers);
ArgumentNullException.ThrowIfNull(terms);
var sales = registers.Where(r => r.Kind != VatRegisterKind.Purchases).Sum(r => r.Tax - r.DeferredTax);
var purchases = registers.Where(r => r.Kind == VatRegisterKind.Purchases).ToList();
var deductibleBeforeProRata = purchases.Sum(r => r.Tax - r.NonDeductibleTax - r.DeferredTax);
var deductible = ProRataCalculator.Deductible(deductibleBeforeProRata, terms.ProRataPercent);
var nonDeductible = purchases.Sum(r => r.NonDeductibleTax) + (deductibleBeforeProRata - deductible);
var deferred = registers.Sum(r => r.DeferredTax);
var balance = Round(sales - deductible - terms.PreviousCredit + terms.PreviousDebit - terms.AdvancePaid);
if (balance <= 0m)
{
return new VatSettlementResult(Round(sales), deductible, Round(nonDeductible), Round(deferred), balance, 0m, 0m, -balance, 0m);
}
var interest = Round(balance * terms.InterestPercent / 100m);
var due = balance + interest;
return due < terms.MinimumPayment
? new VatSettlementResult(Round(sales), deductible, Round(nonDeductible), Round(deferred), balance, 0m, 0m, 0m, balance)
: new VatSettlementResult(Round(sales), deductible, Round(nonDeductible), Round(deferred), balance, interest, due, 0m, 0m);
}
private static decimal Round(decimal amount) => Math.Round(amount, 2, MidpointRounding.AwayFromZero);
}
/// <summary>
/// The pro rata of deduction (art. 19-bis DPR 633/72): the share of operations that give the right to deduct over all
/// operations, rounded up to the unit; during the year the percentage of the previous year applies.
/// </summary>
public static class ProRataCalculator
{
/// <summary>The pro rata percentage of a year.</summary>
/// <param name="withRightToDeduct">Operations that give the right to deduct (taxable, non taxable).</param>
/// <param name="exempt">Exempt operations that do not (art. 10, except the occasional ones).</param>
/// <returns>The percentage, a whole number from 0 to 100; 100 without exempt operations.</returns>
public static decimal Percent(decimal withRightToDeduct, decimal exempt)
{
var total = withRightToDeduct + exempt;
if (exempt <= 0m || total <= 0m)
{
return 100m;
}
return Math.Clamp(Math.Ceiling(withRightToDeduct * 100m / total), 0m, 100m);
}
/// <summary>The VAT deductible with a pro rata.</summary>
/// <param name="tax">The VAT that would be deductible without the pro rata.</param>
/// <param name="percent">The pro rata, percent.</param>
/// <returns>The deductible VAT, rounded to the cent.</returns>
public static decimal Deductible(decimal tax, decimal percent) =>
percent >= 100m ? tax : Math.Round(tax * Math.Max(0m, percent) / 100m, 2, MidpointRounding.AwayFromZero);
}
/// <summary>How the December VAT advance is computed.</summary>
public enum VatAdvanceMethod
{
/// <summary>A share (Italy: 88%) of what was paid for the same period of the previous year.</summary>
Historical = 0,
/// <summary>A share of the VAT expected for the last period of this year.</summary>
Forecast = 1,
/// <summary>The VAT actually due for the operations up to 20 December.</summary>
Actual = 2,
}
/// <summary>The December VAT advance (acconto IVA, issue #65).</summary>
public static class VatAdvanceCalculator
{
/// <summary>The advance.</summary>
/// <param name="method">The method.</param>
/// <param name="basis">For the historical method the VAT paid for the last period of the previous year (before the
/// advance deducted then); for the forecast the VAT expected for the last period; for the actual method the VAT due up
/// to 20 December.</param>
/// <param name="percent">The share for the historical and forecast methods, percent (Italy: 88).</param>
/// <param name="minimum">Below this nothing is paid (Italy: 103.29).</param>
/// <returns>The advance, rounded to the cent; zero below the minimum.</returns>
public static decimal Compute(VatAdvanceMethod method, decimal basis, decimal percent, decimal minimum)
{
if (basis <= 0m)
{
return 0m;
}
var amount = method == VatAdvanceMethod.Actual ? basis : Math.Round(basis * percent / 100m, 2, MidpointRounding.AwayFromZero);
return amount < minimum ? 0m : amount;
}
}
+10 -1
View File
@@ -73,6 +73,9 @@ public abstract class DocumentHeader : Entity<long>, IDemoMarkable
/// <summary>The warehouse.</summary>
public long? WarehouseId { get; set; }
/// <summary>The destination warehouse of a transfer.</summary>
public long? ToWarehouseId { get; set; }
/// <summary>The warehouse reason.</summary>
public long? InventoryReasonId { get; set; }
@@ -220,9 +223,15 @@ public abstract class DocumentHeader : Entity<long>, IDemoMarkable
/// <summary>The ledger entry, once posted (M7).</summary>
public long? GlEntryId { get; set; }
/// <summary>The VAT protocol of a supplier invoice.</summary>
/// <summary>The VAT protocol of a supplier invoice: its progressive number in the purchase register of the year.</summary>
public long? VatProtocol { get; set; }
/// <summary>
/// The date the VAT of a supplier invoice counts from (competenza IVA): the registration date by default, an
/// earlier one when the invoice is received late but deducted in its period.
/// </summary>
public DateOnly? VatDate { get; set; }
/// <summary>When the document was confirmed or issued.</summary>
public DateTime? ConfirmedAt { get; set; }
+209
View File
@@ -0,0 +1,209 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Inventory;
/// <summary>
/// A posting to the stock (SPEC §11.6, ADR 0035, <c>inventory_entries</c>): the movements one confirmed document wrote.
/// Cancelling the document removes its entry; the balances are then computed again from the movements left.
/// </summary>
public sealed class InventoryEntry : Entity<long>, IDemoMarkable
{
/// <summary>The date of the movements: the date of the document.</summary>
public DateOnly EntryDate { get; set; }
/// <summary>The family of the document that posted it.</summary>
public DocumentFamily? SourceFamily { get; set; }
/// <summary>The document that posted it.</summary>
public long? SourceDocumentId { get; set; }
/// <summary>The kind of that document.</summary>
public DocumentKind? SourceKind { get; set; }
/// <summary>The number of that document, as printed.</summary>
public string? SourceNumber { get; set; }
/// <summary>The warehouse reason.</summary>
public long? InventoryReasonId { get; set; }
/// <summary>The customer or supplier of the document.</summary>
public long? PartyId { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>
/// A movement of one item in one warehouse (<c>inventory_entry_lines</c>), in the base unit of the item: positive
/// loads, negative unloads. A transfer writes two lines.
/// </summary>
public sealed class InventoryEntryLine : Entity<long>
{
/// <summary>The entry.</summary>
public long EntryId { get; set; }
/// <summary>The date, as the entry (kept here to read the history of an item without joins).</summary>
public DateOnly EntryDate { get; set; }
/// <summary>The item.</summary>
public long ItemId { get; set; }
/// <summary>The warehouse.</summary>
public long WarehouseId { get; set; }
/// <summary>The quantity in the base unit: positive for loads, negative for unloads.</summary>
public decimal Quantity { get; set; }
/// <summary>
/// The cost comes from the document (purchases, opening stock, adjustments with a cost) and moves the average; when
/// false the line is valued at the average of its moment (sales, returns, transfers).
/// </summary>
public bool Valued { get; set; }
/// <summary>The unit cost in euro.</summary>
public decimal UnitCost { get; set; }
/// <summary>The value of the movement in euro, with the sign of the quantity.</summary>
public decimal Value { get; set; }
/// <summary>The document line that wrote it.</summary>
public long? SourceLineId { get; set; }
/// <summary>The order of the lines in the entry.</summary>
public int SortOrder { get; set; }
}
/// <summary>
/// What an item has in a warehouse (<c>item_balances</c>), kept in step with the movements and the open orders:
/// on hand, committed to customers, ordered from suppliers, average cost and value.
/// </summary>
public sealed class ItemBalance : Entity<long>
{
/// <summary>The item.</summary>
public long ItemId { get; set; }
/// <summary>The warehouse.</summary>
public long WarehouseId { get; set; }
/// <summary>The quantity on hand.</summary>
public decimal OnHand { get; set; }
/// <summary>The quantity in the confirmed customer orders still to deliver.</summary>
public decimal Committed { get; set; }
/// <summary>The quantity in the confirmed supplier orders still to receive.</summary>
public decimal Ordered { get; set; }
/// <summary>The quantity sent towards this warehouse and not yet arrived (transfers are immediate: kept for later).</summary>
public decimal InTransit { get; set; }
/// <summary>The weighted average cost of the item.</summary>
public decimal AverageCost { get; set; }
/// <summary>The value of the quantity on hand at the average cost.</summary>
public decimal Value { get; set; }
/// <summary>The last purchase cost.</summary>
public decimal? LastCost { get; set; }
/// <summary>The date of the last load.</summary>
public DateOnly? LastLoadDate { get; set; }
/// <summary>The date of the last unload.</summary>
public DateOnly? LastUnloadDate { get; set; }
/// <summary>What can be promised: on hand less committed.</summary>
public decimal Available => OnHand - Committed;
}
/// <summary>The state of a physical inventory.</summary>
public enum StockTakeStatus
{
/// <summary>Counting: the quantities can be entered.</summary>
Open = 0,
/// <summary>Posted: the differences became adjustments.</summary>
Posted = 1,
/// <summary>Abandoned.</summary>
Cancelled = 2,
}
/// <summary>A physical inventory of a warehouse (SPEC §11.6, mockup 038, <c>stock_takes</c>).</summary>
public sealed class StockTake : Entity<long>, IDemoMarkable
{
/// <summary>The date the count refers to: the book quantities are those of the evening of that day.</summary>
public DateOnly TakeDate { get; set; }
/// <summary>The warehouse counted.</summary>
public long WarehouseId { get; set; }
/// <summary>A description, such as <c>Inventario di fine anno</c>.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The item category counted; every stocked item when empty.</summary>
public long? CategoryId { get; set; }
/// <summary>The state.</summary>
public StockTakeStatus Status { get; set; }
/// <summary>The warehouse entry that loads what was found more than the books, once posted.</summary>
public long? AdjustmentDocumentId { get; set; }
/// <summary>The warehouse entry that unloads what was found less than the books, once posted.</summary>
public long? LossDocumentId { get; set; }
/// <summary>When it was posted.</summary>
public DateTime? PostedAt { get; set; }
/// <summary>Who posted it.</summary>
public string? PostedBy { get; set; }
/// <summary>Notes.</summary>
public string? Notes { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>A line of a physical inventory (<c>stock_take_lines</c>).</summary>
public sealed class StockTakeLine : Entity<long>
{
/// <summary>The inventory.</summary>
public long StockTakeId { get; set; }
/// <summary>The item.</summary>
public long ItemId { get; set; }
/// <summary>The quantity the books say at the date of the count.</summary>
public decimal BookQuantity { get; set; }
/// <summary>The quantity counted; empty until counted.</summary>
public decimal? CountedQuantity { get; set; }
/// <summary>The unit cost used for the adjustment: the average cost at the date.</summary>
public decimal UnitCost { get; set; }
/// <summary>Notes of the counter.</summary>
public string? Notes { get; set; }
/// <summary>The order on the list (by item code).</summary>
public int SortOrder { get; set; }
/// <summary>The difference to adjust: counted less book, zero while not counted.</summary>
public decimal Difference => CountedQuantity is { } counted ? counted - BookQuantity : 0m;
}
/// <summary>How the stock is valued at a date (SPEC §11.6).</summary>
public enum StockValuationMethod
{
/// <summary>Weighted average cost, moved by every purchase (the one the balances keep).</summary>
WeightedAverage = 0,
/// <summary>The last purchase cost.</summary>
LastCost = 1,
/// <summary>The standard cost of the item.</summary>
StandardCost = 2,
}
@@ -0,0 +1,85 @@
namespace Khaemhat.Core.Inventory;
/// <summary>A movement of one item, in the order of the history.</summary>
/// <param name="Id">The movement.</param>
/// <param name="Date">The date.</param>
/// <param name="WarehouseId">The warehouse.</param>
/// <param name="Quantity">Positive loads, negative unloads, in the base unit.</param>
/// <param name="Valued">The cost comes from the document.</param>
/// <param name="UnitCost">The cost of a valued movement.</param>
public sealed record CostedMovement(long Id, DateOnly Date, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
/// <summary>What one warehouse holds after the history.</summary>
/// <param name="OnHand">The quantity on hand.</param>
/// <param name="LastLoad">The date of the last load.</param>
/// <param name="LastUnload">The date of the last unload.</param>
public sealed record WarehouseStock(decimal OnHand, DateOnly? LastLoad, DateOnly? LastUnload);
/// <summary>The history of an item run through the weighted average.</summary>
/// <param name="UnitCosts">The unit cost of each movement: its own when valued, the average of its moment otherwise.</param>
/// <param name="Warehouses">What each warehouse holds.</param>
/// <param name="AverageCost">The average cost at the end.</param>
/// <param name="LastCost">The cost of the last valued load.</param>
/// <param name="OnHand">The quantity on hand in every warehouse together.</param>
public sealed record CostedHistory(
IReadOnlyDictionary<long, decimal> UnitCosts, IReadOnlyDictionary<long, WarehouseStock> Warehouses, decimal AverageCost, decimal? LastCost, decimal OnHand);
/// <summary>
/// The weighted average cost of an item over its movements (SPEC §11.6, ADR 0035): every valued load (purchase,
/// opening stock, adjustment with a cost) moves the average of the item across its warehouses; every other movement is
/// valued at the average of its moment. When the stock was zero or below, the next valued load sets the average.
/// </summary>
public static class StockCostCalculator
{
/// <summary>The decimals of unit costs.</summary>
public const int CostDecimals = 4;
/// <summary>Runs the history of an item.</summary>
/// <param name="movements">The movements, in date and posting order.</param>
/// <param name="initialCost">The cost used before the first valued load (the standard cost of the item, or zero).</param>
/// <returns>The costs and the stock.</returns>
public static CostedHistory Run(IEnumerable<CostedMovement> movements, decimal initialCost = 0m)
{
ArgumentNullException.ThrowIfNull(movements);
var costs = new Dictionary<long, decimal>();
var warehouses = new Dictionary<long, WarehouseStock>();
var total = 0m;
var average = initialCost;
decimal? last = null;
foreach (var m in movements)
{
decimal cost;
if (m.Valued && m.Quantity > 0m)
{
cost = m.UnitCost;
var after = total + m.Quantity;
average = total <= 0m || after <= 0m ? cost : Math.Round(((total * average) + (m.Quantity * cost)) / after, CostDecimals, MidpointRounding.AwayFromZero);
last = cost;
}
else
{
cost = average;
}
costs[m.Id] = cost;
total += m.Quantity;
var stock = warehouses.TryGetValue(m.WarehouseId, out var s) ? s : new WarehouseStock(0m, null, null);
warehouses[m.WarehouseId] = stock with
{
OnHand = stock.OnHand + m.Quantity,
LastLoad = m.Quantity > 0m ? Later(stock.LastLoad, m.Date) : stock.LastLoad,
LastUnload = m.Quantity < 0m ? Later(stock.LastUnload, m.Date) : stock.LastUnload,
};
}
return new CostedHistory(costs, warehouses, average, last, total);
}
/// <summary>The value of a quantity at a unit cost, in euro to the cent.</summary>
/// <param name="quantity">The quantity.</param>
/// <param name="unitCost">The unit cost.</param>
/// <returns>The value.</returns>
public static decimal Value(decimal quantity, decimal unitCost) => Math.Round(quantity * unitCost, 2, MidpointRounding.AwayFromZero);
private static DateOnly Later(DateOnly? a, DateOnly b) => a is { } x && x > b ? x : b;
}
@@ -0,0 +1,122 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tables;
namespace Khaemhat.Core.Inventory;
/// <summary>A document line as the stock sees it: an item, a quantity in its base unit, a warehouse, a cost.</summary>
/// <param name="LineId">The document line.</param>
/// <param name="ItemId">The item.</param>
/// <param name="Quantity">The quantity in the base unit of the item (positive).</param>
/// <param name="WarehouseId">The warehouse of the line.</param>
/// <param name="UnitCost">The cost per base unit in euro written on the document, if any.</param>
public sealed record StockLineInput(long LineId, long ItemId, decimal Quantity, long WarehouseId, decimal? UnitCost);
/// <summary>A movement to write: one item, one warehouse, a signed quantity.</summary>
/// <param name="SourceLineId">The document line.</param>
/// <param name="ItemId">The item.</param>
/// <param name="WarehouseId">The warehouse.</param>
/// <param name="Quantity">Positive loads, negative unloads.</param>
/// <param name="Valued">The cost comes from the document and moves the average.</param>
/// <param name="UnitCost">The cost of a valued movement; zero for the others (valued at the average).</param>
public sealed record StockMovement(long? SourceLineId, long ItemId, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
/// <summary>What the warehouse reason of a document does.</summary>
/// <param name="Effect">Load, unload or nothing on the quantity.</param>
/// <param name="AffectsValue">Purchases and sales move the value; transfers and goods on approval only quantities.</param>
/// <param name="IsTransfer">A transfer between two warehouses.</param>
public sealed record StockReason(StockEffect Effect, bool AffectsValue, bool IsTransfer)
{
/// <summary>The reason of a row of <c>inventory_reasons</c>.</summary>
/// <param name="reason">The row.</param>
/// <returns>The reason.</returns>
public static StockReason Of(InventoryReason reason)
{
ArgumentNullException.ThrowIfNull(reason);
return new StockReason(reason.Effect, reason.AffectsValue, reason.IsTransfer);
}
}
/// <summary>
/// Which documents move the stock and how (SPEC §11.6, ADR 0035): the warehouse reason of the document decides load,
/// unload or transfer; the kind decides whether the reason counts at all and whether the cost on the lines is a
/// purchase cost that moves the average. Orders do not move the stock: their residuals are the committed and ordered
/// quantities.
/// </summary>
public static class StockEffectMatrix
{
private static readonly HashSet<DocumentKind> Moving =
[
DocumentKind.DeliveryNote, DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice,
DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice,
DocumentKind.PurchaseCreditNote, DocumentKind.InventoryEntry,
];
// The kinds whose costs are purchase costs: they move the average when the reason loads with value.
private static readonly HashSet<DocumentKind> Costing =
[DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice, DocumentKind.InventoryEntry];
/// <summary>Whether documents of a kind move the stock when their reason says so.</summary>
/// <param name="kind">The kind.</param>
/// <returns>Whether they do.</returns>
public static bool MovesStock(DocumentKind kind) => Moving.Contains(kind);
/// <summary>Whether the open lines of a kind are committed to customers.</summary>
/// <param name="kind">The kind.</param>
/// <returns>Whether they are.</returns>
public static bool Commits(DocumentKind kind) => kind == DocumentKind.SalesOrder;
/// <summary>Whether the open lines of a kind are ordered from suppliers.</summary>
/// <param name="kind">The kind.</param>
/// <returns>Whether they are.</returns>
public static bool Orders(DocumentKind kind) => kind == DocumentKind.PurchaseOrder;
/// <summary>Whether a document in a state still holds quantities committed or ordered.</summary>
/// <param name="status">The state.</param>
/// <returns>Whether it is open.</returns>
public static bool IsOpenOrder(DocumentStatus status) => status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled;
/// <summary>The movements of a document.</summary>
/// <param name="kind">The kind of the document.</param>
/// <param name="reason">Its warehouse reason.</param>
/// <param name="toWarehouseId">The destination of a transfer.</param>
/// <param name="lines">The stocked lines.</param>
/// <returns>The movements; none when the kind or the reason does not move the stock.</returns>
/// <exception cref="InvalidOperationException">A transfer without a destination different from the origin.</exception>
public static IReadOnlyList<StockMovement> Movements(DocumentKind kind, StockReason? reason, long? toWarehouseId, IEnumerable<StockLineInput> lines)
{
ArgumentNullException.ThrowIfNull(lines);
if (reason is null || !MovesStock(kind))
{
return [];
}
var result = new List<StockMovement>();
foreach (var line in lines.Where(l => l.Quantity != 0m))
{
if (reason.IsTransfer)
{
if (toWarehouseId is not { } to || to == line.WarehouseId)
{
throw new InvalidOperationException("A transfer needs a destination warehouse different from the origin.");
}
result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, -line.Quantity, false, 0m));
result.Add(new StockMovement(line.LineId, line.ItemId, to, line.Quantity, false, 0m));
continue;
}
switch (reason.Effect)
{
case StockEffect.Load:
var valued = reason.AffectsValue && Costing.Contains(kind) && line.UnitCost is > 0m;
result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, line.Quantity, valued, valued ? line.UnitCost!.Value : 0m));
break;
case StockEffect.Unload:
result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, -line.Quantity, false, 0m));
break;
}
}
return result;
}
}
@@ -0,0 +1,52 @@
using Khaemhat.Core.Inventory;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.CompanyDatabase;
/// <summary>Map of <see cref="InventoryEntry"/> to <c>inventory_entries</c>.</summary>
public sealed class InventoryEntryMap : EntityMap<InventoryEntry>
{
/// <summary>Creates the map.</summary>
public InventoryEntryMap()
{
ToTable("inventory_entries");
Map(x => x.SourceNumber).MaxLength(30);
}
}
/// <summary>Map of <see cref="InventoryEntryLine"/> to <c>inventory_entry_lines</c>.</summary>
public sealed class InventoryEntryLineMap : EntityMap<InventoryEntryLine>
{
/// <summary>Creates the map.</summary>
public InventoryEntryLineMap() => ToTable("inventory_entry_lines");
}
/// <summary>Map of <see cref="ItemBalance"/> to <c>item_balances</c>.</summary>
public sealed class ItemBalanceMap : EntityMap<ItemBalance>
{
/// <summary>Creates the map.</summary>
public ItemBalanceMap() => ToTable("item_balances");
}
/// <summary>Map of <see cref="StockTake"/> to <c>stock_takes</c>.</summary>
public sealed class StockTakeMap : EntityMap<StockTake>
{
/// <summary>Creates the map.</summary>
public StockTakeMap()
{
ToTable("stock_takes");
Map(x => x.Description).MaxLength(100);
Map(x => x.PostedBy).MaxLength(100);
}
}
/// <summary>Map of <see cref="StockTakeLine"/> to <c>stock_take_lines</c>.</summary>
public sealed class StockTakeLineMap : EntityMap<StockTakeLine>
{
/// <summary>Creates the map.</summary>
public StockTakeLineMap()
{
ToTable("stock_take_lines");
Map(x => x.Notes).MaxLength(200);
}
}
@@ -0,0 +1,172 @@
using Khaemhat.Core.Accounting;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.CompanyDatabase;
/// <summary>Map of <see cref="GlAccount"/> to <c>gl_accounts</c>.</summary>
public sealed class GlAccountMap : EntityMap<GlAccount>
{
/// <summary>Creates the map.</summary>
public GlAccountMap()
{
ToTable("gl_accounts");
Map(x => x.Code).MaxLength(20);
Map(x => x.Description).MaxLength(100);
Map(x => x.StatementLine).MaxLength(20);
Map(x => x.Reclassification).MaxLength(20);
}
}
/// <summary>Map of <see cref="VatRegister"/> to <c>vat_registers</c>.</summary>
public sealed class VatRegisterMap : EntityMap<VatRegister>
{
/// <summary>Creates the map.</summary>
public VatRegisterMap()
{
ToTable("vat_registers");
Map(x => x.Code).MaxLength(10);
Map(x => x.Description).MaxLength(100);
}
}
/// <summary>Map of <see cref="JournalTemplate"/> to <c>gl_journal_templates</c>.</summary>
public sealed class JournalTemplateMap : EntityMap<JournalTemplate>
{
/// <summary>Creates the map.</summary>
public JournalTemplateMap()
{
ToTable("gl_journal_templates");
Map(x => x.Code).MaxLength(10);
Map(x => x.Description).MaxLength(100);
Map(x => x.VatRegisterCode).MaxLength(10);
}
}
/// <summary>Map of <see cref="JournalTemplateLine"/> to <c>gl_journal_template_lines</c>.</summary>
public sealed class JournalTemplateLineMap : EntityMap<JournalTemplateLine>
{
/// <summary>Creates the map.</summary>
public JournalTemplateLineMap()
{
ToTable("gl_journal_template_lines");
Map(x => x.Description).MaxLength(100);
}
}
/// <summary>Map of <see cref="GlEntry"/> to <c>gl_entries</c>.</summary>
public sealed class GlEntryMap : EntityMap<GlEntry>
{
/// <summary>Creates the map.</summary>
public GlEntryMap()
{
ToTable("gl_entries");
Map(x => x.EntryNumber).MaxLength(20);
Map(x => x.TemplateCode).MaxLength(10);
Map(x => x.Description).MaxLength(200);
Map(x => x.DocumentNumber).MaxLength(30);
Map(x => x.FinalizedBy).MaxLength(100);
Map(x => x.Notes).MaxLength(500);
}
}
/// <summary>Map of <see cref="GlEntryLine"/> to <c>gl_entry_lines</c>.</summary>
public sealed class GlEntryLineMap : EntityMap<GlEntryLine>
{
/// <summary>Creates the map.</summary>
public GlEntryLineMap()
{
ToTable("gl_entry_lines");
Map(x => x.Description).MaxLength(200);
}
}
/// <summary>Map of <see cref="GlEntryVat"/> to <c>gl_entry_vat</c>.</summary>
public sealed class GlEntryVatMap : EntityMap<GlEntryVat>
{
/// <summary>Creates the map.</summary>
public GlEntryVatMap()
{
ToTable("gl_entry_vat");
Map(x => x.Nature).MaxLength(10);
}
}
/// <summary>Map of <see cref="OpenItem"/> to <c>gl_open_items</c>.</summary>
public sealed class OpenItemMap : EntityMap<OpenItem>
{
/// <summary>Creates the map.</summary>
public OpenItemMap()
{
ToTable("gl_open_items");
Map(x => x.DocumentNumber).MaxLength(30);
}
}
/// <summary>Map of <see cref="RecurringEntry"/> to <c>gl_recurring_entries</c>.</summary>
public sealed class RecurringEntryMap : EntityMap<RecurringEntry>
{
/// <summary>Creates the map.</summary>
public RecurringEntryMap()
{
ToTable("gl_recurring_entries");
Map(x => x.Description).MaxLength(200);
}
}
/// <summary>Map of <see cref="VatSettlement"/> to <c>vat_settlements</c>.</summary>
public sealed class VatSettlementMap : EntityMap<VatSettlement>
{
/// <summary>Creates the map.</summary>
public VatSettlementMap()
{
ToTable("vat_settlements");
Map(x => x.PaymentCode).MaxLength(10);
Map(x => x.ConfirmedBy).MaxLength(100);
}
}
/// <summary>Map of <see cref="VatSettlementLine"/> to <c>vat_settlement_lines</c>.</summary>
public sealed class VatSettlementLineMap : EntityMap<VatSettlementLine>
{
/// <summary>Creates the map.</summary>
public VatSettlementLineMap() => ToTable("vat_settlement_lines");
}
/// <summary>Map of <see cref="TaxPayment"/> to <c>tax_payments</c>.</summary>
public sealed class TaxPaymentMap : EntityMap<TaxPayment>
{
/// <summary>Creates the map.</summary>
public TaxPaymentMap()
{
ToTable("tax_payments");
Map(x => x.PaymentCode).MaxLength(10);
Map(x => x.ReferencePeriod).MaxLength(10);
Map(x => x.Description).MaxLength(200);
}
}
/// <summary>Map of <see cref="Withholding"/> to <c>withholdings</c>.</summary>
public sealed class WithholdingMap : EntityMap<Withholding>
{
/// <summary>Creates the map.</summary>
public WithholdingMap()
{
ToTable("withholdings");
Map(x => x.DocumentNumber).MaxLength(30);
Map(x => x.WithholdingType).MaxLength(10);
Map(x => x.Reason).MaxLength(10);
Map(x => x.SocialSecurityFund).MaxLength(10);
Map(x => x.PaymentCode).MaxLength(10);
}
}
/// <summary>Map of <see cref="VatRegisterPrint"/> to <c>vat_register_prints</c>.</summary>
public sealed class VatRegisterPrintMap : EntityMap<VatRegisterPrint>
{
/// <summary>Creates the map.</summary>
public VatRegisterPrintMap()
{
ToTable("vat_register_prints");
Map(x => x.PrintedBy).MaxLength(100);
}
}
@@ -0,0 +1,136 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>
/// The warehouse (SPEC §11.6, ADR 0035, issues #59 and #60): the movements posted by the documents, the balance of
/// each item in each warehouse, the physical inventories; on the documents the destination of a transfer and the VAT
/// date of a supplier invoice (#56). Immediate invoices unload, supplier invoices load and supplier credit notes give
/// back, like the delivery notes: the reason of the document type decides it and can be removed.
/// </summary>
[Migration(20261113_001, "create_inventory")]
public sealed class M20261113_001_CreateInventory : IMigration
{
private static readonly string[] Headers =
["sale_quotations", "sale_orders", "sale_documents", "purchase_orders", "purchase_documents", "inventory_documents"];
// The reasons given to the document types of the base tables that had none (ItalianBaseTables has them from now on).
private static readonly (string Type, string Reason)[] Reasons = [("FI", "SCA"), ("FF", "CAR"), ("NCF", "RESF")];
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
foreach (var table in Headers)
{
schema.AlterTable(table, t =>
{
t.Int64("to_warehouse_id");
t.Date("vat_date");
});
}
foreach (var (type, reason) in Reasons)
{
schema.Sql(_ => "UPDATE document_types SET inventory_reason_id = (SELECT r.id FROM inventory_reasons r WHERE r.code = '" + reason
+ "') WHERE code = '" + type + "' AND inventory_reason_id IS NULL");
}
schema.CreateTable("inventory_entries", t =>
{
t.Id();
t.Date("entry_date").NotNull();
t.String("source_family", 40);
t.Int64("source_document_id");
t.String("source_kind", 40);
t.String("source_number", 30);
t.Int64("inventory_reason_id");
t.Int64("party_id");
t.DemoColumn();
t.AuditColumns();
t.Index("ix_inventory_entries_source", "source_family", "source_document_id");
t.Index("ix_inventory_entries_date", "entry_date");
t.ForeignKey("fk_inventory_entries_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict);
});
schema.CreateTable("inventory_entry_lines", t =>
{
t.Id();
t.Int64("entry_id").NotNull();
t.Date("entry_date").NotNull();
t.Int64("item_id").NotNull();
t.Int64("warehouse_id").NotNull();
t.Decimal("quantity").NotNull();
t.Bool("valued").NotNull().Default(false);
t.Decimal("unit_cost").NotNull().Default(0m);
t.Decimal("value").NotNull().Default(0m);
t.Int64("source_line_id");
t.Int32("sort_order").NotNull().Default(0);
t.AuditColumns();
t.Index("ix_inventory_entry_lines_entry", "entry_id");
t.Index("ix_inventory_entry_lines_item", "item_id", "entry_date");
t.Index("ix_inventory_entry_lines_warehouse", "warehouse_id", "item_id");
t.ForeignKey("fk_inventory_entry_lines_entry", "entry_id", "inventory_entries", ReferentialAction.Cascade);
t.ForeignKey("fk_inventory_entry_lines_item", "item_id", "items", ReferentialAction.Restrict);
t.ForeignKey("fk_inventory_entry_lines_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
});
schema.CreateTable("item_balances", t =>
{
t.Id();
t.Int64("item_id").NotNull();
t.Int64("warehouse_id").NotNull();
t.Decimal("on_hand").NotNull().Default(0m);
t.Decimal("committed").NotNull().Default(0m);
t.Decimal("ordered").NotNull().Default(0m);
t.Decimal("in_transit").NotNull().Default(0m);
t.Decimal("average_cost").NotNull().Default(0m);
t.Decimal("value").NotNull().Default(0m);
t.Decimal("last_cost");
t.Date("last_load_date");
t.Date("last_unload_date");
t.AuditColumns();
t.Unique("ux_item_balances_item_warehouse", "item_id", "warehouse_id");
t.Index("ix_item_balances_warehouse", "warehouse_id");
t.ForeignKey("fk_item_balances_item", "item_id", "items", ReferentialAction.Cascade);
t.ForeignKey("fk_item_balances_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
});
schema.CreateTable("stock_takes", t =>
{
t.Id();
t.Date("take_date").NotNull();
t.Int64("warehouse_id").NotNull();
t.String("description", 100).NotNull();
t.Int64("category_id");
t.String("status", 40).NotNull();
t.Int64("adjustment_document_id");
t.Int64("loss_document_id");
t.DateTimeUtc("posted_at");
t.String("posted_by", 100);
t.Text("notes");
t.DemoColumn();
t.AuditColumns();
t.Index("ix_stock_takes_date", "take_date");
t.ForeignKey("fk_stock_takes_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
t.ForeignKey("fk_stock_takes_category", "category_id", "item_categories", ReferentialAction.Restrict);
});
schema.CreateTable("stock_take_lines", t =>
{
t.Id();
t.Int64("stock_take_id").NotNull();
t.Int64("item_id").NotNull();
t.Decimal("book_quantity").NotNull().Default(0m);
t.Decimal("counted_quantity");
t.Decimal("unit_cost").NotNull().Default(0m);
t.String("notes", 200);
t.Int32("sort_order").NotNull().Default(0);
t.AuditColumns();
t.Unique("ux_stock_take_lines_item", "stock_take_id", "item_id");
t.ForeignKey("fk_stock_take_lines_take", "stock_take_id", "stock_takes", ReferentialAction.Cascade);
t.ForeignKey("fk_stock_take_lines_item", "item_id", "items", ReferentialAction.Restrict);
});
}
}
@@ -0,0 +1,338 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>
/// The general ledger (SPEC §11.7, ADR 0036 and 0037, issues #62-#67): chart of accounts, VAT registers, journal
/// templates, entries with their lines and VAT lines, open items, recurring entries, VAT settlements, tax payments (F24
/// lines), withholdings and the final prints of the VAT registers. The lines keep the date and the state of their entry,
/// so balances, ledgers and registers read one table with an index.
/// </summary>
[Migration(20261113_002, "create_ledger")]
public sealed class M20261113_002_CreateLedger : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.CreateTable("gl_accounts", t =>
{
t.Id();
t.String("code", 20).NotNull();
t.String("description", 100).NotNull();
t.Bool("disabled").NotNull().Default(false);
t.Int32("level").NotNull().Default(1);
t.Int64("parent_id");
t.String("nature", 40).NotNull();
t.String("type", 40).NotNull();
t.String("statement_line", 20);
t.String("reclassification", 20);
t.Bool("sub_ledger").NotNull().Default(false);
t.Bool("vat_relevant").NotNull().Default(false);
t.Bool("closes_automatically").NotNull().Default(true);
t.Bool("postable").NotNull().Default(false);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_gl_accounts_code", "code");
t.Index("ix_gl_accounts_parent", "parent_id");
t.ForeignKey("fk_gl_accounts_parent", "parent_id", "gl_accounts", ReferentialAction.Restrict);
});
schema.CreateTable("vat_registers", t =>
{
t.Id();
t.String("code", 10).NotNull();
t.String("description", 100).NotNull();
t.Bool("disabled").NotNull().Default(false);
t.String("kind", 40).NotNull();
t.Bool("reverse_charge").NotNull().Default(false);
t.Int32("print_year");
t.Int32("last_page").NotNull().Default(0);
t.Date("last_printed_date");
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_vat_registers_code", "code");
});
schema.CreateTable("gl_journal_templates", t =>
{
t.Id();
t.String("code", 10).NotNull();
t.String("description", 100).NotNull();
t.Bool("disabled").NotNull().Default(false);
t.String("area", 40).NotNull();
t.String("vat_register_code", 10);
t.Bool("opens_items").NotNull().Default(false);
t.Bool("reverses").NotNull().Default(false);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_gl_journal_templates_code", "code");
});
schema.CreateTable("gl_journal_template_lines", t =>
{
t.Id();
t.Int64("journal_template_id").NotNull();
t.Int32("sort_order").NotNull().Default(0);
t.String("role", 40).NotNull();
t.String("side", 40).NotNull();
t.Int64("account_id");
t.String("description", 100);
t.AuditColumns();
t.Index("ix_gl_journal_template_lines_template", "journal_template_id");
t.ForeignKey("fk_gl_journal_template_lines_template", "journal_template_id", "gl_journal_templates", ReferentialAction.Cascade);
t.ForeignKey("fk_gl_journal_template_lines_account", "account_id", "gl_accounts", ReferentialAction.Restrict);
});
schema.CreateTable("gl_entries", t =>
{
t.Id();
t.Int32("year").NotNull();
t.Int64("number");
t.String("entry_number", 20);
t.Int64("journal_number");
t.Date("entry_date").NotNull();
t.Date("competence_date");
t.Int64("journal_template_id");
t.String("template_code", 10);
t.String("description", 200).NotNull();
t.String("status", 40).NotNull();
t.String("source", 40).NotNull();
t.String("source_family", 40);
t.Int64("source_document_id");
t.String("source_kind", 40);
t.String("document_number", 30);
t.Date("document_date");
t.Int64("party_id");
t.Int64("vat_register_id");
t.Int64("vat_protocol");
t.Date("vat_date");
t.Int64("reversal_of_id");
t.Int64("reversed_by_id");
t.Decimal("total_debit").NotNull().Default(0m);
t.Decimal("total_credit").NotNull().Default(0m);
t.DateTimeUtc("finalized_at");
t.String("finalized_by", 100);
t.String("notes", 500);
t.DemoColumn();
t.AuditColumns();
t.Index("ix_gl_entries_date", "entry_date", "number");
t.Unique("ux_gl_entries_number", "year", "number");
t.Index("ix_gl_entries_source", "source_family", "source_document_id");
t.Index("ix_gl_entries_status", "status", "entry_date");
t.Index("ix_gl_entries_register", "vat_register_id", "vat_date");
t.ForeignKey("fk_gl_entries_template", "journal_template_id", "gl_journal_templates", ReferentialAction.Restrict);
t.ForeignKey("fk_gl_entries_register", "vat_register_id", "vat_registers", ReferentialAction.Restrict);
t.ForeignKey("fk_gl_entries_party", "party_id", "parties", ReferentialAction.Restrict);
});
schema.CreateTable("gl_open_items", t =>
{
t.Id();
t.String("direction", 40).NotNull();
t.Int64("party_id").NotNull();
t.Int64("account_id").NotNull();
t.Int64("entry_id").NotNull();
t.String("source_family", 40);
t.Int64("source_document_id");
t.String("document_number", 30);
t.Date("document_date").NotNull();
t.Int32("installment").NotNull().Default(1);
t.Date("due_date").NotNull();
t.Decimal("amount").NotNull().Default(0m);
t.Decimal("paid_amount").NotNull().Default(0m);
t.Int64("payment_method_id");
t.Bool("closed").NotNull().Default(false);
t.DemoColumn();
t.AuditColumns();
t.Index("ix_gl_open_items_party", "party_id", "closed", "due_date");
t.Index("ix_gl_open_items_due", "closed", "due_date");
t.Index("ix_gl_open_items_entry", "entry_id");
t.ForeignKey("fk_gl_open_items_entry", "entry_id", "gl_entries", ReferentialAction.Cascade);
t.ForeignKey("fk_gl_open_items_party", "party_id", "parties", ReferentialAction.Restrict);
t.ForeignKey("fk_gl_open_items_account", "account_id", "gl_accounts", ReferentialAction.Restrict);
});
schema.CreateTable("gl_entry_lines", t =>
{
t.Id();
t.Int64("entry_id").NotNull();
t.Int32("line_number").NotNull();
t.Date("entry_date").NotNull();
t.String("status", 40).NotNull();
t.Int64("account_id").NotNull();
t.Int64("party_id");
t.String("description", 200);
t.Decimal("debit").NotNull().Default(0m);
t.Decimal("credit").NotNull().Default(0m);
t.Int64("cost_center_id");
t.Int64("job_id");
t.Int64("open_item_id");
t.AuditColumns();
t.Index("ix_gl_entry_lines_entry", "entry_id");
t.Index("ix_gl_entry_lines_account", "account_id", "entry_date");
t.Index("ix_gl_entry_lines_party", "party_id", "account_id", "entry_date");
t.Index("ix_gl_entry_lines_cost_center", "cost_center_id", "entry_date");
t.ForeignKey("fk_gl_entry_lines_entry", "entry_id", "gl_entries", ReferentialAction.Cascade);
t.ForeignKey("fk_gl_entry_lines_account", "account_id", "gl_accounts", ReferentialAction.Restrict);
t.ForeignKey("fk_gl_entry_lines_party", "party_id", "parties", ReferentialAction.Restrict);
});
schema.CreateTable("gl_entry_vat", t =>
{
t.Id();
t.Int64("entry_id").NotNull();
t.Int32("line_number").NotNull();
t.Int64("vat_register_id").NotNull();
t.String("register_kind", 40).NotNull();
t.Date("vat_date").NotNull();
t.String("status", 40).NotNull();
t.Int64("tax_code_id");
t.Decimal("rate").NotNull().Default(0m);
t.String("nature", 10);
t.String("exigibility", 40).NotNull();
t.Decimal("taxable").NotNull().Default(0m);
t.Decimal("tax").NotNull().Default(0m);
t.Decimal("non_deductible_tax").NotNull().Default(0m);
t.AuditColumns();
t.Index("ix_gl_entry_vat_entry", "entry_id");
t.Index("ix_gl_entry_vat_register", "vat_register_id", "vat_date");
t.ForeignKey("fk_gl_entry_vat_entry", "entry_id", "gl_entries", ReferentialAction.Cascade);
t.ForeignKey("fk_gl_entry_vat_register", "vat_register_id", "vat_registers", ReferentialAction.Restrict);
});
schema.CreateTable("gl_recurring_entries", t =>
{
t.Id();
t.String("description", 200).NotNull();
t.Int64("model_entry_id").NotNull();
t.String("frequency", 40).NotNull();
t.Date("next_date").NotNull();
t.Date("end_date");
t.Int64("last_entry_id");
t.Bool("disabled").NotNull().Default(false);
t.DemoColumn();
t.AuditColumns();
t.Index("ix_gl_recurring_entries_next", "disabled", "next_date");
t.ForeignKey("fk_gl_recurring_entries_model", "model_entry_id", "gl_entries", ReferentialAction.Restrict);
});
schema.CreateTable("vat_settlements", t =>
{
t.Id();
t.Int32("year").NotNull();
t.Int32("number").NotNull();
t.String("periodicity", 40).NotNull();
t.Date("start_date").NotNull();
t.Date("end_date").NotNull();
t.Date("settlement_date").NotNull();
t.String("status", 40).NotNull();
t.Decimal("sales_tax").NotNull().Default(0m);
t.Decimal("purchase_tax").NotNull().Default(0m);
t.Decimal("non_deductible_tax").NotNull().Default(0m);
t.Decimal("deferred_tax").NotNull().Default(0m);
t.Decimal("pro_rata_percent").NotNull().Default(100m);
t.Decimal("previous_credit").NotNull().Default(0m);
t.Decimal("previous_debit").NotNull().Default(0m);
t.Decimal("advance_paid").NotNull().Default(0m);
t.Decimal("interest_percent").NotNull().Default(0m);
t.Decimal("interest").NotNull().Default(0m);
t.Decimal("amount_due").NotNull().Default(0m);
t.Decimal("credit_carried").NotNull().Default(0m);
t.Decimal("debit_carried").NotNull().Default(0m);
t.String("payment_code", 10);
t.Date("due_date");
t.Int64("gl_entry_id");
t.Int64("tax_payment_id");
t.DateTimeUtc("confirmed_at");
t.String("confirmed_by", 100);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_vat_settlements_period", "year", "periodicity", "number");
});
schema.CreateTable("vat_settlement_lines", t =>
{
t.Id();
t.Int64("settlement_id").NotNull();
t.Int64("vat_register_id").NotNull();
t.String("register_kind", 40).NotNull();
t.Int32("documents").NotNull().Default(0);
t.Decimal("taxable").NotNull().Default(0m);
t.Decimal("tax").NotNull().Default(0m);
t.Decimal("non_deductible_tax").NotNull().Default(0m);
t.Decimal("deferred_tax").NotNull().Default(0m);
t.AuditColumns();
t.Index("ix_vat_settlement_lines_settlement", "settlement_id");
t.ForeignKey("fk_vat_settlement_lines_settlement", "settlement_id", "vat_settlements", ReferentialAction.Cascade);
t.ForeignKey("fk_vat_settlement_lines_register", "vat_register_id", "vat_registers", ReferentialAction.Restrict);
});
schema.CreateTable("tax_payments", t =>
{
t.Id();
t.Date("due_date").NotNull();
t.String("payment_code", 10).NotNull();
t.Int32("reference_year").NotNull();
t.String("reference_period", 10);
t.String("description", 200).NotNull();
t.Decimal("amount").NotNull().Default(0m);
t.String("source", 40).NotNull();
t.Int64("source_id");
t.Date("paid_on");
t.Int64("bank_account_id");
t.Int64("gl_entry_id");
t.DemoColumn();
t.AuditColumns();
t.Index("ix_tax_payments_due", "due_date");
t.Index("ix_tax_payments_source", "source", "source_id");
});
schema.CreateTable("withholdings", t =>
{
t.Id();
t.String("direction", 40).NotNull();
t.String("source_family", 40).NotNull();
t.Int64("source_document_id").NotNull();
t.String("document_number", 30);
t.Date("document_date").NotNull();
t.Int64("party_id").NotNull();
t.String("withholding_type", 10);
t.String("reason", 10);
t.Decimal("taxable").NotNull().Default(0m);
t.String("social_security_fund", 10);
t.Decimal("social_security_amount").NotNull().Default(0m);
t.Decimal("rate").NotNull().Default(0m);
t.Decimal("base_percent").NotNull().Default(100m);
t.Decimal("amount").NotNull().Default(0m);
t.String("payment_code", 10);
t.Date("invoice_paid_on");
t.String("status", 40).NotNull();
t.Int64("tax_payment_id");
t.Int64("gl_entry_id");
t.DemoColumn();
t.AuditColumns();
t.Index("ix_withholdings_source", "source_family", "source_document_id");
t.Index("ix_withholdings_status", "direction", "status", "invoice_paid_on");
t.ForeignKey("fk_withholdings_party", "party_id", "parties", ReferentialAction.Restrict);
});
schema.CreateTable("vat_register_prints", t =>
{
t.Id();
t.Int64("vat_register_id").NotNull();
t.Int32("year").NotNull();
t.Date("from_date").NotNull();
t.Date("to_date").NotNull();
t.Int32("first_page").NotNull();
t.Int32("last_page").NotNull();
t.Int64("attachment_id");
t.DateTimeUtc("printed_at").NotNull();
t.String("printed_by", 100);
t.AuditColumns();
t.Index("ix_vat_register_prints_register", "vat_register_id", "year");
t.ForeignKey("fk_vat_register_prints_register", "vat_register_id", "vat_registers", ReferentialAction.Cascade);
});
}
}
+52 -20
View File
@@ -1,4 +1,3 @@
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tax;
namespace Khaemhat.Fiscal.Abstractions;
@@ -96,7 +95,7 @@ public interface IFixedAssetRules
/// <param name="Description">What it pays.</param>
public sealed record TaxPaymentCode(string Code, string Description);
/// <summary>The country's tax payment form (Italy: F24); the file export arrives with the VAT settlement (M7).</summary>
/// <summary>The country's tax payment form (Italy: F24): the payment codes and the data of a form.</summary>
public interface ITaxPaymentFormExporter
{
/// <summary>The name of the form, such as <c>F24</c>.</summary>
@@ -119,6 +118,19 @@ public interface ITaxPaymentFormExporter
/// <param name="quarter">The quarter, 1-4.</param>
/// <returns>The payment code.</returns>
string StampDutyCode(int quarter);
/// <summary>The name proposed for the data file of a form.</summary>
/// <param name="form">The form.</param>
/// <returns>The file name.</returns>
string FileName(TaxPaymentForm form);
/// <summary>
/// The data of a form for the intermediary or the home banking: one line per payment code, in the order and with the
/// fields of the form (ADR 0037: the telematic layout of the intermediaries is not produced).
/// </summary>
/// <param name="form">The form.</param>
/// <returns>The file, UTF-8.</returns>
byte[] Export(TaxPaymentForm form);
}
/// <summary>Which statement a schema line belongs to.</summary>
@@ -147,24 +159,6 @@ public interface IFinancialStatementsSchema
IReadOnlyList<FinancialStatementLine> Lines(FinancialStatementKind kind);
}
/// <summary>An account of the country's model chart of accounts.</summary>
/// <param name="Code">The hierarchical code, such as <c>01.01.001</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="ParentCode">The parent account, if any.</param>
/// <param name="Nature">The statement it ends up in.</param>
/// <param name="StatementLine">The financial statement line it maps to, if any.</param>
public sealed record AccountTemplate(string Code, string Description, string? ParentCode, AccountNature Nature, string? StatementLine);
/// <summary>The model chart of accounts loaded into a new company (arrives with the ledger, M7).</summary>
public interface IChartOfAccountsTemplate
{
/// <summary>The name of the model, such as <c>PMI standard</c>.</summary>
string Name { get; }
/// <summary>The accounts, parents before children.</summary>
IReadOnlyList<AccountTemplate> Accounts { get; }
}
/// <summary>A line of an Intrastat return.</summary>
/// <param name="CountryCode">The country of the counterparty.</param>
/// <param name="VatNumber">The VAT number of the counterparty, without country prefix.</param>
@@ -273,3 +267,41 @@ public interface IPlaceDirectory
/// <summary>The municipalities.</summary>
IReadOnlyList<MunicipalityTemplate> Municipalities { get; }
}
/// <summary>What a received invoice tells about the self-invoice it may need.</summary>
/// <param name="SupplierCountry">The country of the supplier (ISO 3166-1 alpha-2).</param>
/// <param name="SupplierInEu">The supplier is in another member state of the European Union.</param>
/// <param name="Goods">The invoice is mostly for goods (otherwise services).</param>
/// <param name="Natures">The VAT natures of its lines (codes of the country's e-invoice format), if any.</param>
/// <param name="Received">The day it was received or registered.</param>
public sealed record SelfInvoiceCase(string SupplierCountry, bool SupplierInEu, bool Goods, IReadOnlyCollection<string> Natures, DateOnly Received);
/// <summary>The self-invoice a received invoice needs.</summary>
/// <param name="DocumentTypeCode">The document type of the base tables, such as <c>AF17</c>.</param>
/// <param name="Reason">Why, in the language of the users.</param>
/// <param name="Deadline">The last day to issue it.</param>
public sealed record SelfInvoiceAdvice(string DocumentTypeCode, string Reason, DateOnly Deadline);
/// <summary>
/// The country's rules of self-invoices and integrations (Italy: TD16-TD29 under reverse charge, purchases from abroad,
/// regularisations): which type a received invoice needs, by when, and the VAT code that integrates it.
/// </summary>
public interface ISelfInvoiceRules
{
/// <summary>The document types of self-invoices, in the order of the menu.</summary>
IReadOnlyList<string> DocumentTypeCodes { get; }
/// <summary>The VAT code (of the base tables) of the ordinary rate, proposed on the lines of an integration.</summary>
string OrdinaryTaxCode { get; }
/// <summary>The self-invoice a received invoice needs, if any.</summary>
/// <param name="input">The invoice.</param>
/// <returns>The advice, or <see langword="null"/> when none is needed.</returns>
SelfInvoiceAdvice? Advise(SelfInvoiceCase input);
/// <summary>The last day to issue a self-invoice of a type for an invoice received on a day.</summary>
/// <param name="documentTypeCode">The type.</param>
/// <param name="received">The day the invoice was received (or the operation took place).</param>
/// <returns>The deadline.</returns>
DateOnly Deadline(string documentTypeCode, DateOnly received);
}
@@ -0,0 +1,281 @@
namespace Khaemhat.Fiscal.Abstractions;
// The supplier invoices received as files of the country's e-invoice format (Italy: FatturaPA, also signed .p7m).
// The records keep the file as it is, with the codes of the format; the import service maps them to documents.
/// <summary>
/// Reads the e-invoice files received from suppliers: an optional feature of a country pack, like
/// <see cref="IEInvoiceFormat"/>. The reader only reads: it never contacts a service and never resolves external
/// references.
/// </summary>
public interface IIncomingInvoiceReader
{
/// <summary>
/// Whether the file looks like one the reader understands (Italy: <c>.xml</c>, <c>.p7m</c> in DER or as base64
/// text). The content is sniffed, not only the name.
/// </summary>
/// <param name="fileName">The name of the file, extension included.</param>
/// <param name="content">The content, or at least its first bytes.</param>
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
bool CanRead(string fileName, ReadOnlySpan<byte> content);
/// <summary>Reads a file.</summary>
/// <param name="fileName">The name of the file, extension included.</param>
/// <param name="content">The whole content.</param>
/// <returns>The file with its invoices.</returns>
/// <exception cref="IncomingInvoiceException">The file is not readable, not an invoice, or misses mandatory data;
/// <see cref="IncomingInvoiceException.Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</exception>
IncomingInvoiceFile Read(string fileName, byte[] content);
}
/// <summary>A received e-invoice file that cannot be read; <see cref="Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</summary>
public sealed class IncomingInvoiceException : Exception
{
/// <summary>Creates the exception.</summary>
public IncomingInvoiceException()
: this(IncomingInvoiceErrors.NotReadable, "The file is not readable.")
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public IncomingInvoiceException(string message)
: this(IncomingInvoiceErrors.NotReadable, message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public IncomingInvoiceException(string message, Exception innerException)
: this(IncomingInvoiceErrors.NotReadable, message, innerException)
{
}
/// <summary>Creates the exception with a code.</summary>
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
/// <param name="message">What went wrong.</param>
public IncomingInvoiceException(string code, string message)
: base(message) => Code = code;
/// <summary>Creates the exception with a code and its cause.</summary>
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public IncomingInvoiceException(string code, string message, Exception? innerException)
: base(message, innerException) => Code = code;
/// <summary>The text code of the error, one of <see cref="IncomingInvoiceErrors"/>.</summary>
public string Code { get; }
}
/// <summary>The codes of <see cref="IncomingInvoiceException"/>.</summary>
public static class IncomingInvoiceErrors
{
/// <summary>Neither XML nor a signed envelope: garbage, an empty file, a truncated download.</summary>
public const string NotReadable = "incoming.not-readable";
/// <summary>A well-formed XML document that is not an e-invoice.</summary>
public const string NotInvoice = "incoming.not-invoice";
/// <summary>A signed envelope whose content cannot be extracted.</summary>
public const string SignatureBroken = "incoming.signature-broken";
/// <summary>An e-invoice that misses mandatory data (date, number, document type...).</summary>
public const string Invalid = "incoming.invalid";
}
/// <summary>A received 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.</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 IncomingInvoiceFile(
string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
IncomingParty Supplier, IncomingParty Customer, IReadOnlyList<IncomingInvoice> Invoices,
IncomingSignature? Signature, byte[] Xml);
/// <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 IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
/// <summary>A party of the invoice (supplier or customer) 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 IncomingParty(
string? CountryCode, string? VatNumber, string? TaxCode, string? Name, string? FirstName, string? LastName,
string? Address, string? StreetNumber, string? PostalCode, string? City, string? Province, string? Country,
string? TaxRegime, string? Email, string? Phone, string? ReaOffice, string? ReaNumber)
{
/// <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>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 IncomingInvoice(
string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
IReadOnlyList<string> Causals, bool Art73,
IReadOnlyList<IncomingWithholding> Withholdings, IncomingStampDuty? StampDuty,
IReadOnlyList<IncomingSocialSecurity> SocialSecurity, IReadOnlyList<IncomingDiscount> Discounts,
IReadOnlyList<IncomingReference> Orders, IReadOnlyList<IncomingReference> Contracts,
IReadOnlyList<IncomingReference> RelatedInvoices, IReadOnlyList<IncomingReference> DeliveryNotes,
IReadOnlyList<IncomingLine> Lines, IReadOnlyList<IncomingTaxSummary> TaxSummary,
IReadOnlyList<IncomingPayment> Payments, IReadOnlyList<IncomingAttachment> Attachments);
/// <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 IncomingLine(
int Number, IReadOnlyList<IncomingItemCode> Codes, string Description, decimal? Quantity, string? Unit,
decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList<IncomingDiscount> Discounts,
bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference);
/// <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 IncomingItemCode(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 IncomingDiscount(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 IncomingTaxSummary(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 IncomingPayment(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 IncomingReference(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 IncomingWithholding(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 IncomingStampDuty(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 IncomingSocialSecurity(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 IncomingAttachment(string Name, string? Format, string? Description, byte[] Content);
/// <summary>
/// How a received e-invoice becomes a document of the company: which document type registers each type of the format
/// (Italy: TD01 and the like as supplier invoice FF, TD04 and TD08 as supplier credit note NCF).
/// </summary>
public interface IIncomingInvoiceRules
{
/// <summary>The code of the document type that registers an invoice of this type of the format.</summary>
/// <param name="formatType">The type in the file (TD01...).</param>
/// <returns>The document type code, or none when the type is not registered as a purchase (a self-invoice).</returns>
string? DocumentTypeCode(string formatType);
}
+211
View File
@@ -0,0 +1,211 @@
using Khaemhat.Core.Accounting;
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>An account of the country's model chart of accounts.</summary>
/// <param name="Code">The hierarchical code, such as <c>05.01.001</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="Nature">The statement it ends up in.</param>
/// <param name="Type">What the automatic postings look for in it.</param>
/// <param name="StatementLine">The line of the legal financial statements, if any.</param>
/// <param name="SubLedger">The lines carry a customer or supplier.</param>
/// <param name="VatRelevant">Relevant for VAT.</param>
public sealed record AccountTemplate(
string Code,
string Description,
AccountNature Nature,
AccountType Type = AccountType.Generic,
string? StatementLine = null,
bool SubLedger = false,
bool VatRelevant = false)
{
/// <summary>The parent account: the code without its last part.</summary>
public string? ParentCode => AccountCodes.ParentOf(Code);
/// <summary>The level: the number of parts of the code.</summary>
public int Level => AccountCodes.LevelOf(Code);
}
/// <summary>A VAT register of the base data.</summary>
/// <param name="Code">The code, such as <c>VEN1</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="Kind">Sales, purchases or receipts.</param>
/// <param name="ReverseCharge">A section for reverse-charge self-invoices.</param>
public sealed record VatRegisterTemplate(string Code, string Description, VatRegisterKind Kind, bool ReverseCharge = false);
/// <summary>A line of a journal template of the base data.</summary>
/// <param name="Role">What it stands for.</param>
/// <param name="Side">Debit or credit for an invoice.</param>
/// <param name="AccountCode">The account, by code (fixed for <see cref="PostingRole.Account"/>, default otherwise).</param>
/// <param name="Description">The description proposed.</param>
public sealed record JournalTemplateLineTemplate(PostingRole Role, AccountSide Side, string? AccountCode = null, string? Description = null);
/// <summary>A journal template (causale contabile) of the base data.</summary>
/// <param name="Code">The code, such as <c>FV</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="Area">The kind of operations.</param>
/// <param name="VatRegisterCode">The VAT register, for entries with VAT.</param>
/// <param name="OpensItems">The entries open items of customers or suppliers.</param>
/// <param name="Reverses">Credit notes: the sides of the document are reversed.</param>
/// <param name="Lines">The model of the lines.</param>
public sealed record JournalTemplateTemplate(
string Code, string Description, JournalArea Area, string? VatRegisterCode, bool OpensItems, bool Reverses, IReadOnlyList<JournalTemplateLineTemplate> Lines);
/// <summary>Which journal template and VAT register a document type of the base data uses.</summary>
/// <param name="DocumentTypeCode">The document type, such as <c>FI</c>.</param>
/// <param name="JournalTemplateCode">The journal template, such as <c>FV</c>.</param>
/// <param name="VatRegisterCode">The VAT register, such as <c>VEN1</c>.</param>
public sealed record DocumentPostingTemplate(string DocumentTypeCode, string JournalTemplateCode, string? VatRegisterCode);
/// <summary>
/// The ledger of the base data (SPEC §11.7, §14, issue #62): the model chart of accounts, the VAT registers, the
/// journal templates and the template and register of each document type. The accounts of the roles (customers,
/// VAT on sales...) are those of the lines of the templates.
/// </summary>
public interface ILedgerTemplate
{
/// <summary>The name of the model chart, such as <c>PMI standard</c>.</summary>
string Name { get; }
/// <summary>The accounts, parents before children.</summary>
IReadOnlyList<AccountTemplate> Accounts { get; }
/// <summary>The VAT registers.</summary>
IReadOnlyList<VatRegisterTemplate> VatRegisters { get; }
/// <summary>The journal templates.</summary>
IReadOnlyList<JournalTemplateTemplate> JournalTemplates { get; }
/// <summary>The template and register of the document types.</summary>
IReadOnlyList<DocumentPostingTemplate> DocumentPostings { get; }
/// <summary>The account of a role when no template line gives one (customers, suppliers, VAT, bank...).</summary>
/// <param name="role">The role.</param>
/// <returns>The account code, or <see langword="null"/>.</returns>
string? AccountOf(PostingRole role);
}
/// <summary>The rules of the periodic VAT settlement and of the other tax payments of the country.</summary>
public interface IVatSettlementRules
{
/// <summary>The smallest VAT payment; below it the debit is carried (Italy: 25.82).</summary>
decimal MinimumPayment { get; }
/// <summary>The share of the base of the December advance with the historical and forecast methods (Italy: 88).</summary>
decimal AdvancePercent { get; }
/// <summary>The smallest advance (Italy: 103.29).</summary>
decimal AdvanceMinimum { get; }
/// <summary>The payment code of the VAT of a period (Italy: 6001-6012, 6031-6033, and 6099 for the last quarter).</summary>
/// <param name="period">The period.</param>
/// <returns>The code.</returns>
string PaymentCode(TaxPeriod period);
/// <summary>What the form wants in the field of the month or installment for the VAT of a period (Italy: <c>0101</c> for 6099).</summary>
/// <param name="period">The period.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
string? PaymentPeriod(TaxPeriod period);
/// <summary>The day the December advance is due (Italy: 27 December).</summary>
/// <param name="year">The year.</param>
/// <returns>The day, past holidays.</returns>
DateOnly AdvanceDue(int year);
/// <summary>The day withholdings of fees paid in a month are due (Italy: the 16th of the next month).</summary>
/// <param name="year">The year of the payment of the invoice.</param>
/// <param name="month">The month.</param>
/// <returns>The day, past holidays.</returns>
DateOnly WithholdingDue(int year, int month);
/// <summary>The day the stamp duty of the e-invoices of a quarter is due.</summary>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter, 1-4.</param>
/// <returns>The day, past holidays.</returns>
DateOnly StampDutyDue(int year, int quarter);
/// <summary>The day the communication of the settlements of a quarter is due (Italy: LIPE).</summary>
/// <param name="year">The year.</param>
/// <param name="quarter">The quarter, 1-4.</param>
/// <returns>The day, past holidays.</returns>
DateOnly PeriodicReturnDue(int year, int quarter);
}
/// <summary>A period of the communication of VAT settlements (a month, or a quarter for quarterly payers).</summary>
/// <param name="Period">The period.</param>
/// <param name="ActiveTotal">The taxable amount of the operations issued.</param>
/// <param name="PassiveTotal">The taxable amount of the operations received.</param>
/// <param name="TaxDue">The VAT due.</param>
/// <param name="TaxDeducted">The VAT deducted.</param>
/// <param name="PreviousDebit">The debit below the minimum carried from the previous period.</param>
/// <param name="PreviousCredit">The credit of the previous period.</param>
/// <param name="Interest">The interest of quarterly payers.</param>
/// <param name="Advance">The December advance.</param>
/// <param name="Balance">Positive to pay, negative in credit.</param>
public sealed record PeriodicVatReturnModule(
TaxPeriod Period,
decimal ActiveTotal,
decimal PassiveTotal,
decimal TaxDue,
decimal TaxDeducted,
decimal PreviousDebit,
decimal PreviousCredit,
decimal Interest,
decimal Advance,
decimal Balance);
/// <summary>The communication of VAT settlements of a quarter (Italy: LIPE).</summary>
/// <param name="Year">The year.</param>
/// <param name="Quarter">The quarter.</param>
/// <param name="TaxCode">The tax code of the company.</param>
/// <param name="VatNumber">The VAT number of the company, without country.</param>
/// <param name="DeclarantTaxCode">Who signs, when not the company (its legal representative).</param>
/// <param name="IntermediaryTaxCode">The intermediary who sends it, if any.</param>
/// <param name="CommitmentDate">The day of the commitment of the intermediary.</param>
/// <param name="Modules">The months or the quarter.</param>
public sealed record PeriodicVatReturn(
int Year,
int Quarter,
string TaxCode,
string VatNumber,
string? DeclarantTaxCode,
string? IntermediaryTaxCode,
DateOnly CommitmentDate,
IReadOnlyList<PeriodicVatReturnModule> Modules);
/// <summary>Writes the file of the communication of VAT settlements (Italy: LIPE XML).</summary>
public interface IPeriodicVatReturnWriter
{
/// <summary>The name of the communication, such as <c>LIPE</c>.</summary>
string Name { get; }
/// <summary>The file name proposed.</summary>
/// <param name="data">The communication.</param>
/// <returns>The name.</returns>
string FileName(PeriodicVatReturn data);
/// <summary>Writes the file.</summary>
/// <param name="data">The communication.</param>
/// <returns>The file, UTF-8.</returns>
byte[] Write(PeriodicVatReturn data);
}
/// <summary>A line of a tax payment form (Italy: a line of the Erario section of the F24).</summary>
/// <param name="Code">The payment code.</param>
/// <param name="Period">The month or installment, as the form wants it.</param>
/// <param name="Year">The reference year.</param>
/// <param name="Debit">The amount due.</param>
/// <param name="Credit">The credit used in compensation.</param>
/// <param name="Description">What it pays.</param>
public sealed record TaxPaymentFormLine(string Code, string? Period, int Year, decimal Debit, decimal Credit, string Description);
/// <summary>A tax payment form (Italy: F24) of one due date.</summary>
/// <param name="DueDate">The day.</param>
/// <param name="TaxCode">The tax code of the company.</param>
/// <param name="Name">The name of the company.</param>
/// <param name="Lines">The lines.</param>
public sealed record TaxPaymentForm(DateOnly DueDate, string TaxCode, string Name, IReadOnlyList<TaxPaymentFormLine> Lines)
{
/// <summary>The balance to pay.</summary>
public decimal Balance => Lines.Sum(l => l.Debit - l.Credit);
}
@@ -0,0 +1,238 @@
codice;descrizione;natura;tipo;voce_cee;partitario;iva
01;Immobilizzazioni immateriali;A;;B.I;;
01.01;Immobilizzazioni immateriali;A;;B.I;;
01.01.001;Costi di impianto e di ampliamento;A;;B.I.1;;
01.01.002;Costi di sviluppo;A;;B.I.2;;
01.01.003;Software e diritti di utilizzazione;A;;B.I.3;;
01.01.004;Marchi e brevetti;A;;B.I.4;;
01.01.005;Avviamento;A;;B.I.5;;
01.01.006;Altre immobilizzazioni immateriali;A;;B.I.7;;
02;Immobilizzazioni materiali;A;;B.II;;
02.01;Terreni e fabbricati;A;;B.II.1;;
02.01.001;Terreni;A;;B.II.1;;
02.01.002;Fabbricati;A;;B.II.1;;
02.02;Impianti e macchinari;A;;B.II.2;;
02.02.001;Impianti generici;A;;B.II.2;;
02.02.002;Macchinari;A;;B.II.2;;
02.03;Attrezzature;A;;B.II.3;;
02.03.001;Attrezzature industriali e commerciali;A;;B.II.3;;
02.04;Altri beni;A;;B.II.4;;
02.04.001;Mobili e arredi;A;;B.II.4;;
02.04.002;Macchine d'ufficio elettroniche;A;;B.II.4;;
02.04.003;Autovetture;A;;B.II.4;;
02.04.004;Autocarri;A;;B.II.4;;
02.04.005;Beni di costo unitario non superiore a 516,46 euro;A;;B.II.4;;
03;Immobilizzazioni finanziarie;A;;B.III;;
03.01;Partecipazioni e crediti immobilizzati;A;;B.III;;
03.01.001;Partecipazioni;A;;B.III.1;;
03.01.002;Depositi cauzionali;A;;B.III.2;;
04;Rimanenze;A;;C.I;;
04.01;Rimanenze di magazzino;A;;C.I;;
04.01.001;Rimanenze di merci;A;;C.I.4;;
04.01.002;Rimanenze di materie prime;A;;C.I.1;;
04.01.003;Rimanenze di prodotti finiti;A;;C.I.4;;
04.01.004;Acconti a fornitori per merci;A;;C.I.5;;
05;Crediti verso clienti;A;;C.II.1;;
05.01;Clienti;A;CL;C.II.1;;
05.01.001;Clienti Italia;A;CL;C.II.1;S;
05.01.002;Clienti esteri;A;CL;C.II.1;S;
05.01.003;Clienti c/fatture da emettere;A;;C.II.1;;
05.02;Effetti e rettifiche;A;;C.II.1;;
05.02.001;Effetti attivi e RiBa all'incasso;A;;C.II.1;;
05.02.002;Fondo svalutazione crediti;A;;C.II.1;;
06;Altri crediti;A;;C.II;;
06.01;Crediti diversi;A;;C.II.5-quater;;
06.01.001;Crediti diversi;A;;C.II.5-quater;;
06.01.002;Anticipi a fornitori;A;;C.II.5-quater;;
06.01.003;Crediti verso dipendenti;A;;C.II.5-quater;;
06.02;Crediti per IVA;A;IV;C.II.5-bis;;
06.02.001;IVA su acquisti;A;IV;C.II.5-bis;;
06.02.002;Erario c/IVA a credito annuale;A;IV;C.II.5-bis;;
06.03;Crediti tributari;A;ER;C.II.5-bis;;
06.03.001;Erario c/ritenute subite;A;ER;C.II.5-bis;;
06.03.002;Erario c/acconti IRES;A;ER;C.II.5-bis;;
06.03.003;Erario c/acconti IRAP;A;ER;C.II.5-bis;;
07;Disponibilità liquide;A;;C.IV;;
07.01;Banche;A;BA;C.IV.1;;
07.01.001;Banca c/c;A;BA;C.IV.1;;
07.01.002;Banca c/c secondo conto;A;BA;C.IV.1;;
07.01.003;Conto postale;A;BA;C.IV.1;;
07.02;Cassa;A;CA;C.IV.3;;
07.02.001;Cassa contanti;A;CA;C.IV.3;;
07.02.002;Carte di pagamento prepagate;A;CA;C.IV.3;;
08;Ratei e risconti attivi;A;;D;;
08.01;Ratei e risconti attivi;A;;D;;
08.01.001;Ratei attivi;A;;D;;
08.01.002;Risconti attivi;A;;D;;
09;Fondi di ammortamento;A;;B.II;;
09.01;Fondi di ammortamento immobilizzazioni immateriali;A;;B.I;;
09.01.001;Fondo ammortamento immobilizzazioni immateriali;A;;B.I;;
09.02;Fondi di ammortamento immobilizzazioni materiali;A;;B.II;;
09.02.001;Fondo ammortamento fabbricati;A;;B.II.1;;
09.02.002;Fondo ammortamento impianti e macchinari;A;;B.II.2;;
09.02.003;Fondo ammortamento attrezzature;A;;B.II.3;;
09.02.004;Fondo ammortamento mobili e arredi;A;;B.II.4;;
09.02.005;Fondo ammortamento macchine d'ufficio;A;;B.II.4;;
09.02.006;Fondo ammortamento automezzi;A;;B.II.4;;
10;Patrimonio netto;P;;A;;
10.01;Capitale e riserve;P;;A;;
10.01.001;Capitale sociale;P;;A.I;;
10.01.002;Riserva legale;P;;A.IV;;
10.01.003;Riserva straordinaria;P;;A.VI;;
10.01.004;Versamenti in conto capitale;P;;A.VI;;
10.02;Risultati;P;;A;;
10.02.001;Utili (perdite) portati a nuovo;P;;A.VIII;;
10.02.002;Utile (perdita) dell'esercizio;P;;A.IX;;
11;Fondi per rischi e oneri;P;;B;;
11.01;Fondi per rischi e oneri;P;;B;;
11.01.001;Fondo rischi su crediti;P;;B.4;;
11.01.002;Fondo imposte anche differite;P;;B.2;;
11.01.003;Altri fondi per rischi e oneri;P;;B.4;;
12;Trattamento di fine rapporto;P;;C;;
12.01;Trattamento di fine rapporto;P;;C;;
12.01.001;Fondo trattamento di fine rapporto;P;;C;;
13;Debiti verso banche e finanziatori;P;;D.4;;
13.01;Debiti verso banche;P;;D.4;;
13.01.001;Banche c/anticipi su fatture;P;;D.4;;
13.01.002;Mutui passivi;P;;D.4;;
13.01.003;Finanziamenti bancari a breve;P;;D.4;;
13.02;Altri finanziatori;P;;D.3;;
13.02.001;Finanziamenti dei soci;P;;D.3;;
14;Debiti verso fornitori;P;;D.7;;
14.01;Fornitori;P;FO;D.7;;
14.01.001;Fornitori Italia;P;FO;D.7;S;
14.01.002;Fornitori esteri;P;FO;D.7;S;
14.01.003;Fornitori c/fatture da ricevere;P;;D.7;;
14.02;Acconti ed effetti;P;;D.6;;
14.02.001;Acconti da clienti;P;;D.6;;
14.02.002;Effetti passivi;P;;D.9;;
15;Debiti tributari e previdenziali;P;;D.12;;
15.01;Debiti per IVA;P;IV;D.12;;
15.01.001;IVA su vendite;P;IV;D.12;;
15.01.002;Erario c/liquidazione IVA;P;IV;D.12;;
15.01.003;Erario c/IVA in sospensione;P;IV;D.12;;
15.02;Erario c/ritenute;P;ER;D.12;;
15.02.001;Erario c/ritenute lavoro autonomo;P;ER;D.12;;
15.02.002;Erario c/ritenute provvigioni;P;ER;D.12;;
15.02.003;Erario c/ritenute lavoro dipendente;P;ER;D.12;;
15.03;Debiti previdenziali;P;;D.13;;
15.03.001;INPS c/contributi;P;;D.13;;
15.03.002;Enasarco c/contributi;P;;D.13;;
15.03.003;INAIL c/premi;P;;D.13;;
15.04;Imposte;P;ER;D.12;;
15.04.001;Erario c/IRES;P;ER;D.12;;
15.04.002;Erario c/IRAP;P;ER;D.12;;
15.04.003;Erario c/imposta di bollo;P;ER;D.12;;
16;Altri debiti;P;;D.14;;
16.01;Debiti diversi;P;;D.14;;
16.01.001;Debiti diversi;P;;D.14;;
16.01.002;Dipendenti c/retribuzioni;P;;D.14;;
16.01.003;Amministratori c/compensi;P;;D.14;;
17;Ratei e risconti passivi;P;;E;;
17.01;Ratei e risconti passivi;P;;E;;
17.01.001;Ratei passivi;P;;E;;
17.01.002;Risconti passivi;P;;E;;
20;Acquisti di materie e merci;C;;B.6;;
20.01;Acquisti;C;;B.6;;
20.01.001;Merci c/acquisti;C;;B.6;;S
20.01.002;Materie prime c/acquisti;C;;B.6;;S
20.01.003;Materiale di consumo;C;;B.6;;S
20.01.004;Imballaggi;C;;B.6;;S
20.01.005;Carburanti e lubrificanti;C;;B.6;;S
20.01.006;Cancelleria;C;;B.6;;S
20.02;Rettifiche degli acquisti;C;;B.6;;
20.02.001;Resi e sconti su acquisti;C;;B.6;;S
21;Costi per servizi;C;;B.7;;
21.01;Utenze;C;;B.7;;
21.01.001;Energia elettrica;C;;B.7;;S
21.01.002;Gas e riscaldamento;C;;B.7;;S
21.01.003;Acqua;C;;B.7;;S
21.01.004;Telefonia e internet;C;;B.7;;S
21.02;Servizi professionali;C;;B.7;;
21.02.001;Consulenze tecniche;C;;B.7;;S
21.02.002;Consulenze legali e notarili;C;;B.7;;S
21.02.003;Compensi per la contabilità;C;;B.7;;S
21.02.004;Compensi agli amministratori;C;;B.7;;
21.02.005;Provvigioni ad agenti;C;;B.7;;S
21.03;Servizi commerciali e generali;C;;B.7;;
21.03.001;Trasporti su acquisti;C;;B.7;;S
21.03.002;Trasporti su vendite;C;;B.7;;S
21.03.003;Manutenzioni e riparazioni;C;;B.7;;S
21.03.004;Pubblicità e promozione;C;;B.7;;S
21.03.005;Assicurazioni;C;;B.7;;
21.03.006;Servizi software e cloud;C;;B.7;;S
21.03.007;Pulizia e vigilanza;C;;B.7;;S
21.03.008;Viaggi e trasferte;C;;B.7;;S
21.03.009;Spese postali e di spedizione;C;;B.7;;S
21.03.010;Formazione del personale;C;;B.7;;S
21.03.011;Spese e commissioni bancarie;C;;B.7;;
22;Godimento di beni di terzi;C;;B.8;;
22.01;Godimento di beni di terzi;C;;B.8;;
22.01.001;Affitti passivi;C;;B.8;;S
22.01.002;Canoni di leasing;C;;B.8;;S
22.01.003;Noleggi;C;;B.8;;S
23;Costi del personale;C;;B.9;;
23.01;Costi del personale;C;;B.9;;
23.01.001;Salari e stipendi;C;;B.9.a;;
23.01.002;Oneri sociali;C;;B.9.b;;
23.01.003;Trattamento di fine rapporto;C;;B.9.c;;
24;Ammortamenti e svalutazioni;C;;B.10;;
24.01;Ammortamenti;C;;B.10;;
24.01.001;Ammortamento immobilizzazioni immateriali;C;;B.10.a;;
24.01.002;Ammortamento immobilizzazioni materiali;C;;B.10.b;;
24.02;Svalutazioni;C;;B.10.d;;
24.02.001;Svalutazione dei crediti;C;;B.10.d;;
25;Variazioni delle rimanenze;C;;B.11;;
25.01;Variazioni delle rimanenze;C;;B.11;;
25.01.001;Rimanenze iniziali di merci;C;;B.11;;
25.01.002;Rimanenze finali di merci;C;;B.11;;
26;Accantonamenti;C;;B.12;;
26.01;Accantonamenti;C;;B.12;;
26.01.001;Accantonamento per rischi;C;;B.12;;
26.01.002;Altri accantonamenti;C;;B.13;;
27;Oneri diversi di gestione;C;;B.14;;
27.01;Oneri diversi di gestione;C;;B.14;;
27.01.001;Imposte e tasse diverse;C;;B.14;;
27.01.002;Imposta di bollo;C;;B.14;;
27.01.003;IVA indetraibile;C;;B.14;;
27.01.004;Abbuoni e arrotondamenti passivi;C;;B.14;;
27.01.005;Sopravvenienze passive;C;;B.14;;
27.01.006;Minusvalenze ordinarie;C;;B.14;;
27.01.007;Sanzioni e interessi su tributi;C;;B.14;;
27.01.008;Quote associative e abbonamenti;C;;B.14;;S
28;Oneri finanziari;C;;C.17;;
28.01;Interessi e oneri finanziari;C;;C.17;;
28.01.001;Interessi passivi bancari;C;;C.17;;
28.01.002;Interessi passivi su mutui;C;;C.17;;
28.01.003;Interessi sulla liquidazione IVA trimestrale;C;;C.17;;
28.01.004;Oneri finanziari diversi;C;;C.17;;
29;Imposte sul reddito;C;;20;;
29.01;Imposte sul reddito dell'esercizio;C;;20;;
29.01.001;IRES dell'esercizio;C;;20;;
29.01.002;IRAP dell'esercizio;C;;20;;
30;Ricavi delle vendite e delle prestazioni;R;;A.1;;
30.01;Ricavi;R;;A.1;;
30.01.001;Ricavi per vendita di merci;R;;A.1;;S
30.01.002;Ricavi per vendita di prodotti;R;;A.1;;S
30.01.003;Ricavi per prestazioni di servizi;R;;A.1;;S
30.01.004;Ricavi per cessioni intracomunitarie ed esportazioni;R;;A.1;;S
30.02;Rettifiche dei ricavi;R;;A.1;;
30.02.001;Resi e sconti su vendite;R;;A.1;;S
31;Altri ricavi e proventi;R;;A.5;;
31.01;Altri ricavi e proventi;R;;A.5;;
31.01.001;Rimborso spese di trasporto;R;;A.5;;S
31.01.002;Rimborso spese di bollo;R;;A.5;;
31.01.003;Rivalsa contributi previdenziali;R;;A.5;;S
31.01.004;Abbuoni e arrotondamenti attivi;R;;A.5;;
31.01.005;Plusvalenze ordinarie;R;;A.5;;
31.01.006;Sopravvenienze attive;R;;A.5;;
31.01.007;Contributi in conto esercizio;R;;A.5;;
32;Proventi finanziari;R;;C.16;;
32.01;Proventi finanziari;R;;C.16;;
32.01.001;Interessi attivi bancari;R;;C.16;;
32.01.002;Altri proventi finanziari;R;;C.16;;
90;Conti di apertura e chiusura;O;;;;
90.01;Conti di apertura e chiusura;O;;;;
90.01.001;Stato patrimoniale di apertura;O;;;;
90.01.002;Stato patrimoniale di chiusura;O;;;;
90.01.003;Conto economico di chiusura;O;;;;
1 codice descrizione natura tipo voce_cee partitario iva
2 01 Immobilizzazioni immateriali A B.I
3 01.01 Immobilizzazioni immateriali A B.I
4 01.01.001 Costi di impianto e di ampliamento A B.I.1
5 01.01.002 Costi di sviluppo A B.I.2
6 01.01.003 Software e diritti di utilizzazione A B.I.3
7 01.01.004 Marchi e brevetti A B.I.4
8 01.01.005 Avviamento A B.I.5
9 01.01.006 Altre immobilizzazioni immateriali A B.I.7
10 02 Immobilizzazioni materiali A B.II
11 02.01 Terreni e fabbricati A B.II.1
12 02.01.001 Terreni A B.II.1
13 02.01.002 Fabbricati A B.II.1
14 02.02 Impianti e macchinari A B.II.2
15 02.02.001 Impianti generici A B.II.2
16 02.02.002 Macchinari A B.II.2
17 02.03 Attrezzature A B.II.3
18 02.03.001 Attrezzature industriali e commerciali A B.II.3
19 02.04 Altri beni A B.II.4
20 02.04.001 Mobili e arredi A B.II.4
21 02.04.002 Macchine d'ufficio elettroniche A B.II.4
22 02.04.003 Autovetture A B.II.4
23 02.04.004 Autocarri A B.II.4
24 02.04.005 Beni di costo unitario non superiore a 516,46 euro A B.II.4
25 03 Immobilizzazioni finanziarie A B.III
26 03.01 Partecipazioni e crediti immobilizzati A B.III
27 03.01.001 Partecipazioni A B.III.1
28 03.01.002 Depositi cauzionali A B.III.2
29 04 Rimanenze A C.I
30 04.01 Rimanenze di magazzino A C.I
31 04.01.001 Rimanenze di merci A C.I.4
32 04.01.002 Rimanenze di materie prime A C.I.1
33 04.01.003 Rimanenze di prodotti finiti A C.I.4
34 04.01.004 Acconti a fornitori per merci A C.I.5
35 05 Crediti verso clienti A C.II.1
36 05.01 Clienti A CL C.II.1
37 05.01.001 Clienti Italia A CL C.II.1 S
38 05.01.002 Clienti esteri A CL C.II.1 S
39 05.01.003 Clienti c/fatture da emettere A C.II.1
40 05.02 Effetti e rettifiche A C.II.1
41 05.02.001 Effetti attivi e RiBa all'incasso A C.II.1
42 05.02.002 Fondo svalutazione crediti A C.II.1
43 06 Altri crediti A C.II
44 06.01 Crediti diversi A C.II.5-quater
45 06.01.001 Crediti diversi A C.II.5-quater
46 06.01.002 Anticipi a fornitori A C.II.5-quater
47 06.01.003 Crediti verso dipendenti A C.II.5-quater
48 06.02 Crediti per IVA A IV C.II.5-bis
49 06.02.001 IVA su acquisti A IV C.II.5-bis
50 06.02.002 Erario c/IVA a credito annuale A IV C.II.5-bis
51 06.03 Crediti tributari A ER C.II.5-bis
52 06.03.001 Erario c/ritenute subite A ER C.II.5-bis
53 06.03.002 Erario c/acconti IRES A ER C.II.5-bis
54 06.03.003 Erario c/acconti IRAP A ER C.II.5-bis
55 07 Disponibilità liquide A C.IV
56 07.01 Banche A BA C.IV.1
57 07.01.001 Banca c/c A BA C.IV.1
58 07.01.002 Banca c/c secondo conto A BA C.IV.1
59 07.01.003 Conto postale A BA C.IV.1
60 07.02 Cassa A CA C.IV.3
61 07.02.001 Cassa contanti A CA C.IV.3
62 07.02.002 Carte di pagamento prepagate A CA C.IV.3
63 08 Ratei e risconti attivi A D
64 08.01 Ratei e risconti attivi A D
65 08.01.001 Ratei attivi A D
66 08.01.002 Risconti attivi A D
67 09 Fondi di ammortamento A B.II
68 09.01 Fondi di ammortamento immobilizzazioni immateriali A B.I
69 09.01.001 Fondo ammortamento immobilizzazioni immateriali A B.I
70 09.02 Fondi di ammortamento immobilizzazioni materiali A B.II
71 09.02.001 Fondo ammortamento fabbricati A B.II.1
72 09.02.002 Fondo ammortamento impianti e macchinari A B.II.2
73 09.02.003 Fondo ammortamento attrezzature A B.II.3
74 09.02.004 Fondo ammortamento mobili e arredi A B.II.4
75 09.02.005 Fondo ammortamento macchine d'ufficio A B.II.4
76 09.02.006 Fondo ammortamento automezzi A B.II.4
77 10 Patrimonio netto P A
78 10.01 Capitale e riserve P A
79 10.01.001 Capitale sociale P A.I
80 10.01.002 Riserva legale P A.IV
81 10.01.003 Riserva straordinaria P A.VI
82 10.01.004 Versamenti in conto capitale P A.VI
83 10.02 Risultati P A
84 10.02.001 Utili (perdite) portati a nuovo P A.VIII
85 10.02.002 Utile (perdita) dell'esercizio P A.IX
86 11 Fondi per rischi e oneri P B
87 11.01 Fondi per rischi e oneri P B
88 11.01.001 Fondo rischi su crediti P B.4
89 11.01.002 Fondo imposte anche differite P B.2
90 11.01.003 Altri fondi per rischi e oneri P B.4
91 12 Trattamento di fine rapporto P C
92 12.01 Trattamento di fine rapporto P C
93 12.01.001 Fondo trattamento di fine rapporto P C
94 13 Debiti verso banche e finanziatori P D.4
95 13.01 Debiti verso banche P D.4
96 13.01.001 Banche c/anticipi su fatture P D.4
97 13.01.002 Mutui passivi P D.4
98 13.01.003 Finanziamenti bancari a breve P D.4
99 13.02 Altri finanziatori P D.3
100 13.02.001 Finanziamenti dei soci P D.3
101 14 Debiti verso fornitori P D.7
102 14.01 Fornitori P FO D.7
103 14.01.001 Fornitori Italia P FO D.7 S
104 14.01.002 Fornitori esteri P FO D.7 S
105 14.01.003 Fornitori c/fatture da ricevere P D.7
106 14.02 Acconti ed effetti P D.6
107 14.02.001 Acconti da clienti P D.6
108 14.02.002 Effetti passivi P D.9
109 15 Debiti tributari e previdenziali P D.12
110 15.01 Debiti per IVA P IV D.12
111 15.01.001 IVA su vendite P IV D.12
112 15.01.002 Erario c/liquidazione IVA P IV D.12
113 15.01.003 Erario c/IVA in sospensione P IV D.12
114 15.02 Erario c/ritenute P ER D.12
115 15.02.001 Erario c/ritenute lavoro autonomo P ER D.12
116 15.02.002 Erario c/ritenute provvigioni P ER D.12
117 15.02.003 Erario c/ritenute lavoro dipendente P ER D.12
118 15.03 Debiti previdenziali P D.13
119 15.03.001 INPS c/contributi P D.13
120 15.03.002 Enasarco c/contributi P D.13
121 15.03.003 INAIL c/premi P D.13
122 15.04 Imposte P ER D.12
123 15.04.001 Erario c/IRES P ER D.12
124 15.04.002 Erario c/IRAP P ER D.12
125 15.04.003 Erario c/imposta di bollo P ER D.12
126 16 Altri debiti P D.14
127 16.01 Debiti diversi P D.14
128 16.01.001 Debiti diversi P D.14
129 16.01.002 Dipendenti c/retribuzioni P D.14
130 16.01.003 Amministratori c/compensi P D.14
131 17 Ratei e risconti passivi P E
132 17.01 Ratei e risconti passivi P E
133 17.01.001 Ratei passivi P E
134 17.01.002 Risconti passivi P E
135 20 Acquisti di materie e merci C B.6
136 20.01 Acquisti C B.6
137 20.01.001 Merci c/acquisti C B.6 S
138 20.01.002 Materie prime c/acquisti C B.6 S
139 20.01.003 Materiale di consumo C B.6 S
140 20.01.004 Imballaggi C B.6 S
141 20.01.005 Carburanti e lubrificanti C B.6 S
142 20.01.006 Cancelleria C B.6 S
143 20.02 Rettifiche degli acquisti C B.6
144 20.02.001 Resi e sconti su acquisti C B.6 S
145 21 Costi per servizi C B.7
146 21.01 Utenze C B.7
147 21.01.001 Energia elettrica C B.7 S
148 21.01.002 Gas e riscaldamento C B.7 S
149 21.01.003 Acqua C B.7 S
150 21.01.004 Telefonia e internet C B.7 S
151 21.02 Servizi professionali C B.7
152 21.02.001 Consulenze tecniche C B.7 S
153 21.02.002 Consulenze legali e notarili C B.7 S
154 21.02.003 Compensi per la contabilità C B.7 S
155 21.02.004 Compensi agli amministratori C B.7
156 21.02.005 Provvigioni ad agenti C B.7 S
157 21.03 Servizi commerciali e generali C B.7
158 21.03.001 Trasporti su acquisti C B.7 S
159 21.03.002 Trasporti su vendite C B.7 S
160 21.03.003 Manutenzioni e riparazioni C B.7 S
161 21.03.004 Pubblicità e promozione C B.7 S
162 21.03.005 Assicurazioni C B.7
163 21.03.006 Servizi software e cloud C B.7 S
164 21.03.007 Pulizia e vigilanza C B.7 S
165 21.03.008 Viaggi e trasferte C B.7 S
166 21.03.009 Spese postali e di spedizione C B.7 S
167 21.03.010 Formazione del personale C B.7 S
168 21.03.011 Spese e commissioni bancarie C B.7
169 22 Godimento di beni di terzi C B.8
170 22.01 Godimento di beni di terzi C B.8
171 22.01.001 Affitti passivi C B.8 S
172 22.01.002 Canoni di leasing C B.8 S
173 22.01.003 Noleggi C B.8 S
174 23 Costi del personale C B.9
175 23.01 Costi del personale C B.9
176 23.01.001 Salari e stipendi C B.9.a
177 23.01.002 Oneri sociali C B.9.b
178 23.01.003 Trattamento di fine rapporto C B.9.c
179 24 Ammortamenti e svalutazioni C B.10
180 24.01 Ammortamenti C B.10
181 24.01.001 Ammortamento immobilizzazioni immateriali C B.10.a
182 24.01.002 Ammortamento immobilizzazioni materiali C B.10.b
183 24.02 Svalutazioni C B.10.d
184 24.02.001 Svalutazione dei crediti C B.10.d
185 25 Variazioni delle rimanenze C B.11
186 25.01 Variazioni delle rimanenze C B.11
187 25.01.001 Rimanenze iniziali di merci C B.11
188 25.01.002 Rimanenze finali di merci C B.11
189 26 Accantonamenti C B.12
190 26.01 Accantonamenti C B.12
191 26.01.001 Accantonamento per rischi C B.12
192 26.01.002 Altri accantonamenti C B.13
193 27 Oneri diversi di gestione C B.14
194 27.01 Oneri diversi di gestione C B.14
195 27.01.001 Imposte e tasse diverse C B.14
196 27.01.002 Imposta di bollo C B.14
197 27.01.003 IVA indetraibile C B.14
198 27.01.004 Abbuoni e arrotondamenti passivi C B.14
199 27.01.005 Sopravvenienze passive C B.14
200 27.01.006 Minusvalenze ordinarie C B.14
201 27.01.007 Sanzioni e interessi su tributi C B.14
202 27.01.008 Quote associative e abbonamenti C B.14 S
203 28 Oneri finanziari C C.17
204 28.01 Interessi e oneri finanziari C C.17
205 28.01.001 Interessi passivi bancari C C.17
206 28.01.002 Interessi passivi su mutui C C.17
207 28.01.003 Interessi sulla liquidazione IVA trimestrale C C.17
208 28.01.004 Oneri finanziari diversi C C.17
209 29 Imposte sul reddito C 20
210 29.01 Imposte sul reddito dell'esercizio C 20
211 29.01.001 IRES dell'esercizio C 20
212 29.01.002 IRAP dell'esercizio C 20
213 30 Ricavi delle vendite e delle prestazioni R A.1
214 30.01 Ricavi R A.1
215 30.01.001 Ricavi per vendita di merci R A.1 S
216 30.01.002 Ricavi per vendita di prodotti R A.1 S
217 30.01.003 Ricavi per prestazioni di servizi R A.1 S
218 30.01.004 Ricavi per cessioni intracomunitarie ed esportazioni R A.1 S
219 30.02 Rettifiche dei ricavi R A.1
220 30.02.001 Resi e sconti su vendite R A.1 S
221 31 Altri ricavi e proventi R A.5
222 31.01 Altri ricavi e proventi R A.5
223 31.01.001 Rimborso spese di trasporto R A.5 S
224 31.01.002 Rimborso spese di bollo R A.5
225 31.01.003 Rivalsa contributi previdenziali R A.5 S
226 31.01.004 Abbuoni e arrotondamenti attivi R A.5
227 31.01.005 Plusvalenze ordinarie R A.5
228 31.01.006 Sopravvenienze attive R A.5
229 31.01.007 Contributi in conto esercizio R A.5
230 32 Proventi finanziari R C.16
231 32.01 Proventi finanziari R C.16
232 32.01.001 Interessi attivi bancari R C.16
233 32.01.002 Altri proventi finanziari R C.16
234 90 Conti di apertura e chiusura O
235 90.01 Conti di apertura e chiusura O
236 90.01.001 Stato patrimoniale di apertura O
237 90.01.002 Stato patrimoniale di chiusura O
238 90.01.003 Conto economico di chiusura O
@@ -0,0 +1,517 @@
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Reads the FatturaPA files received from suppliers (SPEC §11.9, issue #57): ordinary invoices v1.2.x
/// (<c>FPR12</c>, <c>FPA12</c>), simplified invoices (<c>FSM10</c>), plain <c>.xml</c> or signed CAdES <c>.p7m</c>
/// (binary or base64 text, also nested).
/// </summary>
/// <remarks>
/// <para>Elements are matched by local name, whatever the namespace or prefix (<c>p:</c>, <c>ns2:</c>, none). The XML
/// is read with DTDs prohibited and no resolver, so nothing external is ever loaded. A UTF-8 byte order mark, a
/// missing XML declaration, an ISO-8859-1 or windows-1252 declaration and leading whitespace are tolerated.</para>
/// <para>Amounts use the invariant culture (<c>.</c> separator) and dates <c>yyyy-MM-dd</c>. The reader does not
/// validate the file against the XSD nor recompute totals: it reports what the supplier wrote and rejects only files
/// without the data an import cannot do without (document type, date, number, prices and rates of the lines, the
/// rows of the tax summary, the amounts of withholdings and payments). A missing <c>Divisa</c> is read as
/// <c>EUR</c>; an attachment whose content is not valid base64 is kept with an empty content.</para>
/// <para>For signed files the signature is checked for integrity only (see <see cref="CmsSignedData"/>): no trust chain
/// and no revocation check.</para>
/// <para>Simplified invoices (<c>FSM10</c>): each <c>DatiBeniServizi</c> becomes a line with no quantity whose unit and
/// total price are <c>Importo</c> minus the tax, because there <c>Importo</c> includes the tax. The tax is
/// <c>DatiIVA/Imposta</c> or, when only the rate is given, the tax included in <c>Importo</c> at that rate; the rate is
/// <c>DatiIVA/Aliquota</c> or, when only the tax is given, derived from it. The tax summary groups the lines by rate and
/// nature, the total is the sum of <c>Importo</c> and <c>DatiFatturaRettificata</c> becomes the related invoice.</para>
/// </remarks>
public sealed class FatturaPaReader : IIncomingInvoiceReader
{
/// <summary>The largest file read, as for signed envelopes (50 MB).</summary>
public const int MaxSize = CmsSignedData.MaxSize;
/// <inheritdoc />
public bool CanRead(string fileName, ReadOnlySpan<byte> content) =>
!content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content));
/// <inheritdoc />
public IncomingInvoiceFile Read(string fileName, byte[] content)
{
ArgumentNullException.ThrowIfNull(fileName);
ArgumentNullException.ThrowIfNull(content);
if (content.Length == 0)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is empty.");
}
if (content.Length > MaxSize)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, $"The file is larger than {MaxSize / (1024 * 1024)} MB.");
}
IncomingSignature? signature = null;
var xml = content;
if (!LooksLikeXml(content) && CmsSignedData.LooksLikeCms(content))
{
CmsContent envelope;
try
{
envelope = CmsSignedData.Read(content);
}
catch (CmsFormatException ex)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.SignatureBroken, "The content of the signed file cannot be extracted: " + ex.Message, ex);
}
xml = envelope.Content;
var signer = envelope.Signer;
signature = new IncomingSignature(
envelope.Verified, signer?.Name, signer?.TaxCode, signer?.SigningTime,
signer?.CertificateNotBefore, signer?.CertificateNotAfter, envelope.Problem);
}
if (!LooksLikeXml(xml))
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is neither XML nor a signed envelope.");
}
var root = Parse(xml).Root
?? throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML has no root element.");
return root.Name.LocalName switch
{
"FatturaElettronica" => ReadOrdinary(fileName, root, signature, xml),
"FatturaElettronicaSemplificata" => ReadSimplified(fileName, root, signature, xml),
_ => throw new IncomingInvoiceException(IncomingInvoiceErrors.NotInvoice, $"The XML is a '{root.Name.LocalName}', not an electronic invoice."),
};
}
// --- XML -------------------------------------------------------------------------------------------------------
private static bool LooksLikeXml(ReadOnlySpan<byte> content)
{
if (content.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
{
content = content[3..];
}
else if (content.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]) || content.StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
{
return true;
}
var trimmed = content.TrimStart((ReadOnlySpan<byte>)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']);
return !trimmed.IsEmpty && trimmed[0] == (byte)'<';
}
private static XDocument Parse(byte[] xml)
{
var text = Decode(xml).TrimStart('', ' ', '\t', '\r', '\n');
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
};
try
{
using var reader = XmlReader.Create(new StringReader(text), settings);
return XDocument.Load(reader);
}
catch (XmlException ex)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML is not well formed: " + ex.Message, ex);
}
}
// The text is decoded here, then read from a string: the encoding of the declaration is honoured without the
// reader having to know code pages (windows-1252 is common in files written by older programs).
private static string Decode(byte[] xml)
{
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
{
return new UTF8Encoding(false).GetString(xml, 3, xml.Length - 3);
}
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]))
{
return Encoding.Unicode.GetString(xml, 2, xml.Length - 2);
}
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
{
return Encoding.BigEndianUnicode.GetString(xml, 2, xml.Length - 2);
}
return EncodingOfDeclaration(xml).GetString(xml);
}
private static Encoding EncodingOfDeclaration(byte[] xml)
{
var head = Encoding.ASCII.GetString(xml, 0, Math.Min(xml.Length, 256));
var start = head.IndexOf("<?xml", StringComparison.Ordinal);
var end = start < 0 ? -1 : head.IndexOf("?>", start, StringComparison.Ordinal);
if (end < 0)
{
return new UTF8Encoding(false);
}
var declaration = head[start..end];
var at = declaration.IndexOf("encoding", StringComparison.OrdinalIgnoreCase);
if (at < 0)
{
return new UTF8Encoding(false);
}
var quote = declaration.IndexOfAny(['"', '\''], at);
var close = quote < 0 ? -1 : declaration.IndexOf(declaration[quote], quote + 1);
if (close < 0)
{
return new UTF8Encoding(false);
}
var name = declaration[(quote + 1)..close].Trim().ToUpperInvariant();
return name switch
{
"UTF-8" or "UTF8" => new UTF8Encoding(false),
"ISO-8859-1" or "LATIN1" or "ISO8859-1" => Encoding.Latin1,
"WINDOWS-1252" or "CP1252" => CodePage(1252),
"ISO-8859-15" => CodePage(28605),
_ => new UTF8Encoding(false),
};
}
private static Encoding CodePage(int codePage) =>
CodePagesEncodingProvider.Instance.GetEncoding(codePage) ?? Encoding.Latin1;
// --- Ordinary invoice --------------------------------------------------------------------------------------------
private static IncomingInvoiceFile ReadOrdinary(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
{
var header = El(root, "FatturaElettronicaHeader")
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
var transmission = El(header, "DatiTrasmissione");
var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore.");
var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente.");
var bodies = Els(root, "FatturaElettronicaBody").ToList();
if (bodies.Count == 0)
{
throw Invalid("The invoice has no FatturaElettronicaBody.");
}
return new IncomingInvoiceFile(
fileName,
Text(transmission, "FormatoTrasmissione"),
Text(transmission, "ProgressivoInvio"),
Text(transmission, "CodiceDestinatario"),
ReadParty(supplier),
ReadParty(customer),
bodies.Select(ReadBody).ToList(),
signature,
xml);
}
private static IncomingParty ReadParty(XElement party)
{
var personal = El(party, "DatiAnagrafici");
var identifiers = El(party, "IdentificativiFiscali");
var others = El(party, "AltriDatiIdentificativi");
var vat = El(personal, "IdFiscaleIVA") ?? El(identifiers, "IdFiscaleIVA") ?? El(party, "IdFiscaleIVA");
var names = El(personal, "Anagrafica") ?? others ?? party;
var office = El(party, "Sede") ?? El(others, "Sede");
var register = El(party, "IscrizioneREA");
var contacts = El(party, "Contatti");
return new IncomingParty(
Text(vat, "IdPaese"),
Text(vat, "IdCodice"),
Text(personal, "CodiceFiscale") ?? Text(identifiers, "CodiceFiscale") ?? Text(party, "CodiceFiscale"),
Text(names, "Denominazione"),
Text(names, "Nome"),
Text(names, "Cognome"),
Text(office, "Indirizzo"),
Text(office, "NumeroCivico"),
Text(office, "CAP"),
Text(office, "Comune"),
Text(office, "Provincia"),
Text(office, "Nazione"),
Text(personal, "RegimeFiscale") ?? Text(party, "RegimeFiscale"),
Text(contacts, "Email"),
Text(contacts, "Telefono"),
Text(register, "Ufficio"),
Text(register, "NumeroREA"));
}
private static IncomingInvoice ReadBody(XElement body, int index)
{
var general = El(body, "DatiGenerali");
var document = El(general, "DatiGeneraliDocumento")
?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento.");
var goods = El(body, "DatiBeniServizi");
var stamp = El(document, "DatiBollo");
return new IncomingInvoice(
Required(document, "TipoDocumento", index),
Text(document, "Divisa") ?? "EUR",
RequiredDate(document, "Data", index),
Required(document, "Numero", index),
OptionalDecimal(document, "ImportoTotaleDocumento"),
OptionalDecimal(document, "Arrotondamento"),
Els(document, "Causale").Select(c => c.Value.Trim()).Where(c => c.Length > 0).ToList(),
Flag(document, "Art73"),
Els(document, "DatiRitenuta").Select(w => new IncomingWithholding(
Required(w, "TipoRitenuta", index),
RequiredDecimal(w, "ImportoRitenuta", index),
RequiredDecimal(w, "AliquotaRitenuta", index),
Text(w, "CausalePagamento"))).ToList(),
stamp is null ? null : new IncomingStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m),
Els(document, "DatiCassaPrevidenziale").Select(s => new IncomingSocialSecurity(
Required(s, "TipoCassa", index),
RequiredDecimal(s, "AlCassa", index),
RequiredDecimal(s, "ImportoContributoCassa", index),
OptionalDecimal(s, "ImponibileCassa"),
RequiredDecimal(s, "AliquotaIVA", index),
Flag(s, "Ritenuta"),
Text(s, "Natura"))).ToList(),
ReadDiscounts(document),
ReadReferences(general, "DatiOrdineAcquisto"),
ReadReferences(general, "DatiContratto"),
ReadReferences(general, "DatiFattureCollegate"),
Els(general, "DatiDDT").Select(d => new IncomingReference(
Text(d, "NumeroDDT"), OptionalDate(d, "DataDDT"), LineNumbers(d), null, null)).ToList(),
Els(goods, "DettaglioLinee").Select((l, i) => ReadLine(l, i, index)).ToList(),
Els(goods, "DatiRiepilogo").Select(r => new IncomingTaxSummary(
RequiredDecimal(r, "AliquotaIVA", index),
Text(r, "Natura"),
RequiredDecimal(r, "ImponibileImporto", index),
RequiredDecimal(r, "Imposta", index),
Text(r, "EsigibilitaIVA"),
Text(r, "RiferimentoNormativo"),
OptionalDecimal(r, "SpeseAccessorie"),
OptionalDecimal(r, "Arrotondamento"))).ToList(),
ReadPayments(body, index),
ReadAttachments(body));
}
private static IncomingLine ReadLine(XElement line, int position, int index) => new(
OptionalInt(line, "NumeroLinea") ?? position + 1,
Els(line, "CodiceArticolo")
.Select(c => new IncomingItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty))
.Where(c => c.Value.Length > 0)
.ToList(),
Text(line, "Descrizione") ?? string.Empty,
OptionalDecimal(line, "Quantita"),
Text(line, "UnitaMisura"),
RequiredDecimal(line, "PrezzoUnitario", index),
RequiredDecimal(line, "PrezzoTotale", index),
RequiredDecimal(line, "AliquotaIVA", index),
Text(line, "Natura"),
ReadDiscounts(line),
Flag(line, "Ritenuta"),
Text(line, "TipoCessionePrestazione"),
OptionalDate(line, "DataInizioPeriodo"),
OptionalDate(line, "DataFinePeriodo"),
Text(line, "RiferimentoAmministrazione"));
private static List<IncomingDiscount> ReadDiscounts(XElement? parent) =>
Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount(
string.Equals(Text(d, "Tipo"), "MG", StringComparison.OrdinalIgnoreCase),
OptionalDecimal(d, "Percentuale"),
OptionalDecimal(d, "Importo"))).ToList();
private static List<IncomingReference> ReadReferences(XElement? general, string name) =>
Els(general, name).Select(r => new IncomingReference(
Text(r, "IdDocumento"), OptionalDate(r, "Data"), LineNumbers(r), Text(r, "CodiceCIG"), Text(r, "CodiceCUP"))).ToList();
private static List<int> LineNumbers(XElement reference) =>
Els(reference, "RiferimentoNumeroLinea")
.Select(n => int.TryParse(n.Value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : 0)
.Where(n => n > 0)
.ToList();
private static List<IncomingPayment> ReadPayments(XElement body, int index) =>
Els(body, "DatiPagamento").SelectMany(p =>
{
var conditions = Text(p, "CondizioniPagamento");
return Els(p, "DettaglioPagamento").Select(d => new IncomingPayment(
conditions,
Text(d, "ModalitaPagamento"),
OptionalDate(d, "DataScadenzaPagamento"),
RequiredDecimal(d, "ImportoPagamento", index),
Text(d, "IBAN"),
Text(d, "BIC"),
Text(d, "Beneficiario")));
}).ToList();
private static List<IncomingAttachment> ReadAttachments(XElement body) =>
Els(body, "Allegati").Select(a => new IncomingAttachment(
Text(a, "NomeAttachment") ?? "allegato",
Text(a, "FormatoAttachment"),
Text(a, "DescrizioneAttachment"),
DecodeAttachment(El(a, "Attachment")?.Value))).ToList();
private static byte[] DecodeAttachment(string? base64)
{
if (string.IsNullOrWhiteSpace(base64))
{
return [];
}
var compact = new StringBuilder(base64.Length);
foreach (var c in base64)
{
if (!char.IsWhiteSpace(c))
{
compact.Append(c);
}
}
var text = compact.ToString();
var buffer = new byte[text.Length / 4 * 3 + 3];
return Convert.TryFromBase64String(text, buffer, out var written) ? buffer[..written] : [];
}
// --- Simplified invoice ------------------------------------------------------------------------------------------
private static IncomingInvoiceFile ReadSimplified(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
{
var header = El(root, "FatturaElettronicaHeader")
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
var transmission = El(header, "DatiTrasmissione");
var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore.");
var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente.");
var bodies = Els(root, "FatturaElettronicaBody").ToList();
if (bodies.Count == 0)
{
throw Invalid("The invoice has no FatturaElettronicaBody.");
}
return new IncomingInvoiceFile(
fileName,
Text(transmission, "FormatoTrasmissione"),
Text(transmission, "ProgressivoInvio"),
Text(transmission, "CodiceDestinatario"),
ReadParty(supplier),
ReadParty(customer),
bodies.Select(ReadSimplifiedBody).ToList(),
signature,
xml);
}
private static IncomingInvoice ReadSimplifiedBody(XElement body, int index)
{
var general = El(body, "DatiGenerali");
var document = El(general, "DatiGeneraliDocumento")
?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento.");
var lines = Els(body, "DatiBeniServizi").Select((l, i) => ReadSimplifiedLine(l, i, index)).ToList();
var gross = Els(body, "DatiBeniServizi").Sum(l => RequiredDecimal(l, "Importo", index));
var summary = lines
.GroupBy(l => (l.TaxRate, l.Nature))
.Select(g => new IncomingTaxSummary(
g.Key.TaxRate, g.Key.Nature, g.Sum(l => l.TotalPrice), g.Sum(l => l.Tax), null,
g.Select(l => l.LegalReference).FirstOrDefault(r => r is not null), null, null))
.ToList();
var corrected = Els(general, "DatiFatturaRettificata")
.Select(r => new IncomingReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null))
.ToList();
return new IncomingInvoice(
Required(document, "TipoDocumento", index),
Text(document, "Divisa") ?? "EUR",
RequiredDate(document, "Data", index),
Required(document, "Numero", index),
gross,
null,
[],
false,
[],
Flag(document, "BolloVirtuale") ? new IncomingStampDuty(true, 0m) : null,
[],
[],
[],
[],
corrected,
[],
lines.Select(l => l.Line).ToList(),
summary,
[],
ReadAttachments(body));
}
private static SimplifiedLine ReadSimplifiedLine(XElement line, int position, int index)
{
var gross = RequiredDecimal(line, "Importo", index);
var vat = El(line, "DatiIVA");
var tax = OptionalDecimal(vat, "Imposta");
var rate = OptionalDecimal(vat, "Aliquota");
tax ??= rate is { } r && r != 0m ? Math.Round(gross * r / (100m + r), 2, MidpointRounding.AwayFromZero) : 0m;
var net = gross - tax.Value;
rate ??= net != 0m ? Math.Round(tax.Value / net * 100m, 2, MidpointRounding.AwayFromZero) : 0m;
var nature = Text(line, "Natura");
return new SimplifiedLine(
new IncomingLine(position + 1, [], Text(line, "Descrizione") ?? string.Empty, null, null, net, net, rate.Value, nature,
[], false, null, null, null, null),
tax.Value,
Text(line, "RiferimentoNormativo"));
}
private sealed record SimplifiedLine(IncomingLine Line, decimal Tax, string? LegalReference)
{
public decimal TaxRate => Line.TaxRate;
public string? Nature => Line.Nature;
public decimal TotalPrice => Line.TotalPrice;
}
// --- Helpers -----------------------------------------------------------------------------------------------------
private static XElement? El(XElement? parent, string localName) =>
parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName);
private static IEnumerable<XElement> Els(XElement? parent, string localName) =>
parent is null ? [] : parent.Elements().Where(e => e.Name.LocalName == localName);
private static string? Text(XElement? parent, string localName)
{
var value = El(parent, localName)?.Value.Trim();
return string.IsNullOrEmpty(value) ? null : value;
}
private static bool Flag(XElement? parent, string localName) =>
string.Equals(Text(parent, localName), "SI", StringComparison.OrdinalIgnoreCase);
private static string Required(XElement parent, string localName, int index) =>
Text(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing.");
private static decimal? OptionalDecimal(XElement? parent, string localName) =>
Text(parent, localName) is { } text && decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)
? value
: null;
private static decimal RequiredDecimal(XElement parent, string localName, int index) =>
OptionalDecimal(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a number.");
private static int? OptionalInt(XElement parent, string localName) =>
Text(parent, localName) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null;
private static DateOnly? OptionalDate(XElement? parent, string localName)
{
var text = Text(parent, localName);
if (text is null)
{
return null;
}
// xs:date may carry a time zone (2026-03-15+01:00): the day is what counts.
var day = text.Length > 10 ? text[..10] : text;
return DateOnly.TryParseExact(day, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) ? date : null;
}
private static DateOnly RequiredDate(XElement parent, string localName, int index) =>
OptionalDate(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a date.");
private static IncomingInvoiceException Invalid(string message) => new(IncomingInvoiceErrors.Invalid, message);
}
@@ -0,0 +1,22 @@
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// The types of a received FatturaPA and the purchase document that registers them: invoices, deposits, fee notes,
/// debit notes and deferred invoices (TD01, TD02, TD03, TD05, TD06, TD24, TD25, TD26, TD27) as supplier invoice FF,
/// credit notes (TD04, TD08) as supplier credit note NCF. The self-invoice types TD16-TD23, TD28 and TD29 are issued by
/// the company itself and are not purchases.
/// </summary>
public sealed class IncomingInvoiceRulesIt : IIncomingInvoiceRules
{
private static readonly HashSet<string> Invoices = new(StringComparer.Ordinal) { "TD01", "TD02", "TD03", "TD05", "TD06", "TD24", "TD25", "TD26", "TD27" };
private static readonly HashSet<string> CreditNotes = new(StringComparer.Ordinal) { "TD04", "TD08" };
/// <inheritdoc />
public string? DocumentTypeCode(string formatType)
{
var type = formatType?.Trim().ToUpperInvariant() ?? string.Empty;
return Invoices.Contains(type) ? "FF" : CreditNotes.Contains(type) ? "NCF" : null;
}
}
@@ -50,7 +50,7 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null, DocumentKind.Quotation),
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null, DocumentKind.SalesOrder),
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null, DocumentKind.DeliveryNote),
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01", DocumentKind.ImmediateInvoice),
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.ImmediateInvoice),
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.AccompanyingInvoice),
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24", DocumentKind.DeferredInvoice),
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02", DocumentKind.DownPaymentInvoice),
@@ -62,10 +62,16 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17", DocumentKind.SelfInvoice),
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18", DocumentKind.SelfInvoice),
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19", DocumentKind.SelfInvoice),
new("AF20", "Autofattura per regolarizzazione", NumeratorKind.SalesInvoice, "AUT", null, "TD20", DocumentKind.SelfInvoice),
new("AF21", "Autofattura per splafonamento", NumeratorKind.SalesInvoice, "AUT", null, "TD21", DocumentKind.SelfInvoice),
new("AF22", "Estrazione beni da deposito IVA", NumeratorKind.SalesInvoice, "AUT", null, "TD22", DocumentKind.SelfInvoice),
new("AF23", "Estrazione beni da deposito IVA con versamento", NumeratorKind.SalesInvoice, "AUT", null, "TD23", DocumentKind.SelfInvoice),
new("AF28", "Acquisti da San Marino con IVA", NumeratorKind.SalesInvoice, "AUT", null, "TD28", DocumentKind.SelfInvoice),
new("AF29", "Comunicazione per omessa o irregolare fatturazione", NumeratorKind.SalesInvoice, "AUT", null, "TD29", DocumentKind.SelfInvoice),
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null, DocumentKind.PurchaseOrder),
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null, DocumentKind.PurchaseDeliveryNote),
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseInvoice),
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseCreditNote),
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", "CAR", null, DocumentKind.PurchaseInvoice),
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", "RESF", null, DocumentKind.PurchaseCreditNote),
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null, DocumentKind.InventoryEntry),
];
}
@@ -0,0 +1,256 @@
using Khaemhat.Core.Accounting;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// The Italian ledger of the base data (SPEC §11.7, issue #62, ADR 0036): a chart of accounts for small and medium
/// companies in three levels (mastro, conto, sottoconto) linked to the lines of the financial statements of art.
/// 2424-2425 of the Civil Code, the VAT registers, the journal templates (causali contabili) and the template of each
/// document type. The chart is the embedded file <c>Data/piano-dei-conti.csv</c>.
/// </summary>
public sealed class ItalianLedgerTemplate : ILedgerTemplate
{
/// <summary>The account of trade receivables from Italian customers.</summary>
public const string Customers = "05.01.001";
/// <summary>The account of trade payables to Italian suppliers.</summary>
public const string Suppliers = "14.01.001";
/// <summary>VAT on purchases.</summary>
public const string PurchaseVat = "06.02.001";
/// <summary>VAT on sales.</summary>
public const string SalesVat = "15.01.001";
/// <summary>The VAT settlement account.</summary>
public const string VatSettlement = "15.01.002";
/// <summary>The main bank account.</summary>
public const string Bank = "07.01.001";
/// <summary>Cash.</summary>
public const string Cash = "07.02.001";
/// <summary>Sales of goods.</summary>
public const string Revenue = "30.01.001";
/// <summary>Purchases of goods.</summary>
public const string Cost = "20.01.001";
/// <summary>Withholdings operated on fees of self-employed workers, to pay.</summary>
public const string WithholdingPayable = "15.02.001";
/// <summary>Withholdings suffered on the company's fees.</summary>
public const string WithholdingCredit = "06.03.001";
/// <summary>Social security charged on fees.</summary>
public const string SocialSecurity = "31.01.003";
/// <summary>Stamp duty charged to customers.</summary>
public const string StampDutyCharged = "31.01.002";
/// <summary>Stamp duty as a cost.</summary>
public const string StampDutyCost = "27.01.002";
/// <summary>Rounding and allowances.</summary>
public const string Rounding = "27.01.004";
/// <summary>The interest of quarterly VAT payers.</summary>
public const string VatInterest = "28.01.003";
private readonly Lazy<IReadOnlyList<AccountTemplate>> _accounts = new(ReadAccounts);
/// <inheritdoc />
public string Name => "PMI standard";
/// <inheritdoc />
public IReadOnlyList<AccountTemplate> Accounts => _accounts.Value;
/// <inheritdoc />
public IReadOnlyList<VatRegisterTemplate> VatRegisters { get; } =
[
new("VEN1", "Registro fatture emesse", VatRegisterKind.Sales),
new("ACQ1", "Registro fatture acquisti", VatRegisterKind.Purchases),
new("CORR", "Registro dei corrispettivi", VatRegisterKind.Receipts),
new("VEN-RC", "Registro fatture emesse - autofatture e integrazioni", VatRegisterKind.Sales, ReverseCharge: true),
new("ACQ-RC", "Registro fatture acquisti - autofatture e integrazioni", VatRegisterKind.Purchases, ReverseCharge: true),
];
/// <inheritdoc />
public IReadOnlyList<JournalTemplateTemplate> JournalTemplates { get; } = BuildTemplates();
/// <inheritdoc />
public IReadOnlyList<DocumentPostingTemplate> DocumentPostings { get; } = BuildDocumentPostings();
/// <inheritdoc />
public string? AccountOf(PostingRole role) => role switch
{
PostingRole.Customer => Customers,
PostingRole.Supplier => Suppliers,
PostingRole.Revenue => Revenue,
PostingRole.Cost => Cost,
PostingRole.SalesVat or PostingRole.SplitPaymentVat => SalesVat,
PostingRole.PurchaseVat => PurchaseVat,
PostingRole.Bank => Bank,
PostingRole.Cash => Cash,
PostingRole.WithholdingPayable => WithholdingPayable,
PostingRole.WithholdingCredit => WithholdingCredit,
PostingRole.SocialSecurity => SocialSecurity,
PostingRole.StampDuty => StampDutyCost,
PostingRole.Rounding => Rounding,
PostingRole.VatSettlement => VatSettlement,
_ => null,
};
private static List<JournalTemplateTemplate> BuildTemplates()
{
static JournalTemplateLineTemplate L(PostingRole role, AccountSide side, string? account = null, string? description = null) =>
new(role, side, account, description);
return
[
new("FV", "Fattura di vendita", JournalArea.Sales, "VEN1", OpensItems: true, Reverses: false,
[
L(PostingRole.Customer, AccountSide.Debit, Customers),
L(PostingRole.Revenue, AccountSide.Credit, Revenue),
L(PostingRole.SocialSecurity, AccountSide.Credit, SocialSecurity),
L(PostingRole.StampDuty, AccountSide.Credit, StampDutyCharged),
L(PostingRole.SalesVat, AccountSide.Credit, SalesVat),
]),
new("NCV", "Nota di credito a cliente", JournalArea.Sales, "VEN1", OpensItems: true, Reverses: true,
[
L(PostingRole.Customer, AccountSide.Debit, Customers),
L(PostingRole.Revenue, AccountSide.Credit, "30.02.001"),
L(PostingRole.SocialSecurity, AccountSide.Credit, SocialSecurity),
L(PostingRole.StampDuty, AccountSide.Credit, StampDutyCharged),
L(PostingRole.SalesVat, AccountSide.Credit, SalesVat),
]),
new("FA", "Fattura di acquisto", JournalArea.Purchases, "ACQ1", OpensItems: true, Reverses: false,
[
L(PostingRole.Supplier, AccountSide.Credit, Suppliers),
L(PostingRole.Cost, AccountSide.Debit, Cost),
L(PostingRole.StampDuty, AccountSide.Debit, StampDutyCost),
L(PostingRole.PurchaseVat, AccountSide.Debit, PurchaseVat),
]),
new("NCA", "Nota di credito da fornitore", JournalArea.Purchases, "ACQ1", OpensItems: true, Reverses: true,
[
L(PostingRole.Supplier, AccountSide.Credit, Suppliers),
L(PostingRole.Cost, AccountSide.Debit, "20.02.001"),
L(PostingRole.StampDuty, AccountSide.Debit, StampDutyCost),
L(PostingRole.PurchaseVat, AccountSide.Debit, PurchaseVat),
]),
new("AFRC", "Autofattura e integrazione reverse charge", JournalArea.Purchases, "VEN-RC", OpensItems: false, Reverses: false,
[
L(PostingRole.PurchaseVat, AccountSide.Debit, PurchaseVat),
L(PostingRole.Cost, AccountSide.Debit, "27.01.003", "IVA indetraibile"),
L(PostingRole.SalesVat, AccountSide.Credit, SalesVat),
]),
new("CORR", "Corrispettivi giornalieri", JournalArea.Sales, "CORR", OpensItems: false, Reverses: false,
[
L(PostingRole.Cash, AccountSide.Debit, Cash),
L(PostingRole.Revenue, AccountSide.Credit, Revenue),
L(PostingRole.SalesVat, AccountSide.Credit, SalesVat),
]),
new("INC", "Incasso da cliente", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
[
L(PostingRole.Bank, AccountSide.Debit, Bank),
L(PostingRole.Customer, AccountSide.Credit, Customers),
]),
new("PAG", "Pagamento a fornitore", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
[
L(PostingRole.Supplier, AccountSide.Debit, Suppliers),
L(PostingRole.Bank, AccountSide.Credit, Bank),
]),
new("RIT", "Ritenuta d'acconto operata", JournalArea.Taxes, null, OpensItems: false, Reverses: false,
[
L(PostingRole.Supplier, AccountSide.Debit, Suppliers),
L(PostingRole.WithholdingPayable, AccountSide.Credit, WithholdingPayable),
]),
new("RITS", "Ritenuta d'acconto subita", JournalArea.Taxes, null, OpensItems: false, Reverses: false,
[
L(PostingRole.WithholdingCredit, AccountSide.Debit, WithholdingCredit),
L(PostingRole.Customer, AccountSide.Credit, Customers),
]),
new("LIQ", "Liquidazione IVA periodica", JournalArea.Taxes, null, OpensItems: false, Reverses: false,
[
L(PostingRole.SalesVat, AccountSide.Debit, SalesVat),
L(PostingRole.PurchaseVat, AccountSide.Credit, PurchaseVat),
L(PostingRole.Account, AccountSide.Debit, VatInterest, "Interessi trimestrali"),
L(PostingRole.Cost, AccountSide.Debit, "27.01.003", "IVA indetraibile da pro rata"),
L(PostingRole.VatSettlement, AccountSide.Credit, VatSettlement),
]),
new("F24", "Versamento con modello F24", JournalArea.Taxes, null, OpensItems: false, Reverses: false,
[
L(PostingRole.VatSettlement, AccountSide.Debit, VatSettlement),
L(PostingRole.WithholdingPayable, AccountSide.Debit, WithholdingPayable),
L(PostingRole.Account, AccountSide.Debit, StampDutyCost, "Imposta di bollo"),
L(PostingRole.Bank, AccountSide.Credit, Bank),
]),
new("GIRO", "Giroconto", JournalArea.General, null, OpensItems: false, Reverses: false,
[
L(PostingRole.Account, AccountSide.Debit),
L(PostingRole.Account, AccountSide.Credit),
]),
new("SPB", "Spese e commissioni bancarie", JournalArea.Treasury, null, OpensItems: false, Reverses: false,
[
L(PostingRole.Account, AccountSide.Debit, "21.03.011"),
L(PostingRole.Bank, AccountSide.Credit, Bank),
]),
new("STO", "Storno di scrittura", JournalArea.General, null, OpensItems: false, Reverses: true, []),
];
}
private static List<DocumentPostingTemplate> BuildDocumentPostings()
{
var postings = new List<DocumentPostingTemplate>();
foreach (var code in new[] { "FI", "FA", "FD", "FACC", "ND", "PAR" })
{
postings.Add(new(code, "FV", "VEN1"));
}
postings.Add(new("NC", "NCV", "VEN1"));
postings.Add(new("FF", "FA", "ACQ1"));
postings.Add(new("NCF", "NCA", "ACQ1"));
for (var n = 16; n <= 29; n++)
{
postings.Add(new("AF" + n.ToString(System.Globalization.CultureInfo.InvariantCulture), "AFRC", "VEN-RC"));
}
return postings;
}
private static IReadOnlyList<AccountTemplate> ReadAccounts()
{
using var stream = typeof(ItalianLedgerTemplate).Assembly.GetManifestResourceStream("Khaemhat.Fiscal.Italy.Data.piano-dei-conti.csv")
?? throw new InvalidOperationException("The file piano-dei-conti.csv is missing from the assembly.");
using var reader = new StreamReader(stream);
return [.. CsvReader.Parse(reader.ReadToEnd(), ';').Skip(1).Where(l => l.Count >= 3 && l[0].Length > 0).Select(ToAccount)];
}
private static AccountTemplate ToAccount(IReadOnlyList<string> l)
{
string Field(int i) => l.Count > i ? l[i].Trim() : string.Empty;
var nature = Field(2) switch
{
"A" => AccountNature.Asset,
"P" => AccountNature.Liability,
"C" => AccountNature.Cost,
"R" => AccountNature.Revenue,
_ => AccountNature.Memorandum,
};
var type = Field(3) switch
{
"CL" => AccountType.Customers,
"FO" => AccountType.Suppliers,
"BA" => AccountType.Bank,
"CA" => AccountType.Cash,
"IV" => AccountType.Vat,
"ER" => AccountType.Tax,
_ => AccountType.Generic,
};
var line = Field(4);
return new AccountTemplate(Field(0), Field(1), nature, type, line.Length == 0 ? null : line, Field(5) == "S", Field(6) == "S");
}
}
+35
View File
@@ -115,6 +115,40 @@ public sealed class F24Exporter : ITaxPaymentFormExporter
return (2520 + quarter).ToString(System.Globalization.CultureInfo.InvariantCulture);
}
/// <inheritdoc />
public string FileName(TaxPaymentForm form)
{
ArgumentNullException.ThrowIfNull(form);
return $"F24_{form.TaxCode}_{form.DueDate.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)}.csv";
}
/// <inheritdoc />
/// <remarks>
/// A semicolon file in UTF-8: a header line with due date, tax code and name, then one line per code of the Erario
/// section (sezione <c>ER</c>) with code, installment or month, reference year, debit and credit with a comma, and the
/// description; the last line is the balance. Intermediaries and home banking import it or copy it into the form.
/// </remarks>
public byte[] Export(TaxPaymentForm form)
{
ArgumentNullException.ThrowIfNull(form);
var culture = System.Globalization.CultureInfo.InvariantCulture;
static string Amount(decimal value) =>
value == 0m ? string.Empty : value.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture).Replace('.', ',');
static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' ').Replace('\r', ' ');
var text = new System.Text.StringBuilder();
text.Append("F24;").Append(form.DueDate.ToString("dd/MM/yyyy", culture)).Append(';').Append(form.TaxCode).Append(';').Append(Clean(form.Name)).Append('\n');
text.Append("Sezione;Codice tributo;Rateazione/mese;Anno di riferimento;Importo a debito;Importo a credito;Descrizione\n");
foreach (var line in form.Lines)
{
text.Append("ER;").Append(line.Code).Append(';').Append(line.Period ?? string.Empty).Append(';')
.Append(line.Year.ToString(culture)).Append(';').Append(Amount(line.Debit)).Append(';').Append(Amount(line.Credit)).Append(';')
.Append(Clean(line.Description)).Append('\n');
}
text.Append("Saldo;;;;").Append(form.Balance.ToString("0.00", culture).Replace('.', ',')).Append(";;\n");
return new System.Text.UTF8Encoding(false).GetBytes(text.ToString());
}
private static List<TaxPaymentCode> BuildCodes()
{
string[] months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
@@ -135,6 +169,7 @@ public sealed class F24Exporter : ITaxPaymentFormExporter
codes.Add(new("1040", "Ritenute su redditi di lavoro autonomo"));
codes.Add(new("1038", "Ritenute su provvigioni"));
codes.Add(new("1019", "Ritenute del 4% operate dal condominio a titolo di acconto IRPEF"));
codes.Add(new("1001", "Ritenute su retribuzioni, pensioni, trasferte, mensilita' aggiuntive"));
for (var q = 1; q <= 4; q++)
{
codes.Add(new((2520 + q).ToString(System.Globalization.CultureInfo.InvariantCulture), $"Imposta di bollo sulle fatture elettroniche, {q}° trimestre"));
@@ -15,12 +15,18 @@ public sealed class ItalyFiscalPack : FiscalPackBase
public ItalyFiscalPack()
{
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
AddFeature<ITaxIdentifierRules>(new ItalianTaxIdentifierRules());
AddFeature<IBaseTablesTemplate>(new ItalianBaseTables());
AddFeature<IPlaceDirectory>(new ItalianPlaces());
AddFeature<ILedgerTemplate>(new ItalianLedgerTemplate());
AddFeature<IVatSettlementRules>(new VatSettlementRulesIt());
AddFeature<IPeriodicVatReturnWriter>(new LipeWriter());
// ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026).
AddFeature<IBankDirectory>(new ItalianBankDirectory([]));
@@ -0,0 +1,59 @@
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Italian self-invoices and integrations (provvedimento AdE 99922/2020, specifiche FatturaPA 1.9): TD16 integrates a
/// domestic reverse charge (natures N6.x), TD17 the purchase of services from abroad, TD18 of goods from another member
/// state, TD19 of goods located in Italy from a non-resident (art. 17 c.2). Integrations go to the exchange system by
/// the 15th of the month after the receipt; regularisations (TD20) and communications (TD29) within 90 days.
/// </summary>
public sealed class SelfInvoiceRulesIt : ISelfInvoiceRules
{
/// <inheritdoc />
public IReadOnlyList<string> DocumentTypeCodes { get; } = ["AF16", "AF17", "AF18", "AF19", "AF20", "AF21", "AF22", "AF23", "AF28", "AF29"];
/// <inheritdoc />
public string OrdinaryTaxCode => "22";
/// <inheritdoc />
public SelfInvoiceAdvice? Advise(SelfInvoiceCase input)
{
ArgumentNullException.ThrowIfNull(input);
var domestic = string.Equals(input.SupplierCountry, "IT", StringComparison.OrdinalIgnoreCase);
if (domestic)
{
if (input.Natures.Any(n => n.StartsWith("N6", StringComparison.Ordinal)))
{
return Advice("AF16", "Inversione contabile interna (art. 17 c.6 e 74 c.7-8 DPR 633/72): integrazione della fattura del fornitore.", input.Received);
}
return null;
}
if (string.Equals(input.SupplierCountry, "SM", StringComparison.OrdinalIgnoreCase))
{
return input.Natures.Count == 0
? Advice("AF28", "Acquisto da San Marino con IVA addebitata in fattura.", input.Received)
: null;
}
if (!input.Goods)
{
return Advice("AF17", "Acquisto di servizi da un fornitore estero (art. 17 c.2 e 7-ter DPR 633/72).", input.Received);
}
return input.SupplierInEu
? Advice("AF18", "Acquisto intracomunitario di beni (art. 46-47 DL 331/93).", input.Received)
: Advice("AF19", "Acquisto di beni già in Italia da un soggetto non residente (art. 17 c.2 DPR 633/72).", input.Received);
}
/// <inheritdoc />
public DateOnly Deadline(string documentTypeCode, DateOnly received) => documentTypeCode switch
{
"AF20" or "AF29" => received.AddDays(90),
_ => new DateOnly(received.Year, received.Month, 15).AddMonths(1),
};
private SelfInvoiceAdvice Advice(string code, string reason, DateOnly received) => new(code, reason, Deadline(code, received));
}
@@ -0,0 +1,189 @@
using System.Globalization;
using System.Text;
using System.Xml;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// The Italian rules of the periodic VAT settlement and of the other payments of the ledger (issue #65, ADR 0037):
/// <list type="bullet">
/// <item>payments below 25.82 euro are not made and move to the next period (art. 1 c. 4 DPR 100/1998);</item>
/// <item>the December advance is 88% of the base, not due below 103.29 euro, paid by 27 December (L. 405/1990);</item>
/// <item>the last quarter of quarterly payers is paid with the annual return, code 6099 installment <c>0101</c>;</item>
/// <item>withholdings are paid by the 16th of the month after the payment of the fee;</item>
/// <item>the stamp duty of e-invoices of a quarter by 31 May, 30 September, 30 November and 28 February (DM 17/06/2014);</item>
/// <item>the communication of the settlements (LIPE) by 31 May, 16 September, 30 November and the end of February.</item>
/// </list>
/// Deadlines on Saturdays, Sundays and holidays move to the next working day; payments due from 1 to 20 August to the 20th.
/// </summary>
public sealed class VatSettlementRulesIt : IVatSettlementRules
{
private readonly ItalianFiscalCalendar _calendar = new();
/// <inheritdoc />
public decimal MinimumPayment => 25.82m;
/// <inheritdoc />
public decimal AdvancePercent => 88m;
/// <inheritdoc />
public decimal AdvanceMinimum => 103.29m;
/// <inheritdoc />
public string PaymentCode(TaxPeriod period)
{
ArgumentNullException.ThrowIfNull(period);
return period.Periodicity == VatPeriodicity.Monthly
? (6000 + period.Number).ToString(CultureInfo.InvariantCulture)
: period.Number == 4 ? "6099" : (6030 + period.Number).ToString(CultureInfo.InvariantCulture);
}
/// <inheritdoc />
public string? PaymentPeriod(TaxPeriod period)
{
ArgumentNullException.ThrowIfNull(period);
return period.Periodicity == VatPeriodicity.Quarterly && period.Number == 4 ? "0101" : null;
}
/// <inheritdoc />
public DateOnly AdvanceDue(int year) => _calendar.NextWorkingDay(new DateOnly(year, 12, 27));
/// <inheritdoc />
public DateOnly WithholdingDue(int year, int month) => Payment(new DateOnly(year, month, 16).AddMonths(1));
/// <inheritdoc />
public DateOnly StampDutyDue(int year, int quarter) => Payment(quarter switch
{
1 => new DateOnly(year, 5, 31),
2 => new DateOnly(year, 9, 30),
3 => new DateOnly(year, 11, 30),
4 => new DateOnly(year + 1, 2, 28),
_ => throw new ArgumentOutOfRangeException(nameof(quarter)),
});
/// <inheritdoc />
public DateOnly PeriodicReturnDue(int year, int quarter) => _calendar.NextWorkingDay(quarter switch
{
1 => new DateOnly(year, 5, 31),
2 => new DateOnly(year, 9, 16),
3 => new DateOnly(year, 11, 30),
4 => new DateOnly(year + 1, 3, 1).AddDays(-1),
_ => throw new ArgumentOutOfRangeException(nameof(quarter)),
});
private DateOnly Payment(DateOnly due) =>
_calendar.NextWorkingDay(due.Month == 8 && due.Day <= 20 ? new DateOnly(due.Year, 8, 20) : due);
}
/// <summary>
/// The communication of the periodic VAT settlements (LIPE, art. 21-bis DL 78/2010) in the XML of the technical
/// specifications <c>IVP18</c> of the Agenzia delle Entrate: one <c>Modulo</c> per month or quarter, amounts with a comma
/// and two decimals. The file is meant for the intermediary or for the web services of the Agenzia, which sign and send it.
/// </summary>
public sealed class LipeWriter : IPeriodicVatReturnWriter
{
/// <summary>The namespace of the schema.</summary>
public const string Namespace = "urn:www.agenziaentrate.gov.it:specificheTecniche:sco:ivp";
/// <inheritdoc />
public string Name => "LIPE";
/// <inheritdoc />
public string FileName(PeriodicVatReturn data)
{
ArgumentNullException.ThrowIfNull(data);
return string.Create(CultureInfo.InvariantCulture, $"IT{data.TaxCode}_LI_{data.Year}_T{data.Quarter}.xml");
}
/// <inheritdoc />
public byte[] Write(PeriodicVatReturn data)
{
ArgumentNullException.ThrowIfNull(data);
var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = true };
using var buffer = new MemoryStream();
using (var xml = XmlWriter.Create(buffer, settings))
{
xml.WriteStartDocument();
xml.WriteStartElement("iv", "Fornitura", Namespace);
xml.WriteStartElement("iv", "Intestazione", Namespace);
Element(xml, "CodiceFornitura", "IVP18");
if (data.DeclarantTaxCode is { Length: > 0 } declarant)
{
Element(xml, "CodiceFiscaleDichiarante", declarant);
Element(xml, "CodiceCarica", "1");
}
xml.WriteEndElement();
xml.WriteStartElement("iv", "Comunicazione", Namespace);
xml.WriteAttributeString("identificativo", "00001");
xml.WriteStartElement("iv", "Frontespizio", Namespace);
Element(xml, "CodiceFiscale", data.TaxCode);
Element(xml, "AnnoImposta", data.Year.ToString(CultureInfo.InvariantCulture));
Element(xml, "PartitaIVA", data.VatNumber);
if (data.DeclarantTaxCode is { Length: > 0 } signer)
{
Element(xml, "CFDichiarante", signer);
Element(xml, "CodiceCaricaDichiarante", "1");
}
Element(xml, "FirmaDichiarazione", "1");
if (data.IntermediaryTaxCode is { Length: > 0 } intermediary)
{
Element(xml, "CFIntermediario", intermediary);
Element(xml, "ImpegnoPresentazione", "1");
Element(xml, "DataImpegno", data.CommitmentDate.ToString("ddMMyyyy", CultureInfo.InvariantCulture));
Element(xml, "FirmaIntermediario", "1");
}
xml.WriteEndElement();
xml.WriteStartElement("iv", "DatiContabili", Namespace);
var number = 0;
foreach (var module in data.Modules)
{
xml.WriteStartElement("iv", "Modulo", Namespace);
Element(xml, "NumeroModulo", (++number).ToString(CultureInfo.InvariantCulture));
Element(
xml,
module.Period.Periodicity == VatPeriodicity.Monthly ? "Mese" : "Trimestre",
module.Period.Number.ToString(CultureInfo.InvariantCulture));
Amount(xml, "TotaleOperazioniAttive", module.ActiveTotal);
Amount(xml, "TotaleOperazioniPassive", module.PassiveTotal);
Amount(xml, "IvaEsigibile", module.TaxDue);
Amount(xml, "IvaDetratta", module.TaxDeducted);
var difference = module.TaxDue - module.TaxDeducted;
Amount(xml, difference >= 0m ? "IvaDovuta" : "IvaCredito", Math.Abs(difference));
Amount(xml, "DebitoPrecedente", module.PreviousDebit);
Amount(xml, "CreditoPeriodoPrecedente", module.PreviousCredit);
Amount(xml, "InteressiDovuti", module.Interest);
Amount(xml, "Acconto", module.Advance);
Amount(xml, module.Balance >= 0m ? "ImportoDaVersare" : "ImportoACredito", Math.Abs(module.Balance), always: true);
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndDocument();
}
return buffer.ToArray();
}
/// <summary>An amount as the schema wants it: comma and two decimals, no thousands separator.</summary>
/// <param name="amount">The amount.</param>
/// <returns>The text, such as <c>1234,50</c>.</returns>
public static string FormatAmount(decimal amount) =>
Math.Round(amount, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture).Replace('.', ',');
private static void Element(XmlWriter xml, string name, string value) => xml.WriteElementString("iv", name, Namespace, value);
private static void Amount(XmlWriter xml, string name, decimal value, bool always = false)
{
if (value != 0m || always)
{
Element(xml, name, FormatAmount(value));
}
}
}
@@ -0,0 +1,756 @@
using System.Buffers.Text;
using System.Formats.Asn1;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Khaemhat.Infrastructure.Security;
/// <summary>A structure that is not a readable CMS SignedData, or whose content cannot be extracted.</summary>
public sealed class CmsFormatException : Exception
{
/// <summary>Creates the exception.</summary>
public CmsFormatException()
: base("Not a CMS SignedData structure.")
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public CmsFormatException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public CmsFormatException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>A signer of a CMS SignedData with what its certificate says and the result of the check.</summary>
/// <param name="Name">The name of the signer: common name, else given name and surname, else organization, else
/// serial number of the subject.</param>
/// <param name="TaxCode">The tax code of the signer, from the subject's <c>SERIALNUMBER</c> (OID 2.5.4.5) without
/// the <c>TINIT-</c> or <c>IT:</c> prefix, when present.</param>
/// <param name="Subject">The subject of the certificate, or <see langword="null"/> when it was not found.</param>
/// <param name="Issuer">The issuer of the certificate, or <see langword="null"/> when it was not found.</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="SigningTime">The <c>signingTime</c> signed attribute: what the signer's clock said, not a trusted timestamp.</param>
/// <param name="Verified">Whether the digest of the content and the signature match.</param>
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
/// <param name="Certificate">The DER of the signer certificate, or <see langword="null"/> when it was not found.</param>
public sealed record CmsSigner(
string? Name, string? TaxCode, string? Subject, string? Issuer,
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, DateTimeOffset? SigningTime,
bool Verified, string? Problem, byte[]? Certificate);
/// <summary>The content of one or more nested CMS SignedData envelopes and their signers.</summary>
/// <param name="Content">The content of the innermost envelope.</param>
/// <param name="Signers">The signers, outermost envelope first.</param>
/// <param name="Layers">How many envelopes were opened (two for <c>.xml.p7m.p7m</c>).</param>
public sealed record CmsContent(byte[] Content, IReadOnlyList<CmsSigner> Signers, int Layers)
{
/// <summary>Whether there is at least one signer and every signer of every envelope is verified.</summary>
public bool Verified => Signers.Count > 0 && Signers.All(s => s.Verified);
/// <summary>The first problem found, or <see langword="null"/> when <see cref="Verified"/>.</summary>
public string? Problem => Signers.Count == 0 ? "The envelope has no signer." : Signers.FirstOrDefault(s => s.Problem is not null)?.Problem;
/// <summary>The signer of the outermost envelope, or <see langword="null"/> when there is none.</summary>
public CmsSigner? Signer => Signers.Count > 0 ? Signers[0] : null;
}
/// <summary>
/// A minimal reader of CMS SignedData (RFC 5652, PKCS #7), the envelope of CAdES signed files such as <c>.p7m</c>,
/// written on <c>System.Formats.Asn1</c> because <c>System.Security.Cryptography.Pkcs</c> is a separate package
/// (SPEC §1.2).
/// </summary>
/// <remarks>
/// <para>It accepts DER and BER (indefinite lengths, content split in constructed chunks), the base64 text of the
/// binary with or without line breaks and <c>-----BEGIN</c> armour, and nested envelopes (<c>.p7m.p7m</c>), opened
/// until the content is no longer CMS.</para>
/// <para>It checks integrity only: the <c>messageDigest</c> attribute against the content (SHA-1, SHA-256, SHA-384,
/// SHA-512) and the signature with the public key of the embedded signer certificate (RSA PKCS #1 v1.5, RSA-PSS with
/// the salt as long as the hash, ECDSA). It does <b>not</b> check the trust chain, the qualified status of the
/// certificate or its revocation, because no trusted list is available offline; it never follows external
/// references. A broken signature still returns the content, with <see cref="CmsSigner.Verified"/> false and the
/// problem; only unreadable structures throw <see cref="CmsFormatException"/>. Detached signatures (no content) are
/// not supported.</para>
/// </remarks>
public static class CmsSignedData
{
/// <summary>The largest envelope read, 50 MB.</summary>
public const int MaxSize = 50 * 1024 * 1024;
/// <summary>The most nested envelopes opened.</summary>
public const int MaxLayers = 8;
private const string SignedDataOid = "1.2.840.113549.1.7.2";
private const string ContentTypeAttributeOid = "1.2.840.113549.1.9.3";
private const string MessageDigestAttributeOid = "1.2.840.113549.1.9.4";
private const string SigningTimeAttributeOid = "1.2.840.113549.1.9.5";
private const string RsaEncryptionOid = "1.2.840.113549.1.1.1";
private const string RsaPssOid = "1.2.840.113549.1.1.10";
private const string EcPublicKeyOid = "1.2.840.10045.2.1";
// DER of OBJECT IDENTIFIER 1.2.840.113549.1.7.2 (signedData): what follows the header of the outer SEQUENCE.
private static readonly byte[] SignedDataOidDer = [0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02];
private static readonly Asn1Tag Context0 = new(TagClass.ContextSpecific, 0);
private static readonly Asn1Tag Context0Constructed = new(TagClass.ContextSpecific, 0, isConstructed: true);
private static readonly Asn1Tag Context1 = new(TagClass.ContextSpecific, 1);
/// <summary>Whether the bytes look like a CMS SignedData, in binary or as base64 text. Only the start is looked at.</summary>
/// <param name="data">The content, or at least its first hundred bytes.</param>
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
public static bool LooksLikeCms(ReadOnlySpan<byte> data)
{
if (LooksLikeBinaryCms(data))
{
return true;
}
// Base64 text: decode the first characters and look again.
Span<byte> chars = stackalloc byte[96];
var count = 0;
foreach (var b in SkipArmour(SkipBom(data)))
{
if (IsBase64Whitespace(b))
{
continue;
}
if (!IsBase64Char(b))
{
break;
}
chars[count++] = b;
if (count == chars.Length)
{
break;
}
}
count -= count % 4;
if (count < 24)
{
return false;
}
Span<byte> decoded = stackalloc byte[72];
var status = Base64.DecodeFromUtf8(chars[..count], decoded, out _, out var written, isFinalBlock: false);
return status is System.Buffers.OperationStatus.Done or System.Buffers.OperationStatus.NeedMoreData
&& LooksLikeBinaryCms(decoded[..written]);
}
/// <summary>
/// Opens a CMS SignedData and every envelope nested inside it, and checks the signatures. Accepts DER, BER and
/// base64 text (see the remarks of the class).
/// </summary>
/// <param name="data">The envelope.</param>
/// <returns>The content of the innermost envelope and the signers.</returns>
/// <exception cref="CmsFormatException">The data is not a CMS SignedData, is too large, nests too deep, has no
/// content, or cannot be decoded.</exception>
public static CmsContent Read(byte[] data)
{
ArgumentNullException.ThrowIfNull(data);
var current = data;
var signers = new List<CmsSigner>();
var layers = 0;
while (true)
{
if (current.Length > MaxSize)
{
throw new CmsFormatException($"The envelope is larger than {MaxSize / (1024 * 1024)} MB.");
}
var binary = ToBinary(current);
if (binary is null)
{
if (layers == 0)
{
throw new CmsFormatException("Not a CMS SignedData structure.");
}
return new CmsContent(current, signers, layers);
}
if (++layers > MaxLayers)
{
throw new CmsFormatException($"More than {MaxLayers} nested envelopes.");
}
current = ReadLayer(binary, signers);
}
}
/// <summary>
/// Decodes the base64 text form of a binary structure: whitespace and line breaks are skipped, <c>-----BEGIN</c>
/// and <c>-----END</c> lines dropped, a UTF-8 byte order mark ignored.
/// </summary>
/// <param name="text">The text, as bytes.</param>
/// <returns>The decoded bytes, or <see langword="null"/> when the text is not base64.</returns>
public static byte[]? DecodeBase64Text(ReadOnlySpan<byte> text)
{
var body = SkipBom(text);
var filtered = new byte[body.Length];
var count = 0;
var lineStart = true;
var skippingLine = false;
foreach (var b in body)
{
if (b is (byte)'\n' or (byte)'\r')
{
lineStart = true;
skippingLine = false;
continue;
}
if (lineStart && b == (byte)'-')
{
skippingLine = true;
}
lineStart = false;
if (skippingLine || IsBase64Whitespace(b))
{
continue;
}
if (!IsBase64Char(b) && b != (byte)'=')
{
return null;
}
filtered[count++] = b;
}
if (count == 0 || count % 4 != 0)
{
return null;
}
var output = new byte[Base64.GetMaxDecodedFromUtf8Length(count)];
var status = Base64.DecodeFromUtf8(filtered.AsSpan(0, count), output, out _, out var written);
return status == System.Buffers.OperationStatus.Done ? output[..written] : null;
}
private static byte[]? ToBinary(byte[] data)
{
if (LooksLikeBinaryCms(data))
{
return data;
}
if (!LooksLikeCms(data))
{
return null;
}
var decoded = DecodeBase64Text(data);
return decoded is not null && LooksLikeBinaryCms(decoded) ? decoded : null;
}
private static bool LooksLikeBinaryCms(ReadOnlySpan<byte> data)
{
if (data.Length < 2 || data[0] != 0x30)
{
return false;
}
int header;
if (data[1] <= 0x80)
{
header = 2;
}
else
{
var lengthBytes = data[1] & 0x7F;
if (lengthBytes > 4)
{
return false;
}
header = 2 + lengthBytes;
}
return data.Length >= header + SignedDataOidDer.Length && data.Slice(header, SignedDataOidDer.Length).SequenceEqual(SignedDataOidDer);
}
private static byte[] ReadLayer(byte[] data, List<CmsSigner> signers)
{
try
{
var outer = new AsnReader(data, AsnEncodingRules.BER);
var contentInfo = outer.ReadSequence();
if (contentInfo.ReadObjectIdentifier() != SignedDataOid)
{
throw new CmsFormatException("The envelope is not SignedData.");
}
var signedData = contentInfo.ReadSequence(Context0Constructed).ReadSequence();
signedData.ReadInteger();
signedData.ReadSetOf(skipSortOrderValidation: true);
var encapsulated = signedData.ReadSequence();
encapsulated.ReadObjectIdentifier();
if (!encapsulated.HasData)
{
throw new CmsFormatException("The signature is detached: the envelope has no content.");
}
var content = encapsulated.ReadSequence(Context0Constructed).ReadOctetString();
var certificates = new List<byte[]>();
if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context0))
{
var set = signedData.ReadSetOf(skipSortOrderValidation: true, Context0);
while (set.HasData)
{
var tag = set.PeekTag();
var encoded = set.ReadEncodedValue();
if (tag.HasSameClassAndValue(Asn1Tag.Sequence))
{
certificates.Add(encoded.ToArray());
}
}
}
if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context1))
{
signedData.ReadEncodedValue();
}
var signerInfos = signedData.ReadSetOf(skipSortOrderValidation: true);
var found = 0;
while (signerInfos.HasData)
{
signers.Add(ReadSigner(signerInfos.ReadSequence(), content, certificates));
found++;
}
if (found == 0)
{
signers.Add(new CmsSigner(null, null, null, null, null, null, null, false, "The envelope has no signer.", null));
}
return content;
}
catch (AsnContentException ex)
{
throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex);
}
catch (CryptographicException ex)
{
throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex);
}
}
private static CmsSigner ReadSigner(AsnReader signerInfo, byte[] content, List<byte[]> certificates)
{
signerInfo.ReadInteger();
byte[]? issuer = null;
byte[]? serial = null;
byte[]? keyIdentifier = null;
if (signerInfo.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence))
{
var issuerAndSerial = signerInfo.ReadSequence();
issuer = issuerAndSerial.ReadEncodedValue().ToArray();
serial = issuerAndSerial.ReadIntegerBytes().ToArray();
}
else
{
keyIdentifier = signerInfo.ReadOctetString(Context0);
}
var (digestOid, _) = ReadAlgorithm(signerInfo);
byte[]? signedAttributes = null;
if (signerInfo.PeekTag().HasSameClassAndValue(Context0))
{
signedAttributes = signerInfo.ReadEncodedValue().ToArray();
}
var (signatureOid, signatureParameters) = ReadAlgorithm(signerInfo);
var signature = signerInfo.ReadOctetString();
DateTimeOffset? signingTime = null;
byte[]? messageDigest = null;
if (signedAttributes is not null)
{
ReadAttributes(signedAttributes, out messageDigest, out signingTime);
}
using var certificate = FindCertificate(certificates, issuer, serial, keyIdentifier);
var problem = Verify(certificate, content, digestOid, signedAttributes, messageDigest, signatureOid, signatureParameters, signature);
return Describe(certificate, signingTime, problem);
}
private static (string Oid, byte[]? Parameters) ReadAlgorithm(AsnReader reader)
{
var algorithm = reader.ReadSequence();
var oid = algorithm.ReadObjectIdentifier();
var parameters = algorithm.HasData ? algorithm.ReadEncodedValue().ToArray() : null;
return (oid, parameters);
}
private static void ReadAttributes(byte[] signedAttributes, out byte[]? messageDigest, out DateTimeOffset? signingTime)
{
messageDigest = null;
signingTime = null;
var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0);
while (set.HasData)
{
var attribute = set.ReadSequence();
var type = attribute.ReadObjectIdentifier();
var values = attribute.ReadSetOf(skipSortOrderValidation: true);
if (!values.HasData)
{
continue;
}
switch (type)
{
case MessageDigestAttributeOid:
messageDigest = values.ReadOctetString();
break;
case SigningTimeAttributeOid:
signingTime = values.PeekTag().HasSameClassAndValue(Asn1Tag.UtcTime) ? values.ReadUtcTime() : values.ReadGeneralizedTime();
break;
case ContentTypeAttributeOid:
default:
break;
}
}
}
private static X509Certificate2? FindCertificate(List<byte[]> certificates, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier)
{
foreach (var der in certificates)
{
X509Certificate2 certificate;
try
{
certificate = X509CertificateLoader.LoadCertificate(der);
}
catch (CryptographicException)
{
continue;
}
if (Matches(certificate, issuer, serial, keyIdentifier))
{
return certificate;
}
certificate.Dispose();
}
return null;
}
private static bool Matches(X509Certificate2 certificate, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier)
{
if (issuer is not null && serial is not null)
{
return certificate.IssuerName.RawData.AsSpan().SequenceEqual(issuer)
&& certificate.SerialNumberBytes.Span.SequenceEqual(serial);
}
return keyIdentifier is not null
&& certificate.Extensions.OfType<X509SubjectKeyIdentifierExtension>().FirstOrDefault() is { } extension
&& extension.SubjectKeyIdentifierBytes.Span.SequenceEqual(keyIdentifier);
}
private static string? Verify(
X509Certificate2? certificate, byte[] content, string digestOid, byte[]? signedAttributes, byte[]? messageDigest,
string signatureOid, byte[]? signatureParameters, byte[] signature)
{
if (certificate is null)
{
return "The signer certificate is not in the envelope.";
}
if (HashOf(digestOid) is not { } digest)
{
return $"Unsupported digest algorithm {digestOid}.";
}
List<byte[]> signedForms;
if (signedAttributes is null)
{
signedForms = [content];
}
else
{
if (messageDigest is null)
{
return "The signed attributes have no message digest.";
}
if (!CryptographicOperations.FixedTimeEquals(CryptographicOperations.HashData(digest, content), messageDigest))
{
return "The content does not match the signed digest: it was changed after signing.";
}
signedForms = SignedAttributesAsSet(signedAttributes);
}
try
{
foreach (var signed in signedForms)
{
var result = VerifySignature(certificate, signed, digest, signatureOid, signatureParameters, signature);
if (result is null)
{
return null;
}
if (result.Length > 0)
{
return result;
}
}
}
catch (CryptographicException ex)
{
return "The signature cannot be checked: " + ex.Message;
}
return "The signature does not match the signer certificate.";
}
// The signature covers the DER of the attributes as a SET (tag 0x31), not the [0] implicit tag of the file. The
// bytes of the file are tried first (they are DER in every well-formed signature); a DER re-encoding after.
private static List<byte[]> SignedAttributesAsSet(byte[] signedAttributes)
{
var forms = new List<byte[]>();
if (signedAttributes.Length > 1 && signedAttributes[1] != 0x80)
{
var asSet = (byte[])signedAttributes.Clone();
asSet[0] = 0x31;
forms.Add(asSet);
}
try
{
var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0);
var writer = new AsnWriter(AsnEncodingRules.DER);
using (writer.PushSetOf())
{
while (set.HasData)
{
writer.WriteEncodedValue(set.ReadEncodedValue().Span);
}
}
var der = writer.Encode();
if (!forms.Exists(f => f.AsSpan().SequenceEqual(der)))
{
forms.Add(der);
}
}
catch (ArgumentException)
{
// Attributes that are not DER inside cannot be re-encoded; the bytes of the file are all there is.
}
catch (AsnContentException)
{
// Same as above.
}
return forms;
}
// Null when verified, an empty string when the signature does not match, a message for an unsupported algorithm.
private static string? VerifySignature(
X509Certificate2 certificate, byte[] signed, HashAlgorithmName digest, string signatureOid, byte[]? signatureParameters, byte[] signature)
{
switch (signatureOid)
{
case RsaPssOid:
{
using var rsa = certificate.GetRSAPublicKey();
if (rsa is null)
{
return "The signer certificate has no RSA key.";
}
var pssHash = PssHash(signatureParameters) ?? digest;
return rsa.VerifyData(signed, signature, pssHash, RSASignaturePadding.Pss) ? null : string.Empty;
}
case EcPublicKeyOid:
case "1.2.840.10045.4.1":
case "1.2.840.10045.4.3.2":
case "1.2.840.10045.4.3.3":
case "1.2.840.10045.4.3.4":
{
using var ecdsa = certificate.GetECDsaPublicKey();
if (ecdsa is null)
{
return "The signer certificate has no ECDSA key.";
}
var hash = signatureOid == EcPublicKeyOid ? digest : HashOfSignature(signatureOid) ?? digest;
return ecdsa.VerifyData(signed, signature, hash, DSASignatureFormat.Rfc3279DerSequence) ? null : string.Empty;
}
case RsaEncryptionOid:
case "1.2.840.113549.1.1.5":
case "1.2.840.113549.1.1.11":
case "1.2.840.113549.1.1.12":
case "1.2.840.113549.1.1.13":
{
using var rsa = certificate.GetRSAPublicKey();
if (rsa is null)
{
return "The signer certificate has no RSA key.";
}
var hash = signatureOid == RsaEncryptionOid ? digest : HashOfSignature(signatureOid) ?? digest;
return rsa.VerifyData(signed, signature, hash, RSASignaturePadding.Pkcs1) ? null : string.Empty;
}
default:
return $"Unsupported signature algorithm {signatureOid}.";
}
}
private static HashAlgorithmName? HashOf(string digestOid) => digestOid switch
{
"1.3.14.3.2.26" => HashAlgorithmName.SHA1,
"2.16.840.1.101.3.4.2.1" => HashAlgorithmName.SHA256,
"2.16.840.1.101.3.4.2.2" => HashAlgorithmName.SHA384,
"2.16.840.1.101.3.4.2.3" => HashAlgorithmName.SHA512,
_ => null,
};
private static HashAlgorithmName? HashOfSignature(string signatureOid) => signatureOid switch
{
"1.2.840.113549.1.1.5" or "1.2.840.10045.4.1" => HashAlgorithmName.SHA1,
"1.2.840.113549.1.1.11" or "1.2.840.10045.4.3.2" => HashAlgorithmName.SHA256,
"1.2.840.113549.1.1.12" or "1.2.840.10045.4.3.3" => HashAlgorithmName.SHA384,
"1.2.840.113549.1.1.13" or "1.2.840.10045.4.3.4" => HashAlgorithmName.SHA512,
_ => null,
};
// RSASSA-PSS-params: hashAlgorithm [0] (default SHA-1), maskGenAlgorithm [1], saltLength [2], trailerField [3].
private static HashAlgorithmName? PssHash(byte[]? parameters)
{
if (parameters is null)
{
return null;
}
var sequence = new AsnReader(parameters, AsnEncodingRules.BER).ReadSequence();
if (!sequence.HasData || !sequence.PeekTag().HasSameClassAndValue(Context0))
{
return HashAlgorithmName.SHA1;
}
var (oid, _) = ReadAlgorithm(sequence.ReadSequence(Context0Constructed));
return HashOf(oid);
}
private static CmsSigner Describe(X509Certificate2? certificate, DateTimeOffset? signingTime, string? problem)
{
if (certificate is null)
{
return new CmsSigner(null, null, null, null, null, null, signingTime, false, problem, null);
}
string? commonName = null, givenName = null, surname = null, organization = null, serialNumber = null;
foreach (var rdn in certificate.SubjectName.EnumerateRelativeDistinguishedNames())
{
if (rdn.HasMultipleElements)
{
continue;
}
var value = rdn.GetSingleElementValue();
switch (rdn.GetSingleElementType().Value)
{
case "2.5.4.3":
commonName ??= value;
break;
case "2.5.4.42":
givenName ??= value;
break;
case "2.5.4.4":
surname ??= value;
break;
case "2.5.4.10":
organization ??= value;
break;
case "2.5.4.5":
serialNumber ??= value;
break;
default:
break;
}
}
var personName = string.Join(' ', new[] { givenName, surname }.Where(s => !string.IsNullOrWhiteSpace(s)));
var name = NullIfBlank(commonName) ?? NullIfBlank(personName) ?? NullIfBlank(organization) ?? NullIfBlank(serialNumber);
return new CmsSigner(
name,
TaxCodeOf(serialNumber),
certificate.Subject,
certificate.Issuer,
new DateTimeOffset(certificate.NotBefore.ToUniversalTime(), TimeSpan.Zero),
new DateTimeOffset(certificate.NotAfter.ToUniversalTime(), TimeSpan.Zero),
signingTime,
problem is null,
problem,
certificate.RawData);
}
// ETSI EN 319 412-1: SERIALNUMBER = TINIT-<tax code>; older Italian certificates use IT:<tax code>.
private static string? TaxCodeOf(string? serialNumber)
{
if (string.IsNullOrWhiteSpace(serialNumber))
{
return null;
}
var value = serialNumber.Trim();
if (value.StartsWith("TINIT-", StringComparison.OrdinalIgnoreCase))
{
return NullIfBlank(value["TINIT-".Length..].Trim());
}
if (value.StartsWith("IT:", StringComparison.OrdinalIgnoreCase))
{
return NullIfBlank(value["IT:".Length..].Trim());
}
return value.Length is 11 or 16 && value.All(char.IsAsciiLetterOrDigit) ? value.ToUpperInvariant() : null;
}
private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value;
private static ReadOnlySpan<byte> SkipBom(ReadOnlySpan<byte> data) =>
data.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]) ? data[3..] : data;
private static ReadOnlySpan<byte> SkipArmour(ReadOnlySpan<byte> data)
{
var trimmed = data.TrimStart((ReadOnlySpan<byte>)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']);
if (!trimmed.StartsWith("-----"u8))
{
return trimmed;
}
var end = trimmed.IndexOf((byte)'\n');
return end < 0 ? [] : trimmed[(end + 1)..];
}
private static bool IsBase64Char(byte b) =>
b is (>= (byte)'A' and <= (byte)'Z') or (>= (byte)'a' and <= (byte)'z') or (>= (byte)'0' and <= (byte)'9') or (byte)'+' or (byte)'/';
private static bool IsBase64Whitespace(byte b) => b is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n';
}
@@ -19,6 +19,9 @@
case WidgetIds.SystemStatus:
<SystemStatusWidget Definition="Definition" />
break;
case WidgetIds.Understock:
<UnderstockWidget Definition="Definition" />
break;
default:
<ComingWidget Definition="Definition" />
break;
@@ -0,0 +1,74 @@
@using Khaemhat.Application.Inventory
@inject ShellSession Session
@inject InventoryService Inventory
@* Sottoscorta (SPEC §10.3, §11.6): the items under their minimum stock or reorder point, the most urgent first, with a
link to the reorder proposal. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<Actions>
@if (_rows is { Count: > 0 })
{
<span class="badge @(_rows.Any(r => r.Level == StockLevel.Out) ? "red" : "amber")">@T.Number(_rows.Count)</span>
}
</Actions>
<ChildContent>
@if (_failed)
{
<p class="kh-wempty"><KhIcon Name="alert" /> @T["Dashboard.Feed.Error"]</p>
}
else if (_rows is null)
{
<p class="kh-wempty muted">@T["Dashboard.Feed.Loading"]</p>
}
else if (_rows.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Dashboard.Widgets.Understock.Empty"]</p>
}
else
{
<div class="list kh-wlist">
@foreach (var row in _rows)
{
<a class="li" href="magazzino/giacenze?articolo=@row.ItemId">
<span class="kh-tone @(row.Level == StockLevel.Out ? "err" : "warn")" aria-hidden="true"></span>
<div class="grow">
<div class="t"><span class="code">@row.Code</span> @row.Description</div>
<div class="s">@T.Format("Dashboard.Widgets.Understock.Line", T.Number(row.Available), T.Number(row.MinimumStock ?? row.ReorderPoint ?? 0m))</div>
</div>
<span class="badge @(row.Level == StockLevel.Out ? "red" : "amber")">@T["Inventory.Levels." + row.Level]</span>
</a>
}
</div>
<div class="kh-wfoot"><a href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Dashboard.Widgets.Understock.Reorder"]</a></div>
}
</ChildContent>
</KhWidget>
@code {
private IReadOnlyList<StockRow>? _rows;
private bool _failed;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(InventoryService.StockPermission))
{
_rows = [];
return;
}
try
{
_rows = await Inventory.UnderstockAsync(actor, company, 8);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_failed = true;
}
}
}
@@ -40,7 +40,7 @@ else
<KhSelect TValue="MissingCodeAction" Label="@T["ImportExport.Missing"]" Name="missing" Options="MissingChoices" Value="_options.Missing"
ValueChanged="SetMissing" Span="6" Disabled="_busy" />
}
else if (IsPrices)
else if (OnlyExistingOption)
{
<KhSelect TValue="ExistingCodeAction" Label="@T["ImportExport.Existing"]" Name="existing" Options="ExistingChoices" Value="_options.Existing"
ValueChanged="SetExisting" Span="12" Disabled="_busy" />
@@ -40,13 +40,13 @@ public partial class ImportExportPage
private bool IsRecordTarget => Target is PartiesImportTarget or ItemsImportTarget;
private bool IsPrices => Target is PricesImportTarget;
private bool OnlyExistingOption => Target is PricesImportTarget or ChartOfAccountsImportTarget;
private bool CanExport => Target.CanExport && Session.Permissions.Flags.CanExport && Session.Permissions.Allows(Target.ExportPermission);
private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null;
private string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6";
private static string CheckOnlyMilestone => "M7";
private IReadOnlyList<KhOption<string>> TargetChoices => [.. Targets.Select(t => new KhOption<string>(t.Key, TargetName(t.Key)))];
@@ -0,0 +1,247 @@
@page "/magazzino/riordino"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Inventory
@using Khaemhat.Application.Items
@using Khaemhat.Application.Parties
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Documents
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Items
@using Khaemhat.Web.Parties
@using Khaemhat.Web.Tables
@inject ShellSession Session
@inject ReorderService Reorder
@inject PartyService Parties
@inject TableService Tables
@inject ToastService Toasts
@* The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the
reorder point or the minimum stock, with the quantity to order and the usual supplier; the lines chosen, perhaps with
another quantity or supplier, become draft supplier orders, one per supplier. *@
<KhPageTitle Text="@T["Inventory.Reorder.Title"]" Icon="refresh" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
}
else if (!Session.Permissions.Allows(InventoryService.StockPermission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<KhStrip Items="Stats" Label="@T["Inventory.Reorder.Title"]" />
@if (_orders.Count > 0)
{
<div class="callout ok kh-pad" role="status">
<KhIcon Name="check-circle" />
<span>
@T.Format("Inventory.Reorder.Created", _orders.Count)
@foreach (var order in _orders)
{
<span> </span><a href="@SalesScreens.RecordUrl(order.Record.Header.Kind, order.Record.Header.Id)">@order.Supplier</a>
}
</span>
</div>
}
<KhPanel Title="@T["Inventory.Reorder.Lines"]" Icon="list">
<Actions>
<span class="muted sm">@T.Format("Inventory.Reorder.Selected", Chosen.Count(), T.Money(ChosenValue))</span>
<button type="button" class="btn" disabled="@_busy" @onclick="LoadAsync"><KhIcon Name="refresh" /> @T["Inventory.Reorder.Refresh"]</button>
@if (CanOrder)
{
<button type="button" class="btn primary" disabled="@(_busy || !Chosen.Any())" @onclick="CreateAsync"><KhIcon Name="truck" /> @T["Inventory.Reorder.Create"]</button>
}
</Actions>
<ChildContent>
@if (_lines.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Inventory.Reorder.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Inventory.Reorder.Lines"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@_lines.All(l => l.Chosen)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
<th scope="col">@T["Items.Fields.Code"]</th>
<th scope="col">@T["Items.Fields.Description"]</th>
<th scope="col">@T["Items.Radar.Unit"]</th>
<th scope="col" class="num">@T["Inventory.Stock.Available"]</th>
<th scope="col" class="num">@T["Inventory.Stock.OrderedColumn"]</th>
<th scope="col" class="num">@T["Inventory.Stock.Minimum"]</th>
<th scope="col" class="num">@T["Inventory.Stock.ReorderPoint"]</th>
<th scope="col" class="num">@T["Inventory.Reorder.Quantity"]</th>
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
<th scope="col" class="num">@T["Inventory.Reorder.Price"]</th>
<th scope="col">@T["Inventory.Reorder.Expected"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in _lines)
{
var row = line.Proposal;
<tr class="@(line.Chosen ? "sel" : null)">
<td class="kh-check"><input type="checkbox" checked="@line.Chosen" aria-label="@row.Code" @onchange="e => line.Chosen = e.Value is true" /></td>
<td class="code">@row.Code</td>
<td>@row.Description</td>
<td>@PartyScreens.Describe(_lookups.Units, row.UnitOfMeasureId)</td>
<td class="num @(row.Available < 0m ? "err" : null)">@Qty(row.Available)</td>
<td class="num">@Qty(row.Ordered)</td>
<td class="num">@(row.MinimumStock is { } m ? Qty(m) : null)</td>
<td class="num">@(row.ReorderPoint is { } p ? Qty(p) : null)</td>
<td class="num">
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.Reorder.Quantity"] + " " + row.Code)"
value="@Qty(line.Quantity)" @onchange="e => SetQuantity(line, e.Value?.ToString())" />
</td>
<td class="kh-cellpick">
<KhHotlink TItem="PartyRow" Name="@("Supplier" + row.ItemId)" Value="line.Supplier" ValueChanged="v => line.Supplier = v" Span="12"
Search="SearchAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Placeholder="@T["Inventory.Reorder.ChooseSupplier"]" />
</td>
<td class="num">@(row.Price is { } price ? T.Money(price) : null)</td>
<td>@(row.ExpectedDate is { } date ? T.Date(date) : null)</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
</KhPanel>
<p class="muted sm kh-pad">@T["Inventory.Reorder.Hint"]</p>
}
@code {
private List<Line> _lines = [];
private List<(DocumentRecord Record, string Supplier)> _orders = [];
private ItemLookups _lookups = ItemLookups.Empty;
private bool _loaded;
private bool _busy;
private bool CanOrder => Session.Permissions.Allows("purchases.order.write");
private IEnumerable<Line> Chosen => _lines.Where(l => l.Chosen && l.Supplier is not null && l.Quantity > 0m);
private decimal ChosenValue => Chosen.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2));
private IReadOnlyList<KhStat> Stats =>
[
new(T["Inventory.Reorder.Items"], T.Number(_lines.Count), _lines.Count > 0 ? KhTone.Warning : KhTone.Ok),
new(T["Inventory.Reorder.Suppliers"], T.Number(_lines.Where(l => l.Supplier is not null).Select(l => l.Supplier!.Id).Distinct().Count())),
new(T["Inventory.Reorder.Value"], T.Money(_lines.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2)))),
new(T["Inventory.Reorder.WithoutSupplier"], T.Number(_lines.Count(l => l.Supplier is null)), _lines.Any(l => l.Supplier is null) ? KhTone.Warning : KhTone.Neutral),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.StockPermission))
{
_lookups = await ItemLookups.ForRadarAsync(Tables, actor, company);
await LoadAsync();
}
_loaded = true;
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
var proposals = await Reorder.ProposalsAsync(actor, company);
var supplierIds = proposals.Where(p => p.SupplierId is not null).Select(p => p.SupplierId!.Value).Distinct().ToList();
var suppliers = Session.Permissions.Allows(PartyService.ReadPermission)
? (await Parties.RowsAsync(actor, company, supplierIds)).ToDictionary(r => r.Id)
: [];
_lines = [.. proposals.Select(p => new Line(p)
{
Quantity = p.Quantity,
Supplier = p.SupplierId is { } s ? suppliers.GetValueOrDefault(s) : null,
Chosen = p.SupplierId is not null,
})];
}
private async Task<IReadOnlyList<PartyRow>> SearchAsync(string text, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken)
: [];
private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture);
private void SetQuantity(Line line, string? text)
{
if (decimal.TryParse((text ?? string.Empty).Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value)
&& value >= 0m)
{
line.Quantity = value;
}
}
private void ToggleAll(ChangeEventArgs e)
{
foreach (var line in _lines)
{
line.Chosen = e.Value is true;
}
}
private async Task CreateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (_lines.Any(l => l.Chosen && l.Supplier is null))
{
Toasts.Show(ToastKind.Warning, T["Inventory.Reorder.MissingSupplier"]);
}
_busy = true;
try
{
var names = Chosen.Select(l => l.Supplier!).DistinctBy(r => r.Id).ToDictionary(r => r.Id, r => r.Name);
var orders = await Reorder.CreateOrdersAsync(actor, company, [.. Chosen.Select(l => new ReorderChoice(l.Proposal.ItemId, l.Supplier!.Id, l.Quantity))]);
_orders = [.. orders.Select(o => (o, names.GetValueOrDefault(o.Header.PartyId ?? 0) ?? string.Empty))];
Toasts.Show(ToastKind.Success, T.Format("Inventory.Reorder.Created", _orders.Count));
await LoadAsync();
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c)));
}
finally
{
_busy = false;
}
}
private sealed class Line(ReorderProposal proposal)
{
public ReorderProposal Proposal { get; } = proposal;
public decimal Quantity { get; set; }
public PartyRow? Supplier { get; set; }
public bool Chosen { get; set; }
}
}
@@ -0,0 +1,450 @@
@page "/magazzino/giacenze"
@attribute [Authorize]
@using Khaemhat.Application.Inventory
@using Khaemhat.Application.Items
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Inventory
@using Khaemhat.Core.Tables
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Items
@using Khaemhat.Web.Parties
@inject ShellSession Session
@inject InventoryService Inventory
@inject ItemService Items
@inject TableService Tables
@inject ToastService Toasts
@inject DialogService Dialogs
@inject TimeProvider Clock
@* Stock and availability (SPEC §11.6, mockup 036): every stocked item with on hand, committed, ordered and available,
its thresholds and, for who may see costs, the average cost and the value; the state under the thresholds. One
warehouse or all together. The movements of an item with their running balance; the value at a date with the ABC
classes; the rebuild of the warehouse from its documents. *@
<KhPageTitle Text="@T["Inventory.Stock.Title"]" Icon="box" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
}
else if (!Session.Permissions.Allows(InventoryService.StockPermission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<KhStrip Items="Stats" Label="@T["Inventory.Stock.Title"]" />
<KhForm Layout="KhFormLayout.Grid" Class="kh-pagefilters">
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="Warehouse" Options="_warehouses" Empty="@T["Inventory.Stock.AllWarehouses"]"
Value="@PartyScreens.Text(_warehouse)" ValueChanged="SetWarehouseAsync" Span="4" />
<KhCheck Label="@T["Inventory.Stock.IncludeEmpty"]" Name="IncludeEmpty" Value="_includeEmpty" ValueChanged="SetIncludeEmptyAsync" Span="4" />
</KhForm>
<KhRadar TItem="StockRow" @ref="_radar" Id="stock" Columns="Columns" Source="ListAsync" KeyOf="r => r.ItemId" Selectable="false" OnOpen="OpenMovementsAsync"
QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Inventory.Stock.Search"]" ExportName="giacenze" Label="@T["Inventory.Stock.Title"]">
<Toolbar>
<a class="btn" href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Shell.Menu.Inventory.Reorder"]</a>
<a class="btn" href="magazzino/inventario"><KhIcon Name="file-check" /> @T["Shell.Menu.Inventory.StockTake"]</a>
@if (_costs)
{
<button type="button" class="btn" @onclick="OpenValuation"><KhIcon Name="euro" /> @T["Inventory.Valuation.Title"]</button>
}
@if (Session.Permissions.Allows(InventoryService.PostPermission))
{
<button type="button" class="btn" disabled="@_busy" @onclick="RebuildAsync"><KhIcon Name="layers" /> @T["Inventory.Rebuild.Action"]</button>
}
</Toolbar>
</KhRadar>
@if (_rebuild is { } progress)
{
<div class="callout info kh-pad" role="status">
<KhIcon Name="layers" />
<span>@T.Format("Inventory.Rebuild.Progress", T["Inventory.Rebuild.Phases." + progress.Phase], T.Number(progress.Done), T.Number(progress.Total))</span>
</div>
}
<KhDialog Open="_item is not null" Title="@MovementsTitle" Icon="layers" Size="lg" OnClose="() => _item = null">
<ChildContent>
@if (_balances is { Count: > 1 })
{
<KhStrip Items="BalanceStats" Label="@T["Inventory.Movements.ByWarehouse"]" />
}
@if (_movements is null)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (_movements.Count == 0)
{
<p class="muted kh-pad">@T["Inventory.Movements.None"]</p>
}
else
{
<div class="gridwrap kh-dialoggrid">
<table class="grid" aria-label="@T["Inventory.Movements.Title"]">
<thead>
<tr>
<th scope="col">@T["Inventory.Movements.Date"]</th>
<th scope="col">@T["Inventory.Movements.Document"]</th>
<th scope="col">@T["Inventory.Fields.Reason"]</th>
<th scope="col">@T["Inventory.Movements.Party"]</th>
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
@if (_costs)
{
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
}
<th scope="col" class="num">@T["Inventory.Movements.Balance"]</th>
</tr>
</thead>
<tbody>
@foreach (var move in _movements)
{
<tr>
<td>@T.Date(move.Date)</td>
<td>
@if (move.Kind is { } kind && move.DocumentId is { } document)
{
<a href="@SalesScreens.RecordUrl(kind, document)">@T["Sales.Kinds." + kind] <span class="mono">@move.Number</span></a>
}
</td>
<td class="code">@move.ReasonCode</td>
<td>@move.PartyName</td>
<td>@PartyScreens.Describe(_warehouses, move.WarehouseId)</td>
<td class="num @(move.Quantity < 0m ? "err" : "ok")">@Qty(move.Quantity)</td>
@if (_costs)
{
<td class="num">@Cost(move.UnitCost)</td>
}
<td class="num"><b>@Qty(move.Balance)</b></td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
<Footer>
@if (_item is { } item)
{
<a class="btn" href="@ItemScreens.RecordUrl(item.ItemId)"><KhIcon Name="box" /> @T["Inventory.Movements.OpenItem"]</a>
}
<button type="button" class="btn primary" @onclick="() => _item = null">@T["Common.Close"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_valuationOpen" Title="@T["Inventory.Valuation.Title"]" Icon="euro" Size="lg" OnClose="() => _valuationOpen = false">
<ChildContent>
<KhForm Layout="KhFormLayout.Grid">
<KhDateBox Label="@T["Inventory.Valuation.Date"]" Name="ValuationDate" Value="_valuationDate" ValueChanged="v => _valuationDate = v" Span="4" Required="true" />
<KhSelect TValue="string" Label="@T["Inventory.Valuation.Method"]" Name="Method" Options="Methods" Value="@_method.ToString()" Span="4"
ValueChanged="SetMethod" />
<div class="c4 kh-endrow">
<button type="button" class="btn primary" disabled="@_busy" @onclick="ValueAsync"><KhIcon Name="chart" /> @T["Inventory.Valuation.Compute"]</button>
</div>
</KhForm>
@if (_valuation is { } rows)
{
<KhStrip Items="ValuationStats" Label="@T["Inventory.Valuation.Title"]" />
<div class="gridwrap kh-dialoggrid">
<table class="grid" aria-label="@T["Inventory.Valuation.Title"]">
<thead>
<tr>
<th scope="col">@T["Items.Fields.Code"]</th>
<th scope="col">@T["Items.Fields.Description"]</th>
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
<th scope="col" class="num">@T["Inventory.Stock.Value"]</th>
<th scope="col">@T["Inventory.Valuation.Class"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in rows)
{
<tr>
<td class="code">@row.Code</td>
<td>@row.Description</td>
<td class="num">@Qty(row.Quantity)</td>
<td class="num">@T.Money(row.UnitCost)</td>
<td class="num">@T.Money(row.Value)</td>
<td><KhBadge Tone="@(row.AbcClass switch { 'A' => KhTone.Ok, 'B' => KhTone.Info, _ => KhTone.Neutral })">@row.AbcClass</KhBadge></td>
</tr>
}
</tbody>
</table>
</div>
}
<p class="muted sm">@T["Inventory.Valuation.Hint"]</p>
</ChildContent>
<Footer>
<button type="button" class="btn primary" @onclick="() => _valuationOpen = false">@T["Common.Close"]</button>
</Footer>
</KhDialog>
}
@code {
private static readonly ListFields<StockRow> Fields = new ListFields<StockRow>()
.Add("code", r => r.Code, searchable: true)
.Add("description", r => r.Description, searchable: true)
.Add("category", r => r.CategoryId)
.Add("unit", r => r.UnitOfMeasureId)
.Add("onHand", r => r.OnHand)
.Add("committed", r => r.Committed)
.Add("ordered", r => r.Ordered)
.Add("available", r => r.Available)
.Add("minimum", r => r.MinimumStock)
.Add("reorderPoint", r => r.ReorderPoint)
.Add("averageCost", r => r.AverageCost)
.Add("value", r => r.Value, total: true)
.Add("lastLoad", r => r.LastLoad)
.Add("lastUnload", r => r.LastUnload)
.Add("level", r => r.Level)
.OrderByDefault(new ListSort("code"));
private InMemoryListSource<StockRow> _source = new([], Fields);
private IReadOnlyList<StockRow> _rows = [];
private ItemLookups _lookups = ItemLookups.Empty;
private IReadOnlyList<KhOption<string>> _warehouses = [];
private KhRadar<StockRow>? _radar;
private long? _warehouse;
private bool _includeEmpty;
private bool _costs;
private bool _loaded;
private bool _busy;
private RebuildProgress? _rebuild;
private StockRow? _item;
private IReadOnlyList<MovementRow>? _movements;
private IReadOnlyList<ItemBalance>? _balances;
private bool _valuationOpen;
private DateOnly? _valuationDate;
private StockValuationMethod _method = StockValuationMethod.WeightedAverage;
private IReadOnlyList<ValuationRow>? _valuation;
/// <summary>An item to open at once, from the dashboard.</summary>
[SupplyParameterFromQuery(Name = "articolo")]
public long? ItemId { get; set; }
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
private IReadOnlyList<KhStat> Stats =>
[
new(T["Inventory.Stock.Items"], T.Number(_rows.Count(r => r.OnHand != 0m))),
new(T["Inventory.Stock.Understock"], T.Number(_rows.Count(r => r.Level is StockLevel.Understock or StockLevel.Reorder)),
_rows.Any(r => r.Level is StockLevel.Understock or StockLevel.Reorder) ? KhTone.Warning : KhTone.Neutral),
new(T["Inventory.Stock.Out"], T.Number(_rows.Count(r => r.Level == StockLevel.Out)), _rows.Any(r => r.Level == StockLevel.Out) ? KhTone.Error : KhTone.Neutral),
new(T["Inventory.Stock.Ordered"], T.Number(_rows.Count(r => r.Ordered > 0m))),
.. _costs ? [new KhStat(T["Inventory.Stock.TotalValue"], T.Money(_rows.Sum(r => r.Value ?? 0m)))] : Array.Empty<KhStat>(),
];
private IReadOnlyList<KhStat> BalanceStats => _balances is null ? [] :
[.. _balances.Select(b => new KhStat(PartyScreens.Describe(_warehouses, b.WarehouseId) ?? string.Empty, Qty(b.OnHand)))];
private IReadOnlyList<KhStat> ValuationStats => _valuation is null ? [] :
[
new(T["Inventory.Stock.Items"], T.Number(_valuation.Count)),
new(T["Inventory.Stock.TotalValue"], T.Money(_valuation.Sum(r => r.Value))),
new(T["Inventory.Valuation.ClassA"], T.Number(_valuation.Count(r => r.AbcClass == 'A'))),
new(T["Inventory.Valuation.ClassB"], T.Number(_valuation.Count(r => r.AbcClass == 'B'))),
new(T["Inventory.Valuation.ClassC"], T.Number(_valuation.Count(r => r.AbcClass == 'C'))),
];
private IReadOnlyList<KhOption<string>> Methods =>
[
new(nameof(StockValuationMethod.WeightedAverage), T["Inventory.Valuation.Methods.WeightedAverage"]),
new(nameof(StockValuationMethod.LastCost), T["Inventory.Valuation.Methods.LastCost"]),
new(nameof(StockValuationMethod.StandardCost), T["Inventory.Valuation.Methods.StandardCost"]),
];
private string MovementsTitle => _item is { } item ? item.Code + " · " + item.Description : T["Inventory.Movements.Title"];
private IReadOnlyList<KhColumn<StockRow>> Columns =>
[
new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "120px" },
new("description", T["Items.Fields.Description"], r => r.Description),
new("category", T["Items.Radar.Category"], r => PartyScreens.Describe(_lookups.Categories, r.CategoryId)) { Width = "110px" },
new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "50px" },
new("onHand", T["Inventory.Stock.OnHand"], r => r.OnHand) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" },
new("committed", T["Inventory.Stock.Committed"], r => r.Committed) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" },
new("ordered", T["Inventory.Stock.OrderedColumn"], r => r.Ordered) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" },
new("available", T["Inventory.Stock.Available"], r => r.Available)
{
Kind = KhColumnKind.Number, Decimals = 2, Width = "90px", CellClass = r => r.Available < 0m ? "err" : null,
},
new("minimum", T["Inventory.Stock.Minimum"], r => r.MinimumStock) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px" },
new("reorderPoint", T["Inventory.Stock.ReorderPoint"], r => r.ReorderPoint) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px", Visible = false },
new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "100px", Visible = _costs, Export = _costs },
new("value", T["Inventory.Stock.Value"], r => r.Value) { Kind = KhColumnKind.Money, Width = "110px", Visible = _costs, Export = _costs, Total = _costs },
new("lastLoad", T["Inventory.Stock.LastLoad"], r => r.LastLoad) { Kind = KhColumnKind.Date, Width = "95px", Visible = false },
new("lastUnload", T["Inventory.Stock.LastUnload"], r => r.LastUnload) { Kind = KhColumnKind.Date, Width = "95px", Visible = false },
new("level", T["Items.Radar.State"], r => T["Inventory.Levels." + r.Level])
{
Width = "120px",
Template = r => @<KhBadge Tone="ToneOf(r.Level)">@T["Inventory.Levels." + r.Level]</KhBadge>,
},
];
private IReadOnlyList<KhQuickFilter> QuickFilters =>
[
new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]),
new("level", T["Items.Radar.State"],
[
new(string.Empty, T["Items.Radar.All"]),
.. Enum.GetValues<StockLevel>().Select(l => new KhOption<string>(l.ToString(), T["Inventory.Levels." + l])),
]),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.StockPermission))
{
_lookups = await ItemLookups.ForRadarAsync(Tables, actor, company);
_warehouses = [.. (await Tables.ActiveAsync<Warehouse>(actor, company)).Select(w => new KhOption<string>(PartyScreens.Text(w.Id)!, w.Code + " · " + w.Description))];
_costs = await Items.CanSeeCostsAsync(actor, company);
_valuationDate = Today;
await LoadAsync();
if (ItemId is { } id && _rows.FirstOrDefault(r => r.ItemId == id) is { } row)
{
await OpenMovementsAsync(row);
}
}
_loaded = true;
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_rows = await Inventory.StockAsync(actor, company, new StockFilter { WarehouseId = _warehouse, IncludeEmpty = _includeEmpty });
_source = new InMemoryListSource<StockRow>(_rows, Fields);
}
private Task<ListPage<StockRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) => _source.QueryAsync(query, cancellationToken);
private async Task ReloadAsync()
{
await LoadAsync();
if (_radar is not null)
{
await _radar.ReloadAsync();
}
}
private async Task SetWarehouseAsync(string? value)
{
_warehouse = PartyScreens.Id(value);
await ReloadAsync();
}
private async Task SetIncludeEmptyAsync(bool value)
{
_includeEmpty = value;
await ReloadAsync();
}
private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture);
private string Cost(decimal? value) => value is { } cost ? T.Money(cost) : string.Empty;
private static KhTone ToneOf(StockLevel level) => level switch
{
StockLevel.Out => KhTone.Error,
StockLevel.Understock => KhTone.Warning,
StockLevel.Reorder => KhTone.Info,
_ => KhTone.Ok,
};
private static string? RowClassOf(StockRow row) => row.Level is StockLevel.Out or StockLevel.Understock ? "hl" : null;
private async Task OpenMovementsAsync(StockRow row)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_item = row;
_movements = null;
_balances = null;
if (!Session.Permissions.Allows(InventoryService.EntryReadPermission))
{
_movements = [];
return;
}
_balances = await Inventory.BalancesAsync(actor, company, row.ItemId);
_movements = await Inventory.MovementsAsync(actor, company, row.ItemId, _warehouse, null, null);
}
private void OpenValuation()
{
_valuation = null;
_valuationOpen = true;
}
private void SetMethod(string? value) =>
_method = Enum.TryParse<StockValuationMethod>(value, out var method) ? method : StockValuationMethod.WeightedAverage;
private async Task ValueAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _valuationDate is not { } date)
{
return;
}
_busy = true;
try
{
_valuation = await Inventory.ValuationAsync(actor, company, date, _warehouse, _method);
}
finally
{
_busy = false;
}
}
private async Task RebuildAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (!await Dialogs.ConfirmAsync(new(T["Inventory.Rebuild.Title"], T["Inventory.Rebuild.Text"], T["Inventory.Rebuild.Action"], T["Common.Cancel"])))
{
return;
}
_busy = true;
var progress = new Progress<RebuildProgress>(p =>
{
_rebuild = p;
_ = InvokeAsync(StateHasChanged);
});
try
{
var (documents, items) = await Task.Run(() => Inventory.RebuildAsync(actor, company, progress));
Toasts.Show(ToastKind.Success, T.Format("Inventory.Rebuild.Done", T.Number(documents), T.Number(items)));
await ReloadAsync();
}
finally
{
_busy = false;
_rebuild = null;
}
}
}
@@ -0,0 +1,524 @@
@page "/magazzino/inventario"
@page "/magazzino/inventario/{Id:long}"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Inventory
@using Khaemhat.Application.Items
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Documents
@using Khaemhat.Core.Inventory
@using Khaemhat.Core.Tables
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Items
@using Khaemhat.Web.Parties
@using Khaemhat.Web.Tables
@inject ShellSession Session
@inject StockTakeService StockTakes
@inject ItemService Items
@inject TableService Tables
@inject ToastService Toasts
@inject DialogService Dialogs
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* The physical stock take (SPEC §11.6, mockup 038): opened on a warehouse at a date (and perhaps a category), it freezes
the book quantity and cost of each item; the counts are typed on the list or read from a scanner file; posting turns
the differences into gain and loss movements at the date of the count. *@
<KhPageTitle Text="@Title" Icon="file-check" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
}
else if (!Session.Permissions.Allows(InventoryService.EntryReadPermission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else if (Id is null)
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["Inventory.StockTake.New"]" Icon="plus">
@if (CanWrite)
{
<KhForm Layout="KhFormLayout.Grid" Validation="_validation" Class="kh-import-options">
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="WarehouseId" Options="_warehouses" Value="@PartyScreens.Text(_warehouse)"
ValueChanged="v => _warehouse = PartyScreens.Id(v)" Span="12" Required="true" />
<KhDateBox Label="@T["Inventory.StockTake.Date"]" Name="TakeDate" Value="_date" ValueChanged="v => _date = v" Span="6" Required="true" />
<KhSelect TValue="string" Label="@T["Items.Radar.Category"]" Name="CategoryId" Options="_lookups.Categories" Empty="@T["Inventory.StockTake.AllCategories"]"
Value="@PartyScreens.Text(_category)" ValueChanged="v => _category = PartyScreens.Id(v)" Span="6" />
<KhTextBox Label="@T["Inventory.StockTake.Description"]" Name="Description" Value="@_description" ValueChanged="v => _description = v" Span="12"
Hint="@T["Inventory.StockTake.DescriptionHint"]" />
<div class="c12 kh-endrow">
<button type="button" class="btn primary" disabled="@(_busy || _warehouse is null || _date is null)" @onclick="CreateAsync">
<KhIcon Name="file-check" /> @T["Inventory.StockTake.Open"]
</button>
</div>
</KhForm>
}
<p class="muted sm kh-pad">@T["Inventory.StockTake.Hint"]</p>
</KhPanel>
</div>
<div class="kh-import-main">
<KhPanel Title="@T["Inventory.StockTake.List"]" Icon="list">
@if (_takes.Count == 0)
{
<p class="muted kh-pad">@T["Inventory.StockTake.None"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Inventory.StockTake.List"]">
<thead>
<tr>
<th scope="col">@T["Inventory.StockTake.Date"]</th>
<th scope="col">@T["Inventory.StockTake.Description"]</th>
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
<th scope="col">@T["Items.Radar.State"]</th>
</tr>
</thead>
<tbody>
@foreach (var take in _takes)
{
<tr>
<td>@T.Date(take.TakeDate)</td>
<td><a href="magazzino/inventario/@take.Id">@take.Description</a></td>
<td>@PartyScreens.Describe(_warehouses, take.WarehouseId)</td>
<td><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
</div>
</div>
}
else if (_view is null)
{
<div class="kh-message"><KhIcon Name="alert" Class="lg" /><h1>@T["Inventory.StockTake.Missing"]</h1><p><a href="magazzino/inventario">@T["Inventory.StockTake.List"]</a></p></div>
}
else
{
var take = _view.Take;
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@take.Description" Icon="file-check">
<KhVSteps Items="Steps" Current="Step" Label="@T["Inventory.StockTake.Procedure"]" />
<dl class="kh-facts">
<dt>@T["Inventory.Fields.Warehouse"]</dt><dd>@PartyScreens.Describe(_warehouses, take.WarehouseId)</dd>
<dt>@T["Inventory.StockTake.Date"]</dt><dd>@T.Date(take.TakeDate)</dd>
<dt>@T["Items.Radar.Category"]</dt><dd>@(PartyScreens.Describe(_lookups.Categories, take.CategoryId) ?? T["Inventory.StockTake.AllCategories"])</dd>
<dt>@T["Items.Radar.State"]</dt><dd><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></dd>
@if (take.Status == StockTakeStatus.Posted)
{
<dt>@T["Inventory.StockTake.Movements"]</dt>
<dd>
@if (take.AdjustmentDocumentId is { } gain)
{
<a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, gain)">@StockTakeService.GainReason</a>
}
@if (take.LossDocumentId is { } loss)
{
<span> </span><a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, loss)">@StockTakeService.LossReason</a>
}
</dd>
}
</dl>
@if (IsOpen && CanWrite)
{
<div class="kh-endrow kh-pad">
<button type="button" class="btn" disabled="@_busy" @onclick="CancelAsync"><KhIcon Name="x-circle" /> @T["Inventory.StockTake.Cancel"]</button>
</div>
}
</KhPanel>
</div>
<div class="kh-import-main">
<KhStrip Items="Stats" Label="@T["Inventory.StockTake.Procedure"]" />
<KhPanel Title="@T["Inventory.StockTake.Lines"]" Icon="list">
<ChildContent>
<div class="kh-taketools">
<input type="search" class="in kh-searchbox" placeholder="@T["Inventory.Stock.Search"]" aria-label="@T["Inventory.Stock.Search"]"
value="@_search" @oninput="e => _search = e.Value?.ToString()" />
<select class="in" aria-label="@T["Inventory.StockTake.Show"]" @onchange="e => _show = e.Value?.ToString() ?? string.Empty">
<option value="" selected="@(_show.Length == 0)">@T["Inventory.StockTake.ShowAll"]</option>
<option value="todo" selected="@(_show == "todo")">@T["Inventory.StockTake.ShowToCount"]</option>
<option value="diff" selected="@(_show == "diff")">@T["Inventory.StockTake.ShowDifferences"]</option>
</select>
@if (IsOpen && CanWrite)
{
<label class="btn kh-filebtn">
<KhIcon Name="upload" /> @T["Inventory.StockTake.Import"]
<InputFile OnChange="ImportAsync" accept=".csv,.txt,text/csv,text/plain" disabled="@_busy" />
</label>
<button type="button" class="btn" disabled="@(_busy || _counts.Count == 0)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Inventory.StockTake.Save"]</button>
@if (Session.Permissions.Allows(InventoryService.PostPermission))
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="PostAsync"><KhIcon Name="check-circle" /> @T["Inventory.StockTake.Post"]</button>
}
}
</div>
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Inventory.StockTake.Lines"]">
<thead>
<tr>
<th scope="col">@T["Items.Fields.Code"]</th>
<th scope="col">@T["Items.Fields.Description"]</th>
<th scope="col">@T["Items.Radar.Unit"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.Book"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.Counted"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.Difference"]</th>
@if (_costs)
{
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
<th scope="col" class="num">@T["Inventory.StockTake.DifferenceValue"]</th>
}
<th scope="col">@T["Items.Radar.State"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in Shown)
{
var id = line.Line.Id;
var counted = CountOf(line);
var difference = counted is { } c ? c - line.Line.BookQuantity : 0m;
<tr class="@(counted is not null && difference != 0m ? "hl" : null)">
<td class="code">@line.Code</td>
<td>@line.Description</td>
<td>@PartyScreens.Describe(_lookups.Units, line.UnitOfMeasureId)</td>
<td class="num">@Qty(line.Line.BookQuantity)</td>
<td class="num">
@if (IsOpen && CanWrite)
{
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.StockTake.Counted"] + " " + line.Code)"
value="@(counted is { } v ? Qty(v) : null)" @onchange="e => SetCount(id, e.Value?.ToString())" />
}
else
{
@(counted is { } v ? Qty(v) : "—")
}
</td>
<td class="num @(difference < 0m ? "err" : difference > 0m ? "ok" : null)">@(counted is null ? null : Qty(difference))</td>
@if (_costs)
{
<td class="num">@T.Money(line.Line.UnitCost)</td>
<td class="num">@(counted is null ? null : T.Money(Math.Round(difference * line.Line.UnitCost, 2)))</td>
}
<td>
@if (counted is null)
{
<KhBadge Tone="KhTone.Neutral">@T["Inventory.StockTake.ToCount"]</KhBadge>
}
else if (difference == 0m)
{
<KhBadge Tone="KhTone.Ok">@T["Inventory.StockTake.Matches"]</KhBadge>
}
else
{
<KhBadge Tone="KhTone.Warning">@T["Inventory.StockTake.Differs"]</KhBadge>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</ChildContent>
</KhPanel>
</div>
</div>
}
@code {
private readonly KhValidation _validation = new();
private readonly Dictionary<long, decimal?> _counts = [];
private IReadOnlyList<StockTake> _takes = [];
private IReadOnlyList<KhOption<string>> _warehouses = [];
private ItemLookups _lookups = ItemLookups.Empty;
private StockTakeView? _view;
private long? _warehouse;
private long? _category;
private DateOnly? _date;
private string? _description;
private string? _search;
private string _show = string.Empty;
private bool _costs;
private bool _loaded;
private bool _busy;
/// <summary>The stock take shown, or none for the list.</summary>
[Parameter]
public long? Id { get; set; }
private string Title => _view?.Take.Description is { } description && Id is not null ? description : T["Inventory.StockTake.Title"];
private bool CanWrite => Session.Permissions.Allows("inventory.entry.write");
private bool IsOpen => _view?.Take.Status == StockTakeStatus.Open;
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
private IReadOnlyList<KhStep> Steps =>
[
new(T["Inventory.StockTake.Steps.Open"], T["Inventory.StockTake.Steps.OpenDetail"]),
new(T["Inventory.StockTake.Steps.Count"], T["Inventory.StockTake.Steps.CountDetail"]),
new(T["Inventory.StockTake.Steps.Check"], T["Inventory.StockTake.Steps.CheckDetail"]),
new(T["Inventory.StockTake.Steps.Post"], T["Inventory.StockTake.Steps.PostDetail"]),
];
private int Step => _view is null ? 0 : _view.Take.Status != StockTakeStatus.Open ? 4 : Counted == 0 ? 1 : Counted < _view.Lines.Count ? 1 : 2;
private int Counted => _view?.Lines.Count(l => CountOf(l) is not null) ?? 0;
private IReadOnlyList<KhStat> Stats
{
get
{
if (_view is null)
{
return [];
}
var counted = _view.Lines.Where(l => CountOf(l) is not null).ToList();
var differences = counted.Where(l => CountOf(l) != l.Line.BookQuantity).ToList();
var value = differences.Sum(l => Math.Round((CountOf(l)!.Value - l.Line.BookQuantity) * l.Line.UnitCost, 2));
return
[
new(T["Inventory.StockTake.Items"], T.Number(_view.Lines.Count)),
new(T["Inventory.StockTake.CountedItems"], T.Number(counted.Count), counted.Count == _view.Lines.Count ? KhTone.Ok : KhTone.Neutral),
new(T["Inventory.StockTake.Differences"], T.Number(differences.Count), differences.Count > 0 ? KhTone.Warning : KhTone.Neutral),
.. _costs ? [new KhStat(T["Inventory.StockTake.DifferenceValue"], T.Money(value), value < 0m ? KhTone.Error : KhTone.Neutral)] : Array.Empty<KhStat>(),
];
}
}
private IEnumerable<StockTakeLineView> Shown => (_view?.Lines ?? []).Where(l =>
(string.IsNullOrWhiteSpace(_search)
|| l.Code.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase)
|| l.Description.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase))
&& _show switch
{
"todo" => CountOf(l) is null,
"diff" => CountOf(l) is { } c && c != l.Line.BookQuantity,
_ => true,
});
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.EntryReadPermission))
{
if (!_loaded)
{
_lookups = await ItemLookups.ForRadarAsync(Tables, actor, company);
_warehouses = [.. (await Tables.ActiveAsync<Warehouse>(actor, company)).Select(w => new KhOption<string>(PartyScreens.Text(w.Id)!, w.Code + " · " + w.Description))];
_warehouse = await DefaultWarehouseAsync(actor, company);
_costs = await Items.CanSeeCostsAsync(actor, company);
_date = Today;
}
_counts.Clear();
if (Id is { } id)
{
_view = await StockTakes.GetAsync(actor, company, id);
}
else
{
_view = null;
_takes = await StockTakes.ListAsync(actor, company);
}
}
_loaded = true;
}
private async Task<long?> DefaultWarehouseAsync(Actor actor, string company) =>
(await Tables.ActiveAsync<Warehouse>(actor, company)).OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id;
private decimal? CountOf(StockTakeLineView line) => _counts.TryGetValue(line.Line.Id, out var count) ? count : line.Line.CountedQuantity;
private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture);
private static KhTone ToneOf(StockTakeStatus status) => status switch
{
StockTakeStatus.Posted => KhTone.Ok,
StockTakeStatus.Cancelled => KhTone.Neutral,
_ => KhTone.Info,
};
private void SetCount(long lineId, string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
_counts[lineId] = null;
return;
}
if (decimal.TryParse(text.Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value) && value >= 0m)
{
_counts[lineId] = value;
}
else
{
Toasts.Show(ToastKind.Error, T["inventory.stock-take.negative"]);
}
}
private async Task CreateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _warehouse is not { } warehouse || _date is not { } date)
{
return;
}
_busy = true;
try
{
var view = await StockTakes.CreateAsync(actor, company, warehouse, date, _category, _description);
Toasts.Show(ToastKind.Success, T.Format("Inventory.StockTake.Opened", view.Lines.Count));
Navigation.NavigateTo("magazzino/inventario/" + view.Take.Id.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
catch (ValidationFailedException ex)
{
ShowErrors(ex);
}
finally
{
_busy = false;
}
}
private async Task SaveAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id || _counts.Count == 0)
{
return;
}
_busy = true;
try
{
_view = await StockTakes.SaveCountsAsync(actor, company, id, _counts);
_counts.Clear();
Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Saved"]);
}
catch (ValidationFailedException ex)
{
ShowErrors(ex);
}
finally
{
_busy = false;
}
}
private async Task ImportAsync(InputFileChangeEventArgs e)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id)
{
return;
}
_busy = true;
try
{
if (_counts.Count > 0)
{
await StockTakes.SaveCountsAsync(actor, company, id, _counts);
_counts.Clear();
}
using var buffer = new MemoryStream();
await using (var stream = e.File.OpenReadStream(5 * 1024 * 1024))
{
await stream.CopyToAsync(buffer);
}
buffer.Position = 0;
var result = await StockTakes.ImportCountsAsync(actor, company, id, buffer);
_view = await StockTakes.GetAsync(actor, company, id);
Toasts.Show(result.Unknown.Count == 0 ? ToastKind.Success : ToastKind.Warning,
T.Format("Inventory.StockTake.Imported", result.Applied, result.Unknown.Count) + (result.Unknown.Count == 0 ? string.Empty : " " + string.Join(", ", result.Unknown.Take(5))));
}
catch (ValidationFailedException ex)
{
ShowErrors(ex);
}
catch (IOException)
{
Toasts.Show(ToastKind.Error, T["Inventory.StockTake.FileTooLarge"]);
}
finally
{
_busy = false;
}
}
private async Task PostAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id)
{
return;
}
if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.PostTitle"], T["Inventory.StockTake.PostText"], T["Inventory.StockTake.Post"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
if (_counts.Count > 0)
{
await StockTakes.SaveCountsAsync(actor, company, id, _counts);
_counts.Clear();
}
_view = await StockTakes.PostAsync(actor, company, id);
Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Posted"]);
}
catch (ValidationFailedException ex)
{
ShowErrors(ex);
}
catch (InvalidDocumentActionException)
{
Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]);
}
finally
{
_busy = false;
}
}
private async Task CancelAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id)
{
return;
}
if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.CancelTitle"], T["Inventory.StockTake.CancelText"], T["Inventory.StockTake.Cancel"], T["Common.Back"], Danger: true)))
{
return;
}
await StockTakes.CancelAsync(actor, company, id);
_view = await StockTakes.GetAsync(actor, company, id);
}
private void ShowErrors(ValidationFailedException ex) =>
Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c)));
}
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more