diff --git a/CHANGELOG.md b/CHANGELOG.md index b291c48..ca5e538 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index 94d8181..ae039ba 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -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` + diff --git a/docs/STATUS.md b/docs/STATUS.md index 8ff9c89..18e31f8 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -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. diff --git a/docs/adr/0036-contabilita-generale.md b/docs/adr/0036-contabilita-generale.md new file mode 100644 index 0000000..e2c7539 --- /dev/null +++ b/docs/adr/0036-contabilita-generale.md @@ -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. diff --git a/docs/adr/0037-contabilizzazione-e-iva.md b/docs/adr/0037-contabilizzazione-e-iva.md new file mode 100644 index 0000000..89150fb --- /dev/null +++ b/docs/adr/0037-contabilizzazione-e-iva.md @@ -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). diff --git a/docs/wiki/Acquisti.md b/docs/wiki/Acquisti.md index c9ed07e..26c7b32 100644 --- a/docs/wiki/Acquisti.md +++ b/docs/wiki/Acquisti.md @@ -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 diff --git a/docs/wiki/Attivita-programmate.md b/docs/wiki/Attivita-programmate.md index 1de2141..d14b60a 100644 --- a/docs/wiki/Attivita-programmate.md +++ b/docs/wiki/Attivita-programmate.md @@ -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, diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index b30a694..28f1452 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -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. | diff --git a/docs/wiki/Contabilita.md b/docs/wiki/Contabilita.md index 0359188..f4ccabd 100644 --- a/docs/wiki/Contabilita.md +++ b/docs/wiki/Contabilita.md @@ -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/` 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) diff --git a/docs/wiki/Fiscalita-italiana.md b/docs/wiki/Fiscalita-italiana.md index 1451cab..fcbaf26 100644 --- a/docs/wiki/Fiscalita-italiana.md +++ b/docs/wiki/Fiscalita-italiana.md @@ -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_LI__T.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 diff --git a/docs/wiki/Guida-utente.md b/docs/wiki/Guida-utente.md index e5b266e..422acc8 100644 --- a/docs/wiki/Guida-utente.md +++ b/docs/wiki/Guida-utente.md @@ -1,6 +1,6 @@ # Guida all'uso -> **Stato:** completa per la versione 0.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) diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index fb78f92..d093f14 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -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) diff --git a/docs/wiki/IVA.md b/docs/wiki/IVA.md index c066306..6755df5 100644 --- a/docs/wiki/IVA.md +++ b/docs/wiki/IVA.md @@ -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_LI__T.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) diff --git a/docs/wiki/Import-Export.md b/docs/wiki/Import-Export.md index af9ccc5..4f5336d 100644 --- a/docs/wiki/Import-Export.md +++ b/docs/wiki/Import-Export.md @@ -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 diff --git a/docs/wiki/Magazzino.md b/docs/wiki/Magazzino.md index b7cf4f7..ba0e923 100644 --- a/docs/wiki/Magazzino.md +++ b/docs/wiki/Magazzino.md @@ -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 diff --git a/docs/wiki/Primi-passi.md b/docs/wiki/Primi-passi.md index 79d3883..51beda3 100644 --- a/docs/wiki/Primi-passi.md +++ b/docs/wiki/Primi-passi.md @@ -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 diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index ee677f5..099b967 100644 --- a/docs/wiki/Roadmap.md +++ b/docs/wiki/Roadmap.md @@ -13,7 +13,7 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo quando verrà deciso esplicitamente. -**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0). **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 | |---|---|---|---| diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md index da6f66c..a89de1e 100644 --- a/docs/wiki/Tabelle-azienda.md +++ b/docs/wiki/Tabelle-azienda.md @@ -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 diff --git a/docs/wiki/Vendite.md b/docs/wiki/Vendite.md index 88c1a20..6d2b9aa 100644 --- a/docs/wiki/Vendite.md +++ b/docs/wiki/Vendite.md @@ -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'è. diff --git a/docs/wiki/img/contabilita-bilancio.png b/docs/wiki/img/contabilita-bilancio.png new file mode 100644 index 0000000..d924586 Binary files /dev/null and b/docs/wiki/img/contabilita-bilancio.png differ diff --git a/docs/wiki/img/contabilita-causali.png b/docs/wiki/img/contabilita-causali.png new file mode 100644 index 0000000..6ad812d Binary files /dev/null and b/docs/wiki/img/contabilita-causali.png differ diff --git a/docs/wiki/img/contabilita-liquidazione-iva.png b/docs/wiki/img/contabilita-liquidazione-iva.png new file mode 100644 index 0000000..8e58bea Binary files /dev/null and b/docs/wiki/img/contabilita-liquidazione-iva.png differ diff --git a/docs/wiki/img/contabilita-partitari.png b/docs/wiki/img/contabilita-partitari.png new file mode 100644 index 0000000..01b378b Binary files /dev/null and b/docs/wiki/img/contabilita-partitari.png differ diff --git a/docs/wiki/img/contabilita-piano-dei-conti.png b/docs/wiki/img/contabilita-piano-dei-conti.png new file mode 100644 index 0000000..6beef59 Binary files /dev/null and b/docs/wiki/img/contabilita-piano-dei-conti.png differ diff --git a/docs/wiki/img/contabilita-prima-nota.png b/docs/wiki/img/contabilita-prima-nota.png new file mode 100644 index 0000000..86adb2d Binary files /dev/null and b/docs/wiki/img/contabilita-prima-nota.png differ diff --git a/docs/wiki/img/contabilita-registrazione-fattura.png b/docs/wiki/img/contabilita-registrazione-fattura.png new file mode 100644 index 0000000..28678e1 Binary files /dev/null and b/docs/wiki/img/contabilita-registrazione-fattura.png differ diff --git a/docs/wiki/img/contabilita-registri-iva.png b/docs/wiki/img/contabilita-registri-iva.png new file mode 100644 index 0000000..9ad5ff1 Binary files /dev/null and b/docs/wiki/img/contabilita-registri-iva.png differ diff --git a/docs/wiki/img/contabilita-ricorrenti.png b/docs/wiki/img/contabilita-ricorrenti.png new file mode 100644 index 0000000..a0f2f3f Binary files /dev/null and b/docs/wiki/img/contabilita-ricorrenti.png differ diff --git a/docs/wiki/img/contabilita-ritenute.png b/docs/wiki/img/contabilita-ritenute.png new file mode 100644 index 0000000..1ed6728 Binary files /dev/null and b/docs/wiki/img/contabilita-ritenute.png differ diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index 755b410..97c8cc2 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -115,6 +115,7 @@ public sealed partial class DocumentEngine private readonly CompanyFiscalContext _packs; private readonly TimeProvider _clock; private readonly ILogger _logger; + private readonly Ledger.LedgerPoster _ledger; /// Creates the engine. /// The units of work. @@ -124,10 +125,13 @@ public sealed partial class DocumentEngine /// The fiscal pack of each company (tax rounding, stamp duty). /// The clock. /// The log (section Documenti): confirmations, changes of state, deletions. + /// Posts the documents to the ledger (module ACCT). public DocumentEngine( IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock, - ILogger logger) + ILogger 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); } diff --git a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs index d66782f..516d01b 100644 --- a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs +++ b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs @@ -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; /// With a sub-ledger of customers or suppliers. /// Closed by the year end. /// Not used any more. +/// The line of the legal statements (voce CEE). +/// The line of the reclassified statements. 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); /// /// 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 } /// -/// The chart of accounts (piano-dei-conti): CSV, XLSX or khaemhat-coa.json. Until the ledger exists (M7) -/// the file is only checked; M7 writes the accounts this check accepts. +/// The chart of accounts (piano-dei-conti): CSV, XLSX or khaemhat-coa.json. The accounts the check +/// accepts are added; those that exist are updated when the options say so (M7, issue #62). /// -/// Checks the permission. -public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget +public sealed class ChartOfAccountsImportTarget : IImportTarget { /// The permission to change the chart of accounts. public const string WritePermission = "ledger.account.write"; + private readonly PermissionService _permissions; + private readonly IUnitOfWorkFactory? _factory; + + /// Creates the target. + /// Checks the permission. + /// The units of work, to write the accounts. + public ChartOfAccountsImportTarget(PermissionService permissions, IUnitOfWorkFactory? factory = null) + { + _permissions = permissions; + _factory = factory; + } + /// public string Key => "piano-dei-conti"; @@ -204,10 +218,10 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : public string ExportPermission => "ledger.account.read"; /// - public bool CanApply => false; + public bool CanApply => _factory is not null; /// - public bool CanExport => false; + public bool CanExport => _factory is not null; /// public IReadOnlyList Fields => ChartOfAccountsImportValidator.Fields; @@ -216,15 +230,46 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : public async Task> CheckAsync(ImportContext context, IReadOnlyList 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; } /// - public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => - throw new InvalidOperationException(ImportErrors.CheckOnly); + public async Task> ApplyAsync(ImportContext context, IReadOnlyList 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 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 })]; + } /// - public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => - Task.FromResult>>([]); + public async Task>> 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().ListAsync(Data.Querying.Query.For(), cancellationToken).ConfigureAwait(false)).Items + .OrderBy(a => a.Code, StringComparer.Ordinal); + return [.. accounts.Select(a => (IReadOnlyList) + [ + 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), + ])]; + } } diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index f4ef55c..2558e67 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -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; diff --git a/src/Khaemhat.Application/Ledger/JournalEntryService.cs b/src/Khaemhat.Application/Ledger/JournalEntryService.cs new file mode 100644 index 0000000..bf0fe2f --- /dev/null +++ b/src/Khaemhat.Application/Ledger/JournalEntryService.cs @@ -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; + +/// An entry with its lines and VAT lines. +/// The entry. +/// The lines. +/// The VAT lines. +/// The name of the customer or supplier of the entry. +public sealed record EntryView(GlEntry Entry, IReadOnlyList Lines, IReadOnlyList Vat, string? PartyName) +{ + /// Debit minus credit. + public decimal Difference => Lines.Sum(l => l.Debit - l.Credit); +} + +/// An entry as the journal lists it. +/// The entry. +/// The customer or supplier. +public sealed record EntryRow(GlEntry Entry, string? PartyName); + +/// What the journal list shows. +/// From this day. +/// Up to this day. +/// Only this state. +/// Only this template. +/// Text in the description or the document number. +/// The first row. +/// How many rows. +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); + +/// An entry typed in the journal. +/// The entry, for a change. +/// The date of registration. +/// The description. +/// The lines. +public sealed record EntryInput(long? Id, DateOnly EntryDate, string Description, IReadOnlyList Lines) +{ + /// The template. + public long? JournalTemplateId { get; init; } + + /// The date of competence. + public DateOnly? CompetenceDate { get; init; } + + /// The number of the document. + public string? DocumentNumber { get; init; } + + /// The date of the document. + public DateOnly? DocumentDate { get; init; } + + /// The customer or supplier. + public long? PartyId { get; init; } + + /// The VAT register. + public long? VatRegisterId { get; init; } + + /// The VAT date. + public DateOnly? VatDate { get; init; } + + /// The VAT lines. + public IReadOnlyList Vat { get; init; } = []; + + /// Notes. + public string? Notes { get; init; } + + /// Post it (it must balance) rather than keep it as a draft. + public bool Post { get; init; } +} + +/// A journal template with its lines, for the guided entry. +/// The template. +/// Its lines. +public sealed record TemplateView(JournalTemplate Template, IReadOnlyList Lines); + +/// +/// 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. +/// +public sealed class JournalEntryService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly FiscalYearService _fiscal; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal calendar. + /// The history. + /// The clock. + 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; + } + + /// The entries, the latest first. + /// Who reads. + /// The company. + /// The filter and the page. + /// Cancellation. + /// The page and the total. + public async Task<(IReadOnlyList 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(); + 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(); + 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); + } + + /// An entry with its lines. + /// Who reads. + /// The company. + /// The entry. + /// Cancellation. + /// The entry, or none. + public async Task 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); + } + + /// The journal templates with their lines, for the guided entry. + /// Who reads. + /// The company. + /// Cancellation. + /// The active templates, by code. + public async Task> 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().ListAsync(Query.For().Where(t => !t.Disabled).OrderBy(t => t.Code), cancellationToken) + .ConfigureAwait(false)).Items; + var lines = (await uow.Repository().ListAsync(Query.For().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items; + return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))]; + } + + /// + /// 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. + /// + /// Who writes. + /// The company. + /// The entry. + /// Cancellation. + /// The entry as saved. + public async Task 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? 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().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); + } + + /// Removes an entry that is not final and does not come from a document. + /// Who removes it. + /// The company. + /// The entry. + /// Cancellation. + /// A task. + 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().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().CountAsync(Query.For().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); + } + + /// + /// 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. + /// + /// Who reverses. + /// The company. + /// The entry. + /// The date of the reversal. + /// Cancellation. + /// The reversal. + public async Task 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().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); + } + + /// + /// 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. + /// + /// Who does it: needs ledger.entry.finalize. + /// The company. + /// The last day. + /// Cancellation. + /// How many entries became final. + public async Task 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().CountAsync( + Query.For().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().ListAsync( + Query.For().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().ListAsync(Query.For(), 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().UpdateAsync(year, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + return done; + } + + /// Posts a draft: it must balance. + /// Who posts. + /// The company. + /// The entry. + /// Cancellation. + /// The entry as posted. + public async Task 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); + } + + /// A line of an entry as a draft line. + /// The line. + /// The draft. + 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); + } + + /// A VAT line of an entry as a draft line. + /// The line. + /// The draft. + 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); + } + + /// Writes the reversal of an entry in the open transaction. + internal static async Task 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().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 ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().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> PartyNamesAsync(IUnitOfWork uow, IEnumerable 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().ListAsync(Query.For().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 errors, CancellationToken cancellationToken) + { + var year = await uow.Repository().FindAsync( + Query.For().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, + }; +} diff --git a/src/Khaemhat.Application/Ledger/LedgerPoster.cs b/src/Khaemhat.Application/Ledger/LedgerPoster.cs new file mode 100644 index 0000000..6292366 --- /dev/null +++ b/src/Khaemhat.Application/Ledger/LedgerPoster.cs @@ -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; + +/// +/// Posts the documents to the ledger (SPEC §11.7, issue #64, ADR 0037) inside the transaction of the document engine, +/// like 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 (). +/// +public sealed class LedgerPoster +{ + private readonly ILicenseGate _licence; + + /// Creates the poster. + /// The licence (module ACCT). + public LedgerPoster(ILicenseGate licence) + { + ArgumentNullException.ThrowIfNull(licence); + _licence = licence; + } + + /// Whether the documents post to the ledger. + public bool Active => _licence.IsModuleActive(ModuleCodes.Accounting); + + /// What a kind of document posts, if anything. + /// The kind. + /// The posting kind and whether the sides are reversed, or . + 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, + }; + + /// Writes again the entry of a document from its current state. + /// The unit of work of the company, in a transaction. + /// The family. + /// The document. + /// Cancellation. + /// The entry, or when the document posts nothing. + public async Task 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); + } + + /// Posts or removes the entry of a document whatever the licence (bulk posting, tests). + /// The unit of work of the company, in a transaction. + /// The family. + /// The document. + /// Cancellation. + /// The entry, or . + internal static async Task 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; + } + + /// The entry of a document that is not reversed, if any. + internal static async Task CurrentEntryAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken) + { + var entries = (await uow.Repository().ListAsync( + Query.For().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 SameAsync(IUnitOfWork uow, GlEntry existing, IReadOnlyList 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 Lines, List Vat)?> BuildAsync( + IUnitOfWork uow, DocumentFamily family, DocumentHeader header, (PostingKind Kind, bool Reverse) posting, CancellationToken cancellationToken) + { + var type = await uow.Repository().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().FindAsync( + Query.For().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().ListAsync(Query.For(), 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().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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id); + var inputLines = new List(); + 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().ListAsync(Query.For(), 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> ItemsAsync(IUnitOfWork uow, IReadOnlyList 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().ListAsync(Query.For().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 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().ListAsync( + Query.For().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(); + 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().CountAsync( + Query.For().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().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); + } +} diff --git a/src/Khaemhat.Application/Ledger/LedgerQueryService.cs b/src/Khaemhat.Application/Ledger/LedgerQueryService.cs new file mode 100644 index 0000000..720fec4 --- /dev/null +++ b/src/Khaemhat.Application/Ledger/LedgerQueryService.cs @@ -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; + +/// A movement of an account (or of a party on an account), with the running balance. +/// The entry, for the drill-down. +/// The number of the entry. +/// The date. +/// The description of the line, or of the entry. +/// The number of the document. +/// The date of the document. +/// The journal template. +/// The account (when the view is of a party). +/// The debit. +/// The credit. +/// The balance after the movement, debit positive. +/// The state of the entry. +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); + +/// A page of the movements of an account or a party. +/// The balance before the period. +/// The movements of the page. +/// How many movements the period has. +/// The debits of the period. +/// The credits of the period. +/// The balance at the end of the period. +public sealed record LedgerPage(decimal Opening, IReadOnlyList Movements, long TotalCount, decimal TotalDebit, decimal TotalCredit, decimal Closing); + +/// What the movements are asked for. +/// The account; with , its sub-ledger. +/// The customer or supplier (partitario, estratto conto). +/// From this day. +/// Up to this day. +/// Count the drafts too. +/// The first movement of the page. +/// The size of the page. +public sealed record LedgerFilter(long? AccountId, long? PartyId, DateOnly From, DateOnly To, bool IncludeDrafts = false, int Offset = 0, int Limit = 50); + +/// A line of the trial balance. +/// The account. +/// The code. +/// The description. +/// The level (1 mastro, 2 conto, 3 sottoconto). +/// The nature. +/// The balance before the period. +/// The debits of the period. +/// The credits of the period. +/// The balance at the end, debit positive. +public sealed record TrialBalanceLine(long AccountId, string Code, string Description, int Level, AccountNature Nature, decimal Opening, decimal Debit, decimal Credit, decimal Closing); + +/// The trial balance of a period. +/// The accounts with movements or a balance, with the totals of their parents. +/// The debits of the period. +/// The credits of the period. +/// The result of the period (revenues minus costs). +public sealed record TrialBalance(IReadOnlyList Lines, decimal TotalDebit, decimal TotalCredit, decimal Result) +{ + /// Whether debits and credits match. + public bool Balanced => TotalDebit == TotalCredit; +} + +/// A party with a balance on the customer or supplier accounts. +/// The party. +/// The name. +/// The debits. +/// The credits. +/// The balance, debit positive. +/// The open items not closed. +public sealed record PartyBalance(long PartyId, string Name, decimal Debit, decimal Credit, decimal Balance, int OpenItems); + +/// +/// 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. +/// +public sealed class LedgerQueryService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + + /// Creates the service. + /// The units of work. + /// The permissions. + public LedgerQueryService(IUnitOfWorkFactory factory, PermissionService permissions) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + _factory = factory; + _permissions = permissions; + } + + /// The movements of an account or of a party in a period, with the running balance. + /// Who reads. + /// The company. + /// The account or party, the period, the page. + /// Cancellation. + /// The page. + public async Task 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); + } + + /// The customers or suppliers with their balance on the sub-ledger accounts. + /// Who reads. + /// The company. + /// Customers or suppliers. + /// Up to this day. + /// Part of the name. + /// Cancellation. + /// The parties, by name. + public async Task> 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(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))]; + } + + /// The open items of a party (or of all), by due date. + /// Who reads. + /// The company. + /// The party, or for all. + /// Receivables or payables. + /// Show the closed items too. + /// Cancellation. + /// The items. + public async Task> 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().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().ListAsync(query.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items; + } + + /// The trial balance of a period (bilancio di verifica), optionally of one cost center. + /// Who reads. + /// The company. + /// From this day. + /// Up to this day. + /// Only the lines of this cost center. + /// Count the drafts too. + /// Cancellation. + /// The trial balance. + public async Task 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); + } + + /// The trial balance as PDF. + /// Who prints. + /// The company. + /// From this day. + /// Up to this day. + /// Only the lines of this cost center. + /// Cancellation. + /// The file. + public async Task 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var center = costCenterId is { } c ? await uow.Repository().GetAsync(c, cancellationToken).ConfigureAwait(false) : null; + var rows = new List>(); + 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); + } + + /// The movements of an account or party as PDF (mastrino, estratto conto). + /// Who prints. + /// The company. + /// The account or party and the period (the page is ignored). + /// Cancellation. + /// The file. + public async Task 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var account = filter.AccountId is { } a ? await uow.Repository().GetAsync(a, cancellationToken).ConfigureAwait(false) : null; + var party = filter.PartyId is { } p ? await uow.Repository().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> { 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); + } + + /// + /// 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. + /// + /// Who prints. + /// The company. + /// From this day. + /// Up to this day. + /// Only the final entries. + /// Cancellation. + /// The file. + public async Task 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var fiscalYear = await uow.Repository().FindAsync(Query.For().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(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>(); + 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); + } + + /// The movements of an account or party, paged in the database, with the running balance. + internal static async Task 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(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(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(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(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(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); + } + + /// The trial balance, with the totals of the parent accounts. + internal static async Task 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(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(); + 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); +} diff --git a/src/Khaemhat.Application/Ledger/LedgerReport.cs b/src/Khaemhat.Application/Ledger/LedgerReport.cs new file mode 100644 index 0000000..91830e2 --- /dev/null +++ b/src/Khaemhat.Application/Ledger/LedgerReport.cs @@ -0,0 +1,138 @@ +using System.Globalization; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Ledger; + +/// A column of a ledger print. +/// The heading. +/// The width in points. +/// Aligned on the right (amounts). +public sealed record ReportColumn(string Title, double Width, bool Right = false); + +/// +/// 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 +/// year/page as the final prints of the books want (art. 2215-bis c.c., numbering by year). +/// +internal static class LedgerReport +{ + private const double Margin = 28; + private const double LineHeight = 11; + private static readonly PdfColor Rule = PdfColor.Gray(180); + + /// Writes a print. + /// The name, VAT number and address of the company. + /// The title, such as Registro IVA vendite. + /// The period and the kind of print. + /// The columns. + /// The rows; a row whose first cell starts with ** is a bold total. + /// The year of the page numbers. + /// The number of the first page. + /// Cancellation. + /// The file and the number of pages. + public static async Task<(byte[] File, int Pages)> WriteAsync( + string company, string title, string subtitle, IReadOnlyList columns, IReadOnlyList> 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); + } + + /// An amount as the prints show it, with the Italian separators. + /// The amount. + /// The text; empty for zero. + public static string Money(decimal amount) => amount == 0m ? string.Empty : amount.ToString("#,##0.00", Italian); + + /// A date as the prints show it. + /// The date. + /// The text. + public static string Date(DateOnly? date) => date?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) ?? string.Empty; + + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); +} diff --git a/src/Khaemhat.Application/Ledger/LedgerService.cs b/src/Khaemhat.Application/Ledger/LedgerService.cs new file mode 100644 index 0000000..47c522e --- /dev/null +++ b/src/Khaemhat.Application/Ledger/LedgerService.cs @@ -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; + +/// An account typed in the chart. +/// The account, for a change. +/// The code, such as 05.01.003. +/// The description. +/// The statement it ends up in (taken from the parent below the first level). +/// What the automatic postings look for. +public sealed record AccountInput(long? Id, string Code, string Description, AccountNature Nature, AccountType Type = AccountType.Generic) +{ + /// The line of the legal statements. + public string? StatementLine { get; init; } + + /// The line of the reclassified statements. + public string? Reclassification { get; init; } + + /// The lines carry a customer or supplier. + public bool SubLedger { get; init; } + + /// Relevant for VAT. + public bool VatRelevant { get; init; } + + /// Closed at the year end. + public bool ClosesAutomatically { get; init; } = true; + + /// No longer used. + public bool Disabled { get; init; } +} + +/// A line of a journal template typed on its screen. +/// What it stands for. +/// Debit or credit. +/// The account. +/// The description proposed. +public sealed record TemplateLineInput(PostingRole Role, AccountSide Side, long? AccountId, string? Description); + +/// A journal template typed on its screen (mockup 043). +/// The template, for a change. +/// The code. +/// The description. +/// The kind of operations. +/// The model of the lines. +public sealed record TemplateInput(long? Id, string Code, string Description, JournalArea Area, IReadOnlyList Lines) +{ + /// The VAT register. + public string? VatRegisterCode { get; init; } + + /// Opens items of customers or suppliers. + public bool OpensItems { get; init; } + + /// Reverses the sides (credit notes). + public bool Reverses { get; init; } + + /// No longer used. + public bool Disabled { get; init; } +} + +/// What a bulk posting did. +/// Documents posted or posted again. +/// Documents that could not be posted, with the reason. +public sealed record PostingReport(int Posted, IReadOnlyList Failed); + +/// +/// 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). +/// +public sealed class LedgerService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The history. + public LedgerService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + _factory = factory; + _permissions = permissions; + _audit = audit; + } + + /// The chart of accounts, by code. + /// Who reads. + /// The company. + /// Cancellation. + /// Every account. + public async Task> 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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.OrderBy(a => a.Code, StringComparer.Ordinal)]; + } + + /// The VAT registers, by code. + /// Who reads. + /// The company. + /// Cancellation. + /// Every register. + public async Task> 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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return [.. registers.OrderBy(r => r.Kind).ThenBy(r => r.ReverseCharge).ThenBy(r => r.Code, StringComparer.Ordinal)]; + } + + /// Saves an account: a new one under a leaf with postings is refused, the parent stops being postable. + /// Who writes. + /// The company. + /// The account. + /// Cancellation. + /// The account as saved. + public async Task 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(); + var code = (input.Code ?? string.Empty).Trim(); + var errors = new List(); + 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().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().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; + } + + /// Removes an account without children, postings or use in the templates. + /// Who removes it. + /// The company. + /// The account. + /// Cancellation. + /// A task. + 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(); + var account = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.AccountMissing); + if (await repository.CountAsync(Query.For().Where(a => a.ParentId == id), cancellationToken).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["Id:" + LedgerErrors.AccountHasChildren]); + } + + var inTemplates = await uow.Repository().CountAsync(Query.For().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().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); + } + + /// The journal templates with their lines. + /// Who reads. + /// The company. + /// Cancellation. + /// Every template, by code. + public async Task> 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().ListAsync(Query.For().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false)).Items; + var lines = (await uow.Repository().ListAsync(Query.For().OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items; + return [.. templates.Select(t => new TemplateView(t, [.. lines.Where(l => l.JournalTemplateId == t.Id)]))]; + } + + /// Saves a journal template with its lines. + /// Who writes. + /// The company. + /// The template. + /// Cancellation. + /// The template as saved. + public async Task 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(); + var code = (input.Code ?? string.Empty).Trim().ToUpperInvariant(); + var errors = new List(); + 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().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(); + 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().InsertAsync(row, cancellationToken).ConfigureAwait(false); + lines.Add(row); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return new TemplateView(template, lines); + } + + /// Removes a template that no entry or document type uses. + /// Who removes it. + /// The company. + /// The template. + /// Cancellation. + /// A task. + 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.TemplateMissing); + var code = template.Code; + var entries = await uow.Repository().CountAsync(Query.For().Where(e => e.JournalTemplateId == id), cancellationToken).ConfigureAwait(false); + var types = await uow.Repository().CountAsync(Query.For().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().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); + } + + /// + /// 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 writes again the entries that are not final. + /// + /// Who posts. + /// The company. + /// From this day. + /// Up to this day. + /// Post again also the documents already posted. + /// Cancellation. + /// What was posted. + public async Task 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(); + foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument }) + { + List 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); + } + + /// Writes the accounts the import of a chart accepted: new codes are added, existing ones updated. + /// The unit of work, in a transaction. + /// The accounts, parents first or in any order. + /// Update the accounts that exist. + /// Cancellation. + /// For each code, whether it was created () or updated. + internal static async Task> ImportAsync(IUnitOfWork uow, IReadOnlyList accounts, bool update, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + var existing = (await repository.ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Code, StringComparer.OrdinalIgnoreCase); + var result = new Dictionary(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 UsedAsync(IUnitOfWork uow, long accountId, CancellationToken cancellationToken) => + await uow.Repository().CountAsync(Query.For().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, + }; +} diff --git a/src/Khaemhat.Application/Ledger/LedgerStore.cs b/src/Khaemhat.Application/Ledger/LedgerStore.cs new file mode 100644 index 0000000..280b07b --- /dev/null +++ b/src/Khaemhat.Application/Ledger/LedgerStore.cs @@ -0,0 +1,257 @@ +using System.Globalization; +using Khaemhat.Core.Accounting; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Ledger; + +/// The permissions of the ledger (module ACCT, ). +public static class LedgerPermissions +{ + /// See the chart of accounts and the journal templates. + public const string AccountRead = "ledger.account.read"; + + /// Change the chart of accounts and the journal templates. + public const string AccountWrite = "ledger.account.write"; + + /// See the journal, the ledgers and the balances. + public const string EntryRead = "ledger.entry.read"; + + /// Write entries and post documents. + public const string EntryWrite = "ledger.entry.write"; + + /// Make entries final (libro giornale). + public const string EntryFinalize = "ledger.entry.finalize"; + + /// See the VAT registers. + public const string VatRegisterRead = "vat.register.read"; + + /// See the settlements, withholdings, stamp duty and F24. + public const string SettlementRead = "vat.settlement.read"; + + /// Confirm settlements and record tax payments. + public const string SettlementConfirm = "vat.settlement.confirm"; +} + +/// A line of an entry being written. +/// The account. +/// The customer or supplier. +/// The description. +/// The debit. +/// The credit. +/// The cost center. +/// The job. +public sealed record EntryLineDraft(long? AccountId, long? PartyId, string? Description, decimal Debit, decimal Credit, long? CostCenterId = null, long? JobId = null); + +/// A VAT line of an entry being written. +/// The VAT code. +/// The rate. +/// The nature. +/// The taxable amount, with sign. +/// The VAT, with sign. +/// The VAT not deductible. +/// When the VAT is due. +/// The register, when different from the one of the entry (self-invoices). +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); + +/// +/// 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. +/// +internal static class LedgerStore +{ + /// Writes a new entry with its lines and VAT lines; posted entries get their number. + public static async Task InsertAsync( + IUnitOfWork uow, GlEntry entry, IReadOnlyList lines, IReadOnlyList 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().InsertAsync(entry, cancellationToken).ConfigureAwait(false); + await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false); + return entry; + } + + /// Replaces the lines of an entry and updates it. + public static async Task UpdateAsync( + IUnitOfWork uow, GlEntry entry, IReadOnlyList lines, IReadOnlyList 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().UpdateAsync(entry, cancellationToken).ConfigureAwait(false); + await RemoveLinesAsync(uow, entry.Id, cancellationToken).ConfigureAwait(false); + await WriteLinesAsync(uow, entry, lines, vat, cancellationToken).ConfigureAwait(false); + } + + /// Changes the state of an entry and of its lines. + 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().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); + } + + /// Removes an entry with its lines, VAT lines and open items. + 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().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false); + } + + /// The lines of an entry, in order. + public static async Task> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken) + .ConfigureAwait(false)).Items; + + /// The VAT lines of an entry, in order. + public static async Task> VatAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken) + .ConfigureAwait(false)).Items; + + /// Every account, by id. + public static async Task> AccountsAsync(IUnitOfWork uow, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id); + + /// The rules the validator reads, by id. + public static Dictionary Rules(IReadOnlyDictionary accounts) => + accounts.Values.ToDictionary(a => a.Id, a => new AccountRule(a.Id, a.Postable, a.Disabled, a.SubLedger)); + + /// A journal template with its lines, by code. + public static async Task<(JournalTemplate Template, IReadOnlyList Lines)?> TemplateAsync( + IUnitOfWork uow, string? code, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(code)) + { + return null; + } + + var template = await uow.Repository().FindAsync(Query.For().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false); + if (template is null) + { + return null; + } + + var lines = (await uow.Repository().ListAsync( + Query.For().Where(l => l.JournalTemplateId == template.Id).OrderBy(l => l.SortOrder), cancellationToken).ConfigureAwait(false)).Items; + return (template, lines); + } + + /// A VAT register by code. + public static Task RegisterAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) => + string.IsNullOrWhiteSpace(code) + ? Task.FromResult(null) + : uow.Repository().FindAsync(Query.For().Where(r => r.Code == code), cancellationToken); + + /// The account of a code, if any. + public static Task AccountAsync(IUnitOfWork uow, string? code, CancellationToken cancellationToken) => + string.IsNullOrWhiteSpace(code) + ? Task.FromResult(null) + : uow.Repository().FindAsync(Query.For().Where(a => a.Code == code), cancellationToken); + + /// + /// 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. + /// + 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(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); + } + + /// The number of an entry as shown. + 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 lines, IReadOnlyList vat, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + 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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id); + var vatRepository = uow.Repository(); + 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); + } + } + + /// A text cut to a length. + public static string? Trim(string? text, int length) => text is null || text.Length <= length ? text : text[..length]; +} diff --git a/src/Khaemhat.Application/Ledger/RecurringEntryService.cs b/src/Khaemhat.Application/Ledger/RecurringEntryService.cs new file mode 100644 index 0000000..e0999a3 --- /dev/null +++ b/src/Khaemhat.Application/Ledger/RecurringEntryService.cs @@ -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; + +/// A recurring entry being written. +/// The recurring entry, or for a new one. +/// What it is (rent, leasing, insurance). +/// The entry copied each time (usually a draft kept as model). +/// How often. +/// The date of the next entry. +/// The last date, if any. +/// Suspended. +public sealed record RecurringEntryInput(long? Id, string Description, long ModelEntryId, RecurrenceFrequency Frequency, DateOnly NextDate, DateOnly? EndDate, bool Disabled = false); + +/// +/// 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 ledger.recurring 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. +/// +public sealed class RecurringEntryService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly JournalEntryService _journal; + private readonly AuditTrail _audit; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The journal. + /// The history. + 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; + } + + /// The recurring entries, by next date. + /// Who reads. + /// The company. + /// Cancellation. + /// The recurring entries. + public async Task> 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().ListAsync(Query.For().OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items; + } + + /// Writes a recurring entry. + /// Who writes. + /// The company. + /// The recurring entry. + /// Cancellation. + /// The recurring entry. + public async Task 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(); + if (string.IsNullOrWhiteSpace(input.Description)) + { + errors.Add("Description:" + LedgerErrors.DescriptionRequired); + } + + var model = await uow.Repository().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? 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; + } + + /// Deletes a recurring entry (the entries already written stay). + /// Who deletes. + /// The company. + /// The recurring entry. + /// Cancellation. + /// A task. + 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound); + await uow.Repository().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); + } + + /// Writes the recurring entries due up to a day. + /// Who writes them. + /// The company. + /// Up to this day. + /// Cancellation. + /// The entries written and the problems met. + public async Task<(int Written, IReadOnlyList 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 due; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + due = (await uow.Repository().ListAsync( + Query.For().Where(r => !r.Disabled && r.NextDate <= upTo).OrderBy(r => r.NextDate), cancellationToken).ConfigureAwait(false)).Items; + } + + var written = 0; + var problems = new List(); + 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().UpdateAsync(recurring, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + written++; + } + } + + return (written, problems); + } + + /// The date after a due date. + /// The due date. + /// How often. + /// The next due date (the end of the month stays the end of the month). + 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; + } +} + +/// Writes the recurring entries due of every active company with the ledger, every morning. +/// The companies. +/// The recurring entries. +/// The licence. +/// The clock. +public sealed class RecurringEntriesJob(ICompanyRegistry companies, RecurringEntryService service, ILicenseGate license, TimeProvider clock) : IScheduledJob +{ + /// The job type. + public const string JobType = "ledger.recurring"; + + /// + public string Type => JobType; + + /// + public async Task 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(); + 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); + } +} diff --git a/src/Khaemhat.Application/Ledger/TaxService.cs b/src/Khaemhat.Application/Ledger/TaxService.cs new file mode 100644 index 0000000..6cbca92 --- /dev/null +++ b/src/Khaemhat.Application/Ledger/TaxService.cs @@ -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; + +/// A withholding with the name of its party. +/// The withholding. +/// The supplier or customer. +/// Its tax code (or VAT number). +public sealed record WithholdingRow(Withholding Withholding, string PartyName, string? PartyTaxCode); + +/// The stamp duty on the e-invoices of a quarter. +/// The year. +/// The quarter. +/// The invoices with stamp duty. +/// The duty. +/// When it is paid (moved to a later quarter below the threshold). +/// The F24 line, once recorded. +public sealed record StampDutyQuarter(int Year, int Quarter, int Documents, decimal Amount, DateOnly DueDate, TaxPayment? Payment); + +/// An invoice with stamp duty. +/// The invoice. +/// Its number. +/// Its date. +/// The customer. +/// The taxable amount. +/// The duty. +/// Charged to the customer (otherwise borne by the company). +/// The kind of document. +public sealed record StampDutyDocument(long DocumentId, string? DocumentNumber, DateOnly DocumentDate, string? PartyName, decimal Taxable, decimal StampDuty, bool Charged, DocumentKind Kind); + +/// A line of the F24 written by hand. +/// The line, or for a new one. +/// The due date. +/// The payment code. +/// The reference year. +/// The month or installment. +/// What it pays. +/// The amount (negative for a credit used in compensation). +public sealed record TaxPaymentInput(long? Id, DateOnly DueDate, string PaymentCode, int ReferenceYear, string? ReferencePeriod, string Description, decimal Amount); + +/// +/// 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. +/// +public sealed class TaxService +{ + /// The stamp duty of a quarter at or below this moves to the next due date (DM 4/12/2023). + 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; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The clock. + 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; + } + + /// The F24 lines due in a year. + /// Who reads. + /// The company. + /// The year of the due dates. + /// Cancellation. + /// The lines, by due date and code. + public async Task> 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().ListAsync( + Query.For().Where(t => t.DueDate >= from && t.DueDate <= to).OrderBy(t => t.DueDate).OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items; + } + + /// Writes a line of the F24 by hand (a tax the ledger does not compute, or a credit used in compensation). + /// Who writes. + /// The company. + /// The line. + /// Cancellation. + /// The line. + public async Task 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(); + 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? 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; + } + + /// Deletes a line written by hand and not paid. + /// Who deletes. + /// The company. + /// The line. + /// Cancellation. + /// A task. + 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().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().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); + } + + /// The F24 of a due date: its unpaid lines, one per code and period. + /// Who reads. + /// The company. + /// The due date. + /// Cancellation. + /// The form. + public async Task 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); + } + + /// The data file of the F24 of a due date. + /// Who asks. + /// The company. + /// The due date. + /// Cancellation. + /// The file. + public async Task 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(); + 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)); + } + + /// + /// Records the payment of the F24 of a due date: its lines are paid, the withholdings in it are paid, and the entry + /// F24 moves the tax accounts against the bank. + /// + /// Who records it. + /// The company. + /// The due date. + /// The day of payment. + /// The bank account debited; for the default one. + /// Cancellation. + /// The payment entry, if the ledger has the template. + public async Task 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().ListAsync( + Query.For().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(); + 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().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; + } + + /// Takes back the payment of an F24: the entry goes (or is reversed when final), the lines are unpaid. + /// Who does it. + /// The company. + /// The due date. + /// Cancellation. + /// A task. + 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().ListAsync( + Query.For().Where(t => t.DueDate == dueDate && t.PaidOn != null), cancellationToken).ConfigureAwait(false)).Items; + foreach (var entryId in payments.Select(p => p.GlEntryId).OfType().Distinct()) + { + if (await uow.Repository().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().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); + } + + /// The withholdings of the documents of a year. + /// Who reads. + /// The company. + /// The year of the documents. + /// Operated or suffered; for both. + /// Cancellation. + /// The withholdings, by date. + public async Task> 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().Where(w => w.DocumentDate >= from && w.DocumentDate <= to); + if (direction is { } d) + { + query = query.Where(w => w.Direction == d); + } + + var items = (await uow.Repository().ListAsync(query.OrderBy(w => w.DocumentDate), cancellationToken).ConfigureAwait(false)).Items; + return await RowsAsync(uow, items, cancellationToken).ConfigureAwait(false); + } + + /// + /// Records that the invoice of a withholding has been paid. An operated withholding becomes due: the entry + /// RIT 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 RITS moves it from the customer to the tax credit. + /// + /// Who records it. + /// The company. + /// The withholding. + /// The day the invoice was paid. + /// Cancellation. + /// The withholding. + public async Task 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(); + var withholdingRules = pack.GetFeature(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var withholding = await uow.Repository().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(); + var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture); + var year = paidOn.Year; + var payment = await payments.FindAsync( + Query.For().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().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; + } + + /// Takes back the payment of the invoice of a withholding while its F24 line is not paid. + /// Who does it. + /// The company. + /// The withholding. + /// Cancellation. + /// The withholding. + public async Task 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().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().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment) + { + payment.Amount -= withholding.Amount; + if (payment.Amount == 0m) + { + await uow.Repository().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false); + } + else + { + await uow.Repository().UpdateAsync(payment, cancellationToken).ConfigureAwait(false); + } + } + + if (withholding.GlEntryId is { } entryId && await uow.Repository().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().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; + } + + /// + /// 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. + /// + /// Who asks. + /// The company. + /// The year of payment. + /// Cancellation. + /// The CSV file. + public async Task 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().ListAsync( + Query.For().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()); + } + + /// The stamp duty on the e-invoices of each quarter of a year. + /// Who reads. + /// The company. + /// The year. + /// Cancellation. + /// Four quarters. + public async Task> 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(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await StampDutyAsync(uow, rules, year, cancellationToken).ConfigureAwait(false); + } + + /// The sale invoices with stamp duty of a quarter. + /// Who reads. + /// The company. + /// The year. + /// The quarter. + /// Cancellation. + /// The invoices, by date. + public async Task> 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(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); + } + + /// Records the F24 line of the stamp duty of a quarter (or updates it while unpaid). + /// Who records it. + /// The company. + /// The year. + /// The quarter. + /// Cancellation. + /// The line, or when no duty is due. + public async Task 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(); + var form = pack.Require(); + 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().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().InsertAsync(payment, cancellationToken).ConfigureAwait(false); + } + else + { + await uow.Repository().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; + } + + /// + /// 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. + /// + internal static async Task> 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(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().ListAsync( + Query.For().Where(t => t.Source == TaxPaymentSource.StampDuty && t.ReferenceYear == year), cancellationToken).ConfigureAwait(false)).Items; + var result = new List(); + 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 FormAsync(IUnitOfWork uow, DateOnly dueDate, bool? paid, CancellationToken cancellationToken) + { + var query = Query.For().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().ListAsync(query.OrderBy(t => t.PaymentCode), cancellationToken).ConfigureAwait(false)).Items; + var profile = await uow.Repository().FindAsync(Query.For(), 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 BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken) + { + var banks = uow.Repository(); + if (id is { } bankId) + { + return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["BankAccountId:" + LedgerErrors.BankAccountMissing]); + } + + var profile = await uow.Repository().FindAsync(Query.For(), 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().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 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().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 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> RowsAsync(IUnitOfWork uow, IReadOnlyList items, CancellationToken cancellationToken) + { + var ids = items.Select(w => w.PartyId).Distinct().ToList(); + var parties = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().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); +} diff --git a/src/Khaemhat.Application/Ledger/VatService.cs b/src/Khaemhat.Application/Ledger/VatService.cs new file mode 100644 index 0000000..f5a5f17 --- /dev/null +++ b/src/Khaemhat.Application/Ledger/VatService.cs @@ -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; + +/// A line of a VAT register. +/// The entry. +/// The number of the entry. +/// The protocol. +/// The VAT date. +/// The number of the document. +/// The date of the document. +/// The customer or supplier. +/// The rate. +/// The nature. +/// When the VAT is due. +/// The taxable amount. +/// The VAT. +/// The VAT not deductible. +/// The state of the entry. +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); + +/// A total by rate of a VAT register. +/// The rate. +/// The nature. +/// The taxable amount. +/// The VAT. +/// The VAT not deductible. +public sealed record VatRateTotal(decimal Rate, string? Nature, decimal Taxable, decimal Tax, decimal NonDeductibleTax); + +/// A VAT register in a period. +/// The register. +/// The lines, by date and protocol. +/// The totals by rate. +public sealed record VatRegisterView(VatRegister Register, IReadOnlyList Rows, IReadOnlyList Totals); + +/// A settlement with its lines and the names of its registers. +/// The settlement. +/// One line per register. +/// The registers, by id. +public sealed record VatSettlementView(VatSettlement Settlement, IReadOnlyList Lines, IReadOnlyDictionary Registers); + +/// A file produced by the ledger. +/// The name proposed. +/// The media type. +/// The content. +public sealed record LedgerFile(string FileName, string MediaType, byte[] Content); + +/// +/// 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. +/// +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; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The fiscal calendar. + /// The history. + /// The clock. + 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; + } + + /// A VAT register in a period. + /// Who reads. + /// The company. + /// The register. + /// From this VAT date. + /// Up to this VAT date. + /// Cancellation. + /// The register. + public async Task 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); + } + + /// + /// 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). + /// + /// Who prints. + /// The company. + /// The register. + /// From this day (for a final print, the day after the last one). + /// Up to this day. + /// A final print. + /// Cancellation. + /// The PDF. + public async Task 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().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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var rows = new List>(); + 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().UpdateAsync(register, cancellationToken).ConfigureAwait(false); + await uow.Repository().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); + } + + /// The settlements of a year. + /// Who reads. + /// The company. + /// The year. + /// Cancellation. + /// The settlements, by period. + public async Task> 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().ListAsync(Query.For().Where(s => s.Year == year).OrderBy(s => s.Number), cancellationToken) + .ConfigureAwait(false)).Items; + } + + /// A settlement with its lines. + /// Who reads. + /// The company. + /// The settlement. + /// Cancellation. + /// The settlement, or none. + public async Task 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); + } + + /// + /// 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. + /// + /// Who computes: needs vat.settlement.read. + /// The company. + /// The year. + /// The month or quarter. + /// Cancellation. + /// The settlement, as a draft. + public async Task 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(); + 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var periodicity = profile?.VatPeriodicity ?? VatPeriodicity.Monthly; + var period = TaxPeriod.Of(year, number, periodicity); + var settlements = uow.Repository(); + var existing = await settlements.FindAsync( + Query.For().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().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().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( + 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().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); + } + + /// + /// Confirms a settlement: the periods become settled, the entry LIQ closes the VAT accounts into the VAT + /// settlement account (with the interest and the pro rata) and the amount due becomes an F24 line. + /// + /// Who confirms: needs vat.settlement.confirm. + /// The company. + /// The settlement. + /// Cancellation. + /// The settlement as confirmed. + public async Task 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(); + var form = pack.GetFeature(); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var settlements = uow.Repository(); + 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().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().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); + } + + /// + /// 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. + /// + /// Who does it. + /// The company. + /// The settlement. + /// Cancellation. + /// The settlement as a draft. + public async Task 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(); + var settlement = await settlements.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.NotFound); + var end = settlement.EndDate; + if (await settlements.CountAsync(Query.For().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().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment) + { + if (payment.PaidOn is not null) + { + throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]); + } + + await uow.Repository().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false); + } + + if (settlement.GlEntryId is { } entryId && await uow.Repository().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); + } + + /// The base of the December advance for each method, as the ledger knows it. + /// Who reads. + /// The company. + /// The year of the advance. + /// Cancellation. + /// 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). + 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().FindAsync(Query.For(), 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().FindAsync( + Query.For().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)); + } + + /// Records the December advance as an F24 line due on 27 December. + /// Who records it. + /// The company. + /// The year. + /// The method. + /// The base of the method. + /// Cancellation. + /// The F24 line, or when nothing is due. + public async Task 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(); + var form = pack.Require(); + 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var payments = uow.Repository(); + var existing = await payments.FindAsync( + Query.For().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; + } + + /// The communication of the settlements of a quarter (LIPE) from its confirmed settlements. + /// Who asks. + /// The company. + /// The year. + /// The quarter. + /// Cancellation. + /// The file. + public async Task 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(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var profile = await uow.Repository().FindAsync(Query.For(), 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().ListAsync( + Query.For().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(); + foreach (var s in settlements) + { + var settlementId = s.Id; + var lines = (await uow.Repository().ListAsync(Query.For().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)); + } + + /// The VAT of each register in a period, from the posted entries. + internal static async Task> TotalsAsync(IUnitOfWork uow, DateOnly from, DateOnly to, CancellationToken cancellationToken) + { + var draft = nameof(GlEntryStatus.Draft); + var immediate = nameof(TaxExigibility.Immediate); + var rows = await uow.QueryAsync(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))]; + } + + /// The lines and totals of a register in a period. + internal static async Task RegisterAsync(IUnitOfWork uow, long registerId, DateOnly from, DateOnly to, CancellationToken cancellationToken) + { + var register = await uow.Repository().GetAsync(registerId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(LedgerErrors.VatRegisterRequired); + var draft = nameof(GlEntryStatus.Draft); + var rows = await uow.QueryAsync(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); + } + + /// The name and VAT number of the company for the heading of the prints. + 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 ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } settlement) + { + return null; + } + + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => l.SettlementId == id), cancellationToken) + .ConfigureAwait(false)).Items; + var registers = (await uow.Repository().ListAsync(Query.For(), 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 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(); + 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 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); +} diff --git a/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs b/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs new file mode 100644 index 0000000..22994c0 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs @@ -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; + +/// +/// 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. +/// +/// Posts the documents. +/// Writes the model entry of the rental. +/// Computes and confirms the settlements. +/// Withholdings, stamp duty and F24. +/// The recurring rental. +/// Reads the ledger. +/// Today. +public sealed class DemoLedgerSeeder( + LedgerService ledger, JournalEntryService journal, VatService vat, TaxService taxes, RecurringEntryService recurring, IUnitOfWorkFactory factory, TimeProvider clock) + : ICompanySeeder +{ + /// The account of the rental, from the Italian chart of accounts (Noleggi). + public const string RentAccount = "22.01.003"; + + /// The bank account that pays it. + public const string BankAccount = "07.01.001"; + + /// The monthly rental of the demo office printer. + public const decimal Rent = 45m; + + private static readonly Actor Seed = Actor.System; + + /// + public int Order => 40; + + /// + 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(); + if (await accounts.CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0) + { + return; // No chart of accounts: the company has no accounting module. + } + + if (await uow.Repository().CountAsync( + Query.For().Where(e => e.Source == GlEntrySource.Manual || e.Source == GlEntrySource.VatSettlement), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return; + } + + rentId = (await accounts.FindAsync(Query.For().Where(a => a.Code == RentAccount), cancellationToken).ConfigureAwait(false))?.Id; + bankId = (await accounts.FindAsync(Query.For().Where(a => a.Code == BankAccount), cancellationToken).ConfigureAwait(false))?.Id; + periodicity = (await uow.Repository().FindAsync(Query.For(), 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); + } + } +} diff --git a/src/Khaemhat.Application/Seeding/LedgerSeeder.cs b/src/Khaemhat.Application/Seeding/LedgerSeeder.cs new file mode 100644 index 0000000..e087c18 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/LedgerSeeder.cs @@ -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; + +/// +/// 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. +/// +public sealed class LedgerSeeder : ISeeder +{ + /// + public string ModuleCode => ModuleCodes.Accounting; + + /// + public SeedKind Kind => SeedKind.Base; + + /// + public int Order => 50; + + /// + public async Task RunAsync(SeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (context.Pack.GetFeature() 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(); + foreach (var posting in ledger.DocumentPostings) + { + var type = await types.FindAsync(Query.For().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> SeedAccountsAsync(SeedContext context, ILedgerTemplate ledger, CancellationToken cancellationToken) + { + var repository = context.UnitOfWork.Repository(); + var existing = (await repository.ListAsync(Query.For(), 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 accounts, CancellationToken cancellationToken) + { + var repository = context.UnitOfWork.Repository(); + var lines = context.UnitOfWork.Repository(); + var existing = (await repository.ListAsync(Query.For(), 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); + } + } + } +} diff --git a/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs b/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs new file mode 100644 index 0000000..418334d --- /dev/null +++ b/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs @@ -0,0 +1,264 @@ +using System.Globalization; + +namespace Khaemhat.Core.Accounting; + +/// The error codes of the journal; the interface translates them (Ledger.json). +public static class LedgerErrors +{ + /// The entry does not exist. + public const string NotFound = "ledger.entry.not-found"; + + /// The entry has no description. + public const string DescriptionRequired = "ledger.entry.description-required"; + + /// The entry has no date. + public const string DateRequired = "ledger.entry.date-required"; + + /// The entry has no lines. + public const string LinesRequired = "ledger.entry.lines-required"; + + /// Debit and credit differ. + public const string Unbalanced = "ledger.entry.unbalanced"; + + /// A line without account. + public const string AccountRequired = "ledger.line.account-required"; + + /// A line on an account that does not exist. + public const string AccountMissing = "ledger.line.account-missing"; + + /// A line on a level that does not receive postings (mastro or conto with children). + public const string AccountNotPostable = "ledger.line.account-not-postable"; + + /// A line on an account no longer used. + public const string AccountDisabled = "ledger.line.account-disabled"; + + /// A line of a sub-ledger account without customer or supplier. + public const string PartyRequired = "ledger.line.party-required"; + + /// A line with neither debit nor credit. + public const string AmountRequired = "ledger.line.amount-required"; + + /// A line with both debit and credit. + public const string BothSides = "ledger.line.both-sides"; + + /// A negative amount. + public const string Negative = "ledger.line.negative"; + + /// VAT lines without the VAT register. + public const string VatRegisterRequired = "ledger.entry.vat-register-required"; + + /// A VAT line without VAT code. + public const string VatCodeRequired = "ledger.vat.code-required"; + + /// A final entry cannot change: reverse it. + public const string Final = "ledger.entry.final"; + + /// An entry of a document changes only through the document. + public const string FromDocument = "ledger.entry.from-document"; + + /// The entry was already reversed. + public const string AlreadyReversed = "ledger.entry.already-reversed"; + + /// Only posted or final entries are reversed. + public const string NotPosted = "ledger.entry.not-posted"; + + /// Entries become final in date order: an earlier date is already final. + public const string FinalOrder = "ledger.entry.final-order"; + + /// A role of the journal template has no account. + public const string RoleAccountMissing = "ledger.posting.account-missing"; + + /// The journal template does not exist. + public const string TemplateMissing = "ledger.template.missing"; + + /// The account has postings: disable it instead. + public const string AccountUsed = "ledger.account.used"; + + /// The account has children. + public const string AccountHasChildren = "ledger.account.has-children"; + + /// The code of the account does not fit its parent. + public const string AccountParent = "ledger.account.parent"; + + /// Another account has the code. + public const string AccountDuplicate = "ledger.account.duplicate"; + + /// The code of the account is not one to three groups of digits separated by points. + public const string AccountCode = "ledger.account.code"; + + /// The entry is the model of a recurring entry. + public const string RecurringModel = "ledger.entry.recurring-model"; + + /// Drafts are left before the day to make final. + public const string DraftsBeforeFinal = "ledger.entry.drafts-before-final"; + + /// No fiscal year contains the day. + public const string NoFiscalYear = "ledger.entry.no-fiscal-year"; + + /// The code of a template is missing or longer than 10. + public const string TemplateCode = "ledger.template.code"; + + /// Another template has the code. + public const string TemplateDuplicate = "ledger.template.duplicate"; + + /// The template is used by entries or document types. + public const string TemplateUsed = "ledger.template.used"; + + /// The settlement of the period is already confirmed. + public const string SettlementConfirmed = "vat.settlement.confirmed"; + + /// The previous period is not settled. + public const string SettlementPrevious = "vat.settlement.previous"; + + /// A later period is already settled. + public const string SettlementLater = "vat.settlement.later"; + + /// The tax payment is already paid. + public const string PaymentPaid = "tax.payment.paid"; + + /// The withholding is not due or already paid. + public const string WithholdingNotDue = "withholding.not-due"; + + /// The account of the bank is missing. + public const string BankAccountMissing = "ledger.bank.account-missing"; + + /// The final print of a VAT register must follow the last one. + public const string PrintOrder = "vat.register.print-order"; +} + +/// An account as the validator needs it. +/// The account. +/// Receives postings. +/// No longer used. +/// Its lines need a customer or supplier. +public sealed record AccountRule(long Id, bool Postable, bool Disabled, bool SubLedger); + +/// A line as the validator reads it. +/// The account. +/// The customer or supplier. +/// The debit. +/// The credit. +public sealed record EntryLineCheck(long? AccountId, long? PartyId, decimal Debit, decimal Credit); + +/// +/// 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. +/// +public static class JournalEntryValidator +{ + /// Checks an entry. + /// The description. + /// The lines. + /// The number of VAT lines. + /// Whether the entry has its VAT register. + /// The accounts, by id. + /// Whether the entry is being posted (it must balance) or saved as a draft. + /// The errors, as field:code; empty when valid. + public static IReadOnlyList Check( + string? description, IReadOnlyList lines, int vatLines, bool hasVatRegister, IReadOnlyDictionary accounts, bool posting) + { + ArgumentNullException.ThrowIfNull(lines); + ArgumentNullException.ThrowIfNull(accounts); + var errors = new List(); + 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; + } + + /// Debit minus credit of the lines. + /// The lines. + /// The difference; zero when the entry balances. + public static decimal Difference(IEnumerable lines) => + lines?.Sum(l => l.Debit - l.Credit) ?? throw new ArgumentNullException(nameof(lines)); +} + +/// Codes of accounts in the form MM.CC.SSS. +public static class AccountCodes +{ + /// The level of a code (number of parts), or zero when the code is not valid. + /// The code. + /// 1 to 3, or 0. + 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; + } + + /// The code of the parent: the code without its last part. + /// The code. + /// The parent code, or for a mastro. + public static string? ParentOf(string code) + { + ArgumentNullException.ThrowIfNull(code); + var dot = code.LastIndexOf('.'); + return dot < 0 ? null : code[..dot]; + } +} diff --git a/src/Khaemhat.Core/Accounting/Ledger.cs b/src/Khaemhat.Core/Accounting/Ledger.cs new file mode 100644 index 0000000..662276e --- /dev/null +++ b/src/Khaemhat.Core/Accounting/Ledger.cs @@ -0,0 +1,837 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Entities; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Tax; + +namespace Khaemhat.Core.Accounting; + +/// The side of a posting. +public enum AccountSide +{ + /// Dare. + Debit = 0, + + /// Avere. + Credit = 1, +} + +/// +/// An account of the chart (SPEC §11.7, mockup 042, gl_accounts): three levels, mastro (05), conto +/// (05.01) and sottoconto (05.01.001); 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). +/// +public sealed class GlAccount : CodedEntity +{ + /// The level, 1 to 3: the number of parts of the code. + public int Level { get; set; } + + /// The account it adds up into. + public long? ParentId { get; set; } + + /// The statement it ends up in. + public AccountNature Nature { get; set; } + + /// What the automatic postings look for in it. + public AccountType Type { get; set; } + + /// The line of the legal financial statements (voce CEE, art. 2424/2425), such as C.II.1. + public string? StatementLine { get; set; } + + /// The line of the reclassified statements. + public string? Reclassification { get; set; } + + /// The lines carry a customer or supplier: the account has a sub-ledger (partitario). + public bool SubLedger { get; set; } + + /// Relevant for VAT (revenues and costs that go to the VAT registers). + public bool VatRelevant { get; set; } + + /// Closed by the year end into the income statement or the balance sheet. + public bool ClosesAutomatically { get; set; } + + /// Postings go on it: only the leaves. + public bool Postable { get; set; } +} + +/// What a VAT register records. +public enum VatRegisterKind +{ + /// Invoices issued: VAT due. + Sales = 0, + + /// Invoices received: VAT deductible. + Purchases = 1, + + /// Daily receipts of retail sales (corrispettivi): VAT due. + Receipts = 2, +} + +/// +/// A VAT register (SPEC §11.7, mockup 045, vat_registers): sales, purchases or receipts, with sections for +/// the self-invoices of reverse charge (the same operation annotated in a sales and a purchase register). +/// +public sealed class VatRegister : CodedEntity +{ + /// What it records. + public VatRegisterKind Kind { get; set; } + + /// A section for reverse-charge self-invoices: the VAT is due and deducted together (neutral). + public bool ReverseCharge { get; set; } + + /// The year of the last final print. + public int? PrintYear { get; set; } + + /// The last page of the last final print of . + public int LastPage { get; set; } + + /// The last day printed in final form. + public DateOnly? LastPrintedDate { get; set; } +} + +/// The kind of operations a journal template records. +public enum JournalArea +{ + /// Anything else. + General = 0, + + /// Invoices issued and their notes. + Sales = 1, + + /// Invoices received and their notes. + Purchases = 2, + + /// Collections, payments, transfers. + Treasury = 3, + + /// VAT settlements and tax payments. + Taxes = 4, + + /// Year end: accruals, depreciation, closing and opening. + YearEnd = 5, +} + +/// +/// A journal template (causale contabile, SPEC §11.7, mockup 043, gl_journal_templates): what an entry is, +/// which VAT register it uses and the model of its lines. +/// +public sealed class JournalTemplate : CodedEntity +{ + /// The kind of operations. + public JournalArea Area { get; set; } + + /// The VAT register, by code, for entries with VAT. + public string? VatRegisterCode { get; set; } + + /// The entries open items of customers or suppliers (scadenze). + public bool OpensItems { get; set; } + + /// The sign of the document is reversed (credit notes). + public bool Reverses { get; set; } +} + +/// What a line of a journal template stands for, so that the automatic postings find its account. +public enum PostingRole +{ + /// A fixed account (contropartita). + Account = 0, + + /// The customer: the customers control account with the party. + Customer = 1, + + /// The supplier: the suppliers control account with the party. + Supplier = 2, + + /// Revenues, by line. + Revenue = 3, + + /// Costs, by line. + Cost = 4, + + /// VAT on sales. + SalesVat = 5, + + /// VAT on purchases. + PurchaseVat = 6, + + /// A bank account. + Bank = 7, + + /// Cash. + Cash = 8, + + /// Withholding taxes to pay (Erario c/ritenute). + WithholdingPayable = 9, + + /// Withholding taxes suffered (Erario c/ritenute subite). + WithholdingCredit = 10, + + /// Social security contributions charged on fees (rivalsa cassa previdenza). + SocialSecurity = 11, + + /// Stamp duty charged to the customer, or paid. + StampDuty = 12, + + /// Roundings and small differences (abbuoni). + Rounding = 13, + + /// The VAT settlement account (Erario c/IVA). + VatSettlement = 14, + + /// VAT of split payment, due by the public customer. + SplitPaymentVat = 15, +} + +/// A line of a journal template (gl_journal_template_lines). +public sealed class JournalTemplateLine : Entity +{ + /// The template. + public long JournalTemplateId { get; set; } + + /// The order. + public int SortOrder { get; set; } + + /// What the line stands for. + public PostingRole Role { get; set; } + + /// Debit or credit, for an invoice (a credit note reverses it). + public AccountSide Side { get; set; } + + /// The account: fixed for , the default for the other roles. + public long? AccountId { get; set; } + + /// The description proposed on the line. + public string? Description { get; set; } +} + +/// The state of an entry. +public enum GlEntryStatus +{ + /// Being written: may not balance, counts nowhere. + Draft = 0, + + /// Posted (provvisoria): balanced, counts in balances and registers, can still change. + Posted = 1, + + /// Final (definitiva): numbered on the journal, immutable; only a reversal corrects it. + Final = 2, +} + +/// Where an entry comes from. +public enum GlEntrySource +{ + /// Typed in the journal. + Manual = 0, + + /// Posted by a document (invoice, credit note, self-invoice). + Document = 1, + + /// A VAT settlement. + VatSettlement = 2, + + /// A tax payment (F24). + TaxPayment = 3, + + /// Generated from a recurring entry. + Recurring = 4, + + /// The reversal of another entry. + Reversal = 5, + + /// The payment of an invoice with a withholding. + Withholding = 6, +} + +/// +/// An entry of the journal (registrazione di prima nota, SPEC §11.7, mockups 040-041, gl_entries): numbered +/// per year when posted, numbered on the journal (libro giornale) when final. +/// +public sealed class GlEntry : Entity, IDemoMarkable +{ + /// The year of the number. + public int Year { get; set; } + + /// The number in the year, once posted. + public long? Number { get; set; } + + /// The number as shown, such as 2026/00125. + public string? EntryNumber { get; set; } + + /// The progressive number on the journal, once final. + public long? JournalNumber { get; set; } + + /// The date of registration. + public DateOnly EntryDate { get; set; } + + /// The date of economic competence, when different. + public DateOnly? CompetenceDate { get; set; } + + /// The journal template. + public long? JournalTemplateId { get; set; } + + /// The code of the template, as it was. + public string? TemplateCode { get; set; } + + /// The description. + public string Description { get; set; } = string.Empty; + + /// The state. + public GlEntryStatus Status { get; set; } + + /// Where it comes from. + public GlEntrySource Source { get; set; } + + /// The family of the document that posted it. + public DocumentFamily? SourceFamily { get; set; } + + /// The document that posted it. + public long? SourceDocumentId { get; set; } + + /// The kind of that document. + public DocumentKind? SourceKind { get; set; } + + /// The number of the document (the supplier's number for purchases). + public string? DocumentNumber { get; set; } + + /// The date of the document. + public DateOnly? DocumentDate { get; set; } + + /// The customer or supplier. + public long? PartyId { get; set; } + + /// The VAT register, for entries with VAT. + public long? VatRegisterId { get; set; } + + /// The protocol in the VAT register. + public long? VatProtocol { get; set; } + + /// The date the VAT counts from (registration for purchases). + public DateOnly? VatDate { get; set; } + + /// The entry this one reverses. + public long? ReversalOfId { get; set; } + + /// The entry that reversed this one. + public long? ReversedById { get; set; } + + /// The total debit (equal to the credit once posted). + public decimal TotalDebit { get; set; } + + /// The total credit. + public decimal TotalCredit { get; set; } + + /// When it became final. + public DateTime? FinalizedAt { get; set; } + + /// Who made it final. + public string? FinalizedBy { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } + + /// Whether it balances. + public bool Balanced => TotalDebit == TotalCredit; +} + +/// A line of an entry (gl_entry_lines). +public sealed class GlEntryLine : Entity +{ + /// The entry. + public long EntryId { get; set; } + + /// The order, from 1. + public int LineNumber { get; set; } + + /// The date of the entry (kept here to read balances without joins). + public DateOnly EntryDate { get; set; } + + /// The state of the entry (kept here: drafts count nowhere). + public GlEntryStatus Status { get; set; } + + /// The account. + public long AccountId { get; set; } + + /// The customer or supplier, on sub-ledger accounts. + public long? PartyId { get; set; } + + /// The description. + public string? Description { get; set; } + + /// The debit. + public decimal Debit { get; set; } + + /// The credit. + public decimal Credit { get; set; } + + /// The cost center. + public long? CostCenterId { get; set; } + + /// The job. + public long? JobId { get; set; } + + /// The open item it settles or creates. + public long? OpenItemId { get; set; } +} + +/// A VAT line of an entry (gl_entry_vat): what the VAT registers and the settlement read. +public sealed class GlEntryVat : Entity +{ + /// The entry. + public long EntryId { get; set; } + + /// The order, from 1. + public int LineNumber { get; set; } + + /// The register. + public long VatRegisterId { get; set; } + + /// The kind of the register (kept here for the settlement). + public VatRegisterKind RegisterKind { get; set; } + + /// The VAT date of the entry (kept here: the registers and the settlement read by it). + public DateOnly VatDate { get; set; } + + /// The state of the entry (kept here). + public GlEntryStatus Status { get; set; } + + /// The VAT code. + public long? TaxCodeId { get; set; } + + /// The rate in percent. + public decimal Rate { get; set; } + + /// The nature of operations without VAT. + public string? Nature { get; set; } + + /// When the VAT becomes due. + public TaxExigibility Exigibility { get; set; } + + /// The taxable amount, with the sign of the operation (negative for credit notes). + public decimal Taxable { get; set; } + + /// The VAT, with the sign of the operation. + public decimal Tax { get; set; } + + /// The part of the VAT that cannot be deducted. + public decimal NonDeductibleTax { get; set; } +} + +/// Whether an open item is to collect or to pay. +public enum OpenItemDirection +{ + /// From a customer. + Receivable = 0, + + /// To a supplier. + Payable = 1, +} + +/// +/// An open item (partita aperta, gl_open_items): an installment of an invoice posted to the ledger, which the +/// schedule of collections and payments (M8) settles. +/// +public sealed class OpenItem : Entity, IDemoMarkable +{ + /// To collect or to pay. + public OpenItemDirection Direction { get; set; } + + /// The customer or supplier. + public long PartyId { get; set; } + + /// The control account. + public long AccountId { get; set; } + + /// The entry that opened it. + public long EntryId { get; set; } + + /// The family of the document. + public DocumentFamily? SourceFamily { get; set; } + + /// The document. + public long? SourceDocumentId { get; set; } + + /// The number of the document. + public string? DocumentNumber { get; set; } + + /// The date of the document. + public DateOnly DocumentDate { get; set; } + + /// The installment, from 1. + public int Installment { get; set; } + + /// The due date. + public DateOnly DueDate { get; set; } + + /// The amount, negative for credit notes. + public decimal Amount { get; set; } + + /// What was collected or paid. + public decimal PaidAmount { get; set; } + + /// The payment method. + public long? PaymentMethodId { get; set; } + + /// Fully settled. + public bool Closed { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// How often a recurring entry repeats. +public enum RecurrenceFrequency +{ + /// Every month. + Monthly = 0, + + /// Every three months. + Quarterly = 1, + + /// Every six months. + HalfYearly = 2, + + /// Every year. + Yearly = 3, +} + +/// +/// A recurring entry (gl_recurring_entries): an entry used as model, copied as a draft at each due date (rents, +/// leases, fees). +/// +public sealed class RecurringEntry : Entity, IDemoMarkable +{ + /// The description. + public string Description { get; set; } = string.Empty; + + /// The entry copied. + public long ModelEntryId { get; set; } + + /// How often. + public RecurrenceFrequency Frequency { get; set; } + + /// The date of the next copy. + public DateOnly NextDate { get; set; } + + /// No copies after this day. + public DateOnly? EndDate { get; set; } + + /// The last entry made. + public long? LastEntryId { get; set; } + + /// Suspended. + public bool Disabled { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// The state of a VAT settlement. +public enum VatSettlementStatus +{ + /// Computed, can be computed again. + Draft = 0, + + /// Confirmed: the period is settled and the entry posted. + Confirmed = 1, +} + +/// A periodic VAT settlement (SPEC §11.7, mockup 046, vat_settlements). +public sealed class VatSettlement : Entity, IDemoMarkable +{ + /// The year. + public int Year { get; set; } + + /// The month (1-12) or the quarter (1-4). + public int Number { get; set; } + + /// Monthly or quarterly. + public VatPeriodicity Periodicity { get; set; } + + /// The first day. + public DateOnly StartDate { get; set; } + + /// The last day. + public DateOnly EndDate { get; set; } + + /// The day of the settlement. + public DateOnly SettlementDate { get; set; } + + /// The state. + public VatSettlementStatus Status { get; set; } + + /// The VAT due on sales of the period. + public decimal SalesTax { get; set; } + + /// The VAT deductible on purchases, after the pro rata. + public decimal PurchaseTax { get; set; } + + /// The VAT on purchases that cannot be deducted. + public decimal NonDeductibleTax { get; set; } + + /// The VAT of the period not yet due (deferred, split payment, cash accounting). + public decimal DeferredTax { get; set; } + + /// The pro rata applied, percent. + public decimal ProRataPercent { get; set; } = 100m; + + /// The credit of the previous period. + public decimal PreviousCredit { get; set; } + + /// The debit of the previous period below the minimum, carried here. + public decimal PreviousDebit { get; set; } + + /// The advance paid in December, deducted from the last period. + public decimal AdvancePaid { get; set; } + + /// The interest rate for quarterly payers, percent. + public decimal InterestPercent { get; set; } + + /// The interest. + public decimal Interest { get; set; } + + /// The VAT to pay (zero when below the minimum or in credit). + public decimal AmountDue { get; set; } + + /// The credit carried to the next period. + public decimal CreditCarried { get; set; } + + /// The debit below the minimum, carried to the next period. + public decimal DebitCarried { get; set; } + + /// The F24 payment code. + public string? PaymentCode { get; set; } + + /// The day the payment is due. + public DateOnly? DueDate { get; set; } + + /// The entry that closes the VAT accounts. + public long? GlEntryId { get; set; } + + /// The tax payment created. + public long? TaxPaymentId { get; set; } + + /// When it was confirmed. + public DateTime? ConfirmedAt { get; set; } + + /// Who confirmed it. + public string? ConfirmedBy { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A line of a VAT settlement: one register (vat_settlement_lines). +public sealed class VatSettlementLine : Entity +{ + /// The settlement. + public long SettlementId { get; set; } + + /// The register. + public long VatRegisterId { get; set; } + + /// The kind of the register. + public VatRegisterKind RegisterKind { get; set; } + + /// The number of entries. + public int Documents { get; set; } + + /// The taxable amount. + public decimal Taxable { get; set; } + + /// The VAT. + public decimal Tax { get; set; } + + /// The VAT not deductible. + public decimal NonDeductibleTax { get; set; } + + /// The VAT not yet due. + public decimal DeferredTax { get; set; } +} + +/// What a tax payment pays. +public enum TaxPaymentSource +{ + /// Typed by hand. + Manual = 0, + + /// A VAT settlement. + VatSettlement = 1, + + /// The VAT advance of December. + VatAdvance = 2, + + /// Withholding taxes. + Withholding = 3, + + /// Stamp duty on e-invoices. + StampDuty = 4, +} + +/// +/// A line of a tax payment form (rigo F24, tax_payments): a payment code, the period it refers to and the +/// amount; paid lines post the payment entry. +/// +public sealed class TaxPayment : Entity, IDemoMarkable +{ + /// The day it is due. + public DateOnly DueDate { get; set; } + + /// The payment code, such as 6009. + public string PaymentCode { get; set; } = string.Empty; + + /// The year the payment refers to. + public int ReferenceYear { get; set; } + + /// The month or installment it refers to, as the form wants it (0009, 0003). + public string? ReferencePeriod { get; set; } + + /// The description. + public string Description { get; set; } = string.Empty; + + /// The amount due. + public decimal Amount { get; set; } + + /// What it pays. + public TaxPaymentSource Source { get; set; } + + /// The record it pays (settlement), when one. + public long? SourceId { get; set; } + + /// The day it was paid. + public DateOnly? PaidOn { get; set; } + + /// The bank account used. + public long? BankAccountId { get; set; } + + /// The entry of the payment. + public long? GlEntryId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// Whether the company withheld a tax or suffered it. +public enum WithholdingDirection +{ + /// Withheld by the company on fees it pays (operata): to pay with F24. + Operated = 0, + + /// Withheld by a customer on the company's fees (subita): a tax credit. + Suffered = 1, +} + +/// The state of a withholding. +public enum WithholdingStatus +{ + /// The invoice is not paid yet: nothing is due. + Waiting = 0, + + /// The invoice is paid: due by the 16th of the next month. + Due = 1, + + /// Paid with F24. + Paid = 2, + + /// Suffered: a credit for the tax return. + Suffered = 3, +} + +/// +/// A withholding tax of an invoice (ritenuta d'acconto, SPEC §11.7, mockup 047, withholdings): operated on the +/// fees and commissions received, suffered on the fees issued. +/// +public sealed class Withholding : Entity, IDemoMarkable +{ + /// Operated or suffered. + public WithholdingDirection Direction { get; set; } + + /// The family of the invoice. + public DocumentFamily SourceFamily { get; set; } + + /// The invoice. + public long SourceDocumentId { get; set; } + + /// The number of the invoice. + public string? DocumentNumber { get; set; } + + /// The date of the invoice. + public DateOnly DocumentDate { get; set; } + + /// The supplier (operated) or customer (suffered). + public long PartyId { get; set; } + + /// The type of the e-invoice, such as RT01. + public string? WithholdingType { get; set; } + + /// The reason of the payment (A, R...). + public string? Reason { get; set; } + + /// The fee or commission. + public decimal Taxable { get; set; } + + /// The social security fund, such as TC22. + public string? SocialSecurityFund { get; set; } + + /// The social security contribution charged. + public decimal SocialSecurityAmount { get; set; } + + /// The rate, percent. + public decimal Rate { get; set; } + + /// The share of the fee the rate applies to, percent. + public decimal BasePercent { get; set; } = 100m; + + /// The tax withheld. + public decimal Amount { get; set; } + + /// The F24 payment code. + public string? PaymentCode { get; set; } + + /// The day the invoice was paid: the withholding is due from that month. + public DateOnly? InvoicePaidOn { get; set; } + + /// The state. + public WithholdingStatus Status { get; set; } + + /// The F24 line that paid it. + public long? TaxPaymentId { get; set; } + + /// The entry that moved it to the tax authority when the invoice was paid. + public long? GlEntryId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A print of a VAT register (vat_register_prints): final prints number the pages of the year. +public sealed class VatRegisterPrint : Entity +{ + /// The register. + public long VatRegisterId { get; set; } + + /// The year. + public int Year { get; set; } + + /// The first day. + public DateOnly FromDate { get; set; } + + /// The last day. + public DateOnly ToDate { get; set; } + + /// The first page. + public int FirstPage { get; set; } + + /// The last page. + public int LastPage { get; set; } + + /// The attachment with the PDF. + public long? AttachmentId { get; set; } + + /// When. + public DateTime PrintedAt { get; set; } + + /// Who. + public string? PrintedBy { get; set; } +} diff --git a/src/Khaemhat.Core/Accounting/PostingEngine.cs b/src/Khaemhat.Core/Accounting/PostingEngine.cs new file mode 100644 index 0000000..a34bc8e --- /dev/null +++ b/src/Khaemhat.Core/Accounting/PostingEngine.cs @@ -0,0 +1,276 @@ +using Khaemhat.Core.Tax; + +namespace Khaemhat.Core.Accounting; + +/// What a document posts. +public enum PostingKind +{ + /// An invoice issued, a debit note, a fee: customer, revenues, VAT on sales. + Sale = 0, + + /// An invoice received: supplier, costs, VAT on purchases. + Purchase = 1, + + /// A self-invoice or integration (reverse charge): VAT due and VAT deducted, no customer or supplier. + SelfInvoice = 2, +} + +/// A revenue or cost line of a document, after discounts. +/// The account of the line (from the line, the item, the party or the template). +/// The taxable amount of the line, positive. +/// The VAT code of the line (non-deductible VAT goes to its cost). +/// The cost center. +/// The job. +public sealed record PostingLineInput(long? AccountId, decimal Amount, long? TaxCodeId = null, long? CostCenterId = null, long? JobId = null); + +/// A line of the tax summary of a document. +/// The VAT code. +/// The rate. +/// The nature, for operations without VAT. +/// When the VAT is due. +/// The taxable amount. +/// The VAT. +/// The VAT not deductible. +public sealed record PostingTaxInput(long? TaxCodeId, decimal Rate, string? Nature, TaxExigibility Exigibility, decimal Taxable, decimal Tax, decimal NonDeductibleTax); + +/// A document to post, with its amounts as computed by the documents engine. +/// Sale, purchase or self-invoice. +/// A credit note: every side is reversed and the VAT is negative. +/// The customer or supplier. +/// The revenue or cost lines. +/// The tax summary. +/// The total of the document (taxable, VAT and stamp duty charged). +/// The stamp duty charged on the document (zero when the company bears it). +/// The social security contribution charged on a fee (rivalsa). +public sealed record PostingInput( + PostingKind Kind, + bool Reverse, + long? PartyId, + IReadOnlyList Lines, + IReadOnlyList Taxes, + decimal Total, + decimal StampDuty = 0m, + decimal SocialSecurity = 0m); + +/// The accounts a posting needs besides those of the lines. +/// The control account of the customer or supplier. +/// The revenue or cost when a line has none (and the non-deductible VAT of a self-invoice). +/// VAT on sales. +/// VAT on purchases. +/// Stamp duty (revenue when charged to a customer, cost when charged by a supplier). +/// Social security charged on fees (revenue on sales). +public sealed record PostingAccounts(long? Party, long? DefaultLine, long? SalesVat, long? PurchaseVat, long? StampDuty = null, long? SocialSecurity = null); + +/// A line of the entry produced. +/// What the line stands for. +/// The account. +/// The customer or supplier, on their line. +/// Debit or credit. +/// The amount, positive. +/// The cost center. +/// The job. +public sealed record PostedLine(PostingRole Role, long AccountId, long? PartyId, AccountSide Side, decimal Amount, long? CostCenterId = null, long? JobId = null) +{ + /// The debit. + public decimal Debit => Side == AccountSide.Debit ? Amount : 0m; + + /// The credit. + public decimal Credit => Side == AccountSide.Credit ? Amount : 0m; +} + +/// A VAT line of the entry produced, for a register of the given kind. +/// Sales or purchases (a self-invoice writes one of each). +/// The tax line, with the sign of the operation. +public sealed record PostedVat(VatRegisterKind RegisterKind, PostingTaxInput Tax); + +/// The entry of a document. +/// The lines. +/// The VAT lines. +public sealed record PostingResult(IReadOnlyList Lines, IReadOnlyList Vat) +{ + /// The total debit. + public decimal Debit => Lines.Sum(l => l.Debit); + + /// The total credit. + public decimal Credit => Lines.Sum(l => l.Credit); +} + +/// An account a posting needs is not configured. +/// The role without account. +public sealed class PostingAccountMissingException(PostingRole role) : Exception("No account for " + role + ".") +{ + /// The role without account. + public PostingRole Role { get; } = role; +} + +/// +/// 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. +/// +/// 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). +/// 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. +/// 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. +/// +/// 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. +/// +public static class PostingEngine +{ + /// Posts a document. + /// The document. + /// The accounts. + /// The entry. + /// An account the document needs is missing. + public static PostingResult Post(PostingInput input, PostingAccounts accounts) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(accounts); + var lines = new List(); + var vat = new List(); + 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 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 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; +} diff --git a/src/Khaemhat.Core/Accounting/VatSettlementCalculator.cs b/src/Khaemhat.Core/Accounting/VatSettlementCalculator.cs new file mode 100644 index 0000000..26d2f62 --- /dev/null +++ b/src/Khaemhat.Core/Accounting/VatSettlementCalculator.cs @@ -0,0 +1,150 @@ +namespace Khaemhat.Core.Accounting; + +/// The VAT of one register in a period, as the settlement reads it. +/// The register. +/// Sales, purchases or receipts. +/// The number of entries. +/// The taxable amount. +/// The VAT of the period. +/// The VAT on purchases that cannot be deducted by its code. +/// The VAT not due in the period (deferred, split payment). +public sealed record VatRegisterTotals(long RegisterId, VatRegisterKind Kind, int Documents, decimal Taxable, decimal Tax, decimal NonDeductibleTax, decimal DeferredTax); + +/// What the settlement needs besides the registers. +/// The share of VAT on purchases that can be deducted (pro rata), percent. +/// The credit carried from the previous period. +/// The debit below the minimum carried from the previous period. +/// The December advance, deducted from the last period of the year. +/// The interest of quarterly payers, percent (zero for monthly). +/// The smallest amount paid; below it the debit is carried (Italy: 25.82). +public sealed record VatSettlementTerms( + decimal ProRataPercent = 100m, + decimal PreviousCredit = 0m, + decimal PreviousDebit = 0m, + decimal AdvancePaid = 0m, + decimal InterestPercent = 0m, + decimal MinimumPayment = 0m); + +/// The result of a settlement. +/// The VAT due on sales and receipts. +/// The VAT deducted on purchases, after the pro rata. +/// The VAT on purchases not deducted (by code and by pro rata). +/// The VAT of the period not yet due. +/// Due minus deducted, minus the credit and the advance, plus the debit carried: positive to pay. +/// The interest of quarterly payers. +/// What to pay; zero below the minimum or in credit. +/// The credit for the next period. +/// The debit below the minimum, for the next period. +public sealed record VatSettlementResult( + decimal SalesTax, + decimal PurchaseTax, + decimal NonDeductibleTax, + decimal DeferredTax, + decimal Balance, + decimal Interest, + decimal AmountDue, + decimal CreditCarried, + decimal DebitCarried); + +/// +/// 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. +/// +public static class VatSettlementCalculator +{ + /// Computes a settlement. + /// The VAT of each register in the period. + /// Pro rata, carried amounts, advance, interest and minimum. + /// The result, rounded to the cent. + public static VatSettlementResult Compute(IReadOnlyList 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); +} + +/// +/// 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. +/// +public static class ProRataCalculator +{ + /// The pro rata percentage of a year. + /// Operations that give the right to deduct (taxable, non taxable). + /// Exempt operations that do not (art. 10, except the occasional ones). + /// The percentage, a whole number from 0 to 100; 100 without exempt operations. + 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); + } + + /// The VAT deductible with a pro rata. + /// The VAT that would be deductible without the pro rata. + /// The pro rata, percent. + /// The deductible VAT, rounded to the cent. + public static decimal Deductible(decimal tax, decimal percent) => + percent >= 100m ? tax : Math.Round(tax * Math.Max(0m, percent) / 100m, 2, MidpointRounding.AwayFromZero); +} + +/// How the December VAT advance is computed. +public enum VatAdvanceMethod +{ + /// A share (Italy: 88%) of what was paid for the same period of the previous year. + Historical = 0, + + /// A share of the VAT expected for the last period of this year. + Forecast = 1, + + /// The VAT actually due for the operations up to 20 December. + Actual = 2, +} + +/// The December VAT advance (acconto IVA, issue #65). +public static class VatAdvanceCalculator +{ + /// The advance. + /// The method. + /// 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. + /// The share for the historical and forecast methods, percent (Italy: 88). + /// Below this nothing is paid (Italy: 103.29). + /// The advance, rounded to the cent; zero below the minimum. + 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; + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs b/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs new file mode 100644 index 0000000..23bd9a4 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs @@ -0,0 +1,172 @@ +using Khaemhat.Core.Accounting; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to gl_accounts. +public sealed class GlAccountMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to vat_registers. +public sealed class VatRegisterMap : EntityMap +{ + /// Creates the map. + public VatRegisterMap() + { + ToTable("vat_registers"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to gl_journal_templates. +public sealed class JournalTemplateMap : EntityMap +{ + /// Creates the map. + public JournalTemplateMap() + { + ToTable("gl_journal_templates"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.VatRegisterCode).MaxLength(10); + } +} + +/// Map of to gl_journal_template_lines. +public sealed class JournalTemplateLineMap : EntityMap +{ + /// Creates the map. + public JournalTemplateLineMap() + { + ToTable("gl_journal_template_lines"); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to gl_entries. +public sealed class GlEntryMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to gl_entry_lines. +public sealed class GlEntryLineMap : EntityMap +{ + /// Creates the map. + public GlEntryLineMap() + { + ToTable("gl_entry_lines"); + Map(x => x.Description).MaxLength(200); + } +} + +/// Map of to gl_entry_vat. +public sealed class GlEntryVatMap : EntityMap +{ + /// Creates the map. + public GlEntryVatMap() + { + ToTable("gl_entry_vat"); + Map(x => x.Nature).MaxLength(10); + } +} + +/// Map of to gl_open_items. +public sealed class OpenItemMap : EntityMap +{ + /// Creates the map. + public OpenItemMap() + { + ToTable("gl_open_items"); + Map(x => x.DocumentNumber).MaxLength(30); + } +} + +/// Map of to gl_recurring_entries. +public sealed class RecurringEntryMap : EntityMap +{ + /// Creates the map. + public RecurringEntryMap() + { + ToTable("gl_recurring_entries"); + Map(x => x.Description).MaxLength(200); + } +} + +/// Map of to vat_settlements. +public sealed class VatSettlementMap : EntityMap +{ + /// Creates the map. + public VatSettlementMap() + { + ToTable("vat_settlements"); + Map(x => x.PaymentCode).MaxLength(10); + Map(x => x.ConfirmedBy).MaxLength(100); + } +} + +/// Map of to vat_settlement_lines. +public sealed class VatSettlementLineMap : EntityMap +{ + /// Creates the map. + public VatSettlementLineMap() => ToTable("vat_settlement_lines"); +} + +/// Map of to tax_payments. +public sealed class TaxPaymentMap : EntityMap +{ + /// Creates the map. + public TaxPaymentMap() + { + ToTable("tax_payments"); + Map(x => x.PaymentCode).MaxLength(10); + Map(x => x.ReferencePeriod).MaxLength(10); + Map(x => x.Description).MaxLength(200); + } +} + +/// Map of to withholdings. +public sealed class WithholdingMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to vat_register_prints. +public sealed class VatRegisterPrintMap : EntityMap +{ + /// Creates the map. + public VatRegisterPrintMap() + { + ToTable("vat_register_prints"); + Map(x => x.PrintedBy).MaxLength(100); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_002_CreateLedger.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_002_CreateLedger.cs new file mode 100644 index 0000000..dc75aa4 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_002_CreateLedger.cs @@ -0,0 +1,338 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// 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. +/// +[Migration(20261113_002, "create_ledger")] +public sealed class M20261113_002_CreateLedger : IMigration +{ + /// + 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); + }); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs index b9bb46c..feaa051 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Features.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -1,4 +1,3 @@ -using Khaemhat.Core.Accounting; using Khaemhat.Core.Tax; namespace Khaemhat.Fiscal.Abstractions; @@ -96,7 +95,7 @@ public interface IFixedAssetRules /// What it pays. public sealed record TaxPaymentCode(string Code, string Description); -/// The country's tax payment form (Italy: F24); the file export arrives with the VAT settlement (M7). +/// The country's tax payment form (Italy: F24): the payment codes and the data of a form. public interface ITaxPaymentFormExporter { /// The name of the form, such as F24. @@ -119,6 +118,19 @@ public interface ITaxPaymentFormExporter /// The quarter, 1-4. /// The payment code. string StampDutyCode(int quarter); + + /// The name proposed for the data file of a form. + /// The form. + /// The file name. + string FileName(TaxPaymentForm form); + + /// + /// 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). + /// + /// The form. + /// The file, UTF-8. + byte[] Export(TaxPaymentForm form); } /// Which statement a schema line belongs to. @@ -147,24 +159,6 @@ public interface IFinancialStatementsSchema IReadOnlyList Lines(FinancialStatementKind kind); } -/// An account of the country's model chart of accounts. -/// The hierarchical code, such as 01.01.001. -/// The description. -/// The parent account, if any. -/// The statement it ends up in. -/// The financial statement line it maps to, if any. -public sealed record AccountTemplate(string Code, string Description, string? ParentCode, AccountNature Nature, string? StatementLine); - -/// The model chart of accounts loaded into a new company (arrives with the ledger, M7). -public interface IChartOfAccountsTemplate -{ - /// The name of the model, such as PMI standard. - string Name { get; } - - /// The accounts, parents before children. - IReadOnlyList Accounts { get; } -} - /// A line of an Intrastat return. /// The country of the counterparty. /// The VAT number of the counterparty, without country prefix. diff --git a/src/Khaemhat.Fiscal.Abstractions/Ledger.cs b/src/Khaemhat.Fiscal.Abstractions/Ledger.cs new file mode 100644 index 0000000..11b1cdc --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/Ledger.cs @@ -0,0 +1,211 @@ +using Khaemhat.Core.Accounting; + +namespace Khaemhat.Fiscal.Abstractions; + +/// An account of the country's model chart of accounts. +/// The hierarchical code, such as 05.01.001. +/// The description. +/// The statement it ends up in. +/// What the automatic postings look for in it. +/// The line of the legal financial statements, if any. +/// The lines carry a customer or supplier. +/// Relevant for VAT. +public sealed record AccountTemplate( + string Code, + string Description, + AccountNature Nature, + AccountType Type = AccountType.Generic, + string? StatementLine = null, + bool SubLedger = false, + bool VatRelevant = false) +{ + /// The parent account: the code without its last part. + public string? ParentCode => AccountCodes.ParentOf(Code); + + /// The level: the number of parts of the code. + public int Level => AccountCodes.LevelOf(Code); +} + +/// A VAT register of the base data. +/// The code, such as VEN1. +/// The description. +/// Sales, purchases or receipts. +/// A section for reverse-charge self-invoices. +public sealed record VatRegisterTemplate(string Code, string Description, VatRegisterKind Kind, bool ReverseCharge = false); + +/// A line of a journal template of the base data. +/// What it stands for. +/// Debit or credit for an invoice. +/// The account, by code (fixed for , default otherwise). +/// The description proposed. +public sealed record JournalTemplateLineTemplate(PostingRole Role, AccountSide Side, string? AccountCode = null, string? Description = null); + +/// A journal template (causale contabile) of the base data. +/// The code, such as FV. +/// The description. +/// The kind of operations. +/// The VAT register, for entries with VAT. +/// The entries open items of customers or suppliers. +/// Credit notes: the sides of the document are reversed. +/// The model of the lines. +public sealed record JournalTemplateTemplate( + string Code, string Description, JournalArea Area, string? VatRegisterCode, bool OpensItems, bool Reverses, IReadOnlyList Lines); + +/// Which journal template and VAT register a document type of the base data uses. +/// The document type, such as FI. +/// The journal template, such as FV. +/// The VAT register, such as VEN1. +public sealed record DocumentPostingTemplate(string DocumentTypeCode, string JournalTemplateCode, string? VatRegisterCode); + +/// +/// 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. +/// +public interface ILedgerTemplate +{ + /// The name of the model chart, such as PMI standard. + string Name { get; } + + /// The accounts, parents before children. + IReadOnlyList Accounts { get; } + + /// The VAT registers. + IReadOnlyList VatRegisters { get; } + + /// The journal templates. + IReadOnlyList JournalTemplates { get; } + + /// The template and register of the document types. + IReadOnlyList DocumentPostings { get; } + + /// The account of a role when no template line gives one (customers, suppliers, VAT, bank...). + /// The role. + /// The account code, or . + string? AccountOf(PostingRole role); +} + +/// The rules of the periodic VAT settlement and of the other tax payments of the country. +public interface IVatSettlementRules +{ + /// The smallest VAT payment; below it the debit is carried (Italy: 25.82). + decimal MinimumPayment { get; } + + /// The share of the base of the December advance with the historical and forecast methods (Italy: 88). + decimal AdvancePercent { get; } + + /// The smallest advance (Italy: 103.29). + decimal AdvanceMinimum { get; } + + /// The payment code of the VAT of a period (Italy: 6001-6012, 6031-6033, and 6099 for the last quarter). + /// The period. + /// The code. + string PaymentCode(TaxPeriod period); + + /// What the form wants in the field of the month or installment for the VAT of a period (Italy: 0101 for 6099). + /// The period. + /// The value, or . + string? PaymentPeriod(TaxPeriod period); + + /// The day the December advance is due (Italy: 27 December). + /// The year. + /// The day, past holidays. + DateOnly AdvanceDue(int year); + + /// The day withholdings of fees paid in a month are due (Italy: the 16th of the next month). + /// The year of the payment of the invoice. + /// The month. + /// The day, past holidays. + DateOnly WithholdingDue(int year, int month); + + /// The day the stamp duty of the e-invoices of a quarter is due. + /// The year. + /// The quarter, 1-4. + /// The day, past holidays. + DateOnly StampDutyDue(int year, int quarter); + + /// The day the communication of the settlements of a quarter is due (Italy: LIPE). + /// The year. + /// The quarter, 1-4. + /// The day, past holidays. + DateOnly PeriodicReturnDue(int year, int quarter); +} + +/// A period of the communication of VAT settlements (a month, or a quarter for quarterly payers). +/// The period. +/// The taxable amount of the operations issued. +/// The taxable amount of the operations received. +/// The VAT due. +/// The VAT deducted. +/// The debit below the minimum carried from the previous period. +/// The credit of the previous period. +/// The interest of quarterly payers. +/// The December advance. +/// Positive to pay, negative in credit. +public sealed record PeriodicVatReturnModule( + TaxPeriod Period, + decimal ActiveTotal, + decimal PassiveTotal, + decimal TaxDue, + decimal TaxDeducted, + decimal PreviousDebit, + decimal PreviousCredit, + decimal Interest, + decimal Advance, + decimal Balance); + +/// The communication of VAT settlements of a quarter (Italy: LIPE). +/// The year. +/// The quarter. +/// The tax code of the company. +/// The VAT number of the company, without country. +/// Who signs, when not the company (its legal representative). +/// The intermediary who sends it, if any. +/// The day of the commitment of the intermediary. +/// The months or the quarter. +public sealed record PeriodicVatReturn( + int Year, + int Quarter, + string TaxCode, + string VatNumber, + string? DeclarantTaxCode, + string? IntermediaryTaxCode, + DateOnly CommitmentDate, + IReadOnlyList Modules); + +/// Writes the file of the communication of VAT settlements (Italy: LIPE XML). +public interface IPeriodicVatReturnWriter +{ + /// The name of the communication, such as LIPE. + string Name { get; } + + /// The file name proposed. + /// The communication. + /// The name. + string FileName(PeriodicVatReturn data); + + /// Writes the file. + /// The communication. + /// The file, UTF-8. + byte[] Write(PeriodicVatReturn data); +} + +/// A line of a tax payment form (Italy: a line of the Erario section of the F24). +/// The payment code. +/// The month or installment, as the form wants it. +/// The reference year. +/// The amount due. +/// The credit used in compensation. +/// What it pays. +public sealed record TaxPaymentFormLine(string Code, string? Period, int Year, decimal Debit, decimal Credit, string Description); + +/// A tax payment form (Italy: F24) of one due date. +/// The day. +/// The tax code of the company. +/// The name of the company. +/// The lines. +public sealed record TaxPaymentForm(DateOnly DueDate, string TaxCode, string Name, IReadOnlyList Lines) +{ + /// The balance to pay. + public decimal Balance => Lines.Sum(l => l.Debit - l.Credit); +} diff --git a/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv b/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv new file mode 100644 index 0000000..4d206da --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv @@ -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;;;; diff --git a/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs b/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs new file mode 100644 index 0000000..cb71a0d --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs @@ -0,0 +1,256 @@ +using Khaemhat.Core.Accounting; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// 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 Data/piano-dei-conti.csv. +/// +public sealed class ItalianLedgerTemplate : ILedgerTemplate +{ + /// The account of trade receivables from Italian customers. + public const string Customers = "05.01.001"; + + /// The account of trade payables to Italian suppliers. + public const string Suppliers = "14.01.001"; + + /// VAT on purchases. + public const string PurchaseVat = "06.02.001"; + + /// VAT on sales. + public const string SalesVat = "15.01.001"; + + /// The VAT settlement account. + public const string VatSettlement = "15.01.002"; + + /// The main bank account. + public const string Bank = "07.01.001"; + + /// Cash. + public const string Cash = "07.02.001"; + + /// Sales of goods. + public const string Revenue = "30.01.001"; + + /// Purchases of goods. + public const string Cost = "20.01.001"; + + /// Withholdings operated on fees of self-employed workers, to pay. + public const string WithholdingPayable = "15.02.001"; + + /// Withholdings suffered on the company's fees. + public const string WithholdingCredit = "06.03.001"; + + /// Social security charged on fees. + public const string SocialSecurity = "31.01.003"; + + /// Stamp duty charged to customers. + public const string StampDutyCharged = "31.01.002"; + + /// Stamp duty as a cost. + public const string StampDutyCost = "27.01.002"; + + /// Rounding and allowances. + public const string Rounding = "27.01.004"; + + /// The interest of quarterly VAT payers. + public const string VatInterest = "28.01.003"; + + private readonly Lazy> _accounts = new(ReadAccounts); + + /// + public string Name => "PMI standard"; + + /// + public IReadOnlyList Accounts => _accounts.Value; + + /// + public IReadOnlyList 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), + ]; + + /// + public IReadOnlyList JournalTemplates { get; } = BuildTemplates(); + + /// + public IReadOnlyList DocumentPostings { get; } = BuildDocumentPostings(); + + /// + 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 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 BuildDocumentPostings() + { + var postings = new List(); + 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 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 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"); + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs index 5d17e25..39bbbe1 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs @@ -115,6 +115,40 @@ public sealed class F24Exporter : ITaxPaymentFormExporter return (2520 + quarter).ToString(System.Globalization.CultureInfo.InvariantCulture); } + /// + public string FileName(TaxPaymentForm form) + { + ArgumentNullException.ThrowIfNull(form); + return $"F24_{form.TaxCode}_{form.DueDate.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)}.csv"; + } + + /// + /// + /// 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 ER) 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. + /// + 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 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")); diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 4289fa3..be01d51 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -24,6 +24,9 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new ItalianTaxIdentifierRules()); AddFeature(new ItalianBaseTables()); AddFeature(new ItalianPlaces()); + AddFeature(new ItalianLedgerTemplate()); + AddFeature(new VatSettlementRulesIt()); + AddFeature(new LipeWriter()); // ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026). AddFeature(new ItalianBankDirectory([])); diff --git a/src/Khaemhat.Fiscal.Italy/VatSettlementRulesIt.cs b/src/Khaemhat.Fiscal.Italy/VatSettlementRulesIt.cs new file mode 100644 index 0000000..83667e6 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/VatSettlementRulesIt.cs @@ -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; + +/// +/// The Italian rules of the periodic VAT settlement and of the other payments of the ledger (issue #65, ADR 0037): +/// +/// payments below 25.82 euro are not made and move to the next period (art. 1 c. 4 DPR 100/1998); +/// the December advance is 88% of the base, not due below 103.29 euro, paid by 27 December (L. 405/1990); +/// the last quarter of quarterly payers is paid with the annual return, code 6099 installment 0101; +/// withholdings are paid by the 16th of the month after the payment of the fee; +/// the stamp duty of e-invoices of a quarter by 31 May, 30 September, 30 November and 28 February (DM 17/06/2014); +/// the communication of the settlements (LIPE) by 31 May, 16 September, 30 November and the end of February. +/// +/// Deadlines on Saturdays, Sundays and holidays move to the next working day; payments due from 1 to 20 August to the 20th. +/// +public sealed class VatSettlementRulesIt : IVatSettlementRules +{ + private readonly ItalianFiscalCalendar _calendar = new(); + + /// + public decimal MinimumPayment => 25.82m; + + /// + public decimal AdvancePercent => 88m; + + /// + public decimal AdvanceMinimum => 103.29m; + + /// + 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); + } + + /// + public string? PaymentPeriod(TaxPeriod period) + { + ArgumentNullException.ThrowIfNull(period); + return period.Periodicity == VatPeriodicity.Quarterly && period.Number == 4 ? "0101" : null; + } + + /// + public DateOnly AdvanceDue(int year) => _calendar.NextWorkingDay(new DateOnly(year, 12, 27)); + + /// + public DateOnly WithholdingDue(int year, int month) => Payment(new DateOnly(year, month, 16).AddMonths(1)); + + /// + 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)), + }); + + /// + 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); +} + +/// +/// The communication of the periodic VAT settlements (LIPE, art. 21-bis DL 78/2010) in the XML of the technical +/// specifications IVP18 of the Agenzia delle Entrate: one Modulo 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. +/// +public sealed class LipeWriter : IPeriodicVatReturnWriter +{ + /// The namespace of the schema. + public const string Namespace = "urn:www.agenziaentrate.gov.it:specificheTecniche:sco:ivp"; + + /// + public string Name => "LIPE"; + + /// + public string FileName(PeriodicVatReturn data) + { + ArgumentNullException.ThrowIfNull(data); + return string.Create(CultureInfo.InvariantCulture, $"IT{data.TaxCode}_LI_{data.Year}_T{data.Quarter}.xml"); + } + + /// + 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(); + } + + /// An amount as the schema wants it: comma and two decimals, no thousands separator. + /// The amount. + /// The text, such as 1234,50. + 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)); + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor index f4cde79..20098f2 100644 --- a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor @@ -40,7 +40,7 @@ else } - else if (IsPrices) + else if (OnlyExistingOption) { diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs index 052d287..381e634 100644 --- a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs @@ -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); diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/AccountsPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/AccountsPage.razor new file mode 100644 index 0000000..694e06e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/AccountsPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.Accounts.Title"]
+

