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>
This commit was merged in pull request #126.
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 03:49:32 +01:00
commit cfca29d71c
83 files changed
+13838 -497

No files matched your search

+50
View File
@@ -7,6 +7,56 @@ 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
+385
View File
@@ -731,6 +731,7 @@ Migrazioni applicate in ordine:
- `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`
@@ -1165,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 |
@@ -2807,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 |
@@ -2969,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 |
@@ -2990,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 -->
+19 -8
View File
@@ -2,21 +2,24 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**Ultimo aggiornamento:** 2026-11-12
**Milestone corrente:** M7 — Contabilità generale (issue #62-#68), **non ancora iniziata**: si parte quando il
titolare lo dice. M6 chiusa: PR #125 in `main`, tag `v0.6.0`, immagine e release.
**Prossimo passo:** M7 dall'issue #62. #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-0035.
- 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`,
@@ -77,6 +80,14 @@ numero del fornitore al posto di *DDT fornitore* senza numero; FIFO e LIFO a lot
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,
@@ -123,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.
+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).
+3 -3
View File
@@ -10,8 +10,8 @@ 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. Arrivano più avanti: la **registrazione contabile** e i registri IVA (M7),
> i **pagamenti** e lo scadenzario (M8), il **file XML** delle autofatture e lo scarico dal canale SDI (M9).
> 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
@@ -137,7 +137,7 @@ di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` dell
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 con la [Contabilità](Contabilita) (M7). Le definizioni ufficiali dei codici TD sono in
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
+2 -1
View File
@@ -137,7 +137,7 @@ il dettaglio dell'ultima. Le esecuzioni sono registrate nel database di sistema.
## Job di sistema
Nella versione 0.6.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 |
|---|---|---|
@@ -147,6 +147,7 @@ Nella versione 0.6.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`)
| `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,
+2 -1
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** completa per 0.6.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,7 @@ 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. |
+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)
+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
+10 -8
View File
@@ -1,6 +1,6 @@
# Guida all'uso
> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6)
> **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,19 +9,21 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c
## Che cosa c'è in questa versione
| Area | In 0.6.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, 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 | contabilità M7, partite 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 | registri IVA M7, 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 | libro inventari M7 |
| Contabilità, IVA, scadenzario | — | M7, M8 |
| 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, prezzi e giacenze iniziali da CSV, Excel e JSON; esportazione dai radar | 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.
@@ -189,5 +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) ·
[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.6.0 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6; 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)
+11 -8
View File
@@ -1,6 +1,6 @@
# Import/Export
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (giacenze iniziali dalla 0.6.0, 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
@@ -103,7 +103,7 @@ magazzino per deposito** con la causale `APE` (esistenza iniziale) alla data del
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.
@@ -116,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 |
@@ -161,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
@@ -213,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
@@ -234,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
+2 -2
View File
@@ -11,7 +11,7 @@ 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** (M7), i report di magazzino stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0).
> **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
@@ -150,7 +150,7 @@ fornitore non vengono ordinate.
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 [Contabilità](Contabilita) (M7).
inventari con la chiusura dell'esercizio (M10).
## Ricostruzione
+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), M6 (0.6.0). **Prossima:** M7.
**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
+3 -2
View File
@@ -10,8 +10,9 @@ 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. Dalla 0.6 i documenti **muovono il magazzino** (DDT e fatture
> accompagnatorie scaricano, gli ordini impegnano: vedi [Magazzino](Magazzino)). Arrivano più avanti: la
> **registrazione contabile** (M7), le **partite** e il controllo del fido (M8), il **file XML** per lo
> 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'è.
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