@T["Ledger.Accounts.Heading"]

+
@T["Ledger.Accounts.Hint"]
+
+
+
+ @if (CanWrite) + { + + } +
+
+ +
+ +
+ + + @T.Format("Ledger.Accounts.Count", T.Number(_accounts.Count)) +
+
+ + + + + + + + + + + @foreach (var a in Visible) + { + + + + + + + } + +
@T["Ledger.Fields.Code"]@T["Ledger.Fields.Description"]@T["Ledger.Fields.Nature"]@T["Ledger.Fields.StatementLine"]
@a.Code@a.Description@T[LedgerScreens.EnumKey(a.Nature)]@a.StatementLine
+
+
+ +
+ @if (_editing) + { + +
+ + + + + + + + + + +
+
+ @if (_id is { } id) + { + + } + + +
+
+ } + else if (_selected is { } account) + { + + + @if (CanWrite) + { + + } + + +
+
@T["Ledger.Fields.Level"]
@T[$"Ledger.Accounts.Level{account.Level}"]
+
@T["Ledger.Fields.Nature"]
@T[LedgerScreens.EnumKey(account.Nature)]
+
@T["Ledger.Fields.Type"]
@T[LedgerScreens.EnumKey(account.Type)]
+
@T["Ledger.Fields.StatementLine"]
@(account.StatementLine ?? "-")
+
@T["Ledger.Fields.SubLedger"]
@T[account.SubLedger ? "Common.Yes" : "Common.No"]
+
+
+
+ + @if (account.Postable && Session.Permissions.Allows(LedgerPermissions.EntryRead)) + { + + + + + + + + + } + } + else + { +

@T["Ledger.Accounts.Choose"]

+ } +
+
+
+ +@code { + private const int PageSize = 30; + private IReadOnlyList _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 Visible => string.IsNullOrWhiteSpace(_search) + ? _accounts + : _accounts.Where(a => a.Code.StartsWith(_search.Trim(), StringComparison.OrdinalIgnoreCase) || a.Description.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase)); + + /// + 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; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/BalancePage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/BalancePage.razor new file mode 100644 index 0000000..2a1a52b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/BalancePage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.Balance.Title"]
+

@T["Ledger.Balance.Heading"]

+
@T["Ledger.Balance.Hint"]
+
+
+
+ + + +
+
+ + +
+ + + + + +
+ @if (_balance is { } balance) + { + + @if (balance.Lines.Count == 0) + { +

@T["Ledger.Balance.None"]

+ } + else + { +
+ + + + + + + + + + + + + + @foreach (var line in balance.Lines.Where(l => l.Level <= _level)) + { + + + + + + + + + + } + + + + + + + + + +
@T["Ledger.Fields.Account"]@T["Ledger.Fields.Description"]@T["Ledger.Balance.Opening"]@T["Ledger.Side.Dare"]@T["Ledger.Side.Avere"]@T["Ledger.Balance.Debit"]@T["Ledger.Balance.Credit"]
@line.Code@line.Description@(line.Opening == 0m ? null : LedgerScreens.Balance(T, line.Opening))@LedgerScreens.AmountText(T, line.Debit)@LedgerScreens.AmountText(T, line.Credit)@(line.Closing > 0m ? T.Money(line.Closing) : null)@(line.Closing < 0m ? T.Money(-line.Closing) : null)
@T["Ledger.Balance.Totals"]@T.Money(balance.TotalDebit)@T.Money(balance.TotalCredit)@T[balance.Result >= 0m ? "Ledger.Balance.Profit" : "Ledger.Balance.Loss"] @T.Money(Math.Abs(balance.Result))
+
+ } + } +
+
+ +@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 _centers = []; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private IReadOnlyList> CenterChoices => [.. _centers.Select(c => new KhOption(c.Id, c.Code + " · " + c.Description))]; + + private IReadOnlyList> LevelChoices => + [ + new(1, T["Ledger.Accounts.Level1"]), + new(2, T["Ledger.Accounts.Level2"]), + new(3, T["Ledger.Accounts.Level3"]), + ]; + + private IReadOnlyList 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), + ]; + + /// + 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(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 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; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/EntryPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/EntryPage.razor new file mode 100644 index 0000000..dcaf50b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/EntryPage.razor @@ -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. *@ + + + + @if (!_loaded) + { +