@@ -115,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>
@@ -124,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);
@@ -269,6 +273,7 @@ public sealed partial class DocumentEngine
{
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -357,6 +362,7 @@ public sealed partial class DocumentEngine
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);
}
@@ -703,6 +709,7 @@ public sealed partial class DocumentEngine
// A cancelled delivery note gives its stock back; a closed or reopened order its open quantities.
await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName);
}
@@ -2,6 +2,7 @@ using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Data;
namespace Khaemhat.Application.ImportExport;
@@ -17,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
@@ -145,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));
@@ -182,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";
@@ -204,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;
@@ -216,15 +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);
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
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))
{
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.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<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),
])];
}
}
@@ -59,6 +59,7 @@ public sealed class JobScheduler
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,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,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;
}
}
@@ -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,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);
});
}
}
+14 -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>
+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,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"));
@@ -24,6 +24,9 @@ public sealed class ItalyFiscalPack : FiscalPackBase
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,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));
}
}
}
@@ -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,7 +40,7 @@ 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);
@@ -0,0 +1,316 @@
@page "/contabilita/piano-dei-conti"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerService Ledger
@inject LedgerQueryService Queries
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The chart of accounts and the account ledger (SPEC §11.7, mockup 042): mastri, conti and sottoconti in three levels
with the line of the legal statements, the account chosen with its data and its movements in a period, each with
the way to its entry. Accounts with movements or children cannot be deleted, only disabled. *@
<KhPageTitle Text="@T["Ledger.Accounts.Title"]" Icon="layers" />
<LedgerGuard Permission="@LedgerPermissions.AccountRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Accounts.Title"]</div>
<h1>@T["Ledger.Accounts.Heading"]</h1>
<div class="sub">@T["Ledger.Accounts.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (CanWrite)
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="() => Edit(null)"><KhIcon Name="plus" /> @T["Ledger.Accounts.New"]</button>
}
</div>
</div>
<div class="kh-ledger-split">
<KhPanel Title="@T["Ledger.Accounts.Chart"]" Icon="list" Tight="true">
<div class="filters">
<input type="search" class="in" placeholder="@T["Ledger.Accounts.Search"]" aria-label="@T["Ledger.Accounts.Search"]" value="@_search"
@oninput="e => _search = e.Value?.ToString()" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Accounts.Count", T.Number(_accounts.Count))</span>
</div>
<div class="kh-ledger-tree">
<table class="grid" aria-label="@T["Ledger.Accounts.Chart"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Code"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Fields.Nature"]</th>
<th scope="col">@T["Ledger.Fields.StatementLine"]</th>
</tr>
</thead>
<tbody>
@foreach (var a in Visible)
{
<tr class="@(a.Id == _selected?.Id ? "sel" : null) @(a.Disabled ? "muted" : null)" style="cursor:pointer" @onclick="() => SelectAsync(a)">
<td class="code lvl@(a.Level)" style="padding-left:@((a.Level - 1) * 14 + 8)px">@a.Code</td>
<td class="lvl@(a.Level)">@a.Description</td>
<td>@T[LedgerScreens.EnumKey(a.Nature)]</td>
<td class="code">@a.StatementLine</td>
</tr>
}
</tbody>
</table>
</div>
</KhPanel>
<div class="kh-ledger-side">
@if (_editing)
{
<KhPanel Title="@T[_id is null ? "Ledger.Accounts.New" : "Ledger.Accounts.Edit"]" Icon="edit">
<div class="form plain">
<KhTextBox Label="@T["Ledger.Fields.Code"]" Name="code" @bind-Value="_code" Span="4" Required="true" Mono="true" MaxLength="20" Hint="@T["Ledger.Accounts.CodeHint"]" Disabled="@(_id is not null)" />
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="description" @bind-Value="_description" Span="8" Required="true" MaxLength="100" />
<KhSelect TValue="AccountNature" Label="@T["Ledger.Fields.Nature"]" Name="nature" Options="LedgerScreens.Choices<AccountNature>(T)" @bind-Value="_nature" Span="6" />
<KhSelect TValue="AccountType" Label="@T["Ledger.Fields.Type"]" Name="type" Options="LedgerScreens.Choices<AccountType>(T)" @bind-Value="_type" Span="6" />
<KhTextBox Label="@T["Ledger.Fields.StatementLine"]" Name="cee" @bind-Value="_statementLine" Span="6" MaxLength="20" Mono="true" Hint="@T["Ledger.Accounts.CeeHint"]" />
<KhTextBox Label="@T["Ledger.Fields.Reclassification"]" Name="reclass" @bind-Value="_reclassification" Span="6" MaxLength="20" Mono="true" />
<KhCheck Label="@T["Ledger.Fields.SubLedger"]" Name="subledger" @bind-Value="_subLedger" Span="6" />
<KhCheck Label="@T["Ledger.Fields.VatRelevant"]" Name="vat" @bind-Value="_vatRelevant" Span="6" />
<KhCheck Label="@T["Ledger.Fields.ClosesAutomatically"]" Name="closes" @bind-Value="_closes" Span="6" />
<KhCheck Label="@T["Ledger.Fields.Disabled"]" Name="disabled" @bind-Value="_disabled" Span="6" />
</div>
<div class="kh-formactions">
@if (_id is { } id)
{
<button type="button" class="btn" disabled="@_busy" @onclick="() => DeleteAsync(id)"><KhIcon Name="trash" /> @T["Common.Delete"]</button>
}
<button type="button" class="btn" @onclick="() => _editing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</div>
</KhPanel>
}
else if (_selected is { } account)
{
<KhPanel Title="@(account.Code + " · " + account.Description)" Icon="book">
<Actions>
@if (CanWrite)
{
<button type="button" class="btn sm" @onclick="() => Edit(account)"><KhIcon Name="edit" /> @T["Common.Edit"]</button>
}
</Actions>
<ChildContent>
<dl class="kv">
<dt>@T["Ledger.Fields.Level"]</dt><dd>@T[$"Ledger.Accounts.Level{account.Level}"]</dd>
<dt>@T["Ledger.Fields.Nature"]</dt><dd>@T[LedgerScreens.EnumKey(account.Nature)]</dd>
<dt>@T["Ledger.Fields.Type"]</dt><dd>@T[LedgerScreens.EnumKey(account.Type)]</dd>
<dt>@T["Ledger.Fields.StatementLine"]</dt><dd class="code">@(account.StatementLine ?? "-")</dd>
<dt>@T["Ledger.Fields.SubLedger"]</dt><dd>@T[account.SubLedger ? "Common.Yes" : "Common.No"]</dd>
</dl>
</ChildContent>
</KhPanel>
@if (account.Postable && Session.Permissions.Allows(LedgerPermissions.EntryRead))
{
<KhPanel Title="@T["Ledger.Accounts.Ledger"]" Icon="list" Tight="true">
<Actions>
<button type="button" class="btn sm" disabled="@_busy" @onclick="PrintAsync"><KhIcon Name="printer" /> @T["Ledger.Print"]</button>
</Actions>
<ChildContent>
<MovementsTable Page="_page" From="_from" To="_to" FromChanged="SetFromAsync" ToChanged="SetToAsync" OnPage="PageAsync" Offset="_offset" PageSize="PageSize" ShowAccount="false" />
</ChildContent>
</KhPanel>
}
}
else
{
<p class="kh-wempty">@T["Ledger.Accounts.Choose"]</p>
}
</div>
</div>
</LedgerGuard>
@code {
private const int PageSize = 30;
private IReadOnlyList<GlAccount> _accounts = [];
private GlAccount? _selected;
private string? _search;
private bool _busy;
private LedgerPage? _page;
private int _offset;
private DateOnly? _from;
private DateOnly? _to;
private bool _editing;
private long? _id;
private string? _code;
private string? _description;
private AccountNature _nature;
private AccountType _type;
private string? _statementLine;
private string? _reclassification;
private bool _subLedger;
private bool _vatRelevant;
private bool _closes = true;
private bool _disabled;
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.AccountWrite);
private IEnumerable<GlAccount> Visible => string.IsNullOrWhiteSpace(_search)
? _accounts
: _accounts.Where(a => a.Code.StartsWith(_search.Trim(), StringComparison.OrdinalIgnoreCase) || a.Description.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase));
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
_from = new DateOnly(today.Year, 1, 1);
_to = new DateOnly(today.Year, 12, 31);
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.AccountRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_accounts = await Ledger.AccountsAsync(actor, company);
}
}
private async Task SelectAsync(GlAccount account)
{
_selected = account;
_editing = false;
_offset = 0;
await LoadMovementsAsync();
}
private async Task LoadMovementsAsync()
{
_page = null;
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { Postable: true } account
|| _from is not { } from || _to is not { } to || !Session.Permissions.Allows(LedgerPermissions.EntryRead))
{
return;
}
_page = await Queries.MovementsAsync(actor, company, new LedgerFilter(account.Id, null, from, to, false, _offset, PageSize));
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
_offset = 0;
await LoadMovementsAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
_offset = 0;
await LoadMovementsAsync();
}
private async Task PageAsync(int offset)
{
_offset = offset;
await LoadMovementsAsync();
}
private async Task PrintAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { } account || _from is not { } from || _to is not { } to)
{
return;
}
_busy = true;
try
{
await LedgerScreens.DownloadAsync(JS, await Queries.PrintMovementsAsync(actor, company, new LedgerFilter(account.Id, null, from, to)));
}
finally
{
_busy = false;
}
}
private void Edit(GlAccount? account)
{
_id = account?.Id;
_code = account?.Code ?? (_selected is { Level: < 3 } parent ? parent.Code + "." : null);
_description = account?.Description;
_nature = account?.Nature ?? _selected?.Nature ?? AccountNature.Asset;
_type = account?.Type ?? (account is null ? _selected?.Type ?? AccountType.Generic : AccountType.Generic);
_statementLine = account?.StatementLine ?? (account is null ? _selected?.StatementLine : null);
_reclassification = account?.Reclassification;
_subLedger = account?.SubLedger ?? false;
_vatRelevant = account?.VatRelevant ?? false;
_closes = account?.ClosesAutomatically ?? true;
_disabled = account?.Disabled ?? false;
_editing = true;
}
private async Task SaveAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var saved = await Ledger.SaveAccountAsync(actor, company, new AccountInput(_id, _code ?? string.Empty, _description ?? string.Empty, _nature, _type)
{
StatementLine = _statementLine,
Reclassification = _reclassification,
SubLedger = _subLedger,
VatRelevant = _vatRelevant,
ClosesAutomatically = _closes,
Disabled = _disabled,
});
_accounts = await Ledger.AccountsAsync(actor, company);
_selected = _accounts.FirstOrDefault(a => a.Id == saved.Id);
_editing = false;
Toasts.Show(ToastKind.Success, T["Ledger.Saved"], saved.Code);
await LoadMovementsAsync();
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotSaved"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private async Task DeleteAsync(long id)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Accounts.Delete"], T.Format("Ledger.Accounts.DeleteText", _code ?? string.Empty), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
await Ledger.DeleteAccountAsync(actor, company, id);
_accounts = await Ledger.AccountsAsync(actor, company);
_selected = null;
_editing = false;
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,207 @@
@page "/contabilita/bilancio"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Accounting
@using Khaemhat.Core.Tables
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerQueryService Queries
@inject TableService Tables
@inject ToastService Toasts
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The trial balance and the general journal (SPEC §11.7, issue #67): the balances of every account in a period, with
the totals of conti and mastri, by cost center too, debits and credits that must match and the result of the
period; the print of the trial balance and of the general journal, provisional or of the final entries. *@
<KhPageTitle Text="@T["Ledger.Balance.Title"]" Icon="chart" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Balance.Title"]</div>
<h1>@T["Ledger.Balance.Heading"]</h1>
<div class="sub">@T["Ledger.Balance.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<button type="button" class="btn" disabled="@(_busy || _from is null || _to is null)" @onclick="PrintAsync"><KhIcon Name="printer" /> @T["Ledger.Balance.Print"]</button>
<button type="button" class="btn" disabled="@(_busy || _from is null || _to is null)" @onclick="() => JournalAsync(final: false)"><KhIcon Name="book" /> @T["Ledger.Balance.JournalProvisional"]</button>
<button type="button" class="btn" disabled="@(_busy || _from is null || _to is null)" @onclick="() => JournalAsync(final: true)"><KhIcon Name="lock" /> @T["Ledger.Balance.JournalFinal"]</button>
</div>
</div>
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="from" Value="_from" ValueChanged="SetFromAsync" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="to" Value="_to" ValueChanged="SetToAsync" />
<KhSelect TValue="long?" Label="@T["Ledger.Fields.CostCenter"]" Name="center" Options="CenterChoices" Value="_center" ValueChanged="SetCenterAsync" Empty="@T["Ledger.Balance.AllCenters"]" />
<KhSelect TValue="int" Label="@T["Ledger.Balance.Detail"]" Name="level" Options="LevelChoices" @bind-Value="_level" />
<KhCheck Label="@T["Ledger.Balance.Drafts"]" Name="drafts" Value="_drafts" ValueChanged="SetDraftsAsync" />
</div>
@if (_balance is { } balance)
{
<KhStrip Items="Stats(balance)" Label="@T["Ledger.Balance.Title"]" />
@if (balance.Lines.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Balance.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid kh-ledger-tree" aria-label="@T["Ledger.Balance.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Account"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col" class="num">@T["Ledger.Balance.Opening"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col" class="num">@T["Ledger.Balance.Debit"]</th>
<th scope="col" class="num">@T["Ledger.Balance.Credit"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in balance.Lines.Where(l => l.Level <= _level))
{
<tr>
<td class="code lvl@(line.Level)" style="padding-left:@((line.Level - 1) * 14 + 8)px">@line.Code</td>
<td class="lvl@(line.Level)">@line.Description</td>
<td class="num">@(line.Opening == 0m ? null : LedgerScreens.Balance(T, line.Opening))</td>
<td class="num">@LedgerScreens.AmountText(T, line.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, line.Credit)</td>
<td class="num">@(line.Closing > 0m ? T.Money(line.Closing) : null)</td>
<td class="num">@(line.Closing < 0m ? T.Money(-line.Closing) : null)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="3"><b>@T["Ledger.Balance.Totals"]</b></td>
<td class="num"><b>@T.Money(balance.TotalDebit)</b></td>
<td class="num"><b>@T.Money(balance.TotalCredit)</b></td>
<td colspan="2" class="num"><b>@T[balance.Result >= 0m ? "Ledger.Balance.Profit" : "Ledger.Balance.Loss"] @T.Money(Math.Abs(balance.Result))</b></td>
</tr>
</tfoot>
</table>
</div>
}
}
</KhPanel>
</LedgerGuard>
@code {
private DateOnly? _from;
private DateOnly? _to;
private long? _center;
private int _level = 3;
private bool _drafts;
private bool _busy;
private TrialBalance? _balance;
private IReadOnlyList<CostCenter> _centers = [];
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhOption<long?>> CenterChoices => [.. _centers.Select(c => new KhOption<long?>(c.Id, c.Code + " · " + c.Description))];
private IReadOnlyList<KhOption<int>> LevelChoices =>
[
new(1, T["Ledger.Accounts.Level1"]),
new(2, T["Ledger.Accounts.Level2"]),
new(3, T["Ledger.Accounts.Level3"]),
];
private IReadOnlyList<KhStat> Stats(TrialBalance balance) =>
[
new(T["Ledger.Side.Dare"], T.Money(balance.TotalDebit)),
new(T["Ledger.Side.Avere"], T.Money(balance.TotalCredit)),
new(T["Ledger.Balance.Check"], T[balance.Balanced ? "Ledger.Balance.Balanced" : "Ledger.Balance.NotBalanced"], balance.Balanced ? KhTone.Ok : KhTone.Error),
new(T["Ledger.Balance.Result"], T.Money(balance.Result), balance.Result >= 0m ? KhTone.Ok : KhTone.Warning),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, 1, 1);
_to = Today;
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.EntryRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
try
{
_centers = await Tables.ActiveAsync<CostCenter>(actor, company);
}
catch (AccessDeniedException)
{
_centers = [];
}
await LoadAsync();
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to)
{
return;
}
_balance = await Queries.TrialBalanceAsync(actor, company, from, to, _center, _drafts);
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
await LoadAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
await LoadAsync();
}
private async Task SetCenterAsync(long? center)
{
_center = center;
await LoadAsync();
}
private async Task SetDraftsAsync(bool drafts)
{
_drafts = drafts;
await LoadAsync();
}
private async Task PrintAsync() => await RunAsync(async (actor, company, from, to) =>
await LedgerScreens.DownloadAsync(JS, await Queries.PrintTrialBalanceAsync(actor, company, from, to, _center)));
private async Task JournalAsync(bool final) => await RunAsync(async (actor, company, from, to) =>
await LedgerScreens.DownloadAsync(JS, await Queries.PrintJournalAsync(actor, company, from, to, final)));
private async Task RunAsync(Func<Actor, string, DateOnly, DateOnly, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to)
{
return;
}
_busy = true;
try
{
await action(actor, company, from, to);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,655 @@
@page "/contabilita/prima-nota/nuova"
@page "/contabilita/prima-nota/{Id:long}"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Parties
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Accounting
@using Khaemhat.Core.Tables
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject JournalEntryService Journal
@inject LedgerService Ledger
@inject PartyService Parties
@inject TableService Tables
@inject ToastService Toasts
@inject DialogService Dialogs
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* An entry of the journal (SPEC §11.7, mockups 040-041): guided by a journal template, which proposes the accounts
and the sides, or typed by hand; the totals and the imbalance are always in view and an entry is posted only when it
balances; the VAT lines feed the VAT register of the entry. Entries of documents and final entries are read only:
they are changed by the document, or reversed. *@
<KhPageTitle Text="@Title" Icon="book" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else
{
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / <a href="@(LedgerScreens.BasePath + "/prima-nota")">@T["Ledger.Journal.Title"]</a> / @Title</div>
<h1>@Title</h1>
<div class="sub">
@if (_entry is { } e)
{
<KhBadge Tone="LedgerScreens.ToneOf(e.Status)">@T[LedgerScreens.EnumKey(e.Status)]</KhBadge>
<span> @T[LedgerScreens.EnumKey(e.Source)]</span>
@if (e.JournalNumber is { } j)
{
<span> · @T.Format("Ledger.Entry.JournalNumber", j)</span>
}
@if (e.ReversalOfId is { } of)
{
<span> · <a href="@LedgerScreens.EntryUrl(of)">@T["Ledger.Entry.ReversalOf"]</a></span>
}
@if (e.ReversedById is { } by)
{
<span> · <a href="@LedgerScreens.EntryUrl(by)">@T["Ledger.Entry.ReversedBy"]</a></span>
}
}
else
{
@T["Ledger.Entry.NewHint"]
}
</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (Editable && CanWrite)
{
<button type="button" class="btn" disabled="@_busy" @onclick="() => SaveAsync(post: false)"><KhIcon Name="save" /> @T["Ledger.Entry.SaveDraft"]</button>
<button type="button" class="btn primary" disabled="@(_busy || !Balanced)" @onclick="() => SaveAsync(post: true)"><KhIcon Name="check" /> @T["Ledger.Entry.Post"]</button>
}
@if (_entry is { } current && CanWrite)
{
@if (current.Status != GlEntryStatus.Draft && current.ReversedById is null && current.ReversalOfId is null)
{
<button type="button" class="btn" disabled="@_busy" @onclick="ReverseAsync"><KhIcon Name="undo" /> @T["Ledger.Entry.Reverse"]</button>
}
@if (current.Status != GlEntryStatus.Final && current.Source != GlEntrySource.Document)
{
<button type="button" class="btn" disabled="@_busy" @onclick="DeleteAsync"><KhIcon Name="trash" /> @T["Common.Delete"]</button>
}
}
</div>
</div>
<KhStrip Items="Stats" Label="@T["Ledger.Entry.Totals"]" />
@if (!Balanced && _lines.Any(l => l.Debit != 0m || l.Credit != 0m))
{
<div class="callout err kh-pad" role="alert">
<KhIcon Name="alert" />
<span>@T.Format("Ledger.Entry.Unbalanced", T.Money(Math.Abs(Difference)), T[Difference > 0m ? "Ledger.Side.Avere" : "Ledger.Side.Dare"])</span>
</div>
}
<KhPanel Title="@T["Ledger.Entry.Header"]" Icon="file">
<div class="form plain">
<KhDateBox Label="@T["Ledger.Fields.Date"]" Name="date" @bind-Value="_date" Span="3" Required="true" Disabled="!Editable" />
<KhSelect TValue="long?" Label="@T["Ledger.Fields.Template"]" Name="template" Options="TemplateChoices" Value="_templateId" ValueChanged="SetTemplate"
Empty="@T["Ledger.Entry.NoTemplate"]" Span="5" Disabled="!Editable" />
<KhSelect TValue="long?" Label="@T["Ledger.Fields.VatRegister"]" Name="register" Options="RegisterChoices" @bind-Value="_registerId"
Empty="@T["Ledger.Entry.NoRegister"]" Span="4" Disabled="!Editable" />
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="description" @bind-Value="_description" Span="6" Required="true" MaxLength="200" Disabled="!Editable" />
<KhTextBox Label="@T["Ledger.Fields.DocumentNumber"]" Name="docnumber" @bind-Value="_documentNumber" Span="3" MaxLength="30" Disabled="!Editable" />
<KhDateBox Label="@T["Ledger.Fields.DocumentDate"]" Name="docdate" @bind-Value="_documentDate" Span="3" Disabled="!Editable" />
</div>
</KhPanel>
<KhPanel Title="@T["Ledger.Entry.Lines"]" Icon="list" Tight="true">
<Actions>
@if (Editable)
{
<button type="button" class="btn sm" @onclick="AddLine"><KhIcon Name="plus" /> @T["Ledger.Entry.AddLine"]</button>
<button type="button" class="btn sm" disabled="@(Balanced || _lines.Count == 0)" @onclick="CloseDifference"><KhIcon Name="check" /> @T["Ledger.Entry.CloseDifference"]</button>
}
</Actions>
<ChildContent>
<datalist id="kh-accounts">
@foreach (var a in _accounts.Where(a => a.Postable && !a.Disabled))
{
<option value="@(a.Code + " · " + a.Description)"></option>
}
</datalist>
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Entry.Lines"]">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">@T["Ledger.Fields.Account"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col">@T["Ledger.Fields.LineDescription"]</th>
<th scope="col">@T["Ledger.Fields.CostCenter"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < _lines.Count; i++)
{
var line = _lines[i];
var n = i + 1;
var account = AccountOf(line.AccountId);
<tr class="@(line.AccountId is null && (line.Debit != 0m || line.Credit != 0m) ? "err" : null)">
<td class="muted">@n</td>
@if (Editable)
{
<td><input class="in" list="kh-accounts" aria-label="@(T["Ledger.Fields.Account"] + " " + n)" value="@AccountText(account)" @onchange="e => SetAccount(line, e.Value?.ToString())" style="min-width:260px" /></td>
<td class="kh-cellpick">
@if (account?.SubLedger == true)
{
<KhHotlink TItem="PartyRow" Name="@("party" + n)" Value="line.Party" ValueChanged="v => line.Party = v" Span="12"
Search="(t, c) => SearchPartiesAsync(account, t, c)" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Placeholder="@T["Ledger.Entry.ChooseParty"]" />
}
</td>
<td><input class="in" maxlength="200" aria-label="@(T["Ledger.Fields.LineDescription"] + " " + n)" value="@line.Description" @onchange="e => line.Description = e.Value?.ToString()" /></td>
<td>
<select class="in" aria-label="@(T["Ledger.Fields.CostCenter"] + " " + n)" @onchange="e => line.CostCenterId = long.TryParse(e.Value?.ToString(), out var c) && c > 0 ? c : null">
<option value="0"></option>
@foreach (var center in _centers)
{
<option value="@center.Id" selected="@(center.Id == line.CostCenterId)">@center.Code</option>
}
</select>
</td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@(T["Ledger.Side.Dare"] + " " + n)" value="@LedgerScreens.AmountText(T, line.Debit)" @onchange="e => SetAmount(line, e.Value?.ToString(), debit: true)" /></td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@(T["Ledger.Side.Avere"] + " " + n)" value="@LedgerScreens.AmountText(T, line.Credit)" @onchange="e => SetAmount(line, e.Value?.ToString(), debit: false)" /></td>
<td><button type="button" class="btn sm" aria-label="@T["Ledger.Entry.RemoveLine"]" @onclick="() => _lines.Remove(line)"><KhIcon Name="trash" /></button></td>
}
else
{
<td><span class="code">@account?.Code</span> @account?.Description</td>
<td>@line.Party?.Name</td>
<td>@line.Description</td>
<td>@_centers.FirstOrDefault(c => c.Id == line.CostCenterId)?.Code</td>
<td class="num">@LedgerScreens.AmountText(T, line.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, line.Credit)</td>
<td></td>
}
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="5" class="num"><b>@T["Ledger.Entry.Totals"]</b></td>
<td class="num"><b>@T.Money(TotalDebit)</b></td>
<td class="num"><b>@T.Money(TotalCredit)</b></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
</ChildContent>
</KhPanel>
@if (_registerId is not null || _vat.Count > 0)
{
<KhPanel Title="@T["Ledger.Entry.Vat"]" Icon="euro" Tight="true">
<Actions>
@if (Editable)
{
<button type="button" class="btn sm" @onclick="() => _vat.Add(new VatLine())"><KhIcon Name="plus" /> @T["Ledger.Entry.AddVat"]</button>
}
</Actions>
<ChildContent>
<table class="grid" aria-label="@T["Ledger.Entry.Vat"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.TaxCode"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var v in _vat)
{
<tr>
@if (Editable)
{
<td>
<select class="in" aria-label="@T["Ledger.Fields.TaxCode"]" @onchange="e => SetTaxCode(v, e.Value?.ToString())">
<option value="0"></option>
@foreach (var taxCode in _taxCodes)
{
<option value="@taxCode.Id" selected="@(taxCode.Id == v.TaxCodeId)">@(taxCode.Code + " · " + taxCode.Description)</option>
}
</select>
</td>
<td class="num">@(v.Nature ?? v.Rate.ToString("0.##", T.Culture) + "%")</td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@T["Ledger.Fields.Taxable"]" value="@LedgerScreens.AmountText(T, v.Taxable)" @onchange="e => SetTaxable(v, e.Value?.ToString())" /></td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@T["Ledger.Fields.Tax"]" value="@LedgerScreens.AmountText(T, v.Tax)" @onchange="e => v.Tax = LedgerScreens.ParseAmount(T, e.Value?.ToString())" /></td>
<td class="num"><input class="in num" inputmode="decimal" aria-label="@T["Ledger.Fields.NonDeductible"]" value="@LedgerScreens.AmountText(T, v.NonDeductible)" @onchange="e => v.NonDeductible = LedgerScreens.ParseAmount(T, e.Value?.ToString())" /></td>
<td><button type="button" class="btn sm" aria-label="@T["Ledger.Entry.RemoveLine"]" @onclick="() => _vat.Remove(v)"><KhIcon Name="trash" /></button></td>
}
else
{
<td>@_taxCodes.FirstOrDefault(c => c.Id == v.TaxCodeId)?.Code</td>
<td class="num">@(v.Nature ?? v.Rate.ToString("0.##", T.Culture) + "%")</td>
<td class="num">@T.Money(v.Taxable)</td>
<td class="num">@T.Money(v.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, v.NonDeductible)</td>
<td></td>
}
</tr>
}
</tbody>
</table>
</ChildContent>
</KhPanel>
}
<KhDialog Open="_reverseOpen" Title="@T["Ledger.Entry.Reverse"]" Icon="undo" OnClose="() => _reverseOpen = false">
<ChildContent>
<p>@T["Ledger.Entry.ReverseText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Entry.ReverseDate"]" Name="reversedate" @bind-Value="_reverseDate" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _reverseOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _reverseDate is null)" @onclick="ConfirmReverseAsync"><KhIcon Name="undo" /> @T["Ledger.Entry.Reverse"]</button>
</Footer>
</KhDialog>
}
</LedgerGuard>
@code {
private bool _loaded;
private bool _busy;
private GlEntry? _entry;
private IReadOnlyList<GlAccount> _accounts = [];
private IReadOnlyList<TemplateView> _templates = [];
private IReadOnlyList<VatRegister> _registers = [];
private IReadOnlyList<TaxCode> _taxCodes = [];
private IReadOnlyList<CostCenter> _centers = [];
private DateOnly? _date;
private long? _templateId;
private long? _registerId;
private string? _description;
private string? _documentNumber;
private DateOnly? _documentDate;
private List<Line> _lines = [];
private List<VatLine> _vat = [];
private bool _reverseOpen;
private DateOnly? _reverseDate;
/// <summary>The entry, or <see langword="null"/> for a new one.</summary>
[Parameter]
public long? Id { get; set; }
private string Title => _entry is { } e ? T.Format("Ledger.Entry.Title", e.EntryNumber ?? T["Ledger.Journal.NoNumber"]) : T["Ledger.Entry.New"];
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.EntryWrite);
private bool Editable => CanWrite && (_entry is null || (_entry.Status != GlEntryStatus.Final && _entry.Source != GlEntrySource.Document));
private decimal TotalDebit => _lines.Sum(l => l.Debit);
private decimal TotalCredit => _lines.Sum(l => l.Credit);
private decimal Difference => TotalDebit - TotalCredit;
private bool Balanced => Difference == 0m && TotalDebit != 0m;
private IReadOnlyList<KhStat> Stats =>
[
new(T["Ledger.Side.Dare"], T.Money(TotalDebit)),
new(T["Ledger.Side.Avere"], T.Money(TotalCredit)),
new(T["Ledger.Entry.Difference"], T.Money(Math.Abs(Difference)), Difference == 0m ? KhTone.Ok : KhTone.Error),
new(T["Ledger.Entry.LinesCount"], T.Number(_lines.Count)),
];
private IReadOnlyList<KhOption<long?>> TemplateChoices =>
[.. _templates.Where(t => !t.Template.Disabled).Select(t => new KhOption<long?>(t.Template.Id, t.Template.Code + " · " + t.Template.Description))];
private IReadOnlyList<KhOption<long?>> RegisterChoices =>
[.. _registers.Where(r => !r.Disabled).Select(r => new KhOption<long?>(r.Id, r.Code + " · " + r.Description))];
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(LedgerPermissions.EntryRead)
|| !Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_loaded = true;
return;
}
if (_accounts.Count == 0)
{
_accounts = await Ledger.AccountsAsync(actor, company);
_templates = await Journal.TemplatesAsync(actor, company);
_registers = await Ledger.RegistersAsync(actor, company);
_taxCodes = await ActiveAsync<TaxCode>(actor, company);
_centers = await ActiveAsync<CostCenter>(actor, company);
}
await LoadAsync(actor, company);
_loaded = true;
}
private async Task<IReadOnlyList<TItem>> ActiveAsync<TItem>(Actor actor, string company)
where TItem : CodedEntity, new()
{
try
{
return await Tables.ActiveAsync<TItem>(actor, company);
}
catch (AccessDeniedException)
{
return [];
}
}
private async Task LoadAsync(Actor actor, string company)
{
if (Id is not { } id)
{
_entry = null;
_date = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
_lines = [new Line(), new Line()];
_vat = [];
return;
}
var view = await Journal.GetAsync(actor, company, id);
if (view is null)
{
Navigation.NavigateTo(LedgerScreens.BasePath + "/prima-nota");
return;
}
var e = view.Entry;
_entry = e;
_date = e.EntryDate;
_templateId = e.JournalTemplateId;
_registerId = e.VatRegisterId;
_description = e.Description;
_documentNumber = e.DocumentNumber;
_documentDate = e.DocumentDate;
var partyIds = view.Lines.Where(l => l.PartyId is not null).Select(l => l.PartyId!.Value).Distinct().ToList();
var parties = partyIds.Count == 0 || !Session.Permissions.Allows(PartyService.ReadPermission)
? new Dictionary<long, PartyRow>()
: (await Parties.RowsAsync(actor, company, partyIds)).ToDictionary(p => p.Id);
_lines = [.. view.Lines.Select(l => new Line
{
AccountId = l.AccountId,
Party = l.PartyId is { } p ? parties.GetValueOrDefault(p) : null,
Description = l.Description,
Debit = l.Debit,
Credit = l.Credit,
CostCenterId = l.CostCenterId,
JobId = l.JobId,
})];
_vat = [.. view.Vat.Select(v => new VatLine
{
TaxCodeId = v.TaxCodeId,
Rate = v.Rate,
Nature = v.Nature,
Taxable = v.Taxable,
Tax = v.Tax,
NonDeductible = v.NonDeductibleTax,
Exigibility = v.Exigibility,
RegisterId = v.VatRegisterId == e.VatRegisterId ? null : v.VatRegisterId,
})];
}
private GlAccount? AccountOf(long? id) => id is { } value ? _accounts.FirstOrDefault(a => a.Id == value) : null;
private static string AccountText(GlAccount? account) => account is null ? string.Empty : account.Code + " · " + account.Description;
private void SetAccount(Line line, string? text)
{
var code = (text ?? string.Empty).Split('·')[0].Trim();
var account = _accounts.FirstOrDefault(a => string.Equals(a.Code, code, StringComparison.OrdinalIgnoreCase))
?? _accounts.FirstOrDefault(a => a.Postable && a.Description.Contains(code, StringComparison.OrdinalIgnoreCase));
line.AccountId = account?.Id;
if (account?.SubLedger != true)
{
line.Party = null;
}
}
private void SetAmount(Line line, string? text, bool debit)
{
var amount = LedgerScreens.ParseAmount(T, text);
if (debit)
{
line.Debit = amount;
if (amount != 0m)
{
line.Credit = 0m;
}
}
else
{
line.Credit = amount;
if (amount != 0m)
{
line.Debit = 0m;
}
}
}
private void AddLine() => _lines.Add(new Line { Description = _description });
// The last line without an amount (or a new one) takes the difference on the side that balances.
private void CloseDifference()
{
var target = _lines.LastOrDefault(l => l.Debit == 0m && l.Credit == 0m);
if (target is null)
{
target = new Line { Description = _description };
_lines.Add(target);
}
if (Difference > 0m)
{
target.Credit = Difference;
}
else
{
target.Debit = -Difference;
}
}
// A template proposes its lines with their accounts and sides, and its VAT register.
private void SetTemplate(long? id)
{
_templateId = id;
if (_templates.FirstOrDefault(t => t.Template.Id == id) is not { } view)
{
return;
}
_description ??= view.Template.Description;
if (view.Template.VatRegisterCode is { } code)
{
_registerId = _registers.FirstOrDefault(r => r.Code == code)?.Id ?? _registerId;
}
if (_lines.All(l => l.Debit == 0m && l.Credit == 0m))
{
_lines = [.. view.Lines.Select(l => new Line { AccountId = l.AccountId, Description = l.Description ?? _description })];
}
}
private async Task<IReadOnlyList<PartyRow>> SearchPartiesAsync(GlAccount? account, string text, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
? await Parties.SearchAsync(actor, company, account?.Type == AccountType.Suppliers ? PartyArchive.Suppliers : PartyArchive.Customers, text, cancellationToken)
: [];
private void SetTaxCode(VatLine line, string? value)
{
line.TaxCodeId = long.TryParse(value, out var id) && id > 0 ? id : null;
var code = _taxCodes.FirstOrDefault(c => c.Id == line.TaxCodeId);
line.Rate = code?.Rate ?? 0m;
line.Nature = code?.Nature;
line.Exigibility = code?.Exigibility ?? Khaemhat.Core.Tax.TaxExigibility.Immediate;
line.Tax = Math.Round(line.Taxable * line.Rate / 100m, 2, MidpointRounding.AwayFromZero);
line.NonDeductible = Math.Round(line.Tax * (code?.NonDeductiblePercent ?? 0m) / 100m, 2, MidpointRounding.AwayFromZero);
}
private void SetTaxable(VatLine line, string? text)
{
line.Taxable = LedgerScreens.ParseAmount(T, text);
line.Tax = Math.Round(line.Taxable * line.Rate / 100m, 2, MidpointRounding.AwayFromZero);
var code = _taxCodes.FirstOrDefault(c => c.Id == line.TaxCodeId);
line.NonDeductible = Math.Round(line.Tax * (code?.NonDeductiblePercent ?? 0m) / 100m, 2, MidpointRounding.AwayFromZero);
}
private async Task SaveAsync(bool post)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var input = new EntryInput(
_entry?.Id,
_date ?? default,
_description ?? string.Empty,
[.. _lines.Select(l => new EntryLineDraft(l.AccountId, l.Party?.Id, l.Description, l.Debit, l.Credit, l.CostCenterId, l.JobId))])
{
JournalTemplateId = _templateId,
DocumentNumber = _documentNumber,
DocumentDate = _documentDate,
PartyId = _lines.Select(l => l.Party?.Id).FirstOrDefault(p => p is not null),
VatRegisterId = _registerId,
VatDate = _date,
Vat = [.. _vat.Where(v => v.Taxable != 0m || v.Tax != 0m).Select(v => new EntryVatDraft(v.TaxCodeId, v.Rate, v.Nature, v.Taxable, v.Tax, v.NonDeductible, v.Exigibility, v.RegisterId))],
Notes = _entry?.Notes,
Post = post,
};
var saved = await Journal.SaveAsync(actor, company, input);
Toasts.Show(ToastKind.Success, T[post ? "Ledger.Entry.Posted" : "Ledger.Saved"], saved.Entry.EntryNumber);
if (Id != saved.Entry.Id)
{
Navigation.NavigateTo(LedgerScreens.EntryUrl(saved.Entry.Id));
}
else
{
await LoadAsync(actor, company);
}
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotSaved"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private void ReverseAsync()
{
_reverseDate = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
_reverseOpen = true;
}
private async Task ConfirmReverseAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _entry is null || _reverseDate is not { } date)
{
return;
}
_busy = true;
try
{
var reversal = await Journal.ReverseAsync(actor, company, _entry.Id, date);
_reverseOpen = false;
Toasts.Show(ToastKind.Success, T["Ledger.Entry.Reversed"], reversal.Entry.EntryNumber);
Navigation.NavigateTo(LedgerScreens.EntryUrl(reversal.Entry.Id));
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private async Task DeleteAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _entry is null)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Entry.Delete"], T.Format("Ledger.Entry.DeleteText", _entry.EntryNumber ?? _entry.Description), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
await Journal.DeleteAsync(actor, company, _entry.Id);
Toasts.Show(ToastKind.Success, T["Ledger.Entry.Deleted"]);
Navigation.NavigateTo(LedgerScreens.BasePath + "/prima-nota");
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private sealed class Line
{
public long? AccountId { get; set; }
public PartyRow? Party { get; set; }
public string? Description { get; set; }
public decimal Debit { get; set; }
public decimal Credit { get; set; }
public long? CostCenterId { get; set; }
public long? JobId { get; set; }
}
private sealed class VatLine
{
public long? TaxCodeId { get; set; }
public decimal Rate { get; set; }
public string? Nature { get; set; }
public decimal Taxable { get; set; }
public decimal Tax { get; set; }
public decimal NonDeductible { get; set; }
public Khaemhat.Core.Tax.TaxExigibility Exigibility { get; set; }
public long? RegisterId { get; set; }
}
}
@@ -0,0 +1,473 @@
@page "/contabilita"
@page "/contabilita/prima-nota"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject JournalEntryService Journal
@inject LedgerService Ledger
@inject RecurringEntryService Recurring
@inject ToastService Toasts
@inject DialogService Dialogs
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* The journal (SPEC §11.7, mockup 040): the entries of a period, paged, with their state (draft, posted, final), the
way to each entry, the posting of the documents not yet in the ledger, the final numbering of the general journal
and the recurring entries. *@
<KhPageTitle Text="@T["Ledger.Journal.Title"]" Icon="book" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Journal.Title"]</div>
<h1>@T["Ledger.Journal.Heading"]</h1>
<div class="sub">@T["Ledger.Journal.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (CanWrite)
{
<a class="btn primary" href="@(LedgerScreens.BasePath + "/prima-nota/nuova")"><KhIcon Name="plus" /> @T["Ledger.Journal.New"]</a>
<button type="button" class="btn" disabled="@_busy" @onclick="PostDocumentsAsync"><KhIcon Name="refresh" /> @T["Ledger.Journal.PostDocuments"]</button>
}
@if (CanFinalize)
{
<button type="button" class="btn" disabled="@_busy" @onclick="FinalizeAsync"><KhIcon Name="lock" /> @T["Ledger.Journal.Finalize"]</button>
}
</div>
</div>
<KhTabs Items="Tabs" Active="@_tab" ActiveChanged="t => _tab = t" Label="@T["Ledger.Journal.Title"]" />
@if (_tab == "recurring")
{
<KhPanel Title="@T["Ledger.Recurring.Title"]" Icon="history" Tight="true">
<Actions>
@if (CanWrite)
{
<button type="button" class="btn" disabled="@_busy" @onclick="GenerateAsync"><KhIcon Name="zap" /> @T["Ledger.Recurring.Generate"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="() => EditRecurring(null)"><KhIcon Name="plus" /> @T["Ledger.Recurring.New"]</button>
}
</Actions>
<ChildContent>
@if (_recurring.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Recurring.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.Recurring.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Recurring.Frequency"]</th>
<th scope="col">@T["Ledger.Recurring.NextDate"]</th>
<th scope="col">@T["Ledger.Recurring.EndDate"]</th>
<th scope="col">@T["Ledger.Recurring.Model"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var r in _recurring)
{
<tr>
<td>@r.Description</td>
<td>@T[LedgerScreens.EnumKey(r.Frequency)]</td>
<td>@T.Date(r.NextDate)</td>
<td>@(r.EndDate is { } end ? T.Date(end) : "-")</td>
<td><a href="@LedgerScreens.EntryUrl(r.ModelEntryId)">@T["Ledger.Recurring.OpenModel"]</a></td>
<td><KhBadge Tone="@(r.Disabled ? KhTone.Neutral : KhTone.Ok)">@T[r.Disabled ? "Ledger.Recurring.Suspended" : "Ledger.Recurring.Active"]</KhBadge></td>
<td class="num">
@if (CanWrite)
{
<button type="button" class="btn sm" @onclick="() => EditRecurring(r)"><KhIcon Name="edit" /> @T["Common.Edit"]</button>
<button type="button" class="btn sm" @onclick="() => DeleteRecurringAsync(r)"><KhIcon Name="trash" /></button>
}
</td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
</KhPanel>
<p class="muted sm kh-pad">@T["Ledger.Recurring.Hint"]</p>
}
else
{
<KhPanel Tight="true">
<div class="filters">
<input type="search" class="in" placeholder="@T["Ledger.Journal.Search"]" aria-label="@T["Ledger.Journal.Search"]" value="@_text"
@onchange="e => SetTextAsync(e.Value?.ToString())" />
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="from" Value="_from" ValueChanged="d => SetFromAsync(d)" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="to" Value="_to" ValueChanged="d => SetToAsync(d)" />
<KhSelect TValue="GlEntryStatus?" Label="@T["Ledger.Fields.Status"]" Name="status" Options="StatusChoices" Value="_status" ValueChanged="SetStatusAsync" Empty="@T["Ledger.Journal.AllStates"]" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Journal.Count", T.Number(_total))</span>
</div>
@if (_rows.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Journal.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Journal.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Number"]</th>
<th scope="col">@T["Ledger.Fields.Date"]</th>
<th scope="col">@T["Ledger.Fields.Template"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in _rows)
{
var e = row.Entry;
<tr style="cursor:pointer" @onclick="() => Navigation.NavigateTo(LedgerScreens.EntryUrl(e.Id))">
<td class="code"><a href="@LedgerScreens.EntryUrl(e.Id)">@(e.EntryNumber ?? T["Ledger.Journal.NoNumber"])</a></td>
<td>@T.Date(e.EntryDate)</td>
<td class="code">@e.TemplateCode</td>
<td>@e.Description</td>
<td>@e.DocumentNumber</td>
<td>@row.PartyName</td>
<td class="num">@T.Money(e.TotalDebit)</td>
<td>
<KhBadge Tone="LedgerScreens.ToneOf(e.Status)">@T[LedgerScreens.EnumKey(e.Status)]</KhBadge>
@if (e.ReversedById is not null)
{
<KhBadge Tone="KhTone.Neutral">@T["Ledger.Journal.Reversed"]</KhBadge>
}
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="filters">
<span class="muted sm">@T.Format("Ledger.Pager", _offset + 1, Math.Min(_offset + PageSize, _total), _total)</span>
<span class="grow"></span>
<button type="button" class="btn sm" disabled="@(_offset == 0)" @onclick="() => PageAsync(-1)"><KhIcon Name="chevron-left" /> @T["Ledger.Previous"]</button>
<button type="button" class="btn sm" disabled="@(_offset + PageSize >= _total)" @onclick="() => PageAsync(1)">@T["Ledger.Next"] <KhIcon Name="chevron-right" /></button>
</div>
}
</KhPanel>
}
<KhDialog Open="_finalizeOpen" Title="@T["Ledger.Journal.Finalize"]" Icon="lock" OnClose="() => _finalizeOpen = false">
<ChildContent>
<p>@T["Ledger.Journal.FinalizeText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Journal.FinalizeUpTo"]" Name="upto" @bind-Value="_upTo" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _finalizeOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _upTo is null)" @onclick="ConfirmFinalizeAsync"><KhIcon Name="lock" /> @T["Ledger.Journal.Finalize"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_postOpen" Title="@T["Ledger.Journal.PostDocuments"]" Icon="refresh" OnClose="() => _postOpen = false">
<ChildContent>
<p>@T["Ledger.Journal.PostText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="postfrom" @bind-Value="_postFrom" Span="6" Required="true" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="postto" @bind-Value="_postTo" Span="6" Required="true" />
<KhCheck Label="@T["Ledger.Journal.PostAgain"]" Name="again" @bind-Value="_postAgain" Span="12" />
</div>
@if (_report is { } report)
{
<div class="callout @(report.Failed.Count == 0 ? "ok" : "warn")" role="status">
<KhIcon Name="info" />
<div>
@T.Format("Ledger.Journal.Posted", report.Posted)
@foreach (var failure in report.Failed)
{
<div class="sm">@failure</div>
}
</div>
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _postOpen = false">@T["Common.Close"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _postFrom is null || _postTo is null)" @onclick="ConfirmPostAsync"><KhIcon Name="zap" /> @T["Ledger.Journal.PostRun"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_recurringOpen" Title="@T["Ledger.Recurring.Title"]" Icon="history" OnClose="() => _recurringOpen = false">
<ChildContent>
<div class="form plain">
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="rdesc" @bind-Value="_rDescription" Span="12" Required="true" MaxLength="200" />
<KhTextBox Label="@T["Ledger.Recurring.ModelNumber"]" Name="rmodel" @bind-Value="_rModel" Span="6" Required="true" Mono="true" Hint="@T["Ledger.Recurring.ModelHint"]" />
<KhSelect TValue="RecurrenceFrequency" Label="@T["Ledger.Recurring.Frequency"]" Name="rfreq" Options="LedgerScreens.Choices<RecurrenceFrequency>(T)" @bind-Value="_rFrequency" Span="6" />
<KhDateBox Label="@T["Ledger.Recurring.NextDate"]" Name="rnext" @bind-Value="_rNext" Span="6" Required="true" />
<KhDateBox Label="@T["Ledger.Recurring.EndDate"]" Name="rend" @bind-Value="_rEnd" Span="6" />
<KhCheck Label="@T["Ledger.Recurring.Suspended"]" Name="rdisabled" @bind-Value="_rDisabled" Span="12" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _recurringOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveRecurringAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
</LedgerGuard>
@code {
private const int PageSize = 50;
private IReadOnlyList<EntryRow> _rows = [];
private IReadOnlyList<RecurringEntry> _recurring = [];
private int _total;
private int _offset;
private string? _text;
private DateOnly? _from;
private DateOnly? _to;
private GlEntryStatus? _status;
private string _tab = "entries";
private bool _busy;
private bool _finalizeOpen;
private DateOnly? _upTo;
private bool _postOpen;
private DateOnly? _postFrom;
private DateOnly? _postTo;
private bool _postAgain;
private PostingReport? _report;
private bool _recurringOpen;
private long? _rId;
private string? _rDescription;
private string? _rModel;
private RecurrenceFrequency _rFrequency;
private DateOnly? _rNext;
private DateOnly? _rEnd;
private bool _rDisabled;
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.EntryWrite);
private bool CanFinalize => Session.Permissions.Allows(LedgerPermissions.EntryFinalize);
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhTabItem> Tabs =>
[
new("entries", "book", T["Ledger.Journal.Entries"], _total),
new("recurring", "history", T["Ledger.Recurring.Title"], _recurring.Count),
];
private IReadOnlyList<KhOption<GlEntryStatus?>> StatusChoices =>
[.. Enum.GetValues<GlEntryStatus>().Select(s => new KhOption<GlEntryStatus?>(s, T[LedgerScreens.EnumKey(s)]))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, 1, 1);
_to = new DateOnly(Today.Year, 12, 31);
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.EntryRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
await LoadAsync();
_recurring = await Recurring.ListAsync(actor, company);
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
(_rows, _total) = await Journal.ListAsync(actor, company, new EntryFilter(_from, _to, _status, null, _text, _offset, PageSize));
}
private async Task SetTextAsync(string? text)
{
_text = string.IsNullOrWhiteSpace(text) ? null : text.Trim();
_offset = 0;
await LoadAsync();
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
_offset = 0;
await LoadAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
_offset = 0;
await LoadAsync();
}
private async Task SetStatusAsync(GlEntryStatus? status)
{
_status = status;
_offset = 0;
await LoadAsync();
}
private async Task PageAsync(int step)
{
_offset = Math.Max(0, _offset + (step * PageSize));
await LoadAsync();
}
private void FinalizeAsync()
{
_upTo ??= Today.AddDays(-Today.Day);
_finalizeOpen = true;
}
private async Task ConfirmFinalizeAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _upTo is not { } upTo)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Journal.Finalize"], T.Format("Ledger.Journal.FinalizeConfirm", T.Date(upTo)), T["Ledger.Journal.Finalize"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async () =>
{
var count = await Journal.FinalizeAsync(actor, company, upTo);
Toasts.Show(ToastKind.Success, T.Format("Ledger.Journal.Finalized", count));
_finalizeOpen = false;
await LoadAsync();
});
}
private void PostDocumentsAsync()
{
_postFrom ??= new DateOnly(Today.Year, 1, 1);
_postTo ??= Today;
_report = null;
_postOpen = true;
}
private async Task ConfirmPostAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _postFrom is not { } from || _postTo is not { } to)
{
return;
}
await RunAsync(async () =>
{
_report = await Ledger.PostPendingAsync(actor, company, from, to, _postAgain);
await LoadAsync();
});
}
private void EditRecurring(RecurringEntry? r)
{
_rId = r?.Id;
_rDescription = r?.Description;
_rModel = r?.ModelEntryId.ToString(System.Globalization.CultureInfo.InvariantCulture);
_rFrequency = r?.Frequency ?? RecurrenceFrequency.Monthly;
_rNext = r?.NextDate ?? Today;
_rEnd = r?.EndDate;
_rDisabled = r?.Disabled ?? false;
_recurringOpen = true;
}
private async Task SaveRecurringAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
var model = await ModelIdAsync(actor, company, _rModel);
await RunAsync(async () =>
{
await Recurring.SaveAsync(actor, company, new RecurringEntryInput(_rId, _rDescription ?? string.Empty, model, _rFrequency, _rNext ?? default, _rEnd, _rDisabled));
_recurring = await Recurring.ListAsync(actor, company);
_recurringOpen = false;
Toasts.Show(ToastKind.Success, T["Ledger.Saved"]);
});
}
// The model is chosen by the number of the entry as shown (2026/00012) or by its id.
private async Task<long> ModelIdAsync(Actor actor, string company, string? text)
{
text = text?.Trim();
if (string.IsNullOrEmpty(text))
{
return 0;
}
if (!text.Contains('/', StringComparison.Ordinal) && long.TryParse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var id))
{
return id;
}
var (rows, _) = await Journal.ListAsync(actor, company, new EntryFilter(Text: text, Limit: 20));
return rows.FirstOrDefault(r => r.Entry.EntryNumber == text)?.Entry.Id ?? 0;
}
private async Task DeleteRecurringAsync(RecurringEntry r)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Recurring.Delete"], T.Format("Ledger.Recurring.DeleteText", r.Description), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async () =>
{
await Recurring.DeleteAsync(actor, company, r.Id);
_recurring = await Recurring.ListAsync(actor, company);
});
}
private async Task GenerateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
await RunAsync(async () =>
{
var (written, problems) = await Recurring.GenerateAsync(actor, company, Today);
Toasts.Show(problems.Count == 0 ? ToastKind.Success : ToastKind.Warning, T.Format("Ledger.Recurring.Generated", written), string.Join(" ", problems));
_recurring = await Recurring.ListAsync(actor, company);
await LoadAsync();
});
}
private async Task RunAsync(Func<Task> action)
{
_busy = true;
try
{
await action();
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,55 @@
@using Khaemhat.Application.Modules
@inject ShellSession Session
@* What every page of the ledger checks first: an open company, the module ACCT in the licence and the permission. *@
@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["Ledger.NoCompany"]</h1>
</div>
}
else if (!Session.Licenses.IsModuleActive(ModuleCodes.Accounting))
{
<div class="kh-message">
<KhIcon Name="key" Class="lg" />
<h1>@T["Ledger.NoModule.Title"]</h1>
<p class="lead">@T["Ledger.NoModule.Lead"]</p>
</div>
}
else if (!Session.Permissions.Allows(Permission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
<a class="btn" href="./">@T["Common.BackHome"]</a>
</div>
}
else
{
@ChildContent
}
@code {
private bool _loaded;
/// <summary>The permission the page needs.</summary>
[Parameter, EditorRequired]
public string Permission { get; set; } = string.Empty;
/// <summary>The page.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_loaded = true;
}
}
@@ -0,0 +1,114 @@
@using Khaemhat.Application.Ledger
@using Khaemhat.Web.Ledger
@* The movements of an account or a party (mastrino, estratto conto, mockups 042 and 044): the period, the opening
balance, the movements of the page with the running balance and the way to each entry, the totals and the pager. *@
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="mfrom" Value="From" ValueChanged="FromChanged" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="mto" Value="To" ValueChanged="ToChanged" />
<span class="grow"></span>
@if (Page is { } p)
{
<span class="muted sm">@T["Ledger.Movements.Opening"]: <b>@LedgerScreens.Balance(T, p.Opening)</b></span>
}
</div>
@if (Page is not { } page)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (page.TotalCount == 0)
{
<p class="kh-wempty">@T["Ledger.Movements.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Movements.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Date"]</th>
<th scope="col">@T["Ledger.Fields.Number"]</th>
@if (ShowAccount)
{
<th scope="col">@T["Ledger.Fields.Account"]</th>
}
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col" class="num">@T["Ledger.Movements.Balance"]</th>
</tr>
</thead>
<tbody>
@foreach (var m in page.Movements)
{
<tr>
<td>@T.Date(m.EntryDate)</td>
<td class="code"><a href="@LedgerScreens.EntryUrl(m.EntryId)">@(m.EntryNumber ?? T["Ledger.Journal.NoNumber"])</a></td>
@if (ShowAccount)
{
<td class="code">@m.AccountCode</td>
}
<td>@m.DocumentNumber</td>
<td>@m.Description</td>
<td class="num">@LedgerScreens.AmountText(T, m.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, m.Credit)</td>
<td class="num">@LedgerScreens.Balance(T, m.Balance)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="@(ShowAccount ? 5 : 4)" class="num"><b>@T["Ledger.Movements.Totals"]</b></td>
<td class="num"><b>@T.Money(page.TotalDebit)</b></td>
<td class="num"><b>@T.Money(page.TotalCredit)</b></td>
<td class="num"><b>@LedgerScreens.Balance(T, page.Closing)</b></td>
</tr>
</tfoot>
</table>
</div>
<div class="filters">
<span class="muted sm">@T.Format("Ledger.Pager", Offset + 1, Math.Min(Offset + PageSize, page.TotalCount), page.TotalCount)</span>
<span class="grow"></span>
<button type="button" class="btn sm" disabled="@(Offset == 0)" @onclick="() => OnPage.InvokeAsync(Math.Max(0, Offset - PageSize))"><KhIcon Name="chevron-left" /> @T["Ledger.Previous"]</button>
<button type="button" class="btn sm" disabled="@(Offset + PageSize >= page.TotalCount)" @onclick="() => OnPage.InvokeAsync(Offset + PageSize)">@T["Ledger.Next"] <KhIcon Name="chevron-right" /></button>
</div>
}
@code {
/// <summary>The page of movements, or <see langword="null"/> while loading.</summary>
[Parameter]
public LedgerPage? Page { get; set; }
/// <summary>From this day.</summary>
[Parameter]
public DateOnly? From { get; set; }
/// <summary>Up to this day.</summary>
[Parameter]
public DateOnly? To { get; set; }
/// <summary>The start of the period changed.</summary>
[Parameter]
public EventCallback<DateOnly?> FromChanged { get; set; }
/// <summary>The end of the period changed.</summary>
[Parameter]
public EventCallback<DateOnly?> ToChanged { get; set; }
/// <summary>Another page is asked, by its first movement.</summary>
[Parameter]
public EventCallback<int> OnPage { get; set; }
/// <summary>The first movement of the page.</summary>
[Parameter]
public int Offset { get; set; }
/// <summary>The size of a page.</summary>
[Parameter]
public int PageSize { get; set; } = 30;
/// <summary>Show the account of each movement (statements of a party).</summary>
[Parameter]
public bool ShowAccount { get; set; }
}
@@ -0,0 +1,246 @@
@page "/contabilita/partitari"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerQueryService Queries
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The sub-ledgers of customers and suppliers (partitario, estratto conto, SPEC §11.7, mockup 044): each party with
its balance and its open items; the party chosen with its movements in a period on every account, the running
balance and the way to each entry, its open items and the print of the statement. *@
<KhPageTitle Text="@T["Ledger.Parties.Title"]" Icon="users" />
<LedgerGuard Permission="@LedgerPermissions.EntryRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Parties.Title"]</div>
<h1>@T["Ledger.Parties.Heading"]</h1>
<div class="sub">@T["Ledger.Parties.Hint"]</div>
</div>
</div>
<KhTabs Items="Tabs" Active="@(_type == AccountType.Suppliers ? "suppliers" : "customers")" ActiveChanged="SetTypeAsync" Label="@T["Ledger.Parties.Title"]" />
<div class="kh-ledger-split">
<KhPanel Title="@T[_type == AccountType.Suppliers ? "Ledger.Parties.Suppliers" : "Ledger.Parties.Customers"]" Icon="users" Tight="true">
<div class="filters">
<input type="search" class="in" placeholder="@T["Ledger.Parties.Search"]" aria-label="@T["Ledger.Parties.Search"]" value="@_search"
@onchange="e => SearchAsync(e.Value?.ToString())" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Parties.Total", LedgerScreens.Balance(T, _balances.Sum(b => b.Balance)))</span>
</div>
@if (_balances.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Parties.None"]</p>
}
else
{
<div class="kh-ledger-tree">
<table class="grid" aria-label="@T["Ledger.Parties.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.Side.Avere"]</th>
<th scope="col" class="num">@T["Ledger.Movements.Balance"]</th>
<th scope="col" class="num">@T["Ledger.Parties.OpenItems"]</th>
</tr>
</thead>
<tbody>
@foreach (var b in _balances)
{
<tr class="@(b.PartyId == _selected?.PartyId ? "sel" : null)" style="cursor:pointer" @onclick="() => SelectAsync(b)">
<td>@b.Name</td>
<td class="num">@T.Money(b.Debit)</td>
<td class="num">@T.Money(b.Credit)</td>
<td class="num"><b>@LedgerScreens.Balance(T, b.Balance)</b></td>
<td class="num">@(b.OpenItems > 0 ? T.Number(b.OpenItems) : null)</td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
<div class="kh-ledger-side">
@if (_selected is { } party)
{
<KhPanel Title="@T.Format("Ledger.Parties.Statement", party.Name)" Icon="file" Tight="true">
<Actions>
<button type="button" class="btn sm" disabled="@_busy" @onclick="PrintAsync"><KhIcon Name="printer" /> @T["Ledger.Print"]</button>
</Actions>
<ChildContent>
<MovementsTable Page="_page" From="_from" To="_to" FromChanged="SetFromAsync" ToChanged="SetToAsync" OnPage="PageAsync" Offset="_offset" PageSize="PageSize" />
</ChildContent>
</KhPanel>
<KhPanel Title="@T["Ledger.Parties.OpenItemsTitle"]" Icon="clock" Tight="true">
<Actions>
<KhCheck Label="@T["Ledger.Parties.ShowClosed"]" Name="closed" Value="_closed" ValueChanged="SetClosedAsync" />
</Actions>
<ChildContent>
@if (_items.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Parties.NoOpenItems"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.Parties.OpenItemsTitle"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Parties.Installment"]</th>
<th scope="col">@T["Ledger.Parties.DueDate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col" class="num">@T["Ledger.Parties.Paid"]</th>
<th scope="col" class="num">@T["Ledger.Parties.Residual"]</th>
</tr>
</thead>
<tbody>
@foreach (var item in _items)
{
var overdue = !item.Closed && item.DueDate < Today;
<tr class="@(item.Closed ? "muted" : null)">
<td><a href="@LedgerScreens.EntryUrl(item.EntryId)">@item.DocumentNumber</a></td>
<td>@T.Date(item.DocumentDate)</td>
<td>@item.Installment</td>
<td class="@(overdue ? "err" : null)">@T.Date(item.DueDate)</td>
<td class="num">@T.Money(item.Amount)</td>
<td class="num">@LedgerScreens.AmountText(T, item.PaidAmount)</td>
<td class="num"><b>@T.Money(item.Amount - item.PaidAmount)</b></td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
</KhPanel>
}
else
{
<p class="kh-wempty">@T["Ledger.Parties.Choose"]</p>
}
</div>
</div>
</LedgerGuard>
@code {
private const int PageSize = 30;
private AccountType _type = AccountType.Customers;
private IReadOnlyList<PartyBalance> _balances = [];
private PartyBalance? _selected;
private string? _search;
private LedgerPage? _page;
private IReadOnlyList<OpenItem> _items = [];
private int _offset;
private DateOnly? _from;
private DateOnly? _to;
private bool _closed;
private bool _busy;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhTabItem> Tabs =>
[
new("customers", "users", T["Ledger.Parties.Customers"]),
new("suppliers", "truck", T["Ledger.Parties.Suppliers"]),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, 1, 1);
_to = Today;
await LoadAsync();
}
private async Task LoadAsync()
{
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.EntryRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_balances = await Queries.PartyBalancesAsync(actor, company, _type, _to ?? Today, _search);
}
}
private async Task SetTypeAsync(string tab)
{
_type = tab == "suppliers" ? AccountType.Suppliers : AccountType.Customers;
_selected = null;
await LoadAsync();
}
private async Task SearchAsync(string? text)
{
_search = text;
await LoadAsync();
}
private async Task SelectAsync(PartyBalance party)
{
_selected = party;
_offset = 0;
await LoadPartyAsync();
}
private async Task LoadPartyAsync()
{
_page = null;
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { } party || _from is not { } from || _to is not { } to)
{
return;
}
_page = await Queries.MovementsAsync(actor, company, new LedgerFilter(null, party.PartyId, from, to, false, _offset, PageSize));
_items = await Queries.OpenItemsAsync(actor, company, party.PartyId, _type == AccountType.Suppliers ? OpenItemDirection.Payable : OpenItemDirection.Receivable, _closed);
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
_offset = 0;
await LoadPartyAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
_offset = 0;
await LoadPartyAsync();
}
private async Task PageAsync(int offset)
{
_offset = offset;
await LoadPartyAsync();
}
private async Task SetClosedAsync(bool closed)
{
_closed = closed;
await LoadPartyAsync();
}
private async Task PrintAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected is not { } party || _from is not { } from || _to is not { } to)
{
return;
}
_busy = true;
try
{
await LedgerScreens.DownloadAsync(JS, await Queries.PrintMovementsAsync(actor, company, new LedgerFilter(null, party.PartyId, from, to)));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,227 @@
@page "/contabilita/bollo"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject TaxService Taxes
@inject ToastService Toasts
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The virtual stamp duty on e-invoices (SPEC §11.7, mockup 060): the invoices of a quarter with the duty, the amount,
the payment code and the due date (a small first quarter goes with the second, the first two with the third), the
F24 line, its data file and its payment. *@
<KhPageTitle Text="@T["Ledger.StampDuty.Title"]" Icon="file-check" />
<LedgerGuard Permission="@LedgerPermissions.SettlementRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.StampDuty.Title"]</div>
<h1>@T["Ledger.StampDuty.Heading"]</h1>
<div class="sub">@T["Ledger.StampDuty.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (Current is { } q)
{
<KhBadge Tone="KhTone.Info">@T.Format("Ledger.StampDuty.QuarterBadge", q.Quarter, q.Year)</KhBadge>
}
@if (CanConfirm)
{
<button type="button" class="btn primary" disabled="@(_busy || Current is null || Current.Amount == 0m || Current.Payment?.PaidOn is not null)" @onclick="RecordAsync"><KhIcon Name="check" /> @T["Ledger.StampDuty.Record"]</button>
}
<button type="button" class="btn" disabled="@(_busy || Current?.Payment is null)" @onclick="ExportAsync"><KhIcon Name="download" /> @T["Ledger.StampDuty.Export"]</button>
</div>
</div>
<div class="filters kh-ledger-filters">
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Year"]" Name="year" Options="YearChoices" Value="_year" ValueChanged="SetYearAsync" />
<KhSelect TValue="int" Label="@T["Ledger.StampDuty.Quarter"]" Name="quarter" Options="QuarterChoices" Value="_quarter" ValueChanged="SetQuarterAsync" />
</div>
@if (Current is { } current)
{
<KhStrip Items="Stats(current)" Label="@T["Ledger.StampDuty.Title"]" />
}
<KhPanel Tight="true">
@if (_documents.Count == 0)
{
<p class="kh-wempty">@T["Ledger.StampDuty.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.StampDuty.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.StampDuty.Duty"]</th>
<th scope="col">@T["Ledger.StampDuty.Charge"]</th>
</tr>
</thead>
<tbody>
@foreach (var d in _documents)
{
<tr>
<td class="code"><a href="@Khaemhat.Web.Documents.SalesScreens.RecordUrl(d.Kind, d.DocumentId)">@d.DocumentNumber</a></td>
<td>@T.Date(d.DocumentDate)</td>
<td>@d.PartyName</td>
<td class="num">@T.Money(d.Taxable)</td>
<td class="num">@T.Money(d.StampDuty)</td>
<td><KhBadge Tone="@(d.Charged ? KhTone.Info : KhTone.Neutral)">@T[d.Charged ? "Ledger.StampDuty.Charged" : "Ledger.StampDuty.Borne"]</KhBadge></td>
</tr>
}
</tbody>
</table>
}
<div class="filters"><span class="muted sm">@T["Ledger.StampDuty.Footer"]</span></div>
</KhPanel>
<KhPanel Title="@T.Format("Ledger.StampDuty.Year", _year)" Icon="calendar" Tight="true">
<table class="grid" aria-label="@T.Format("Ledger.StampDuty.Year", _year)">
<thead>
<tr>
<th scope="col">@T["Ledger.StampDuty.Quarter"]</th>
<th scope="col" class="num">@T["Ledger.StampDuty.Invoices"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col">@T["Ledger.Settlement.DueDate"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var q in _quarters)
{
<tr class="@(q.Quarter == _quarter ? "sel" : null)" style="cursor:pointer" @onclick="() => SetQuarterAsync(q.Quarter)">
<td>@T.Format("Ledger.StampDuty.QuarterBadge", q.Quarter, q.Year)</td>
<td class="num">@q.Documents</td>
<td class="num">@T.Money(q.Amount)</td>
<td>@T.Date(q.DueDate)</td>
<td>
@if (q.Payment is { PaidOn: { } paid })
{
<KhBadge Tone="KhTone.Ok">@T.Format("Ledger.StampDuty.PaidOn", T.Date(paid))</KhBadge>
}
else if (q.Payment is not null)
{
<KhBadge Tone="KhTone.Warning">@T["Ledger.StampDuty.InF24"]</KhBadge>
}
else if (q.Amount > 0m)
{
<KhBadge Tone="KhTone.Neutral">@T["Ledger.StampDuty.ToRecord"]</KhBadge>
}
</td>
</tr>
}
</tbody>
</table>
</KhPanel>
</LedgerGuard>
@code {
private int _year;
private int _quarter;
private IReadOnlyList<StampDutyQuarter> _quarters = [];
private IReadOnlyList<StampDutyDocument> _documents = [];
private bool _busy;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private bool CanConfirm => Session.Permissions.Allows(LedgerPermissions.SettlementConfirm);
private StampDutyQuarter? Current => _quarters.FirstOrDefault(q => q.Quarter == _quarter);
private IReadOnlyList<KhOption<int>> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption<int>(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))];
private IReadOnlyList<KhOption<int>> QuarterChoices => [.. Enumerable.Range(1, 4).Select(q => new KhOption<int>(q, T.Format("Ledger.StampDuty.QuarterBadge", q, _year)))];
private IReadOnlyList<KhStat> Stats(StampDutyQuarter q)
{
var previous = q.Quarter > 1 ? _quarters.FirstOrDefault(p => p.Quarter == q.Quarter - 1) : null;
return
[
new(T["Ledger.StampDuty.Invoices"], T.Number(q.Documents)),
new(T["Ledger.Fields.Amount"], T.Money(q.Amount)),
new(T["Ledger.Settlement.PaymentCode"], q.Payment?.PaymentCode ?? "-"),
new(T["Ledger.Settlement.DueDate"], T.Date(q.DueDate)),
new(T["Ledger.StampDuty.Previous"], previous is null ? "-" : T.Money(previous.Amount) + (previous.Payment?.PaidOn is { } paid ? " · " + T.Format("Ledger.StampDuty.PaidOn", T.Date(paid)) : string.Empty),
previous?.Payment?.PaidOn is not null ? KhTone.Ok : KhTone.Neutral),
];
}
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_year = Today.Year;
_quarter = ((Today.Month - 1) / 3) + 1;
if (Session.Actor is { } && Session.Company is { } && Session.Permissions.Allows(LedgerPermissions.SettlementRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
await LoadAsync();
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_quarters = await Taxes.StampDutyAsync(actor, company, _year);
_documents = await Taxes.StampDutyDocumentsAsync(actor, company, _year, _quarter);
}
private async Task SetYearAsync(int year)
{
_year = year;
await LoadAsync();
}
private async Task SetQuarterAsync(int quarter)
{
_quarter = quarter;
await LoadAsync();
}
private async Task RecordAsync() => await RunAsync(async (actor, company) =>
{
var payment = await Taxes.StampDutyPaymentAsync(actor, company, _year, _quarter);
Toasts.Show(ToastKind.Success, payment is null ? T["Ledger.StampDuty.NoneDue"] : T.Format("Ledger.StampDuty.Recorded", T.Money(payment.Amount), T.Date(payment.DueDate)));
await LoadAsync();
});
private async Task ExportAsync() => await RunAsync(async (actor, company) =>
{
if (Current?.Payment is { } payment)
{
await LedgerScreens.DownloadAsync(JS, await Taxes.ExportFormAsync(actor, company, payment.DueDate));
}
});
private async Task RunAsync(Func<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,283 @@
@page "/contabilita/causali"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject LedgerService Ledger
@inject ToastService Toasts
@inject DialogService Dialogs
@* The journal templates (causali contabili, SPEC §11.7, mockup 043): each template is a model of entry, with the
lines in order, the role of each line (customer, revenue, VAT on sales...), its side and its usual account, the VAT
register and whether it opens items. The documents post through the template of their type. *@
<KhPageTitle Text="@T["Ledger.Templates.Title"]" Icon="layers" />
<LedgerGuard Permission="@LedgerPermissions.AccountRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Templates.Title"]</div>
<h1>@T["Ledger.Templates.Heading"]</h1>
<div class="sub">@T["Ledger.Templates.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
@if (CanWrite)
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="() => Edit(null)"><KhIcon Name="plus" /> @T["Ledger.Templates.New"]</button>
}
</div>
</div>
<div class="kh-ledger-split">
<KhPanel Title="@T["Ledger.Templates.List"]" Icon="list" Tight="true">
<table class="grid" aria-label="@T["Ledger.Templates.List"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Code"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Fields.VatRegister"]</th>
</tr>
</thead>
<tbody>
@foreach (var view in _templates)
{
var t = view.Template;
<tr class="@(t.Id == _id ? "sel" : null) @(t.Disabled ? "muted" : null)" style="cursor:pointer" @onclick="() => Edit(view)">
<td class="code">@t.Code</td>
<td>@t.Description</td>
<td class="code">@t.VatRegisterCode</td>
</tr>
}
</tbody>
</table>
</KhPanel>
<div class="kh-ledger-side">
@if (_editing)
{
<datalist id="kh-template-accounts">
@foreach (var a in _accounts.Where(a => a.Postable && !a.Disabled))
{
<option value="@(a.Code + " · " + a.Description)"></option>
}
</datalist>
<KhPanel Title="@T[_id is null ? "Ledger.Templates.New" : "Ledger.Templates.Edit"]" Icon="edit">
<div class="form plain">
<KhTextBox Label="@T["Ledger.Fields.Code"]" Name="code" @bind-Value="_code" Span="3" Required="true" Mono="true" MaxLength="10" Disabled="!CanWrite" />
<KhTextBox Label="@T["Ledger.Fields.Description"]" Name="description" @bind-Value="_description" Span="9" Required="true" MaxLength="100" Disabled="!CanWrite" />
<KhSelect TValue="JournalArea" Label="@T["Ledger.Fields.Area"]" Name="area" Options="LedgerScreens.Choices<JournalArea>(T)" @bind-Value="_area" Span="4" Disabled="!CanWrite" />
<KhSelect TValue="string" Label="@T["Ledger.Fields.VatRegister"]" Name="register" Options="RegisterChoices" @bind-Value="_register" Empty="@T["Ledger.Entry.NoRegister"]" Span="4" Disabled="!CanWrite" />
<KhCheck Label="@T["Ledger.Fields.OpensItems"]" Name="opens" @bind-Value="_opensItems" Span="4" Disabled="!CanWrite" />
<KhCheck Label="@T["Ledger.Fields.Reverses"]" Name="reverses" @bind-Value="_reverses" Span="4" Disabled="!CanWrite" />
<KhCheck Label="@T["Ledger.Fields.Disabled"]" Name="disabled" @bind-Value="_disabled" Span="4" Disabled="!CanWrite" />
</div>
</KhPanel>
<KhPanel Title="@T["Ledger.Templates.Lines"]" Icon="list" Tight="true">
<Actions>
@if (CanWrite)
{
<button type="button" class="btn sm" @onclick="() => _lines.Add(new Line())"><KhIcon Name="plus" /> @T["Ledger.Entry.AddLine"]</button>
}
</Actions>
<ChildContent>
<table class="grid" aria-label="@T["Ledger.Templates.Lines"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Role"]</th>
<th scope="col">@T["Ledger.Fields.Side"]</th>
<th scope="col">@T["Ledger.Fields.Account"]</th>
<th scope="col">@T["Ledger.Fields.LineDescription"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var line in _lines)
{
<tr>
<td>
<select class="in" aria-label="@T["Ledger.Fields.Role"]" disabled="@(!CanWrite)" @onchange="e => SetRole(line, e.Value)">
@foreach (var role in Enum.GetValues<PostingRole>())
{
<option value="@role" selected="@(role == line.Role)">@T[LedgerScreens.EnumKey(role)]</option>
}
</select>
</td>
<td>
<select class="in" aria-label="@T["Ledger.Fields.Side"]" disabled="@(!CanWrite)" @onchange="e => SetSide(line, e.Value)">
@foreach (var side in Enum.GetValues<AccountSide>())
{
<option value="@side" selected="@(side == line.Side)">@T[LedgerScreens.EnumKey(side)]</option>
}
</select>
</td>
<td><input class="in" list="kh-template-accounts" aria-label="@T["Ledger.Fields.Account"]" disabled="@(!CanWrite)" value="@AccountText(line.AccountId)" @onchange="e => SetAccount(line, e.Value?.ToString())" style="min-width:220px" /></td>
<td><input class="in" maxlength="100" aria-label="@T["Ledger.Fields.LineDescription"]" disabled="@(!CanWrite)" value="@line.Description" @onchange="e => line.Description = e.Value?.ToString()" /></td>
<td>
@if (CanWrite)
{
<button type="button" class="btn sm" aria-label="@T["Ledger.Entry.RemoveLine"]" @onclick="() => _lines.Remove(line)"><KhIcon Name="trash" /></button>
}
</td>
</tr>
}
</tbody>
</table>
</ChildContent>
</KhPanel>
@if (CanWrite)
{
<div class="kh-formactions">
@if (_id is { } id)
{
<button type="button" class="btn" disabled="@_busy" @onclick="() => DeleteAsync(id)"><KhIcon Name="trash" /> @T["Common.Delete"]</button>
}
<button type="button" class="btn" @onclick="() => _editing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</div>
}
}
else
{
<p class="kh-wempty">@T["Ledger.Templates.Choose"]</p>
}
</div>
</div>
</LedgerGuard>
@code {
private IReadOnlyList<TemplateView> _templates = [];
private IReadOnlyList<GlAccount> _accounts = [];
private IReadOnlyList<VatRegister> _registers = [];
private bool _busy;
private bool _editing;
private long? _id;
private string? _code;
private string? _description;
private JournalArea _area;
private string? _register;
private bool _opensItems;
private bool _reverses;
private bool _disabled;
private List<Line> _lines = [];
private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.AccountWrite);
private IReadOnlyList<KhOption<string>> RegisterChoices => [.. _registers.Select(r => new KhOption<string>(r.Code, r.Code + " · " + r.Description))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.AccountRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_templates = await Ledger.TemplatesAsync(actor, company);
_accounts = await Ledger.AccountsAsync(actor, company);
_registers = await Ledger.RegistersAsync(actor, company);
}
}
private string AccountText(long? id) => _accounts.FirstOrDefault(a => a.Id == id) is { } a ? a.Code + " · " + a.Description : string.Empty;
private void SetAccount(Line line, string? text)
{
var code = (text ?? string.Empty).Split('·')[0].Trim();
line.AccountId = code.Length == 0 ? null : _accounts.FirstOrDefault(a => string.Equals(a.Code, code, StringComparison.OrdinalIgnoreCase))?.Id;
}
private void Edit(TemplateView? view)
{
var t = view?.Template;
_id = t?.Id;
_code = t?.Code;
_description = t?.Description;
_area = t?.Area ?? JournalArea.General;
_register = t?.VatRegisterCode;
_opensItems = t?.OpensItems ?? false;
_reverses = t?.Reverses ?? false;
_disabled = t?.Disabled ?? false;
_lines = view is null
? [new Line { Side = AccountSide.Debit }, new Line { Side = AccountSide.Credit }]
: [.. view.Lines.Select(l => new Line { Role = l.Role, Side = l.Side, AccountId = l.AccountId, Description = l.Description })];
_editing = true;
}
private async Task SaveAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
var saved = await Ledger.SaveTemplateAsync(actor, company, new TemplateInput(
_id, _code ?? string.Empty, _description ?? string.Empty, _area, [.. _lines.Select(l => new TemplateLineInput(l.Role, l.Side, l.AccountId, l.Description))])
{
VatRegisterCode = _register,
OpensItems = _opensItems,
Reverses = _reverses,
Disabled = _disabled,
});
_templates = await Ledger.TemplatesAsync(actor, company);
Edit(_templates.FirstOrDefault(t => t.Template.Id == saved.Template.Id));
Toasts.Show(ToastKind.Success, T["Ledger.Saved"], saved.Template.Code);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotSaved"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private async Task DeleteAsync(long id)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Templates.Delete"], T.Format("Ledger.Templates.DeleteText", _code ?? string.Empty), T["Common.Delete"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
await Ledger.DeleteTemplateAsync(actor, company, id);
_templates = await Ledger.TemplatesAsync(actor, company);
_editing = false;
_id = null;
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
private sealed class Line
{
public PostingRole Role { get; set; }
public AccountSide Side { get; set; }
public long? AccountId { get; set; }
public string? Description { get; set; }
}
private static void SetRole(Line line, object? value) => line.Role = Enum.Parse<PostingRole>(value?.ToString() ?? nameof(PostingRole.Account));
private static void SetSide(Line line, object? value) => line.Side = Enum.Parse<AccountSide>(value?.ToString() ?? nameof(AccountSide.Debit));
}
@@ -0,0 +1,263 @@
@page "/contabilita/registri-iva"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject VatService Vat
@inject LedgerService Ledger
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The VAT registers (SPEC §11.7, mockup 045): the lines of a register in a period with protocol, document, party,
rate, taxable and VAT, the totals by rate; the provisional print of any period and the final print, which goes on
from the day after the last one and numbers the pages of the year after the last page printed. *@
<KhPageTitle Text="@T["Ledger.VatRegisters.Title"]" Icon="file-check" />
<LedgerGuard Permission="@LedgerPermissions.VatRegisterRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.VatRegisters.Title"]</div>
<h1>@T["Ledger.VatRegisters.Heading"]</h1>
<div class="sub">@T["Ledger.VatRegisters.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<button type="button" class="btn" disabled="@(_busy || _view is null)" @onclick="() => PrintAsync(final: false)"><KhIcon Name="printer" /> @T["Ledger.VatRegisters.PrintProvisional"]</button>
@if (Session.Permissions.Allows(LedgerPermissions.SettlementConfirm))
{
<button type="button" class="btn primary" disabled="@(_busy || _view is null)" @onclick="OpenFinal"><KhIcon Name="lock" /> @T["Ledger.VatRegisters.PrintFinal"]</button>
}
</div>
</div>
@if (_registers.Count > 0)
{
<KhTabs Items="Tabs" Active="@_registerId.ToString(System.Globalization.CultureInfo.InvariantCulture)" ActiveChanged="SetRegisterAsync" Label="@T["Ledger.VatRegisters.Title"]" />
}
@if (_view is { } view)
{
<KhStrip Items="Stats(view)" Label="@view.Register.Description" />
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["Ledger.Fields.From"]" Name="from" Value="_from" ValueChanged="SetFromAsync" />
<KhDateBox Label="@T["Ledger.Fields.To"]" Name="to" Value="_to" ValueChanged="SetToAsync" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.VatRegisters.Lines", T.Number(view.Rows.Count))</span>
</div>
@if (view.Rows.Count == 0)
{
<p class="kh-wempty">@T["Ledger.VatRegisters.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@view.Register.Description">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Protocol"]</th>
<th scope="col">@T["Ledger.Fields.VatDate"]</th>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col">@T["Ledger.Fields.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
<th scope="col">@T["Ledger.Fields.Exigibility"]</th>
</tr>
</thead>
<tbody>
@foreach (var r in view.Rows)
{
<tr>
<td class="code"><a href="@LedgerScreens.EntryUrl(r.EntryId)">@r.VatProtocol</a></td>
<td>@T.Date(r.VatDate)</td>
<td>@r.DocumentNumber</td>
<td>@(r.DocumentDate is { } d ? T.Date(d) : null)</td>
<td>@r.PartyName</td>
<td>@RateText(r.Rate, r.Nature)</td>
<td class="num">@T.Money(r.Taxable)</td>
<td class="num">@T.Money(r.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, r.NonDeductibleTax)</td>
<td>@(r.Exigibility == Khaemhat.Core.Tax.TaxExigibility.Immediate ? null : T["Ledger.Enums.TaxExigibility." + r.Exigibility])</td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
<KhPanel Title="@T["Ledger.VatRegisters.Totals"]" Icon="euro" Tight="true">
<table class="grid" aria-label="@T["Ledger.VatRegisters.Totals"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
</tr>
</thead>
<tbody>
@foreach (var t in view.Totals)
{
<tr>
<td>@RateText(t.Rate, t.Nature)</td>
<td class="num">@T.Money(t.Taxable)</td>
<td class="num">@T.Money(t.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, t.NonDeductibleTax)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td><b>@T["Ledger.VatRegisters.RegisterTotal"]</b></td>
<td class="num"><b>@T.Money(view.Totals.Sum(t => t.Taxable))</b></td>
<td class="num"><b>@T.Money(view.Totals.Sum(t => t.Tax))</b></td>
<td class="num"><b>@LedgerScreens.AmountText(T, view.Totals.Sum(t => t.NonDeductibleTax))</b></td>
</tr>
</tfoot>
</table>
</KhPanel>
}
else if (_registers.Count == 0)
{
<p class="kh-wempty">@T["Ledger.VatRegisters.NoRegisters"]</p>
}
<KhDialog Open="_finalOpen" Title="@T["Ledger.VatRegisters.PrintFinal"]" Icon="lock" OnClose="() => _finalOpen = false">
<ChildContent>
<p>@T.Format("Ledger.VatRegisters.FinalText", _finalFrom is { } ff ? T.Date(ff) : "-", _view?.Register.PrintYear == _finalTo?.Year ? (_view?.Register.LastPage ?? 0) + 1 : 1)</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.VatRegisters.FinalUpTo"]" Name="finalto" @bind-Value="_finalTo" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _finalOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _finalTo is null)" @onclick="() => PrintAsync(final: true)"><KhIcon Name="printer" /> @T["Ledger.VatRegisters.PrintFinal"]</button>
</Footer>
</KhDialog>
</LedgerGuard>
@code {
private IReadOnlyList<VatRegister> _registers = [];
private long _registerId;
private VatRegisterView? _view;
private DateOnly? _from;
private DateOnly? _to;
private bool _busy;
private bool _finalOpen;
private DateOnly? _finalFrom;
private DateOnly? _finalTo;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private IReadOnlyList<KhTabItem> Tabs =>
[.. _registers.Where(r => !r.Disabled).Select(r => new KhTabItem(r.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), "file", r.Code + " · " + r.Description))];
private IReadOnlyList<KhStat> Stats(VatRegisterView view) =>
[
new(T["Ledger.Fields.Kind"], T[LedgerScreens.EnumKey(view.Register.Kind)] + (view.Register.ReverseCharge ? " · RC" : string.Empty)),
new(T["Ledger.Fields.Taxable"], T.Money(view.Totals.Sum(t => t.Taxable))),
new(T["Ledger.Fields.Tax"], T.Money(view.Totals.Sum(t => t.Tax))),
new(T["Ledger.VatRegisters.LastPrint"], view.Register.LastPrintedDate is { } d ? T.Date(d) : T["Ledger.VatRegisters.NeverPrinted"],
view.Register.LastPrintedDate is null ? KhTone.Warning : KhTone.Ok),
new(T["Ledger.VatRegisters.LastPage"], view.Register.PrintYear is { } y ? y.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/" + view.Register.LastPage.ToString(System.Globalization.CultureInfo.InvariantCulture) : "-"),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_from = new DateOnly(Today.Year, Today.Month, 1).AddMonths(-1);
_to = new DateOnly(Today.Year, Today.Month, 1).AddDays(-1);
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.VatRegisterRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
_registers = await Ledger.RegistersAsync(actor, company);
_registerId = _registers.FirstOrDefault(r => !r.Disabled)?.Id ?? 0;
await LoadAsync();
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _registerId == 0 || _from is not { } from || _to is not { } to)
{
return;
}
_view = await Vat.RegisterAsync(actor, company, _registerId, from, to);
}
private async Task SetRegisterAsync(string id)
{
_registerId = long.Parse(id, System.Globalization.CultureInfo.InvariantCulture);
await LoadAsync();
}
private async Task SetFromAsync(DateOnly? date)
{
_from = date;
await LoadAsync();
}
private async Task SetToAsync(DateOnly? date)
{
_to = date;
await LoadAsync();
}
private string RateText(decimal rate, string? nature) => nature ?? rate.ToString("0.##", T.Culture) + "%";
private void OpenFinal()
{
var register = _view?.Register;
_finalFrom = register?.LastPrintedDate is { } last ? last.AddDays(1) : new DateOnly(Today.Year, 1, 1);
_finalTo = _to;
_finalOpen = true;
}
private async Task PrintAsync(bool final)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to)
{
return;
}
if (final && !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.VatRegisters.PrintFinal"], T["Ledger.VatRegisters.FinalConfirm"], T["Ledger.VatRegisters.PrintFinal"], T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
var file = final
? await Vat.PrintRegisterAsync(actor, company, _registerId, _finalFrom ?? from, _finalTo ?? to, final: true)
: await Vat.PrintRegisterAsync(actor, company, _registerId, from, to, final: false);
await LedgerScreens.DownloadAsync(JS, file);
if (final)
{
_finalOpen = false;
_registers = await Ledger.RegistersAsync(actor, company);
Toasts.Show(ToastKind.Success, T["Ledger.VatRegisters.Printed"]);
await LoadAsync();
}
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,411 @@
@page "/contabilita/liquidazione-iva"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Application.Tables
@using Khaemhat.Core.Accounting
@using Khaemhat.Core.Tax
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject VatService Vat
@inject TaxService Taxes
@inject CompanyProfileService Profiles
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* The periodic VAT settlement (SPEC §11.7, mockup 046): the registers of the period, the VAT due and deductible, the
credit carried, the advance and the interest of quarterly payers; the confirmation settles the months (no more VAT
documents there), posts the entry and writes the F24 line; the LIPE of the quarter and the F24 data for the
intermediary or the home banking. In December, the advance. *@
<KhPageTitle Text="@T["Ledger.Settlement.Title"]" Icon="coins" />
<LedgerGuard Permission="@LedgerPermissions.SettlementRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Settlement.Title"]</div>
<h1>@T["Ledger.Settlement.Heading"]</h1>
<div class="sub">@T["Ledger.Settlement.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<KhBadge Tone="KhTone.Info">@PeriodName(_year, _number)</KhBadge>
@if (_view is { } v)
{
<KhBadge Tone="@(v.Settlement.Status == VatSettlementStatus.Confirmed ? KhTone.Ok : KhTone.Warning)">@T[LedgerScreens.EnumKey(v.Settlement.Status)]</KhBadge>
}
</div>
</div>
<div class="toolbar kh-pad">
<button type="button" class="btn primary" disabled="@(_busy || Confirmed)" @onclick="ComputeAsync"><KhIcon Name="zap" /> @T["Ledger.Settlement.Compute"]</button>
@if (CanConfirm)
{
@if (Confirmed)
{
<button type="button" class="btn" disabled="@_busy" @onclick="ReopenAsync"><KhIcon Name="undo" /> @T["Ledger.Settlement.Reopen"]</button>
}
else
{
<button type="button" class="btn" disabled="@(_busy || _view is null)" @onclick="ConfirmAsync"><KhIcon Name="lock" /> @T["Ledger.Settlement.Confirm"]</button>
}
}
<button type="button" class="btn" disabled="@(_busy || !QuarterClosed)" @onclick="LipeAsync"><KhIcon Name="file" /> @T["Ledger.Settlement.Lipe"]</button>
<button type="button" class="btn" disabled="@(_busy || _view?.Settlement.DueDate is null || _view.Settlement.AmountDue == 0m)" @onclick="F24Async"><KhIcon Name="download" /> @T["Ledger.Settlement.F24Data"]</button>
</div>
<KhPanel>
<div class="form plain">
<KhField Label="@T["Ledger.Settlement.Periodicity"]" Span="3"><span class="in ro">@T["Ledger.Enums.VatPeriodicity." + _periodicity]</span></KhField>
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Year"]" Name="year" Options="YearChoices" Value="_year" ValueChanged="SetYearAsync" Span="2" />
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Period"]" Name="period" Options="PeriodChoices" Value="_number" ValueChanged="SetPeriodAsync" Span="3" />
<KhField Label="@T["Ledger.Settlement.PreviousCredit"]" Span="2"><span class="in ro">@T.Money(_view?.Settlement.PreviousCredit ?? 0m)</span></KhField>
<KhField Label="@T["Ledger.Settlement.ProRata"]" Span="2"><span class="in ro">@T.Format("Ledger.Settlement.ProRataValue", (_view?.Settlement.ProRataPercent ?? 100m).ToString("0.##", T.Culture))</span></KhField>
</div>
</KhPanel>
@if (_view is { } view)
{
var s = view.Settlement;
<KhPanel Title="@T["Ledger.Settlement.Registers"]" Icon="file-check" Tight="true">
<table class="grid" aria-label="@T["Ledger.Settlement.Registers"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.VatRegister"]</th>
<th scope="col">@T["Ledger.Fields.Kind"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.Documents"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Tax"]</th>
<th scope="col" class="num">@T["Ledger.Fields.NonDeductible"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.Deferred"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in view.Lines)
{
var register = view.Registers.GetValueOrDefault(line.VatRegisterId);
<tr>
<td class="code">@register?.Code</td>
<td>@register?.Description</td>
<td class="num">@line.Documents</td>
<td class="num">@T.Money(line.Taxable)</td>
<td class="num">@T.Money(line.Tax)</td>
<td class="num">@LedgerScreens.AmountText(T, line.NonDeductibleTax)</td>
<td class="num">@LedgerScreens.AmountText(T, line.DeferredTax)</td>
</tr>
}
</tbody>
</table>
</KhPanel>
<div class="kh-ledger-two">
<KhPanel Title="@T["Ledger.Settlement.Calculation"]" Icon="chart">
<div class="totals">
<span>@T["Ledger.Settlement.SalesTax"]</span><span>@T.Money(s.SalesTax)</span>
<span>@T["Ledger.Settlement.PurchaseTax"]</span><span>@T.Money(s.PurchaseTax)</span>
<span>@T["Ledger.Settlement.NonDeductibleTax"]</span><span>@T.Money(s.NonDeductibleTax)</span>
<span>@T["Ledger.Settlement.DeferredTax"]</span><span>@T.Money(s.DeferredTax)</span>
<span>@T["Ledger.Settlement.PreviousCredit"]</span><span>@T.Money(s.PreviousCredit)</span>
<span>@T["Ledger.Settlement.PreviousDebit"]</span><span>@T.Money(s.PreviousDebit)</span>
<span>@T["Ledger.Settlement.AdvancePaid"]</span><span>@T.Money(s.AdvancePaid)</span>
<span>@T.Format("Ledger.Settlement.Interest", s.InterestPercent.ToString("0.##", T.Culture))</span><span>@T.Money(s.Interest)</span>
@if (s.AmountDue > 0m)
{
<span class="big">@T["Ledger.Settlement.AmountDue"]</span><span>@T.Money(s.AmountDue)</span>
}
else if (s.DebitCarried > 0m)
{
<span class="big">@T["Ledger.Settlement.DebitCarried"]</span><span>@T.Money(s.DebitCarried)</span>
}
else
{
<span class="big">@T["Ledger.Settlement.CreditCarried"]</span><span>@T.Money(s.CreditCarried)</span>
}
</div>
</KhPanel>
<KhPanel Title="@T["Ledger.Settlement.Payment"]" Icon="euro">
<dl class="kv">
<dt>@T["Ledger.Settlement.PaymentCode"]</dt><dd class="code">@s.PaymentCode</dd>
<dt>@T["Ledger.Settlement.Year"]</dt><dd>@s.Year</dd>
<dt>@T["Ledger.Fields.Amount"]</dt><dd>@T.Money(s.AmountDue)</dd>
<dt>@T["Ledger.Settlement.DueDate"]</dt><dd>@(s.DueDate is { } due ? T.Date(due) : "-")</dd>
<dt>@T["Ledger.Settlement.Entry"]</dt><dd>
@if (s.GlEntryId is { } entry)
{
<a href="@LedgerScreens.EntryUrl(entry)">@T["Ledger.Settlement.OpenEntry"]</a>
}
else
{
<span>-</span>
}
</dd>
<dt>@T["Ledger.Settlement.LipeQuarter"]</dt><dd>@T.Format("Ledger.Settlement.QuarterName", QuarterOf(s), s.Year)</dd>
</dl>
<div class="callout info kh-pad">
<KhIcon Name="info" />
<span>@T["Ledger.Settlement.Telematic"]</span>
</div>
</KhPanel>
</div>
}
else
{
<p class="kh-wempty">@T["Ledger.Settlement.NotComputed"]</p>
}
<KhPanel Title="@T.Format("Ledger.Settlement.YearList", _year)" Icon="list" Tight="true">
@if (_settlements.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Settlement.NoneYet"]</p>
}
else
{
<table class="grid" aria-label="@T.Format("Ledger.Settlement.YearList", _year)">
<thead>
<tr>
<th scope="col">@T["Ledger.Settlement.Period"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.SalesTax"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.PurchaseTax"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.AmountDue"]</th>
<th scope="col" class="num">@T["Ledger.Settlement.CreditCarried"]</th>
<th scope="col">@T["Ledger.Settlement.DueDate"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var item in _settlements)
{
<tr class="@(item.Number == _number ? "sel" : null)" style="cursor:pointer" @onclick="() => SetPeriodAsync(item.Number)">
<td>@PeriodName(item.Year, item.Number)</td>
<td class="num">@T.Money(item.SalesTax)</td>
<td class="num">@T.Money(item.PurchaseTax)</td>
<td class="num">@(item.AmountDue == 0m ? null : T.Money(item.AmountDue))</td>
<td class="num">@(item.CreditCarried == 0m ? null : T.Money(item.CreditCarried))</td>
<td>@(item.DueDate is { } due ? T.Date(due) : null)</td>
<td><KhBadge Tone="@(item.Status == VatSettlementStatus.Confirmed ? KhTone.Ok : KhTone.Warning)">@T[LedgerScreens.EnumKey(item.Status)]</KhBadge></td>
</tr>
}
</tbody>
</table>
}
</KhPanel>
@if (CanConfirm)
{
<KhPanel Title="@T.Format("Ledger.Advance.Title", _year)" Icon="calendar">
<p class="muted sm">@T["Ledger.Advance.Hint"]</p>
<div class="form plain">
<KhSelect TValue="VatAdvanceMethod" Label="@T["Ledger.Advance.Method"]" Name="method" Options="LedgerScreens.Choices<VatAdvanceMethod>(T)" Value="_method" ValueChanged="SetMethod" Span="4" />
<KhNumberBox Label="@T["Ledger.Advance.Basis"]" Name="basis" @bind-Value="_basis" Span="4" Hint="@T["Ledger.Advance.BasisHint"]" />
<KhField Label="@T["Ledger.Advance.Bases"]" Span="4">
<span class="in ro">@T.Format("Ledger.Advance.BasesValue", T.Money(_bases.Historical), T.Money(_bases.Actual))</span>
</KhField>
</div>
<div class="kh-formactions">
<button type="button" class="btn" disabled="@_busy" @onclick="LoadBasesAsync"><KhIcon Name="refresh" /> @T["Ledger.Advance.Refresh"]</button>
<button type="button" class="btn primary" disabled="@(_busy || (_basis ?? 0m) <= 0m)" @onclick="AdvanceAsync"><KhIcon Name="check" /> @T["Ledger.Advance.Record"]</button>
</div>
</KhPanel>
}
</LedgerGuard>
@code {
private VatPeriodicity _periodicity = VatPeriodicity.Monthly;
private int _year;
private int _number;
private VatSettlementView? _view;
private IReadOnlyList<VatSettlement> _settlements = [];
private bool _busy;
private VatAdvanceMethod _method = VatAdvanceMethod.Historical;
private decimal? _basis;
private (decimal Historical, decimal Actual) _bases;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private bool CanConfirm => Session.Permissions.Allows(LedgerPermissions.SettlementConfirm);
private bool Confirmed => _view?.Settlement.Status == VatSettlementStatus.Confirmed;
private int LastNumber => _periodicity == VatPeriodicity.Monthly ? 12 : 4;
// The LIPE of a quarter needs its settlements confirmed: the last month of the quarter (or the quarter itself).
private bool QuarterClosed => _view?.Settlement is { Status: VatSettlementStatus.Confirmed } s
&& (s.Periodicity == VatPeriodicity.Quarterly || s.Number % 3 == 0);
private IReadOnlyList<KhOption<int>> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption<int>(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))];
private IReadOnlyList<KhOption<int>> PeriodChoices => [.. Enumerable.Range(1, LastNumber).Select(n => new KhOption<int>(n, PeriodName(_year, n)))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(LedgerPermissions.SettlementRead)
|| !Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
return;
}
try
{
_periodicity = (await Profiles.GetAsync(actor, company)).VatPeriodicity;
}
catch (AccessDeniedException)
{
_periodicity = VatPeriodicity.Monthly;
}
var previous = Today.AddMonths(-1);
_year = previous.Year;
_number = _periodicity == VatPeriodicity.Monthly ? previous.Month : ((previous.Month - 1) / 3) + 1;
await LoadAsync();
await LoadBasesAsync();
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_settlements = await Vat.SettlementsAsync(actor, company, _year);
var current = _settlements.FirstOrDefault(s => s.Number == _number && s.Periodicity == _periodicity);
_view = current is null ? null : await Vat.SettlementAsync(actor, company, current.Id);
}
private async Task LoadBasesAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_bases = await Vat.AdvanceBasisAsync(actor, company, _year);
SetMethod(_method);
}
private void SetMethod(VatAdvanceMethod method)
{
_method = method;
_basis = method switch
{
VatAdvanceMethod.Historical => _bases.Historical,
VatAdvanceMethod.Actual => _bases.Actual,
_ => _basis,
};
}
private async Task SetYearAsync(int year)
{
_year = year;
await LoadAsync();
await LoadBasesAsync();
}
private async Task SetPeriodAsync(int number)
{
_number = number;
await LoadAsync();
}
private string PeriodName(int year, int number)
{
if (year == 0)
{
return string.Empty;
}
if (_periodicity == VatPeriodicity.Quarterly)
{
return T.Format("Ledger.Settlement.QuarterName", number, year);
}
var text = new DateOnly(year, number, 1).ToString("MMMM yyyy", T.Culture);
return char.ToUpper(text[0], T.Culture) + text[1..];
}
private static int QuarterOf(VatSettlement s) => s.Periodicity == VatPeriodicity.Quarterly ? s.Number : ((s.Number - 1) / 3) + 1;
private async Task ComputeAsync() => await RunAsync(async (actor, company) =>
{
_view = await Vat.ComputeAsync(actor, company, _year, _number);
_settlements = await Vat.SettlementsAsync(actor, company, _year);
});
private async Task ConfirmAsync()
{
if (_view is not { } view || !await Dialogs.ConfirmAsync(new ConfirmRequest(
T["Ledger.Settlement.Confirm"], T.Format("Ledger.Settlement.ConfirmText", PeriodName(_year, _number), T.Money(view.Settlement.AmountDue)), T["Ledger.Settlement.Confirm"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
_view = await Vat.ConfirmAsync(actor, company, view.Settlement.Id);
_settlements = await Vat.SettlementsAsync(actor, company, _year);
Toasts.Show(ToastKind.Success, T["Ledger.Settlement.Confirmed"], PeriodName(_year, _number));
});
}
private async Task ReopenAsync()
{
if (_view is not { } view || !await Dialogs.ConfirmAsync(new ConfirmRequest(
T["Ledger.Settlement.Reopen"], T["Ledger.Settlement.ReopenText"], T["Ledger.Settlement.Reopen"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
_view = await Vat.ReopenAsync(actor, company, view.Settlement.Id);
_settlements = await Vat.SettlementsAsync(actor, company, _year);
});
}
private async Task LipeAsync() => await RunAsync(async (actor, company) =>
{
if (_view?.Settlement is { } s)
{
await LedgerScreens.DownloadAsync(JS, await Vat.PeriodicReturnAsync(actor, company, s.Year, QuarterOf(s)));
}
});
private async Task F24Async() => await RunAsync(async (actor, company) =>
{
if (_view?.Settlement.DueDate is { } due)
{
await LedgerScreens.DownloadAsync(JS, await Taxes.ExportFormAsync(actor, company, due));
}
});
private async Task AdvanceAsync() => await RunAsync(async (actor, company) =>
{
var payment = await Vat.AdvanceAsync(actor, company, _year, _method, _basis ?? 0m);
Toasts.Show(ToastKind.Success, payment is null ? T["Ledger.Advance.NoneDue"] : T.Format("Ledger.Advance.Recorded", T.Money(payment.Amount), T.Date(payment.DueDate)));
});
private async Task RunAsync(Func<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -0,0 +1,420 @@
@page "/contabilita/ritenute"
@attribute [Authorize]
@using Khaemhat.Application.Ledger
@using Khaemhat.Application.Security
@using Khaemhat.Core.Accounting
@using Khaemhat.Web.Ledger
@inject ShellSession Session
@inject TaxService Taxes
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@inject TimeProvider Clock
@* Withholdings and the F24 (SPEC §11.7, mockup 047): the withholdings operated on the fees received, which become due
when the invoice is paid and join the F24 of the 16th of the next month, and those suffered on the fees issued, a
credit for the tax return; the CU data of a year; the F24 of a due date with every tax in it (VAT, withholdings,
stamp duty), its data file and the record of its payment. *@
<KhPageTitle Text="@T["Ledger.Withholdings.Title"]" Icon="shield-check" />
<LedgerGuard Permission="@LedgerPermissions.SettlementRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@LedgerScreens.BasePath">@T["Shell.Menu.Ledger"]</a> / @T["Ledger.Withholdings.Title"]</div>
<h1>@T["Ledger.Withholdings.Heading"]</h1>
<div class="sub">@T["Ledger.Withholdings.Hint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<button type="button" class="btn" disabled="@_busy" @onclick="CertificationsAsync"><KhIcon Name="file" /> @T["Ledger.Withholdings.Cu"]</button>
</div>
</div>
<KhTabs Items="Tabs" Active="@_tab" ActiveChanged="SetTabAsync" Label="@T["Ledger.Withholdings.Title"]" />
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhSelect TValue="int" Label="@T["Ledger.Settlement.Year"]" Name="year" Options="YearChoices" Value="_year" ValueChanged="SetYearAsync" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Ledger.Withholdings.Total", T.Money(_rows.Sum(r => r.Withholding.Amount)))</span>
</div>
@if (_rows.Count == 0)
{
<p class="kh-wempty">@T["Ledger.Withholdings.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Ledger.Withholdings.Title"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Fields.Document"]</th>
<th scope="col">@T["Ledger.Fields.DocumentDate"]</th>
<th scope="col">@T["Ledger.Fields.Party"]</th>
<th scope="col">@T["Ledger.Withholdings.Type"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Taxable"]</th>
<th scope="col">@T["Ledger.Withholdings.Fund"]</th>
<th scope="col" class="num">@T["Ledger.Withholdings.FundAmount"]</th>
<th scope="col">@T["Ledger.Withholdings.Rate"]</th>
<th scope="col" class="num">@T["Ledger.Fields.Amount"]</th>
<th scope="col">@T["Ledger.Withholdings.PaidOn"]</th>
<th scope="col">@T["Ledger.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in _rows)
{
var w = row.Withholding;
<tr>
<td class="code">
@if (w.GlEntryId is { } entry)
{
<a href="@LedgerScreens.EntryUrl(entry)">@w.DocumentNumber</a>
}
else
{
@w.DocumentNumber
}
</td>
<td>@T.Date(w.DocumentDate)</td>
<td>@row.PartyName</td>
<td>@w.WithholdingType @(w.Reason is { } reason ? "· " + reason : null)</td>
<td class="num">@T.Money(w.Taxable)</td>
<td>@w.SocialSecurityFund</td>
<td class="num">@LedgerScreens.AmountText(T, w.SocialSecurityAmount)</td>
<td>@(w.Rate.ToString("0.##", T.Culture))% @(w.BasePercent != 100m ? T.Format("Ledger.Withholdings.On", w.BasePercent.ToString("0.##", T.Culture)) : null)</td>
<td class="num"><b>@T.Money(w.Amount)</b></td>
<td>@(w.InvoicePaidOn is { } paid ? T.Date(paid) : null)</td>
<td><KhBadge Tone="ToneOf(w.Status)">@T[LedgerScreens.EnumKey(w.Status)]</KhBadge></td>
<td class="num">
@if (CanConfirm)
{
@if (w.InvoicePaidOn is null)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="() => OpenPaid(row)"><KhIcon Name="check" /> @T["Ledger.Withholdings.InvoicePaid"]</button>
}
else if (w.Status != WithholdingStatus.Paid)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="() => UndoAsync(row)"><KhIcon Name="undo" /></button>
}
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T["Ledger.Withholdings.Footer"]</span></div>
</KhPanel>
<div class="kh-ledger-two">
<KhPanel Title="@T["Ledger.F24.Title"]" Icon="euro" Tight="true">
<Actions>
<select class="in" style="width:auto" aria-label="@T["Ledger.F24.DueDate"]" @onchange="e => SetDueAsync(e.Value?.ToString())">
@foreach (var date in _dueDates)
{
<option value="@date.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)" selected="@(date == _due)">@T.Date(date)</option>
}
</select>
<button type="button" class="btn sm" disabled="@(_busy || _due is null)" @onclick="ExportAsync"><KhIcon Name="download" /> @T["Ledger.Settlement.F24Data"]</button>
@if (CanConfirm)
{
@if (_formPaid)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="UnpayAsync"><KhIcon Name="undo" /> @T["Ledger.F24.Unpay"]</button>
}
else
{
<button type="button" class="btn sm primary" disabled="@(_busy || _form is null || _form.Lines.Count == 0)" @onclick="OpenPay"><KhIcon Name="check" /> @T["Ledger.F24.Pay"]</button>
}
}
</Actions>
<ChildContent>
@if (_form is not { Lines.Count: > 0 } form)
{
<p class="kh-wempty">@T[_formPaid ? "Ledger.F24.AllPaid" : "Ledger.F24.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Ledger.F24.Lines"]">
<thead>
<tr>
<th scope="col">@T["Ledger.Settlement.PaymentCode"]</th>
<th scope="col">@T["Ledger.Fields.Description"]</th>
<th scope="col">@T["Ledger.Settlement.Period"]</th>
<th scope="col" class="num">@T["Ledger.Side.Dare"]</th>
<th scope="col" class="num">@T["Ledger.F24.Credit"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in form.Lines)
{
<tr>
<td class="code">@line.Code</td>
<td>@line.Description</td>
<td>@(line.Period is { } p ? p + "/" + line.Year : line.Year.ToString(System.Globalization.CultureInfo.InvariantCulture))</td>
<td class="num">@LedgerScreens.AmountText(T, line.Debit)</td>
<td class="num">@LedgerScreens.AmountText(T, line.Credit)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="3"><b>@T.Format("Ledger.F24.Total", _due is { } td ? T.Date(td) : string.Empty)</b></td>
<td class="num" colspan="2"><b>@T.Money(form.Balance)</b></td>
</tr>
</tfoot>
</table>
}
</ChildContent>
</KhPanel>
<div class="callout info">
<KhIcon Name="info" />
<span>@T["Ledger.Withholdings.Note"]</span>
</div>
</div>
<KhDialog Open="_paidOpen" Title="@T["Ledger.Withholdings.InvoicePaid"]" Icon="check" OnClose="() => _paidOpen = false">
<ChildContent>
<p>@T.Format("Ledger.Withholdings.InvoicePaidText", _paidRow?.Withholding.DocumentNumber ?? string.Empty, _paidRow?.PartyName ?? string.Empty)</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.Withholdings.PaidOn"]" Name="paidon" @bind-Value="_paidOn" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _paidOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _paidOn is null)" @onclick="ConfirmPaidAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_payOpen" Title="@T["Ledger.F24.Pay"]" Icon="euro" OnClose="() => _payOpen = false">
<ChildContent>
<p>@T.Format("Ledger.F24.PayText", _due is { } pd ? T.Date(pd) : string.Empty, T.Money(_form?.Balance ?? 0m))</p>
<div class="form plain">
<KhDateBox Label="@T["Ledger.F24.PaidOn"]" Name="f24paid" @bind-Value="_payOn" Span="6" Required="true" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _payOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _payOn is null)" @onclick="PayAsync"><KhIcon Name="check" /> @T["Ledger.F24.Pay"]</button>
</Footer>
</KhDialog>
</LedgerGuard>
@code {
private string _tab = "operated";
private int _year;
private IReadOnlyList<WithholdingRow> _rows = [];
private IReadOnlyList<DateOnly> _dueDates = [];
private DateOnly? _due;
private Khaemhat.Fiscal.Abstractions.TaxPaymentForm? _form;
private bool _formPaid;
private bool _busy;
private bool _paidOpen;
private WithholdingRow? _paidRow;
private DateOnly? _paidOn;
private bool _payOpen;
private DateOnly? _payOn;
private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime);
private bool CanConfirm => Session.Permissions.Allows(LedgerPermissions.SettlementConfirm);
private IReadOnlyList<KhTabItem> Tabs =>
[
new("operated", "users", T["Ledger.Withholdings.Operated"]),
new("suffered", "user", T["Ledger.Withholdings.Suffered"]),
new("all", "list", T["Ledger.Withholdings.All"]),
];
private IReadOnlyList<KhOption<int>> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption<int>(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_year = Today.Year;
if (Session.Actor is { } && Session.Company is { } && Session.Permissions.Allows(LedgerPermissions.SettlementRead)
&& Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting))
{
await LoadAsync();
await LoadDueDatesAsync(null);
}
}
private async Task LoadAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
WithholdingDirection? direction = _tab switch
{
"operated" => WithholdingDirection.Operated,
"suffered" => WithholdingDirection.Suffered,
_ => null,
};
_rows = await Taxes.WithholdingsAsync(actor, company, _year, direction);
}
// The due dates of the year with something on them; the first one still unpaid from today on is chosen.
private async Task LoadDueDatesAsync(DateOnly? keep)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
var payments = (await Taxes.PaymentsAsync(actor, company, _year)).Concat(await Taxes.PaymentsAsync(actor, company, _year + 1)).ToList();
_dueDates = [.. payments.Select(p => p.DueDate).Distinct().Order()];
DateOnly? firstUnpaid = payments.Where(p => p.PaidOn is null).OrderBy(p => p.DueDate).Select(p => (DateOnly?)p.DueDate).FirstOrDefault();
DateOnly? lastDue = _dueDates.Count > 0 ? _dueDates[^1] : null;
_due = keep is { } k && _dueDates.Contains(k) ? k : firstUnpaid ?? lastDue;
_formPaid = _due is { } due && payments.Where(p => p.DueDate == due).All(p => p.PaidOn is not null);
await LoadFormAsync();
}
private async Task LoadFormAsync()
{
_form = null;
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _due is not { } due)
{
return;
}
_form = await Taxes.FormAsync(actor, company, due);
}
private async Task SetTabAsync(string tab)
{
_tab = tab;
await LoadAsync();
}
private async Task SetYearAsync(int year)
{
_year = year;
await LoadAsync();
await LoadDueDatesAsync(null);
}
private async Task SetDueAsync(string? text)
{
if (DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var date))
{
await LoadDueDatesAsync(date);
}
}
private void OpenPaid(WithholdingRow row)
{
_paidRow = row;
_paidOn = Today;
_paidOpen = true;
}
private async Task ConfirmPaidAsync() => await RunAsync(async (actor, company) =>
{
if (_paidRow is { } row && _paidOn is { } date)
{
await Taxes.InvoicePaidAsync(actor, company, row.Withholding.Id, date);
_paidOpen = false;
await LoadAsync();
await LoadDueDatesAsync(_due);
}
});
private async Task UndoAsync(WithholdingRow row)
{
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.Withholdings.Undo"], T.Format("Ledger.Withholdings.UndoText", row.Withholding.DocumentNumber ?? string.Empty), T["Ledger.Withholdings.Undo"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
await Taxes.UndoInvoicePaidAsync(actor, company, row.Withholding.Id);
await LoadAsync();
await LoadDueDatesAsync(_due);
});
}
private async Task CertificationsAsync() => await RunAsync(async (actor, company) => await LedgerScreens.DownloadAsync(JS, await Taxes.CertificationsAsync(actor, company, _year)));
private async Task ExportAsync() => await RunAsync(async (actor, company) =>
{
if (_due is { } due)
{
await LedgerScreens.DownloadAsync(JS, await Taxes.ExportFormAsync(actor, company, due));
}
});
private void OpenPay()
{
_payOn = _due is { } due && due <= Today ? due : Today;
_payOpen = true;
}
private async Task PayAsync() => await RunAsync(async (actor, company) =>
{
if (_due is { } due && _payOn is { } paidOn)
{
var entry = await Taxes.PayAsync(actor, company, due, paidOn);
_payOpen = false;
Toasts.Show(ToastKind.Success, T["Ledger.F24.Paid"], entry?.EntryNumber);
await LoadAsync();
await LoadDueDatesAsync(due);
}
});
private async Task UnpayAsync()
{
if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Ledger.F24.Unpay"], T["Ledger.F24.UnpayText"], T["Ledger.F24.Unpay"], T["Common.Cancel"])))
{
return;
}
await RunAsync(async (actor, company) =>
{
if (_due is { } due)
{
await Taxes.UnpayAsync(actor, company, due);
await LoadAsync();
await LoadDueDatesAsync(due);
}
});
}
private static KhTone ToneOf(WithholdingStatus status) => status switch
{
WithholdingStatus.Due => KhTone.Warning,
WithholdingStatus.Paid => KhTone.Ok,
WithholdingStatus.Suffered => KhTone.Neutral,
_ => KhTone.Info,
};
private async Task RunAsync(Func<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -154,6 +154,16 @@ internal static class KhaemhatServices
services.AddSingleton<IScheduledJob, Khaemhat.Application.Inventory.InventoryRebuildJob>();
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
// The ledger (ADR 0036, ADR 0037): the documents post through LedgerPoster inside the transaction of the engine.
services.AddSingleton<Khaemhat.Application.Ledger.LedgerPoster>();
services.AddSingleton<Khaemhat.Application.Ledger.JournalEntryService>();
services.AddSingleton<Khaemhat.Application.Ledger.LedgerService>();
services.AddSingleton<Khaemhat.Application.Ledger.VatService>();
services.AddSingleton<Khaemhat.Application.Ledger.TaxService>();
services.AddSingleton<Khaemhat.Application.Ledger.LedgerQueryService>();
services.AddSingleton<Khaemhat.Application.Ledger.RecurringEntryService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.Ledger.RecurringEntriesJob>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
@@ -177,6 +187,7 @@ internal static class KhaemhatServices
services.AddSingleton<ISeeder, BaseTablesSeeder>();
services.AddSingleton<ISeeder, DemoPartiesSeeder>();
services.AddSingleton<ISeeder, DemoItemsSeeder>();
services.AddSingleton<ISeeder, LedgerSeeder>();
services.AddSingleton<SeedRunner>();
// Companies and start.
@@ -186,6 +197,8 @@ internal static class KhaemhatServices
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
services.AddSingleton<DemoPurchasesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoPurchasesSeeder>());
services.AddSingleton<DemoLedgerSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoLedgerSeeder>());
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
+1
View File
@@ -133,6 +133,7 @@ public static class SeedCommand
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoLedgerSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
+106
View File
@@ -0,0 +1,106 @@
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Web.Tables;
using Khaemhat.Web.Ui;
using Microsoft.JSInterop;
namespace Khaemhat.Web.Ledger;
/// <summary>What the screens of the ledger share (SPEC §11.7, mockups 040-047 and 060): addresses, texts of enums and errors, downloads.</summary>
public static class LedgerScreens
{
/// <summary>The address of the area.</summary>
public const string BasePath = "/contabilita";
/// <summary>The address of an entry.</summary>
/// <param name="id">The entry.</param>
/// <returns>The address.</returns>
public static string EntryUrl(long id) => BasePath + "/prima-nota/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>The key of the text of an enum value.</summary>
/// <param name="value">The value.</param>
/// <returns>The key.</returns>
public static string EnumKey(Enum value)
{
ArgumentNullException.ThrowIfNull(value);
return "Ledger.Enums." + value.GetType().Name + "." + value;
}
/// <summary>The choices of an enum.</summary>
/// <typeparam name="TEnum">The enum.</typeparam>
/// <param name="texts">The texts.</param>
/// <returns>The choices in declaration order.</returns>
public static IReadOnlyList<KhOption<TEnum>> Choices<TEnum>(ITexts texts)
where TEnum : struct, Enum
{
ArgumentNullException.ThrowIfNull(texts);
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<TEnum>(v, texts[EnumKey(v)]))];
}
/// <summary>The text of the errors of a refused operation.</summary>
/// <param name="texts">The texts.</param>
/// <param name="exception">The refusal.</param>
/// <returns>The messages, one sentence each.</returns>
public static string Errors(ITexts texts, ValidationFailedException exception)
{
ArgumentNullException.ThrowIfNull(texts);
ArgumentNullException.ThrowIfNull(exception);
return string.Join(" ", exception.Errors.Select(e => TableValues.SplitError(e).Code).Distinct(StringComparer.Ordinal).Select(c => texts.Contains(c) ? texts[c] : c));
}
/// <summary>The tone of the state of an entry.</summary>
/// <param name="status">The state.</param>
/// <returns>The tone.</returns>
public static KhTone ToneOf(GlEntryStatus status) => status switch
{
GlEntryStatus.Draft => KhTone.Warning,
GlEntryStatus.Final => KhTone.Ok,
_ => KhTone.Info,
};
/// <summary>A balance as the screens show it: amount and side (D or A).</summary>
/// <param name="texts">The texts.</param>
/// <param name="amount">The balance, debit positive.</param>
/// <returns>The text.</returns>
public static string Balance(ITexts texts, decimal amount)
{
ArgumentNullException.ThrowIfNull(texts);
return amount == 0m ? texts.Money(0m) : texts.Money(Math.Abs(amount)) + " " + texts[amount > 0m ? "Ledger.Side.D" : "Ledger.Side.A"];
}
/// <summary>Gives the browser a file made by the ledger.</summary>
/// <param name="js">The interop.</param>
/// <param name="file">The file.</param>
/// <returns>A task.</returns>
public static async Task DownloadAsync(IJSRuntime js, LedgerFile file)
{
ArgumentNullException.ThrowIfNull(js);
ArgumentNullException.ThrowIfNull(file);
using var buffer = new MemoryStream(file.Content);
using var stream = new DotNetStreamReference(buffer, leaveOpen: true);
await js.InvokeVoidAsync("khaemhat.download", file.FileName, file.MediaType, stream).ConfigureAwait(false);
}
/// <summary>Reads an amount typed with the Italian separators.</summary>
/// <param name="texts">The texts (for the culture).</param>
/// <param name="text">The text.</param>
/// <returns>The amount, or zero.</returns>
public static decimal ParseAmount(ITexts texts, string? text)
{
ArgumentNullException.ThrowIfNull(texts);
var clean = (text ?? string.Empty).Replace("€", string.Empty, StringComparison.Ordinal).Replace(".", string.Empty, StringComparison.Ordinal).Trim();
return decimal.TryParse(clean, System.Globalization.NumberStyles.Number, texts.Culture, out var value) ? Math.Round(value, 2, MidpointRounding.AwayFromZero) : 0m;
}
/// <summary>An amount for an input box: empty for zero.</summary>
/// <param name="texts">The texts.</param>
/// <param name="amount">The amount.</param>
/// <returns>The text.</returns>
public static string AmountText(ITexts texts, decimal amount)
{
ArgumentNullException.ThrowIfNull(texts);
return amount == 0m ? string.Empty : amount.ToString("#,##0.00", texts.Culture);
}
}
@@ -4,6 +4,8 @@
"Close": "Chiudi",
"Cancel": "Annulla",
"Save": "Salva",
"Edit": "Modifica",
"Delete": "Elimina",
"Reset": "Ripristina",
"Yes": "Sì",
"No": "No",
@@ -0,0 +1,520 @@
{
"Ledger": {
"Saved": "Salvato",
"NotSaved": "Non salvato",
"NotDone": "Operazione non eseguita",
"NoCompany": "Scegli un'azienda per lavorare sulla contabilità",
"NoModule": {
"Title": "Contabilità non attiva",
"Lead": "La licenza di questa azienda non comprende il modulo Contabilità generale e IVA (ACCT). Attivalo da Amministrazione, Licenze."
},
"Print": "Stampa",
"Pager": "{0}-{1} di {2}",
"Previous": "Precedenti",
"Next": "Successivi",
"Side": {
"Dare": "Dare",
"Avere": "Avere",
"D": "D",
"A": "A"
},
"Fields": {
"Account": "Conto",
"Amount": "Importo",
"Area": "Area",
"ClosesAutomatically": "Chiuso in automatico a fine esercizio",
"Code": "Codice",
"CostCenter": "Centro di costo",
"Date": "Data",
"Description": "Descrizione",
"Disabled": "Disattivato",
"Document": "Documento",
"DocumentDate": "Data documento",
"DocumentNumber": "Numero documento",
"Exigibility": "Esigibilità",
"From": "Dal",
"To": "Al",
"Kind": "Tipo",
"Level": "Livello",
"LineDescription": "Descrizione riga",
"Nature": "Natura",
"NonDeductible": "Indetraibile",
"Number": "Numero",
"OpensItems": "Apre partite",
"Party": "Cliente o fornitore",
"Protocol": "Protocollo",
"Rate": "Aliquota",
"Reclassification": "Riclassificazione",
"Reverses": "Causale di storno",
"Role": "Ruolo",
"Side": "Segno",
"StatementLine": "Voce di bilancio CEE",
"Status": "Stato",
"SubLedger": "Partitario",
"Tax": "Imposta",
"TaxCode": "Codice IVA",
"Taxable": "Imponibile",
"Template": "Causale",
"Type": "Tipo",
"VatDate": "Data registrazione IVA",
"VatRegister": "Registro IVA",
"VatRelevant": "Rilevante IVA"
},
"Journal": {
"Title": "Prima nota",
"Heading": "Prima nota",
"Hint": "Le registrazioni contabili dell'esercizio: manuali, dai documenti, dalle liquidazioni e dai versamenti.",
"Entries": "Registrazioni",
"Count": "{0} registrazioni",
"None": "Nessuna registrazione con questi filtri.",
"Search": "Cerca per descrizione, numero o documento",
"AllStates": "Tutti gli stati",
"New": "Nuova registrazione",
"NoNumber": "Bozza",
"Reversed": "Stornata",
"PostDocuments": "Contabilizza documenti",
"PostText": "Registra in prima nota i documenti di vendita e acquisto confermati del periodo che non sono ancora contabilizzati.",
"PostAgain": "Ricontabilizza anche i documenti già registrati (solo se le registrazioni non sono definitive)",
"PostRun": "Contabilizza",
"Posted": "Documenti contabilizzati: {0}.",
"Finalize": "Rendi definitive",
"FinalizeText": "Le registrazioni rese definitive ricevono il numero di libro giornale e non si possono più modificare né eliminare: si correggono solo con uno storno.",
"FinalizeUpTo": "Fino al giorno",
"FinalizeConfirm": "Rendere definitive tutte le registrazioni fino al {0}? L'operazione non si può annullare.",
"Finalized": "Registrazioni rese definitive: {0}."
},
"Entry": {
"Title": "Registrazione {0}",
"New": "Nuova registrazione",
"NewHint": "Scegli una causale per proporre le righe, poi completa conti e importi: Dare e Avere devono quadrare.",
"Header": "Testata",
"Lines": "Righe",
"LinesCount": "Righe",
"Vat": "Castelletto IVA",
"Totals": "Totali",
"Difference": "Sbilancio",
"Unbalanced": "La registrazione non quadra: mancano {0} in {1}.",
"CloseDifference": "Chiudi lo sbilancio",
"AddLine": "Aggiungi riga",
"RemoveLine": "Togli riga",
"AddVat": "Aggiungi aliquota",
"ChooseParty": "Cerca cliente o fornitore",
"NoTemplate": "Nessuna causale",
"NoRegister": "Nessun registro IVA",
"JournalNumber": "Libro giornale n. {0}",
"SaveDraft": "Salva bozza",
"Post": "Registra",
"Posted": "Registrazione salvata",
"Reverse": "Storna",
"ReverseDate": "Data dello storno",
"ReverseText": "Lo storno crea una nuova registrazione con Dare e Avere invertiti che annulla questa.",
"Reversed": "Storno registrato",
"ReversalOf": "storno di un'altra registrazione",
"ReversedBy": "stornata da un'altra registrazione",
"Delete": "Elimina registrazione",
"DeleteText": "Eliminare la registrazione {0}? Solo le registrazioni non definitive si possono eliminare.",
"Deleted": "Registrazione eliminata"
},
"Recurring": {
"Title": "Ricorrenti",
"Hint": "Le registrazioni che si ripetono (affitti, canoni, ratei): ogni notte Khaemhat copia la registrazione modello alle date previste.",
"None": "Nessuna registrazione ricorrente.",
"New": "Nuova ricorrente",
"Model": "Registrazione modello",
"ModelNumber": "Numero della registrazione modello",
"ModelHint": "Il numero di prima nota della registrazione da copiare.",
"OpenModel": "Apri il modello",
"Frequency": "Frequenza",
"NextDate": "Prossima data",
"EndDate": "Fino al",
"Active": "Attiva",
"Suspended": "Sospesa",
"Generate": "Genera ora",
"Generated": "Registrazioni ricorrenti generate: {0}.",
"Delete": "Elimina ricorrente",
"DeleteText": "Eliminare la ricorrente \"{0}\"? Le registrazioni già generate restano."
},
"Accounts": {
"Title": "Piano dei conti",
"Heading": "Piano dei conti",
"Hint": "Mastri, conti e sottoconti dell'azienda, con natura, voce di bilancio CEE e mastrino dei movimenti.",
"Chart": "Conti",
"Count": "{0} conti",
"Search": "Cerca per codice o descrizione",
"Choose": "Scegli un conto per vederne i dati e il mastrino.",
"New": "Nuovo conto",
"Edit": "Modifica conto",
"Delete": "Elimina conto",
"DeleteText": "Eliminare il conto {0}? Si possono eliminare solo i conti senza movimenti e senza sottoconti.",
"CodeHint": "Mastro, conto e sottoconto separati da punti, ad esempio 05.01.001.",
"CeeHint": "La voce dello schema di bilancio civilistico (art. 2424 e 2425 c.c.), ad esempio CII1.",
"Ledger": "Mastrino",
"Level1": "Mastri",
"Level2": "Conti",
"Level3": "Sottoconti"
},
"Templates": {
"Title": "Causali contabili",
"Heading": "Causali contabili",
"Hint": "Le causali guidano la prima nota: propongono conti, segni e registro IVA delle righe.",
"List": "Causali",
"Choose": "Scegli una causale per modificarla.",
"New": "Nuova causale",
"Edit": "Modifica causale",
"Lines": "Righe proposte",
"Delete": "Elimina causale",
"DeleteText": "Eliminare la causale {0}? Le causali usate da una registrazione non si possono eliminare."
},
"Parties": {
"Title": "Partitari",
"Heading": "Partitari clienti e fornitori",
"Hint": "Saldo contabile, estratto conto e partite aperte di ogni cliente e fornitore.",
"Customers": "Clienti",
"Suppliers": "Fornitori",
"Search": "Cerca per nome o codice",
"None": "Nessun movimento per questi soggetti.",
"Total": "Saldo complessivo {0}",
"OpenItems": "Aperte",
"Choose": "Scegli un cliente o un fornitore per vederne l'estratto conto.",
"Statement": "Estratto conto di {0}",
"OpenItemsTitle": "Partite",
"ShowClosed": "Mostra anche le partite chiuse",
"NoOpenItems": "Nessuna partita aperta.",
"Installment": "Rata",
"DueDate": "Scadenza",
"Paid": "Pagato",
"Residual": "Residuo"
},
"Movements": {
"Title": "Movimenti",
"None": "Nessun movimento nel periodo.",
"Opening": "Saldo iniziale",
"Totals": "Totali del periodo",
"Balance": "Saldo"
},
"Balance": {
"Title": "Bilancio di verifica",
"Heading": "Bilancio di verifica e libro giornale",
"Hint": "I saldi di tutti i conti nel periodo, con i totali di conti e mastri; la stampa del bilancio e del libro giornale.",
"AllCenters": "Tutti i centri di costo",
"Detail": "Dettaglio",
"Drafts": "Comprendi le bozze",
"Print": "Stampa bilancio",
"JournalProvisional": "Libro giornale di prova",
"JournalFinal": "Libro giornale definitivo",
"None": "Nessun saldo nel periodo.",
"Opening": "Saldo iniziale",
"Debit": "Saldo Dare",
"Credit": "Saldo Avere",
"Totals": "Totali",
"Check": "Quadratura",
"Balanced": "Dare e Avere quadrano",
"NotBalanced": "Dare e Avere non quadrano",
"Result": "Risultato del periodo",
"Profit": "Utile",
"Loss": "Perdita"
},
"VatRegisters": {
"Title": "Registri IVA",
"Heading": "Registri IVA",
"Hint": "Vendite, acquisti e corrispettivi del periodo con protocollo, imponibile e imposta per aliquota; stampa di prova e definitiva.",
"NoRegisters": "Non ci sono registri IVA: aggiorna le tabelle di base dell'azienda.",
"None": "Nessuna registrazione nel periodo.",
"Lines": "{0} registrazioni",
"Totals": "Riepilogo per aliquota",
"RegisterTotal": "Totale registro",
"LastPrint": "Ultima stampa definitiva",
"LastPage": "Ultima pagina",
"NeverPrinted": "Mai stampato",
"PrintProvisional": "Stampa di prova",
"PrintFinal": "Stampa definitiva",
"FinalUpTo": "Fino al giorno",
"FinalText": "La stampa definitiva parte dal {0} e numera le pagine dalla {1}; dopo la stampa le registrazioni del periodo non si possono più modificare.",
"FinalConfirm": "Stampare in definitivo il registro? L'operazione non si può annullare.",
"Printed": "Registro stampato"
},
"Settlement": {
"Title": "Liquidazione IVA",
"Heading": "Liquidazione IVA periodica",
"Hint": "Calcolo dell'IVA a debito e a credito del periodo, credito o debito riportato, interessi trimestrali, registrazione e dati per F24 e LIPE.",
"Periodicity": "Periodicità",
"Year": "Anno",
"Period": "Periodo",
"QuarterName": "{0}° trimestre {1}",
"PreviousCredit": "Credito periodo precedente",
"PreviousDebit": "Debito periodo precedente",
"Compute": "Calcola",
"Confirm": "Conferma liquidazione",
"ConfirmText": "Confermare la liquidazione di {0}? Viene registrata in prima nota e l'importo di {1} va nei versamenti F24.",
"Confirmed": "Liquidazione confermata",
"Reopen": "Riapri",
"ReopenText": "Riaprire la liquidazione? La registrazione viene eliminata o stornata e il versamento F24 tolto, se non è già pagato.",
"NotComputed": "Liquidazione non ancora calcolata: premi Calcola.",
"Calculation": "Calcolo",
"Registers": "Registri del periodo",
"Documents": "Documenti",
"Deferred": "Esigibilità differita",
"SalesTax": "IVA a debito sulle vendite",
"PurchaseTax": "IVA a credito sugli acquisti",
"NonDeductibleTax": "IVA indetraibile",
"DeferredTax": "IVA a esigibilità differita",
"ProRata": "Pro rata",
"ProRataValue": "Detraibilità {0}%",
"CreditCarried": "Credito da riportare",
"DebitCarried": "Debito sotto la soglia di versamento, riportato",
"AdvancePaid": "Acconto versato",
"Interest": "Interessi trimestrali {0}%",
"AmountDue": "Da versare",
"Payment": "Versamento",
"PaymentCode": "Codice tributo",
"DueDate": "Scadenza",
"Entry": "Registrazione",
"OpenEntry": "Apri la registrazione",
"LipeQuarter": "Trimestre LIPE",
"Lipe": "Comunicazione LIPE",
"F24Data": "Dati F24",
"Telematic": "Khaemhat prepara i file della comunicazione LIPE e i dati del modello F24: l'invio telematico si fa con i servizi dell'Agenzia delle Entrate o dell'intermediario.",
"YearList": "Liquidazioni {0}",
"NoneYet": "Nessuna liquidazione nell'anno."
},
"Advance": {
"Title": "Acconto IVA {0}",
"Hint": "L'acconto di dicembre si versa entro il 27/12 con il codice 6013 (mensili) o 6035 (trimestrali); non è dovuto sotto 103,29 euro.",
"Bases": "Basi di calcolo",
"BasesValue": "Storico {0} · Effettivo {1}",
"Method": "Metodo",
"Basis": "Base di calcolo",
"BasisHint": "Per il metodo previsionale, l'IVA che prevedi di dover versare per dicembre o il quarto trimestre.",
"Refresh": "Ricalcola le basi",
"Record": "Registra acconto",
"Recorded": "Acconto di {0} da versare entro il {1}",
"NoneDue": "Nessun acconto dovuto"
},
"Withholdings": {
"Title": "Ritenute d'acconto",
"Heading": "Ritenute d'acconto e F24",
"Hint": "Le ritenute operate sui compensi ai professionisti e quelle subite sulle tue fatture; prospetto F24, versamento e dati per la Certificazione Unica.",
"Operated": "Operate",
"Suffered": "Subite",
"All": "Tutte",
"None": "Nessuna ritenuta nell'anno.",
"Type": "Tipo",
"Rate": "Aliquota",
"On": "su {0}% dell'imponibile",
"Fund": "Cassa",
"FundAmount": "Contributo cassa",
"PaidOn": "Pagata il",
"Total": "Totale ritenute {0}",
"Footer": "La ritenuta operata diventa dovuta quando paghi la fattura del professionista e si versa entro il 16 del mese successivo.",
"Note": "La Certificazione Unica si invia con i servizi dell'Agenzia delle Entrate: Khaemhat prepara i dati dei percipienti.",
"Cu": "Dati Certificazione Unica",
"InvoicePaid": "Fattura pagata",
"InvoicePaidText": "Registra il pagamento della fattura {0} di {1}: la ritenuta diventa da versare con l'F24 del mese successivo.",
"Undo": "Annulla pagamento",
"UndoText": "Annullare il pagamento della fattura {0}? La registrazione della ritenuta viene tolta."
},
"F24": {
"Title": "Prospetto F24",
"DueDate": "Scadenza",
"Lines": "Righe del modello F24",
"None": "Nessun tributo in scadenza.",
"AllPaid": "Tutti i tributi della scadenza sono pagati.",
"Credit": "Credito",
"Total": "Saldo F24 del {0}",
"Pay": "Registra pagamento",
"PayText": "Registra il pagamento dell'F24 del {0} per {1}: Khaemhat scrive la registrazione in prima nota.",
"PaidOn": "Pagato il",
"Paid": "Pagamento F24 registrato",
"Unpay": "Annulla pagamento",
"UnpayText": "Annullare il pagamento dell'F24? La registrazione del pagamento viene tolta o stornata."
},
"StampDuty": {
"Title": "Imposta di bollo",
"Heading": "Imposta di bollo sulle fatture elettroniche",
"Hint": "Il bollo virtuale da 2 euro sulle fatture esenti sopra 77,47 euro, per trimestre, con codice tributo e scadenza.",
"Year": "Bollo {0}",
"Quarter": "Trimestre",
"QuarterBadge": "{0}° trim. {1}",
"Invoices": "Fatture",
"Duty": "Bollo",
"Charge": "Addebito",
"Charged": "Addebitato al cliente",
"Borne": "A carico dell'azienda",
"None": "Nessuna fattura con bollo nel trimestre.",
"Footer": "Sotto 5.000 euro il bollo del primo trimestre si versa con il secondo (30/9) e quello dei primi due con il terzo (30/11).",
"Previous": "Trimestre precedente",
"Record": "Metti in F24",
"Recorded": "Bollo di {0} da versare entro il {1}",
"NoneDue": "Nessun bollo da versare",
"Export": "Dati F24",
"PaidOn": "pagato il {0}",
"InF24": "In F24",
"ToRecord": "Da mettere in F24"
},
"Enums": {
"GlEntryStatus": {
"Draft": "Bozza",
"Posted": "Registrata",
"Final": "Definitiva"
},
"GlEntrySource": {
"Manual": "Manuale",
"Document": "Da documento",
"VatSettlement": "Liquidazione IVA",
"TaxPayment": "Versamento F24",
"Recurring": "Ricorrente",
"Reversal": "Storno",
"Withholding": "Ritenuta"
},
"RecurrenceFrequency": {
"Monthly": "Mensile",
"Quarterly": "Trimestrale",
"HalfYearly": "Semestrale",
"Yearly": "Annuale"
},
"AccountNature": {
"Asset": "Attività",
"Liability": "Passività",
"Cost": "Costo",
"Revenue": "Ricavo",
"Memorandum": "Conto d'ordine"
},
"AccountType": {
"Generic": "Generico",
"Customers": "Clienti",
"Suppliers": "Fornitori",
"Bank": "Banca",
"Cash": "Cassa",
"Vat": "IVA",
"Tax": "Tributi"
},
"JournalArea": {
"General": "Generale",
"Sales": "Vendite",
"Purchases": "Acquisti",
"Treasury": "Tesoreria",
"Taxes": "Imposte",
"YearEnd": "Chiusura esercizio"
},
"PostingRole": {
"Account": "Conto indicato",
"Customer": "Cliente",
"Supplier": "Fornitore",
"Revenue": "Ricavo",
"Cost": "Costo",
"SalesVat": "IVA vendite",
"PurchaseVat": "IVA acquisti",
"Bank": "Banca",
"Cash": "Cassa",
"WithholdingPayable": "Ritenute da versare",
"WithholdingCredit": "Ritenute subite",
"SocialSecurity": "Contributo cassa",
"StampDuty": "Bollo",
"Rounding": "Arrotondamenti",
"VatSettlement": "Erario c/IVA",
"SplitPaymentVat": "IVA split payment"
},
"AccountSide": {
"Debit": "Dare",
"Credit": "Avere"
},
"VatRegisterKind": {
"Sales": "Vendite",
"Purchases": "Acquisti",
"Receipts": "Corrispettivi"
},
"VatSettlementStatus": {
"Draft": "Da confermare",
"Confirmed": "Confermata"
},
"WithholdingStatus": {
"Waiting": "In attesa del pagamento",
"Due": "Da versare",
"Paid": "Versata",
"Suffered": "Subita"
},
"VatAdvanceMethod": {
"Historical": "Storico",
"Forecast": "Previsionale",
"Actual": "Effettivo"
},
"VatPeriodicity": {
"Monthly": "Mensile",
"Quarterly": "Trimestrale"
},
"TaxExigibility": {
"Immediate": "Immediata",
"Deferred": "Differita",
"SplitPayment": "Scissione dei pagamenti"
}
}
},
"ledger": {
"entry": {
"not-found": "La registrazione non esiste più.",
"description-required": "Scrivi la descrizione della registrazione.",
"date-required": "Indica la data di registrazione.",
"lines-required": "Una registrazione ha almeno due righe.",
"unbalanced": "Il totale Dare e il totale Avere non coincidono.",
"vat-register-required": "Con righe IVA serve un registro IVA.",
"final": "La registrazione è definitiva: si corregge solo con uno storno.",
"from-document": "La registrazione viene da un documento: correggi il documento e ricontabilizzalo.",
"already-reversed": "La registrazione è già stata stornata.",
"not-posted": "Si possono stornare solo le registrazioni registrate.",
"final-order": "Le date devono seguire l'ordine del libro giornale: c'è già una registrazione definitiva successiva.",
"recurring-model": "La registrazione è il modello di una ricorrente: togli prima la ricorrente.",
"drafts-before-final": "Ci sono bozze nel periodo: registrale o eliminale prima di renderlo definitivo.",
"no-fiscal-year": "Non c'è un esercizio aperto per questa data."
},
"line": {
"account-required": "Ogni riga ha un conto.",
"account-missing": "Un conto delle righe non esiste più.",
"account-not-postable": "Si registra solo sui sottoconti, non su mastri e conti.",
"account-disabled": "Un conto delle righe è disattivato.",
"party-required": "Le righe su clienti e fornitori indicano il soggetto.",
"amount-required": "Ogni riga ha un importo in Dare o in Avere.",
"both-sides": "Una riga ha l'importo in Dare oppure in Avere, non in entrambi.",
"negative": "Gli importi non possono essere negativi."
},
"vat": {
"code-required": "Ogni riga IVA ha un codice IVA."
},
"posting": {
"account-missing": "Manca un conto per contabilizzare il documento: controlla causali e piano dei conti."
},
"template": {
"missing": "Manca la causale contabile per questo documento: aggiorna le tabelle di base.",
"code": "Il codice della causale non è valido.",
"duplicate": "Esiste già una causale con questo codice.",
"used": "La causale è usata da registrazioni: disattivala invece di eliminarla."
},
"account": {
"used": "Il conto ha movimenti: disattivalo invece di eliminarlo.",
"has-children": "Il conto ha sottoconti: elimina prima quelli.",
"parent": "Il conto padre non esiste: crea prima il mastro o il conto.",
"duplicate": "Esiste già un conto con questo codice.",
"code": "Il codice del conto non è valido: usa mastro, conto e sottoconto separati da punti."
},
"bank": {
"account-missing": "Il conto bancario non ha un conto contabile e manca il conto banca predefinito."
}
},
"vat": {
"settlement": {
"confirmed": "La liquidazione è confermata: riaprila per ricalcolarla.",
"previous": "Conferma prima la liquidazione del periodo precedente.",
"later": "C'è una liquidazione successiva confermata: riapri prima quella."
},
"register": {
"print-order": "La stampa definitiva riprende dal giorno dopo l'ultima stampata."
}
},
"tax": {
"payment": {
"paid": "Il versamento è già pagato: annulla prima il pagamento."
}
},
"withholding": {
"not-due": "La ritenuta non è ancora da versare: registra prima il pagamento della fattura."
}
}
+4 -1
View File
@@ -89,8 +89,12 @@
"_": "Contabilità",
"Journal": "Prima nota",
"Accounts": "Piano dei conti",
"Templates": "Causali",
"Parties": "Partitari",
"VatRegisters": "Registri IVA",
"VatSettlement": "Liquidazione IVA",
"Withholdings": "Ritenute e F24",
"StampDuty": "Bollo virtuale",
"Statements": "Bilancio"
},
"Finance": {
@@ -104,7 +108,6 @@
"_": "Fatt. elettronica",
"Dashboard": "Cruscotto SDI",
"Channels": "Canali di trasmissione",
"StampDuty": "Bollo virtuale",
"IntentDeclarations": "Dichiarazioni d'intento"
},
"Assets": {
+6 -4
View File
@@ -69,14 +69,16 @@ public static class MenuCatalog
Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", null,
("Shell.Menu.Inventory.Stock", "giacenze"), ("Shell.Menu.Inventory.Entries", "movimenti"), ("Shell.Menu.Inventory.StockTake", "inventario"),
("Shell.Menu.Inventory.Reorder", "riordino")),
Area("Shell.Menu.Ledger", "book", "/contabilita", ModuleCodes.Accounting, "ledger.entry.read", "M7",
("Shell.Menu.Ledger.Journal", "prima-nota"), ("Shell.Menu.Ledger.Accounts", "piano-dei-conti"), ("Shell.Menu.Ledger.VatRegisters", "registri-iva"),
("Shell.Menu.Ledger.VatSettlement", "liquidazione-iva"), ("Shell.Menu.Ledger.Statements", "bilancio")),
Area("Shell.Menu.Ledger", "book", "/contabilita", ModuleCodes.Accounting, "ledger.entry.read", null,
("Shell.Menu.Ledger.Journal", "prima-nota"), ("Shell.Menu.Ledger.Accounts", "piano-dei-conti"), ("Shell.Menu.Ledger.Templates", "causali"),
("Shell.Menu.Ledger.Parties", "partitari"), ("Shell.Menu.Ledger.VatRegisters", "registri-iva"),
("Shell.Menu.Ledger.VatSettlement", "liquidazione-iva"), ("Shell.Menu.Ledger.Withholdings", "ritenute"),
("Shell.Menu.Ledger.StampDuty", "bollo"), ("Shell.Menu.Ledger.Statements", "bilancio")),
Area("Shell.Menu.Finance", "coins", "/scadenzario", ModuleCodes.Finance, "finance.schedule.read", "M9",
("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Dunning", "solleciti"),
("Shell.Menu.Finance.Reconciliation", "riconciliazione")),
Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M8",
("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"), ("Shell.Menu.EInvoicing.StampDuty", "bollo"),
("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"),
("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento")),
Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10",
("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")),
+14
View File
@@ -422,3 +422,17 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
.kh-cellpick .f > label:empty { display: none; }
.kh-plainlist { margin: 4px 0 0; padding-left: 18px; }
.kh-pendingself { margin-bottom: 12px; }
/* Ledger (M7): chart and detail side by side, levels of the chart, the summary of a settlement, grids of amounts. */
.kh-ledger-split { display: grid; grid-template-columns: minmax(0, 4fr) minmax(0, 7fr); gap: 12px; align-items: start; }
.kh-ledger-side { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
.kh-ledger-tree { max-height: 68vh; overflow: auto; }
.kh-ledger-tree .lvl1, .kh-ledger-tree .lvl2 { font-weight: 600; }
.kh-ledger-tree .lvl1 { color: var(--kh-accent); }
.kh-ledger-two { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 12px; align-items: start; }
.kh-ledger-checks { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; color: var(--kh-ok); }
.kh-ledger-checks .no { color: var(--kh-warn); }
.kh-ledger-filters .f { margin: 0; }
.grid tr.err td { background: var(--kh-err-soft); }
.grid tfoot td { border-top: 1px solid var(--kh-border); }
@media (max-width: 1100px) { .kh-ledger-split, .kh-ledger-two { grid-template-columns: minmax(0, 1fr); } }
@@ -0,0 +1,299 @@
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tax;
namespace Khaemhat.Core.Tests.Accounting;
/// <summary>
/// The pure rules of the ledger (issues #62-#65): the checks of an entry, the account codes, the posting of each kind of
/// document, the VAT settlement with pro rata, carried amounts, interest and minimum, and the December advance.
/// </summary>
[TestClass]
public sealed class LedgerRulesTests
{
private const long Customer = 1;
private const long Supplier = 2;
private const long Revenue = 3;
private const long OtherRevenue = 4;
private const long Cost = 5;
private const long SalesVat = 6;
private const long PurchaseVat = 7;
private const long Stamp = 8;
private const long Fund = 9;
private static readonly PostingAccounts SaleAccounts = new(Customer, Revenue, SalesVat, PurchaseVat, Stamp, Fund);
private static readonly PostingAccounts PurchaseAccounts = new(Supplier, Cost, SalesVat, PurchaseVat, Stamp);
private static readonly Dictionary<long, AccountRule> Accounts = new()
{
[Customer] = new(Customer, Postable: true, Disabled: false, SubLedger: true),
[Revenue] = new(Revenue, Postable: true, Disabled: false, SubLedger: false),
[Cost] = new(Cost, Postable: false, Disabled: false, SubLedger: false),
[SalesVat] = new(SalesVat, Postable: true, Disabled: true, SubLedger: false),
};
[TestMethod]
public void Validator_AcceptsABalancedEntry_AndAcceptsUnbalancedDrafts()
{
EntryLineCheck[] lines = [new(Customer, 10, 122m, 0m), new(Revenue, null, 0m, 122m)];
Assert.IsEmpty(JournalEntryValidator.Check("Fattura", lines, 0, false, Accounts, posting: true));
EntryLineCheck[] half = [new(Revenue, null, 0m, 100m)];
Assert.IsEmpty(JournalEntryValidator.Check("Bozza", half, 0, false, Accounts, posting: false));
CollectionAssert.Contains(JournalEntryValidator.Check("Bozza", half, 0, false, Accounts, posting: true).ToList(), "Lines:" + LedgerErrors.Unbalanced);
Assert.AreEqual(-100m, JournalEntryValidator.Difference(half));
}
[TestMethod]
public void Validator_ReportsEveryProblemOfTheLines()
{
EntryLineCheck[] lines =
[
new(null, null, 10m, 0m),
new(99, null, 10m, 0m),
new(Cost, null, 10m, 0m),
new(SalesVat, null, 0m, 10m),
new(Customer, null, 0m, 10m),
new(Revenue, null, -5m, 0m),
new(Revenue, null, 5m, 5m),
new(Revenue, null, 0m, 0m),
];
var errors = JournalEntryValidator.Check(" ", lines, 1, false, Accounts, posting: true);
CollectionAssert.IsSubsetOf(
new[]
{
"Description:" + LedgerErrors.DescriptionRequired,
"Lines.0.AccountId:" + LedgerErrors.AccountRequired,
"Lines.1.AccountId:" + LedgerErrors.AccountMissing,
"Lines.2.AccountId:" + LedgerErrors.AccountNotPostable,
"Lines.3.AccountId:" + LedgerErrors.AccountDisabled,
"Lines.4.PartyId:" + LedgerErrors.PartyRequired,
"Lines.5.Debit:" + LedgerErrors.Negative,
"Lines.6.Credit:" + LedgerErrors.BothSides,
"Lines.7.Debit:" + LedgerErrors.AmountRequired,
"VatRegisterId:" + LedgerErrors.VatRegisterRequired,
},
errors.ToList());
}
[TestMethod]
[DataRow("05", 1)]
[DataRow("05.01", 2)]
[DataRow("05.01.001", 3)]
[DataRow("05.01.001.1", 0)]
[DataRow("05..001", 0)]
[DataRow("", 0)]
[DataRow("05.0-1", 0)]
public void AccountCodes_HaveUpToThreeLevels(string code, int level) => Assert.AreEqual(level, AccountCodes.LevelOf(code));
[TestMethod]
public void AccountCodes_KnowTheirParent()
{
Assert.AreEqual("05.01", AccountCodes.ParentOf("05.01.001"));
Assert.AreEqual("05", AccountCodes.ParentOf("05.01"));
Assert.IsNull(AccountCodes.ParentOf("05"));
}
[TestMethod]
public void Sale_DebitsTheCustomer_CreditsRevenuesStampAndVat()
{
var input = new PostingInput(
PostingKind.Sale, false, 10,
[new PostingLineInput(Revenue, 600m), new PostingLineInput(OtherRevenue, 400m), new PostingLineInput(Revenue, 0m)],
[Tax(1000m, 22m, 220m)],
Total: 1222m, StampDuty: 2m);
var result = PostingEngine.Post(input, SaleAccounts);
Assert.AreEqual(result.Debit, result.Credit);
Assert.AreEqual(1222m, Line(result, PostingRole.Customer).Debit);
Assert.AreEqual(10L, Line(result, PostingRole.Customer).PartyId);
Assert.AreEqual(600m, result.Lines.Single(l => l.AccountId == Revenue).Credit);
Assert.AreEqual(400m, result.Lines.Single(l => l.AccountId == OtherRevenue).Credit);
Assert.AreEqual(2m, Line(result, PostingRole.StampDuty).Credit);
Assert.AreEqual(220m, Line(result, PostingRole.SalesVat).Credit);
Assert.AreEqual(VatRegisterKind.Sales, result.Vat.Single().RegisterKind);
}
[TestMethod]
public void Sale_GivesTheFooterDiscountToTheLargestLine()
{
// Lines for 1000, a footer discount of 10: the summary says 990.
var input = new PostingInput(PostingKind.Sale, false, 10,
[new PostingLineInput(Revenue, 700m), new PostingLineInput(OtherRevenue, 300m)], [Tax(990m, 22m, 217.8m)], Total: 1207.8m);
var result = PostingEngine.Post(input, SaleAccounts);
Assert.AreEqual(result.Debit, result.Credit);
Assert.AreEqual(690m, result.Lines.Single(l => l.AccountId == Revenue).Credit);
Assert.AreEqual(300m, result.Lines.Single(l => l.AccountId == OtherRevenue).Credit);
}
[TestMethod]
public void Sale_WithSplitPayment_TakesTheVatBackFromTheCustomer()
{
var input = new PostingInput(PostingKind.Sale, false, 10, [new PostingLineInput(Revenue, 1000m)],
[Tax(1000m, 22m, 220m) with { Exigibility = TaxExigibility.SplitPayment }], Total: 1220m);
var result = PostingEngine.Post(input, SaleAccounts);
Assert.AreEqual(result.Debit, result.Credit);
var customer = result.Lines.Where(l => l.Role == PostingRole.Customer).Sum(l => l.Debit - l.Credit);
Assert.AreEqual(1000m, customer, "The public body pays the taxable amount only.");
Assert.AreEqual(220m, Line(result, PostingRole.SplitPaymentVat).Debit);
}
[TestMethod]
public void Fee_CreditsTheSocialSecurityCharged()
{
var input = new PostingInput(PostingKind.Sale, false, 10, [new PostingLineInput(Revenue, 1000m)], [Tax(1040m, 22m, 228.8m)],
Total: 1268.8m, SocialSecurity: 40m);
var result = PostingEngine.Post(input, SaleAccounts);
Assert.AreEqual(result.Debit, result.Credit);
Assert.AreEqual(40m, Line(result, PostingRole.SocialSecurity).Credit);
Assert.AreEqual(1000m, Line(result, PostingRole.Revenue).Credit);
}
[TestMethod]
public void Purchase_PutsTheNonDeductibleVatOnTheCost()
{
var input = new PostingInput(PostingKind.Purchase, false, 20, [new PostingLineInput(Cost, 500m, TaxCodeId: 77)],
[new PostingTaxInput(77, 22m, null, TaxExigibility.Immediate, 500m, 110m, 66m)], Total: 610m);
var result = PostingEngine.Post(input, PurchaseAccounts);
Assert.AreEqual(result.Debit, result.Credit);
Assert.AreEqual(610m, Line(result, PostingRole.Supplier).Credit);
Assert.AreEqual(566m, Line(result, PostingRole.Cost).Debit);
Assert.AreEqual(44m, Line(result, PostingRole.PurchaseVat).Debit);
Assert.AreEqual(VatRegisterKind.Purchases, result.Vat.Single().RegisterKind);
}
[TestMethod]
public void CreditNote_ReversesEverySide_AndTheVat()
{
var input = new PostingInput(PostingKind.Sale, true, 10, [new PostingLineInput(Revenue, 100m)], [Tax(100m, 22m, 22m)], Total: 122m);
var result = PostingEngine.Post(input, SaleAccounts);
Assert.AreEqual(result.Debit, result.Credit);
Assert.AreEqual(122m, Line(result, PostingRole.Customer).Credit);
Assert.AreEqual(100m, Line(result, PostingRole.Revenue).Debit);
Assert.AreEqual(22m, Line(result, PostingRole.SalesVat).Debit);
Assert.AreEqual(-22m, result.Vat.Single().Tax.Tax);
Assert.AreEqual(-100m, result.Vat.Single().Tax.Taxable);
}
[TestMethod]
public void SelfInvoice_WritesTheVatInBothRegisters()
{
var input = new PostingInput(PostingKind.SelfInvoice, false, null, [], [Tax(1000m, 22m, 220m)], Total: 220m);
var result = PostingEngine.Post(input, PurchaseAccounts);
Assert.AreEqual(result.Debit, result.Credit);
Assert.AreEqual(220m, Line(result, PostingRole.PurchaseVat).Debit);
Assert.AreEqual(220m, Line(result, PostingRole.SalesVat).Credit);
CollectionAssert.AreEquivalent(new[] { VatRegisterKind.Sales, VatRegisterKind.Purchases }, result.Vat.Select(v => v.RegisterKind).ToList());
}
[TestMethod]
public void Posting_WithoutAnAccount_SaysWhichOne()
{
var input = new PostingInput(PostingKind.Sale, false, 10, [new PostingLineInput(Revenue, 100m)], [Tax(100m, 22m, 22m)], Total: 122m);
var missing = Assert.ThrowsExactly<PostingAccountMissingException>(() => PostingEngine.Post(input, SaleAccounts with { SalesVat = null }));
Assert.AreEqual(PostingRole.SalesVat, missing.Role);
}
[TestMethod]
public void Settlement_PaysTheDifference_WithQuarterlyInterest()
{
VatRegisterTotals[] registers =
[
new(1, VatRegisterKind.Sales, 10, 20000m, 4400m, 0m, 0m),
new(2, VatRegisterKind.Receipts, 3, 1000m, 220m, 0m, 0m),
new(3, VatRegisterKind.Purchases, 8, 10000m, 2200m, 200m, 0m),
];
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(PreviousCredit: 300m, InterestPercent: 1m, MinimumPayment: 25.82m));
Assert.AreEqual(4620m, result.SalesTax);
Assert.AreEqual(2000m, result.PurchaseTax);
Assert.AreEqual(200m, result.NonDeductibleTax);
Assert.AreEqual(2320m, result.Balance); // 4620 - 2000 - 300
Assert.AreEqual(23.2m, result.Interest);
Assert.AreEqual(2343.2m, result.AmountDue);
Assert.AreEqual(0m, result.CreditCarried);
}
[TestMethod]
public void Settlement_InCredit_CarriesTheCredit()
{
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 1, 1000m, 220m, 0m, 0m), new(3, VatRegisterKind.Purchases, 1, 5000m, 1100m, 0m, 0m)];
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(InterestPercent: 1m, MinimumPayment: 25.82m));
Assert.AreEqual(0m, result.AmountDue);
Assert.AreEqual(880m, result.CreditCarried);
Assert.AreEqual(0m, result.Interest);
}
[TestMethod]
public void Settlement_BelowTheMinimum_CarriesTheDebit()
{
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 1, 100m, 22m, 0m, 0m)];
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(MinimumPayment: 25.82m));
Assert.AreEqual(0m, result.AmountDue);
Assert.AreEqual(22m, result.DebitCarried);
var next = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(PreviousDebit: result.DebitCarried, MinimumPayment: 25.82m));
Assert.AreEqual(44m, next.AmountDue);
}
[TestMethod]
public void Settlement_LeavesTheDeferredVatForLater_AndDeductsTheAdvance()
{
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 2, 2000m, 440m, 0m, 220m)];
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(AdvancePaid: 100m));
Assert.AreEqual(220m, result.SalesTax);
Assert.AreEqual(220m, result.DeferredTax);
Assert.AreEqual(120m, result.AmountDue);
}
[TestMethod]
public void ProRata_RoundsUp_AndLimitsTheDeduction()
{
Assert.AreEqual(100m, ProRataCalculator.Percent(1000m, 0m));
Assert.AreEqual(67m, ProRataCalculator.Percent(2000m, 1000m)); // 66.67 rounded up
Assert.AreEqual(670m, ProRataCalculator.Deductible(1000m, 67m));
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 1, 10000m, 2200m, 0m, 0m), new(3, VatRegisterKind.Purchases, 1, 5000m, 1000m, 0m, 0m)];
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(ProRataPercent: 67m));
Assert.AreEqual(670m, result.PurchaseTax);
Assert.AreEqual(330m, result.NonDeductibleTax);
Assert.AreEqual(1530m, result.AmountDue);
}
[TestMethod]
public void Advance_IsEightyEightPercent_AndNothingBelowTheMinimum()
{
Assert.AreEqual(880m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Historical, 1000m, 88m, 103.29m));
Assert.AreEqual(440m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Forecast, 500m, 88m, 103.29m));
Assert.AreEqual(500m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Actual, 500m, 88m, 103.29m));
Assert.AreEqual(0m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Historical, 100m, 88m, 103.29m));
Assert.AreEqual(0m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Actual, -10m, 88m, 103.29m));
}
private static PostingTaxInput Tax(decimal taxable, decimal rate, decimal tax) => new(1, rate, null, TaxExigibility.Immediate, taxable, tax, 0m);
private static PostedLine Line(PostingResult result, PostingRole role) => result.Lines.Single(l => l.Role == role);
}
@@ -82,6 +82,8 @@ public sealed class MappingTests
"purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines",
"document_links", "document_tax_summaries", "document_installments",
"inventory_entries", "inventory_entry_lines", "item_balances", "stock_takes", "stock_take_lines",
"gl_accounts", "vat_registers", "gl_journal_templates", "gl_journal_template_lines", "gl_entries", "gl_entry_lines", "gl_entry_vat",
"gl_open_items", "gl_recurring_entries", "vat_settlements", "vat_settlement_lines", "tax_payments", "withholdings", "vat_register_prints",
];
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
}
@@ -0,0 +1,158 @@
using System.Text;
using System.Xml.Linq;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>
/// The Italian ledger (issues #62, #65, #66): the model chart of accounts and its templates, the F24 codes and due dates
/// of VAT, withholdings and stamp duty, the LIPE file and the F24 data file.
/// </summary>
[TestClass]
public sealed class ItalianLedgerTests
{
private static readonly ItalyFiscalPack Pack = new();
private static readonly ILedgerTemplate Template = Pack.Require<ILedgerTemplate>();
private static readonly IVatSettlementRules Rules = Pack.Require<IVatSettlementRules>();
[TestMethod]
public void Chart_HasValidCodes_WithTheirParentsFirst()
{
var seen = new HashSet<string>(StringComparer.Ordinal);
Assert.IsGreaterThan(100, Template.Accounts.Count);
foreach (var account in Template.Accounts)
{
Assert.AreNotEqual(0, account.Level, account.Code);
Assert.IsTrue(seen.Add(account.Code), "Duplicate " + account.Code);
if (account.ParentCode is { } parent)
{
Assert.Contains(parent, seen, account.Code + " comes before its parent " + parent);
}
}
}
[TestMethod]
public void Templates_UseAccountsOfTheChart_AndTheRolesHaveSubAccounts()
{
var accounts = Template.Accounts.ToDictionary(a => a.Code, StringComparer.Ordinal);
var registers = Template.VatRegisters.Select(r => r.Code).ToHashSet(StringComparer.Ordinal);
foreach (var template in Template.JournalTemplates)
{
Assert.IsTrue(template.Reverses || template.Lines.Count > 0, template.Code + " proposes its lines (only the reversal copies them)");
if (template.VatRegisterCode is { } register)
{
Assert.Contains(register, registers, template.Code);
}
foreach (var line in template.Lines.Where(l => l.AccountCode is not null))
{
Assert.IsTrue(accounts.TryGetValue(line.AccountCode!, out var account), template.Code + " " + line.AccountCode);
Assert.AreEqual(3, account.Level, template.Code + " posts on a sub-account");
}
}
foreach (var role in Enum.GetValues<PostingRole>().Where(r => r != PostingRole.Account))
{
if (Template.AccountOf(role) is { } code)
{
Assert.AreEqual(3, accounts[code].Level, role.ToString());
}
}
Assert.IsTrue(accounts[ItalianLedgerTemplate.Customers].SubLedger);
Assert.IsTrue(accounts[ItalianLedgerTemplate.Suppliers].SubLedger);
var templates = Template.JournalTemplates.Select(t => t.Code).ToHashSet(StringComparer.Ordinal);
foreach (var posting in Template.DocumentPostings)
{
Assert.Contains(posting.JournalTemplateCode, templates, posting.DocumentTypeCode);
}
}
[TestMethod]
public void Templates_ForTheSettlementAndThePayments_Exist()
{
var codes = Template.JournalTemplates.Select(t => t.Code).ToList();
CollectionAssert.IsSubsetOf(new[] { "FV", "NCV", "FA", "NCA", "LIQ", "F24", "RIT", "RITS" }, codes);
}
[TestMethod]
[DataRow(VatPeriodicity.Monthly, 1, "6001", null)]
[DataRow(VatPeriodicity.Monthly, 12, "6012", null)]
[DataRow(VatPeriodicity.Quarterly, 1, "6031", null)]
[DataRow(VatPeriodicity.Quarterly, 3, "6033", null)]
[DataRow(VatPeriodicity.Quarterly, 4, "6099", "0101")]
public void VatPaymentCodes(VatPeriodicity periodicity, int number, string code, string? period)
{
var tax = TaxPeriod.Of(2026, number, periodicity);
Assert.AreEqual(code, Rules.PaymentCode(tax));
Assert.AreEqual(period, Rules.PaymentPeriod(tax));
}
[TestMethod]
public void TheRules_HaveTheItalianAmounts()
{
Assert.AreEqual(25.82m, Rules.MinimumPayment);
Assert.AreEqual(88m, Rules.AdvancePercent);
Assert.AreEqual(103.29m, Rules.AdvanceMinimum);
}
[TestMethod]
public void DueDates_MoveToTheNextWorkingDay_AndAugustToThe20th()
{
// The withholdings of March 2026 by 16 April (a Thursday); of July by 20 August.
Assert.AreEqual(new DateOnly(2026, 4, 16), Rules.WithholdingDue(2026, 3));
Assert.AreEqual(new DateOnly(2026, 8, 20), Rules.WithholdingDue(2026, 7));
// 16 May 2026 is a Saturday: Monday 18.
Assert.AreEqual(new DateOnly(2026, 5, 18), Rules.WithholdingDue(2026, 4));
// The stamp duty of the second quarter by 30 September, of the first by 31 May (a Sunday: 1 June).
Assert.AreEqual(new DateOnly(2026, 9, 30), Rules.StampDutyDue(2026, 2));
Assert.AreEqual(new DateOnly(2026, 6, 1), Rules.StampDutyDue(2026, 1));
// The advance by 27 December (a Sunday in 2026: Monday 28).
Assert.AreEqual(new DateOnly(2026, 12, 28), Rules.AdvanceDue(2026));
}
[TestMethod]
public void Lipe_WritesOneModulePerPeriod_WithCommaAmounts()
{
var data = new PeriodicVatReturn(2026, 3, "01234567890", "01234567890", null, null, new DateOnly(2026, 11, 13),
[
new PeriodicVatReturnModule(TaxPeriod.Of(2026, 3, VatPeriodicity.Quarterly), 20000m, 10000m, 4400m, 2200m, 0m, 300m, 19m, 0m, 1919m),
]);
var writer = Pack.Require<IPeriodicVatReturnWriter>();
var xml = XDocument.Parse(Encoding.UTF8.GetString(writer.Write(data)));
XNamespace iv = LipeWriter.Namespace;
var module = xml.Descendants(iv + "Modulo").Single();
Assert.AreEqual("IT01234567890_LI_2026_T3.xml", writer.FileName(data));
Assert.AreEqual("IVP18", xml.Descendants(iv + "CodiceFornitura").Single().Value);
Assert.AreEqual("3", module.Element(iv + "Trimestre")!.Value);
Assert.AreEqual("4400,00", module.Element(iv + "IvaEsigibile")!.Value);
Assert.AreEqual("2200,00", module.Element(iv + "IvaDovuta")!.Value);
Assert.AreEqual("300,00", module.Element(iv + "CreditoPeriodoPrecedente")!.Value);
Assert.AreEqual("1919,00", module.Element(iv + "ImportoDaVersare")!.Value);
Assert.IsNull(module.Element(iv + "Acconto"), "Zero amounts are left out.");
Assert.AreEqual("1234,50", LipeWriter.FormatAmount(1234.5m));
}
[TestMethod]
public void F24_ExportsTheErarioLines_AndTheBalance()
{
var form = new TaxPaymentForm(new DateOnly(2026, 11, 16), "01234567890", "Demo; S.r.l.",
[
new TaxPaymentFormLine("6033", null, 2026, 1919m, 0m, "IVA terzo trimestre"),
new TaxPaymentFormLine("1040", "10", 2026, 400m, 0m, "Ritenute lavoro autonomo"),
]);
var exporter = Pack.Require<ITaxPaymentFormExporter>();
var lines = Encoding.UTF8.GetString(exporter.Export(form)).Split('\n', StringSplitOptions.RemoveEmptyEntries);
Assert.AreEqual("F24;16/11/2026;01234567890;Demo, S.r.l.", lines[0]);
Assert.AreEqual("ER;6033;;2026;1919,00;;IVA terzo trimestre", lines[2]);
Assert.AreEqual("ER;1040;10;2026;400,00;;Ritenute lavoro autonomo", lines[3]);
Assert.AreEqual("Saldo;;;;2319,00;;", lines[4]);
Assert.AreEqual(2319m, form.Balance);
}
}
@@ -0,0 +1,178 @@
using System.Globalization;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Application.Seeding;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tax;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Ledger;
/// <summary>
/// The demo accounting and the ledger flows on a real instance (issues #63-#68): the demo documents posted and balanced,
/// the settlements of the periods ended confirmed and checked by hand against the VAT registers, the withholding of the
/// professional due, the recurring rent, an entry typed, posted, reversed and made final.
/// </summary>
[TestClass]
public sealed class DemoLedgerTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task DemoSeed_PostsTheYear_AndSettlesThePeriodsEnded()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await SeedAsync(app.Services, company);
var today = DateOnly.FromDateTime(DateTime.Now);
var queries = app.Services.GetRequiredService<LedgerQueryService>();
var vat = app.Services.GetRequiredService<VatService>();
var journal = app.Services.GetRequiredService<JournalEntryService>();
// Every document of the year is in the journal, and the trial balance balances.
var (entries, total) = await journal.ListAsync(Root, company, new EntryFilter(Limit: 500));
Assert.IsGreaterThan(10, total);
Assert.IsTrue(entries.Any(e => e.Entry.Source == GlEntrySource.Document));
var rents = Enumerable.Range(2, today.Month - 1).Count(m => new DateOnly(today.Year, m, 5) <= today);
Assert.AreEqual(rents, entries.Count(e => e.Entry.Source == GlEntrySource.Recurring), "The rent of every month after January.");
var balance = await queries.TrialBalanceAsync(Root, company, new DateOnly(today.Year, 1, 1), today);
Assert.IsTrue(balance.Balanced, $"Debit {balance.TotalDebit} credit {balance.TotalCredit}");
// The settlements of the periods ended are confirmed, in order.
var settlements = await vat.SettlementsAsync(Root, company, today.Year);
Assert.IsNotEmpty(settlements);
Assert.IsTrue(settlements.All(s => s.Status == VatSettlementStatus.Confirmed));
foreach (var s in settlements.OrderBy(s => s.Number))
{
TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture,
$"{s.Number}/{s.Year}: sales {s.SalesTax:0.00} purchases {s.PurchaseTax:0.00} credit in {s.PreviousCredit:0.00} due {s.AmountDue:0.00} credit out {s.CreditCarried:0.00}"));
}
var first = settlements.Where(s => s.SalesTax != 0m || s.PurchaseTax != 0m).OrderBy(s => s.Number).First();
// The first settlement with VAT checked by hand against the registers.
var registers = await app.Services.GetRequiredService<LedgerService>().RegistersAsync(Root, company);
decimal sales = 0m, deductible = 0m;
foreach (var register in registers)
{
var view = await vat.RegisterAsync(Root, company, register.Id, first.StartDate, first.EndDate);
var due = view.Rows.Where(r => r.Exigibility == TaxExigibility.Immediate).Sum(r => r.Tax);
if (register.Kind == VatRegisterKind.Purchases)
{
deductible += due - view.Rows.Sum(r => r.NonDeductibleTax);
}
else
{
sales += due;
}
}
deductible = ProRataCalculator.Deductible(deductible, first.ProRataPercent);
var difference = sales - deductible - first.PreviousCredit + first.PreviousDebit;
var interest = difference > 0m ? Math.Round(difference * first.InterestPercent / 100m, 2, MidpointRounding.AwayFromZero) : 0m;
var expected = difference + interest >= 25.82m ? difference + interest : 0m;
Report(first, sales, deductible, interest, expected);
Assert.AreEqual(sales, first.SalesTax);
Assert.AreEqual(deductible, first.PurchaseTax);
Assert.AreEqual(expected, first.AmountDue);
Assert.AreEqual(difference < 0m ? -difference : 0m, first.CreditCarried);
if (first.AmountDue > 0m)
{
Assert.IsNotNull(first.GlEntryId);
Assert.IsNotNull(first.TaxPaymentId);
}
// The professional's invoice is paid: its withholding is due (or already paid with an F24).
var withholdings = await app.Services.GetRequiredService<TaxService>().WithholdingsAsync(Root, company, today.Year, WithholdingDirection.Operated);
Assert.IsNotEmpty(withholdings);
Assert.IsTrue(withholdings.All(w => w.Withholding.Status is WithholdingStatus.Due or WithholdingStatus.Paid));
// Run again, nothing changes.
var seeder = app.Services.GetRequiredService<DemoLedgerSeeder>();
await seeder.SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true));
Assert.AreEqual(total, (await journal.ListAsync(Root, company, new EntryFilter(Limit: 1))).Total);
await app.StopAsync();
}
}
[TestMethod]
public async Task AnEntry_IsTypedPostedReversedAndMadeFinal()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Base);
var ledger = app.Services.GetRequiredService<LedgerService>();
var journal = app.Services.GetRequiredService<JournalEntryService>();
var queries = app.Services.GetRequiredService<LedgerQueryService>();
var accounts = (await ledger.AccountsAsync(Root, company)).ToDictionary(a => a.Code, StringComparer.Ordinal);
var rent = accounts[DemoLedgerSeeder.RentAccount].Id;
var bank = accounts[DemoLedgerSeeder.BankAccount].Id;
var day = new DateOnly(DateTime.Now.Year, 1, 10);
// An unbalanced entry is kept as a draft, not posted.
EntryLineDraft[] half = [new(rent, null, null, 500m, 0m), new(bank, null, null, 0m, 400m)];
var draft = await journal.SaveAsync(Root, company, new EntryInput(null, day, "Affitto", half));
Assert.AreEqual(GlEntryStatus.Draft, draft.Entry.Status);
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(
() => journal.SaveAsync(Root, company, new EntryInput(draft.Entry.Id, day, "Affitto", half) { Post = true }));
Assert.Contains("Lines:" + LedgerErrors.Unbalanced, refused.Errors);
// Balanced, it is posted with its number; the rent account moves.
EntryLineDraft[] lines = [new(rent, null, null, 500m, 0m), new(bank, null, null, 0m, 500m)];
var posted = await journal.SaveAsync(Root, company, new EntryInput(draft.Entry.Id, day, "Affitto", lines) { Post = true });
Assert.AreEqual(GlEntryStatus.Posted, posted.Entry.Status);
Assert.IsNotNull(posted.Entry.EntryNumber);
var page = await queries.MovementsAsync(Root, company, new LedgerFilter(rent, null, day.AddDays(-9), day.AddDays(20)));
Assert.AreEqual(500m, page.Closing);
// The reversal cancels it, and a second reversal is refused.
var reversal = await journal.ReverseAsync(Root, company, posted.Entry.Id, day.AddDays(1));
Assert.AreEqual(GlEntrySource.Reversal, reversal.Entry.Source);
page = await queries.MovementsAsync(Root, company, new LedgerFilter(rent, null, day.AddDays(-9), day.AddDays(20)));
Assert.AreEqual(0m, page.Closing);
Assert.AreEqual(2, page.TotalCount);
var again = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => journal.ReverseAsync(Root, company, posted.Entry.Id, day.AddDays(2)));
Assert.IsTrue(again.Errors.Any(e => e.EndsWith(LedgerErrors.AlreadyReversed, StringComparison.Ordinal)));
// Made final, the entries get their journal number and cannot be deleted.
Assert.AreEqual(2, await journal.FinalizeAsync(Root, company, day.AddDays(1)));
var final = await journal.GetAsync(Root, company, posted.Entry.Id);
Assert.AreEqual(GlEntryStatus.Final, final!.Entry.Status);
var locked = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => journal.DeleteAsync(Root, company, posted.Entry.Id));
Assert.IsTrue(locked.Errors.Any(e => e.EndsWith(LedgerErrors.Final, StringComparison.Ordinal)));
await app.StopAsync();
}
}
[TestMethod]
[DataRow("2026-01-31", RecurrenceFrequency.Monthly, "2026-02-28")]
[DataRow("2026-02-28", RecurrenceFrequency.Monthly, "2026-03-31")]
[DataRow("2026-01-05", RecurrenceFrequency.Monthly, "2026-02-05")]
[DataRow("2026-01-15", RecurrenceFrequency.Quarterly, "2026-04-15")]
[DataRow("2026-03-31", RecurrenceFrequency.HalfYearly, "2026-09-30")]
[DataRow("2026-06-10", RecurrenceFrequency.Yearly, "2027-06-10")]
public void Recurring_NextDate_KeepsTheEndOfTheMonth(string date, RecurrenceFrequency frequency, string next) =>
Assert.AreEqual(DateOnly.Parse(next, CultureInfo.InvariantCulture), RecurringEntryService.Next(DateOnly.Parse(date, CultureInfo.InvariantCulture), frequency));
private static async Task SeedAsync(IServiceProvider services, string company)
{
await services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, context);
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(company, context);
await services.GetRequiredService<DemoLedgerSeeder>().SeedAsync(company, context);
}
private void Report(VatSettlement settlement, decimal sales, decimal deductible, decimal interest, decimal expected) =>
TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture,
$"Settlement {settlement.Number}/{settlement.Year} ({settlement.Periodicity}, {settlement.StartDate:dd/MM}-{settlement.EndDate:dd/MM}): " +
$"sales VAT {sales:0.00}, deductible {deductible:0.00}, previous credit {settlement.PreviousCredit:0.00}, interest {interest:0.00}, " +
$"due {expected:0.00}; code {settlement.PaymentCode} by {settlement.DueDate:dd/MM/yyyy}"));
}
@@ -1,6 +1,10 @@
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using Khaemhat.Application.Preferences;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tax;
using Khaemhat.Web.Ledger;
using Khaemhat.Web.Shell;
namespace Khaemhat.Web.Tests.Shell;
@@ -94,6 +98,26 @@ public sealed partial class LocalizationRulesTests
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList());
}
[TestMethod]
public void LedgerEnumsAndErrors_HaveTexts()
{
var keys = new List<string>();
foreach (var type in new[]
{
typeof(GlEntryStatus), typeof(GlEntrySource), typeof(RecurrenceFrequency), typeof(AccountNature), typeof(AccountType),
typeof(JournalArea), typeof(PostingRole), typeof(AccountSide), typeof(VatRegisterKind), typeof(VatSettlementStatus),
typeof(WithholdingStatus), typeof(VatAdvanceMethod), typeof(VatPeriodicity), typeof(TaxExigibility),
})
{
keys.AddRange(Enum.GetValues(type).Cast<Enum>().Select(LedgerScreens.EnumKey));
}
keys.AddRange(typeof(LedgerErrors).GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!));
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList());
}
[TestMethod]
public void TextFiles_AvoidCharactersGiteaFlagsAsAmbiguous()
{
@@ -271,6 +295,6 @@ public sealed partial class LocalizationRulesTests
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
private static partial Regex EntityPattern();
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport)\\.[A-Za-z0-9_.]+)\"")]
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport|Ledger)\\.[A-Za-z0-9_.]+)\"")]
private static partial Regex KeyPattern();
}