@T["Common.Loading"]

+ } + else + { +
+
+ +

@Title

+
+ @if (_entry is { } e) + { + @T[LedgerScreens.EnumKey(e.Status)] + @T[LedgerScreens.EnumKey(e.Source)] + @if (e.JournalNumber is { } j) + { + · @T.Format("Ledger.Entry.JournalNumber", j) + } + @if (e.ReversalOfId is { } of) + { + · @T["Ledger.Entry.ReversalOf"] + } + @if (e.ReversedById is { } by) + { + · @T["Ledger.Entry.ReversedBy"] + } + } + else + { + @T["Ledger.Entry.NewHint"] + } +
+
+
+
+ @if (Editable && CanWrite) + { + + + } + @if (_entry is { } current && CanWrite) + { + @if (current.Status != GlEntryStatus.Draft && current.ReversedById is null && current.ReversalOfId is null) + { + + } + @if (current.Status != GlEntryStatus.Final && current.Source != GlEntrySource.Document) + { + + } + } +
+
+ + + + @if (!Balanced && _lines.Any(l => l.Debit != 0m || l.Credit != 0m)) + { + + } + + +
+ + + + + + +
+
+ + + + @if (Editable) + { + + + } + + + + @foreach (var a in _accounts.Where(a => a.Postable && !a.Disabled)) + { + + } + +
+ + + + + + + + + + + + + + + @for (var i = 0; i < _lines.Count; i++) + { + var line = _lines[i]; + var n = i + 1; + var account = AccountOf(line.AccountId); + + + @if (Editable) + { + + + + + + + + } + else + { + + + + + + + + } + + } + + + + + + + + + +
#@T["Ledger.Fields.Account"]@T["Ledger.Fields.Party"]@T["Ledger.Fields.LineDescription"]@T["Ledger.Fields.CostCenter"]@T["Ledger.Side.Dare"]@T["Ledger.Side.Avere"]
@n + @if (account?.SubLedger == true) + { + + } + + + @account?.Code @account?.Description@line.Party?.Name@line.Description@_centers.FirstOrDefault(c => c.Id == line.CostCenterId)?.Code@LedgerScreens.AmountText(T, line.Debit)@LedgerScreens.AmountText(T, line.Credit)
@T["Ledger.Entry.Totals"]@T.Money(TotalDebit)@T.Money(TotalCredit)
+
+
+
+ + @if (_registerId is not null || _vat.Count > 0) + { + + + @if (Editable) + { + + } + + + + + + + + + + + + + + + @foreach (var v in _vat) + { + + @if (Editable) + { + + + + + + + } + else + { + + + + + + + } + + } + +
@T["Ledger.Fields.TaxCode"]@T["Ledger.Fields.Rate"]@T["Ledger.Fields.Taxable"]@T["Ledger.Fields.Tax"]@T["Ledger.Fields.NonDeductible"]
+ + @(v.Nature ?? v.Rate.ToString("0.##", T.Culture) + "%")@_taxCodes.FirstOrDefault(c => c.Id == v.TaxCodeId)?.Code@(v.Nature ?? v.Rate.ToString("0.##", T.Culture) + "%")@T.Money(v.Taxable)@T.Money(v.Tax)@LedgerScreens.AmountText(T, v.NonDeductible)
+
+
+ } + + + +

@T["Ledger.Entry.ReverseText"]

+
+ +
+
+
+ + +
+
+ } +
+ +@code { + private bool _loaded; + private bool _busy; + private GlEntry? _entry; + private IReadOnlyList _accounts = []; + private IReadOnlyList _templates = []; + private IReadOnlyList _registers = []; + private IReadOnlyList _taxCodes = []; + private IReadOnlyList _centers = []; + private DateOnly? _date; + private long? _templateId; + private long? _registerId; + private string? _description; + private string? _documentNumber; + private DateOnly? _documentDate; + private List _lines = []; + private List _vat = []; + private bool _reverseOpen; + private DateOnly? _reverseDate; + + /// The entry, or for a new one. + [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 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> TemplateChoices => + [.. _templates.Where(t => !t.Template.Disabled).Select(t => new KhOption(t.Template.Id, t.Template.Code + " · " + t.Template.Description))]; + + private IReadOnlyList> RegisterChoices => + [.. _registers.Where(r => !r.Disabled).Select(r => new KhOption(r.Id, r.Code + " · " + r.Description))]; + + /// + 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(actor, company); + _centers = await ActiveAsync(actor, company); + } + + await LoadAsync(actor, company); + _loaded = true; + } + + private async Task> ActiveAsync(Actor actor, string company) + where TItem : CodedEntity, new() + { + try + { + return await Tables.ActiveAsync(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() + : (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> 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; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/JournalPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/JournalPage.razor new file mode 100644 index 0000000..9d5dff3 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/JournalPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.Journal.Title"]
+

@T["Ledger.Journal.Heading"]

+
@T["Ledger.Journal.Hint"]
+
+
+
+ @if (CanWrite) + { + @T["Ledger.Journal.New"] + + } + @if (CanFinalize) + { + + } +
+
+ + + + @if (_tab == "recurring") + { + + + @if (CanWrite) + { + + + } + + + @if (_recurring.Count == 0) + { +

@T["Ledger.Recurring.None"]

+ } + else + { + + + + + + + + + + + + + + @foreach (var r in _recurring) + { + + + + + + + + + + } + +
@T["Ledger.Fields.Description"]@T["Ledger.Recurring.Frequency"]@T["Ledger.Recurring.NextDate"]@T["Ledger.Recurring.EndDate"]@T["Ledger.Recurring.Model"]@T["Ledger.Fields.Status"]
@r.Description@T[LedgerScreens.EnumKey(r.Frequency)]@T.Date(r.NextDate)@(r.EndDate is { } end ? T.Date(end) : "-")@T["Ledger.Recurring.OpenModel"]@T[r.Disabled ? "Ledger.Recurring.Suspended" : "Ledger.Recurring.Active"] + @if (CanWrite) + { + + + } +
+ } +
+
+

@T["Ledger.Recurring.Hint"]

+ } + else + { + +
+ + + + + + @T.Format("Ledger.Journal.Count", T.Number(_total)) +
+ @if (_rows.Count == 0) + { +

@T["Ledger.Journal.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var e = row.Entry; + + + + + + + + + + + } + +
@T["Ledger.Fields.Number"]@T["Ledger.Fields.Date"]@T["Ledger.Fields.Template"]@T["Ledger.Fields.Description"]@T["Ledger.Fields.Document"]@T["Ledger.Fields.Party"]@T["Ledger.Fields.Amount"]@T["Ledger.Fields.Status"]
@(e.EntryNumber ?? T["Ledger.Journal.NoNumber"])@T.Date(e.EntryDate)@e.TemplateCode@e.Description@e.DocumentNumber@row.PartyName@T.Money(e.TotalDebit) + @T[LedgerScreens.EnumKey(e.Status)] + @if (e.ReversedById is not null) + { + @T["Ledger.Journal.Reversed"] + } +
+
+
+ @T.Format("Ledger.Pager", _offset + 1, Math.Min(_offset + PageSize, _total), _total) + + + +
+ } +
+ } + + + +

@T["Ledger.Journal.FinalizeText"]

+
+ +
+
+
+ + +
+
+ + + +

@T["Ledger.Journal.PostText"]

+
+ + + +
+ @if (_report is { } report) + { +
+ +
+ @T.Format("Ledger.Journal.Posted", report.Posted) + @foreach (var failure in report.Failed) + { +
@failure
+ } +
+
+ } +
+
+ + +
+
+ + + +
+ + + + + + +
+
+
+ + +
+
+
+ +@code { + private const int PageSize = 50; + private IReadOnlyList _rows = []; + private IReadOnlyList _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 Tabs => + [ + new("entries", "book", T["Ledger.Journal.Entries"], _total), + new("recurring", "history", T["Ledger.Recurring.Title"], _recurring.Count), + ]; + + private IReadOnlyList> StatusChoices => + [.. Enum.GetValues().Select(s => new KhOption(s, T[LedgerScreens.EnumKey(s)]))]; + + /// + 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 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 action) + { + _busy = true; + try + { + await action(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], LedgerScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/LedgerGuard.razor b/src/Khaemhat.Web/Components/Pages/Ledger/LedgerGuard.razor new file mode 100644 index 0000000..d5c4c22 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/LedgerGuard.razor @@ -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) +{ +

@T["Common.Loading"]

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

@T["Ledger.NoCompany"]

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

@T["Ledger.NoModule.Title"]

+

@T["Ledger.NoModule.Lead"]

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

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+ @T["Common.BackHome"] +
+} +else +{ + @ChildContent +} + +@code { + private bool _loaded; + + /// The permission the page needs. + [Parameter, EditorRequired] + public string Permission { get; set; } = string.Empty; + + /// The page. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/MovementsTable.razor b/src/Khaemhat.Web/Components/Pages/Ledger/MovementsTable.razor new file mode 100644 index 0000000..21b52ec --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/MovementsTable.razor @@ -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. *@ +
+ + + + @if (Page is { } p) + { + @T["Ledger.Movements.Opening"]: @LedgerScreens.Balance(T, p.Opening) + } +
+@if (Page is not { } page) +{ +

@T["Common.Loading"]

+} +else if (page.TotalCount == 0) +{ +

@T["Ledger.Movements.None"]

+} +else +{ +
+ + + + + + @if (ShowAccount) + { + + } + + + + + + + + + @foreach (var m in page.Movements) + { + + + + @if (ShowAccount) + { + + } + + + + + + + } + + + + + + + + + +
@T["Ledger.Fields.Date"]@T["Ledger.Fields.Number"]@T["Ledger.Fields.Account"]@T["Ledger.Fields.Document"]@T["Ledger.Fields.Description"]@T["Ledger.Side.Dare"]@T["Ledger.Side.Avere"]@T["Ledger.Movements.Balance"]
@T.Date(m.EntryDate)@(m.EntryNumber ?? T["Ledger.Journal.NoNumber"])@m.AccountCode@m.DocumentNumber@m.Description@LedgerScreens.AmountText(T, m.Debit)@LedgerScreens.AmountText(T, m.Credit)@LedgerScreens.Balance(T, m.Balance)
@T["Ledger.Movements.Totals"]@T.Money(page.TotalDebit)@T.Money(page.TotalCredit)@LedgerScreens.Balance(T, page.Closing)
+
+
+ @T.Format("Ledger.Pager", Offset + 1, Math.Min(Offset + PageSize, page.TotalCount), page.TotalCount) + + + +
+} + +@code { + /// The page of movements, or while loading. + [Parameter] + public LedgerPage? Page { get; set; } + + /// From this day. + [Parameter] + public DateOnly? From { get; set; } + + /// Up to this day. + [Parameter] + public DateOnly? To { get; set; } + + /// The start of the period changed. + [Parameter] + public EventCallback FromChanged { get; set; } + + /// The end of the period changed. + [Parameter] + public EventCallback ToChanged { get; set; } + + /// Another page is asked, by its first movement. + [Parameter] + public EventCallback OnPage { get; set; } + + /// The first movement of the page. + [Parameter] + public int Offset { get; set; } + + /// The size of a page. + [Parameter] + public int PageSize { get; set; } = 30; + + /// Show the account of each movement (statements of a party). + [Parameter] + public bool ShowAccount { get; set; } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/PartyLedgerPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/PartyLedgerPage.razor new file mode 100644 index 0000000..6436a0e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/PartyLedgerPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.Parties.Title"]
+

@T["Ledger.Parties.Heading"]

+
@T["Ledger.Parties.Hint"]
+
+
+ + + +
+ +
+ + + @T.Format("Ledger.Parties.Total", LedgerScreens.Balance(T, _balances.Sum(b => b.Balance))) +
+ @if (_balances.Count == 0) + { +

@T["Ledger.Parties.None"]

+ } + else + { +
+ + + + + + + + + + + + @foreach (var b in _balances) + { + + + + + + + + } + +
@T["Ledger.Fields.Party"]@T["Ledger.Side.Dare"]@T["Ledger.Side.Avere"]@T["Ledger.Movements.Balance"]@T["Ledger.Parties.OpenItems"]
@b.Name@T.Money(b.Debit)@T.Money(b.Credit)@LedgerScreens.Balance(T, b.Balance)@(b.OpenItems > 0 ? T.Number(b.OpenItems) : null)
+
+ } +
+ +
+ @if (_selected is { } party) + { + + + + + + + + + + + + + + @if (_items.Count == 0) + { +

@T["Ledger.Parties.NoOpenItems"]

+ } + else + { + + + + + + + + + + + + + + @foreach (var item in _items) + { + var overdue = !item.Closed && item.DueDate < Today; + + + + + + + + + + } + +
@T["Ledger.Fields.Document"]@T["Ledger.Fields.DocumentDate"]@T["Ledger.Parties.Installment"]@T["Ledger.Parties.DueDate"]@T["Ledger.Fields.Amount"]@T["Ledger.Parties.Paid"]@T["Ledger.Parties.Residual"]
@item.DocumentNumber@T.Date(item.DocumentDate)@item.Installment@T.Date(item.DueDate)@T.Money(item.Amount)@LedgerScreens.AmountText(T, item.PaidAmount)@T.Money(item.Amount - item.PaidAmount)
+ } +
+
+ } + else + { +

@T["Ledger.Parties.Choose"]

+ } +
+
+
+ +@code { + private const int PageSize = 30; + private AccountType _type = AccountType.Customers; + private IReadOnlyList _balances = []; + private PartyBalance? _selected; + private string? _search; + private LedgerPage? _page; + private IReadOnlyList _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 Tabs => + [ + new("customers", "users", T["Ledger.Parties.Customers"]), + new("suppliers", "truck", T["Ledger.Parties.Suppliers"]), + ]; + + /// + 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; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/StampDutyPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/StampDutyPage.razor new file mode 100644 index 0000000..28cdba5 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/StampDutyPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.StampDuty.Title"]
+

@T["Ledger.StampDuty.Heading"]

+
@T["Ledger.StampDuty.Hint"]
+
+
+
+ @if (Current is { } q) + { + @T.Format("Ledger.StampDuty.QuarterBadge", q.Quarter, q.Year) + } + @if (CanConfirm) + { + + } + +
+
+ +
+ + +
+ + @if (Current is { } current) + { + + } + + + @if (_documents.Count == 0) + { +

@T["Ledger.StampDuty.None"]

+ } + else + { + + + + + + + + + + + + + @foreach (var d in _documents) + { + + + + + + + + + } + +
@T["Ledger.Fields.Document"]@T["Ledger.Fields.DocumentDate"]@T["Ledger.Fields.Party"]@T["Ledger.Fields.Taxable"]@T["Ledger.StampDuty.Duty"]@T["Ledger.StampDuty.Charge"]
@d.DocumentNumber@T.Date(d.DocumentDate)@d.PartyName@T.Money(d.Taxable)@T.Money(d.StampDuty)@T[d.Charged ? "Ledger.StampDuty.Charged" : "Ledger.StampDuty.Borne"]
+ } +
@T["Ledger.StampDuty.Footer"]
+
+ + + + + + + + + + + + + + @foreach (var q in _quarters) + { + + + + + + + + } + +
@T["Ledger.StampDuty.Quarter"]@T["Ledger.StampDuty.Invoices"]@T["Ledger.Fields.Amount"]@T["Ledger.Settlement.DueDate"]@T["Ledger.Fields.Status"]
@T.Format("Ledger.StampDuty.QuarterBadge", q.Quarter, q.Year)@q.Documents@T.Money(q.Amount)@T.Date(q.DueDate) + @if (q.Payment is { PaidOn: { } paid }) + { + @T.Format("Ledger.StampDuty.PaidOn", T.Date(paid)) + } + else if (q.Payment is not null) + { + @T["Ledger.StampDuty.InF24"] + } + else if (q.Amount > 0m) + { + @T["Ledger.StampDuty.ToRecord"] + } +
+
+
+ +@code { + private int _year; + private int _quarter; + private IReadOnlyList _quarters = []; + private IReadOnlyList _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> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList> QuarterChoices => [.. Enumerable.Range(1, 4).Select(q => new KhOption(q, T.Format("Ledger.StampDuty.QuarterBadge", q, _year)))]; + + private IReadOnlyList 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), + ]; + } + + /// + 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 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; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/TemplatesPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/TemplatesPage.razor new file mode 100644 index 0000000..013ee96 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/TemplatesPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.Templates.Title"]
+

@T["Ledger.Templates.Heading"]

+
@T["Ledger.Templates.Hint"]
+
+
+
+ @if (CanWrite) + { + + } +
+
+ +
+ + + + + + + + + + + @foreach (var view in _templates) + { + var t = view.Template; + + + + + + } + +
@T["Ledger.Fields.Code"]@T["Ledger.Fields.Description"]@T["Ledger.Fields.VatRegister"]
@t.Code@t.Description@t.VatRegisterCode
+
+ +
+ @if (_editing) + { + + @foreach (var a in _accounts.Where(a => a.Postable && !a.Disabled)) + { + + } + + +
+ + + + + + + +
+
+ + + @if (CanWrite) + { + + } + + + + + + + + + + + + + + @foreach (var line in _lines) + { + + + + + + + + } + +
@T["Ledger.Fields.Role"]@T["Ledger.Fields.Side"]@T["Ledger.Fields.Account"]@T["Ledger.Fields.LineDescription"]
+ + + + + @if (CanWrite) + { + + } +
+
+
+ @if (CanWrite) + { +
+ @if (_id is { } id) + { + + } + + +
+ } + } + else + { +

@T["Ledger.Templates.Choose"]

+ } +
+
+
+ +@code { + private IReadOnlyList _templates = []; + private IReadOnlyList _accounts = []; + private IReadOnlyList _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 _lines = []; + + private bool CanWrite => Session.Permissions.Allows(LedgerPermissions.AccountWrite); + + private IReadOnlyList> RegisterChoices => [.. _registers.Select(r => new KhOption(r.Code, r.Code + " · " + r.Description))]; + + /// + 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(value?.ToString() ?? nameof(PostingRole.Account)); + + private static void SetSide(Line line, object? value) => line.Side = Enum.Parse(value?.ToString() ?? nameof(AccountSide.Debit)); +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/VatRegistersPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/VatRegistersPage.razor new file mode 100644 index 0000000..b6b9037 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/VatRegistersPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.VatRegisters.Title"]
+

@T["Ledger.VatRegisters.Heading"]

+
@T["Ledger.VatRegisters.Hint"]
+
+
+
+ + @if (Session.Permissions.Allows(LedgerPermissions.SettlementConfirm)) + { + + } +
+
+ + @if (_registers.Count > 0) + { + + } + + @if (_view is { } view) + { + + + +
+ + + + @T.Format("Ledger.VatRegisters.Lines", T.Number(view.Rows.Count)) +
+ @if (view.Rows.Count == 0) + { +

@T["Ledger.VatRegisters.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + @foreach (var r in view.Rows) + { + + + + + + + + + + + + + } + +
@T["Ledger.Fields.Protocol"]@T["Ledger.Fields.VatDate"]@T["Ledger.Fields.Document"]@T["Ledger.Fields.DocumentDate"]@T["Ledger.Fields.Party"]@T["Ledger.Fields.Rate"]@T["Ledger.Fields.Taxable"]@T["Ledger.Fields.Tax"]@T["Ledger.Fields.NonDeductible"]@T["Ledger.Fields.Exigibility"]
@r.VatProtocol@T.Date(r.VatDate)@r.DocumentNumber@(r.DocumentDate is { } d ? T.Date(d) : null)@r.PartyName@RateText(r.Rate, r.Nature)@T.Money(r.Taxable)@T.Money(r.Tax)@LedgerScreens.AmountText(T, r.NonDeductibleTax)@(r.Exigibility == Khaemhat.Core.Tax.TaxExigibility.Immediate ? null : T["Ledger.Enums.TaxExigibility." + r.Exigibility])
+
+ } +
+ + + + + + + + + + + + + @foreach (var t in view.Totals) + { + + + + + + + } + + + + + + + + + +
@T["Ledger.Fields.Rate"]@T["Ledger.Fields.Taxable"]@T["Ledger.Fields.Tax"]@T["Ledger.Fields.NonDeductible"]
@RateText(t.Rate, t.Nature)@T.Money(t.Taxable)@T.Money(t.Tax)@LedgerScreens.AmountText(T, t.NonDeductibleTax)
@T["Ledger.VatRegisters.RegisterTotal"]@T.Money(view.Totals.Sum(t => t.Taxable))@T.Money(view.Totals.Sum(t => t.Tax))@LedgerScreens.AmountText(T, view.Totals.Sum(t => t.NonDeductibleTax))
+
+ } + else if (_registers.Count == 0) + { +

@T["Ledger.VatRegisters.NoRegisters"]

+ } + + + +

@T.Format("Ledger.VatRegisters.FinalText", _finalFrom is { } ff ? T.Date(ff) : "-", _view?.Register.PrintYear == _finalTo?.Year ? (_view?.Register.LastPage ?? 0) + 1 : 1)

+
+ +
+
+
+ + +
+
+
+ +@code { + private IReadOnlyList _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 Tabs => + [.. _registers.Where(r => !r.Disabled).Select(r => new KhTabItem(r.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), "file", r.Code + " · " + r.Description))]; + + private IReadOnlyList 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) : "-"), + ]; + + /// + 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; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/VatSettlementPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/VatSettlementPage.razor new file mode 100644 index 0000000..14c2012 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/VatSettlementPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.Settlement.Title"]
+

@T["Ledger.Settlement.Heading"]

+
@T["Ledger.Settlement.Hint"]
+
+
+
+ @PeriodName(_year, _number) + @if (_view is { } v) + { + @T[LedgerScreens.EnumKey(v.Settlement.Status)] + } +
+
+ +
+ + @if (CanConfirm) + { + @if (Confirmed) + { + + } + else + { + + } + } + + +
+ + +
+ @T["Ledger.Enums.VatPeriodicity." + _periodicity] + + + @T.Money(_view?.Settlement.PreviousCredit ?? 0m) + @T.Format("Ledger.Settlement.ProRataValue", (_view?.Settlement.ProRataPercent ?? 100m).ToString("0.##", T.Culture)) +
+
+ + @if (_view is { } view) + { + var s = view.Settlement; + + + + + + + + + + + + + + + @foreach (var line in view.Lines) + { + var register = view.Registers.GetValueOrDefault(line.VatRegisterId); + + + + + + + + + + } + +
@T["Ledger.Fields.VatRegister"]@T["Ledger.Fields.Kind"]@T["Ledger.Settlement.Documents"]@T["Ledger.Fields.Taxable"]@T["Ledger.Fields.Tax"]@T["Ledger.Fields.NonDeductible"]@T["Ledger.Settlement.Deferred"]
@register?.Code@register?.Description@line.Documents@T.Money(line.Taxable)@T.Money(line.Tax)@LedgerScreens.AmountText(T, line.NonDeductibleTax)@LedgerScreens.AmountText(T, line.DeferredTax)
+
+ +
+ +
+ @T["Ledger.Settlement.SalesTax"]@T.Money(s.SalesTax) + @T["Ledger.Settlement.PurchaseTax"]@T.Money(s.PurchaseTax) + @T["Ledger.Settlement.NonDeductibleTax"]@T.Money(s.NonDeductibleTax) + @T["Ledger.Settlement.DeferredTax"]@T.Money(s.DeferredTax) + @T["Ledger.Settlement.PreviousCredit"]@T.Money(s.PreviousCredit) + @T["Ledger.Settlement.PreviousDebit"]@T.Money(s.PreviousDebit) + @T["Ledger.Settlement.AdvancePaid"]@T.Money(s.AdvancePaid) + @T.Format("Ledger.Settlement.Interest", s.InterestPercent.ToString("0.##", T.Culture))@T.Money(s.Interest) + @if (s.AmountDue > 0m) + { + @T["Ledger.Settlement.AmountDue"]@T.Money(s.AmountDue) + } + else if (s.DebitCarried > 0m) + { + @T["Ledger.Settlement.DebitCarried"]@T.Money(s.DebitCarried) + } + else + { + @T["Ledger.Settlement.CreditCarried"]@T.Money(s.CreditCarried) + } +
+
+ +
+
@T["Ledger.Settlement.PaymentCode"]
@s.PaymentCode
+
@T["Ledger.Settlement.Year"]
@s.Year
+
@T["Ledger.Fields.Amount"]
@T.Money(s.AmountDue)
+
@T["Ledger.Settlement.DueDate"]
@(s.DueDate is { } due ? T.Date(due) : "-")
+
@T["Ledger.Settlement.Entry"]
+ @if (s.GlEntryId is { } entry) + { + @T["Ledger.Settlement.OpenEntry"] + } + else + { + - + } +
+
@T["Ledger.Settlement.LipeQuarter"]
@T.Format("Ledger.Settlement.QuarterName", QuarterOf(s), s.Year)
+
+
+ + @T["Ledger.Settlement.Telematic"] +
+
+
+ } + else + { +

@T["Ledger.Settlement.NotComputed"]

+ } + + + @if (_settlements.Count == 0) + { +

@T["Ledger.Settlement.NoneYet"]

+ } + else + { + + + + + + + + + + + + + + @foreach (var item in _settlements) + { + + + + + + + + + + } + +
@T["Ledger.Settlement.Period"]@T["Ledger.Settlement.SalesTax"]@T["Ledger.Settlement.PurchaseTax"]@T["Ledger.Settlement.AmountDue"]@T["Ledger.Settlement.CreditCarried"]@T["Ledger.Settlement.DueDate"]@T["Ledger.Fields.Status"]
@PeriodName(item.Year, item.Number)@T.Money(item.SalesTax)@T.Money(item.PurchaseTax)@(item.AmountDue == 0m ? null : T.Money(item.AmountDue))@(item.CreditCarried == 0m ? null : T.Money(item.CreditCarried))@(item.DueDate is { } due ? T.Date(due) : null)@T[LedgerScreens.EnumKey(item.Status)]
+ } +
+ + @if (CanConfirm) + { + +

@T["Ledger.Advance.Hint"]

+
+ + + + @T.Format("Ledger.Advance.BasesValue", T.Money(_bases.Historical), T.Money(_bases.Actual)) + +
+
+ + +
+
+ } +
+ +@code { + private VatPeriodicity _periodicity = VatPeriodicity.Monthly; + private int _year; + private int _number; + private VatSettlementView? _view; + private IReadOnlyList _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> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList> PeriodChoices => [.. Enumerable.Range(1, LastNumber).Select(n => new KhOption(n, PeriodName(_year, n)))]; + + /// + 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 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; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/WithholdingsPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/WithholdingsPage.razor new file mode 100644 index 0000000..132fa6b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/WithholdingsPage.razor @@ -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. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Ledger.Withholdings.Title"]
+

@T["Ledger.Withholdings.Heading"]

+
@T["Ledger.Withholdings.Hint"]
+
+
+
+ +
+
+ + + + +
+ + + @T.Format("Ledger.Withholdings.Total", T.Money(_rows.Sum(r => r.Withholding.Amount))) +
+ @if (_rows.Count == 0) + { +

@T["Ledger.Withholdings.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var w = row.Withholding; + + + + + + + + + + + + + + + } + +
@T["Ledger.Fields.Document"]@T["Ledger.Fields.DocumentDate"]@T["Ledger.Fields.Party"]@T["Ledger.Withholdings.Type"]@T["Ledger.Fields.Taxable"]@T["Ledger.Withholdings.Fund"]@T["Ledger.Withholdings.FundAmount"]@T["Ledger.Withholdings.Rate"]@T["Ledger.Fields.Amount"]@T["Ledger.Withholdings.PaidOn"]@T["Ledger.Fields.Status"]
+ @if (w.GlEntryId is { } entry) + { + @w.DocumentNumber + } + else + { + @w.DocumentNumber + } + @T.Date(w.DocumentDate)@row.PartyName@w.WithholdingType @(w.Reason is { } reason ? "· " + reason : null)@T.Money(w.Taxable)@w.SocialSecurityFund@LedgerScreens.AmountText(T, w.SocialSecurityAmount)@(w.Rate.ToString("0.##", T.Culture))% @(w.BasePercent != 100m ? T.Format("Ledger.Withholdings.On", w.BasePercent.ToString("0.##", T.Culture)) : null)@T.Money(w.Amount)@(w.InvoicePaidOn is { } paid ? T.Date(paid) : null)@T[LedgerScreens.EnumKey(w.Status)] + @if (CanConfirm) + { + @if (w.InvoicePaidOn is null) + { + + } + else if (w.Status != WithholdingStatus.Paid) + { + + } + } +
+
+ } +
@T["Ledger.Withholdings.Footer"]
+
+ +
+ + + + + @if (CanConfirm) + { + @if (_formPaid) + { + + } + else + { + + } + } + + + @if (_form is not { Lines.Count: > 0 } form) + { +

@T[_formPaid ? "Ledger.F24.AllPaid" : "Ledger.F24.None"]

+ } + else + { + + + + + + + + + + + + @foreach (var line in form.Lines) + { + + + + + + + + } + + + + + + + +
@T["Ledger.Settlement.PaymentCode"]@T["Ledger.Fields.Description"]@T["Ledger.Settlement.Period"]@T["Ledger.Side.Dare"]@T["Ledger.F24.Credit"]
@line.Code@line.Description@(line.Period is { } p ? p + "/" + line.Year : line.Year.ToString(System.Globalization.CultureInfo.InvariantCulture))@LedgerScreens.AmountText(T, line.Debit)@LedgerScreens.AmountText(T, line.Credit)
@T.Format("Ledger.F24.Total", _due is { } td ? T.Date(td) : string.Empty)@T.Money(form.Balance)
+ } +
+
+
+ + @T["Ledger.Withholdings.Note"] +
+
+ + + +

@T.Format("Ledger.Withholdings.InvoicePaidText", _paidRow?.Withholding.DocumentNumber ?? string.Empty, _paidRow?.PartyName ?? string.Empty)

+
+ +
+
+
+ + +
+
+ + + +

@T.Format("Ledger.F24.PayText", _due is { } pd ? T.Date(pd) : string.Empty, T.Money(_form?.Balance ?? 0m))

+
+ +
+
+
+ + +
+
+
+ +@code { + private string _tab = "operated"; + private int _year; + private IReadOnlyList _rows = []; + private IReadOnlyList _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 Tabs => + [ + new("operated", "users", T["Ledger.Withholdings.Operated"]), + new("suffered", "user", T["Ledger.Withholdings.Suffered"]), + new("all", "list", T["Ledger.Withholdings.All"]), + ]; + + private IReadOnlyList> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + /// + 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 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; + } + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 2e19bf2..67ff05f 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -154,6 +154,16 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); + // The ledger (ADR 0036, ADR 0037): the documents post through LedgerPoster inside the transaction of the engine. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + // The document engine (ADR 0032): one engine, the copies, a typed service per family. services.AddSingleton(); services.AddSingleton(); @@ -177,6 +187,7 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); // Companies and start. @@ -186,6 +197,8 @@ internal static class KhaemhatServices services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index bc58caf..4dbd532 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -133,6 +133,7 @@ public static class SeedCommand // The demo documents go through the document engine, after the masters they use. await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); + await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } } diff --git a/src/Khaemhat.Web/Ledger/LedgerScreens.cs b/src/Khaemhat.Web/Ledger/LedgerScreens.cs new file mode 100644 index 0000000..71c9596 --- /dev/null +++ b/src/Khaemhat.Web/Ledger/LedgerScreens.cs @@ -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; + +/// What the screens of the ledger share (SPEC §11.7, mockups 040-047 and 060): addresses, texts of enums and errors, downloads. +public static class LedgerScreens +{ + /// The address of the area. + public const string BasePath = "/contabilita"; + + /// The address of an entry. + /// The entry. + /// The address. + public static string EntryUrl(long id) => BasePath + "/prima-nota/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// The key of the text of an enum value. + /// The value. + /// The key. + public static string EnumKey(Enum value) + { + ArgumentNullException.ThrowIfNull(value); + return "Ledger.Enums." + value.GetType().Name + "." + value; + } + + /// The choices of an enum. + /// The enum. + /// The texts. + /// The choices in declaration order. + public static IReadOnlyList> Choices(ITexts texts) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v, texts[EnumKey(v)]))]; + } + + /// The text of the errors of a refused operation. + /// The texts. + /// The refusal. + /// The messages, one sentence each. + 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)); + } + + /// The tone of the state of an entry. + /// The state. + /// The tone. + public static KhTone ToneOf(GlEntryStatus status) => status switch + { + GlEntryStatus.Draft => KhTone.Warning, + GlEntryStatus.Final => KhTone.Ok, + _ => KhTone.Info, + }; + + /// A balance as the screens show it: amount and side (D or A). + /// The texts. + /// The balance, debit positive. + /// The text. + 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"]; + } + + /// Gives the browser a file made by the ledger. + /// The interop. + /// The file. + /// A task. + 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); + } + + /// Reads an amount typed with the Italian separators. + /// The texts (for the culture). + /// The text. + /// The amount, or zero. + 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; + } + + /// An amount for an input box: empty for zero. + /// The texts. + /// The amount. + /// The text. + public static string AmountText(ITexts texts, decimal amount) + { + ArgumentNullException.ThrowIfNull(texts); + return amount == 0m ? string.Empty : amount.ToString("#,##0.00", texts.Culture); + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Common.json b/src/Khaemhat.Web/Resources/it-IT/Common.json index 24043b3..e586ccd 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Common.json +++ b/src/Khaemhat.Web/Resources/it-IT/Common.json @@ -4,6 +4,8 @@ "Close": "Chiudi", "Cancel": "Annulla", "Save": "Salva", + "Edit": "Modifica", + "Delete": "Elimina", "Reset": "Ripristina", "Yes": "Sì", "No": "No", diff --git a/src/Khaemhat.Web/Resources/it-IT/Ledger.json b/src/Khaemhat.Web/Resources/it-IT/Ledger.json new file mode 100644 index 0000000..4e9ffbd --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Ledger.json @@ -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." + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index 9948edc..90c9ed4 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -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": { diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index aaa2319..097ecda 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -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")), diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 64c1bf0..53c7d36 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -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); } } diff --git a/tests/Khaemhat.Core.Tests/Accounting/LedgerRulesTests.cs b/tests/Khaemhat.Core.Tests/Accounting/LedgerRulesTests.cs new file mode 100644 index 0000000..5f84cb4 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Accounting/LedgerRulesTests.cs @@ -0,0 +1,299 @@ +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Tax; + +namespace Khaemhat.Core.Tests.Accounting; + +/// +/// 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. +/// +[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 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(() => 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); +} diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 8e4321f..84bf94f 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -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()); } diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/ItalianLedgerTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/ItalianLedgerTests.cs new file mode 100644 index 0000000..d4ca035 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/ItalianLedgerTests.cs @@ -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; + +/// +/// 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. +/// +[TestClass] +public sealed class ItalianLedgerTests +{ + private static readonly ItalyFiscalPack Pack = new(); + private static readonly ILedgerTemplate Template = Pack.Require(); + private static readonly IVatSettlementRules Rules = Pack.Require(); + + [TestMethod] + public void Chart_HasValidCodes_WithTheirParentsFirst() + { + var seen = new HashSet(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().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(); + + 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(); + + 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); + } +} diff --git a/tests/Khaemhat.Web.Tests/Ledger/DemoLedgerTests.cs b/tests/Khaemhat.Web.Tests/Ledger/DemoLedgerTests.cs new file mode 100644 index 0000000..5491407 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Ledger/DemoLedgerTests.cs @@ -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; + +/// +/// 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. +/// +[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(); + var vat = app.Services.GetRequiredService(); + var journal = app.Services.GetRequiredService(); + + // 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().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().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(); + 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().RunAsync(company, SeedKind.Base); + var ledger = app.Services.GetRequiredService(); + var journal = app.Services.GetRequiredService(); + var queries = app.Services.GetRequiredService(); + 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( + () => 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(() => 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(() => 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().RunAsync(company, SeedKind.Demo); + var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + } + + 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}")); +} diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index c30bc6b..ff40898 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -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(); + 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().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(); }