diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cf1547..6c52d8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,60 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. ## [Unreleased] +## [0.10.0] - 2026-11-13 + +M10 - Cespiti, Intrastat, chiusura, bilancio. I beni ammortizzabili hanno il loro registro con il piano civilistico e +fiscale; gli elenchi Intrastat nascono dalle fatture con il file per le Dogane; le dichiarazioni d'intento hanno un +registro e il plafond è controllato quando si conferma la fattura; a fine anno ratei, risconti e una chiusura guidata +in nove passi portano al bilancio CEE con riclassificato, indici ed export per il commercialista. + +### Added +- Cespiti (#82, ADR 0041, mockup 048): categorie con i coefficienti del DM 31/12/1988 (*Categorie standard*), conti e + aliquote civilistica e fiscale; registro con piano di ammortamento per anno, movimenti, beni già in uso con i fondi + iniziali; ammortamenti dell'anno registrati per categoria e annullabili finché non definitivi; dismissioni totali e + parziali con plusvalenza o minusvalenza; stampa del registro dei beni ammortizzabili. +- Intrastat (#83, ADR 0042, mockup 049): elenchi di cessioni e acquisti generati da fatture e note confermate (beni + raggruppati, servizi per fattura, rettifiche), righe manuali che sopravvivono alla rigenerazione, controlli di + nomenclatura, massa, partita IVA e codice CPA, periodicità dovuta dalle soglie dei quattro trimestri precedenti, + file `SCAMBI.CEE` e invio registrato con il protocollo. +- Dichiarazioni d'intento (#83, ADR 0042, mockup 061): registro cronologico delle dichiarazioni ricevute ed emesse + con protocollo telematico, plafond, utilizzato ricalcolato dalle vendite in N3.5, avviso dal 90 %, revoca e stampa; + la conferma di una fattura in N3.5 è rifiutata senza dichiarazione valida o oltre il plafond. +- Ratei e risconti (#84): inserimento con calcolo per giorni, proposta dei risconti dalle fatture di acquisto sui + costi tipicamente a cavallo dell'anno, differenze di cambio al 31/12 sulle partite in valuta. +- Chiusura guidata (#85, ADR 0043, mockup 050): controlli, ammortamenti, ratei e risconti, rimanenze al costo medio + ponderato, accantonamenti (svalutazione crediti 0,5 %, TFR), chiusura dei conti economici e patrimoniali, apertura + dell'esercizio successivo con lo storno dei ratei, stampe definitive (libro giornale, registri IVA, registro + cespiti, bilancio); ogni passo si ripete o si annulla fino alle stampe; blocco dell'esercizio. +- Bilancio (#86, ADR 0043, mockup 051): schede *CEE*, *Riclassificato* e *Indici* nella pagina *Bilancio*; schema + ordinario, abbreviato e micro con l'anno precedente e la variazione, dettaglio dei conti di ogni voce, avviso dei + conti senza voce, stato patrimoniale finanziario e conto economico a valore aggiunto, undici indici, stampa PDF ed + export ZIP per il commercialista (cinque CSV). +- Dati di esempio di fine anno (#87): apertura dei conti al 1° gennaio con cespiti, rimanenze, banca e capitale, + quattro cespiti, un risconto, la dichiarazione d'intento in uso e una cessione intracomunitaria; prova di + integrazione che chiude l'anno demo dal passo 1 al blocco su SQLite e PostgreSQL. +- Permessi `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post`, `intrastat.list.read`, + `intrastat.list.write`, `intrastat.list.export`, `sales.intent.read`, `sales.intent.write`, `ledger.year.close`, + `reports.accountant.export`. +- Tabelle `fixed_asset_categories`, `fixed_assets`, `fixed_asset_movements`, `accruals`, `closing_runs`, + `closing_steps`, `closing_prints`, `intrastat_lists`, `intrastat_list_lines`, `intent_declarations` (migrazione + `create_year_end`). +- ADR 0041, 0042 e 0043; pagine wiki *Cespiti*, *Intrastat*, *Dichiarazioni d'intento* e *Chiusura e bilancio* con + le schermate. + +### Changed +- Menu *Contabilità* con *Ratei e risconti* e *Chiusura esercizio*; menu *Cespiti* con *Categorie*; *Intrastat* e + *Dichiarazioni d'intento* attivi nel menu *Fatturazione elettronica*. +- La dichiarazione d'intento nei dati fiscali del cliente è lo specchio di quella corrente del registro; quelle + scritte prima della 0.10 entrano nel registro alla prima lettura. +- Il pacchetto fiscale espone le regole di cespiti, chiusura, Intrastat, dichiarazioni d'intento e lo schema del + bilancio CEE. + +### Known issues +- Il file `SCAMBI.CEE` non è ancora stato verificato con il software di controllo delle Dogane: controllarlo prima + del primo invio. +- Le differenze di cambio usano il residuo attuale della partita; il TFR della chiusura è una stima. + ## [0.9.0] - 2026-11-13 M9 - Fatturazione elettronica. Le fatture emesse diventano file FatturaPA controllati prima dell'invio con i codici diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index c53aef5..ea0fd4e 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -734,6 +734,36 @@ Migrazioni applicate in ordine: - `core` 20261113002 `create_ledger` (M20261113_002_CreateLedger) - `core` 20261113003 `create_treasury` (M20261113_003_CreateTreasury) - `core` 20261113004 `create_einvoicing` (M20261113_004_CreateEInvoicing) +- `core` 20261113005 `create_year_end` (M20261113_005_CreateYearEnd) + +#### `accruals` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `year` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `description` | String(200) | no | | | +| `account_id` | Int64 | no | | -> `gl_accounts` (Restrict) | +| `amount` | Decimal(19,6) | no | `0` | | +| `period_start` | Date | no | | | +| `period_end` | Date | no | | | +| `year_end` | Date | no | | | +| `adjustment` | Decimal(19,6) | no | `0` | | +| `source_family` | String(40) | sì | | | +| `source_document_id` | Int64 | sì | | | +| `document_number` | String(40) | sì | | | +| `party_id` | Int64 | sì | | | +| `gl_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) | +| `reversal_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_accruals_year` su `year` #### `attachments` @@ -909,6 +939,65 @@ Migrazioni applicate in ordine: - indice unico `ux_carriers_code` su `code` +#### `closing_prints` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `run_id` | Int64 | no | | -> `closing_runs` (Cascade) | +| `kind` | String(20) | no | | | +| `file_name` | String(100) | no | | | +| `pages` | Int32 | no | `0` | | +| `content` | Bytes | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_closing_prints_run` su `run_id` + +#### `closing_runs` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `fiscal_year_id` | Int64 | no | | -> `fiscal_years` (Restrict) | +| `year_code` | String(10) | no | | | +| `status` | String(40) | no | | | +| `next_fiscal_year_id` | Int64 | sì | | | +| `result` | Decimal(19,6) | no | `0` | | +| `locked_at` | DateTimeUtc | sì | | | +| `locked_by` | String(100) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_closing_runs_year` su `fiscal_year_id` + +#### `closing_steps` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `run_id` | Int64 | no | | -> `closing_runs` (Cascade) | +| `number` | Int32 | no | | | +| `status` | String(40) | no | | | +| `entries` | Int32 | no | `0` | | +| `amount` | Decimal(19,6) | no | `0` | | +| `messages` | Text | sì | | | +| `executed_at` | DateTimeUtc | sì | | | +| `executed_by` | String(100) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_closing_steps_number` su `run_id`, `number` + #### `code_sequences` | Colonna | Tipo | Null | Default | Note | @@ -1473,6 +1562,95 @@ Migrazioni applicate in ordine: - indice unico `ux_fiscal_years_code` su `code` - indice unico `ux_fiscal_years_start_date` su `start_date` +#### `fixed_asset_categories` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(20) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `class` | String(40) | no | | | +| `ministerial_group` | String(20) | sì | | | +| `civil_rate` | Decimal(19,6) | no | `0` | | +| `fiscal_rate` | Decimal(19,6) | no | `0` | | +| `civil_half_first_year` | Bool | no | `true` | | +| `asset_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) | +| `fund_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) | +| `depreciation_account_id` | Int64 | sì | | -> `gl_accounts` (Restrict) | +| `deductible_percent` | Decimal(19,6) | no | `100` | | +| `cost_limit` | Decimal(19,6) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_fixed_asset_categories_code` su `code` + +#### `fixed_asset_movements` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `asset_id` | Int64 | no | | -> `fixed_assets` (Cascade) | +| `kind` | String(40) | no | | | +| `movement_date` | Date | no | | | +| `year` | Int32 | no | | | +| `cost_amount` | Decimal(19,6) | no | `0` | | +| `civil_amount` | Decimal(19,6) | no | `0` | | +| `fiscal_amount` | Decimal(19,6) | no | `0` | | +| `proceeds` | Decimal(19,6) | no | `0` | | +| `gain_loss` | Decimal(19,6) | no | `0` | | +| `description` | String(200) | sì | | | +| `gl_entry_id` | Int64 | sì | | -> `gl_entries` (Restrict) | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_fixed_asset_movements_asset` su `asset_id`, `movement_date` +- indice `ix_fixed_asset_movements_year` su `year`, `kind` + +#### `fixed_assets` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(20) | no | | | +| `description` | String(200) | no | | | +| `category_id` | Int64 | no | | -> `fixed_asset_categories` (Restrict) | +| `purchase_date` | Date | no | | | +| `in_service_date` | Date | no | | | +| `supplier_id` | Int64 | sì | | -> `parties` (Restrict) | +| `document_reference` | String(60) | sì | | | +| `location` | String(100) | sì | | | +| `serial_number` | String(60) | sì | | | +| `quantity` | Decimal(19,6) | no | `1` | | +| `cost` | Decimal(19,6) | no | `0` | | +| `civil_fund` | Decimal(19,6) | no | `0` | | +| `fiscal_fund` | Decimal(19,6) | no | `0` | | +| `civil_rate` | Decimal(19,6) | sì | | | +| `fiscal_rate` | Decimal(19,6) | sì | | | +| `residual_value` | Decimal(19,6) | no | `0` | | +| `low_value` | Bool | no | `false` | | +| `status` | String(40) | no | | | +| `disposal_date` | Date | sì | | | +| `last_depreciation_year` | Int32 | sì | | | +| `notes` | String(500) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_fixed_assets_category` su `category_id` +- indice unico `ux_fixed_assets_code` su `code` + #### `gl_accounts` | Colonna | Tipo | Null | Default | Note | @@ -1539,6 +1717,7 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `closing_step` | Int32 | sì | | | - indice `ix_gl_entries_date` su `entry_date`, `number` - indice `ix_gl_entries_register` su `vat_register_id`, `vat_date` @@ -1719,6 +1898,104 @@ Migrazioni applicate in ordine: - indice unico `ux_goods_appearances_code` su `code` +#### `intent_declarations` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `direction` | String(40) | no | | | +| `register_number` | Int32 | no | | | +| `year` | Int32 | no | | | +| `party_id` | Int64 | no | | -> `parties` (Restrict) | +| `number` | String(40) | no | | | +| `declaration_date` | Date | no | | | +| `protocol` | String(40) | no | | | +| `ceiling` | Decimal(19,6) | no | `0` | | +| `used` | Decimal(19,6) | no | `0` | | +| `valid_from` | Date | no | | | +| `valid_to` | Date | no | | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `status` | String(40) | no | | | +| `notes` | String(500) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_intent_declarations_party` su `party_id`, `valid_from` +- indice unico `ux_intent_declarations_register` su `direction`, `year`, `register_number` + +#### `intrastat_list_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `list_id` | Int64 | no | | -> `intrastat_lists` (Cascade) | +| `section` | String(40) | no | | | +| `source_family` | String(40) | sì | | | +| `source_document_id` | Int64 | sì | | | +| `document_number` | String(40) | sì | | | +| `document_date` | Date | sì | | | +| `party_id` | Int64 | sì | | | +| `country_code` | String(2) | no | | | +| `vat_number` | String(20) | sì | | | +| `amount` | Decimal(19,6) | no | `0` | | +| `currency_amount` | Decimal(19,6) | sì | | | +| `statistical_value` | Decimal(19,6) | sì | | | +| `nomenclature_code` | String(10) | sì | | | +| `description` | String(200) | sì | | | +| `transaction_nature` | String(2) | sì | | | +| `delivery_terms` | String(3) | sì | | | +| `transport_mode` | String(1) | sì | | | +| `net_mass` | Decimal(19,6) | sì | | | +| `supplementary_units` | Decimal(19,6) | sì | | | +| `origin_country` | String(2) | sì | | | +| `province` | String(2) | sì | | | +| `supply_mode` | String(1) | sì | | | +| `payment_mode` | String(1) | sì | | | +| `payment_country` | String(2) | sì | | | +| `corrected_year` | Int32 | sì | | | +| `corrected_period` | Int32 | sì | | | +| `correction_sign` | String(1) | sì | | | +| `check` | String(40) | no | | | +| `manual` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_intrastat_list_lines_list` su `list_id`, `section` + +#### `intrastat_lists` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `flow` | String(40) | no | | | +| `year` | Int32 | no | | | +| `period` | Int32 | no | | | +| `periodicity` | String(40) | no | | | +| `status` | String(40) | no | | | +| `progressive` | Int32 | no | `1` | | +| `goods_amount` | Decimal(19,6) | no | `0` | | +| `services_amount` | Decimal(19,6) | no | `0` | | +| `problems` | Int32 | no | `0` | | +| `file_name` | String(60) | sì | | | +| `protocol` | String(40) | sì | | | +| `generated_at` | DateTimeUtc | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_intrastat_lists_period` su `flow`, `year`, `periodicity`, `period` + #### `inventory_document_lines` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/MODULES.md b/docs/MODULES.md index 8569de9..77a3722 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -57,10 +57,11 @@ conservati; ogni accesso residuo risponde `module_not_licensed`. | Purchases | CORE | Documenti | [Acquisti](wiki/Acquisti.md) | M6 | | Inventory | CORE | Magazzino | [Magazzino](wiki/Magazzino.md) | M6 | | Ledger | ACCT | Contabilità | [Contabilita](wiki/Contabilita.md) | M7, M10 | -| Vat | ACCT, INTRA | Contabilità | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md) | M7, M10 | +| Vat | ACCT, INTRA | Contabilità | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md) | M7, M10 (Intrastat) | +| YearEnd | ACCT (chiusura, bilancio), INTRA (Intrastat), CORE (dichiarazioni d'intento) | Contabilità | [Chiusura-e-bilancio](wiki/Chiusura-e-bilancio.md), [Dichiarazioni-d-intento](wiki/Dichiarazioni-d-intento.md) | M10 | | Assets | ASSET | Contabilità | [Cespiti](wiki/Cespiti.md) | M10 | | Finance | FIN | Contabilità (proposta) | [Scadenzario](wiki/Scadenzario.md) | M8 | -| EInvoicing | EINV | SDI/e-invoicing; E-mail/PEC | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) | M9 (dichiarazioni d'intento: M10) | +| EInvoicing | EINV | SDI/e-invoicing; E-mail/PEC | [Fatturazione-elettronica](wiki/Fatturazione-elettronica.md) | M9 | | Crm | CRM | CRM | [CRM](wiki/CRM.md) | M11 | | Services | SVC | CRM (proposta) | [Servizi](wiki/Servizi.md) | M14 (fase 2) | | Channels | CHAN | Integrazioni | [Canali-e-commerce](wiki/Canali-e-commerce.md) | M14 (fase 2) | @@ -161,12 +162,12 @@ conservati; ogni accesso residuo risponde `module_not_licensed`. |---|---| | Licenza | `ACCT` | | Responsabilità | piano dei conti (precaricato e importabile CSV/XLSX/JSON), causali, prima nota con quadratura, contabilizzazione automatica, partitari e mastrini, registrazioni ricorrenti e in valuta, ritenute e casse, ratei/risconti, chiusura e apertura, libri definitivi, bilancio di verifica, CEE e riclassificati, export per il commercialista | -| Entità | `GlAccount`, `JournalTemplate(+Line)`, `GlEntry`, `GlEntryLine`, `GlEntryVat`, `WithholdingTax`, `SocialSecurityCharge`, `AccrualDeferral`, `ClosingRun(+Step)`, `FinancialStatementLine`, `RecurringEntryTemplate` | -| Servizi | `JournalService`, `PostingEngine`, `LedgerPoster`, `PeriodLockService`, `LedgerQueries`, `PartitarioService`, `WithholdingService`, `AccrualDeferralService`, `ClosingProcedure`, `TrialBalanceService`, `FinancialStatementsService`, `RecurringEntriesService`, `ExchangeDifferenceService`, `ChartOfAccountsImportService` | +| Entità | `GlAccount`, `JournalTemplate(+Line)`, `GlEntry`, `GlEntryLine`, `GlEntryVat`, `WithholdingTax`, `SocialSecurityCharge`, `RecurringEntryTemplate`; dalla M10 (cartella `YearEnd`) `AccrualDeferral`, `ClosingRun`, `ClosingStep`, `ClosingPrint` | +| Servizi | `JournalService`, `PostingEngine`, `LedgerPoster`, `PeriodLockService`, `LedgerQueries`, `PartitarioService`, `WithholdingService`, `TrialBalanceService`, `RecurringEntriesService`, `ChartOfAccountsImportService`; dalla M10 `AccrualService` (ratei, risconti, differenze di cambio), `ClosingService` (nove passi, stampe, blocco), `FinancialStatementsService` (CEE, riclassificati, indici, export); nel pacchetto paese `ClosingRulesIt`, `CeeSchemaIt` | | Maschere e mockup | prima nota (040, 041), piano dei conti e mastrino (042), causali (043), partitario/estratto conto (044), ritenute e F24 (047), chiusura esercizio (050), bilancio CEE (051), esercizi e periodi (052) | -| Permessi | **`ledger.entry.finalize`**; proposte: `ledger.entry.read`, `ledger.entry.write`, `ledger.entry.reopen`, `ledger.account.write`, `ledger.closing.run` | +| Permessi | **`ledger.entry.finalize`**, `ledger.entry.read`, `ledger.entry.write`, `ledger.account.write`; dalla M10 `ledger.year.close` (ratei e risconti, chiusura, blocco) e `reports.accountant.export` | | Log | Contabilità | -| Wiki | [Contabilita](wiki/Contabilita.md) | +| Wiki | [Contabilita](wiki/Contabilita.md), [Chiusura-e-bilancio](wiki/Chiusura-e-bilancio.md) | | Milestone | M7 `v0.7.0` (piano dei conti, causali, prima nota, partitari, ritenute, bilancio di verifica); M10 `v0.10.0` (ratei/risconti, chiusura/apertura, libri definitivi, bilancio CEE, export commercialista) | ### 3.8 Vat — IVA, adempimenti e Intrastat @@ -175,28 +176,29 @@ conservati; ogni accesso residuo risponde `module_not_licensed`. |---|---| | Licenza | `ACCT`; parte Intrastat `INTRA` | | Responsabilità | registri IVA con protocollo e stampe definitive, liquidazione periodica (differita, per cassa, pro-rata, acconto, interessi, minimo), dati F24 e LIPE XML, bollo virtuale (dati per F24), dichiarazioni d'intento, elenchi Intrastat | -| Entità | `VatRegister`, `VatSettlement(+Line)`, `StampDutyEntry`, `IntentDeclaration`, `IntrastatDeclaration(+Line)` | +| Entità | `VatRegister`, `VatSettlement(+Line)`, `StampDutyEntry`; dalla M10 `IntentDeclaration`, `IntrastatList(+Line)` | | Servizi | `VatRegisterService`, `VatSettlementService`, `StampDutyService`, `IntentDeclarationService`, `IntrastatService`; nel pacchetto paese `VatSettlementRules`, `VatAdvanceCalculator`, `LipeWriter`, `F24Exporter`, `IntrastatExporterIt` | | Maschere e mockup | registri IVA (045, `VatRegistersPage`), liquidazione IVA/F24/LIPE (046, `VatSettlementPage`), Intrastat (049, `IntrastatPage`) | -| Permessi | **`vat.settlement.confirm`**; proposte: `vat.register.print`, `vat.register.finalize`, `vat.settlement.read`, `vat.intrastat.export` | +| Permessi | **`vat.settlement.confirm`**; proposte: `vat.register.print`, `vat.register.finalize`, `vat.settlement.read`; dalla M10 `intrastat.list.read`, `intrastat.list.write`, `intrastat.list.export`, `sales.intent.read`, `sales.intent.write` | | Log | Contabilità | | Wiki | [IVA](wiki/IVA.md), [Intrastat](wiki/Intrastat.md), [Fiscalita-italiana](wiki/Fiscalita-italiana.md) | | Milestone | M7 `v0.7.0` (registri, liquidazione, F24, LIPE, bollo); M10 `v0.10.0` (Intrastat, dichiarazioni d'intento) | Nota: SPEC elenca bollo virtuale e dichiarazioni d'intento sia in `ACCT` sia in `EINV` (§8.1), e le loro maschere -(060, 061) sotto *Fatturazione elettronica*. Proposta: i servizi stanno in `Vat`, le maschere sono raggiungibili dal -menu *Fatturazione elettronica* se `EINV` è attivo e da *Contabilità* se è attivo solo `ACCT`. Da fissare con ADR. +(060, 061) sotto *Fatturazione elettronica*. Deciso in M10 (ADR 0042): le dichiarazioni d'intento sono nel modulo base +`CORE` perché riguardano la normale fatturazione, Intrastat in `INTRA`; entrambe le pagine stanno nel menu +*Fatturazione elettronica* come nei mockup, i servizi in `Khaemhat.Application/YearEnd`. ### 3.9 Assets — Cespiti | Voce | Contenuto | |---|---| | Licenza | `ASSET` | -| Responsabilità | categorie con coefficienti ministeriali, registro beni ammortizzabili, piano di ammortamento (primo anno 50%, limiti autovetture, beni < €516,46), dismissioni con plus/minusvalenza (TD26), rivalutazioni, piano simulato, contabilizzazione annuale | +| Responsabilità | categorie con coefficienti ministeriali, registro beni ammortizzabili, piano di ammortamento civilistico e fiscale (primo anno 50%, limiti autovetture, beni < €516,46), dismissioni totali e parziali con plus/minusvalenza, registrazione annuale per categoria annullabile, stampa del registro | | Entità | `FixedAsset`, `FixedAssetCategory`, `FixedAssetMovement` | -| Servizi | `FixedAssetService`, `DepreciationService`; `DepreciationCalculator` (Core), `FixedAssetRulesIt`, `MinisterialCoefficients` | -| Maschere e mockup | registro cespiti e piano di ammortamento (048, `FixedAssetsPage`) | -| Permessi | proposte: `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post` | +| Servizi | `FixedAssetService`; `DepreciationCalculator` (Core); nel pacchetto paese le regole dei cespiti e `MinisterialCoefficients` (ADR 0041) | +| Maschere e mockup | registro cespiti e piano di ammortamento (048, `AssetsPage`), ammortamenti (`DepreciationPage`), categorie (`CategoriesPage`) | +| Permessi | `assets.asset.read`, `assets.asset.write`, `assets.depreciation.post` | | Log | Contabilità | | Wiki | [Cespiti](wiki/Cespiti.md) | | Milestone | M10 `v0.10.0` | diff --git a/docs/STATUS.md b/docs/STATUS.md index 68598e8..d5a9651 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -3,9 +3,9 @@ > Punto di ripresa per ogni sessione. Aggiornare a fine sessione. **Ultimo aggiornamento:** 2026-11-13 -**Milestone corrente:** M10 — Cespiti, Intrastat, chiusura e bilancio (issue #82-#87), da iniziare. M9 chiusa: PR in -`main`, tag `v0.9.0`, immagine e release. -**Prossimo passo:** M10 dall'issue #82. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo +**Milestone corrente:** M11 — CRM e servizi (issue #88-#91), da iniziare. M10 chiusa: PR in `main`, tag `v0.10.0`, +immagine e release. +**Prossimo passo:** M11 dall'issue #88. #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; @@ -13,18 +13,22 @@ logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e mode Da M6: schermata dell'import fatture con file caricati (serve un caricamento via CDP); nei movimenti di un articolo il numero del fornitore al posto di *DDT fornitore* senza numero; FIFO e LIFO a lotti (dopo la 1.0). Da M7: schermata del bollo virtuale (la demo non ha fatture esenti sopra 77,47 euro); import di causali e voci di -bilancio dal file `khaemhat-coa.json`; scritture delle rimanenze e libro inventari (M10); IVA per -cassa (fase 2). +bilancio dal file `khaemhat-coa.json`; libro inventari (M13); IVA per cassa (fase 2). Da M8: tracciati CBI e SEPA da provare con un home banking reale; tabella semestrale dei tassi di mora da aggiornare a gennaio e luglio (ADR 0038); blocco per fido su ordini e documenti; report di tesoreria in *Report* (M12). Da M9: schema XSD ufficiale FatturaPA al posto di quello scritto in casa (serve il permesso di scaricarlo); intermediari reali e accreditamento SdICoop (#78, ADR 0040); conformità PDF/A-3 dichiarata della copia di cortesia; -pulsanti *Carica* e *Rimuovi dati di esempio* nell'interfaccia (M12); dichiarazioni d'intento (M10). +pulsanti *Carica* e *Rimuovi dati di esempio* nell'interfaccia (M12). +Da M10: file `SCAMBI.CEE` da verificare con il software di controllo delle Dogane prima del primo invio (ADR 0042); +differenze di cambio calcolate sul residuo attuale della partita (ADR 0043); TFR stimato (retribuzioni / 13,5); +annullare il passo 2 della chiusura toglie tutti gli ammortamenti dell'anno (ADR 0041); il gruppo dichiarazione +d'intento nei dati fiscali del cliente è ora uno specchio del registro (si potrebbe renderlo di sola lettura con un +collegamento al registro); rivalutazioni senza regole guidate. ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7. -- ADR 0001-0040. +- ADR 0001-0043. - Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice). - Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid). - Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`, @@ -107,6 +111,15 @@ pulsanti *Carica* e *Rimuovi dati di esempio* nell'interfaccia (M12); dichiarazi fatturazione nei dati di esempio e rimozione dei dati di esempio guidata dallo schema (#80); wiki *Fatturazione elettronica* con le schermate (#81). #78 (scelta degli intermediari, accreditamento SdICoop) resta aperta. Test: 874 verdi in locale, anche quelli di PostgreSQL (18) con un container locale. +- **M10 (chiusa, `v0.10.0`):** cespiti con categorie ministeriali, piano civilistico e fiscale, ammortamenti per + categoria annullabili, dismissioni e registro (#82, ADR 0041); elenchi Intrastat dai documenti con periodicità dalle + soglie e file `SCAMBI.CEE`, registro delle dichiarazioni d'intento con controllo del plafond alla conferma (#83, + ADR 0042); ratei e risconti per giorni e differenze di cambio (#84); chiusura guidata in nove passi ripetibili e + annullabili con riapertura, stampe definitive e blocco (#85); bilancio CEE ordinario, abbreviato e micro con + riclassificato, indici, stampa ed export per il commercialista (#86, ADR 0043); dati di esempio di fine anno e + chiusura completa dell'anno demo come prova di accettazione (#87); wiki *Cespiti*, *Intrastat*, *Dichiarazioni + d'intento*, *Chiusura e bilancio* con le schermate. Test: 907 verdi in locale, anche quelli di PostgreSQL con un + container locale. - Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13) e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36, M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91, @@ -156,8 +169,8 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si 12. Scadenza IVA di settembre: mockup 046 la mette al 16/10/2026, mockup 047 nell'F24 del 16/11/2026 (corretto: 16/10 per i mensili). **Deciso in M7: ADR 0037, il 16 del mese successivo.** 13. Bollo sulle cessioni intracomunitarie: il mockup 060 lo addebita su N3.2, ma cessioni intra-UE ed esportazioni ne sono esenti; la regola del bollo va legata al codice IVA con esclusioni. 14. Funzioni di fase 2 nelle schermate di M7: ventilazione dei corrispettivi (046) e IVA per cassa completa sono in M14 per §20. **Confermato in M7: non implementate.** -15. Moduli ambigui: bollo e dichiarazioni d'intento sotto ACCT e EINV (§8.1); export commercialista sotto ACCT e REPORT; Intrastat e LIPE nel menu e-fattura nei mockup; §10.2 senza voce Intrastat. -16. Stato "Provvisorio" dell'esercizio nel mockup 052, non previsto da SPEC (aperto / in chiusura / chiuso). +15. Moduli ambigui: bollo e dichiarazioni d'intento sotto ACCT e EINV (§8.1); export commercialista sotto ACCT e REPORT; Intrastat e LIPE nel menu e-fattura nei mockup; §10.2 senza voce Intrastat. **Deciso in M10: dichiarazioni d'intento in CORE, Intrastat in INTRA nel menu e-fattura, export commercialista in ACCT con il permesso `reports.accountant.export` (ADR 0042, 0043).** +16. Stato "Provvisorio" dell'esercizio nel mockup 052, non previsto da SPEC (aperto / in chiusura / chiuso). **Deciso in M10: restano i tre stati di SPEC; "in chiusura" dal passo 6, "chiuso" con il blocco (ADR 0043).** 17. Codici conto incoerenti tra mockup (fornitori 05.02.001 in 040/043, 02.03.001 in 042). **Deciso in M7: ADR 0036, piano PMI standard (clienti 05.01.001, fornitori 14.01.001).** 18. Regola R-005 del mockup 072 "riapre in bozza" una fattura scartata: contrasta con l'immutabilità della fattura emessa. 19. Codice campagne `CMP-…` (068) non presente nelle maschere di §11.12. diff --git a/docs/adr/0041-cespiti.md b/docs/adr/0041-cespiti.md new file mode 100644 index 0000000..88d4094 --- /dev/null +++ b/docs/adr/0041-cespiti.md @@ -0,0 +1,45 @@ +# ADR 0041 - Cespiti: piani paralleli, registrazione per categoria e dismissioni + +- **Stato:** accettata +- **Data:** 2026-11-13 +- **Modifica:** SPEC §11.7, §21; milestone M10, issue #82; mockup 048 + +## Contesto + +SPEC §11.7 chiede il registro dei beni ammortizzabili con piano civilistico e fiscale, il calcolo e la registrazione +delle quote di fine anno, le dismissioni con plusvalenza o minusvalenza e la stampa del registro. Le regole italiane +(coefficienti del DM 31/12/1988, primo anno al 50 % ai fini fiscali, limiti delle autovetture, beni fino a 516,46 €) +devono restare nel pacchetto fiscale. La chiusura dell'esercizio (ADR 0043) deve poter registrare gli ammortamenti +come suo passo 2 e annullarli. + +## Decisione + +1. **Categorie con aliquote proprie.** Il pacchetto italiano espone `IFixedAssetRules` con le categorie standard + (`MinisterialCoefficients`): materiali con i coefficienti comuni del DM 31/12/1988, immateriali con i limiti + dell'art. 103 TUIR. La categoria dell'azienda conserva aliquota civilistica e fiscale, metà aliquota civilistica + nel primo anno, limite di costo e deducibilità, conti di cespite, fondo e ammortamento: la tabella dipende dal + settore e ogni azienda la adatta. +2. **Due piani con la stessa regola.** `DepreciationCalculator` applica le quote costanti al costo, dimezzate nel + primo anno quando richiesto, senza superare il residuo; i beni con aliquota 100 % si ammortizzano nel primo anno. + Il piano fiscale dimezza sempre il primo anno dei beni materiali. Il bene conserva fondo civilistico e fiscale; + l'aliquota del bene vuota segue la categoria. +3. **Una registrazione per anno, una riga per categoria.** Gli ammortamenti si registrano al 31/12 con origine + `FixedAsset` (quota in Dare, fondo in Avere, per categoria) e un movimento `Depreciation` per bene. L'annullamento + toglie movimenti, fondi e registrazione finché la registrazione non è definitiva. Solo la quota civilistica va in + contabilità: la differenza con la fiscale è una variazione in dichiarazione. +4. **Beni già in uso.** Un bene acquistato prima dell'avvio porta i fondi iniziali e l'ultimo esercizio già + ammortizzato con un movimento `Opening`; i fondi entrano in contabilità con la scrittura di apertura dei conti. +5. **Dismissioni senza quota dell'anno.** La dismissione (totale o parziale) toglie il costo dismesso e la quota + proporzionale del fondo, porta il prezzo sul conto *altri crediti* e la differenza a plusvalenza o minusvalenza. + Nell'anno della dismissione **non** si calcola la quota: è la scelta prudente e più semplice da verificare; chi + vuole la quota fino alla data la registra prima con una scrittura manuale. Gli ammortamenti di un anno non si + registrano se esistono già quelli di un anno successivo (`assets.later-depreciation`). + +## Conseguenze + +- Il registro, gli ammortamenti e la stampa funzionano anche senza la chiusura guidata; il passo 2 della chiusura + riusa lo stesso servizio e non duplica le quote. +- L'annullamento del passo 2 rimuove tutti gli ammortamenti dell'anno, anche quelli registrati a mano dalla pagina + Ammortamenti prima della chiusura. +- Le rivalutazioni previste dalle singole leggi restano un movimento `Revaluation` senza regole guidate: si aggiungono + quando servono. diff --git a/docs/adr/0042-intrastat-e-dichiarazioni-d-intento.md b/docs/adr/0042-intrastat-e-dichiarazioni-d-intento.md new file mode 100644 index 0000000..cb9d894 --- /dev/null +++ b/docs/adr/0042-intrastat-e-dichiarazioni-d-intento.md @@ -0,0 +1,46 @@ +# ADR 0042 - Intrastat e dichiarazioni d'intento + +- **Stato:** accettata +- **Data:** 2026-11-13 +- **Modifica:** SPEC §11.7, §8.1; milestone M10, issue #83; mockup 049 e 061 + +## Contesto + +SPEC §11.7 chiede gli elenchi Intrastat generati dai documenti con il file per le Dogane e le dichiarazioni d'intento +degli esportatori abituali con il controllo del plafond. Fino a M9 la dichiarazione d'intento era un gruppo di campi +nei dati fiscali del cliente (protocollo, data, plafond) usato solo dal file FatturaPA. Le soglie, il tracciato e il +formato del protocollo sono regole italiane. + +## Decisione + +1. **Intrastat dai documenti confermati.** `IntrastatService` legge fatture e note di credito (vendite e acquisti) + confermate nel periodo verso soggetti di un altro Stato membro: i beni sono raggruppati per controparte, + nomenclatura e natura della transazione, i servizi hanno una riga per fattura, le note di credito diventano + rettifiche. Natura `11`, consegna `DAP` e trasporto `3` sono proposti e si correggono sulla riga. Le righe manuali + sopravvivono alla rigenerazione. +2. **Periodicità e file nel pacchetto.** `IIntrastatExporter` italiano (`IntrastatExporterIt`) calcola la + periodicità dai quattro trimestri precedenti con le soglie dal 2022 (cessioni 50.000 € per categoria; acquisti di + beni 350.000 € e di servizi 100.000 €, sotto le quali non sono dovuti) e scrive il file `SCAMBI.CEE` a record di + lunghezza fissa. Un elenco con righe incomplete non si esporta; dopo l'invio, con il protocollo, è di sola lettura. +3. **Il tracciato va validato.** Il file segue le specifiche pubblicate ma non è stato provato con il software di + controllo delle Dogane: STATUS lo indica come attività aperta e la wiki chiede il controllo prima del primo invio. +4. **Registro delle dichiarazioni.** Le dichiarazioni diventano una tabella (`intent_declarations`) con direzione + (ricevute o emesse), numero di registro per anno, protocollo (`IIntentRules`: 17 cifre, trattino o barra, 6 + cifre), validità, plafond, utilizzato e stato. Il cliente conserva lo **specchio** della dichiarazione corrente + nei dati fiscali, così documenti e FatturaPA (`AltriDatiGestionali` tipo `INTENTO`) non cambiano. Le dichiarazioni + scritte nei dati fiscali prima della 0.10 vengono adottate nel registro alla prima lettura o al primo controllo. +5. **Controllo alla conferma.** `DocumentEngine` chiama `IntentDeclarationService.CheckAsync` quando conferma una + vendita con righe di natura N3.5: senza dichiarazione attiva che copre la data la conferma è rifiutata + (`intent.no-declaration`), oltre il residuo pure (`intent.ceiling-exceeded`); le note di credito restituiscono + plafond e non sono controllate. Dopo ogni conferma, annullamento o eliminazione l'utilizzato si **ricalcola** da + tutte le vendite N3.5 del cliente, ognuna sulla dichiarazione più recente che ne copre la data; dal 90 % il + registro mostra l'avviso. +6. **Moduli.** Intrastat è nel modulo **INTRA**; le dichiarazioni d'intento nel modulo base **CORE**, perché + riguardano la normale fatturazione. + +## Conseguenze + +- Il plafond è sempre coerente con le fatture, senza contatori da mantenere a mano; il costo è un ricalcolo per + cliente a ogni conferma di una vendita in N3.5. +- Il gruppo *dichiarazione d'intento* dei dati fiscali del cliente resta come specchio; il registro è la fonte. +- La trasmissione telematica (Dogane, Agenzia delle Entrate) resta fuori da Khaemhat. diff --git a/docs/adr/0043-chiusura-e-bilancio.md b/docs/adr/0043-chiusura-e-bilancio.md new file mode 100644 index 0000000..4cd403f --- /dev/null +++ b/docs/adr/0043-chiusura-e-bilancio.md @@ -0,0 +1,57 @@ +# ADR 0043 - Ratei e risconti, chiusura guidata e bilancio + +- **Stato:** accettata +- **Data:** 2026-11-13 +- **Modifica:** SPEC §11.7, §14; milestone M10, issue #84, #85, #86, #87; mockup 050 e 051 + +## Contesto + +SPEC §11.7 chiede ratei e risconti, differenze di cambio, la chiusura dell'esercizio guidata in passi ripetibili, la +riapertura, le stampe definitive, il bilancio CEE con riclassificato e indici e l'esportazione per il commercialista. +La chiusura scrive molte registrazioni che devono poter essere tolte finché i libri non sono definitivi; il bilancio +deve leggere i saldi dell'anno anche dopo la chiusura dei conti. + +## Decisione + +1. **Ratei e risconti per giorni.** `AccrualDeferral` conserva tipo, conto, importo e periodo di competenza; la + rettifica è la parte del periodo fuori dall'esercizio (risconti) o dentro (ratei), in giorni. I risconti si + propongono dalle fatture di acquisto registrate sui conti di costi tipicamente a cavallo dell'anno + (`IClosingRules.PrepaidCandidates`) con un periodo di un anno dalla data: l'utente controlla il periodo. +2. **Differenze di cambio sul residuo.** Le partite aperte in valuta si valutano al cambio dell'ultimo giorno + dell'anno sul **residuo** attuale della partita, non su quello al 31/12: per la chiusura fatta a inizio anno nuovo + la differenza è un'approssimazione accettata e documentata. +3. **Nove passi in ordine.** `ClosingService` esegue controlli, ammortamenti (ADR 0041), ratei e risconti, rimanenze + al costo medio ponderato, accantonamenti (svalutazione crediti 0,5 %, art. 106 TUIR; TFR stimato come retribuzioni + / 13,5 meno quanto già accantonato), chiusura dei conti economici con il risultato a patrimonio, chiusura dei conti + patrimoniali per conto e soggetto, apertura dell'esercizio successivo con lo storno di ratei e risconti, stampe + definitive. Ogni registrazione ha origine `Closing` (o `FixedAsset`, `Accrual`, `ExchangeDifference`) e il numero + del passo, così l'ultimo passo eseguito si **ripete** o si **annulla** togliendo esattamente le sue scritture + (prima i riferimenti, poi le registrazioni, per le chiavi esterne). +4. **Il passo 9 è il punto di non ritorno.** Rende definitive tutte le registrazioni dell'anno (numerazione del + libro giornale) e conserva i PDF di libro giornale, registri IVA, registro cespiti e bilancio CEE. Non si annulla. + Le stampe dei registri IVA nella chiusura sono quelle dell'anno: vidimazione e numerazione delle pagine restano + quelle della pagina IVA. Dopo il passo 9 il **blocco** porta l'esercizio a `Closed` e lo rende di sola lettura. +5. **Conti del pacchetto.** I conti usati (rimanenze, ratei e risconti, fondi, conti di chiusura e apertura, + risultato) sono in `IClosingRules.Accounts` del pacchetto italiano e corrispondono al piano *PMI standard*. Il + risultato si riapre nel conto *utile (perdita) dell'esercizio* (`10.02.002`); la destinazione dell'utile è una + registrazione dell'utente dopo l'approvazione. +6. **Bilancio dai saldi mappati.** `CeeSchemaIt` (`IFinancialStatementsSchema`) descrive le voci degli art. 2424 e + 2425 c.c., l'abbreviato (2435-bis) e il micro (2435-ter, con le voci dell'abbreviato), e le riclassificazioni + finanziaria e a valore aggiunto. Ogni conto porta la voce ordinaria; la natura del conto dice in quale prospetto + va. `FinancialStatementsService` **esclude le scritture dei passi 6 e 7**, così un esercizio chiuso mostra i suoi + saldi; segnala i conti con saldo senza voce. Gli indici sono undici, con formula e anno precedente. +7. **Esportazione semplice.** L'export per il commercialista è uno ZIP di cinque CSV (piano dei conti, bilancio di + verifica, movimenti, stato patrimoniale, conto economico) separati da punto e virgola: nessun formato proprietario + di software terzi. +8. **Prova di accettazione.** Il test di integrazione chiude l'anno demo su SQLite e PostgreSQL: bilancio quadrato + prima e dopo l'assestamento, conti a zero dopo il passo 7, apertura quadrata con il patrimonio uguale all'anno + precedente, stampe PDF, blocco ed export. + +## Conseguenze + +- Una correzione dopo un passo avanzato richiede di annullare i passi a ritroso: è più lungo ma ogni stato intermedio + resta coerente e verificabile. +- L'annullamento del passo 2 toglie tutti gli ammortamenti dell'anno (ADR 0041). +- Il TFR è una stima utile solo se le paghe non lo accantonano già; con le paghe esterne la chiusura non aggiunge + nulla. +- Il libro inventari non è tra le stampe: arriva con i report (M13). diff --git a/docs/wiki/Cespiti.md b/docs/wiki/Cespiti.md index db054fa..c5bd0cc 100644 --- a/docs/wiki/Cespiti.md +++ b/docs/wiki/Cespiti.md @@ -1,113 +1,142 @@ # Cespiti -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M10) -> **Modulo di licenza:** ASSET · **Permessi principali:** `assets.asset.write`, `assets.depreciation.post`, `assets.asset.dispose` · **Specifica:** SPEC §11.7, §14 +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) +> **Modulo di licenza:** ASSET · **Permessi principali:** `assets.asset.read` (registro, piano, stampe), +> `assets.asset.write` (cespiti, categorie, dismissioni), `assets.depreciation.post` (registrare e annullare gli +> ammortamenti) · **Specifica:** SPEC §11.7, §14, ADR 0041 -## A cosa serve - -Il modulo Cespiti tiene il **registro dei beni ammortizzabili**: anagrafica dei beni, categorie con coefficienti, -piano di ammortamento civilistico e fiscale, calcolo e contabilizzazione delle quote annuali, dismissioni con -plusvalenza o minusvalenza, rivalutazioni e stampa del registro. +Il modulo Cespiti tiene il **registro dei beni ammortizzabili**: le categorie con i coefficienti ministeriali, i beni +con il piano di ammortamento civilistico e fiscale, la registrazione delle quote di fine anno, le dismissioni con la +plusvalenza o la minusvalenza e la stampa del **registro dei beni ammortizzabili** (libro cespiti). ## Dove si trova -Menu laterale **Cespiti**, con le voci **Registro cespiti**, **Ammortamenti**, **Categorie**. - -## Schermate - -![048 · Registro cespiti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/048-cespiti-registro.png) -*Mockup 048 — registro dei beni con categoria, coefficiente, data di acquisto, costo storico, fondo, residuo, quota dell'anno e stato; sotto, il piano di ammortamento del cespite selezionato (civilistico e fiscale) e la scheda con conti, fattura di acquisto, deducibilità e ubicazione (anteprima ridotta)* +Menu laterale **Cespiti**, con tre voci: **Registro cespiti**, **Ammortamenti**, **Categorie**. Gli ammortamenti si +registrano anche dal passo 2 della [chiusura dell'esercizio](Chiusura-e-bilancio). ## Il registro -| Colonna | Significato | +![Khaemhat 0.10.0 · registro cespiti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/cespiti-registro.png) +*Il registro dell'azienda demo: quattro beni con categoria, aliquota, entrata in funzione, costo storico, fondo e +valore netto; sotto, il piano di ammortamento del furgone selezionato e il dettaglio con i movimenti.* + +La striscia in alto riassume i cespiti **attivi**, il **costo storico**, il **fondo** e il **valore netto**. Si filtra +per testo (codice, descrizione, matricola), esercizio, categoria e stato. Un clic sulla riga apre sotto: + +- il **piano di ammortamento**: per ogni esercizio il fondo iniziale, l'aliquota, la quota civilistica e quella + fiscale, il fondo e il valore netto a fine anno; l'anno scelto nei filtri è evidenziato; +- il **dettaglio**: categoria, data di acquisto, fornitore e documento, ubicazione, fondo fiscale, ultimo esercizio + ammortizzato e l'elenco dei **movimenti** (acquisto, apertura, incremento, rivalutazione, ammortamento, + dismissione); da qui **Modifica**, **Dismetti** ed **Elimina**. + +| Stato | Significato | |---|---| -| **Codice** | automatico, maschera `CESP-{seq:0000}` (es. `CESP-0041`; vedi [Tabelle azienda](Tabelle-azienda)) | -| Descrizione, Categoria, Coeff. | il coefficiente viene dalla categoria | -| Acquisto | data di entrata in funzione / acquisto | -| Costo storico, Fondo, Residuo | valori alla data | -| Quota anno | quota di ammortamento dell'esercizio | -| Stato | *In uso*, *Primo anno (50 %)*, *Limite fiscale raggiunto*, *Ammortizzato*, *Dismesso* (con plus o minusvalenza) | +| **In ammortamento** | il bene ha ancora un valore da ammortizzare | +| **Ammortizzato** | il fondo ha raggiunto il costo (meno l'eventuale valore residuo) | +| **Dismesso** | il bene è uscito dal patrimonio; resta nel registro con il movimento di dismissione | -Filtri per esercizio, categoria e stato. In testa un avviso ricorda se gli ammortamenti dell'anno non sono ancora -contabilizzati. Il pannello **Dati cespite** mostra categoria e coefficiente, **conto cespite**, **conto fondo**, -**conto quota** (ammortamento), fattura di acquisto, percentuale di deducibilità e ubicazione. +## Inserire un cespite -Un cespite nasce di solito dalla **fattura di acquisto** (righe con articolo di tipo *cespite*, vedi -[Acquisti](Acquisti)) oppure si inserisce a mano con **+**. +1. **Registro cespiti → Nuovo cespite**. +2. Scegli la **categoria** (aliquote e conti vengono da lì) e scrivi la descrizione. Il **codice** vuoto prende il + prossimo numero; la matricola e l'ubicazione sono facoltative. +3. Indica **data di acquisto** e **data di entrata in funzione**: l'ammortamento parte dall'anno di entrata in + funzione, che non può precedere l'acquisto. +4. Scrivi il **costo** e, se serve, il valore residuo. Le aliquote civilistica e fiscale vuote seguono la categoria; + compilale solo per il singolo bene. +5. Per un bene acquistato **prima dell'avvio di Khaemhat** indica i **fondi iniziali** (civilistico e fiscale) e + l'**ultimo esercizio già ammortizzato** fuori da Khaemhat: i fondi entrano con la scrittura di apertura dei conti. + Facoltativi anche quantità, fornitore, documento di acquisto, ubicazione e matricola. +6. Salva. Il piano si ricalcola subito. + +Un cespite con ammortamenti già registrati non si elimina: si dismette. ## Categorie e coefficienti -Le **categorie** sono caricate con i dati di base e riportano i coefficienti della tabella ministeriale (**DM 31 -dicembre 1988**), per esempio fabbricati industriali, macchinari, automezzi, autovetture, macchine elettroniche -d'ufficio. Per ogni categoria si impostano: +![Khaemhat 0.10.0 · categorie cespiti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/cespiti-categorie.png) +*Le categorie standard create dal pacchetto fiscale italiano, con le aliquote e i conti di cespite, fondo e quota.* -- coefficiente fiscale e coefficiente civilistico (possono differire); -- conti contabili (cespite, fondo, quota, plus/minusvalenze); -- eventuale **limite di costo fiscalmente rilevante** e **percentuale di deducibilità** (vedi autovetture); -- se applicare la riduzione al 50 % nel primo esercizio. +**Cespiti → Categorie → Categorie standard** crea le categorie più comuni con i coefficienti della tabella allegata +al **DM 31/12/1988** (fabbricati, impianti, attrezzature, mobili, macchine d'ufficio elettroniche, autocarri, +autovetture, software e altri beni immateriali con i limiti dell'art. 103 TUIR). La tabella dipende dal settore di +attività: ogni aliquota si può cambiare sulla propria categoria. -## Regole di ammortamento +| Campo | A cosa serve | +|---|---| +| **Tipo** | materiale o immateriale (decide la voce di bilancio del fondo) | +| **Aliquota civilistica** e **fiscale** | la quota annua in percentuale; la fiscale non supera il coefficiente ministeriale | +| **Metà aliquota civilistica nel primo esercizio** | applica la riduzione al 50 % anche al piano civilistico (quello fiscale la applica sempre) | +| **Limite di costo** e **deducibilità %** | per le autovetture (art. 164 TUIR): ad esempio 18.075,99 di costo e 20 % di deducibilità | +| **Conto del cespite**, **del fondo**, **dell'ammortamento** | i conti della scrittura di fine anno e della dismissione | + +## Regole di calcolo | Regola | Come la applica Khaemhat | |---|---| -| **Primo anno al 50 %** | nell'esercizio di entrata in funzione la quota fiscale è la metà di quella ordinaria | -| **Civilistico e fiscale** | due piani paralleli (quota e fondo civilistici, quota e fondo fiscali); le differenze restano visibili nel piano | -| **Autovetture** | limite al costo fiscalmente rilevante e deducibilità ridotta secondo la normativa (art. 164 TUIR); i valori sono parametri della categoria, oggi € 18.075,99 di costo massimo per le autovetture a uso promiscuo, e vanno verificati a ogni aggiornamento normativo | -| **Beni di costo non superiore a € 516,46** | possono essere ammortizzati interamente nell'esercizio di acquisto | -| **Fine ammortamento** | la quota si azzera quando il residuo arriva a zero (stato *Ammortizzato*) | +| **Quote costanti** | aliquota per costo, mai più di quanto resta da ammortizzare | +| **Primo anno al 50 %** | nel piano fiscale sempre; nel civilistico se la categoria lo chiede | +| **Civilistico e fiscale** | due piani paralleli; la differenza è una variazione in dichiarazione dei redditi e non genera scritture | +| **Beni di costo unitario fino a 516,46 €** | si mettono in una categoria con aliquota 100 %: sono ammortizzati per intero nel primo anno | +| **Fine ammortamento** | quando il fondo raggiunge il costo il bene passa a *Ammortizzato* | -Il **piano di ammortamento** (riquadro in basso nel mockup) elenca per ogni esercizio quota e fondo civilistici, -quota e fondo fiscali, residuo e stato: *Contabilizzato* per gli anni registrati, *Simulato* per quelli futuri. +## Ammortamenti di fine anno -## Piano simulato +![Khaemhat 0.10.0 · ammortamenti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/cespiti-ammortamenti.png) +*Gli ammortamenti 2026 dell'azienda demo prima della registrazione: quote civilistiche e fiscali per cespite e +totali.* -Il piano degli esercizi futuri è sempre una **simulazione**: cambia se si modificano coefficiente, valore o date. -Serve a prevedere le quote dei prossimi anni (budget, bilancio previsionale) senza produrre registrazioni. +1. **Cespiti → Ammortamenti**, scegli l'esercizio. +2. Controlla le quote: la striscia mostra il totale civilistico, quello fiscale e la loro differenza. +3. **Registra ammortamenti** scrive una registrazione al 31/12 con una riga per categoria (quota in Dare sul conto di + ammortamento, fondo in Avere) e aggiorna fondi e movimenti dei beni. +4. Finché le registrazioni non sono definitive, **Annulla registrazione** toglie la scrittura e riporta i fondi + indietro. -## Calcolo e contabilizzazione annuale - -1. **Cespiti → Registro cespiti**, scegli l'esercizio e premi **Calcola ammortamenti AAAA**. -2. Controlla le quote calcolate e gli stati (primo anno, limite fiscale raggiunto…). -3. Premi **Contabilizza**: viene generata la registrazione con causale **AMM** (quote a costo, fondi in avere). -4. Le quote dell'esercizio risultano *Contabilizzate* nel piano. - -Il calcolo è anche il passo 2 della [chiusura dell'esercizio](Contabilita) e la procedura **Ammortamenti** del catalogo -([Automazioni](Automazioni)). La procedura è idempotente: rieseguirla non duplica le quote. +Il passo 2 della [chiusura](Chiusura-e-bilancio) registra gli ammortamenti se non sono già stati registrati qui. ## Dismissioni -1. Apri il cespite e scegli l'azione di dismissione (per esempio vendita o eliminazione; l'elenco dei tipi di - movimento sarà fissato in sviluppo). -2. Se è una **vendita**, Khaemhat propone la fattura di **cessione cespite (TD26)** in [Vendite](Vendite). -3. Alla data di dismissione calcola la quota dell'anno, chiude fondo e costo e rileva la **plusvalenza** o la - **minusvalenza** sui conti della categoria. -4. Il cespite passa allo stato *Dismesso* e resta nel registro. +1. Seleziona il cespite e premi **Dismetti**. +2. Indica data e **prezzo** (la contropartita è il conto *altri crediti*, che si chiude con l'incasso o con la + fattura). Il **costo dismesso** vuoto significa dismissione totale; un importo minore è una dismissione parziale. +3. Khaemhat toglie dai conti il costo e la quota corrispondente del fondo, porta il prezzo sulla contropartita e la + differenza a **plusvalenza** o **minusvalenza** (conti del pacchetto fiscale). +4. Nell'anno della dismissione non si calcola la quota di ammortamento (scelta prudente spiegata nell'ADR 0041): se + serve, registra prima gli ammortamenti fino alla data con una registrazione manuale. -## Rivalutazioni +La fattura di vendita del bene si emette come una normale fattura in [Vendite](Vendite). -Le **rivalutazioni** aumentano il valore del bene (e, a seconda della norma, il fondo) da una data; il piano di -ammortamento si ricalcola da quella data. Le modalità di ogni specifica legge di rivalutazione saranno definite in -sviluppo quando servono. +## Stampa del registro -## Registro dei beni ammortizzabili +**Stampa registro** (dal registro o dagli ammortamenti) produce il PDF del registro dei beni ammortizzabili +dell'esercizio, con costo, fondo, quota e valore netto per categoria. La stampa definitiva è una delle stampe del +passo 9 della [chiusura](Chiusura-e-bilancio). -**Registro cespiti** stampa il registro dei beni ammortizzabili (provvisorio o definitivo). La stampa definitiva è -uno dei passi della [chiusura dell'esercizio](Contabilita). Il registro si esporta anche in XLSX e PDF. +## Dati di esempio + +I dati dimostrativi creano le categorie standard e quattro beni (un furgone, scaffalature, arredi già in uso con i +fondi iniziali, e un server acquistato nell'anno con la sua registrazione), così il registro, gli ammortamenti e la +chiusura si possono provare subito. Vedi [Dati di base e di esempio](Dati-di-base-e-esempio). ## Permessi e licenza -Serve il modulo **ASSET**; per contabilizzare servono anche ACCT e i permessi di prima nota. I codici dei permessi in -testa sono indicativi (convenzione `modulo.entità.azione`, SPEC §7.2) e saranno fissati in sviluppo. +| Permesso | Consente | +|---|---| +| `assets.asset.read` | registro, piano, ammortamenti (sola lettura), stampe | +| `assets.asset.write` | inserire, modificare, eliminare e dismettere cespiti; categorie | +| `assets.depreciation.post` | registrare e annullare gli ammortamenti | + +Serve il modulo **ASSET**; le registrazioni richiedono anche **ACCT**. ## Domande frequenti -**Ho contabilizzato e poi corretto un coefficiente.** Annulla la registrazione AMM (storno) e rilancia il calcolo: -la procedura ricalcola le quote dell'esercizio. +**Ho registrato gli ammortamenti e poi corretto un'aliquota.** Annulla la registrazione, correggi e registra di nuovo: +è possibile finché la registrazione non è definitiva. -**Il bene è in uso da metà anno: la quota fiscale è ridotta?** Sì, se la categoria applica il primo anno al 50 %. +**Perché la quota fiscale è diversa dalla civilistica?** Le aliquote possono differire e il primo anno al 50 % vale +sempre per il fiscale; la differenza si gestisce in dichiarazione dei redditi. ## Pagine correlate -[Contabilità](Contabilita) · [Acquisti](Acquisti) · [Vendite](Vendite) · [IVA](IVA) · [Automazioni](Automazioni) · -[Report](Report) · [Fiscalità italiana](Fiscalita-italiana) +[Chiusura e bilancio](Chiusura-e-bilancio) · [Contabilità](Contabilita) · [Acquisti](Acquisti) · [Vendite](Vendite) · +[Fiscalità italiana](Fiscalita-italiana) diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index f428174..68bfc5e 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -1,6 +1,6 @@ # Changelog -> **Stato:** completa per 0.9.0 · **Ultima revisione:** 2026-11-13 +> **Stato:** completa per 0.10.0 · **Ultima revisione:** 2026-11-13 Le novità di ogni versione sono nel file [`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository @@ -11,6 +11,7 @@ Le novità di ogni versione sono nel file | Versione | Data | Contenuto | |---|---|---| +| 0.10.0 | 2026-11-13 | M10 — Cespiti, Intrastat, chiusura, bilancio: categorie con i coefficienti ministeriali, registro cespiti con piano civilistico e fiscale, ammortamenti e dismissioni; elenchi Intrastat dai documenti con periodicità dalle soglie e file SCAMBI.CEE; registro delle dichiarazioni d'intento con plafond controllato alla conferma della fattura; ratei, risconti e differenze di cambio; chiusura guidata in nove passi con riapertura, stampe definitive e blocco; bilancio CEE ordinario, abbreviato e micro con riclassificato, indici ed export per il commercialista | | 0.9.0 | 2026-11-13 | M9 — Fatturazione elettronica: file FatturaPA con controllo prima dell'invio e i codici dello SDI; canali PEC, SdICoop e due intermediari con regole di instradamento e canale di riserva; lettura dei canali ogni 15 minuti e ricezione push di SdICoop; notifiche che aggiornano file e documenti; correzione degli scarti; copia di cortesia PDF con l'XML allegato; fatture ricevute da registrare; pacchetti per la conservazione; fatturazione elettronica nei dati di esempio e rimozione dei dati di esempio. | | 0.8.0 | 2026-11-13 | M8 — Scadenzario e tesoreria: partite aperte con aging, incassi e pagamenti con abbuoni, spese e differenze cambio; distinte RiBa, SDD e bonifici SEPA con insoluti, mandati SDD; riconciliazione bancaria CSV, CBI e CAMT.053 con abbinamento automatico; solleciti con interessi di mora; flusso di cassa; tesoreria nei dati di esempio. | | 0.7.0 | 2026-11-13 | M7 — Contabilità generale e IVA: piano dei conti PMI a tre livelli, causali, prima nota con registrazioni provvisorie, definitive e storni, ricorrenti; contabilizzazione automatica di fatture, note e autofatture con righe IVA, partite e ritenute; registri IVA con stampa definitiva, liquidazione mensile o trimestrale con acconto, F24 e LIPE; ritenute d'acconto e dati CU; bollo virtuale; partitari, mastrini, bilancio di verifica e libro giornale; contabilità nei dati di esempio. | diff --git a/docs/wiki/Chiusura-e-bilancio.md b/docs/wiki/Chiusura-e-bilancio.md new file mode 100644 index 0000000..d137970 --- /dev/null +++ b/docs/wiki/Chiusura-e-bilancio.md @@ -0,0 +1,157 @@ +# Chiusura dell'esercizio e bilancio + +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) +> **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.year.close` (ratei e risconti, chiusura, blocco), +> `ledger.entry.read` (bilancio), `reports.accountant.export` (esportazione per il commercialista) · **Specifica:** +> SPEC §11.7, ADR 0043 + +A fine anno la contabilità va **assestata** (ammortamenti, ratei e risconti, rimanenze, accantonamenti), **chiusa** +(conti economici e patrimoniali) e **riaperta** nell'esercizio successivo; poi si stampano i libri definitivi e si +redige il **bilancio**. Khaemhat guida tutto in **nove passi**, ognuno ripetibile e annullabile fino alle stampe +definitive, e mostra il bilancio CEE, il riclassificato e gli indici in ogni momento dell'anno. + +## Dove si trova + +Menu **Contabilità**: **Ratei e risconti**, **Chiusura esercizio**, **Bilancio** (schede *Verifica*, *CEE*, +*Riclassificato*, *Indici*). Gli ammortamenti stanno in [Cespiti](Cespiti). + +## Ratei e risconti + +![Khaemhat 0.10.0 · ratei e risconti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/ratei-risconti.png) +*I ratei e risconti 2026 dell'azienda demo: il risconto attivo del premio di assicurazione del furgone, pagato il +1° ottobre per dodici mesi, di cui 273 giorni su 365 sono di competenza del 2027.* + +I costi e i ricavi che stanno a cavallo di due esercizi si ripartiscono **per giorni**: + +| Tipo | Quando | Scrittura al 31/12 | +|---|---|---| +| **Rateo attivo** | ricavo di competenza dell'anno che si incasserà dopo | ratei attivi in Dare, ricavo in Avere | +| **Rateo passivo** | costo di competenza dell'anno che si pagherà dopo | costo in Dare, ratei passivi in Avere | +| **Risconto attivo** | costo già registrato, in parte di competenza dell'anno dopo | risconti attivi in Dare, costo in Avere | +| **Risconto passivo** | ricavo già registrato, in parte di competenza dell'anno dopo | ricavo in Dare, risconti passivi in Avere | + +1. **Contabilità → Ratei e risconti**, scegli l'esercizio. +2. **Proponi dai documenti** crea i risconti delle fatture di acquisto registrate sui conti di costi che di solito + stanno a cavallo dell'anno (assicurazioni, affitti, leasing, noleggi, software, abbonamenti), con un periodo di + dodici mesi dalla data del documento: **controlla sempre il periodo**. Un costo già proposto non si ripropone. +3. **Nuovo rateo o risconto** per inserirne uno a mano: tipo, conto, descrizione, importo totale e periodo di + competenza. La **rettifica** si calcola subito (giorni fuori dall'esercizio su giorni totali). +4. Un clic sulla riga la modifica o la elimina, finché la chiusura non l'ha registrata. + +Sotto, **Differenze di cambio al 31/12** elenca le partite aperte in valuta con il residuo in valuta, il cambio del +documento, il cambio dell'ultimo giorno dell'anno (da *Tabelle azienda → Valute*, aggiornato anche dai cambi BCE) e +l'**utile o perdita su cambi**. Se il cambio manca la riga lo segnala. + +Il **passo 3** della chiusura registra ratei, risconti e differenze di cambio; il **passo 8** li storna il primo giorno +dell'esercizio successivo. + +## La chiusura guidata + +![Khaemhat 0.10.0 · chiusura esercizio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/chiusura-esercizio.png) +*La chiusura 2026 dell'azienda demo con i nove passi eseguiti: per ognuno le registrazioni, l'importo, l'esito e chi +l'ha eseguito; sotto, le stampe definitive da scaricare.* + +**Contabilità → Chiusura esercizio**, scegli l'esercizio e premi **Esegui passo N**. I passi si eseguono **in +ordine**; l'ultimo eseguito si può **ripetere** (dopo una correzione) o **annullare** (le sue registrazioni +spariscono) finché non si arriva alle stampe definitive. In alto i badge mostrano lo stato degli esercizi (*aperto*, +*in chiusura*, *chiuso*). + +| # | Passo | Cosa fa | +|---|---|---| +| 1 | **Controlli preliminari** | nessuna registrazione provvisoria, registrazioni quadrate, bilancio di verifica in pareggio; segnala i conti con saldo senza voce di bilancio, l'esercizio non ancora terminato e gli esercizi precedenti ancora aperti. L'importo è il risultato provvisorio | +| 2 | **Ammortamenti** | registra le quote civilistiche dei [cespiti](Cespiti), una riga per categoria, se non sono già registrate | +| 3 | **Ratei e risconti** | registra ratei, risconti e differenze di cambio al 31/12 | +| 4 | **Rimanenze finali** | storna le rimanenze iniziali a costo e carica le rimanenze finali di [magazzino](Magazzino) al **costo medio ponderato** | +| 5 | **Accantonamenti** | svalutazione crediti dello **0,5 %** dei crediti verso clienti aperti (limite dell'art. 106 TUIR) e quota **TFR** dell'anno (retribuzioni diviso 13,5, meno quanto già accantonato dalle paghe) | +| 6 | **Chiusura conti economici** | gira costi e ricavi a *Conto economico* e porta il **risultato** (utile o perdita) a patrimonio netto; l'esercizio passa a *in chiusura* | +| 7 | **Chiusura conti patrimoniali** | chiude attività e passività a *Stato patrimoniale finale*, per conto e per cliente o fornitore | +| 8 | **Apertura esercizio successivo** | crea l'esercizio se manca, riapre i conti con *Stato patrimoniale iniziale* (partite di clienti e fornitori comprese) e storna ratei e risconti | +| 9 | **Stampe definitive** | rende **definitive** tutte le registrazioni dell'anno, numera il libro giornale e conserva le stampe: libro giornale, registri IVA, registro cespiti, bilancio CEE | + +Accanto a ogni passo compaiono i messaggi: in grigio le informazioni, in arancione ciò che va verificato, in rosso gli +errori che bloccano (il passo 1 con un errore non lascia proseguire). + +![Khaemhat 0.10.0 · controlli preliminari](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/chiusura-controlli.png) +*Il passo 1 eseguito a novembre: tutto quadra, ma l'esercizio non è ancora terminato e la chiusura risulta +anticipata (esito «Da verificare»).* + +### Prima del passo 9 + +Il passo 9 **non si annulla**: prima controlla il bilancio, i registri IVA (le stampe dei registri dentro la chiusura +sono quelle dell'anno; per la vidimazione e la numerazione delle pagine fa fede [IVA](IVA)), i cespiti e i ratei. +Le registrazioni del nuovo esercizio si possono fare anche durante la chiusura. + +### Blocco dell'esercizio + +Dopo il passo 9 **Blocca esercizio** chiude definitivamente l'anno: diventa di **sola lettura** e non si può più +registrare nulla con data fino al 31/12. L'esercizio passa a *chiuso*. + +## Bilancio CEE + +![Khaemhat 0.10.0 · bilancio CEE](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/bilancio-cee.png) +*Il bilancio CEE 2026 dell'azienda demo, schema ordinario: stato patrimoniale e conto economico con l'anno +precedente e la variazione percentuale.* + +**Contabilità → Bilancio → CEE** costruisce lo **stato patrimoniale** (art. 2424 c.c.) e il **conto economico** +(art. 2425 c.c.) dell'esercizio scelto, con l'anno precedente e la variazione, dai saldi dei conti a cui il piano dei +conti associa una **voce di bilancio** (vedi [Contabilità](Contabilita#piano-dei-conti)). + +- **Schema**: *Ordinario*, *Abbreviato* (art. 2435-bis) o *Micro-impresa* (art. 2435-ter, stesse voci + dell'abbreviato). +- La striscia mostra totale attivo e passivo, risultato d'esercizio e quadratura. +- Se ci sono conti con saldo **senza voce**, un avviso li elenca: assegna la voce nel piano dei conti. +- Un clic su una voce mostra i **conti** che la compongono con i saldi dei due anni. +- Le scritture dei passi 6 e 7 della chiusura non entrano nel calcolo: un esercizio chiuso mostra comunque i suoi + saldi. +- **Stampa bilancio** produce il PDF; **Esporta per il commercialista** scarica uno ZIP con cinque file CSV (piano + dei conti, bilancio di verifica, movimenti, stato patrimoniale, conto economico). + +## Riclassificato e indici + +![Khaemhat 0.10.0 · riclassificato](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/bilancio-riclassificato.png) +*Lo stato patrimoniale riclassificato secondo il criterio finanziario.* + +La scheda **Riclassificato** propone lo **stato patrimoniale finanziario** (attivo per liquidità, passivo per +esigibilità) e il **conto economico a valore aggiunto**. + +![Khaemhat 0.10.0 · indici](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/bilancio-indici.png) +*Gli indici di bilancio con la formula e il valore dei due anni.* + +La scheda **Indici** calcola redditività (ROE, ROI, ROS, rotazione del capitale investito), liquidità (indice di +disponibilità e di liquidità), solidità (indipendenza finanziaria, leva, copertura delle immobilizzazioni) e i giorni +medi di incasso e di pagamento. Un indice senza denominatore mostra un trattino. + +## Prova con i dati di esempio + +I dati dimostrativi aprono l'anno con una scrittura di apertura (cespiti e fondi, rimanenze, banca, capitale), +registrano un premio di assicurazione da riscontare e i cespiti: la chiusura dell'anno demo si può eseguire dal +passo 1 al 9 e verificare il bilancio. Le prove automatiche fanno proprio questo, su SQLite e su PostgreSQL. + +## Permessi e licenza + +| Permesso | Consente | +|---|---| +| `ledger.entry.read` | bilancio CEE, riclassificato, indici, stampa | +| `ledger.year.close` | ratei e risconti, chiusura guidata, blocco dell'esercizio | +| `reports.accountant.export` | esportazione per il commercialista | + +Serve il modulo **ACCT**; il passo 2 usa i cespiti se è attivo **ASSET**. + +## Domande frequenti + +**Il passo 1 è rosso.** Leggi i messaggi: di solito ci sono registrazioni provvisorie da registrare o eliminare in +[Prima nota](Contabilita#prima-nota). Correggi e premi **Ripeti passo 1**. + +**Ho dimenticato una fattura dopo il passo 6.** Annulla i passi dal più recente fino al 5 (uno alla volta), registra +la fattura e riesegui i passi. + +**Dove finisce il risultato?** Nel conto *utile (perdita) dell'esercizio* del patrimonio netto; la destinazione +dell'utile si registra a mano nel nuovo esercizio dopo l'approvazione del bilancio. + +**Il TFR è giusto?** È una stima (retribuzioni dell'anno diviso 13,5 meno quanto già accantonato): se le paghe sono +elaborate fuori, registra la quota del consulente e la chiusura non aggiunge nulla. + +## Pagine correlate + +[Contabilità](Contabilita) · [Cespiti](Cespiti) · [IVA](IVA) · [Magazzino](Magazzino) · [Scadenzario](Scadenzario) · +[Fiscalità italiana](Fiscalita-italiana) · [Report](Report) diff --git a/docs/wiki/Contabilita.md b/docs/wiki/Contabilita.md index e5cbf64..d507f47 100644 --- a/docs/wiki/Contabilita.md +++ b/docs/wiki/Contabilita.md @@ -1,6 +1,6 @@ # Contabilità generale -> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7) +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) > **Modulo di licenza:** ACCT · **Permessi principali:** `ledger.account.read`/`write` (piano dei conti e causali), `ledger.entry.read`/`write` (prima nota, partitari, bilancio), `ledger.entry.finalize` (registrazioni definitive) · **Specifica:** SPEC §11.7, §14, ADR 0036, ADR 0037 Il modulo **Contabilità** tiene la **contabilità generale in partita doppia** dell'azienda: piano dei conti, causali, @@ -17,9 +17,9 @@ nella pagina [IVA](IVA); le regole italiane usate (piano dei conti modello, codi > registrazioni ricorrenti, lo storno, le registrazioni definitive con il numero di libro giornale, i partitari con > estratto conto e partite, i mastrini, il bilancio di verifica e le stampe del bilancio e del libro giornale. > Dalla 0.8 incassi, pagamenti, distinte e riconciliazione bancaria scrivono le loro registrazioni dallo -> [Scadenzario](Scadenzario). Arrivano più avanti: **chiusura -> dell'esercizio**, ratei e risconti, **bilancio CEE** riclassificato e **cespiti** (M10). Non ci sono ancora -> l'import del piano dei conti da file e l'export per il commercialista. +> [Scadenzario](Scadenzario). Dalla 0.10 ci sono la **chiusura guidata dell'esercizio** con ratei e risconti, il +> **bilancio CEE** con riclassificato e indici e l'export per il commercialista ([Chiusura e bilancio](Chiusura-e-bilancio)), +> e i [Cespiti](Cespiti). Non c'è ancora l'import del piano dei conti da file. ## Dove si trova @@ -189,7 +189,7 @@ bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano | **Riclassificazione** | voce del riclassificato, facoltativa | | **Partitario** | le righe indicano il cliente o il fornitore | | **Rilevante IVA** | il conto entra nelle registrazioni con IVA | -| **Chiuso in automatico a fine esercizio** | il conto sarà chiuso dalla procedura di fine esercizio (M10) | +| **Chiuso in automatico a fine esercizio** | il conto è chiuso dalla [chiusura dell'esercizio](Chiusura-e-bilancio) | | **Disattivato** | il conto resta nello storico ma non si usa più | A sinistra l'**albero** con la ricerca per codice o descrizione; a destra i dati del conto scelto e, per i @@ -271,8 +271,8 @@ Le stampe sono file PDF da scaricare: | **Libro giornale di prova** | registrazioni registrate e definitive del periodo, in ordine di data, con le righe | | **Libro giornale definitivo** | solo le registrazioni definitive, con il numero di libro giornale e le pagine numerate dall'inizio dell'anno | -Il bilancio CEE (stato patrimoniale e conto economico civilistici), il riclassificato e gli indici arrivano con la -chiusura dell'esercizio (M10). +Le altre schede della pagina, **CEE**, **Riclassificato** e **Indici**, mostrano il bilancio d'esercizio: sono +spiegate in [Chiusura e bilancio](Chiusura-e-bilancio). ## Dati demo diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index 3637f27..444cce0 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -1,6 +1,6 @@ # Dati di base e di esempio -> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) > **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14 ## A cosa serve @@ -79,8 +79,9 @@ tabella *Comuni* o con l'**Importa CSV** (colonne `Code` e `PostalCodes`, più C compilazione dal CAP propone solo i comuni che hanno il CAP scritto. Le **banche ABI/CAB** non sono ancora incluse: banca e BIC dall'IBAN vengono da un conto dell'azienda presso la stessa banca. Un comune soppresso per fusione resta nella tabella finché non lo disattivi. -Le altre voci dell'elenco (piano dei conti, causali contabili, registri IVA, cespiti, codici tributo, CRM) arrivano con i -moduli che le usano. +Le categorie dei cespiti si creano da **Cespiti → Categorie → Categorie standard** (vedi [Cespiti](Cespiti)). Le altre +voci dell'elenco (piano dei conti, causali contabili, registri IVA, codici tributo, CRM) arrivano con i moduli che le +usano. ### Aggiorna tabelle di base @@ -187,6 +188,19 @@ confermate fino al mese precedente, le ritenute e il bollo virtuale (vedi [Conta | Instradamento | tre regole: PA su PEC, oltre 200 file al giorno sull'Intermediario A, sempre PEC con l'Intermediario A di riserva | | Fatture ricevute | tre fatture di fornitori da registrare | +**Da M10** ci sono anche i dati di **fine anno** (vedi [Cespiti](Cespiti), [Intrastat](Intrastat), +[Dichiarazioni d'intento](Dichiarazioni-d-intento) e [Chiusura e bilancio](Chiusura-e-bilancio)): + +| Dati | Che cosa mostrano | +|---|---| +| Apertura dei conti | una registrazione al 1° gennaio con cespiti e fondi, rimanenze di magazzino, banca, capitale sociale e utili portati a nuovo | +| Cespiti | le categorie standard e quattro beni: furgone, scaffalature e arredi già in uso con i fondi iniziali, un server acquistato nell'anno con la sua registrazione | +| Risconto | il premio di assicurazione del furgone pagato il 1° ottobre per dodici mesi | +| Dichiarazione d'intento | quella di Idrotermica Piemonte nel registro, con una fattura in N3.5 che consuma il plafond | +| Intrastat | una fattura non imponibile art. 41 a Bergwerk Bau (Austria) con codici doganali e pesi, se la licenza comprende **INTRA** | + +Con questi dati la chiusura dell'anno si esegue dal passo 1 al 9. + Il resto della tabella arriva con le milestone dei rispettivi moduli. I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo stesso caricamento è usato come prova automatica di correttezza. diff --git a/docs/wiki/Dichiarazioni-d-intento.md b/docs/wiki/Dichiarazioni-d-intento.md new file mode 100644 index 0000000..e246fa5 --- /dev/null +++ b/docs/wiki/Dichiarazioni-d-intento.md @@ -0,0 +1,91 @@ +# Dichiarazioni d'intento + +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) +> **Modulo di licenza:** CORE · **Permessi principali:** `sales.intent.read` (registro e stampa), `sales.intent.write` +> (inserire, modificare, revocare) · **Specifica:** SPEC §11.7, ADR 0042 + +Gli **esportatori abituali** acquistano senza IVA, entro un **plafond**, presentando al fornitore una **dichiarazione +d'intento** trasmessa all'Agenzia delle Entrate. Khaemhat tiene il **registro cronologico** delle dichiarazioni +ricevute dai clienti (e di quelle emesse verso i fornitori), aggiorna l'**utilizzato** con le fatture emesse, +avvisa quando il plafond è quasi esaurito e **rifiuta la conferma** di una fattura senza dichiarazione valida o oltre +il plafond. + +## Dove si trova + +**Fatturazione elettronica → Dichiarazioni d'intento** (anche all'indirizzo `/vendite/dichiarazioni-intento`). La +funzione è nel modulo base CORE. + +![Khaemhat 0.10.0 · dichiarazioni d'intento](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/dichiarazioni-intento.png) +*Il registro delle dichiarazioni ricevute nel 2026: la dichiarazione di Idrotermica Piemonte con protocollo +telematico, plafond, utilizzato, residuo e percentuale di utilizzo.* + +## Il registro + +Due schede: **Ricevute (clienti)** ed **Emesse (fornitori)**, filtrate per esercizio. + +| Colonna | Significato | +|---|---| +| **Numero**, **Data** | numero progressivo del registro e data della dichiarazione | +| **Cliente** / **Fornitore**, **Codice** | la controparte | +| **Protocollo telematico** | protocollo della ricevuta dell'Agenzia: 17 cifre, trattino (o barra) e 6 cifre di progressivo | +| **Plafond**, **Utilizzato**, **Residuo** | importo dichiarato, fatture già emesse, quanto resta | +| **Esercizio** | anno di riferimento | +| **Stato** | *Attiva* (con la percentuale di utilizzo, in arancione dal 90 %), *Esaurita*, *Revocata* | + +**Stampa registro** produce il PDF del registro dell'anno. + +## Registrare una dichiarazione ricevuta + +1. **Nuova dichiarazione**, scheda *Ricevute*. +2. Scegli il **cliente**, scrivi numero e data, il **protocollo telematico** e il **plafond**. +3. Indica il periodo di validità (**valida dal**, **valida al**): ogni fattura va sulla dichiarazione più recente che ne copre la data. +4. L'**utilizzato** si aggiorna da solo con le fatture: compilalo solo se una parte del plafond è già stata usata con + fatture emesse fuori da Khaemhat. +5. Salva. Il cliente riceve una copia della dichiarazione corrente nei suoi dati fiscali, usata dai documenti e dalla + fattura elettronica. + +Una dichiarazione si **revoca** (per esempio quando il cliente la annulla) e da quel momento non copre più le +fatture. Il plafond non può scendere sotto l'utilizzato; una dichiarazione mai usata si può eliminare. + +## Fatturare a un esportatore abituale + +1. Nella fattura usa per le righe il codice IVA di **natura N3.5** (*non imponibile a seguito di dichiarazione + d'intento*), di solito impostato come codice IVA preferito del cliente. +2. Alla **conferma** Khaemhat cerca una dichiarazione attiva del cliente valida alla data della fattura: + - se **non c'è**, la conferma è rifiutata con il messaggio *nessuna dichiarazione d'intento valida*; + - se l'imponibile in N3.5 **supera il residuo**, la conferma è rifiutata indicando quanto resta; + - altrimenti la fattura è confermata e l'importo si aggiunge all'**utilizzato**; dal 90 % compare l'avviso. +3. La fattura elettronica riporta gli estremi della dichiarazione nel blocco *AltriDatiGestionali* con tipo + `INTENTO` (vedi [Fatturazione elettronica](Fatturazione-elettronica)). + +Le note di credito in N3.5 riducono l'utilizzato; eliminare o annullare una fattura lo ricalcola. + +## Dichiarazioni emesse + +Se l'azienda stessa è esportatore abituale registra nella scheda **Emesse** le dichiarazioni inviate ai propri +fornitori, con lo stesso protocollo e plafond: servono come promemoria e per la stampa del registro. + +## Dati di esempio + +I dati dimostrativi registrano la dichiarazione di **Idrotermica Piemonte** (plafond 150.000 €) ed emettono una +fattura in N3.5 che ne consuma una parte; una fattura in N3.5 a un cliente senza dichiarazione viene rifiutata. + +## Permessi e licenza + +| Permesso | Consente | +|---|---| +| `sales.intent.read` | registro e stampa | +| `sales.intent.write` | inserire, modificare e revocare le dichiarazioni | + +## Domande frequenti + +**La fattura non si conferma: «plafond superato».** Il residuo della dichiarazione non basta. Chiedi al cliente una +nuova dichiarazione (o un'integrazione del plafond) e registrala, oppure fattura la parte eccedente con IVA. + +**Avevo scritto il protocollo nell'anagrafica del cliente.** Le dichiarazioni inserite nei dati fiscali del cliente +prima della versione 0.10 diventano automaticamente righe del registro alla prima apertura. + +## Pagine correlate + +[Vendite](Vendite) · [Anagrafiche](Anagrafiche) · [IVA](IVA) · [Fatturazione elettronica](Fatturazione-elettronica) · +[Intrastat](Intrastat) · [Fiscalità italiana](Fiscalita-italiana) diff --git a/docs/wiki/Fatturazione-elettronica.md b/docs/wiki/Fatturazione-elettronica.md index a5121ce..daa4380 100644 --- a/docs/wiki/Fatturazione-elettronica.md +++ b/docs/wiki/Fatturazione-elettronica.md @@ -1,6 +1,6 @@ # Fatturazione elettronica e canali SDI -> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) > **Modulo di licenza:** EINV · **Permessi principali:** `einvoice.document.read` (cruscotto, notifiche, > conservazione), `einvoice.document.send` (generare, inviare, importare notifiche), `einvoice.inbox.read` e > `einvoice.inbox.import` (fatture ricevute), `einvoice.channel.manage` (canali e instradamento) · **Specifica:** @@ -20,9 +20,9 @@ e **due intermediari** accreditati. > quattro canali con prova di connessione, pausa e regole di instradamento con canale di riserva, la lettura > automatica dei canali ogni 15 minuti, la ricezione push di SdICoop, l'import manuale delle notifiche, la correzione > delle fatture scartate, la copia di cortesia in PDF con l'XML allegato, le fatture ricevute con registrazione in -> blocco, l'elenco delle notifiche e i pacchetti per la conservazione. Arrivano più avanti: le **dichiarazioni -> d'intento** e la **LIPE** ([IVA](IVA), M10), **Intrastat** ([Intrastat](Intrastat), M10) e il formato europeo -> **EN 16931 / UBL** ([Roadmap](Roadmap)). +> blocco, l'elenco delle notifiche e i pacchetti per la conservazione. Dalla 0.10 il menu comprende anche +> [Intrastat](Intrastat) e le [dichiarazioni d'intento](Dichiarazioni-d-intento), i cui estremi entrano nel file +> (`AltriDatiGestionali` di tipo `INTENTO`). Arriva più avanti il formato europeo **EN 16931 / UBL** ([Roadmap](Roadmap)). ## Dove si trova diff --git a/docs/wiki/Fiscalita-italiana.md b/docs/wiki/Fiscalita-italiana.md index 8349435..6750aa7 100644 --- a/docs/wiki/Fiscalita-italiana.md +++ b/docs/wiki/Fiscalita-italiana.md @@ -1,6 +1,6 @@ # Fiscalità italiana -> **Stato:** completa per la versione 0.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) > **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14, ADR 0036, ADR 0037, ADR 0038, ADR 0039 Questa pagina raccoglie in un solo posto i **codici e le regole fiscali italiane** che Khaemhat usa: tipi documento @@ -17,9 +17,9 @@ fa fede il testo mostrato dal programma, non questa pagina. > **In questa versione** sono in uso i codici dei documenti, delle nature, dei pagamenti e dei regimi (dalla 0.4), > e con la 0.7 il piano dei conti *PMI standard*, i registri IVA, le regole della liquidazione e dell'acconto, i > codici tributo e le scadenze dell'F24, il tracciato LIPE, le ritenute d'acconto e il bollo virtuale. Con la 0.9 il -> file FatturaPA e le notifiche SDI sono in uso nella [Fatturazione elettronica](Fatturazione-elettronica). Le parti -> su dichiarazioni d'intento, Intrastat e cespiti descrivono regole che il programma userà con [IVA](IVA), -> [Cespiti](Cespiti) e [Intrastat](Intrastat) (M10). +> file FatturaPA e le notifiche SDI sono in uso nella [Fatturazione elettronica](Fatturazione-elettronica). Con la 0.10 +> sono in uso anche le regole di [Cespiti](Cespiti), [Intrastat](Intrastat), +> [dichiarazioni d'intento](Dichiarazioni-d-intento) e lo schema del bilancio CEE ([Chiusura e bilancio](Chiusura-e-bilancio)). > **Attenzione.** Khaemhat calcola e prepara i dati (F24, LIPE, Certificazione Unica, bollo) ma **non sostituisce il > commercialista** né invia F24, LIPE e CU: l'invio telematico avviene con i servizi dell'Agenzia delle Entrate, @@ -324,11 +324,11 @@ si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermedia |---|---|---| | Split payment | IVA versata dalla PA cessionaria (esigibilità **S**): in contabilità l'IVA viene tolta subito al cliente | [Vendite](Vendite), [Contabilita](Contabilita) | | Reverse charge interno | IVA a carico del cessionario, registri RC vendite e acquisti (IVA neutra) | [Acquisti](Acquisti), [IVA](IVA) | -| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo (M10) | [Fatturazione-elettronica](Fatturazione-elettronica) | +| Dichiarazione d'intento | operazioni non imponibili N3.5 con controllo di plafond, utilizzato e residuo; protocollo di 17 + 6 cifre; avviso dal 90 % | [Dichiarazioni d'intento](Dichiarazioni-d-intento) | | Ritenuta e cassa previdenza | parcelle TD06: cassa (ad esempio 4%) e ritenuta d'acconto | [IVA](IVA#ritenute-dacconto) | -| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 (M10) | [Cespiti](Cespiti) | -| Intrastat | elenchi INTRA cessioni e acquisti, periodicità da soglie, nomenclatura NC8 (M10) | [Intrastat](Intrastat) | -| Bilancio | schemi CEE art. 2424 (stato patrimoniale) e 2425 (conto economico): le voci sono già sui conti, gli schemi arrivano con M10 | [Contabilita](Contabilita) | +| Cespiti | coefficienti del DM 31/12/1988, primo anno al 50%, limiti per le autovetture, beni sotto € 516,46 | [Cespiti](Cespiti) | +| Intrastat | elenchi INTRA cessioni e acquisti, periodicità dalle soglie (50.000 € per le cessioni, 350.000 e 100.000 € per gli acquisti), nomenclatura NC8, file SCAMBI.CEE | [Intrastat](Intrastat) | +| Bilancio | schemi CEE art. 2424 e 2425 c.c., abbreviato (art. 2435-bis) e micro (art. 2435-ter); svalutazione crediti allo 0,5 % (art. 106 TUIR) e TFR nella chiusura | [Chiusura e bilancio](Chiusura-e-bilancio) | ## Domande frequenti diff --git a/docs/wiki/Guida-utente.md b/docs/wiki/Guida-utente.md index 25cc861..fe0fbd2 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.9 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9) +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) Questa pagina accompagna chi usa Khaemhat ogni giorno: dall'accesso alla fattura inviata al cliente, un passo per volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina che lo spiega per intero. Chi deve @@ -9,7 +9,7 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c ## Che cosa c'è in questa versione -| Area | In 0.9.0 | Arriva con | +| Area | In 0.10.0 | Arriva con | |---|---|---| | Accesso e sicurezza | password, verifica in due passaggi, codici di recupero, blocco dopo i tentativi sbagliati | — | | Interfaccia | menu, schede, ricerca globale, notifiche, aiuto F1, dashboard a widget, temi e colori | — | @@ -18,11 +18,12 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c | Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente, costo medio e ultimo costo dai movimenti | — | | Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail, scarico del magazzino e impegno, registrazione contabile automatica, incassi dallo scadenzario, file FatturaPA e invio allo SDI | — | | Acquisti | ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, controllo dei prezzi, import delle fatture elettroniche XML/P7M/ZIP, autofatture e integrazioni in bozza con scadenza, registrazione contabile e registri IVA, pagamenti dallo scadenzario, file e invio delle autofatture | — | -| Magazzino | giacenze per deposito, impegnato e ordinato, costo medio, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione | scritture delle rimanenze e libro inventari con la chiusura dell'esercizio M10 | -| Contabilità | piano dei conti, causali, prima nota, contabilizzazione automatica dei documenti, registrazioni ricorrenti e definitive, partitari, mastrini, bilancio di verifica, libro giornale | chiusura dell'esercizio, bilancio CEE e cespiti M10 | -| IVA | registri IVA, liquidazione con F24, acconto, file LIPE, ritenute d'acconto con prospetto F24 e dati CU, bollo virtuale | dichiarazioni d'intento M10 | +| Magazzino | giacenze per deposito, impegnato e ordinato, costo medio, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione | libro inventari M13 | +| Contabilità | piano dei conti, causali, prima nota, contabilizzazione automatica dei documenti, registrazioni ricorrenti e definitive, partitari, mastrini, bilancio di verifica, libro giornale, ratei e risconti, chiusura guidata dell'esercizio, bilancio CEE con riclassificato e indici, export per il commercialista | — | +| IVA | registri IVA, liquidazione con F24, acconto, file LIPE, ritenute d'acconto con prospetto F24 e dati CU, bollo virtuale, dichiarazioni d'intento con plafond, elenchi Intrastat | — | +| Cespiti | categorie con i coefficienti ministeriali, registro con piano civilistico e fiscale, ammortamenti registrati e annullabili, dismissioni con plus e minusvalenze, stampa del registro | rivalutazioni guidate più avanti | | Scadenzario | partite aperte con aging, incassi e pagamenti, distinte RiBa/SDD/bonifici SEPA con insoluti, mandati SDD, riconciliazione bancaria CSV/CBI/CAMT.053, solleciti con interessi di mora, flusso di cassa | collegamento diretto con la banca e report di tesoreria M12 | -| Fatturazione elettronica | file FatturaPA con controllo prima dell'invio, canali PEC, SdICoop e due intermediari con instradamento, notifiche, correzione degli scarti, copia di cortesia, fatture ricevute da registrare, pacchetti per la conservazione | dichiarazioni d'intento M10, formato europeo UBL più avanti | +| Fatturazione elettronica | file FatturaPA con controllo prima dell'invio, canali PEC, SdICoop e due intermediari con instradamento, notifiche, correzione degli scarti, copia di cortesia, fatture ricevute da registrare, pacchetti per la conservazione | formato europeo UBL più avanti | | Import ed export | clienti, fornitori, articoli, prezzi e giacenze iniziali da CSV, Excel e JSON; esportazione dai radar | import del piano dei conti: più avanti | | Amministrazione da interfaccia | utenti e licenze da variabili e riga di comando | pagine di amministrazione: M12 | @@ -162,8 +163,10 @@ confermati muovono il magazzino da soli: non serve registrare a parte carichi e Con il modulo contabile ogni fattura, nota e autofattura confermata scrive da sola la sua **registrazione** in partita doppia, con le righe IVA nel registro giusto e le **partite** da incassare o pagare. **Contabilità → Prima nota** elenca le registrazioni e serve per quelle manuali (giroconti, spese, versamenti); **Liquidazione IVA** calcola -l'IVA del periodo e prepara l'F24; **Bilancio** dà il bilancio di verifica. Vedi [Contabilità](Contabilita) e -[IVA](IVA). +l'IVA del periodo e prepara l'F24; **Bilancio** dà il bilancio di verifica e, nelle altre schede, il bilancio CEE, +il riclassificato e gli indici. A fine anno **Chiusura esercizio** guida ammortamenti, ratei e risconti, rimanenze, +chiusura dei conti, riapertura e stampe definitive in nove passi. Vedi [Contabilità](Contabilita), [IVA](IVA), +[Cespiti](Cespiti) e [Chiusura e bilancio](Chiusura-e-bilancio). ## 11. Incassare, pagare e la banca diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 2f1b24c..2593221 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -1,6 +1,6 @@ # Khaemhat -> **Stato:** completa per 0.9.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.9.0 (M9; sviluppo in corso) +> **Stato:** completa per 0.10.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10; sviluppo in corso) ![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png) @@ -37,7 +37,8 @@ Il nome viene da uno scriba dell'antico Egitto che sovrintendeva ai granai del r - **Anagrafiche e tabelle:** [Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) · [Tabelle azienda](Tabelle-azienda) - **Ciclo attivo e passivo:** [Vendite](Vendite) · [Acquisti](Acquisti) · [Magazzino](Magazzino) -- **Amministrazione e fisco:** [Contabilità](Contabilita) · [IVA](IVA) · [Cespiti](Cespiti) · [Intrastat](Intrastat) · +- **Amministrazione e fisco:** [Contabilità](Contabilita) · [Chiusura e bilancio](Chiusura-e-bilancio) · [IVA](IVA) · + [Cespiti](Cespiti) · [Intrastat](Intrastat) · [Dichiarazioni d'intento](Dichiarazioni-d-intento) · [Scadenzario](Scadenzario) · [Fatturazione elettronica](Fatturazione-elettronica) · [Fiscalità italiana](Fiscalita-italiana) - **Clienti e servizi:** [CRM](CRM) · [Servizi](Servizi) · [Canali e-commerce](Canali-e-commerce) diff --git a/docs/wiki/IVA.md b/docs/wiki/IVA.md index 9d4b391..cdb0199 100644 --- a/docs/wiki/IVA.md +++ b/docs/wiki/IVA.md @@ -1,6 +1,6 @@ # IVA -> **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7) +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) > **Modulo di licenza:** ACCT · **Permessi principali:** `vat.register.read` (registri IVA), `vat.settlement.read` (liquidazione, ritenute, bollo, F24), `vat.settlement.confirm` (conferme, versamenti, stampe definitive) · **Specifica:** SPEC §11.7, §11.9, §14, ADR 0037 Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabilità**: @@ -18,8 +18,8 @@ Questa pagina descrive l'IVA e i versamenti collegati, tutti nel menu **Contabil > **In questa versione** ci sono i cinque registri IVA con stampe di prova e definitive, la liquidazione con la sua > registrazione e il versamento F24, l'acconto IVA, il file LIPE, le ritenute con il prospetto F24 e il pagamento, i > dati della CU e il bollo virtuale. Dalla 0.8 il pagamento di una parcella dallo -> [Scadenzario](Scadenzario) rende dovuta la ritenuta da solo. Arrivano più avanti: le **dichiarazioni d'intento** e il plafond e l'**Intrastat** (M10), -> l'**IVA per cassa** completa (fase 2). Non ci sono ancora la **dichiarazione IVA annuale** e l'**invio +> [Scadenzario](Scadenzario) rende dovuta la ritenuta da solo. Dalla 0.10 ci sono le [dichiarazioni d'intento](Dichiarazioni-d-intento) con il plafond e gli +> elenchi [Intrastat](Intrastat). Arriva più avanti l'**IVA per cassa** completa (fase 2). Non ci sono ancora la **dichiarazione IVA annuale** e l'**invio > telematico** di F24, LIPE e CU. ## Dove si trova diff --git a/docs/wiki/Intrastat.md b/docs/wiki/Intrastat.md index 33ce6fe..2df21b2 100644 --- a/docs/wiki/Intrastat.md +++ b/docs/wiki/Intrastat.md @@ -1,83 +1,105 @@ # Intrastat -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M10) -> **Modulo di licenza:** INTRA · **Permessi principali:** `intrastat.declaration.write`, `intrastat.declaration.export` · **Specifica:** SPEC §11.7, §8.1 +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) +> **Modulo di licenza:** INTRA · **Permessi principali:** `intrastat.list.read` (elenchi), `intrastat.list.write` +> (generare e correggere), `intrastat.list.export` (file e invio) · **Specifica:** SPEC §11.7, ADR 0042 -## A cosa serve - -Il modulo Intrastat prepara gli **elenchi riepilogativi delle operazioni intracomunitarie** a partire dalle fatture -di vendita e di acquisto già registrate, controlla i dati mancanti e produce il **file nel tracciato dell'Agenzia -delle Dogane**, da trasmettere con i canali telematici previsti (la trasmissione avviene fuori da Khaemhat). +Gli **elenchi riepilogativi Intrastat** raccolgono le cessioni e gli acquisti di beni e servizi con soggetti di altri +Paesi dell'Unione europea. Khaemhat li **genera dalle fatture e note di credito confermate**, controlla i dati di ogni +riga, propone la **periodicità** dovuta e produce il file **SCAMBI.CEE** nel tracciato dell'Agenzia delle Dogane, da +trasmettere con i servizi telematici (la trasmissione avviene fuori da Khaemhat). ## Dove si trova -Nel mockup la voce è **Fatturazione elettronica → Intrastat**; il modulo di licenza è comunque **INTRA**, separato -da EINV. +**Fatturazione elettronica → Intrastat** (la voce compare con il modulo **INTRA**, separato da EINV). -## Schermate +![Khaemhat 0.10.0 · elenco Intrastat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/intrastat-elenco.png) +*L'elenco delle cessioni di novembre 2026 dell'azienda demo: la fattura a Bergwerk Bau (Austria) con nomenclatura, +natura della transazione, consegna, trasporto, ammontare e massa netta; sotto, gli elenchi dell'anno.* -![049 · Intrastat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/049-intrastat.png) -*Mockup 049 — elenchi di settembre (mensile): riquadri con i totali per sezione e le anomalie, elenco delle operazioni con paese, P.IVA, NC8, natura della transazione, consegna, trasporto, valore, massa e controllo; pulsanti Genera elenco e File SCAMBI.CEE* +## Flussi e sezioni -## Gli elenchi +| Flusso | Sezione | Modello | +|---|---|---| +| **Cessioni** | Beni · Rettifiche beni · Servizi · Rettifiche servizi | INTRA-1 bis, ter, quater, quinquies | +| **Acquisti** | Beni · Rettifiche beni · Servizi · Rettifiche servizi | INTRA-2 bis, ter, quater, quinquies | -| Modello | Contenuto | -|---|---| -| **INTRA-1 bis** | cessioni di beni verso altri Paesi UE | -| **INTRA-1 ter** | rettifiche alle cessioni di beni di periodi precedenti | -| **INTRA-1 quater** | servizi resi a soggetti UE | -| **INTRA-2 bis** | acquisti di beni da altri Paesi UE | -| **INTRA-2 ter** | rettifiche agli acquisti di beni di periodi precedenti | -| **INTRA-2 quater** | servizi ricevuti da soggetti UE | - -I riquadri in testa mostrano il periodo e la periodicità, i totali di ogni sezione e il numero di **anomalie**. +La striscia in alto riporta il **periodo**, i totali di cessioni e acquisti di beni, dei servizi resi e ricevuti e il +numero di righe **da completare**. ## Periodicità -La periodicità (**mensile** o **trimestrale**) è determinata dalle **soglie di legge** in base agli importi delle -operazioni, separatamente per cessioni e acquisti. Le soglie sono parametri del pacchetto fiscale italiano e vengono -aggiornate con esso; Khaemhat propone la periodicità e la mostra nel riquadro *Periodo*. +Sotto i filtri Khaemhat indica la **periodicità dovuta** in base agli importi dei quattro trimestri precedenti, per +beni e servizi separatamente, con le soglie in vigore dal 2022: -## Dati richiesti per ogni operazione +| Flusso | Mensile se in almeno un trimestre | Altrimenti | +|---|---|---| +| Cessioni (beni o servizi) | più di 50.000 € | trimestrale | +| Acquisti di beni | più di 350.000 € | non dovuto | +| Acquisti di servizi | più di 100.000 € | non dovuto | -| Dato | Da dove viene | +La periodicità dell'elenco si sceglie nei filtri (mensile o trimestrale) insieme a esercizio e periodo. + +## Generare l'elenco + +1. Scegli **flusso**, **esercizio**, **periodicità** e **periodo**. +2. Premi **Genera** *periodo*. Khaemhat legge le fatture e le note di credito confermate nel periodo verso soggetti con + sede in un altro Paese UE: + - i **beni** sono raggruppati per controparte, nomenclatura e natura della transazione; + - i **servizi** hanno una riga per fattura, con il codice CPA; + - le **note di credito** diventano righe di rettifica. +3. Le righe aggiunte a mano con **Aggiungi riga** restano quando rigeneri l'elenco. + +| Colonna | Da dove viene | |---|---| -| Paese e partita IVA della controparte | anagrafica (P.IVA comunitaria verificata con VIES, vedi [Anagrafiche](Anagrafiche)) | -| **NC8** (nomenclatura combinata a 8 cifre) | scheda articolo ([Articoli e listini](Articoli-e-listini)) | -| Descrizione | riga del documento | -| **Natura della transazione** | causale del documento, modificabile (es. `11` vendita) | -| **Condizioni di consegna** | Incoterms del documento (es. DAP, FCA, EXW) | -| **Modo di trasporto** | dal documento (es. 1 mare, 3 strada) | -| Valore | imponibile in euro | -| **Massa netta** e unità supplementare | peso dell'articolo x quantità | +| Controparte, Paese, Partita IVA | anagrafica (vedi [Anagrafiche](Anagrafiche)) | +| **Nomenclatura / CPA** | codice doganale della scheda articolo ([Articoli e listini](Articoli-e-listini)) | +| **Natura** | proposta `11` (vendita o acquisto a titolo definitivo) | +| **Consegna**, **Trasporto** | proposti `DAP` e `3` (strada) | +| **Ammontare €** | imponibile della riga in euro | +| **Massa netta kg** | peso netto dell'articolo per quantità | -La colonna **Controllo** segnala lo stato di ogni riga: *OK*, *Manca peso netto* (riga evidenziata), *Extra-UE: -escluso* (la controparte non è comunitaria e la riga non entra negli elenchi), *INTRA-2 quater* (servizio ricevuto). -I dati richiesti dipendono dal modello e dalla periodicità; il tracciato preciso segue le istruzioni dell'Agenzia -delle Dogane in vigore. +Un clic sulla riga apre la scheda per correggere sezione, paese, partita IVA, codice, descrizione, ammontare, +massa, natura, consegna e trasporto; le righe si possono anche eliminare finché l'elenco non è inviato. -## Come si prepara l'elenco +## Controlli -1. Apri **Intrastat**, scegli **Periodo** e **Sezione**. -2. Premi **Genera elenco** del periodo: Khaemhat raccoglie le fatture intracomunitarie registrate. -3. Correggi le **anomalie** aprendo l'articolo o il documento (NC8 o peso mancanti, P.IVA non valida…). -4. Rigenera e controlla i totali con i registri IVA ([IVA](IVA)). -5. Premi **File SCAMBI.CEE** per scaricare il file nel tracciato dell'Agenzia delle Dogane; il file resta come - allegato della dichiarazione ([Allegati e file](Allegati-e-file)). -6. Trasmetti il file con il servizio telematico e registra l'avvenuto invio. +| Controllo | Cosa fare | +|---|---| +| **Completa** | niente | +| **Manca la nomenclatura** | completa il codice doganale sull'articolo e rigenera | +| **Manca la massa netta** | completa il peso netto sull'articolo, o la massa sulla riga | +| **Manca la partita IVA** | completa la partita IVA comunitaria della controparte | +| **Manca il codice CPA** | servizio senza codice: completalo sull'articolo | +| **Fuori UE** | la controparte non è comunitaria: la riga non entra nell'elenco | + +## File e invio + +1. **File SCAMBI.CEE** scarica il file a lunghezza fissa (frontespizio e record per beni, servizi e rettifiche). + Un elenco con righe da completare non si esporta. L'elenco passa a *File generato*. +2. Controlla il file con il software di controllo delle Dogane e trasmettilo. +3. **Segna come inviato** chiede il **protocollo di invio**: da quel momento l'elenco è di sola lettura. + +> **Attenzione.** Il tracciato segue le specifiche pubblicate ma non è ancora stato verificato con il software di +> controllo delle Dogane: prima del primo invio controlla sempre il file (vedi [Roadmap](Roadmap)). + +## Dati di esempio + +I dati dimostrativi emettono una fattura non imponibile (art. 41) a **Bergwerk Bau GmbH** (Austria) con articoli che +hanno codice doganale e peso netto: generando l'elenco del mese corrente si vede una riga completa. ## Permessi e licenza -Serve il modulo **INTRA**. I codici dei permessi in testa sono indicativi (convenzione `modulo.entità.azione`, SPEC -§7.2) e saranno fissati in sviluppo. +| Permesso | Consente | +|---|---| +| `intrastat.list.read` | consultare gli elenchi | +| `intrastat.list.write` | generare, aggiungere e correggere righe | +| `intrastat.list.export` | scaricare il file e segnare l'invio | -## Attenzione - -- Gli elenchi dipendono dalla qualità delle anagrafiche: NC8 e peso netto sugli articoli, P.IVA comunitarie valide. -- Soglie, modelli e campi obbligatori cambiano con le determinazioni dell'Agenzia delle Dogane: verificare sempre le - istruzioni in vigore prima dell'invio. +Serve il modulo **INTRA**. ## Pagine correlate [IVA](IVA) · [Vendite](Vendite) · [Acquisti](Acquisti) · [Articoli e listini](Articoli-e-listini) · -[Fatturazione elettronica](Fatturazione-elettronica) · [Fiscalità italiana](Fiscalita-italiana) +[Fatturazione elettronica](Fatturazione-elettronica) · [Dichiarazioni d'intento](Dichiarazioni-d-intento) · +[Fiscalità italiana](Fiscalita-italiana) diff --git a/docs/wiki/Magazzino.md b/docs/wiki/Magazzino.md index ba0e923..a0b2e42 100644 --- a/docs/wiki/Magazzino.md +++ b/docs/wiki/Magazzino.md @@ -1,6 +1,6 @@ # Magazzino -> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6) +> **Stato:** completa per la versione 0.10 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.10.0 (M10) > **Modulo di licenza:** CORE · **Permessi principali:** `inventory.stock.read` (giacenze), `inventory.entry.*` (movimenti, inventario), `inventory.entry.post` (conferma, rettifiche, ricostruzione), `items.cost.read` (costi e valori) · **Specifica:** SPEC §11.6, ADR 0035 Il **magazzino** tiene la quantità e il valore di ogni articolo in ogni **deposito**. Le giacenze si aggiornano da @@ -10,8 +10,9 @@ riordino** e calcoli la **valorizzazione** a una data. > **In questa versione** ci sono giacenze per deposito, impegnato e ordinato, costo medio ponderato, movimenti per > articolo, movimenti manuali e trasferimenti, inventario fisico con import dei conteggi, proposta di riordino, -> valorizzazione con analisi ABC e ricostruzione. Arrivano più avanti: le **scritture contabili** delle rimanenze e il -> **libro inventari** con la chiusura dell'esercizio (M10), i report di magazzino stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0). +> valorizzazione con analisi ABC e ricostruzione. Dalla 0.10 la [chiusura dell'esercizio](Chiusura-e-bilancio) registra le +> rimanenze finali al costo medio ponderato. Arrivano più avanti: il **libro inventari** e i report di magazzino +> stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0). ## Dove si trova @@ -149,8 +150,8 @@ fornitore non vengono ordinate. - La **valorizzazione** (pulsante nelle giacenze) calcola quantità e valore **a una data** qualsiasi, anche passata, con il criterio scelto: *costo medio ponderato*, *ultimo costo* o *costo standard*. Divide gli articoli in **classi ABC**: A gli articoli che fanno l'80% del valore, B fino al 95%, C il resto. -- FIFO e LIFO sono previsti con la gestione a lotti; le rimanenze alimenteranno la chiusura dell'esercizio e il libro - inventari con la chiusura dell'esercizio (M10). +- FIFO e LIFO sono previsti con la gestione a lotti. Il passo 4 della [chiusura](Chiusura-e-bilancio) registra le + rimanenze finali al costo medio ponderato. ## Ricostruzione diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index da5c07b..ca19ee3 100644 --- a/docs/wiki/Roadmap.md +++ b/docs/wiki/Roadmap.md @@ -13,7 +13,7 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo quando verrà deciso esplicitamente. -**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0), M7 (0.7.0), M8 (0.8.0), M9 (0.9.0). **Prossima:** M10. +**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0), M7 (0.7.0), M8 (0.8.0), M9 (0.9.0), M10 (0.10.0). **Prossima:** M11. | # | Milestone | Contenuto principale | Versione | |---|---|---|---| diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index acf2037..b153674 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -28,9 +28,11 @@ **Contabilità e fisco** - [Contabilità](Contabilita) +- [Chiusura e bilancio](Chiusura-e-bilancio) - [IVA](IVA) - [Cespiti](Cespiti) - [Intrastat](Intrastat) +- [Dichiarazioni d'intento](Dichiarazioni-d-intento) - [Scadenzario](Scadenzario) - [Fatturazione elettronica](Fatturazione-elettronica) - [Fiscalità italiana](Fiscalita-italiana) diff --git a/docs/wiki/img/bilancio-cee.png b/docs/wiki/img/bilancio-cee.png new file mode 100644 index 0000000..8c4a092 Binary files /dev/null and b/docs/wiki/img/bilancio-cee.png differ diff --git a/docs/wiki/img/bilancio-indici.png b/docs/wiki/img/bilancio-indici.png new file mode 100644 index 0000000..7453086 Binary files /dev/null and b/docs/wiki/img/bilancio-indici.png differ diff --git a/docs/wiki/img/bilancio-riclassificato.png b/docs/wiki/img/bilancio-riclassificato.png new file mode 100644 index 0000000..bc746b5 Binary files /dev/null and b/docs/wiki/img/bilancio-riclassificato.png differ diff --git a/docs/wiki/img/cespiti-ammortamenti.png b/docs/wiki/img/cespiti-ammortamenti.png new file mode 100644 index 0000000..b3ec85b Binary files /dev/null and b/docs/wiki/img/cespiti-ammortamenti.png differ diff --git a/docs/wiki/img/cespiti-categorie.png b/docs/wiki/img/cespiti-categorie.png new file mode 100644 index 0000000..580f125 Binary files /dev/null and b/docs/wiki/img/cespiti-categorie.png differ diff --git a/docs/wiki/img/cespiti-registro.png b/docs/wiki/img/cespiti-registro.png new file mode 100644 index 0000000..1fd03e0 Binary files /dev/null and b/docs/wiki/img/cespiti-registro.png differ diff --git a/docs/wiki/img/chiusura-controlli.png b/docs/wiki/img/chiusura-controlli.png new file mode 100644 index 0000000..d66eca5 Binary files /dev/null and b/docs/wiki/img/chiusura-controlli.png differ diff --git a/docs/wiki/img/chiusura-esercizio.png b/docs/wiki/img/chiusura-esercizio.png new file mode 100644 index 0000000..233361a Binary files /dev/null and b/docs/wiki/img/chiusura-esercizio.png differ diff --git a/docs/wiki/img/dichiarazioni-intento.png b/docs/wiki/img/dichiarazioni-intento.png new file mode 100644 index 0000000..26ce7e7 Binary files /dev/null and b/docs/wiki/img/dichiarazioni-intento.png differ diff --git a/docs/wiki/img/intrastat-elenco.png b/docs/wiki/img/intrastat-elenco.png new file mode 100644 index 0000000..66ebe03 Binary files /dev/null and b/docs/wiki/img/intrastat-elenco.png differ diff --git a/docs/wiki/img/ratei-risconti.png b/docs/wiki/img/ratei-risconti.png new file mode 100644 index 0000000..9665089 Binary files /dev/null and b/docs/wiki/img/ratei-risconti.png differ diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index 4acf027..6aced45 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -274,6 +274,7 @@ public sealed partial class DocumentEngine await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false); await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false); await _ledger.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false); + await SyncIntentAsync(uow, pack, record.Family, id, cancellationToken).ConfigureAwait(false); } await uow.CommitAsync(cancellationToken).ConfigureAwait(false); @@ -308,6 +309,7 @@ public sealed partial class DocumentEngine await _fiscal.DemandOpenAsync(company, draft.Header.DocumentDate, PeriodUse.Vat, cancellationToken).ConfigureAwait(false); } + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); await uow.BeginAsync(cancellationToken).ConfigureAwait(false); var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, definition.ConfirmAction); @@ -318,6 +320,11 @@ public sealed partial class DocumentEngine } await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is { } intent) + { + // A sale under a declaration of intent needs the declaration and the ceiling left (ADR 0042). + await YearEnd.IntentDeclarationService.CheckAsync(uow, intent, definition.Behavior, record, errors, cancellationToken).ConfigureAwait(false); + } if (definition.Behavior.Has(DocumentEffects.Ledger)) { @@ -363,6 +370,7 @@ public sealed partial class DocumentEngine await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false); await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false); await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false); + await SyncIntentAsync(uow, pack, family, id, cancellationToken).ConfigureAwait(false); await uow.CommitAsync(cancellationToken).ConfigureAwait(false); LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName); } @@ -728,6 +736,7 @@ public sealed partial class DocumentEngine { var company = Company(actor, companyCode); var store = DocumentStores.Of(family); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) { await uow.BeginAsync(cancellationToken).ConfigureAwait(false); @@ -752,6 +761,7 @@ public sealed partial class DocumentEngine // A cancelled delivery note gives its stock back; a closed or reopened order its open quantities. await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false); await _ledger.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false); + await SyncIntentAsync(uow, pack, family, id, cancellationToken).ConfigureAwait(false); await uow.CommitAsync(cancellationToken).ConfigureAwait(false); LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName); } @@ -908,6 +918,11 @@ public sealed partial class DocumentEngine } // Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date. + private static Task SyncIntentAsync(IUnitOfWork uow, Fiscal.Abstractions.IFiscalPack pack, DocumentFamily family, long id, CancellationToken cancellationToken) => + pack.GetFeature() is { } intent + ? YearEnd.IntentDeclarationService.SyncDocumentAsync(uow, intent, family, id, cancellationToken) + : Task.CompletedTask; + private static bool IsRegistered(DocumentKind kind) => kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote; // The rules of a supplier document (§11.5): its own number and date, the VAT date not before it, no duplicate of diff --git a/src/Khaemhat.Application/Inventory/InventoryService.cs b/src/Khaemhat.Application/Inventory/InventoryService.cs index dae909c..0fff417 100644 --- a/src/Khaemhat.Application/Inventory/InventoryService.cs +++ b/src/Khaemhat.Application/Inventory/InventoryService.cs @@ -268,6 +268,13 @@ public sealed class InventoryService var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false); await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false); await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ValuationAsync(uow, date, warehouseId, method, cancellationToken).ConfigureAwait(false); + } + + /// The value of the stock at a date inside a unit of work (the closing values the inventory with it). + internal static async Task> ValuationAsync( + IUnitOfWork uow, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken) + { var lines = (await uow.Repository().ListAsync( Query.For().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken) .ConfigureAwait(false)).Items; diff --git a/src/Khaemhat.Application/Modules/BuiltInModules.cs b/src/Khaemhat.Application/Modules/BuiltInModules.cs index e9a2e92..4d5da7c 100644 --- a/src/Khaemhat.Application/Modules/BuiltInModules.cs +++ b/src/Khaemhat.Application/Modules/BuiltInModules.cs @@ -33,6 +33,8 @@ public static class BuiltInModules ("sales.invoice.delete", "Eliminare fatture in bozza"), ("sales.invoice.print", "Stampare fatture di vendita"), ("sales.invoice.export", "Esportare fatture di vendita"), + ("sales.intent.read", "Vedere le dichiarazioni d'intento"), + ("sales.intent.write", "Registrare le dichiarazioni d'intento"), ("purchases.order.read", "Vedere ordini fornitore"), ("purchases.order.write", "Creare e modificare ordini fornitore"), ("purchases.invoice.read", "Vedere fatture di acquisto"), @@ -135,7 +137,7 @@ public static class PredefinedRoles [ new(Administration, "Amministrazione", "Tutte le funzioni dell'azienda, compresi utenti e impostazioni.", ["*"]), new("ACCOUNTING", "Contabilità", "Contabilità, IVA, cespiti, tesoreria, fatturazione elettronica e Intrastat.", - ["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read", + ["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read", "sales.intent.*", "purchases.invoice.*", "reports.report.read", "attachments.read", "attachments.write"]), new("SALES", "Vendite", "Preventivi, ordini, DDT e fatture di vendita; anagrafiche clienti.", ["sales.*", "parties.*", "items.item.read", "inventory.stock.read", "crm.lead.read", "crm.opportunity.read", diff --git a/src/Khaemhat.Application/Seeding/DemoYearEndSeeder.cs b/src/Khaemhat.Application/Seeding/DemoYearEndSeeder.cs new file mode 100644 index 0000000..91fb697 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoYearEndSeeder.cs @@ -0,0 +1,267 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Application.YearEnd; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Seeding; + +/// +/// The demo data of the year end (SPEC §14, issue #87): the opening balances of the year (share capital, retained +/// earnings, bank, the opening stock and the fixed assets bought in the years before with their funds), the standard categories and four assets, one of them +/// bought this year; the declaration of intent of Idrotermica Piemonte taken into the register and an invoice under it +/// (NI8C); an intra-EU sale of goods to Bergwerk Bau (Austria) with nomenclature and mass for the Intrastat list; the +/// insurance premium paid in October with its prepaid share. With these the guided closing of the demo year runs from +/// the first step to the last. Runs after the demo e-invoices and only once: when the company has fixed assets or +/// accruals it adds nothing. +/// +/// The document engine. +/// The document editor. +/// Posts the new invoices. +/// The fiscal pack of the company. +/// Reads and writes the company. +/// Which modules are licensed. +/// The clock. +public sealed class DemoYearEndSeeder( + DocumentEngine engine, DocumentEditor editor, LedgerService ledger, CompanyFiscalContext packs, IUnitOfWorkFactory factory, ILicenseGate licenses, TimeProvider clock) + : ICompanySeeder +{ + /// The share capital of the demo company. + public const decimal ShareCapital = 50_000m; + + /// The bank balance on the first of January. + public const decimal OpeningBank = 25_000m; + + /// The yearly insurance premium paid on the first of October. + public const decimal InsurancePremium = 1_800m; + + private const string InsuranceAccount = "21.03.005"; + + private const string RetainedEarnings = "10.02.001"; + + private static readonly Actor Seed = Actor.System; + + /// + public int Order => 70; + + /// + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CancellationToken cancellationToken) + { + if (!licenses.IsModuleActive(ModuleCodes.Accounting)) + { + return; + } + + var pack = await packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + var start = new DateOnly(today.Year, 1, 1); + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) + { + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For().Where(e => e.EntryDate == start && e.Source == GlEntrySource.Manual), cancellationToken) + .ConfigureAwait(false) > 0) + { + return; + } + + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await OpeningAsync(uow, pack, today, cancellationToken).ConfigureAwait(false); + await InsuranceAsync(uow, today, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is { } intent) + { + await IntentDeclarationService.AdoptAsync(uow, intent, null, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await InvoicesAsync(companyCode, today, cancellationToken).ConfigureAwait(false); + await ledger.PostPendingAsync(Seed, companyCode, start, today, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + // The opening entry of the year and the fixed assets: three bought in the years before (cost and funds in the + // opening entry) and the computers bought in March and paid by bank transfer. + private async Task OpeningAsync(IUnitOfWork uow, IFiscalPack pack, DateOnly today, CancellationToken cancellationToken) + { + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } closing + || !accounts.TryGetValue(closing.Accounts.Capital, out var capital) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank)) + { + return; + } + + var year = today.Year; + var start = new DateOnly(year, 1, 1); + var lines = new List(); + var assets = new List(); + if (licenses.IsModuleActive(ModuleCodes.Assets) && pack.GetFeature() is { } rules) + { + await FixedAssetService.CreateStandardCategoriesAsync(uow, rules.Coefficients, Seed.UserName, true, cancellationToken).ConfigureAwait(false); + var categories = (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Code, StringComparer.Ordinal); + void Add(string category, string description, int yearsBack, decimal cost, decimal fund, string? serial = null, string? location = null) + { + if (!categories.TryGetValue(category, out var c) || c.AssetAccountId is not { } asset || c.FundAccountId is not { } fundAccount) + { + return; + } + + var bought = new DateOnly(year - yearsBack, 3, 15); + assets.Add(new AssetInput(null, null, description, c.Id, bought, bought, cost) + { + OpeningCivilFund = fund, + OpeningFiscalFund = fund, + LastDepreciationYear = yearsBack > 0 ? year - 1 : null, + SerialNumber = serial, + Location = location, + }); + if (yearsBack > 0) + { + lines.Add(new EntryLineDraft(asset, null, description, cost, 0m)); + lines.Add(new EntryLineDraft(fundAccount, null, description, 0m, fund)); + } + } + + // Funds: the civil quotas of the years before, half in the first year. + Add("AUC", "Furgone Fiat Ducato 2.3 Multijet", 3, 32_000m, 16_000m, "ZFA25000002K12345", "Sede"); + Add("ATT", "Scaffalature metalliche magazzino", 2, 18_400m, 4_140m, null, "Magazzino"); + Add("MOB", "Arredi ufficio commerciale", 4, 9_600m, 4_032m, null, "Uffici"); + Add("EDP", "Server e personal computer", 0, 6_500m, 0m, "SRV-2026-001", "Sala server"); + } + + // The opening stock of the demo warehouse (the inventory entry of the first of January) at its cost. + var stock = (await InventoryService.ValuationAsync(uow, start, null, StockValuationMethod.WeightedAverage, cancellationToken).ConfigureAwait(false)).Sum(r => r.Value); + if (stock > 0m && accounts.TryGetValue(closing.Accounts.Inventory, out var inventory)) + { + lines.Add(new EntryLineDraft(inventory.Id, null, "Rimanenze iniziali", Math.Round(stock, 2, MidpointRounding.AwayFromZero), 0m)); + } + + lines.Add(new EntryLineDraft(bank.Id, null, null, OpeningBank, 0m)); + lines.Add(new EntryLineDraft(capital.Id, null, null, 0m, ShareCapital)); + if (accounts.TryGetValue(RetainedEarnings, out var retained)) + { + var balance = lines.Sum(l => l.Debit - l.Credit); + lines.Add(new EntryLineDraft(retained.Id, null, null, balance < 0m ? -balance : 0m, balance > 0m ? balance : 0m)); + } + await YearEndLedger.PostAsync(uow, start, "Apertura conti (dati dimostrativi)", GlEntrySource.Manual, null, lines, true, cancellationToken).ConfigureAwait(false); + + foreach (var input in assets) + { + await FixedAssetService.SaveAsync(uow, pack.Require(), input, Seed.UserName, true, cancellationToken).ConfigureAwait(false); + if (input.LastDepreciationYear is null + && (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).FirstOrDefault(c => c.Id == input.CategoryId) is { AssetAccountId: { } account }) + { + // Bought this year: the purchase, paid by bank transfer (the invoice of the supplier is not part of the demo). + var bought = input.PurchaseDate; + await YearEndLedger.PostAsync(uow, bought <= today ? bought : today, "Acquisto " + input.Description.ToLowerInvariant(), GlEntrySource.Manual, null, + [new EntryLineDraft(account, null, null, input.Cost, 0m), new EntryLineDraft(bank.Id, null, null, 0m, input.Cost)], true, cancellationToken) + .ConfigureAwait(false); + } + } + } + + // The insurance premium of the van, paid on the first of October for a year: three months fall in this year, nine + // in the next (prepaid expense). + private static async Task InsuranceAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken) + { + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var paid = new DateOnly(today.Year, 10, 1); + if (paid > today || !accounts.TryGetValue(InsuranceAccount, out var insurance) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank)) + { + return; + } + + const string description = "Premio assicurazione furgone 01/10 - 30/09"; + await YearEndLedger.PostAsync(uow, paid, description, GlEntrySource.Manual, null, + [new EntryLineDraft(insurance.Id, null, null, InsurancePremium, 0m), new EntryLineDraft(bank.Id, null, null, 0m, InsurancePremium)], true, cancellationToken) + .ConfigureAwait(false); + await AccrualService.SaveAsync(uow, new AccrualDeferral + { + Year = today.Year, + Kind = AccrualKind.PrepaidExpense, + Description = description, + AccountId = insurance.Id, + Amount = InsurancePremium, + PeriodStart = paid, + PeriodEnd = paid.AddYears(1).AddDays(-1), + DocumentNumber = "POL-4471", + }, Seed.UserName, true, cancellationToken).ConfigureAwait(false); + } + + // An invoice under the declaration of intent of Idrotermica Piemonte (NI8C) and an intra-EU sale of goods to + // Bergwerk Bau (NI41), both of today so that the numbering stays in date order. + private async Task InvoicesAsync(string company, DateOnly today, CancellationToken cancellationToken) + { + Dictionary parties; + List goods; + Dictionary taxCodes; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + parties = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal); + goods = [.. (await uow.Repository().ListAsync(Query.For().Where(i => i.IsDemo && i.Kind == ItemKind.Goods), cancellationToken).ConfigureAwait(false)).Items + .OrderBy(i => i.Id)]; + taxCodes = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(t => t.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal); + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0) + { + return; // No demo sales: the documents would open the numbering. + } + } + + var intrastat = goods.Where(i => !string.IsNullOrEmpty(i.CustomsCode) && i.NetWeight is > 0m).Take(2).ToList(); + if (parties.TryGetValue("Idrotermica Piemonte S.r.l.", out var idrotermica) && taxCodes.TryGetValue("NI8C", out var ni8c) && goods.Count > 3) + { + await InvoiceAsync(company, idrotermica, today, [(goods[1], 40m), (goods[3], 25m)], ni8c, "Fornitura in sospensione d'imposta", cancellationToken).ConfigureAwait(false); + } + + if (licenses.IsModuleActive(ModuleCodes.Intrastat) && parties.TryGetValue("Bergwerk Bau GmbH", out var bergwerk) && taxCodes.TryGetValue("NI41", out var ni41) + && intrastat.Count > 0) + { + await InvoiceAsync(company, bergwerk, today, [.. intrastat.Select(i => (i, 30m))], ni41, "Consegna franco destino Innsbruck", cancellationToken).ConfigureAwait(false); + } + } + + private async Task InvoiceAsync( + string company, long partyId, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, long taxCodeId, string notes, CancellationToken cancellationToken) + { + var record = await engine.NewAsync(Seed, company, "FI", cancellationToken).ConfigureAwait(false); + record.Header.IsDemo = true; + record.Header.DocumentDate = date; + record.Header.Notes = notes; + await editor.ApplyPartyAsync(Seed, company, record, partyId, cancellationToken).ConfigureAwait(false); + foreach (var (item, quantity) in lines) + { + var line = DocumentStores.Of(record.Family).NewLine(); + line.Quantity = quantity; + await editor.FillLineAsync(Seed, company, record, line, item.Id, cancellationToken).ConfigureAwait(false); + line.TaxCodeId = taxCodeId; + record.Lines.Add(line); + } + + record = await engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false); + await engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Application/YearEnd/AccrualService.cs b/src/Khaemhat.Application/YearEnd/AccrualService.cs new file mode 100644 index 0000000..8051b4b --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/AccrualService.cs @@ -0,0 +1,478 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.YearEnd; + +/// An accrual with the names of its account and party. +/// The accrual. +/// The code of the account. +/// The description of the account. +/// The customer or supplier. +public sealed record AccrualRow(AccrualDeferral Accrual, string AccountCode, string AccountDescription, string? PartyName); + +/// The exchange difference of an open item in foreign currency at the year end. +/// The open item. +/// Receivable or payable. +/// The customer or supplier. +/// Its name. +/// The control account. +/// The number of the document. +/// The date of the document. +/// The currency. +/// The rate of the document. +/// The rate of the year end; when none is known. +/// The residual in euro at the rate of the document. +/// The residual in the currency. +/// The difference in euro. +public sealed record ExchangeDifferenceLine( + long OpenItemId, OpenItemDirection Direction, long PartyId, string? PartyName, long AccountId, string? DocumentNumber, DateOnly DocumentDate, string CurrencyCode, + decimal DocumentRate, decimal? YearEndRate, decimal ResidualEuro, decimal ResidualCurrency, decimal Difference) +{ + /// Whether the difference is a gain. + public bool Gain => ExchangeDifferenceCalculator.IsGain(Direction, Difference); +} + +/// +/// The accruals and deferrals and the exchange differences of the year end (SPEC §11.7, issue #84, ADR 0043): ratei and +/// risconti typed or proposed from the costs that straddle the year end, the share computed by days; the open items in +/// foreign currency valued at the rate of the last day. Step 3 of the closing posts both and step 8 reverses them on +/// the first day of the next year. +/// +public sealed class AccrualService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + /// The history. + public AccrualService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(audit); + _factory = factory; + _permissions = permissions; + _packs = packs; + _audit = audit; + } + + /// The accruals of a year. + /// Who reads. + /// The company. + /// The fiscal year. + /// Cancellation. + /// The accruals. + public async Task> ListAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ListAsync(uow, year, cancellationToken).ConfigureAwait(false); + } + + /// Saves an accrual: the share is computed by days; one posted by the closing is read only. + /// Who saves. + /// The company. + /// The accrual; id 0 for a new one. + /// Cancellation. + /// The accrual saved. + public async Task SaveAsync(Actor actor, string companyCode, AccrualDeferral input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var saved = await SaveAsync(uow, input, actor.UserName, input.IsDemo, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, input.Id == 0 ? AuditAction.Insert : AuditAction.Update, saved.Id, null, saved, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return saved; + } + + /// Removes an accrual not posted yet. + /// Who removes. + /// The company. + /// The accrual. + /// 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, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var accrual = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (accrual.GlEntryId is not null) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.AccrualPosted]); + } + + await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, accrual, (AccrualDeferral?)null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Proposes the risconti of a year: the purchase invoices posted to the accounts of costs that usually straddle the + /// year end (insurance, rents, leasing, software), as a period of a year from the date of the document; the user + /// checks the period. A cost already proposed is not proposed again. + /// + /// Who proposes. + /// The company. + /// The fiscal year. + /// Cancellation. + /// How many were added. + public async Task ProposeAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var added = await ProposeAsync(uow, rules, year, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return added; + } + + /// The exchange differences of the open items in foreign currency at the end of a year. + /// Who reads. + /// The company. + /// The fiscal year. + /// Cancellation. + /// The differences. + public async Task> ExchangeDifferencesAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var fiscalYear = await YearAsync(uow, year, cancellationToken).ConfigureAwait(false); + return await ExchangeDifferencesAsync(uow, fiscalYear.EndDate, cancellationToken).ConfigureAwait(false); + } + + internal static async Task YearAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken) + { + var code = year.ToString(System.Globalization.CultureInfo.InvariantCulture); + var last = new DateOnly(year, 12, 31); + return await uow.Repository().FindAsync(Query.For().Where(y => y.Code == code), cancellationToken).ConfigureAwait(false) + ?? await uow.Repository().FindAsync(Query.For().Where(y => y.EndDate >= last && y.StartDate <= last), cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + } + + internal static async Task> ListAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken) + { + var accruals = (await uow.Repository().ListAsync( + Query.For().Where(a => a.Year == year).OrderBy(a => a.Kind).OrderBy(a => a.PeriodStart).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items; + var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false); + var names = await JournalEntryService.PartyNamesAsync(uow, accruals.Select(a => a.PartyId), cancellationToken).ConfigureAwait(false); + return + [ + .. accruals.Select(a => new AccrualRow( + a, + accounts.TryGetValue(a.AccountId, out var account) ? account.Code : string.Empty, + account?.Description ?? string.Empty, + a.PartyId is { } p && names.TryGetValue(p, out var name) ? name : null)), + ]; + } + + internal static async Task SaveAsync(IUnitOfWork uow, AccrualDeferral input, string? userName, bool isDemo, CancellationToken cancellationToken) + { + var errors = new List(); + input.Description = (input.Description ?? string.Empty).Trim(); + if (input.Description.Length == 0) + { + errors.Add("Description:" + YearEndErrors.DescriptionRequired); + } + + var account = (await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false)).GetValueOrDefault(input.AccountId); + var wanted = input.Kind is AccrualKind.AccruedIncome or AccrualKind.DeferredIncome ? AccountNature.Revenue : AccountNature.Cost; + if (account is null || !account.Postable || account.Nature != wanted) + { + errors.Add("AccountId:" + YearEndErrors.AccountRequired); + } + + if (input.Amount <= 0m) + { + errors.Add("Amount:" + YearEndErrors.AmountRequired); + } + + if (input.PeriodEnd < input.PeriodStart) + { + errors.Add("PeriodEnd:" + YearEndErrors.PeriodOrder); + } + + var fiscalYear = await YearAsync(uow, input.Year, cancellationToken).ConfigureAwait(false); + input.YearEnd = fiscalYear.EndDate; + if (input.PeriodStart > input.YearEnd || input.PeriodEnd <= input.YearEnd) + { + // Only a period that straddles the year end has something to adjust. + errors.Add("PeriodEnd:" + YearEndErrors.PeriodOutside); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + var repository = uow.Repository(); + input.Adjustment = AccrualDeferralCalculator.Share(input.Kind, input.Amount, input.PeriodStart, input.PeriodEnd, input.YearEnd); + input.Description = LedgerStore.Trim(input.Description, 200)!; + if (input.Id == 0) + { + input.IsDemo = isDemo; + input.Id = await repository.InsertAsync(input, cancellationToken).ConfigureAwait(false); + return input; + } + + var before = await repository.GetAsync(input.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (before.GlEntryId is not null) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.AccrualPosted]); + } + + input.RowVersion = before.RowVersion; + input.IsDemo = before.IsDemo; + input.SourceFamily = before.SourceFamily; + input.SourceDocumentId = before.SourceDocumentId; + _ = userName; + await repository.UpdateAsync(input, cancellationToken).ConfigureAwait(false); + return input; + } + + internal static async Task ProposeAsync(IUnitOfWork uow, IClosingRules rules, int year, string? userName, CancellationToken cancellationToken) + { + var fiscalYear = await YearAsync(uow, year, cancellationToken).ConfigureAwait(false); + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var candidates = rules.PrepaidCandidates.Where(accounts.ContainsKey).Select(c => accounts[c].Id).ToList(); + if (candidates.Count == 0) + { + return 0; + } + + var from = fiscalYear.StartDate; + var to = fiscalYear.EndDate; + var draft = GlEntryStatus.Draft; + var lines = (await uow.Repository().ListAsync( + Query.For().Where(l => candidates.Contains(l.AccountId) && l.EntryDate >= from && l.EntryDate <= to && l.Status != draft && l.Debit > 0m), + cancellationToken).ConfigureAwait(false)).Items; + if (lines.Count == 0) + { + return 0; + } + + var entryIds = lines.Select(l => l.EntryId).Distinct().ToList(); + var entries = (await uow.Repository().ListAsync(Query.For().Where(e => entryIds.Contains(e.Id)), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(e => e.Id); + var existing = (await uow.Repository().ListAsync(Query.For().Where(a => a.Year == year), cancellationToken).ConfigureAwait(false)) + .Items.Where(a => a.SourceDocumentId is not null).Select(a => (a.SourceFamily, a.SourceDocumentId, a.AccountId)).ToHashSet(); + var added = 0; + foreach (var line in lines.OrderBy(l => l.EntryDate).ThenBy(l => l.Id)) + { + var entry = entries[line.EntryId]; + if (entry.Source is not GlEntrySource.Document || entry.SourceFamily is not DocumentFamily.PurchaseDocument || entry.ReversedById is not null + || !existing.Add((entry.SourceFamily, entry.SourceDocumentId, line.AccountId))) + { + continue; + } + + var start = entry.DocumentDate ?? entry.EntryDate; + var end = start.AddYears(1).AddDays(-1); + if (end <= to) + { + continue; + } + + var accrual = new AccrualDeferral + { + Year = year, + Kind = AccrualKind.PrepaidExpense, + Description = LedgerStore.Trim(line.Description ?? entry.Description, 200)!, + AccountId = line.AccountId, + Amount = line.Debit, + PeriodStart = start, + PeriodEnd = end, + SourceFamily = entry.SourceFamily, + SourceDocumentId = entry.SourceDocumentId, + DocumentNumber = entry.DocumentNumber, + PartyId = entry.PartyId, + }; + await SaveAsync(uow, accrual, userName, entry.IsDemo, cancellationToken).ConfigureAwait(false); + added++; + } + + return added; + } + + internal static async Task> ExchangeDifferencesAsync(IUnitOfWork uow, DateOnly yearEnd, CancellationToken cancellationToken) + { + var items = (await uow.Repository().ListAsync( + Query.For().Where(o => !o.Closed && o.DocumentDate <= yearEnd && o.SourceDocumentId != null), cancellationToken).ConfigureAwait(false)).Items; + if (items.Count == 0) + { + return []; + } + + var currencies = new Dictionary<(DocumentFamily, long), (string Currency, decimal Rate)>(); + foreach (var group in items.Where(i => i.SourceFamily is DocumentFamily.SaleDocument or DocumentFamily.PurchaseDocument).GroupBy(i => i.SourceFamily!.Value)) + { + var ids = group.Select(i => i.SourceDocumentId!.Value).Distinct().ToList(); + IEnumerable headers = group.Key == DocumentFamily.SaleDocument + ? (await uow.Repository().ListAsync(Query.For().Where(d => ids.Contains(d.Id) && d.CurrencyCode != "EUR"), cancellationToken) + .ConfigureAwait(false)).Items + : (await uow.Repository().ListAsync(Query.For().Where(d => ids.Contains(d.Id) && d.CurrencyCode != "EUR"), cancellationToken) + .ConfigureAwait(false)).Items; + foreach (var header in headers) + { + currencies[(group.Key, header.Id)] = (header.CurrencyCode, header.ExchangeRate); + } + } + + if (currencies.Count == 0) + { + return []; + } + + var rates = new Dictionary(StringComparer.Ordinal); + foreach (var code in currencies.Values.Select(c => c.Currency).Distinct()) + { + var rate = await uow.Repository().FindAsync( + Query.For().Where(x => x.CurrencyCode == code && x.RateDate <= yearEnd).OrderByDescending(x => x.RateDate), cancellationToken).ConfigureAwait(false); + rates[code] = rate?.Rate; + } + + var names = await JournalEntryService.PartyNamesAsync(uow, items.Select(i => (long?)i.PartyId), cancellationToken).ConfigureAwait(false); + var result = new List(); + foreach (var item in items.OrderBy(i => i.DocumentDate).ThenBy(i => i.Id)) + { + if (item.Residual == 0m || !currencies.TryGetValue((item.SourceFamily!.Value, item.SourceDocumentId!.Value), out var currency)) + { + continue; + } + + var yearEndRate = rates[currency.Currency]; + var difference = yearEndRate is { } r ? ExchangeDifferenceCalculator.Difference(item.Residual, currency.Rate, r) : 0m; + result.Add(new ExchangeDifferenceLine( + item.Id, item.Direction, item.PartyId, names.TryGetValue(item.PartyId, out var name) ? name : null, item.AccountId, item.DocumentNumber, item.DocumentDate, + currency.Currency, currency.Rate, yearEndRate, item.Residual, ExchangeDifferenceCalculator.InCurrency(item.Residual, currency.Rate), difference)); + } + + return result; + } + + /// Step 3 of the closing: posts the accruals and the exchange differences of the year. + /// The entries written and the amount adjusted. + internal static async Task<(int Entries, decimal Amount, List Messages)> PostAsync( + IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear fiscalYear, int step, bool isDemo, CancellationToken cancellationToken) + { + var year = fiscalYear.EndDate.Year; + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var messages = new List(); + var entries = 0; + var amount = 0m; + var repository = uow.Repository(); + var accruals = (await repository.ListAsync(Query.For().Where(a => a.Year == year && a.GlEntryId == null), cancellationToken).ConfigureAwait(false)).Items + .Where(a => a.Adjustment != 0m).ToList(); + if (accruals.Count > 0) + { + var lines = new List(); + foreach (var accrual in accruals) + { + var text = accrual.Description; + switch (accrual.Kind) + { + case AccrualKind.AccruedIncome: + lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.AccruedIncome).Id, accrual.Adjustment, text)); + lines.Add(YearEndLedger.Credit(accrual.AccountId, accrual.Adjustment, text)); + break; + case AccrualKind.AccruedExpense: + lines.Add(YearEndLedger.Debit(accrual.AccountId, accrual.Adjustment, text)); + lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.AccruedExpenses).Id, accrual.Adjustment, text)); + break; + case AccrualKind.PrepaidExpense: + lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.PrepaidExpenses).Id, accrual.Adjustment, text)); + lines.Add(YearEndLedger.Credit(accrual.AccountId, accrual.Adjustment, text)); + break; + default: + lines.Add(YearEndLedger.Debit(accrual.AccountId, accrual.Adjustment, text)); + lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.DeferredIncome).Id, accrual.Adjustment, text)); + break; + } + } + + var entry = await YearEndLedger.PostAsync(uow, fiscalYear.EndDate, "Ratei e risconti " + fiscalYear.Code, GlEntrySource.Accrual, step, lines, isDemo, cancellationToken) + .ConfigureAwait(false); + foreach (var accrual in accruals) + { + accrual.GlEntryId = entry!.Id; + await repository.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false); + } + + entries++; + amount += accruals.Sum(a => a.Adjustment); + messages.Add("closing.accruals-posted|" + accruals.Count); + } + + var differences = (await ExchangeDifferencesAsync(uow, fiscalYear.EndDate, cancellationToken).ConfigureAwait(false)).ToList(); + foreach (var missing in differences.Where(d => d.YearEndRate is null).Select(d => d.CurrencyCode).Distinct()) + { + messages.Add("!closing.rate-missing|" + missing); + } + + var useful = differences.Where(d => d.Difference != 0m).ToList(); + if (useful.Count > 0) + { + var gains = YearEndLedger.Require(accounts, codes.ExchangeGains).Id; + var losses = YearEndLedger.Require(accounts, codes.ExchangeLosses).Id; + var lines = new List(); + foreach (var d in useful) + { + var text = "Differenza cambio " + d.CurrencyCode + " " + d.DocumentNumber; + + // A receivable grows with a positive difference; a payable grows with it as well, on the other side. + var control = d.Direction == OpenItemDirection.Receivable + ? YearEndLedger.Debit(d.AccountId, d.Difference, text, d.PartyId) + : YearEndLedger.Credit(d.AccountId, d.Difference, text, d.PartyId); + lines.Add(control); + var abs = Math.Abs(d.Difference); + lines.Add(d.Gain ? YearEndLedger.Credit(gains, abs, text) : YearEndLedger.Debit(losses, abs, text)); + } + + await YearEndLedger.PostAsync(uow, fiscalYear.EndDate, "Differenze cambio " + fiscalYear.Code, GlEntrySource.ExchangeDifference, step, lines, isDemo, cancellationToken) + .ConfigureAwait(false); + entries++; + amount += useful.Sum(d => d.Gain ? Math.Abs(d.Difference) : -Math.Abs(d.Difference)); + messages.Add("closing.exchange-posted|" + useful.Count); + } + + if (entries == 0) + { + messages.Add("closing.nothing-to-post"); + } + + return (entries, amount, messages); + } + + /// Undoes step 3: the accruals go back to not posted. + internal static async Task UnpostAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + foreach (var accrual in (await repository.ListAsync(Query.For().Where(a => a.Year == year && a.GlEntryId != null), cancellationToken).ConfigureAwait(false)).Items) + { + accrual.GlEntryId = null; + accrual.ReversalEntryId = null; + await repository.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Khaemhat.Application/YearEnd/ClosingService.cs b/src/Khaemhat.Application/YearEnd/ClosingService.cs new file mode 100644 index 0000000..97eedfb --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/ClosingService.cs @@ -0,0 +1,963 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.YearEnd; + +/// A final print of a closing, without its content. +/// The print. +/// What it is. +/// The file name. +/// The pages. +public sealed record ClosingPrintInfo(long Id, string Kind, string FileName, int Pages); + +/// The guided closing of a year as the screen shows it (mockup 050). +/// The year. +/// The closing, once started. +/// The nine steps (pending ones too). +/// The final prints. +/// The years of the company, for the choice. +public sealed record ClosingView(FiscalYear Year, ClosingRun? Run, IReadOnlyList Steps, IReadOnlyList Prints, IReadOnlyList Years) +{ + /// The next step to run, if any. + public int? NextStep => Steps.FirstOrDefault(s => s.Status == ClosingStepStatus.Pending)?.Number; + + /// The last step run, which can be repeated or undone. + public int? LastDone => Steps.LastOrDefault(s => s.Status != ClosingStepStatus.Pending)?.Number; +} + +/// +/// The guided closing of a fiscal year (SPEC §11.7, issue #85, mockup 050, ADR 0043), in nine steps run in order: +/// +/// checks (drafts, balance, accounts without a line of the statements, year not ended); +/// depreciation of the fixed assets; +/// accruals, deferrals and exchange differences; +/// inventory: the opening stock to costs, the closing stock at weighted average cost; +/// provisions: write-down of receivables and severance pay; +/// closing of the income accounts and the result to equity (the year goes to Closing); +/// closing of the balance-sheet accounts, by customer and supplier; +/// the next year with its opening entry and the reversal of the accruals; +/// the entries made final and the final prints. +/// +/// The last step run can be repeated or undone while its entries are not final; once every step is done the year is +/// locked and becomes read only. +/// +public sealed class ClosingService +{ + /// The number of steps. + public const int StepCount = 9; + + private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly FiscalYearService _fiscal; + private readonly LedgerQueryService _queries; + private readonly VatService _vat; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + /// The calendar. + /// The prints of the journal. + /// The prints of the VAT registers. + /// The history. + /// The clock. + public ClosingService( + IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, FiscalYearService fiscal, LedgerQueryService queries, VatService vat, + AuditTrail audit, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(queries); + ArgumentNullException.ThrowIfNull(vat); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _fiscal = fiscal; + _queries = queries; + _vat = vat; + _audit = audit; + _clock = clock; + } + + /// The closing of a year: the first year not closed when none is given. + /// Who reads. + /// The company. + /// The year, or none. + /// Cancellation. + /// The closing. + public async Task GetAsync(Actor actor, string companyCode, long? fiscalYearId = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ViewAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false); + } + + /// Runs a step (or runs again the last one run). + /// Who runs. + /// The company. + /// The year. + /// The step, 1-9. + /// Cancellation. + /// The closing. + public async Task RunStepAsync(Actor actor, string companyCode, long fiscalYearId, int number, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + if (number == StepCount) + { + await RunFinalStepAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false); + } + else + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await RunStepAsync(uow, pack, fiscalYearId, number, actor.UserName, _clock.GetUtcNow(), cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + return await GetAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false); + } + + /// Undoes the last step run: its entries are removed (refused once final). + /// Who undoes. + /// The company. + /// The year. + /// The step. + /// Cancellation. + /// The closing. + public async Task UndoStepAsync(Actor actor, string companyCode, long fiscalYearId, int number, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await UndoStepAsync(uow, fiscalYearId, number, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + return await GetAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false); + } + + /// Locks the year once every step is done: it becomes read only. + /// Who locks. + /// The company. + /// The year. + /// Cancellation. + /// The closing. + public async Task LockAsync(Actor actor, string companyCode, long fiscalYearId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var (year, run, steps) = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false); + if (run is null || steps.Any(s => s.Status is ClosingStepStatus.Pending or ClosingStepStatus.Failed)) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.StepsPending]); + } + + if (run.Status == ClosingStatus.Locked) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]); + } + + var before = Copy(year); + run.Status = ClosingStatus.Locked; + run.LockedAt = _clock.GetUtcNow().UtcDateTime; + run.LockedBy = actor.UserName; + await uow.Repository().UpdateAsync(run, cancellationToken).ConfigureAwait(false); + year.Status = FiscalYearStatus.Closed; + await uow.Repository().UpdateAsync(year, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, year.Id, before, year, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + return await GetAsync(actor, company, fiscalYearId, cancellationToken).ConfigureAwait(false); + } + + /// A final print of a closing. + /// Who reads. + /// The company. + /// The print. + /// Cancellation. + /// The PDF. + public async Task PrintAsync(Actor actor, string companyCode, long printId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.YearClose, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var print = await uow.Repository().GetAsync(printId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + return new LedgerFile(print.FileName, Infrastructure.Files.PdfWriter.MediaType, print.Content); + } + + internal static async Task ViewAsync(IUnitOfWork uow, long? fiscalYearId, CancellationToken cancellationToken) + { + var years = (await uow.Repository().ListAsync(Query.For().OrderBy(y => y.StartDate), cancellationToken).ConfigureAwait(false)).Items; + var year = fiscalYearId is { } id + ? years.FirstOrDefault(y => y.Id == id) ?? throw new KeyNotFoundException(YearEndErrors.NotFound) + : years.FirstOrDefault(y => y.Status != FiscalYearStatus.Closed) ?? (years.Count > 0 ? years[^1] : null) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + var (_, run, steps) = await LoadAsync(uow, year.Id, cancellationToken).ConfigureAwait(false); + var prints = new List(); + if (run is not null) + { + var runId = run.Id; + var rows = await uow.QueryAsync(SqlFragment.Of($"SELECT id AS id, kind AS kind, file_name AS file_name, pages AS pages FROM closing_prints WHERE run_id = {runId} ORDER BY id"), cancellationToken) + .ConfigureAwait(false); + prints.AddRange(rows.Select(r => new ClosingPrintInfo(r.Id, r.Kind, r.FileName, r.Pages))); + } + + return new ClosingView(year, run, steps, prints, years); + } + + internal static async Task RunStepAsync(IUnitOfWork uow, IFiscalPack pack, long fiscalYearId, int number, string? userName, DateTimeOffset now, CancellationToken cancellationToken) + { + if (number < 1 || number >= StepCount) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.StepOrder]); + } + + var (year, run, steps) = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false); + run ??= await StartAsync(uow, year, cancellationToken).ConfigureAwait(false); + steps = await StepsAsync(uow, run.Id, cancellationToken).ConfigureAwait(false); + if (run.Status == ClosingStatus.Locked) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]); + } + + var step = steps[number - 1]; + if (steps.Skip(number).Any(s => s.Status != ClosingStepStatus.Pending)) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.LaterStepDone]); + } + + if (steps.Take(number - 1).Any(s => s.Status == ClosingStepStatus.Pending)) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.StepOrder]); + } + + if (number > 1 && steps[0].Status == ClosingStepStatus.Failed) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.ChecksFailed]); + } + + if (step.Status != ClosingStepStatus.Pending) + { + // Running a step again: what it wrote goes first. + await UndoAsync(uow, year, run, step, cancellationToken).ConfigureAwait(false); + } + + var isDemo = await IsDemoAsync(uow, cancellationToken).ConfigureAwait(false); + var codes = pack.Require().Accounts; + var result = number switch + { + 1 => await ChecksAsync(uow, pack, year, now, cancellationToken).ConfigureAwait(false), + 2 => await DepreciationAsync(uow, pack, year, userName, cancellationToken).ConfigureAwait(false), + 3 => await AccrualsAsync(uow, codes, year, isDemo, cancellationToken).ConfigureAwait(false), + 4 => await InventoryAsync(uow, codes, year, isDemo, cancellationToken).ConfigureAwait(false), + 5 => await ProvisionsAsync(uow, pack.Require(), year, isDemo, cancellationToken).ConfigureAwait(false), + 6 => await CloseIncomeAsync(uow, codes, year, run, isDemo, cancellationToken).ConfigureAwait(false), + 7 => await CloseBalanceSheetAsync(uow, codes, year, isDemo, cancellationToken).ConfigureAwait(false), + _ => await OpenNextYearAsync(uow, codes, year, run, userName, isDemo, cancellationToken).ConfigureAwait(false), + }; + step.Status = result.Status; + step.Entries = result.Entries; + step.Amount = result.Amount; + step.Messages = result.Messages.Count == 0 ? null : string.Join('\n', result.Messages); + step.ExecutedAt = now.UtcDateTime; + step.ExecutedBy = userName; + await uow.Repository().UpdateAsync(step, cancellationToken).ConfigureAwait(false); + if (number == 6) + { + year.Status = FiscalYearStatus.Closing; + await uow.Repository().UpdateAsync(year, cancellationToken).ConfigureAwait(false); + } + + await uow.Repository().UpdateAsync(run, cancellationToken).ConfigureAwait(false); + } + + internal static async Task UndoStepAsync(IUnitOfWork uow, long fiscalYearId, int number, CancellationToken cancellationToken) + { + var (year, run, steps) = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false); + if (run is null) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.NoClosing]); + } + + if (run.Status == ClosingStatus.Locked) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]); + } + + if (number == StepCount) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.StepIrreversible]); + } + + var step = steps.FirstOrDefault(s => s.Number == number) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (steps.Skip(number).Any(s => s.Status != ClosingStepStatus.Pending)) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.LaterStepDone]); + } + + if (step.Status == ClosingStepStatus.Pending) + { + return; + } + + await UndoAsync(uow, year, run, step, cancellationToken).ConfigureAwait(false); + step.Status = ClosingStepStatus.Pending; + step.Entries = 0; + step.Amount = 0m; + step.Messages = null; + step.ExecutedAt = null; + step.ExecutedBy = null; + await uow.Repository().UpdateAsync(step, cancellationToken).ConfigureAwait(false); + await uow.Repository().UpdateAsync(run, cancellationToken).ConfigureAwait(false); + } + + private static async Task UndoAsync(IUnitOfWork uow, FiscalYear year, ClosingRun run, ClosingStep step, CancellationToken cancellationToken) + { + switch (step.Number) + { + case 2: + await FixedAssetService.UndoDepreciationAsync(uow, year.EndDate.Year, cancellationToken).ConfigureAwait(false); + break; + case 3: + // The accruals point to their entries: they let go first. + await AccrualService.UnpostAsync(uow, year.EndDate.Year, cancellationToken).ConfigureAwait(false); + await DeleteStepEntriesAsync(uow, year, 3, cancellationToken).ConfigureAwait(false); + break; + case 6: + await DeleteStepEntriesAsync(uow, year, 6, cancellationToken).ConfigureAwait(false); + run.Result = 0m; + year.Status = FiscalYearStatus.Open; + await uow.Repository().UpdateAsync(year, cancellationToken).ConfigureAwait(false); + break; + case 8: + await UndoNextYearAsync(uow, year, run, cancellationToken).ConfigureAwait(false); + break; + default: + await DeleteStepEntriesAsync(uow, year, step.Number, cancellationToken).ConfigureAwait(false); + break; + } + } + + private static async Task DeleteStepEntriesAsync(IUnitOfWork uow, FiscalYear year, int number, CancellationToken cancellationToken) + { + var from = year.StartDate; + var to = year.EndDate; + var step = (int?)number; + var ids = (await uow.Repository().ListAsync( + Query.For().Where(e => e.ClosingStep == step && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items.Select(e => e.Id); + await YearEndLedger.DeleteAsync(uow, ids, cancellationToken).ConfigureAwait(false); + } + + private async Task RunFinalStepAsync(Actor actor, string company, long fiscalYearId, CancellationToken cancellationToken) + { + FiscalYear year; + ClosingRun run; + var finalized = 0; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var loaded = await LoadAsync(uow, fiscalYearId, cancellationToken).ConfigureAwait(false); + year = loaded.Year; + run = loaded.Run ?? throw new ValidationFailedException(["Id:" + YearEndErrors.NoClosing]); + if (run.Status == ClosingStatus.Locked) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.ClosingLocked]); + } + + if (loaded.Steps.Take(StepCount - 1).Any(s => s.Status is ClosingStepStatus.Pending or ClosingStepStatus.Failed)) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.StepOrder]); + } + + if (loaded.Steps[StepCount - 1].Status != ClosingStepStatus.Pending) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.StepIrreversible]); + } + + finalized = await FinalizeAsync(uow, year.EndDate, actor.UserName, _clock.GetUtcNow().UtcDateTime, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + // The prints read what was committed: a failure here leaves the step to run again, the entries already final. + await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + var prints = new List(); + var journal = await _queries.PrintJournalAsync(actor, company, year.StartDate, year.EndDate, true, cancellationToken).ConfigureAwait(false); + prints.Add(new ClosingPrint { Kind = "journal", FileName = journal.FileName, Content = journal.Content }); + var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + var registers = (await uow.Repository().ListAsync(Query.For().OrderBy(r => r.Code), cancellationToken).ConfigureAwait(false)).Items; + foreach (var register in registers) + { + var file = await _vat.PrintRegisterAsync(actor, company, register.Id, year.StartDate, year.EndDate, false, cancellationToken).ConfigureAwait(false); + prints.Add(new ClosingPrint { Kind = "vat-" + register.Code, FileName = file.FileName, Content = file.Content }); + } + + var (assets, assetPages) = await FixedAssetService.PrintRegisterAsync(uow, year.EndDate.Year, 1, cancellationToken).ConfigureAwait(false); + prints.Add(new ClosingPrint { Kind = "assets", FileName = assets.FileName, Content = assets.Content, Pages = assetPages }); + var (statements, statementPages) = await FinancialStatementsService.PrintAsync(uow, schema, year.EndDate.Year, FinancialStatementForm.Ordinary, 1, cancellationToken) + .ConfigureAwait(false); + prints.Add(new ClosingPrint + { + Kind = "statements", + FileName = string.Create(Invariant, $"bilancio-{year.Code.Replace('/', '-')}.pdf"), + Content = statements, + Pages = statementPages, + }); + + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var runId = run.Id; + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM closing_prints WHERE run_id = {runId}"), cancellationToken).ConfigureAwait(false); + foreach (var print in prints) + { + print.RunId = run.Id; + print.Pages = print.Pages == 0 ? Pages(print.Content) : print.Pages; + await uow.Repository().InsertAsync(print, cancellationToken).ConfigureAwait(false); + } + + var step = (await StepsAsync(uow, run.Id, cancellationToken).ConfigureAwait(false))[StepCount - 1]; + step.Status = ClosingStepStatus.Done; + step.Entries = finalized; + step.Amount = 0m; + step.Messages = "closing.finalized|" + finalized.ToString(Invariant) + "\nclosing.prints|" + prints.Count.ToString(Invariant); + step.ExecutedAt = _clock.GetUtcNow().UtcDateTime; + step.ExecutedBy = actor.UserName; + await uow.Repository().UpdateAsync(step, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + } + + /// Makes final the posted entries up to a day, numbering them in the journal of their year. + internal static async Task FinalizeAsync(IUnitOfWork uow, DateOnly upTo, string? userName, DateTime now, CancellationToken cancellationToken) + { + var draft = GlEntryStatus.Draft; + if (await uow.Repository().CountAsync(Query.For().Where(e => e.Status == draft && e.EntryDate <= upTo), cancellationToken).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["UpTo:" + LedgerErrors.DraftsBeforeFinal]); + } + + var posted = GlEntryStatus.Posted; + var entries = (await uow.Repository().ListAsync( + Query.For().Where(e => e.Status == posted && e.EntryDate <= upTo).OrderBy(e => e.EntryDate).OrderBy(e => e.Number).OrderBy(e => e.Id), + cancellationToken).ConfigureAwait(false)).Items; + var years = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + foreach (var entry in entries) + { + var year = years.FirstOrDefault(y => y.StartDate <= entry.EntryDate && y.EndDate >= entry.EntryDate) + ?? throw new ValidationFailedException(["UpTo:" + LedgerErrors.NoFiscalYear]); + year.LastFinalEntryNumber++; + year.LastFinalEntryDate = entry.EntryDate; + entry.JournalNumber = year.LastFinalEntryNumber; + entry.FinalizedAt = now; + entry.FinalizedBy = userName; + await LedgerStore.SetStatusAsync(uow, entry, GlEntryStatus.Final, cancellationToken).ConfigureAwait(false); + } + + foreach (var year in years.Where(y => entries.Any(e => y.StartDate <= e.EntryDate && y.EndDate >= e.EntryDate))) + { + await uow.Repository().UpdateAsync(year, cancellationToken).ConfigureAwait(false); + } + + return entries.Count; + } + + private static async Task ChecksAsync(IUnitOfWork uow, IFiscalPack pack, FiscalYear year, DateTimeOffset now, CancellationToken cancellationToken) + { + var errors = new List(); + var warnings = new List(); + var from = year.StartDate; + var to = year.EndDate; + var draft = GlEntryStatus.Draft; + var drafts = await uow.Repository().CountAsync( + Query.For().Where(e => e.Status == draft && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false); + if (drafts > 0) + { + errors.Add("-closing.check-drafts|" + drafts.ToString(Invariant)); + } + + var unbalanced = (await uow.Repository().ListAsync( + Query.For().Where(e => e.Status != draft && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items.Count(e => !e.Balanced); + if (unbalanced > 0) + { + errors.Add("-closing.check-unbalanced|" + unbalanced.ToString(Invariant)); + } + + var balance = await LedgerQueryService.TrialBalanceAsync(uow, from, to, null, false, cancellationToken).ConfigureAwait(false); + if (balance.TotalDebit != balance.TotalCredit) + { + errors.Add("-closing.check-trial-balance|" + LedgerReport.Money(balance.TotalDebit - balance.TotalCredit)); + } + + if (pack.GetFeature() is { } schema) + { + var raw = await FinancialStatementsService.RawAsync(uow, schema, to.Year, cancellationToken).ConfigureAwait(false); + foreach (var account in raw.Unmapped) + { + warnings.Add("!closing.check-unmapped|" + account.Code + "|" + LedgerReport.Money(account.Balance)); + } + } + + if (DateOnly.FromDateTime(now.UtcDateTime) <= to) + { + warnings.Add("!closing.check-year-not-ended|" + LedgerReport.Date(to)); + } + + var earlier = (await uow.Repository().ListAsync(Query.For().Where(y => y.EndDate < from), cancellationToken).ConfigureAwait(false)).Items + .Where(y => y.Status != FiscalYearStatus.Closed).ToList(); + foreach (var open in earlier) + { + warnings.Add("!closing.check-previous-open|" + open.Code); + } + + var messages = errors.Concat(warnings).ToList(); + if (messages.Count == 0) + { + messages.Add("closing.check-ok"); + } + + var status = errors.Count > 0 ? ClosingStepStatus.Failed : warnings.Count > 0 ? ClosingStepStatus.ToVerify : ClosingStepStatus.Passed; + return new StepResult(status, 0, balance.Result, messages); + } + + private static async Task DepreciationAsync(IUnitOfWork uow, IFiscalPack pack, FiscalYear year, string? userName, CancellationToken cancellationToken) + { + if (pack.GetFeature() is not { } rules) + { + return new StepResult(ClosingStepStatus.Done, 0, 0m, ["closing.nothing-to-post"]); + } + + var (amount, entry) = await FixedAssetService.DepreciateAsync(uow, rules, year.EndDate.Year, year.EndDate, 2, userName, cancellationToken).ConfigureAwait(false); + return entry is null + ? new StepResult(ClosingStepStatus.Done, 0, 0m, ["closing.depreciation-none"]) + : new StepResult(ClosingStepStatus.Done, 1, amount, ["closing.depreciation-posted|" + LedgerReport.Money(amount)]); + } + + private static async Task AccrualsAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, bool isDemo, CancellationToken cancellationToken) + { + var (entries, amount, messages) = await AccrualService.PostAsync(uow, codes, year, 3, isDemo, cancellationToken).ConfigureAwait(false); + return new StepResult(messages.Any(m => m.StartsWith('!')) ? ClosingStepStatus.ToVerify : ClosingStepStatus.Done, entries, amount, messages); + } + + private static async Task InventoryAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, bool isDemo, CancellationToken cancellationToken) + { + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var inventory = YearEndLedger.Require(accounts, codes.Inventory); + var opening = YearEndLedger.Require(accounts, codes.OpeningInventory); + var closing = YearEndLedger.Require(accounts, codes.ClosingInventory); + var current = await BalanceAsync(uow, inventory.Id, year.EndDate, cancellationToken).ConfigureAwait(false); + var rows = await InventoryService.ValuationAsync(uow, year.EndDate, null, StockValuationMethod.WeightedAverage, cancellationToken).ConfigureAwait(false); + var value = Math.Round(rows.Sum(r => r.Value), 2, MidpointRounding.AwayFromZero); + var lines = new List + { + YearEndLedger.Debit(opening.Id, current, "Storno rimanenze iniziali"), + YearEndLedger.Credit(inventory.Id, current, "Storno rimanenze iniziali"), + YearEndLedger.Debit(inventory.Id, value, "Rimanenze finali al costo medio ponderato"), + YearEndLedger.Credit(closing.Id, value, "Rimanenze finali al costo medio ponderato"), + }; + var entry = await YearEndLedger.PostAsync(uow, year.EndDate, "Rimanenze di magazzino " + year.Code, GlEntrySource.Closing, 4, lines, isDemo, cancellationToken) + .ConfigureAwait(false); + var messages = new List + { + "closing.inventory-opening|" + LedgerReport.Money(current), + "closing.inventory-closing|" + LedgerReport.Money(value) + "|" + rows.Count.ToString(Invariant), + }; + return new StepResult(ClosingStepStatus.Done, entry is null ? 0 : 1, value, messages); + } + + private static async Task ProvisionsAsync(IUnitOfWork uow, IClosingRules rules, FiscalYear year, bool isDemo, CancellationToken cancellationToken) + { + var codes = rules.Accounts; + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var messages = new List(); + var lines = new List(); + var end = year.EndDate; + var receivable = OpenItemDirection.Receivable; + var receivables = (await uow.Repository().ListAsync( + Query.For().Where(o => o.Direction == receivable && !o.Closed && o.DocumentDate <= end), cancellationToken).ConfigureAwait(false)).Items.Sum(o => o.Residual); + var badDebt = Math.Round(Math.Max(0m, receivables) * rules.BadDebtPercent / 100m, 2, MidpointRounding.AwayFromZero); + if (badDebt > 0m) + { + var text = "Svalutazione crediti " + rules.BadDebtPercent.ToString("0.##", Invariant) + "%"; + lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.BadDebtCharge).Id, badDebt, text)); + lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.BadDebtFund).Id, badDebt, text)); + messages.Add("closing.bad-debt|" + LedgerReport.Money(badDebt) + "|" + LedgerReport.Money(receivables)); + } + + // Severance pay of the year: the wages divided by 13.5 (art. 2120 c.c.), less what the payroll already set aside. + var severance = YearEndLedger.Require(accounts, codes.SeveranceCharge); + var wages = 0m; + foreach (var account in accounts.Values.Where(a => a.Postable && a.Nature == AccountNature.Cost && a.StatementLine == "B.9.a")) + { + wages += await BalanceAsync(uow, account.Id, end, cancellationToken, year.StartDate).ConfigureAwait(false); + } + + var booked = await BalanceAsync(uow, severance.Id, end, cancellationToken, year.StartDate).ConfigureAwait(false); + var due = Math.Round(wages / 13.5m, 2, MidpointRounding.AwayFromZero) - booked; + if (due > 0m) + { + lines.Add(YearEndLedger.Debit(severance.Id, due, "Accantonamento TFR")); + lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.SeveranceFund).Id, due, "Accantonamento TFR")); + messages.Add("!closing.severance|" + LedgerReport.Money(due) + "|" + LedgerReport.Money(wages)); + } + + var entry = await YearEndLedger.PostAsync(uow, end, "Accantonamenti " + year.Code, GlEntrySource.Closing, 5, lines, isDemo, cancellationToken).ConfigureAwait(false); + if (entry is null) + { + messages.Add("closing.nothing-to-post"); + } + + return new StepResult(messages.Any(m => m.StartsWith('!')) ? ClosingStepStatus.ToVerify : ClosingStepStatus.Done, entry is null ? 0 : 1, badDebt + Math.Max(0m, due), messages); + } + + private static async Task CloseIncomeAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, ClosingRun run, bool isDemo, CancellationToken cancellationToken) + { + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var summary = YearEndLedger.Require(accounts, codes.IncomeSummary); + var resultAccount = YearEndLedger.Require(accounts, codes.Result); + var balances = await BalancesAsync(uow, year.StartDate, year.EndDate, byParty: false, cancellationToken).ConfigureAwait(false); + var byId = accounts.Values.ToDictionary(a => a.Id); + var lines = new List(); + var result = 0m; + foreach (var (accountId, _, amount) in balances.OrderBy(b => byId[b.AccountId].Code, StringComparer.Ordinal)) + { + var account = byId[accountId]; + if (account.Nature is not (AccountNature.Cost or AccountNature.Revenue) || amount == 0m) + { + continue; + } + + // The balance goes to the income summary: a cost (debit) is credited, a revenue debited. + lines.Add(YearEndLedger.Credit(accountId, amount, account.Description)); + lines.Add(YearEndLedger.Debit(summary.Id, amount, account.Description)); + result -= amount; + } + + var entries = 0; + if (await YearEndLedger.PostAsync(uow, year.EndDate, "Chiusura conti economici " + year.Code, GlEntrySource.Closing, 6, Merge(lines, summary.Id), isDemo, cancellationToken) + .ConfigureAwait(false) is not null) + { + entries++; + } + + // A profit (revenues above costs) leaves the summary in credit and goes to equity in credit; a loss in debit. + var text = result >= 0m ? "Utile dell'esercizio" : "Perdita dell'esercizio"; + if (await YearEndLedger.PostAsync( + uow, year.EndDate, text + " " + year.Code, GlEntrySource.Closing, 6, + [YearEndLedger.Debit(summary.Id, result, text), YearEndLedger.Credit(resultAccount.Id, result, text)], isDemo, cancellationToken).ConfigureAwait(false) is not null) + { + entries++; + } + + run.Result = result; + return new StepResult(ClosingStepStatus.Done, entries, result, [(result >= 0m ? "closing.profit|" : "closing.loss|") + LedgerReport.Money(Math.Abs(result))]); + } + + private static async Task CloseBalanceSheetAsync(IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, bool isDemo, CancellationToken cancellationToken) + { + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var closingBalance = YearEndLedger.Require(accounts, codes.ClosingBalance); + var lines = await BalanceSheetLinesAsync(uow, accounts, year, cancellationToken).ConfigureAwait(false); + var drafts = new List(); + foreach (var (accountId, partyId, amount) in lines) + { + drafts.Add(YearEndLedger.Credit(accountId, amount, null, partyId)); + } + + var debit = lines.Where(l => l.Amount > 0m).Sum(l => l.Amount); + var credit = -lines.Where(l => l.Amount < 0m).Sum(l => l.Amount); + if (debit != credit) + { + throw new ValidationFailedException(["Number:" + YearEndErrors.ClosingUnbalanced + ":" + LedgerReport.Money(debit - credit)]); + } + + drafts.Add(YearEndLedger.Debit(closingBalance.Id, debit, "Attività")); + drafts.Add(YearEndLedger.Credit(closingBalance.Id, credit, "Passività e patrimonio netto")); + var entry = await YearEndLedger.PostAsync(uow, year.EndDate, "Stato patrimoniale finale " + year.Code, GlEntrySource.Closing, 7, drafts, isDemo, cancellationToken) + .ConfigureAwait(false); + return new StepResult(ClosingStepStatus.Done, entry is null ? 0 : 1, debit, ["closing.balance-closed|" + lines.Count.ToString(Invariant) + "|" + LedgerReport.Money(debit)]); + } + + private static async Task OpenNextYearAsync( + IUnitOfWork uow, YearEndAccountCodes codes, FiscalYear year, ClosingRun run, string? userName, bool isDemo, CancellationToken cancellationToken) + { + var next = await uow.Repository().FindAsync( + Query.For().Where(y => y.StartDate > year.EndDate).OrderBy(y => y.StartDate), cancellationToken).ConfigureAwait(false); + var messages = new List(); + if (next is null) + { + next = await CreateYearAsync(uow, year.EndDate.AddDays(1), cancellationToken).ConfigureAwait(false); + messages.Add("closing.year-created|" + next.Code); + } + + run.NextFiscalYearId = next.Id; + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var openingBalance = YearEndLedger.Require(accounts, codes.OpeningBalance); + + // The opening entry mirrors the closing one of step 7: the balances before it, by account and party. + var closing = await ClosingEntryAsync(uow, year, cancellationToken).ConfigureAwait(false); + var drafts = new List(); + var entries = 0; + if (closing is not null) + { + var closingAccount = YearEndLedger.Require(accounts, codes.ClosingBalance).Id; + var lines = (await LedgerStore.LinesAsync(uow, closing.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.AccountId != closingAccount).ToList(); + foreach (var line in lines) + { + drafts.Add(new EntryLineDraft(line.AccountId, line.PartyId, line.Description, line.Credit, line.Debit)); + } + + drafts.Add(YearEndLedger.Credit(openingBalance.Id, lines.Sum(l => l.Credit), "Attività")); + drafts.Add(YearEndLedger.Debit(openingBalance.Id, lines.Sum(l => l.Debit), "Passività e patrimonio netto")); + if (await YearEndLedger.PostAsync(uow, next.StartDate, "Stato patrimoniale iniziale " + next.Code, GlEntrySource.Closing, 8, drafts, isDemo, cancellationToken) + .ConfigureAwait(false) is not null) + { + entries++; + messages.Add("closing.opening-posted|" + next.Code); + } + } + + // The accruals and the exchange differences of step 3 are reversed on the first day of the new year. + var from = year.StartDate; + var to = year.EndDate; + var step3 = (int?)3; + var adjustments = (await uow.Repository().ListAsync( + Query.For().Where(e => e.ClosingStep == step3 && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items; + foreach (var adjustment in adjustments) + { + var reversal = await JournalEntryService.ReverseAsync(uow, adjustment, next.StartDate, userName, cancellationToken).ConfigureAwait(false); + reversal.ClosingStep = 8; + await uow.Repository().UpdateAsync(reversal, cancellationToken).ConfigureAwait(false); + if (adjustment.Source == GlEntrySource.Accrual) + { + var repository = uow.Repository(); + var entryId = (long?)adjustment.Id; + foreach (var accrual in (await repository.ListAsync(Query.For().Where(a => a.GlEntryId == entryId), cancellationToken).ConfigureAwait(false)).Items) + { + accrual.ReversalEntryId = reversal.Id; + await repository.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false); + } + } + + entries++; + } + + if (adjustments.Count > 0) + { + messages.Add("closing.adjustments-reversed|" + adjustments.Count.ToString(Invariant)); + } + + return new StepResult(ClosingStepStatus.Done, entries, closing?.TotalDebit ?? 0m, messages); + } + + private static async Task UndoNextYearAsync(IUnitOfWork uow, FiscalYear year, ClosingRun run, CancellationToken cancellationToken) + { + if (run.NextFiscalYearId is not { } nextId || await uow.Repository().GetAsync(nextId, cancellationToken).ConfigureAwait(false) is not { } next) + { + return; + } + + var from = next.StartDate; + var to = next.EndDate; + var step8 = (int?)8; + var entries = (await uow.Repository().ListAsync( + Query.For().Where(e => e.ClosingStep == step8 && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false)).Items; + + // The entries of step 3 can be reversed again: they and their accruals let go of the reversals first. + foreach (var reversed in entries.Where(e => e.ReversalOfId is not null)) + { + if (await uow.Repository().GetAsync(reversed.ReversalOfId!.Value, cancellationToken).ConfigureAwait(false) is { } original) + { + original.ReversedById = null; + await uow.Repository().UpdateAsync(original, cancellationToken).ConfigureAwait(false); + } + } + + var accruals = uow.Repository(); + var yearNumber = year.EndDate.Year; + foreach (var accrual in (await accruals.ListAsync(Query.For().Where(a => a.Year == yearNumber && a.ReversalEntryId != null), cancellationToken) + .ConfigureAwait(false)).Items) + { + accrual.ReversalEntryId = null; + await accruals.UpdateAsync(accrual, cancellationToken).ConfigureAwait(false); + } + + await YearEndLedger.DeleteAsync(uow, entries.Select(e => e.Id), cancellationToken).ConfigureAwait(false); + run.NextFiscalYearId = null; + } + + private static async Task ClosingEntryAsync(IUnitOfWork uow, FiscalYear year, CancellationToken cancellationToken) + { + var from = year.StartDate; + var to = year.EndDate; + var step7 = (int?)7; + return await uow.Repository().FindAsync( + Query.For().Where(e => e.ClosingStep == step7 && e.EntryDate >= from && e.EntryDate <= to), cancellationToken).ConfigureAwait(false); + } + + private static async Task> BalanceSheetLinesAsync( + IUnitOfWork uow, Dictionary accounts, FiscalYear year, CancellationToken cancellationToken) + { + var byId = accounts.Values.ToDictionary(a => a.Id); + var balances = await BalancesAsync(uow, null, year.EndDate, byParty: true, cancellationToken).ConfigureAwait(false); + return + [ + .. balances + .Where(b => b.Amount != 0m && byId.TryGetValue(b.AccountId, out var a) && a.Nature is AccountNature.Asset or AccountNature.Liability) + .OrderBy(b => byId[b.AccountId].Code, StringComparer.Ordinal).ThenBy(b => b.PartyId), + ]; + } + + /// The balances (debit minus credit) of the posted entries, by account and optionally by party. + private static async Task> BalancesAsync( + IUnitOfWork uow, DateOnly? from, DateOnly to, bool byParty, CancellationToken cancellationToken) + { + var draft = nameof(GlEntryStatus.Draft); + var start = from ?? DateOnly.MinValue; + var rows = byParty + ? await uow.QueryAsync(SqlFragment.Of($""" + SELECT l.account_id AS account_id, l.party_id AS party_id, SUM(l.debit - l.credit) AS amount + FROM gl_entry_lines l + WHERE l.entry_date >= {start} AND l.entry_date <= {to} AND l.status <> {draft} + GROUP BY l.account_id, l.party_id + """), cancellationToken).ConfigureAwait(false) + : await uow.QueryAsync(SqlFragment.Of($""" + SELECT l.account_id AS account_id, NULL AS party_id, SUM(l.debit - l.credit) AS amount + FROM gl_entry_lines l + WHERE l.entry_date >= {start} AND l.entry_date <= {to} AND l.status <> {draft} + GROUP BY l.account_id + """), cancellationToken).ConfigureAwait(false); + return [.. rows.Select(r => (r.AccountId, r.PartyId, r.Amount ?? 0m))]; + } + + private static async Task BalanceAsync(IUnitOfWork uow, long accountId, DateOnly to, CancellationToken cancellationToken, DateOnly? from = null) + { + var draft = nameof(GlEntryStatus.Draft); + var start = from ?? DateOnly.MinValue; + return await uow.QuerySingleAsync(SqlFragment.Of($""" + SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l + WHERE l.account_id = {accountId} AND l.entry_date >= {start} AND l.entry_date <= {to} AND l.status <> {draft} + """), cancellationToken).ConfigureAwait(false) ?? 0m; + } + + private static List Merge(List lines, long summaryId) + { + // One line for the income summary on each side, so the entry stays readable. + var others = lines.Where(l => l.AccountId != summaryId).ToList(); + var net = lines.Where(l => l.AccountId == summaryId).ToList(); + var debit = net.Sum(l => Math.Max(0m, l.Debit - l.Credit)); + var credit = net.Sum(l => Math.Max(0m, l.Credit - l.Debit)); + others.Add(YearEndLedger.Debit(summaryId, debit, "Costi dell'esercizio")); + others.Add(YearEndLedger.Credit(summaryId, credit, "Ricavi dell'esercizio")); + return others; + } + + private static async Task CreateYearAsync(IUnitOfWork uow, DateOnly start, CancellationToken cancellationToken) + { + var end = start.AddYears(1).AddDays(-1); + var year = new FiscalYear + { + Code = start.Year == end.Year ? start.Year.ToString(Invariant) : string.Create(Invariant, $"{start.Year}/{end.Year % 100:00}"), + StartDate = start, + EndDate = end, + }; + year.Id = await uow.Repository().InsertAsync(year, cancellationToken).ConfigureAwait(false); + for (var i = 0; i < 12; i++) + { + var first = start.AddMonths(i); + await uow.Repository().InsertAsync( + new FiscalPeriod { FiscalYearId = year.Id, Number = i + 1, StartDate = first, EndDate = first.AddMonths(1).AddDays(-1) }, cancellationToken).ConfigureAwait(false); + } + + return year; + } + + private static async Task StartAsync(IUnitOfWork uow, FiscalYear year, CancellationToken cancellationToken) + { + var run = new ClosingRun { FiscalYearId = year.Id, YearCode = year.Code, Status = ClosingStatus.InProgress }; + run.Id = await uow.Repository().InsertAsync(run, cancellationToken).ConfigureAwait(false); + for (var number = 1; number <= StepCount; number++) + { + await uow.Repository().InsertAsync(new ClosingStep { RunId = run.Id, Number = number }, cancellationToken).ConfigureAwait(false); + } + + return run; + } + + private static async Task<(FiscalYear Year, ClosingRun? Run, IReadOnlyList Steps)> LoadAsync(IUnitOfWork uow, long fiscalYearId, CancellationToken cancellationToken) + { + var year = await uow.Repository().GetAsync(fiscalYearId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + var run = await uow.Repository().FindAsync(Query.For().Where(r => r.FiscalYearId == fiscalYearId), cancellationToken).ConfigureAwait(false); + IReadOnlyList steps = run is null + ? [.. Enumerable.Range(1, StepCount).Select(n => new ClosingStep { Number = n })] + : await StepsAsync(uow, run.Id, cancellationToken).ConfigureAwait(false); + return (year, run, steps); + } + + private static async Task> StepsAsync(IUnitOfWork uow, long runId, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().Where(s => s.RunId == runId).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false)).Items; + + private static async Task IsDemoAsync(IUnitOfWork uow, CancellationToken cancellationToken) => + await uow.Repository().CountAsync(Query.For().Where(e => e.IsDemo), cancellationToken).ConfigureAwait(false) > 0; + + private static int Pages(byte[] pdf) + { + // The PDF writer marks every page with "/Type /Page"; the pages object is "/Type /Pages". + var text = System.Text.Encoding.ASCII.GetString(pdf); + var count = 0; + for (var index = text.IndexOf("/Type /Page", StringComparison.Ordinal); index >= 0; index = text.IndexOf("/Type /Page", index + 1, StringComparison.Ordinal)) + { + if (index + 11 >= text.Length || text[index + 11] != 's') + { + count++; + } + } + + return Math.Max(1, count); + } + + private static FiscalYear Copy(FiscalYear year) => new() + { + Id = year.Id, + Code = year.Code, + StartDate = year.StartDate, + EndDate = year.EndDate, + Status = year.Status, + JournalFirstPage = year.JournalFirstPage, + LastFinalEntryNumber = year.LastFinalEntryNumber, + LastFinalEntryDate = year.LastFinalEntryDate, + }; + + private sealed record StepResult(ClosingStepStatus Status, int Entries, decimal Amount, List Messages); + + private sealed record BalanceRow(long AccountId, long? PartyId, decimal? Amount); + + private sealed record PrintRow(long Id, string Kind, string FileName, int Pages); +} diff --git a/src/Khaemhat.Application/YearEnd/FinancialStatementsService.cs b/src/Khaemhat.Application/YearEnd/FinancialStatementsService.cs new file mode 100644 index 0000000..ec87811 --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/FinancialStatementsService.cs @@ -0,0 +1,554 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.YearEnd; + +/// A line of a statement with the amounts of the year and of the year before. +/// The code of the line. +/// The legal description. +/// The depth, from 0. +/// Whether it adds up other lines (shown in bold). +/// The amount of the year. +/// The amount of the year before. +public sealed record StatementRow(string Code, string Description, int Depth, bool Header, decimal Current, decimal Previous); + +/// An account whose balance has no line of the statements. +/// The account. +/// Its code. +/// Its description. +/// Its balance, debit minus credit. +public sealed record UnmappedAccount(long AccountId, string Code, string Description, decimal Balance); + +/// The financial statements of a year (mockup 051). +/// The year. +/// Ordinary, abbreviated or micro. +/// The assets. +/// The liabilities and equity. +/// The income statement. +/// The total assets of the year and of the year before. +/// The total liabilities of the year and of the year before. +/// The result of the year and of the year before. +/// The accounts with a balance and no line. +public sealed record FinancialStatements( + int Year, FinancialStatementForm Form, IReadOnlyList Assets, IReadOnlyList Liabilities, IReadOnlyList Income, + (decimal Current, decimal Previous) TotalAssets, (decimal Current, decimal Previous) TotalLiabilities, (decimal Current, decimal Previous) Result, + IReadOnlyList Unmapped) +{ + /// Whether assets and liabilities balance. + public bool Balanced => TotalAssets.Current == TotalLiabilities.Current; +} + +/// A line of a reclassified statement. +/// The code. +/// What it shows. +/// Whether it is a subtotal. +/// The amount of the year. +/// The amount of the year before. +public sealed record ReclassifiedRow(string Code, string Description, bool Subtotal, decimal Current, decimal Previous); + +/// A ratio of the year and of the year before. +/// The ratio of the year. +/// The ratio of the year before. +public sealed record RatioRow(FinancialRatio Current, FinancialRatio Previous); + +/// An account of a line, for the drill-down. +/// The account. +/// Its code. +/// Its description. +/// The amount of the year, with the sign of the line. +/// The amount of the year before. +public sealed record StatementAccount(long AccountId, string Code, string Description, decimal Current, decimal Previous); + +/// +/// The financial statements (SPEC §11.7, issue #86, mockup 051, ADR 0043): the legal balance sheet and income statement +/// in the ordinary, abbreviated or micro form with the year before, from the balances of the accounts mapped to the lines +/// of the fiscal pack; the statements reclassified by liquidity and by value added, the ratios, the drill-down to the +/// accounts, the print and the export for the accountant. The entries of steps 6 and 7 of the closing are left out, so +/// a closed year shows its balances. +/// +public sealed class FinancialStatementsService +{ + private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + public FinancialStatementsService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + _factory = factory; + _permissions = permissions; + _packs = packs; + } + + /// The financial statements of a year with the year before. + /// Who reads. + /// The company. + /// The year. + /// The form. + /// Cancellation. + /// The statements. + public async Task StatementsAsync(Actor actor, string companyCode, int year, FinancialStatementForm form, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false); + var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await StatementsAsync(uow, schema, year, form, cancellationToken).ConfigureAwait(false); + } + + /// A reclassified statement of a year with the year before. + /// Who reads. + /// The company. + /// The year. + /// By liquidity or by value added. + /// Cancellation. + /// The lines. + public async Task> ReclassifiedAsync(Actor actor, string companyCode, int year, ReclassificationKind kind, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false); + var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var current = await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false); + var previous = await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false); + var now = Reclassify(schema, current, kind); + var before = Reclassify(schema, previous, kind); + return [.. schema.Reclassification(kind).Select(l => new ReclassifiedRow(l.Code, l.Description, l.Subtotal, now[l.Code], before[l.Code]))]; + } + + /// The ratios of a year with the year before. + /// Who reads. + /// The company. + /// The year. + /// Cancellation. + /// The ratios. + public async Task> RatiosAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false); + var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var current = FinancialRatios.Compute(Inputs(schema, await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false))); + var previous = FinancialRatios.Compute(Inputs(schema, await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false))); + return [.. current.Zip(previous, (c, p) => new RatioRow(c, p))]; + } + + /// The accounts that make up a line, for the drill-down. + /// Who reads. + /// The company. + /// The year. + /// The statement. + /// The line. + /// Cancellation. + /// The accounts with a balance. + public async Task> AccountsAsync( + Actor actor, string companyCode, int year, FinancialStatementKind kind, string code, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false); + var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var ordinary = schema.Lines(kind, FinancialStatementForm.Ordinary); + var codes = Descendants(ordinary, code); + var line = ordinary.FirstOrDefault(l => l.Code == code); + var sign = line?.CreditNormal == true ? 1m : -1m; + var current = await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false); + var previous = await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false); + return + [ + .. current.Accounts.Values.Concat(previous.Accounts.Values).DistinctBy(a => a.AccountId) + .Where(a => a.Kind == kind && codes.Contains(a.Line)) + .Select(a => new StatementAccount( + a.AccountId, a.Code, a.Description, + sign * (current.Accounts.TryGetValue(a.AccountId, out var c) ? c.Balance : 0m), + sign * (previous.Accounts.TryGetValue(a.AccountId, out var p) ? p.Balance : 0m))) + .Where(a => a.Current != 0m || a.Previous != 0m) + .OrderBy(a => a.Code, StringComparer.Ordinal), + ]; + } + + /// Prints the statements of a year. + /// Who prints. + /// The company. + /// The year. + /// The form. + /// Cancellation. + /// The PDF. + public async Task PrintAsync(Actor actor, string companyCode, int year, FinancialStatementForm form, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, LedgerPermissions.EntryRead, cancellationToken).ConfigureAwait(false); + var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + (byte[] file, int _) = await PrintAsync(uow, schema, year, form, 1, cancellationToken).ConfigureAwait(false); + return new LedgerFile(string.Create(Invariant, $"bilancio-{year}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file); + } + + /// + /// The export for the accountant: a ZIP of CSV files (semicolon, decimal comma, UTF-8) with the chart of accounts, the + /// trial balance, the movements of the year and the statements. + /// + /// Who exports. + /// The company. + /// The year. + /// Cancellation. + /// The ZIP. + public async Task AccountantExportAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AccountantExport, cancellationToken).ConfigureAwait(false); + var schema = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var content = await AccountantExportAsync(uow, schema, year, cancellationToken).ConfigureAwait(false); + return new LedgerFile(string.Create(Invariant, $"commercialista-{company}-{year}.zip"), "application/zip", content); + } + + internal static async Task StatementsAsync(IUnitOfWork uow, IFinancialStatementsSchema schema, int year, FinancialStatementForm form, CancellationToken cancellationToken) + { + var current = await RawAsync(uow, schema, year, cancellationToken).ConfigureAwait(false); + var previous = await RawAsync(uow, schema, year - 1, cancellationToken).ConfigureAwait(false); + var assets = Rows(schema, FinancialStatementKind.Assets, form, current, previous); + var liabilities = Rows(schema, FinancialStatementKind.Liabilities, form, current, previous); + var income = Rows(schema, FinancialStatementKind.IncomeStatement, form, current, previous); + return new FinancialStatements( + year, form, assets, liabilities, income, + (-current.Total(FinancialStatementKind.Assets), -previous.Total(FinancialStatementKind.Assets)), + (current.Total(FinancialStatementKind.Liabilities) + current.Result, previous.Total(FinancialStatementKind.Liabilities) + previous.Result), + (current.Result, previous.Result), + [.. current.Unmapped.Where(u => u.Balance != 0m)]); + } + + internal static async Task<(byte[] File, int Pages)> PrintAsync( + IUnitOfWork uow, IFinancialStatementsSchema schema, int year, FinancialStatementForm form, int firstPage, CancellationToken cancellationToken) + { + var statements = await StatementsAsync(uow, schema, year, form, cancellationToken).ConfigureAwait(false); + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var rows = new List>(); + void Section(string title, IReadOnlyList lines, (decimal Current, decimal Previous)? total, string? totalTitle) + { + rows.Add(["**" + title, null, null, null]); + foreach (var line in lines) + { + var text = new string(' ', line.Depth * 3) + line.Code + " " + line.Description; + rows.Add([(line.Header ? "**" : string.Empty) + text, null, LedgerReport.Money(line.Current), LedgerReport.Money(line.Previous)]); + } + + if (total is { } t) + { + rows.Add(["**" + totalTitle, null, LedgerReport.Money(t.Current), LedgerReport.Money(t.Previous)]); + } + + rows.Add([null, null, null, null]); + } + + Section("STATO PATRIMONIALE - ATTIVO", statements.Assets, statements.TotalAssets, "Totale attivo"); + Section("STATO PATRIMONIALE - PASSIVO", statements.Liabilities, statements.TotalLiabilities, "Totale passivo"); + Section("CONTO ECONOMICO", statements.Income, null, null); + var formText = form switch + { + FinancialStatementForm.Ordinary => "ordinario (artt. 2424-2425 c.c.)", + FinancialStatementForm.Abbreviated => "abbreviato (art. 2435-bis c.c.)", + _ => "micro-imprese (art. 2435-ter c.c.)", + }; + return await LedgerReport.WriteAsync( + VatService.CompanyLine(profile), + "Bilancio d'esercizio " + year.ToString(Invariant), + "Schema " + formText, + [new ReportColumn("Voce", 520), new ReportColumn(string.Empty, 10), new ReportColumn(year.ToString(Invariant), 110, true), new ReportColumn((year - 1).ToString(Invariant), 110, true)], + rows, + year, + firstPage, + cancellationToken).ConfigureAwait(false); + } + + internal static async Task AccountantExportAsync(IUnitOfWork uow, IFinancialStatementsSchema schema, int year, CancellationToken cancellationToken) + { + var fiscalYear = await AccrualService.YearAsync(uow, year, cancellationToken).ConfigureAwait(false); + var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false); + var balance = await LedgerQueryService.TrialBalanceAsync(uow, fiscalYear.StartDate, fiscalYear.EndDate, null, false, cancellationToken).ConfigureAwait(false); + var statements = await StatementsAsync(uow, schema, year, FinancialStatementForm.Ordinary, cancellationToken).ConfigureAwait(false); + var from = fiscalYear.StartDate; + var to = fiscalYear.EndDate; + var draft = nameof(GlEntryStatus.Draft); + var movements = await uow.QueryAsync(SqlFragment.Of($""" + SELECT e.entry_number AS entry_number, e.entry_date AS entry_date, e.description AS entry_description, e.document_number AS document_number, + a.code AS account_code, p.code AS party_code, l.description AS description, l.debit AS debit, l.credit AS credit + FROM gl_entry_lines l + JOIN gl_entries e ON e.id = l.entry_id + JOIN gl_accounts a ON a.id = l.account_id + LEFT JOIN parties p ON p.id = l.party_id + WHERE l.entry_date >= {from} AND l.entry_date <= {to} AND l.status <> {draft} + ORDER BY e.entry_date, e.id, l.line_number + """), cancellationToken).ConfigureAwait(false); + using var stream = new MemoryStream(); + using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) + { + Csv(zip, "piano-dei-conti.csv", ["Codice", "Descrizione", "Livello", "Natura", "Voce CEE", "Movimentabile"], + accounts.Values.OrderBy(a => a.Code, StringComparer.Ordinal) + .Select(a => (IReadOnlyList)[a.Code, a.Description, a.Level.ToString(Invariant), a.Nature.ToString(), a.StatementLine, a.Postable ? "S" : "N"])); + Csv(zip, "bilancio-di-verifica.csv", ["Conto", "Descrizione", "Saldo iniziale", "Dare", "Avere", "Saldo finale"], + balance.Lines.Where(l => accounts[l.AccountId].Postable) + .Select(l => (IReadOnlyList)[l.Code, l.Description, Amount(l.Opening), Amount(l.Debit), Amount(l.Credit), Amount(l.Closing)])); + Csv(zip, "movimenti.csv", ["Registrazione", "Data", "Descrizione", "Documento", "Conto", "Soggetto", "Descrizione riga", "Dare", "Avere"], + movements.Select(m => (IReadOnlyList)[ + m.EntryNumber, m.EntryDate.ToString("yyyy-MM-dd", Invariant), m.EntryDescription, m.DocumentNumber, m.AccountCode, m.PartyCode, m.Description, + Amount(m.Debit), Amount(m.Credit)])); + Csv(zip, "stato-patrimoniale.csv", ["Sezione", "Voce", "Descrizione", year.ToString(Invariant), (year - 1).ToString(Invariant)], + statements.Assets.Select(r => Row("Attivo", r)).Concat(statements.Liabilities.Select(r => Row("Passivo", r)))); + Csv(zip, "conto-economico.csv", ["Voce", "Descrizione", year.ToString(Invariant), (year - 1).ToString(Invariant)], + statements.Income.Select(r => (IReadOnlyList)[r.Code, r.Description, Amount(r.Current), Amount(r.Previous)])); + } + + return stream.ToArray(); + } + + /// The balances of a year by account, with the line of the statements of each. + internal static async Task RawAsync(IUnitOfWork uow, IFinancialStatementsSchema schema, int year, CancellationToken cancellationToken) + { + var code = year.ToString(Invariant); + var fiscalYear = await uow.Repository().FindAsync(Query.For().Where(y => y.Code == code), cancellationToken).ConfigureAwait(false); + var from = fiscalYear?.StartDate ?? new DateOnly(year, 1, 1); + var to = fiscalYear?.EndDate ?? new DateOnly(year, 12, 31); + var draft = nameof(GlEntryStatus.Draft); + + // Balance-sheet accounts carry their balance from the years before; income accounts count the year only. The + // closing entries of the year (steps 6 and 7) are left out, so a closed year still shows its balances. + var rows = await uow.QueryAsync(SqlFragment.Of($""" + SELECT l.account_id AS account_id, + SUM(CASE WHEN l.entry_date >= {from} THEN l.debit - l.credit ELSE 0 END) AS period_sum, + SUM(l.debit - l.credit) AS total_sum + FROM gl_entry_lines l + JOIN gl_entries e ON e.id = l.entry_id + WHERE l.entry_date <= {to} AND l.status <> {draft} + AND (e.closing_step IS NULL OR e.closing_step < 6 OR e.closing_step > 7 OR l.entry_date < {from}) + GROUP BY l.account_id + """), cancellationToken).ConfigureAwait(false); + var accounts = await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false); + var result = new RawBalances(); + foreach (var row in rows) + { + if (!accounts.TryGetValue(row.AccountId, out var account) || account.Nature == AccountNature.Memorandum) + { + continue; + } + + var income = account.Nature is AccountNature.Cost or AccountNature.Revenue; + var balance = income ? row.PeriodSum ?? 0m : row.TotalSum ?? 0m; + if (balance == 0m) + { + continue; + } + + var kind = account.Nature switch + { + AccountNature.Asset => FinancialStatementKind.Assets, + AccountNature.Liability => FinancialStatementKind.Liabilities, + _ => FinancialStatementKind.IncomeStatement, + }; + if (income) + { + result.Result -= balance; + } + + var line = StatementLineOf(accounts, account); + if (line is null || !schema.Lines(kind, FinancialStatementForm.Ordinary).Any(l => l.Code == line)) + { + result.Unmapped.Add(new UnmappedAccount(account.Id, account.Code, account.Description, balance)); + continue; + } + + // Raw amounts are credit minus debit, the sign every line turns as it needs. + result.Accounts[account.Id] = new RawAccount(account.Id, account.Code, account.Description, kind, line, -balance); + } + + return result; + } + + internal static Dictionary Reclassify(IFinancialStatementsSchema schema, RawBalances raw, ReclassificationKind kind) + { + var values = new Dictionary(StringComparer.Ordinal); + foreach (var line in schema.Reclassification(kind)) + { + decimal value; + if (line.Totals is { Count: > 0 } totals) + { + value = totals.Sum(t => t.StartsWith('-') ? -values.GetValueOrDefault(t[1..]) : values.GetValueOrDefault(t)); + } + else + { + var ordinary = schema.Lines(line.Source, FinancialStatementForm.Ordinary); + var codes = line.Lines.SelectMany(l => Descendants(ordinary, l)).ToHashSet(StringComparer.Ordinal); + value = raw.Sum(line.Source, codes, schema.ResultLine); + value = line.Negate ? -value : value; + } + + values[line.Code] = value; + } + + return values; + } + + internal static RatioInputs Inputs(IFinancialStatementsSchema schema, RawBalances raw) + { + var financial = Reclassify(schema, raw, ReclassificationKind.Financial); + var added = Reclassify(schema, raw, ReclassificationKind.ValueAdded); + return new RatioInputs( + Equity: financial.GetValueOrDefault(ReclassifiedCodes.Equity), + Result: raw.Result, + OperatingResult: added.GetValueOrDefault(ReclassifiedCodes.OperatingResult), + Revenue: added.GetValueOrDefault(ReclassifiedCodes.Revenue), + TotalAssets: financial.GetValueOrDefault(ReclassifiedCodes.TotalAssets), + FixedAssets: financial.GetValueOrDefault(ReclassifiedCodes.FixedAssets), + CurrentAssets: financial.GetValueOrDefault(ReclassifiedCodes.CurrentAssets), + Inventory: financial.GetValueOrDefault(ReclassifiedCodes.Inventory), + Liquidity: financial.GetValueOrDefault(ReclassifiedCodes.Liquidity), + Receivables: financial.GetValueOrDefault(ReclassifiedCodes.Receivables), + CurrentLiabilities: financial.GetValueOrDefault(ReclassifiedCodes.CurrentLiabilities), + LongTermLiabilities: financial.GetValueOrDefault(ReclassifiedCodes.LongTermLiabilities), + Payables: financial.GetValueOrDefault(ReclassifiedCodes.Payables), + Purchases: -added.GetValueOrDefault(ReclassifiedCodes.Purchases), + Days: 365); + } + + private static string? StatementLineOf(Dictionary accounts, GlAccount account) + { + // A sub-account without a line takes the one of its parent. + var current = account; + while (current is not null) + { + if (!string.IsNullOrWhiteSpace(current.StatementLine)) + { + return current.StatementLine.Trim(); + } + + current = current.ParentId is { } p && accounts.TryGetValue(p, out var parent) ? parent : null; + } + + return null; + } + + private static List Rows(IFinancialStatementsSchema schema, FinancialStatementKind kind, FinancialStatementForm form, RawBalances current, RawBalances previous) + { + var ordinary = schema.Lines(kind, FinancialStatementForm.Ordinary); + var lines = schema.Lines(kind, form); + var rows = new List(); + foreach (var line in lines) + { + var depth = 0; + for (var parent = line.ParentCode; parent is not null; parent = lines.FirstOrDefault(l => l.Code == parent)?.ParentCode) + { + depth++; + } + + decimal Value(RawBalances raw) + { + if (line.Totals is { Count: > 0 } totals) + { + var codes = totals.SelectMany(t => Descendants(ordinary, t)).ToHashSet(StringComparer.Ordinal); + return raw.Sum(kind, codes, schema.ResultLine); + } + + var sum = raw.Sum(kind, Descendants(ordinary, line.Code), schema.ResultLine); + return line.CreditNormal ? sum : -sum; + } + + var header = !line.Postable || line.Totals is not null || lines.Any(l => l.ParentCode == line.Code); + rows.Add(new StatementRow(line.Code, line.Description, depth, header, Value(current), Value(previous))); + } + + return rows; + } + + private static HashSet Descendants(IReadOnlyList ordinary, string code) + { + var result = new HashSet(StringComparer.Ordinal) { code }; + var added = true; + while (added) + { + added = false; + foreach (var line in ordinary) + { + if (line.ParentCode is { } parent && result.Contains(parent) && result.Add(line.Code)) + { + added = true; + } + } + } + + return result; + } + + private static string Amount(decimal amount) => amount.ToString("0.00", Invariant).Replace('.', ','); + + private static IReadOnlyList Row(string section, StatementRow row) => [section, row.Code, row.Description, Amount(row.Current), Amount(row.Previous)]; + + private static void Csv(ZipArchive zip, string name, IReadOnlyList header, IEnumerable> rows) + { + var entry = zip.CreateEntry(name, CompressionLevel.Optimal); + using var writer = new StreamWriter(entry.Open(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)); + writer.Write(string.Join(';', header.Select(Quote))); + writer.Write("\r\n"); + foreach (var row in rows) + { + writer.Write(string.Join(';', row.Select(Quote))); + writer.Write("\r\n"); + } + } + + private static string Quote(string? value) + { + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + + return value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; + } + + private sealed record RawRow(long AccountId, decimal? PeriodSum, decimal? TotalSum); + + private sealed record ExportMovementRow( + string? EntryNumber, DateOnly EntryDate, string? EntryDescription, string? DocumentNumber, string AccountCode, string? PartyCode, string? Description, decimal Debit, + decimal Credit); +} + +/// A balance of an account for the statements: credit minus debit. +/// The account. +/// Its code. +/// Its description. +/// Its statement. +/// Its line (ordinary). +/// Credit minus debit. +internal sealed record RawAccount(long AccountId, string Code, string Description, FinancialStatementKind Kind, string Line, decimal Balance); + +/// The balances of a year by account. +internal sealed class RawBalances +{ + /// The accounts with a line. + public Dictionary Accounts { get; } = []; + + /// The accounts with a balance and no line. + public List Unmapped { get; } = []; + + /// The result of the year: revenues less costs. + public decimal Result { get; set; } + + /// The credit-minus-debit sum of a statement. + public decimal Total(FinancialStatementKind kind) => Accounts.Values.Where(a => a.Kind == kind).Sum(a => a.Balance); + + /// The credit-minus-debit sum of some lines; the result of the year goes into its line. + public decimal Sum(FinancialStatementKind kind, IReadOnlySet lines, string resultLine) => + Accounts.Values.Where(a => a.Kind == kind && lines.Contains(a.Line)).Sum(a => a.Balance) + + (kind == FinancialStatementKind.Liabilities && lines.Contains(resultLine) ? Result : 0m); +} diff --git a/src/Khaemhat.Application/YearEnd/FixedAssetService.cs b/src/Khaemhat.Application/YearEnd/FixedAssetService.cs new file mode 100644 index 0000000..e646f58 --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/FixedAssetService.cs @@ -0,0 +1,935 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.YearEnd; + +/// An asset as the register lists it. +/// The asset. +/// Its category. +/// The supplier. +public sealed record AssetRow(FixedAsset Asset, FixedAssetCategory Category, string? SupplierName); + +/// An asset with its history and its plans. +/// The asset. +/// Its category. +/// The supplier. +/// The movements, in date order. +/// The civil plan from the first year. +/// The fiscal plan from the first year. +public sealed record AssetView( + FixedAsset Asset, FixedAssetCategory Category, string? SupplierName, IReadOnlyList Movements, + IReadOnlyList CivilPlan, IReadOnlyList FiscalPlan); + +/// A new or changed asset. +/// The asset, for a change. +/// The code; empty for the next one. +/// The description. +/// The category. +/// The day it was bought. +/// The day it entered service (first year of depreciation). +/// The cost. +public sealed record AssetInput(long? Id, string? Code, string Description, long CategoryId, DateOnly PurchaseDate, DateOnly InServiceDate, decimal Cost) +{ + /// The supplier. + public long? SupplierId { get; init; } + + /// The purchase invoice. + public string? DocumentReference { get; init; } + + /// Where it is. + public string? Location { get; init; } + + /// The serial number. + public string? SerialNumber { get; init; } + + /// How many. + public decimal Quantity { get; init; } = 1m; + + /// The civil fund at the start of the use in Khaemhat (assets bought in earlier years). + public decimal OpeningCivilFund { get; init; } + + /// The fiscal fund at the start of the use in Khaemhat. + public decimal OpeningFiscalFund { get; init; } + + /// The last year already depreciated outside Khaemhat. + public int? LastDepreciationYear { get; init; } + + /// A civil rate of its own. + public decimal? CivilRate { get; init; } + + /// A fiscal rate of its own. + public decimal? FiscalRate { get; init; } + + /// The value not depreciated. + public decimal ResidualValue { get; init; } + + /// Notes. + public string? Notes { get; init; } +} + +/// A disposal or partial disposal. +/// The day. +/// The price. +/// The cost disposed of; the whole asset. +/// The account of the price; other receivables. +public sealed record DisposalInput(DateOnly Date, decimal Proceeds, decimal? CostDisposed = null, long? CounterpartAccountId = null); + +/// The depreciation of an asset in a year. +/// The asset. +/// Its code. +/// Its description. +/// The category. +/// The cost. +/// The civil fund at the start of the year. +/// The civil rate of the year. +/// The civil depreciation. +/// The fiscal rate of the year. +/// The fiscal depreciation. +/// Already posted. +public sealed record DepreciationLine( + long AssetId, string Code, string Description, string CategoryCode, decimal Cost, decimal CivilFund, decimal CivilRate, decimal Civil, decimal FiscalRate, + decimal Fiscal, bool Posted) +{ + /// The civil depreciation not deductible (to add back in the tax return). + public decimal Difference => Civil - Fiscal; +} + +/// +/// The fixed assets (SPEC §11.7, issue #82, mockup 048, ADR 0041): categories with the ministerial coefficients and +/// their accounts, the register with a civil and a fiscal plan, the yearly depreciation posted in one entry (charge to +/// fund), the disposals with the gain or loss, and the print of the register (libro cespiti). +/// +public sealed class FixedAssetService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly FiscalYearService _fiscal; + private readonly AuditTrail _audit; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + /// The fiscal calendar. + /// The history. + public FixedAssetService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, FiscalYearService fiscal, AuditTrail audit) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(audit); + _factory = factory; + _permissions = permissions; + _packs = packs; + _fiscal = fiscal; + _audit = audit; + } + + /// The categories, by code. + /// Who reads. + /// The company. + /// Cancellation. + /// The categories. + public async Task> CategoriesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false); + } + + /// The fiscal coefficients of the company's country, to start a category from. + /// The company. + /// Cancellation. + /// The coefficients. + public async Task> CoefficientsAsync(string companyCode, CancellationToken cancellationToken = default) => + (await _packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false)).Require().Coefficients; + + /// Creates the categories of the coefficients that are missing. + /// Who creates. + /// The company. + /// Cancellation. + /// How many were created. + public async Task CreateStandardCategoriesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false); + var coefficients = await CoefficientsAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var created = await CreateStandardCategoriesAsync(uow, coefficients, actor.UserName, false, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return created; + } + + /// Creates or changes a category. + /// Who writes. + /// The company. + /// The category; id 0 for a new one. + /// Cancellation. + /// The category as saved. + public async Task SaveCategoryAsync(Actor actor, string companyCode, FixedAssetCategory input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false); + var errors = new List(); + input.Code = (input.Code ?? string.Empty).Trim().ToUpperInvariant(); + input.Description = (input.Description ?? string.Empty).Trim(); + if (input.Code.Length == 0) + { + errors.Add("Code:" + YearEndErrors.CodeRequired); + } + + if (input.Description.Length == 0) + { + errors.Add("Description:" + YearEndErrors.DescriptionRequired); + } + + if (input.CivilRate is < 0m or > 100m) + { + errors.Add("CivilRate:" + YearEndErrors.RateRange); + } + + if (input.FiscalRate is < 0m or > 100m) + { + errors.Add("FiscalRate:" + YearEndErrors.RateRange); + } + + if (input.AssetAccountId is null || input.FundAccountId is null || input.DepreciationAccountId is null) + { + errors.Add("AssetAccountId:" + YearEndErrors.CategoryAccounts); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var code = input.Code; + var id = input.Id; + if (await repository.CountAsync(Query.For().Where(c => c.Code == code && c.Id != id), cancellationToken).ConfigureAwait(false) > 0) + { + errors.Add("Code:" + YearEndErrors.CodeTaken); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + if (input.Id == 0) + { + input.Id = await repository.InsertAsync(input, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, input.Id, null, input, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + var before = await repository.GetAsync(input.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + input.RowVersion = before.RowVersion; + input.IsDemo = before.IsDemo; + await repository.UpdateAsync(input, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, input.Id, before, input, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return input; + } + + /// The register, by code. + /// Who reads. + /// The company. + /// Text in the code, description, location or serial number. + /// Only this category. + /// Only this state. + /// Cancellation. + /// The assets. + public async Task> ListAsync( + Actor actor, string companyCode, string? text = null, long? categoryId = null, AssetStatus? status = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For(); + if (categoryId is { } c) + { + query = query.Where(a => a.CategoryId == c); + } + + if (status is { } s) + { + query = query.Where(a => a.Status == s); + } + + if (!string.IsNullOrWhiteSpace(text)) + { + var t = text.Trim(); + query = query.Where(a => a.Code.Contains(t) || a.Description.Contains(t) || a.Location!.Contains(t) || a.SerialNumber!.Contains(t)); + } + + var assets = (await uow.Repository().ListAsync(query.OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items; + var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(x => x.Id); + var names = await JournalEntryService.PartyNamesAsync(uow, assets.Select(a => a.SupplierId), cancellationToken).ConfigureAwait(false); + return [.. assets.Select(a => new AssetRow(a, categories[a.CategoryId], a.SupplierId is { } p && names.TryGetValue(p, out var n) ? n : null))]; + } + + /// An asset with its movements and plans. + /// Who reads. + /// The company. + /// The asset. + /// Cancellation. + /// The asset, or none. + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ViewAsync(uow, rules, id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Records a new asset or changes one. A new asset bought in an earlier year can bring the funds already + /// depreciated (opening movement); cost, category and dates change only while nothing was posted. + /// + /// Who writes. + /// The company. + /// The asset. + /// Cancellation. + /// The asset as saved. + public async Task SaveAsync(Actor actor, string companyCode, AssetInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + long id; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var asset = await SaveAsync(uow, rules, input, actor.UserName, false, cancellationToken).ConfigureAwait(false); + id = asset.Id; + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + } + + /// Removes an asset that has no posted movement. + /// Who removes. + /// The company. + /// The asset. + /// 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, YearEndPermissions.AssetWrite, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var asset = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (await uow.Repository().CountAsync( + Query.For().Where(m => m.AssetId == id && m.GlEntryId != null), cancellationToken).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.AssetPosted]); + } + + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM fixed_asset_movements WHERE asset_id = {id}"), cancellationToken).ConfigureAwait(false); + await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, asset, (FixedAsset?)null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// The depreciation of a year, asset by asset: what was posted and what would be. + /// Who reads. + /// The company. + /// The year. + /// Cancellation. + /// The lines, by code. + public async Task> DepreciationAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await DepreciationAsync(uow, rules, year, cancellationToken).ConfigureAwait(false); + } + + /// Posts the depreciation of a year (the closing does it as its step 2). + /// Who posts. + /// The company. + /// The year. + /// Cancellation. + /// The total civil depreciation posted. + public async Task PostDepreciationAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.DepreciationPost, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + var date = await YearEndDateAsync(company, year, cancellationToken).ConfigureAwait(false); + await _fiscal.DemandOpenAsync(company, date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var (amount, _) = await DepreciateAsync(uow, rules, year, date, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return amount; + } + + /// Removes the depreciation of a year while its entry is not final. + /// Who removes. + /// The company. + /// The year. + /// Cancellation. + /// A task. + public async Task UndoDepreciationAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.DepreciationPost, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await UndoDepreciationAsync(uow, year, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Disposes of an asset or of part of it (cessione, eliminazione): the cost and its share of the fund leave the + /// books, the price goes to the counterpart, the difference to gain or loss. No depreciation is computed for the year + /// of the disposal (ADR 0041). + /// + /// Who posts. + /// The company. + /// The asset. + /// The disposal. + /// Cancellation. + /// The asset after the disposal. + public async Task DisposeAsync(Actor actor, string companyCode, long id, DisposalInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.DepreciationPost, cancellationToken).ConfigureAwait(false); + await _fiscal.DemandOpenAsync(company, input.Date, PeriodUse.NoVat, cancellationToken).ConfigureAwait(false); + var codes = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require().Accounts; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await DisposeAsync(uow, codes, id, input, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + } + + /// The register of the assets of a year (libro cespiti) as PDF. + /// Who prints. + /// The company. + /// The year. + /// Cancellation. + /// The file. + public async Task PrintRegisterAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.AssetRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var (file, _) = await PrintRegisterAsync(uow, year, 1, cancellationToken).ConfigureAwait(false); + return file; + } + + internal static async Task<(LedgerFile File, int Pages)> PrintRegisterAsync(IUnitOfWork uow, int year, int firstPage, CancellationToken cancellationToken) + { + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Id); + var assets = (await uow.Repository().ListAsync(Query.For().OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items; + var movements = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var yearEnd = new DateOnly(year, 12, 31); + var rows = new List>(); + decimal totalCost = 0m, totalOpening = 0m, totalYear = 0m, totalClosing = 0m; + foreach (var group in assets.Where(a => a.PurchaseDate <= yearEnd).GroupBy(a => a.CategoryId).OrderBy(g => categories[g.Key].Code, StringComparer.Ordinal)) + { + var category = categories[group.Key]; + rows.Add(["**" + category.Code, category.Description, null, null, null, null, null, null, null]); + foreach (var asset in group) + { + var own = movements.Where(m => m.AssetId == asset.Id).ToList(); + var cost = own.Where(m => m.MovementDate <= yearEnd).Sum(m => m.CostAmount); + var opening = own.Where(m => m.Year < year || (m.Kind == AssetMovementKind.Opening && m.Year <= year)).Sum(m => m.CivilAmount); + var depreciation = own.Where(m => m.Year == year && m.Kind == AssetMovementKind.Depreciation).Sum(m => m.CivilAmount); + var disposed = own.Where(m => m.Year == year && m.Kind is AssetMovementKind.Disposal or AssetMovementKind.PartialDisposal).Sum(m => m.CivilAmount); + var closing = opening + depreciation + disposed; + var rate = depreciation == 0m ? null : (asset.CivilRate ?? category.CivilRate).ToString("0.##", CultureInfo.InvariantCulture) + "%"; + rows.Add([asset.Code, asset.Description, LedgerReport.Date(asset.InServiceDate), LedgerReport.Money(cost), LedgerReport.Money(opening), rate, + LedgerReport.Money(depreciation), LedgerReport.Money(closing), LedgerReport.Money(cost - closing)]); + totalCost += cost; + totalOpening += opening; + totalYear += depreciation; + totalClosing += closing; + } + } + + rows.Add(["**Totali", null, null, LedgerReport.Money(totalCost), LedgerReport.Money(totalOpening), null, LedgerReport.Money(totalYear), LedgerReport.Money(totalClosing), + LedgerReport.Money(totalCost - totalClosing)]); + var (file, pages) = await LedgerReport.WriteAsync( + VatService.CompanyLine(profile), + "Registro dei beni ammortizzabili", + "Esercizio " + year.ToString(CultureInfo.InvariantCulture) + " - ammortamenti civilistici", + [new("Codice", 60), new("Descrizione", 230), new("In uso dal", 60), new("Costo", 80, true), new("Fondo iniziale", 80, true), new("Aliquota", 50, true), + new("Ammortamento", 80, true), new("Fondo finale", 80, true), new("Residuo", 80, true)], + rows, + year, + firstPage, + cancellationToken).ConfigureAwait(false); + return (new LedgerFile(string.Create(CultureInfo.InvariantCulture, $"registro_cespiti_{year}.pdf"), Infrastructure.Files.PdfWriter.MediaType, file), pages); + } + + internal static async Task> CategoriesAsync(IUnitOfWork uow, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().OrderBy(c => c.Code), cancellationToken).ConfigureAwait(false)).Items; + + internal static async Task CreateStandardCategoriesAsync( + IUnitOfWork uow, IReadOnlyList coefficients, string? userName, bool isDemo, CancellationToken cancellationToken) + { + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var existing = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).Select(c => c.Code).ToHashSet(StringComparer.OrdinalIgnoreCase); + var created = 0; + foreach (var c in coefficients.Where(c => !existing.Contains(c.Code))) + { + var category = new FixedAssetCategory + { + Code = c.Code, + Description = c.Description, + Class = c.Intangible ? AssetClass.Intangible : AssetClass.Tangible, + MinisterialGroup = c.Group.Length <= 20 ? c.Group : c.Group[..20], + CivilRate = c.Rate, + FiscalRate = c.Rate, + CivilHalfFirstYear = !c.Intangible && c.Rate < 100m, + AssetAccountId = accounts.TryGetValue(c.AssetAccount, out var a) ? a.Id : null, + FundAccountId = accounts.TryGetValue(c.FundAccount, out var f) ? f.Id : null, + DepreciationAccountId = accounts.TryGetValue(c.DepreciationAccount, out var d) ? d.Id : null, + DeductiblePercent = c.DeductiblePercent, + CostLimit = c.CostLimit, + IsDemo = isDemo, + }; + category.Id = await uow.Repository().InsertAsync(category, cancellationToken).ConfigureAwait(false); + created++; + } + + _ = userName; + return created; + } + + internal static async Task SaveAsync(IUnitOfWork uow, IFixedAssetRules rules, AssetInput input, string? userName, bool isDemo, CancellationToken cancellationToken) + { + var errors = new List(); + var description = (input.Description ?? string.Empty).Trim(); + if (description.Length == 0) + { + errors.Add("Description:" + YearEndErrors.DescriptionRequired); + } + + if (input.Cost <= 0m) + { + errors.Add("Cost:" + YearEndErrors.CostRequired); + } + + if (input.InServiceDate < input.PurchaseDate) + { + errors.Add("InServiceDate:" + YearEndErrors.ServiceBeforePurchase); + } + + if (input.OpeningCivilFund > input.Cost || input.OpeningFiscalFund > input.Cost || input.OpeningCivilFund < 0m || input.OpeningFiscalFund < 0m) + { + errors.Add("OpeningCivilFund:" + YearEndErrors.FundTooHigh); + } + + if (input.CivilRate is < 0m or > 100m || input.FiscalRate is < 0m or > 100m) + { + errors.Add("CivilRate:" + YearEndErrors.RateRange); + } + + var category = await uow.Repository().GetAsync(input.CategoryId, cancellationToken).ConfigureAwait(false); + if (category is null) + { + errors.Add("CategoryId:" + YearEndErrors.CategoryRequired); + } + + var assets = uow.Repository(); + var code = (input.Code ?? string.Empty).Trim().ToUpperInvariant(); + if (code.Length == 0) + { + var count = await assets.CountAsync(Query.For(), cancellationToken).ConfigureAwait(false); + code = string.Create(CultureInfo.InvariantCulture, $"CE{count + 1:00000}"); + while (await assets.CountAsync(Query.For().Where(a => a.Code == code), cancellationToken).ConfigureAwait(false) > 0) + { + count++; + code = string.Create(CultureInfo.InvariantCulture, $"CE{count + 1:00000}"); + } + } + + var id = input.Id ?? 0L; + if (await assets.CountAsync(Query.For().Where(a => a.Code == code && a.Id != id), cancellationToken).ConfigureAwait(false) > 0) + { + errors.Add("Code:" + YearEndErrors.CodeTaken); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + FixedAsset? before = input.Id is { } existing + ? await assets.GetAsync(existing, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound) + : null; + var posted = before is not null && await uow.Repository().CountAsync( + Query.For().Where(m => m.AssetId == id && m.Kind != AssetMovementKind.Purchase && m.Kind != AssetMovementKind.Opening), cancellationToken).ConfigureAwait(false) > 0; + if (posted && (before!.Cost != input.Cost || before.CategoryId != input.CategoryId || before.InServiceDate != input.InServiceDate)) + { + throw new ValidationFailedException(["Cost:" + YearEndErrors.AssetPosted]); + } + + var asset = before ?? new FixedAsset { Status = AssetStatus.Active, IsDemo = isDemo }; + asset.Code = code; + asset.Description = LedgerStore.Trim(description, 200)!; + asset.CategoryId = input.CategoryId; + asset.PurchaseDate = input.PurchaseDate; + asset.InServiceDate = input.InServiceDate; + asset.SupplierId = input.SupplierId; + asset.DocumentReference = LedgerStore.Trim(input.DocumentReference?.Trim(), 60); + asset.Location = LedgerStore.Trim(input.Location?.Trim(), 100); + asset.SerialNumber = LedgerStore.Trim(input.SerialNumber?.Trim(), 60); + asset.Quantity = input.Quantity <= 0m ? 1m : input.Quantity; + asset.CivilRate = input.CivilRate; + asset.FiscalRate = input.FiscalRate; + asset.ResidualValue = Math.Max(0m, input.ResidualValue); + asset.LowValue = category!.CivilRate >= 100m; + asset.Notes = LedgerStore.Trim(input.Notes?.Trim(), 500); + if (!posted) + { + asset.Cost = input.Cost; + asset.CivilFund = input.OpeningCivilFund; + asset.FiscalFund = input.OpeningFiscalFund; + asset.LastDepreciationYear = input.LastDepreciationYear; + } + + var movements = uow.Repository(); + if (before is null) + { + asset.Id = await assets.InsertAsync(asset, cancellationToken).ConfigureAwait(false); + } + else + { + await assets.UpdateAsync(asset, cancellationToken).ConfigureAwait(false); + if (!posted) + { + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM fixed_asset_movements WHERE asset_id = {asset.Id} AND gl_entry_id IS NULL"), cancellationToken).ConfigureAwait(false); + } + } + + if (!posted) + { + await movements.InsertAsync(new FixedAssetMovement + { + AssetId = asset.Id, + Kind = AssetMovementKind.Purchase, + MovementDate = asset.PurchaseDate, + Year = asset.PurchaseDate.Year, + CostAmount = asset.Cost, + Description = asset.DocumentReference, + IsDemo = asset.IsDemo, + }, cancellationToken).ConfigureAwait(false); + if (asset.CivilFund != 0m || asset.FiscalFund != 0m) + { + var year = asset.LastDepreciationYear ?? asset.PurchaseDate.Year; + await movements.InsertAsync(new FixedAssetMovement + { + AssetId = asset.Id, + Kind = AssetMovementKind.Opening, + MovementDate = new DateOnly(year, 12, 31), + Year = year, + CivilAmount = asset.CivilFund, + FiscalAmount = asset.FiscalFund, + Description = "Fondo ammortamento iniziale", + IsDemo = asset.IsDemo, + }, cancellationToken).ConfigureAwait(false); + } + } + + _ = userName; + return asset; + } + + internal static async Task> DepreciationAsync(IUnitOfWork uow, IFixedAssetRules rules, int year, CancellationToken cancellationToken) + { + var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Id); + var assets = (await uow.Repository().ListAsync(Query.For().OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items; + var kind = AssetMovementKind.Depreciation; + var movements = (await uow.Repository().ListAsync( + Query.For().Where(m => m.Year == year && m.Kind == kind), cancellationToken).ConfigureAwait(false)).Items; + var lines = new List(); + foreach (var asset in assets) + { + var category = categories[asset.CategoryId]; + var done = movements.Where(m => m.AssetId == asset.Id).ToList(); + if (done.Count > 0) + { + var civil = done.Sum(m => m.CivilAmount); + var fiscal = done.Sum(m => m.FiscalAmount); + lines.Add(new DepreciationLine(asset.Id, asset.Code, asset.Description, category.Code, asset.Cost, asset.CivilFund - civil, + DepreciationCalculator.RateOf(Civil(asset, category), year), civil, DepreciationCalculator.RateOf(Fiscal(asset, category, rules), year), fiscal, true)); + continue; + } + + if (asset.Status == AssetStatus.Disposed || (asset.LastDepreciationYear is { } last && last >= year) || asset.InServiceDate.Year > year) + { + continue; + } + + var civilBasis = Civil(asset, category); + var fiscalBasis = Fiscal(asset, category, rules); + var civilAmount = DepreciationCalculator.Yearly(civilBasis, year, asset.CivilFund); + var fiscalAmount = DepreciationCalculator.Yearly(fiscalBasis, year, asset.FiscalFund); + if (civilAmount == 0m && fiscalAmount == 0m) + { + continue; + } + + lines.Add(new DepreciationLine(asset.Id, asset.Code, asset.Description, category.Code, asset.Cost, asset.CivilFund, + DepreciationCalculator.RateOf(civilBasis, year), civilAmount, DepreciationCalculator.RateOf(fiscalBasis, year), fiscalAmount, false)); + } + + return lines; + } + + /// Posts the depreciation not yet posted of a year in one entry; returns the amount and the entry. + internal static async Task<(decimal Amount, GlEntry? Entry)> DepreciateAsync( + IUnitOfWork uow, IFixedAssetRules rules, int year, DateOnly date, int? closingStep, string? userName, CancellationToken cancellationToken) + { + var lines = (await DepreciationAsync(uow, rules, year, cancellationToken).ConfigureAwait(false)).Where(l => !l.Posted).ToList(); + if (lines.Count == 0) + { + return (0m, null); + } + + var categories = (await CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Code, StringComparer.Ordinal); + foreach (var category in lines.Select(l => categories[l.CategoryCode]).Distinct()) + { + if (category.FundAccountId is null || category.DepreciationAccountId is null) + { + throw new ValidationFailedException(["CategoryId:" + YearEndErrors.CategoryAccounts + ":" + category.Code]); + } + } + + var drafts = new List(); + foreach (var group in lines.Where(l => l.Civil != 0m).GroupBy(l => l.CategoryCode).OrderBy(g => g.Key, StringComparer.Ordinal)) + { + var category = categories[group.Key]; + var amount = group.Sum(l => l.Civil); + var text = "Ammortamento " + category.Description; + drafts.Add(YearEndLedger.Debit(category.DepreciationAccountId!.Value, amount, text)); + drafts.Add(YearEndLedger.Credit(category.FundAccountId!.Value, amount, text)); + } + + var assets = uow.Repository(); + var isDemo = false; + foreach (var line in lines) + { + var asset = await assets.GetAsync(line.AssetId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + isDemo |= asset.IsDemo; + } + + var entry = await YearEndLedger.PostAsync( + uow, date, "Ammortamenti dell'esercizio " + year.ToString(CultureInfo.InvariantCulture), GlEntrySource.FixedAsset, closingStep, drafts, isDemo, cancellationToken) + .ConfigureAwait(false); + foreach (var line in lines) + { + var asset = await assets.GetAsync(line.AssetId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + asset.CivilFund += line.Civil; + asset.FiscalFund += line.Fiscal; + asset.LastDepreciationYear = year; + if (asset.CivilFund >= asset.Cost - asset.ResidualValue) + { + asset.Status = AssetStatus.Depreciated; + } + + await assets.UpdateAsync(asset, cancellationToken).ConfigureAwait(false); + await uow.Repository().InsertAsync(new FixedAssetMovement + { + AssetId = asset.Id, + Kind = AssetMovementKind.Depreciation, + MovementDate = date, + Year = year, + CivilAmount = line.Civil, + FiscalAmount = line.Fiscal, + Description = "Ammortamento " + year.ToString(CultureInfo.InvariantCulture), + GlEntryId = entry?.Id, + IsDemo = asset.IsDemo, + }, cancellationToken).ConfigureAwait(false); + } + + _ = userName; + return (lines.Sum(l => l.Civil), entry); + } + + /// Removes the depreciation of a year: movements, funds and entry. + internal static async Task UndoDepreciationAsync(IUnitOfWork uow, int year, CancellationToken cancellationToken) + { + var kind = AssetMovementKind.Depreciation; + var later = await uow.Repository().CountAsync( + Query.For().Where(m => m.Year > year && m.Kind == kind), cancellationToken).ConfigureAwait(false); + if (later > 0) + { + throw new ValidationFailedException(["Year:" + YearEndErrors.LaterDepreciation]); + } + + var movements = (await uow.Repository().ListAsync( + Query.For().Where(m => m.Year == year && m.Kind == kind), cancellationToken).ConfigureAwait(false)).Items; + var entries = movements.Where(m => m.GlEntryId is not null).Select(m => m.GlEntryId!.Value).Distinct().ToList(); + var assets = uow.Repository(); + foreach (var movement in movements) + { + var asset = await assets.GetAsync(movement.AssetId, cancellationToken).ConfigureAwait(false); + if (asset is not null) + { + asset.CivilFund -= movement.CivilAmount; + asset.FiscalFund -= movement.FiscalAmount; + asset.LastDepreciationYear = year - 1 < asset.InServiceDate.Year ? null : year - 1; + if (asset.Status == AssetStatus.Depreciated) + { + asset.Status = AssetStatus.Active; + } + + await assets.UpdateAsync(asset, cancellationToken).ConfigureAwait(false); + } + + await uow.Repository().DeleteAsync(movement.Id, cancellationToken).ConfigureAwait(false); + } + + // The movements pointed to the entries: these go last. + await YearEndLedger.DeleteAsync(uow, entries, cancellationToken).ConfigureAwait(false); + } + + internal static async Task DisposeAsync(IUnitOfWork uow, YearEndAccountCodes codes, long id, DisposalInput input, string? userName, CancellationToken cancellationToken) + { + var asset = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (asset.Status == AssetStatus.Disposed) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.Disposed]); + } + + var costDisposed = input.CostDisposed ?? asset.Cost; + if (costDisposed <= 0m || costDisposed > asset.Cost) + { + throw new ValidationFailedException(["CostDisposed:" + YearEndErrors.DisposalTooHigh]); + } + + if (input.Proceeds < 0m) + { + throw new ValidationFailedException(["Proceeds:" + YearEndErrors.AmountRequired]); + } + + var category = await uow.Repository().GetAsync(asset.CategoryId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (category.AssetAccountId is null || category.FundAccountId is null) + { + throw new ValidationFailedException(["CategoryId:" + YearEndErrors.CategoryAccounts + ":" + category.Code]); + } + + var whole = costDisposed == asset.Cost; + var civilFund = whole ? asset.CivilFund : DepreciationCalculator.FundShare(asset.Cost, asset.CivilFund, costDisposed); + var fiscalFund = whole ? asset.FiscalFund : DepreciationCalculator.FundShare(asset.Cost, asset.FiscalFund, costDisposed); + var gainLoss = DepreciationCalculator.GainLoss(costDisposed, civilFund, input.Proceeds); + var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false); + var counterpart = input.CounterpartAccountId ?? YearEndLedger.Require(accounts, codes.OtherReceivables).Id; + var text = (whole ? "Cessione cespite " : "Cessione parziale cespite ") + asset.Code + " " + asset.Description; + var lines = new List + { + YearEndLedger.Debit(category.FundAccountId.Value, civilFund, text), + YearEndLedger.Debit(counterpart, input.Proceeds, text), + YearEndLedger.Credit(category.AssetAccountId.Value, costDisposed, text), + }; + if (gainLoss > 0m) + { + lines.Add(YearEndLedger.Credit(YearEndLedger.Require(accounts, codes.Gains).Id, gainLoss, "Plusvalenza " + asset.Code)); + } + else if (gainLoss < 0m) + { + lines.Add(YearEndLedger.Debit(YearEndLedger.Require(accounts, codes.Losses).Id, -gainLoss, "Minusvalenza " + asset.Code)); + } + + var entry = await YearEndLedger.PostAsync(uow, input.Date, text, GlEntrySource.FixedAsset, null, lines, asset.IsDemo, cancellationToken).ConfigureAwait(false); + await uow.Repository().InsertAsync(new FixedAssetMovement + { + AssetId = asset.Id, + Kind = whole ? AssetMovementKind.Disposal : AssetMovementKind.PartialDisposal, + MovementDate = input.Date, + Year = input.Date.Year, + CostAmount = -costDisposed, + CivilAmount = -civilFund, + FiscalAmount = -fiscalFund, + Proceeds = input.Proceeds, + GainLoss = gainLoss, + Description = text.Length <= 200 ? text : text[..200], + GlEntryId = entry?.Id, + IsDemo = asset.IsDemo, + }, cancellationToken).ConfigureAwait(false); + asset.Cost -= costDisposed; + asset.CivilFund -= civilFund; + asset.FiscalFund -= fiscalFund; + if (whole) + { + asset.Status = AssetStatus.Disposed; + asset.DisposalDate = input.Date; + } + + await uow.Repository().UpdateAsync(asset, cancellationToken).ConfigureAwait(false); + _ = userName; + } + + private static async Task ViewAsync(IUnitOfWork uow, IFixedAssetRules rules, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } asset) + { + return null; + } + + var category = await uow.Repository().GetAsync(asset.CategoryId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + var movements = (await uow.Repository().ListAsync( + Query.For().Where(m => m.AssetId == id).OrderBy(m => m.MovementDate).OrderBy(m => m.Id), cancellationToken).ConfigureAwait(false)).Items; + var names = await JournalEntryService.PartyNamesAsync(uow, [asset.SupplierId], cancellationToken).ConfigureAwait(false); + var opening = movements.Where(m => m.Kind == AssetMovementKind.Opening).ToList(); + var startYear = asset.InServiceDate.Year; + var civilStart = 0m; + var fiscalStart = 0m; + if (opening.Count > 0) + { + startYear = opening.Max(m => m.Year) + 1; + civilStart = opening.Sum(m => m.CivilAmount); + fiscalStart = opening.Sum(m => m.FiscalAmount); + } + + var cost = movements.Where(m => m.Kind is AssetMovementKind.Purchase or AssetMovementKind.Increase or AssetMovementKind.Revaluation).Sum(m => m.CostAmount); + var civil = Civil(asset, category) with { Cost = cost }; + var fiscal = Fiscal(asset, category, rules) with { Cost = Math.Min(cost, category.CostLimit ?? decimal.MaxValue) }; + return new AssetView( + asset, category, asset.SupplierId is { } p && names.TryGetValue(p, out var n) ? n : null, movements, + DepreciationCalculator.Plan(civil, startYear, civilStart), DepreciationCalculator.Plan(fiscal, startYear, fiscalStart)); + } + + private static DepreciationBasis Civil(FixedAsset asset, FixedAssetCategory category) => + new(asset.Cost, asset.ResidualValue, asset.CivilRate ?? category.CivilRate, asset.InServiceDate.Year, category.CivilHalfFirstYear, asset.LowValue); + + private static DepreciationBasis Fiscal(FixedAsset asset, FixedAssetCategory category, IFixedAssetRules rules) => + new(Math.Min(asset.Cost, category.CostLimit ?? decimal.MaxValue), 0m, asset.FiscalRate ?? category.FiscalRate, asset.InServiceDate.Year, + category.Class == AssetClass.Tangible && rules.FirstYearFactor < 1m, asset.LowValue); + + private async Task YearEndDateAsync(string company, int year, CancellationToken cancellationToken) + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var first = new DateOnly(year, 1, 1); + var last = new DateOnly(year, 12, 31); + var fiscalYear = await uow.Repository().FindAsync( + Query.For().Where(y => y.EndDate >= first && y.EndDate <= last).OrderByDescending(y => y.EndDate), cancellationToken).ConfigureAwait(false); + return fiscalYear?.EndDate ?? new DateOnly(year, 12, 31); + } +} diff --git a/src/Khaemhat.Application/YearEnd/IntentDeclarationService.cs b/src/Khaemhat.Application/YearEnd/IntentDeclarationService.cs new file mode 100644 index 0000000..8c0f799 --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/IntentDeclarationService.cs @@ -0,0 +1,592 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.YearEnd; + +/// A declaration with the name of its party. +/// The declaration. +/// The customer or supplier. +/// Its code. +/// The ceiling used is above the warning share. +public sealed record IntentRow(IntentDeclaration Declaration, string PartyName, string PartyCode, bool Warning); + +/// A declaration being recorded. +/// The declaration, for a change. +/// Received or issued. +/// The customer or supplier. +/// The number of the declarant. +/// The day of the declaration. +/// The protocol of the receipt. +/// The ceiling. +/// The first day it covers. +/// The last day it covers. +public sealed record IntentInput( + long? Id, IntentDirection Direction, long PartyId, string Number, DateOnly DeclarationDate, string Protocol, decimal Ceiling, DateOnly ValidFrom, DateOnly ValidTo) +{ + /// The VAT code of the sales (nature N3.5). + public long? TaxCodeId { get; init; } + + /// Notes. + public string? Notes { get; init; } + + /// The ceiling used, for an issued declaration (the company's own plafond). + public decimal Used { get; init; } +} + +/// What a declaration covers for a sale being written. +/// The declaration, if any covers the day. +/// The ceiling used is above the warning share. +public sealed record IntentCoverage(IntentDeclaration? Declaration, bool Warning); + +/// +/// The declarations of intent (SPEC §11.7, issue #83, mockup 061, ADR 0042): the chronological register of the +/// declarations received from habitual exporters (and of those issued), the ceiling each declaration consumes with the +/// sales of nature N3.5, the warning from 90% and the refusal of a sale above the ceiling when the invoice is issued. The +/// party keeps a mirror of its current declaration for the documents and the e-invoice. +/// +public sealed class IntentDeclarationService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + /// The history. + public IntentDeclarationService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(audit); + _factory = factory; + _permissions = permissions; + _packs = packs; + _audit = audit; + } + + /// The register of a year, in chronological order. + /// Who reads. + /// The company. + /// Received or issued. + /// The year; every year when . + /// Cancellation. + /// The declarations. + public async Task> ListAsync( + Actor actor, string companyCode, IntentDirection direction, int? year = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentRead, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + if (await PendingAdoptionAsync(uow, cancellationToken).ConfigureAwait(false)) + { + // The declarations typed on the parties before the register existed join it the first time it is read. + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await AdoptAsync(uow, rules, null, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + var query = Query.For().Where(d => d.Direction == direction); + if (year is { } y) + { + query = query.Where(d => d.Year == y); + } + + var declarations = (await uow.Repository().ListAsync( + query.OrderByDescending(d => d.Year).OrderByDescending(d => d.RegisterNumber), cancellationToken).ConfigureAwait(false)).Items; + var ids = declarations.Select(d => d.PartyId).Distinct().ToList(); + var parties = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(p => ids.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(p => p.Id); + return [.. declarations.Select(d => new IntentRow( + d, parties.TryGetValue(d.PartyId, out var p) ? p.Name : string.Empty, parties.TryGetValue(d.PartyId, out var q) ? q.Code : string.Empty, + d.Status == IntentStatus.Active && d.UsedPercent >= rules.WarningPercent))]; + } + + /// A declaration. + /// Who reads. + /// The company. + /// The declaration. + /// Cancellation. + /// The declaration, or none. + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + } + + /// The declaration that covers a sale of a customer on a day. + /// Who reads. + /// The company. + /// The customer. + /// The day. + /// Cancellation. + /// The coverage. + public async Task CoverageAsync(Actor actor, string companyCode, long partyId, DateOnly date, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "sales.invoice.read", cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var declaration = Covering(await ReceivedAsync(uow, partyId, cancellationToken).ConfigureAwait(false), date); + return new IntentCoverage(declaration, declaration is not null && declaration.UsedPercent >= rules.WarningPercent); + } + + /// Records a declaration or changes one; the register number follows the year. + /// Who writes. + /// The company. + /// The declaration. + /// Cancellation. + /// The declaration as saved. + public async Task SaveAsync(Actor actor, string companyCode, IntentInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentWrite, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var declaration = await SaveAsync(uow, rules, input, actor.UserName, false, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return declaration; + } + + /// Revokes a declaration: it no longer covers sales. + /// Who revokes. + /// The company. + /// The declaration. + /// Cancellation. + /// A task. + public async Task RevokeAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntentWrite, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var declaration = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + var before = Copy(declaration); + declaration.Status = IntentStatus.Revoked; + await repository.UpdateAsync(declaration, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, declaration, actor.UserName, cancellationToken).ConfigureAwait(false); + if (declaration.Direction == IntentDirection.Received) + { + await SyncPartyAsync(uow, rules, declaration.PartyId, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Removes a declaration that no sale used. + /// Who removes. + /// The company. + /// The declaration. + /// 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, YearEndPermissions.IntentWrite, 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); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var declaration = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (declaration.Used != 0m && declaration.Direction == IntentDirection.Received) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.DeclarationUsed]); + } + + await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, declaration, (IntentDeclaration?)null, actor.UserName, cancellationToken).ConfigureAwait(false); + if (declaration.Direction == IntentDirection.Received) + { + await SyncPartyAsync(uow, rules, declaration.PartyId, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// The register of a year as PDF. + /// Who prints. + /// The company. + /// Received or issued. + /// The year. + /// Cancellation. + /// The file. + public async Task PrintRegisterAsync(Actor actor, string companyCode, IntentDirection direction, int year, CancellationToken cancellationToken = default) + { + var rows = (await ListAsync(actor, companyCode, direction, year, cancellationToken).ConfigureAwait(false)).OrderBy(r => r.Declaration.RegisterNumber).ToList(); + var company = CompanyCodes.Normalize(companyCode); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var lines = rows.Select(r => (IReadOnlyList)[ + r.Declaration.RegisterNumber.ToString(CultureInfo.InvariantCulture), LedgerReport.Date(r.Declaration.DeclarationDate), r.Declaration.Number, + r.Declaration.Protocol, r.PartyName, LedgerReport.Date(r.Declaration.ValidFrom) + " - " + LedgerReport.Date(r.Declaration.ValidTo), + LedgerReport.Money(r.Declaration.Ceiling), LedgerReport.Money(r.Declaration.Used), LedgerReport.Money(r.Declaration.Remaining), + ]).ToList(); + lines.Add(["**Totali", null, null, null, null, null, LedgerReport.Money(rows.Sum(r => r.Declaration.Ceiling)), LedgerReport.Money(rows.Sum(r => r.Declaration.Used)), + LedgerReport.Money(rows.Sum(r => r.Declaration.Remaining))]); + var (file, _) = await LedgerReport.WriteAsync( + VatService.CompanyLine(profile), + direction == IntentDirection.Received ? "Registro delle dichiarazioni d'intento ricevute" : "Registro delle dichiarazioni d'intento emesse", + "Anno " + year.ToString(CultureInfo.InvariantCulture), + [new("N.", 30), new("Data", 55), new("Numero", 70), new("Protocollo", 140), new("Controparte", 190), new("Validità", 115), new("Plafond", 75, true), + new("Utilizzato", 75, true), new("Residuo", 75, true)], + lines, + year, + 1, + cancellationToken).ConfigureAwait(false); + return new LedgerFile( + string.Create(CultureInfo.InvariantCulture, $"dichiarazioni_intento_{(direction == IntentDirection.Received ? "ricevute" : "emesse")}_{year}.pdf"), + Infrastructure.Files.PdfWriter.MediaType, + file); + } + + internal static async Task SaveAsync(IUnitOfWork uow, IIntentRules rules, IntentInput input, string? userName, bool isDemo, CancellationToken cancellationToken) + { + var errors = new List(); + var number = (input.Number ?? string.Empty).Trim(); + var protocol = (input.Protocol ?? string.Empty).Trim(); + if (input.PartyId <= 0) + { + errors.Add("PartyId:" + YearEndErrors.PartyRequired); + } + + if (number.Length == 0) + { + errors.Add("Number:" + YearEndErrors.NumberRequired); + } + + if (!rules.ValidProtocol(protocol)) + { + errors.Add("Protocol:" + YearEndErrors.ProtocolInvalid); + } + + if (input.Ceiling <= 0m) + { + errors.Add("Ceiling:" + YearEndErrors.CeilingRequired); + } + + if (input.ValidTo < input.ValidFrom) + { + errors.Add("ValidTo:" + YearEndErrors.ValidityOrder); + } + + if (input.TaxCodeId is { } taxCodeId) + { + var taxCode = await uow.Repository().GetAsync(taxCodeId, cancellationToken).ConfigureAwait(false); + if (taxCode?.Nature != rules.Nature) + { + errors.Add("TaxCodeId:" + YearEndErrors.TaxCodeNature); + } + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + var repository = uow.Repository(); + IntentDeclaration? before = input.Id is { } id + ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound) + : null; + var declaration = before is null ? new IntentDeclaration { Status = IntentStatus.Active, IsDemo = isDemo } : Copy(before); + if (before is not null && input.Ceiling < before.Used && before.Direction == IntentDirection.Received) + { + throw new ValidationFailedException(["Ceiling:" + YearEndErrors.CeilingBelowUsed]); + } + + var year = input.DeclarationDate.Year; + if (before is null || before.Year != year || before.Direction != input.Direction) + { + var direction = input.Direction; + var last = await repository.FindAsync( + Query.For().Where(d => d.Direction == direction && d.Year == year).OrderByDescending(d => d.RegisterNumber), cancellationToken).ConfigureAwait(false); + declaration.RegisterNumber = (last?.RegisterNumber ?? 0) + 1; + } + + declaration.Direction = input.Direction; + declaration.Year = year; + declaration.PartyId = input.PartyId; + declaration.Number = LedgerStore.Trim(number, 40)!; + declaration.DeclarationDate = input.DeclarationDate; + declaration.Protocol = protocol; + declaration.Ceiling = input.Ceiling; + declaration.ValidFrom = input.ValidFrom; + declaration.ValidTo = input.ValidTo; + declaration.TaxCodeId = input.TaxCodeId; + declaration.Notes = LedgerStore.Trim(input.Notes?.Trim(), 500); + if (input.Direction == IntentDirection.Issued) + { + declaration.Used = Math.Max(0m, input.Used); + declaration.Status = declaration.Status == IntentStatus.Revoked ? IntentStatus.Revoked + : declaration.Used >= declaration.Ceiling ? IntentStatus.Exhausted : IntentStatus.Active; + } + + if (before is null) + { + declaration.Id = await repository.InsertAsync(declaration, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(declaration, cancellationToken).ConfigureAwait(false); + } + + _ = userName; + if (declaration.Direction == IntentDirection.Received) + { + await SyncPartyAsync(uow, rules, declaration.PartyId, cancellationToken).ConfigureAwait(false); + if (before is not null && before.PartyId != declaration.PartyId) + { + await SyncPartyAsync(uow, rules, before.PartyId, cancellationToken).ConfigureAwait(false); + } + } + + return await repository.GetAsync(declaration.Id, cancellationToken).ConfigureAwait(false) ?? declaration; + } + + /// + /// The check of a sale being confirmed (ADR 0042): the lines of nature N3.5 need a declaration that covers the date of + /// the document, and the ceiling left must hold them. Credit notes give the ceiling back and are not checked. + /// + internal static async Task CheckAsync(IUnitOfWork uow, IIntentRules rules, DocumentBehavior behavior, DocumentRecord record, List errors, CancellationToken cancellationToken) + { + if (behavior.Direction != DocumentDirection.Sale || record.Family != DocumentFamily.SaleDocument || record.Header.PartyId is not { } partyId + || Sign(record.Header.Kind) <= 0) + { + return; + } + + var amount = await AmountAsync(uow, rules, record.Lines, cancellationToken).ConfigureAwait(false); + if (amount <= 0m) + { + return; + } + + await AdoptAsync(uow, rules, partyId, cancellationToken).ConfigureAwait(false); + await SyncPartyAsync(uow, rules, partyId, cancellationToken).ConfigureAwait(false); + var declaration = Covering(await ReceivedAsync(uow, partyId, cancellationToken).ConfigureAwait(false), record.Header.DocumentDate); + if (declaration is null) + { + errors.Add("PartyId:" + YearEndErrors.NoDeclaration); + } + else if (declaration.Used + amount > declaration.Ceiling) + { + errors.Add("PartyId:" + YearEndErrors.CeilingExceeded); + } + } + + /// Recomputes the ceiling used by the sales of a document's customer after it changed state. + internal static async Task SyncDocumentAsync(IUnitOfWork uow, IIntentRules rules, DocumentFamily family, long documentId, CancellationToken cancellationToken) + { + if (family != DocumentFamily.SaleDocument) + { + return; + } + + var partyId = await uow.QuerySingleAsync(SqlFragment.Of($"SELECT party_id FROM sale_documents WHERE id = {documentId}"), cancellationToken).ConfigureAwait(false); + if (partyId is { } p && await uow.Repository().CountAsync( + Query.For().Where(d => d.PartyId == p), cancellationToken).ConfigureAwait(false) > 0) + { + await SyncPartyAsync(uow, rules, p, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Recomputes the ceiling used by every declaration received from a customer: each sale of nature N3.5 goes to the + /// latest declaration that covers its date. Then the party mirrors its latest declaration. + /// + internal static async Task SyncPartyAsync(IUnitOfWork uow, IIntentRules rules, long partyId, CancellationToken cancellationToken) + { + var declarations = await ReceivedAsync(uow, partyId, cancellationToken).ConfigureAwait(false); + var draft = nameof(DocumentStatus.Draft); + var cancelled = nameof(DocumentStatus.Cancelled); + var nature = rules.Nature; + var sales = await uow.QueryAsync(SqlFragment.Of($""" + SELECT h.id AS document_id, h.document_date AS document_date, h.kind AS kind, SUM(l.taxable_amount) AS amount + FROM sale_documents h JOIN sale_document_lines l ON l.document_id = h.id JOIN tax_codes t ON t.id = l.tax_code_id + WHERE h.party_id = {partyId} AND t.nature = {nature} AND h.status <> {draft} AND h.status <> {cancelled} + GROUP BY h.id, h.document_date, h.kind + """), cancellationToken).ConfigureAwait(false); + var used = declarations.ToDictionary(d => d.Id, _ => 0m); + foreach (var sale in sales) + { + if (Covering(declarations, sale.DocumentDate) is { } declaration) + { + used[declaration.Id] += Sign(sale.Kind) * (sale.Amount ?? 0m); + } + } + + var repository = uow.Repository(); + foreach (var declaration in declarations) + { + var value = used[declaration.Id]; + var status = declaration.Status == IntentStatus.Revoked ? IntentStatus.Revoked + : value >= declaration.Ceiling ? IntentStatus.Exhausted : IntentStatus.Active; + if (declaration.Used != value || declaration.Status != status) + { + declaration.Used = value; + declaration.Status = status; + await repository.UpdateAsync(declaration, cancellationToken).ConfigureAwait(false); + } + } + + var fiscal = await uow.Repository().FindAsync(Query.For().Where(f => f.PartyId == partyId), cancellationToken).ConfigureAwait(false); + if (fiscal is null) + { + return; + } + + var current = declarations.Where(d => d.Status != IntentStatus.Revoked).OrderByDescending(d => d.ValidFrom).ThenByDescending(d => d.Id).FirstOrDefault(); + fiscal.IntentActive = current is not null; + fiscal.IntentNumber = current?.Number; + fiscal.IntentDate = current?.DeclarationDate; + fiscal.IntentProtocol = current?.Protocol; + fiscal.IntentTaxCodeId = current?.TaxCodeId ?? (current is null ? null : fiscal.IntentTaxCodeId); + fiscal.IntentCeiling = current?.Ceiling; + fiscal.IntentUsed = current?.Used ?? 0m; + fiscal.IntentFrom = current?.ValidFrom; + fiscal.IntentTo = current?.ValidTo; + await uow.Repository().UpdateAsync(fiscal, cancellationToken).ConfigureAwait(false); + } + + /// + /// Turns the declarations typed on the parties before the register existed (and those of the demo data) into + /// declarations of the register. + /// + /// The unit of work, in a transaction. + /// The rules of the fiscal pack. + /// Only this party, or every one. + /// Cancellation. + /// How many were adopted. + internal static async Task AdoptAsync(IUnitOfWork uow, IIntentRules rules, long? partyId, CancellationToken cancellationToken) + { + var query = Query.For().Where(f => f.IntentActive); + if (partyId is { } only) + { + query = query.Where(f => f.PartyId == only); + } + + var mirrors = (await uow.Repository().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items; + var adopted = 0; + foreach (var fiscal in mirrors) + { + var mirrorParty = fiscal.PartyId; + if (await uow.Repository().CountAsync(Query.For().Where(d => d.PartyId == mirrorParty), cancellationToken).ConfigureAwait(false) > 0) + { + continue; + } + + var party = await uow.Repository().GetAsync(mirrorParty, cancellationToken).ConfigureAwait(false); + var date = fiscal.IntentDate ?? fiscal.IntentFrom ?? new DateOnly(DateTime.UtcNow.Year, 1, 1); + var protocol = rules.ValidProtocol(fiscal.IntentProtocol) ? fiscal.IntentProtocol! : new string('0', 17) + "-000000"; + await SaveAsync(uow, rules, new IntentInput( + null, IntentDirection.Received, mirrorParty, fiscal.IntentNumber ?? "-", date, protocol, fiscal.IntentCeiling is > 0m ? fiscal.IntentCeiling.Value : 1m, + fiscal.IntentFrom ?? new DateOnly(date.Year, 1, 1), fiscal.IntentTo ?? new DateOnly(date.Year, 12, 31)) + { + TaxCodeId = await NatureCodeAsync(uow, rules, fiscal.IntentTaxCodeId, cancellationToken).ConfigureAwait(false), + }, null, party?.IsDemo ?? false, cancellationToken).ConfigureAwait(false); + adopted++; + } + + return adopted; + } + + private static async Task PendingAdoptionAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var mirrors = (await uow.Repository().ListAsync(Query.For().Where(f => f.IntentActive), cancellationToken).ConfigureAwait(false)).Items; + if (mirrors.Count == 0) + { + return false; + } + + var ids = mirrors.Select(f => f.PartyId).ToList(); + var adopted = (await uow.Repository().ListAsync(Query.For().Where(d => ids.Contains(d.PartyId)), cancellationToken) + .ConfigureAwait(false)).Items.Select(d => d.PartyId).ToHashSet(); + return ids.Any(id => !adopted.Contains(id)); + } + + private static async Task NatureCodeAsync(IUnitOfWork uow, IIntentRules rules, long? taxCodeId, CancellationToken cancellationToken) + { + if (taxCodeId is { } id && (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false))?.Nature == rules.Nature) + { + return id; + } + + var nature = rules.Nature; + return (await uow.Repository().FindAsync(Query.For().Where(t => t.Nature == nature && !t.Disabled).OrderBy(t => t.Code), cancellationToken) + .ConfigureAwait(false))?.Id; + } + + private static async Task AmountAsync(IUnitOfWork uow, IIntentRules rules, IReadOnlyList lines, CancellationToken cancellationToken) + { + var ids = lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).Distinct().ToList(); + if (ids.Count == 0) + { + return 0m; + } + + var nature = rules.Nature; + var codes = (await uow.Repository().ListAsync(Query.For().Where(t => ids.Contains(t.Id) && t.Nature == nature), cancellationToken) + .ConfigureAwait(false)).Items.Select(t => t.Id).ToHashSet(); + return lines.Where(l => l.TaxCodeId is { } t && codes.Contains(t)).Sum(l => l.TaxableAmount); + } + + private static async Task> ReceivedAsync(IUnitOfWork uow, long partyId, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync( + Query.For().Where(d => d.PartyId == partyId && d.Direction == IntentDirection.Received).OrderBy(d => d.ValidFrom).OrderBy(d => d.Id), + cancellationToken).ConfigureAwait(false)).Items; + + private static IntentDeclaration? Covering(IReadOnlyList declarations, DateOnly date) => + declarations.Where(d => d.Covers(date)).OrderByDescending(d => d.ValidFrom).ThenByDescending(d => d.Id).FirstOrDefault(); + + private static int Sign(DocumentKind kind) => kind switch + { + DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice or DocumentKind.DeferredInvoice or DocumentKind.DownPaymentInvoice or DocumentKind.Fee + or DocumentKind.DebitNote => 1, + DocumentKind.CreditNote => -1, + _ => 0, + }; + + private static IntentDeclaration Copy(IntentDeclaration d) => new() + { + Id = d.Id, + Direction = d.Direction, + RegisterNumber = d.RegisterNumber, + Year = d.Year, + PartyId = d.PartyId, + Number = d.Number, + DeclarationDate = d.DeclarationDate, + Protocol = d.Protocol, + Ceiling = d.Ceiling, + Used = d.Used, + ValidFrom = d.ValidFrom, + ValidTo = d.ValidTo, + TaxCodeId = d.TaxCodeId, + Status = d.Status, + Notes = d.Notes, + IsDemo = d.IsDemo, + RowVersion = d.RowVersion, + CreatedAt = d.CreatedAt, + CreatedBy = d.CreatedBy, + UpdatedAt = d.UpdatedAt, + UpdatedBy = d.UpdatedBy, + }; + + private sealed record UsageRow(long DocumentId, DateOnly DocumentDate, DocumentKind Kind, decimal? Amount); +} diff --git a/src/Khaemhat.Application/YearEnd/IntrastatService.cs b/src/Khaemhat.Application/YearEnd/IntrastatService.cs new file mode 100644 index 0000000..0271c85 --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/IntrastatService.cs @@ -0,0 +1,581 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.YearEnd; + +/// A list with its lines and the names of the parties. +/// The list. +/// The lines, by section. +/// The names of the parties, by id. +public sealed record IntrastatListView(IntrastatList List, IReadOnlyList Lines, IReadOnlyDictionary PartyNames); + +/// +/// The Intrastat lists (SPEC §11.7, issue #83, mockup 049, ADR 0042): the periodicity from the amounts of the four +/// quarters before, the lists generated from the confirmed invoices and credit notes with the parties of the other member +/// states (goods grouped by party, nomenclature and nature of the transaction; services one line per invoice), the lines +/// typed by hand that a new generation keeps, the checks of every line and the file for the customs. +/// +public sealed class IntrastatService +{ + private static readonly DocumentKind[] SaleKinds = + [DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.DebitNote, DocumentKind.CreditNote]; + + private static readonly DocumentKind[] PurchaseKinds = [DocumentKind.PurchaseInvoice, DocumentKind.PurchaseCreditNote]; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + /// The history. + /// The clock. + public IntrastatService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _audit = audit; + _clock = clock; + } + + /// The lists of a year. + /// Who reads. + /// The company. + /// The year. + /// Cancellation. + /// The lists, the latest first. + public async Task> ListsAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync( + Query.For().Where(l => l.Year == year).OrderByDescending(l => l.Period).OrderBy(l => l.Flow), cancellationToken).ConfigureAwait(false)).Items; + } + + /// A list with its lines. + /// Who reads. + /// The company. + /// The list. + /// Cancellation. + /// The list, or none. + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false); + } + + /// How often the lists of a flow are due in a period, from the four quarters before it. + /// Who reads. + /// The company. + /// Sales or purchases. + /// The year. + /// The quarter, 1-4. + /// Cancellation. + /// The periodicity of goods and services. + public async Task DueAsync(Actor actor, string companyCode, IntrastatFlow flow, int year, int quarter, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatRead, cancellationToken).ConfigureAwait(false); + var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await DueAsync(uow, exporter, flow, year, quarter, cancellationToken).ConfigureAwait(false); + } + + /// + /// Generates the list of a period from the documents, keeping the lines typed by hand; a sent list is read only. + /// + /// Who generates. + /// The company. + /// Sales or purchases. + /// The year. + /// Monthly or quarterly. + /// The month or the quarter. + /// Cancellation. + /// The list. + public async Task GenerateAsync( + Actor actor, string companyCode, IntrastatFlow flow, int year, IntrastatPeriodicity periodicity, int period, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, cancellationToken).ConfigureAwait(false); + var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + long id; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + id = (await GenerateAsync(uow, exporter, flow, year, periodicity, period, false, cancellationToken).ConfigureAwait(false)).Id; + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + } + + /// Adds or changes a line by hand: a new generation keeps it. + /// Who writes. + /// The company. + /// The line; id 0 for a new one. + /// Cancellation. + /// The list. + public async Task SaveLineAsync(Actor actor, string companyCode, IntrastatListLine line, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(line); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, cancellationToken).ConfigureAwait(false); + var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var list = await EditableAsync(uow, line.ListId, cancellationToken).ConfigureAwait(false); + line.CountryCode = (line.CountryCode ?? string.Empty).Trim().ToUpperInvariant(); + if (!exporter.MemberStates.Contains(line.CountryCode)) + { + throw new ValidationFailedException(["CountryCode:" + YearEndErrors.CountryNotMember]); + } + + if (line.Amount <= 0m) + { + throw new ValidationFailedException(["Amount:" + YearEndErrors.AmountRequired]); + } + + line.Manual = true; + line.IsDemo = list.IsDemo; + line.VatNumber = Clean(line.VatNumber, 20); + line.NomenclatureCode = Clean(line.NomenclatureCode, 10); + line.Check = CheckOf(exporter, line); + var repository = uow.Repository(); + if (line.Id == 0) + { + line.Id = await repository.InsertAsync(line, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, line.Id, null, line, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + var before = await repository.GetAsync(line.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + line.RowVersion = before.RowVersion; + await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, line.Id, before, line, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, line.ListId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + } + + /// Removes a line. + /// Who removes. + /// The company. + /// The line. + /// Cancellation. + /// A task. + public async Task DeleteLineAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatWrite, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var line = await repository.GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + var list = await EditableAsync(uow, line.ListId, cancellationToken).ConfigureAwait(false); + await repository.DeleteAsync(lineId, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, lineId, line, (IntrastatListLine?)null, actor.UserName, cancellationToken).ConfigureAwait(false); + await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Writes the file of a list for the customs; refused while lines are incomplete. + /// Who exports. + /// The company. + /// The list. + /// Cancellation. + /// The file. + public async Task ExportAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatExport, cancellationToken).ConfigureAwait(false); + var exporter = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var view = await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + if (view.List.Problems > 0) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.ListIncomplete]); + } + + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(profile?.VatNumber)) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.CompanyVatMissing]); + } + + var intrastatReturn = new IntrastatReturn(view.List, view.Lines, profile.VatNumber); + var content = exporter.Write(intrastatReturn); + var list = view.List; + if (list.Status == IntrastatStatus.Draft) + { + list.Status = IntrastatStatus.Generated; + } + + list.GeneratedAt = _clock.GetUtcNow().UtcDateTime; + list.FileName = exporter.FileName(intrastatReturn); + await uow.Repository().UpdateAsync(list, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return new LedgerFile(list.FileName, "text/plain", content); + } + + /// Records that a list was sent, with the protocol of the customs: from then on it is read only. + /// Who records. + /// The company. + /// The list. + /// The protocol. + /// Cancellation. + /// A task. + public async Task MarkSentAsync(Actor actor, string companyCode, long id, string? protocol, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, YearEndPermissions.IntrastatExport, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var list = await EditableAsync(uow, id, cancellationToken).ConfigureAwait(false); + list.Status = IntrastatStatus.Sent; + list.Protocol = Clean(protocol, 40); + await uow.Repository().UpdateAsync(list, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + internal static async Task DueAsync(IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, int year, int quarter, CancellationToken cancellationToken) + { + var goods = 0m; + var services = 0m; + for (var back = 1; back <= 4; back++) + { + var q = quarter - back; + var y = year; + while (q < 1) + { + q += 4; + y--; + } + + var from = new DateOnly(y, ((q - 1) * 3) + 1, 1); + var lines = await CandidatesAsync(uow, exporter, flow, from, from.AddMonths(3).AddDays(-1), cancellationToken).ConfigureAwait(false); + goods = Math.Max(goods, lines.Where(l => l.Section is IntrastatSection.Goods && l.Included).Sum(l => l.Amount)); + services = Math.Max(services, lines.Where(l => l.Section is IntrastatSection.Services && l.Included).Sum(l => l.Amount)); + } + + return exporter.Due(flow, goods, services); + } + + internal static async Task GenerateAsync( + IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, int year, IntrastatPeriodicity periodicity, int period, bool isDemo, CancellationToken cancellationToken) + { + if (periodicity == IntrastatPeriodicity.NotDue || period < 1 || period > (periodicity == IntrastatPeriodicity.Monthly ? 12 : 4)) + { + throw new ValidationFailedException(["Period:" + YearEndErrors.PeriodInvalid]); + } + + var lists = uow.Repository(); + var list = await lists.FindAsync( + Query.For().Where(l => l.Flow == flow && l.Year == year && l.Periodicity == periodicity && l.Period == period), cancellationToken).ConfigureAwait(false); + if (list is { Status: IntrastatStatus.Sent }) + { + throw new ValidationFailedException(["Id:" + YearEndErrors.ListSent]); + } + + if (list is null) + { + var last = await lists.FindAsync(Query.For().Where(l => l.Year == year).OrderByDescending(l => l.Progressive), cancellationToken).ConfigureAwait(false); + list = new IntrastatList + { + Flow = flow, + Year = year, + Period = period, + Periodicity = periodicity, + Status = IntrastatStatus.Draft, + Progressive = (last?.Progressive ?? 0) + 1, + IsDemo = isDemo, + }; + list.Id = await lists.InsertAsync(list, cancellationToken).ConfigureAwait(false); + } + else + { + var listId = list.Id; + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM intrastat_list_lines WHERE list_id = {listId} AND manual = {false}"), cancellationToken).ConfigureAwait(false); + list.Status = IntrastatStatus.Draft; + } + + var from = periodicity == IntrastatPeriodicity.Monthly ? new DateOnly(year, period, 1) : new DateOnly(year, ((period - 1) * 3) + 1, 1); + var to = from.AddMonths(periodicity == IntrastatPeriodicity.Monthly ? 1 : 3).AddDays(-1); + var quarter = ((from.Month - 1) / 3) + 1; + var due = await DueAsync(uow, exporter, flow, year, quarter, cancellationToken).ConfigureAwait(false); + var candidates = await CandidatesAsync(uow, exporter, flow, from, to, cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + foreach (var line in candidates) + { + // A category not due (purchases below the threshold) stays out of the list. + var category = line.Section is IntrastatSection.Goods or IntrastatSection.GoodsCorrection ? due.Goods : due.Services; + if (category == IntrastatPeriodicity.NotDue && flow == IntrastatFlow.Purchases) + { + continue; + } + + line.ListId = list.Id; + line.IsDemo = isDemo || line.IsDemo; + await repository.InsertAsync(line, cancellationToken).ConfigureAwait(false); + } + + await TotalsAsync(uow, list, cancellationToken).ConfigureAwait(false); + return list; + } + + /// The lines a period would have, from the documents (not written). + internal static async Task> CandidatesAsync( + IUnitOfWork uow, IIntrastatExporter exporter, IntrastatFlow flow, DateOnly from, DateOnly to, CancellationToken cancellationToken) + { + var documents = flow == IntrastatFlow.Sales + ? await DocumentsAsync(uow, SaleKinds, from, to, cancellationToken).ConfigureAwait(false) + : await DocumentsAsync(uow, PurchaseKinds, from, to, cancellationToken).ConfigureAwait(false); + if (documents.Count == 0) + { + return []; + } + + var partyIds = documents.Select(d => d.Header.PartyId).Where(p => p is not null).Select(p => p!.Value).Distinct().ToList(); + var parties = (await uow.Repository().ListAsync(Query.For().Where(p => partyIds.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(p => p.Id); + var foreign = documents.Where(d => d.Header.PartyId is { } p && parties.TryGetValue(p, out var party) && !string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase)) + .ToList(); + var itemIds = foreign.SelectMany(d => d.Lines).Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList(); + var items = itemIds.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id); + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var result = new List(); + var goods = new Dictionary<(long Party, string? Code), IntrastatListLine>(); + foreach (var (header, lines) in foreign.OrderBy(d => d.Header.DocumentDate).ThenBy(d => d.Header.Id)) + { + var party = parties[header.PartyId!.Value]; + var country = string.Equals(party.CountryCode, "EL", StringComparison.OrdinalIgnoreCase) ? "GR" : party.CountryCode.ToUpperInvariant(); + var sign = header.Kind is DocumentKind.CreditNote or DocumentKind.PurchaseCreditNote ? -1m : 1m; + var rate = header.ExchangeRate <= 0m ? 1m : header.ExchangeRate; + var family = flow == IntrastatFlow.Sales ? DocumentFamily.SaleDocument : DocumentFamily.PurchaseDocument; + var vat = VatOf(party.VatNumber, country); + decimal services = 0m, servicesCurrency = 0m; + string? serviceCode = null; + string? serviceText = null; + foreach (var line in lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free && l.TaxableAmount != 0m)) + { + var item = line.ItemId is { } i && items.TryGetValue(i, out var it) ? it : null; + var euro = Math.Round(line.TaxableAmount / rate, 2, MidpointRounding.AwayFromZero) * sign; + if (item?.Kind == ItemKind.Service) + { + services += euro; + servicesCurrency += line.TaxableAmount * sign; + serviceCode ??= item.CustomsCode; + serviceText ??= line.Description; + continue; + } + + var code = item?.CustomsCode?.Trim(); + if (!goods.TryGetValue((party.Id, code), out var target)) + { + target = new IntrastatListLine + { + Section = IntrastatSection.Goods, + SourceFamily = family, + SourceDocumentId = header.Id, + DocumentNumber = header.DocumentNumber, + DocumentDate = header.DocumentDate, + PartyId = party.Id, + CountryCode = country, + VatNumber = vat, + NomenclatureCode = code, + Description = Clean(item?.Description ?? line.Description, 200), + TransactionNature = "11", + DeliveryTerms = "DAP", + TransportMode = "3", + OriginCountry = flow == IntrastatFlow.Purchases ? country : null, + Province = Clean(profile?.ProvinceCode, 2), + IsDemo = header.IsDemo, + }; + goods[(party.Id, code)] = target; + result.Add(target); + } + + target.Amount += euro; + target.CurrencyAmount = flow == IntrastatFlow.Purchases && rate != 1m ? (target.CurrencyAmount ?? 0m) + (line.TaxableAmount * sign) : target.CurrencyAmount; + if (item?.NetWeight is { } weight && weight > 0m) + { + target.NetMass = (target.NetMass ?? 0m) + Math.Round(weight * line.Quantity * sign, 3, MidpointRounding.AwayFromZero); + } + } + + if (services != 0m) + { + result.Add(new IntrastatListLine + { + Section = sign < 0m ? IntrastatSection.ServicesCorrection : IntrastatSection.Services, + SourceFamily = family, + SourceDocumentId = header.Id, + DocumentNumber = header.DocumentNumber, + DocumentDate = header.DocumentDate, + PartyId = party.Id, + CountryCode = country, + VatNumber = vat, + Amount = Math.Abs(services), + CurrencyAmount = flow == IntrastatFlow.Purchases && rate != 1m ? Math.Abs(servicesCurrency) : null, + NomenclatureCode = Clean(serviceCode, 10), + Description = Clean(serviceText, 200), + SupplyMode = "I", + PaymentMode = "B", + PaymentCountry = country, + CorrectedYear = sign < 0m ? header.DocumentDate.Year : null, + CorrectedPeriod = sign < 0m ? header.DocumentDate.Month : null, + CorrectionSign = sign < 0m ? "-" : null, + IsDemo = header.IsDemo, + }); + } + } + + foreach (var line in result.Where(l => l.Section == IntrastatSection.Goods && l.Amount < 0m)) + { + // Credit notes beyond the sales of the period are corrections of an earlier one. + line.Section = IntrastatSection.GoodsCorrection; + line.Amount = -line.Amount; + line.NetMass = line.NetMass is { } m ? Math.Abs(m) : null; + line.CorrectionSign = "-"; + line.CorrectedYear = line.DocumentDate?.Year; + line.CorrectedPeriod = line.DocumentDate?.Month; + } + + result.RemoveAll(l => l.Amount == 0m); + foreach (var line in result) + { + line.Amount = Math.Round(line.Amount, 2, MidpointRounding.AwayFromZero); + line.StatisticalValue = line.Section == IntrastatSection.Goods ? line.Amount : null; + line.Check = exporter.MemberStates.Contains(line.CountryCode) && line.CountryCode != "IT" ? CheckOf(exporter, line) : IntrastatCheck.OutsideEu; + } + + return result; + } + + private static async Task Lines)>> DocumentsAsync( + IUnitOfWork uow, DocumentKind[] kinds, DateOnly from, DateOnly to, CancellationToken cancellationToken) + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() + { + var draft = DocumentStatus.Draft; + var cancelled = DocumentStatus.Cancelled; + List wanted = [.. kinds]; + var headers = (await uow.Repository().ListAsync( + Query.For().Where(h => h.DocumentDate >= from && h.DocumentDate <= to && h.Status != draft && h.Status != cancelled && wanted.Contains(h.Kind)), + cancellationToken).ConfigureAwait(false)).Items; + if (headers.Count == 0) + { + return []; + } + + var ids = headers.Select(h => h.Id).ToList(); + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => ids.Contains(l.DocumentId)).OrderBy(l => l.LineNumber), cancellationToken) + .ConfigureAwait(false)).Items; + return [.. headers.Select(h => ((DocumentHeader)h, lines.Where(l => l.DocumentId == h.Id).Cast().ToList()))]; + } + + private static IntrastatCheck CheckOf(IIntrastatExporter exporter, IntrastatListLine line) + { + if (string.IsNullOrWhiteSpace(line.VatNumber)) + { + return IntrastatCheck.MissingVatNumber; + } + + if (line.Section is IntrastatSection.Goods or IntrastatSection.GoodsCorrection) + { + if (!exporter.ValidNomenclature(line.NomenclatureCode)) + { + return IntrastatCheck.MissingNomenclature; + } + + if (line.Section == IntrastatSection.Goods && line.NetMass is null or <= 0m && line.SupplementaryUnits is null or <= 0m) + { + return IntrastatCheck.MissingMass; + } + } + else if (line.NomenclatureCode is not { Length: >= 5 }) + { + return IntrastatCheck.MissingServiceCode; + } + + return IntrastatCheck.Ok; + } + + private static async Task TotalsAsync(IUnitOfWork uow, IntrastatList list, CancellationToken cancellationToken) + { + var listId = list.Id; + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => l.ListId == listId), cancellationToken) + .ConfigureAwait(false)).Items; + list.GoodsAmount = lines.Where(l => l.Included && l.Section is IntrastatSection.Goods).Sum(l => l.Amount) + - lines.Where(l => l.Included && l.Section is IntrastatSection.GoodsCorrection && l.CorrectionSign == "-").Sum(l => l.Amount); + list.ServicesAmount = lines.Where(l => l.Included && l.Section is IntrastatSection.Services).Sum(l => l.Amount) + - lines.Where(l => l.Included && l.Section is IntrastatSection.ServicesCorrection && l.CorrectionSign == "-").Sum(l => l.Amount); + list.Problems = lines.Count(l => l.Included && l.Check != IntrastatCheck.Ok); + await uow.Repository().UpdateAsync(list, cancellationToken).ConfigureAwait(false); + } + + private static async Task EditableAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + var list = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(YearEndErrors.NotFound); + return list.Status == IntrastatStatus.Sent ? throw new ValidationFailedException(["Id:" + YearEndErrors.ListSent]) : list; + } + + private static async Task ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } list) + { + return null; + } + + var lines = (await uow.Repository().ListAsync( + Query.For().Where(l => l.ListId == id).OrderBy(l => l.Section).OrderBy(l => l.DocumentDate).OrderBy(l => l.Id), cancellationToken) + .ConfigureAwait(false)).Items; + var names = await JournalEntryService.PartyNamesAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false); + return new IntrastatListView(list, lines, names); + } + + private static string? VatOf(string? vatNumber, string country) + { + var vat = vatNumber?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + if (string.IsNullOrEmpty(vat)) + { + return null; + } + + var prefix = country == "GR" ? "EL" : country; + return vat.StartsWith(prefix, StringComparison.Ordinal) ? vat[prefix.Length..] : vat; + } + + private static string? Clean(string? text, int length) + { + var value = text?.Trim(); + return string.IsNullOrEmpty(value) ? null : value.Length <= length ? value : value[..length]; + } +} diff --git a/src/Khaemhat.Application/YearEnd/YearEndLedger.cs b/src/Khaemhat.Application/YearEnd/YearEndLedger.cs new file mode 100644 index 0000000..a838e57 --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/YearEndLedger.cs @@ -0,0 +1,90 @@ +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Core.Accounting; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.YearEnd; + +/// +/// The entries the year end writes (ADR 0041, ADR 0043): depreciation, disposals, accruals, exchange differences and the +/// steps of the closing go into the journal as posted entries with their source, so the statements and the closing find +/// them and an undo removes them while they are not final. +/// +internal static class YearEndLedger +{ + /// Writes a posted entry, leaving out the empty lines; nothing when every line is empty. + public static async Task PostAsync( + IUnitOfWork uow, DateOnly date, string description, GlEntrySource source, int? closingStep, IReadOnlyList lines, bool isDemo, + CancellationToken cancellationToken, long? partyId = null, string? documentNumber = null) + { + var useful = lines.Where(l => l.Debit != 0m || l.Credit != 0m).Select(Positive).ToList(); + if (useful.Count == 0) + { + return null; + } + + var debit = useful.Sum(l => l.Debit); + var credit = useful.Sum(l => l.Credit); + if (debit != credit) + { + throw new InvalidOperationException("Unbalanced year-end entry: " + description); + } + + var entry = new GlEntry + { + EntryDate = date, + Description = LedgerStore.Trim(description, 200)!, + Status = GlEntryStatus.Posted, + Source = source, + ClosingStep = closingStep, + PartyId = partyId, + DocumentNumber = LedgerStore.Trim(documentNumber, 30), + IsDemo = isDemo, + }; + return await LedgerStore.InsertAsync(uow, entry, useful, [], cancellationToken).ConfigureAwait(false); + } + + /// Removes entries that are not final. + public static async Task DeleteAsync(IUnitOfWork uow, IEnumerable entryIds, CancellationToken cancellationToken) + { + var ids = entryIds.Distinct().ToList(); + if (ids.Count == 0) + { + return; + } + + var final = GlEntryStatus.Final; + if (await uow.Repository().CountAsync(Query.For().Where(e => ids.Contains(e.Id) && e.Status == final), cancellationToken).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["Status:" + YearEndErrors.EntriesFinal]); + } + + foreach (var id in ids) + { + await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false); + } + } + + /// The accounts by code. + public static async Task> AccountsByCodeAsync(IUnitOfWork uow, CancellationToken cancellationToken) => + (await LedgerStore.AccountsAsync(uow, cancellationToken).ConfigureAwait(false)).Values.ToDictionary(a => a.Code, StringComparer.Ordinal); + + /// The account of a code, or an error naming it. + public static GlAccount Require(IReadOnlyDictionary accounts, string code) => + accounts.TryGetValue(code, out var account) ? account : throw new ValidationFailedException([YearEndErrors.ClosingAccount + ":" + code]); + + /// A debit line (a negative amount goes to the credit). + public static EntryLineDraft Debit(long accountId, decimal amount, string? description = null, long? partyId = null) => + new(accountId, partyId, description, amount, 0m); + + /// A credit line (a negative amount goes to the debit). + public static EntryLineDraft Credit(long accountId, decimal amount, string? description = null, long? partyId = null) => + new(accountId, partyId, description, 0m, amount); + + private static EntryLineDraft Positive(EntryLineDraft line) + { + var net = line.Debit - line.Credit; + return line with { Debit = net > 0m ? net : 0m, Credit = net < 0m ? -net : 0m }; + } +} diff --git a/src/Khaemhat.Application/YearEnd/YearEndPermissions.cs b/src/Khaemhat.Application/YearEnd/YearEndPermissions.cs new file mode 100644 index 0000000..ca52fdb --- /dev/null +++ b/src/Khaemhat.Application/YearEnd/YearEndPermissions.cs @@ -0,0 +1,177 @@ +namespace Khaemhat.Application.YearEnd; + +/// The permissions of the year end (modules ASSET, INTRA, ACCT, REPORT and CORE). +public static class YearEndPermissions +{ + /// See the fixed assets (ASSET). + public const string AssetRead = "assets.asset.read"; + + /// Change the fixed assets and their categories (ASSET). + public const string AssetWrite = "assets.asset.write"; + + /// Post the depreciation and the disposals (ASSET). + public const string DepreciationPost = "assets.depreciation.post"; + + /// See the Intrastat lists (INTRA). + public const string IntrastatRead = "intrastat.list.read"; + + /// Generate and complete the Intrastat lists (INTRA). + public const string IntrastatWrite = "intrastat.list.write"; + + /// Write the file for the customs (INTRA). + public const string IntrastatExport = "intrastat.list.export"; + + /// Run the closing of the year (ACCT). + public const string YearClose = "ledger.year.close"; + + /// Export the data for the accountant (REPORT). + public const string AccountantExport = "reports.accountant.export"; + + /// See the declarations of intent (CORE). + public const string IntentRead = "sales.intent.read"; + + /// Record the declarations of intent (CORE). + public const string IntentWrite = "sales.intent.write"; +} + +/// The error codes of the year end; the interface translates them (YearEnd.json). +public static class YearEndErrors +{ + /// The record does not exist. + public const string NotFound = "yearend.not-found"; + + /// A code is required. + public const string CodeRequired = "yearend.code-required"; + + /// The code is used already. + public const string CodeTaken = "yearend.code-taken"; + + /// A description is required. + public const string DescriptionRequired = "yearend.description-required"; + + /// The category is required. + public const string CategoryRequired = "assets.category-required"; + + /// The category lacks one of its accounts. + public const string CategoryAccounts = "assets.category-accounts"; + + /// A rate outside 0-100. + public const string RateRange = "assets.rate-range"; + + /// The cost must be positive. + public const string CostRequired = "assets.cost-required"; + + /// The fund exceeds the cost. + public const string FundTooHigh = "assets.fund-too-high"; + + /// The asset entered service before it was bought. + public const string ServiceBeforePurchase = "assets.service-before-purchase"; + + /// The asset has postings: it cannot be removed. + public const string AssetPosted = "assets.posted"; + + /// The asset was disposed of. + public const string Disposed = "assets.disposed"; + + /// The cost disposed of exceeds the cost. + public const string DisposalTooHigh = "assets.disposal-too-high"; + + /// The depreciation of a later year is posted: undo that first. + public const string LaterDepreciation = "assets.later-depreciation"; + + /// The entries are final: nothing can be undone. + public const string EntriesFinal = "yearend.entries-final"; + + /// The account is required. + public const string AccountRequired = "accruals.account-required"; + + /// The period of an accrual ends before it starts. + public const string PeriodOrder = "accruals.period-order"; + + /// The period of an accrual does not straddle the year end. + public const string PeriodOutside = "accruals.period-outside"; + + /// The amount must be positive. + public const string AmountRequired = "yearend.amount-required"; + + /// The accrual was posted: undo the step of the closing first. + public const string AccrualPosted = "accruals.posted"; + + /// The party is required. + public const string PartyRequired = "intent.party-required"; + + /// The number of the declaration is required. + public const string NumberRequired = "intent.number-required"; + + /// The protocol is not of 17 digits, a dash and 6 digits. + public const string ProtocolInvalid = "intent.protocol-invalid"; + + /// The validity ends before it starts. + public const string ValidityOrder = "intent.validity-order"; + + /// The ceiling must be positive. + public const string CeilingRequired = "intent.ceiling-required"; + + /// The ceiling is lower than what was used. + public const string CeilingBelowUsed = "intent.ceiling-below-used"; + + /// The VAT code must have the nature N3.5. + public const string TaxCodeNature = "intent.tax-code-nature"; + + /// A sale with nature N3.5 without a declaration covering its date. + public const string NoDeclaration = "intent.no-declaration"; + + /// The sale exceeds the ceiling left. + public const string CeilingExceeded = "intent.ceiling-exceeded"; + + /// The declaration was used: revoke it instead. + public const string DeclarationUsed = "intent.used"; + + /// The list was sent: read only. + public const string ListSent = "intrastat.sent"; + + /// The period is not valid for the periodicity. + public const string PeriodInvalid = "intrastat.period-invalid"; + + /// The country is not a member state. + public const string CountryNotMember = "intrastat.country-not-member"; + + /// The company has no VAT number. + public const string CompanyVatMissing = "intrastat.company-vat-missing"; + + /// The list has lines to complete. + public const string ListIncomplete = "intrastat.incomplete"; + + /// The year has no closing yet. + public const string NoClosing = "closing.not-started"; + + /// The closing is locked. + public const string ClosingLocked = "closing.locked"; + + /// A step before this one is not done. + public const string StepOrder = "closing.step-order"; + + /// A later step is done: undo it first. + public const string LaterStepDone = "closing.later-step-done"; + + /// The checks failed. + public const string ChecksFailed = "closing.checks-failed"; + + /// The step cannot be undone (the entries are final). + public const string StepIrreversible = "closing.step-irreversible"; + + /// A previous year is not closed. + public const string PreviousOpen = "closing.previous-open"; + + /// The year has not ended. + public const string YearNotEnded = "closing.year-not-ended"; + + /// The steps are not all done. + public const string StepsPending = "closing.steps-pending"; + + /// An account of the closing is missing from the chart. + public const string ClosingAccount = "closing.account-missing"; + + /// The balance-sheet accounts do not balance: the income accounts of earlier years are still open. + public const string ClosingUnbalanced = "closing.unbalanced"; +} diff --git a/src/Khaemhat.Core/Accounting/FixedAssets.cs b/src/Khaemhat.Core/Accounting/FixedAssets.cs new file mode 100644 index 0000000..41622f1 --- /dev/null +++ b/src/Khaemhat.Core/Accounting/FixedAssets.cs @@ -0,0 +1,315 @@ +using Khaemhat.Core.Entities; +using Khaemhat.Core.Tables; + +namespace Khaemhat.Core.Accounting; + +/// Whether a category holds tangible or intangible assets. +public enum AssetClass +{ + /// Immobilizzazioni materiali. + Tangible = 0, + + /// Immobilizzazioni immateriali. + Intangible = 1, +} + +/// +/// A category of fixed assets (SPEC §11.7, mockup 048, fixed_asset_categories): the ministerial coefficient, the +/// civil and fiscal rates and the accounts the depreciation posts to. +/// +public sealed class FixedAssetCategory : CodedEntity +{ + /// Tangible or intangible. + public AssetClass Class { get; set; } + + /// The group and species of the ministerial table (DM 31/12/1988), such as XXII.1. + public string? MinisterialGroup { get; set; } + + /// The civil (economic-technical) yearly rate, percent. + public decimal CivilRate { get; set; } + + /// The fiscal yearly rate, percent: at most the ministerial coefficient. + public decimal FiscalRate { get; set; } + + /// Half the rate in the first year, for the civil plan too (the fiscal plan always halves it). + public bool CivilHalfFirstYear { get; set; } = true; + + /// The asset account (cost). + public long? AssetAccountId { get; set; } + + /// The accumulated depreciation account (fondo). + public long? FundAccountId { get; set; } + + /// The depreciation cost account. + public long? DepreciationAccountId { get; set; } + + /// The share of cost and depreciation deductible, percent (passenger cars: 20). + public decimal DeductiblePercent { get; set; } = 100m; + + /// The fiscal limit on the cost (passenger cars: 18,075.99), if any. + public decimal? CostLimit { get; set; } +} + +/// The state of a fixed asset. +public enum AssetStatus +{ + /// In use and being depreciated. + Active = 0, + + /// Fully depreciated, still in use. + Depreciated = 1, + + /// Sold or scrapped. + Disposed = 2, +} + +/// +/// A fixed asset (cespite, SPEC §11.7, mockup 048, fixed_assets): its cost, the rates (from the category unless +/// changed), the depreciation already done and its state. The history of its values is in its movements. +/// +public sealed class FixedAsset : Entity, IDemoMarkable +{ + /// The code, such as CESP-0041. + public string Code { get; set; } = string.Empty; + + /// The description. + public string Description { get; set; } = string.Empty; + + /// The category. + public long CategoryId { get; set; } + + /// The day it was bought. + public DateOnly PurchaseDate { get; set; } + + /// The day it went into use: the depreciation starts in that year. + public DateOnly InServiceDate { get; set; } + + /// The supplier. + public long? SupplierId { get; set; } + + /// The purchase document, as text (the supplier's number and date). + public string? DocumentReference { get; set; } + + /// Where it is. + public string? Location { get; set; } + + /// The serial number. + public string? SerialNumber { get; set; } + + /// The quantity. + public decimal Quantity { get; set; } = 1m; + + /// The cost: purchase plus increases and revaluations, less disposals. + public decimal Cost { get; set; } + + /// The civil accumulated depreciation. + public decimal CivilFund { get; set; } + + /// The fiscal accumulated depreciation. + public decimal FiscalFund { get; set; } + + /// The civil rate, when different from the category. + public decimal? CivilRate { get; set; } + + /// The fiscal rate, when different from the category. + public decimal? FiscalRate { get; set; } + + /// The value left at the end of its life, not depreciated. + public decimal ResidualValue { get; set; } + + /// A good of unit cost up to the low-value threshold, depreciated in full in its first year. + public bool LowValue { get; set; } + + /// The state. + public AssetStatus Status { get; set; } + + /// The day it was disposed of. + public DateOnly? DisposalDate { get; set; } + + /// The last year depreciated. + public int? LastDepreciationYear { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } + + /// The civil net book value. + public decimal NetValue => Cost - CivilFund; +} + +/// What a movement of a fixed asset records. +public enum AssetMovementKind +{ + /// The purchase. + Purchase = 0, + + /// An increase of cost (improvement, extraordinary maintenance). + Increase = 1, + + /// A revaluation by law. + Revaluation = 2, + + /// The depreciation of a year. + Depreciation = 3, + + /// A disposal of part of the asset. + PartialDisposal = 4, + + /// The disposal of the whole asset (sale, scrapping). + Disposal = 5, + + /// The values brought in when the register starts (assets bought before Khaemhat). + Opening = 6, +} + +/// A movement of a fixed asset (fixed_asset_movements): the history of its cost and depreciation. +public sealed class FixedAssetMovement : Entity, IDemoMarkable +{ + /// The asset. + public long AssetId { get; set; } + + /// What it records. + public AssetMovementKind Kind { get; set; } + + /// The day. + public DateOnly MovementDate { get; set; } + + /// The fiscal year of a depreciation. + public int Year { get; set; } + + /// The change of cost (negative for disposals). + public decimal CostAmount { get; set; } + + /// The change of the civil fund (the depreciation, or negative for disposals). + public decimal CivilAmount { get; set; } + + /// The change of the fiscal fund. + public decimal FiscalAmount { get; set; } + + /// The price of a disposal. + public decimal Proceeds { get; set; } + + /// The gain (positive) or loss (negative) of a disposal. + public decimal GainLoss { get; set; } + + /// The description. + public string? Description { get; set; } + + /// The entry posted. + public long? GlEntryId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// The depreciation of one year of a plan. +/// The year. +/// The fund at the start of the year. +/// The rate applied, percent (halved in the first year). +/// The depreciation of the year. +/// The fund at the end of the year. +/// The value left to depreciate. +public sealed record DepreciationYear(int Year, decimal Opening, decimal Rate, decimal Amount, decimal Closing, decimal NetValue); + +/// What the depreciation of an asset needs. +/// The cost. +/// The value not depreciated. +/// The yearly rate, percent. +/// The first year of use. +/// Half the rate in the first year. +/// Fully depreciated in its first year. +public sealed record DepreciationBasis(decimal Cost, decimal Residual, decimal Rate, int FirstYear, bool HalfFirstYear, bool LowValue); + +/// +/// The straight-line depreciation (SPEC §21, issue #82): the rate on the cost, halved in the first year when asked, never +/// more than what is left; low-value goods in full in the first year. The same rules make the civil and the fiscal plan, +/// with their own rates. +/// +public static class DepreciationCalculator +{ + /// The depreciation of a year. + /// The asset. + /// The year. + /// The fund at the start of the year. + /// The amount, rounded to the cent; zero before the first year or when nothing is left. + public static decimal Yearly(DepreciationBasis basis, int year, decimal fund) + { + ArgumentNullException.ThrowIfNull(basis); + var depreciable = Math.Max(0m, basis.Cost - basis.Residual); + var left = Math.Max(0m, depreciable - fund); + if (year < basis.FirstYear || left == 0m) + { + return 0m; + } + + if (basis.LowValue) + { + return left; + } + + var amount = Math.Round(depreciable * RateOf(basis, year) / 100m, 2, MidpointRounding.AwayFromZero); + return Math.Min(amount, left); + } + + /// The rate of a year: halved in the first year when asked. + /// The asset. + /// The year. + /// The rate, percent. + public static decimal RateOf(DepreciationBasis basis, int year) + { + ArgumentNullException.ThrowIfNull(basis); + if (basis.LowValue) + { + return year == basis.FirstYear ? 100m : 0m; + } + + return year == basis.FirstYear && basis.HalfFirstYear ? basis.Rate / 2m : basis.Rate; + } + + /// The whole plan from a year with its fund, to the end of the depreciation (at most 100 years). + /// The asset. + /// The first year shown. + /// The fund at the start of that year. + /// The years. + public static IReadOnlyList Plan(DepreciationBasis basis, int fromYear, decimal fund) + { + ArgumentNullException.ThrowIfNull(basis); + var depreciable = Math.Max(0m, basis.Cost - basis.Residual); + var years = new List(); + var year = Math.Max(fromYear, basis.FirstYear); + while (years.Count < 100) + { + var amount = Yearly(basis, year, fund); + if (amount <= 0m) + { + break; + } + + years.Add(new DepreciationYear(year, fund, RateOf(basis, year), amount, fund + amount, depreciable - fund - amount)); + fund += amount; + year++; + } + + return years; + } + + /// + /// The gain or loss of a disposal: the price less the net value of the part disposed of (cost less fund, both in the + /// share disposed of). + /// + /// The cost disposed of. + /// The fund of the part disposed of. + /// The price. + /// Positive a gain (plusvalenza), negative a loss (minusvalenza). + public static decimal GainLoss(decimal cost, decimal fund, decimal proceeds) => proceeds - (cost - fund); + + /// The share of a fund that follows a part of the cost disposed of. + /// The cost of the whole asset. + /// Its fund. + /// The cost disposed of. + /// The fund of that part, rounded to the cent. + public static decimal FundShare(decimal totalCost, decimal totalFund, decimal costDisposed) => + totalCost == 0m ? 0m : Math.Round(totalFund * costDisposed / totalCost, 2, MidpointRounding.AwayFromZero); +} diff --git a/src/Khaemhat.Core/Accounting/Intrastat.cs b/src/Khaemhat.Core/Accounting/Intrastat.cs new file mode 100644 index 0000000..63de443 --- /dev/null +++ b/src/Khaemhat.Core/Accounting/Intrastat.cs @@ -0,0 +1,222 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Accounting; + +/// Sales to or purchases from the other member states. +public enum IntrastatFlow +{ + /// Cessioni (INTRA-1). + Sales = 0, + + /// Acquisti (INTRA-2). + Purchases = 1, +} + +/// How often the lists are due. +public enum IntrastatPeriodicity +{ + /// Every month. + Monthly = 0, + + /// Every quarter. + Quarterly = 1, + + /// Not due (purchases below the threshold). + NotDue = 2, +} + +/// The section of a list. +public enum IntrastatSection +{ + /// Goods (INTRA-1 bis, INTRA-2 bis). + Goods = 0, + + /// Corrections of goods of earlier periods (ter). + GoodsCorrection = 1, + + /// Services (INTRA-1 quater, INTRA-2 quater). + Services = 2, + + /// Corrections of services of earlier periods (quinquies). + ServicesCorrection = 3, +} + +/// The state of a list. +public enum IntrastatStatus +{ + /// Being prepared: can be generated again. + Draft = 0, + + /// The file was written. + Generated = 1, + + /// Sent to the customs: read only. + Sent = 2, +} + +/// What the check of a line found. +public enum IntrastatCheck +{ + /// Complete. + Ok = 0, + + /// The combined nomenclature code is missing or not of 8 digits. + MissingNomenclature = 1, + + /// The net mass is missing. + MissingMass = 2, + + /// The VAT number of the counterparty is missing. + MissingVatNumber = 3, + + /// The counterparty is outside the European Union: left out. + OutsideEu = 4, + + /// The service code (CPA) is missing. + MissingServiceCode = 5, +} + +/// +/// An Intrastat list of a period (SPEC §11.7, mockup 049, intrastat_lists): the sales or purchases of goods and +/// services with the other member states, generated from the documents, completed by hand and written to the file +/// of the customs (SCAMBI.CEE). +/// +public sealed class IntrastatList : Entity, IDemoMarkable +{ + /// Sales or purchases. + public IntrastatFlow Flow { get; set; } + + /// The year. + public int Year { get; set; } + + /// The month (1-12) or the quarter (1-4). + public int Period { get; set; } + + /// Monthly or quarterly. + public IntrastatPeriodicity Periodicity { get; set; } + + /// The state. + public IntrastatStatus Status { get; set; } + + /// The progressive number of the list in the year, for the file. + public int Progressive { get; set; } = 1; + + /// The goods total. + public decimal GoodsAmount { get; set; } + + /// The services total. + public decimal ServicesAmount { get; set; } + + /// The lines with something missing. + public int Problems { get; set; } + + /// The name of the file written. + public string? FileName { get; set; } + + /// The protocol given by the customs. + public string? Protocol { get; set; } + + /// When it was generated. + public DateTime? GeneratedAt { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A line of an Intrastat list (intrastat_list_lines). +public sealed class IntrastatListLine : Entity, IDemoMarkable +{ + /// The list. + public long ListId { get; set; } + + /// The section. + public IntrastatSection Section { 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 customer or supplier. + public long? PartyId { get; set; } + + /// The member state of the counterparty. + public string CountryCode { get; set; } = string.Empty; + + /// The VAT number of the counterparty, without the country. + public string? VatNumber { get; set; } + + /// The amount in euro. + public decimal Amount { get; set; } + + /// The amount in the currency of the document, when not euro (purchases). + public decimal? CurrencyAmount { get; set; } + + /// The statistical value in euro. + public decimal? StatisticalValue { get; set; } + + /// The combined nomenclature code (goods, 8 digits) or the CPA code (services, 5-6 digits). + public string? NomenclatureCode { get; set; } + + /// What was sold or bought. + public string? Description { get; set; } + + /// The nature of the transaction (table B, such as 11). + public string? TransactionNature { get; set; } + + /// The delivery terms (Incoterms, such as DAP). + public string? DeliveryTerms { get; set; } + + /// The mode of transport (1 sea, 2 rail, 3 road, 4 air, 5 post, 7 fixed installations, 8 inland waterway, 9 own propulsion). + public string? TransportMode { get; set; } + + /// The net mass in kilograms. + public decimal? NetMass { get; set; } + + /// The supplementary units. + public decimal? SupplementaryUnits { get; set; } + + /// The country of origin of the goods (purchases). + public string? OriginCountry { get; set; } + + /// The province of origin (sales) or destination (purchases). + public string? Province { get; set; } + + /// How the service is supplied: I once, R repeated. + public string? SupplyMode { get; set; } + + /// How it is paid: B transfer, A direct debit, X other. + public string? PaymentMode { get; set; } + + /// The country of the payment. + public string? PaymentCountry { get; set; } + + /// For corrections: the year of the list corrected. + public int? CorrectedYear { get; set; } + + /// For corrections: the period of the list corrected. + public int? CorrectedPeriod { get; set; } + + /// For corrections: the sign, + or -. + public string? CorrectionSign { get; set; } + + /// What the check found. + public IntrastatCheck Check { get; set; } + + /// Typed or changed by hand: generating again keeps it. + public bool Manual { get; set; } + + /// + public bool IsDemo { get; set; } + + /// Whether it goes into the file and the totals. + public bool Included => Check != IntrastatCheck.OutsideEu; +} diff --git a/src/Khaemhat.Core/Accounting/Ledger.cs b/src/Khaemhat.Core/Accounting/Ledger.cs index 15c77c0..4513287 100644 --- a/src/Khaemhat.Core/Accounting/Ledger.cs +++ b/src/Khaemhat.Core/Accounting/Ledger.cs @@ -264,6 +264,18 @@ public enum GlEntrySource /// A collection, a payment or a remittance of the schedule (M8). Treasury = 7, + + /// The depreciation, a disposal or the opening values of a fixed asset (M10). + FixedAsset = 8, + + /// An accrual or deferral at the year end, or its reversal at the opening (M10). + Accrual = 9, + + /// The exchange differences of the open items at the year end (M10). + ExchangeDifference = 10, + + /// A step of the guided closing: inventory, provisions, closing and opening (M10). + Closing = 11, } /// @@ -353,6 +365,9 @@ public sealed class GlEntry : Entity, IDemoMarkable /// Notes. public string? Notes { get; set; } + /// The step of the closing that wrote it (closing/<step>), 1-9. + public int? ClosingStep { get; set; } + /// public bool IsDemo { get; set; } diff --git a/src/Khaemhat.Core/Accounting/YearEnd.cs b/src/Khaemhat.Core/Accounting/YearEnd.cs new file mode 100644 index 0000000..ae00834 --- /dev/null +++ b/src/Khaemhat.Core/Accounting/YearEnd.cs @@ -0,0 +1,326 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Accounting; + +/// What an accrual or deferral adjusts at the year end. +public enum AccrualKind +{ + /// Rateo attivo: revenue of the year to be collected or invoiced next year. + AccruedIncome = 0, + + /// Rateo passivo: cost of the year to be paid or invoiced next year. + AccruedExpense = 1, + + /// Risconto attivo: cost recorded this year that belongs to the next (insurance paid in advance). + PrepaidExpense = 2, + + /// Risconto passivo: revenue recorded this year that belongs to the next. + DeferredIncome = 3, +} + +/// +/// An accrual or deferral (rateo o risconto, SPEC §11.7, issue #84, accruals): an amount of a cost or revenue +/// spread over a period across the year end; the share of the year (ratei) or of the next years (risconti) is posted +/// at the year end and reversed at the opening. +/// +public sealed class AccrualDeferral : Entity, IDemoMarkable +{ + /// The fiscal year it adjusts (the year of its end date). + public int Year { get; set; } + + /// The kind. + public AccrualKind Kind { get; set; } + + /// The description. + public string Description { get; set; } = string.Empty; + + /// The cost or revenue account. + public long AccountId { get; set; } + + /// The whole amount of the period. + public decimal Amount { get; set; } + + /// The first day of the period. + public DateOnly PeriodStart { get; set; } + + /// The last day of the period. + public DateOnly PeriodEnd { get; set; } + + /// The last day of the year adjusted. + public DateOnly YearEnd { get; set; } + + /// The share posted at the year end. + public decimal Adjustment { get; set; } + + /// The family of the document it comes from. + public DocumentFamily? SourceFamily { get; set; } + + /// The document it comes from. + public long? SourceDocumentId { get; set; } + + /// The number of that document. + public string? DocumentNumber { get; set; } + + /// The customer or supplier. + public long? PartyId { get; set; } + + /// The entry of the year end. + public long? GlEntryId { get; set; } + + /// The entry that reverses it at the opening of the next year. + public long? ReversalEntryId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// +/// The share of an amount by days (SPEC §21, issue #84): what belongs to the year up to its end (ratei) or after it +/// (risconti), counting the days of the period both ends included. +/// +public static class AccrualDeferralCalculator +{ + /// The share of an amount posted at the year end. + /// The kind. + /// The whole amount. + /// The first day of the period. + /// The last day of the period. + /// The last day of the year. + /// For ratei the days up to the year end, for risconti those after it, rounded to the cent. + public static decimal Share(AccrualKind kind, decimal amount, DateOnly start, DateOnly end, DateOnly yearEnd) + { + if (end < start) + { + return 0m; + } + + var total = end.DayNumber - start.DayNumber + 1; + var within = Math.Clamp(yearEnd.DayNumber - start.DayNumber + 1, 0, total); + var days = kind is AccrualKind.AccruedIncome or AccrualKind.AccruedExpense ? within : total - within; + return Math.Round(amount * days / total, 2, MidpointRounding.AwayFromZero); + } + + /// The days of the period that belong to the year and to the next years. + /// The first day of the period. + /// The last day of the period. + /// The last day of the year. + /// The days of the year, the days after, the total. + public static (int Within, int After, int Total) Days(DateOnly start, DateOnly end, DateOnly yearEnd) + { + if (end < start) + { + return (0, 0, 0); + } + + var total = end.DayNumber - start.DayNumber + 1; + var within = Math.Clamp(yearEnd.DayNumber - start.DayNumber + 1, 0, total); + return (within, total - within, total); + } + + /// Whether the adjustment is a cost (ratei passivi, risconti attivi on cost accounts) or a revenue. + /// The kind. + /// for costs. + public static bool IsCost(AccrualKind kind) => kind is AccrualKind.AccruedExpense or AccrualKind.PrepaidExpense; +} + +/// +/// The exchange difference of an open item in foreign currency at the year end (SPEC §21, issue #84): the residual in +/// the currency valued at the rate of the year end against its value in euro at the rate of the document. +/// +public static class ExchangeDifferenceCalculator +{ + /// The residual in the currency of the document. + /// The residual in euro, at the rate of the document. + /// Units of the currency for one euro on the document. + /// The residual in the currency. + public static decimal InCurrency(decimal residualEuro, decimal documentRate) => Math.Round(residualEuro * documentRate, 2, MidpointRounding.AwayFromZero); + + /// The difference in euro: positive increases the residual in euro. + /// The residual in euro, at the rate of the document. + /// Units of the currency for one euro on the document. + /// Units of the currency for one euro at the year end. + /// The new value less the old one, rounded to the cent. + public static decimal Difference(decimal residualEuro, decimal documentRate, decimal yearEndRate) + { + if (documentRate <= 0m || yearEndRate <= 0m) + { + return 0m; + } + + var revalued = Math.Round(residualEuro * documentRate / yearEndRate, 2, MidpointRounding.AwayFromZero); + return revalued - residualEuro; + } + + /// Whether a difference is a gain for the company. + /// A receivable or a payable. + /// The difference of the residual in euro. + /// A larger receivable or a smaller payable is a gain. + public static bool IsGain(OpenItemDirection direction, decimal difference) => + direction == OpenItemDirection.Receivable ? difference > 0m : difference < 0m; +} + +/// The state of a year-end closing. +public enum ClosingStatus +{ + /// Steps being run. + InProgress = 0, + + /// Every step done and the year locked: read only. + Locked = 1, +} + +/// The state of a step of the closing. +public enum ClosingStepStatus +{ + /// Not run yet. + Pending = 0, + + /// Run, with entries or without anything to do. + Done = 1, + + /// Checks passed. + Passed = 2, + + /// Run with something to look at (warnings). + ToVerify = 3, + + /// Checks failed: the next steps wait. + Failed = 4, +} + +/// +/// The guided closing of a fiscal year (SPEC §11.7, mockup 050, closing_runs): its steps, the year that +/// follows and the lock. +/// +public sealed class ClosingRun : Entity +{ + /// The year closed. + public long FiscalYearId { get; set; } + + /// The code of the year, such as 2026. + public string YearCode { get; set; } = string.Empty; + + /// The state. + public ClosingStatus Status { get; set; } + + /// The year opened by the closing. + public long? NextFiscalYearId { get; set; } + + /// The result of the year: positive a profit. + public decimal Result { get; set; } + + /// When the year was locked. + public DateTime? LockedAt { get; set; } + + /// Who locked it. + public string? LockedBy { get; set; } +} + +/// A step of a closing (closing_steps): run, repeated or undone until the year is locked. +public sealed class ClosingStep : Entity +{ + /// The closing. + public long RunId { get; set; } + + /// The number, 1-9. + public int Number { get; set; } + + /// The state. + public ClosingStepStatus Status { get; set; } + + /// The entries written by the step. + public int Entries { get; set; } + + /// The amount the step worked on (depreciation, inventory, result...). + public decimal Amount { get; set; } + + /// What happened, one message per line (codes of texts with their values). + public string? Messages { get; set; } + + /// When it ran. + public DateTime? ExecutedAt { get; set; } + + /// Who ran it. + public string? ExecutedBy { get; set; } +} + +/// A final print of a closing (closing_prints): the books of the year, kept with the closing. +public sealed class ClosingPrint : Entity +{ + /// The closing. + public long RunId { get; set; } + + /// What the print is: journal, inventory, vat, assets. + public string Kind { get; set; } = string.Empty; + + /// The file name. + public string FileName { get; set; } = string.Empty; + + /// The pages. + public int Pages { get; set; } + + /// The PDF. + public byte[] Content { get; set; } = []; +} + +/// The figures the financial ratios read, from the reclassified statements. +/// Patrimonio netto, with the result of the year. +/// The result of the year. +/// The operating result (EBIT, A-B). +/// The revenue of sales (A.1). +/// The total assets (capitale investito). +/// The fixed assets, net. +/// The current assets (with accruals). +/// The inventory. +/// Cash and banks. +/// Trade receivables. +/// Liabilities due within the year (with accruals). +/// Liabilities due later, funds and severance. +/// Trade payables. +/// Purchases of materials and services (B.6, B.7). +/// The days of the period (365 for a year). +public sealed record RatioInputs( + decimal Equity, decimal Result, decimal OperatingResult, decimal Revenue, decimal TotalAssets, decimal FixedAssets, decimal CurrentAssets, + decimal Inventory, decimal Liquidity, decimal Receivables, decimal CurrentLiabilities, decimal LongTermLiabilities, decimal Payables, + decimal Purchases, int Days); + +/// A financial ratio. +/// The code, such as ROE. +/// The value; when the denominator is zero. +/// Shown as a percent. +/// Shown in days. +public sealed record FinancialRatio(string Code, decimal? Value, bool Percent = false, bool DaysUnit = false); + +/// +/// The financial ratios of the statements (SPEC §11.7, mockup 051): profitability (ROE, ROI, ROS), liquidity (current, +/// quick), solidity (equity ratio, leverage, fixed asset coverage), rotation (days of customers and suppliers). +/// +public static class FinancialRatios +{ + /// Computes the ratios. + /// The figures. + /// The ratios, in display order. + public static IReadOnlyList Compute(RatioInputs input) + { + ArgumentNullException.ThrowIfNull(input); + var days = input.Days <= 0 ? 365 : input.Days; + return + [ + new("ROE", Ratio(input.Result, input.Equity, 100m), Percent: true), + new("ROI", Ratio(input.OperatingResult, input.TotalAssets, 100m), Percent: true), + new("ROS", Ratio(input.OperatingResult, input.Revenue, 100m), Percent: true), + new("TURNOVER", Ratio(input.Revenue, input.TotalAssets, 1m)), + new("CURRENT", Ratio(input.CurrentAssets, input.CurrentLiabilities, 1m)), + new("QUICK", Ratio(input.CurrentAssets - input.Inventory, input.CurrentLiabilities, 1m)), + new("EQUITY", Ratio(input.Equity, input.TotalAssets, 100m), Percent: true), + new("LEVERAGE", Ratio(input.TotalAssets, input.Equity, 1m)), + new("COVERAGE", Ratio(input.Equity + input.LongTermLiabilities, input.FixedAssets, 1m)), + new("DSO", Ratio(input.Receivables * days, input.Revenue, 1m), DaysUnit: true), + new("DPO", Ratio(input.Payables * days, input.Purchases, 1m), DaysUnit: true), + ]; + } + + private static decimal? Ratio(decimal numerator, decimal denominator, decimal factor) => + denominator == 0m ? null : Math.Round(numerator / denominator * factor, 2, MidpointRounding.AwayFromZero); +} diff --git a/src/Khaemhat.Core/Parties/IntentDeclarations.cs b/src/Khaemhat.Core/Parties/IntentDeclarations.cs new file mode 100644 index 0000000..6eea111 --- /dev/null +++ b/src/Khaemhat.Core/Parties/IntentDeclarations.cs @@ -0,0 +1,91 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Parties; + +/// Whether a declaration of intent was received from a customer or issued by the company. +public enum IntentDirection +{ + /// Received from a habitual exporter customer: its sales go without VAT up to the ceiling. + Received = 0, + + /// Issued by the company to a supplier, on its own ceiling (plafond). + Issued = 1, +} + +/// The state of a declaration of intent. +public enum IntentStatus +{ + /// In force. + Active = 0, + + /// The ceiling is used up. + Exhausted = 1, + + /// Revoked or replaced. + Revoked = 2, +} + +/// +/// A declaration of intent (dichiarazione d'intento, SPEC §11.7, mockup 061, intent_declarations): a habitual +/// exporter buys without VAT (art. 8 c. 1 lett. c DPR 633/72) up to the ceiling it declares; the invoices carry the +/// protocol of the Agenzia delle Entrate and the nature N3.5. The register keeps the declarations received and issued +/// in chronological order with the ceiling used. +/// +public sealed class IntentDeclaration : Entity, IDemoMarkable +{ + /// Received or issued. + public IntentDirection Direction { get; set; } + + /// The progressive of the chronological register in the year. + public int RegisterNumber { get; set; } + + /// The year. + public int Year { get; set; } + + /// The customer (received) or supplier (issued). + public long PartyId { get; set; } + + /// The number given by the declarant, such as 12345/2026. + public string Number { get; set; } = string.Empty; + + /// The day of the declaration. + public DateOnly DeclarationDate { get; set; } + + /// The protocol of the receipt of the Agenzia delle Entrate (17 digits, dash, 6 digits). + public string Protocol { get; set; } = string.Empty; + + /// The ceiling declared. + public decimal Ceiling { get; set; } + + /// The ceiling used by the invoices. + public decimal Used { get; set; } + + /// The first day it covers. + public DateOnly ValidFrom { get; set; } + + /// The last day it covers. + public DateOnly ValidTo { get; set; } + + /// The VAT code the invoices use (nature N3.5). + public long? TaxCodeId { get; set; } + + /// The state. + public IntentStatus Status { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } + + /// The ceiling left. + public decimal Remaining => Ceiling - Used; + + /// The share used, percent. + public decimal UsedPercent => Ceiling <= 0m ? 0m : Math.Round(Used / Ceiling * 100m, 0, MidpointRounding.AwayFromZero); + + /// Whether it covers a day. + /// The day. + /// when active and the day is in its period. + public bool Covers(DateOnly date) => Status != IntentStatus.Revoked && ValidFrom <= date && date <= ValidTo; +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_005_CreateYearEnd.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_005_CreateYearEnd.cs new file mode 100644 index 0000000..820e24b --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_005_CreateYearEnd.cs @@ -0,0 +1,251 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// The year end (SPEC §11.7, ADR 0041-0043, issues #82-#86): the fixed assets with their categories and movements, the +/// accruals and deferrals, the guided closing with its steps and final prints, the Intrastat lists and the declarations +/// of intent; the entries remember the step of the closing that wrote them. +/// +[Migration(20261113_005, "create_year_end")] +public sealed class M20261113_005_CreateYearEnd : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.AlterTable("gl_entries", t => t.Int32("closing_step")); + + schema.CreateTable("fixed_asset_categories", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("class", 40).NotNull(); + t.String("ministerial_group", 20); + t.Decimal("civil_rate").NotNull().Default(0m); + t.Decimal("fiscal_rate").NotNull().Default(0m); + t.Bool("civil_half_first_year").NotNull().Default(true); + t.Int64("asset_account_id"); + t.Int64("fund_account_id"); + t.Int64("depreciation_account_id"); + t.Decimal("deductible_percent").NotNull().Default(100m); + t.Decimal("cost_limit"); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_fixed_asset_categories_code", "code"); + t.ForeignKey("fk_fixed_asset_categories_asset", "asset_account_id", "gl_accounts", ReferentialAction.Restrict); + t.ForeignKey("fk_fixed_asset_categories_fund", "fund_account_id", "gl_accounts", ReferentialAction.Restrict); + t.ForeignKey("fk_fixed_asset_categories_depreciation", "depreciation_account_id", "gl_accounts", ReferentialAction.Restrict); + }); + + schema.CreateTable("fixed_assets", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 200).NotNull(); + t.Int64("category_id").NotNull(); + t.Date("purchase_date").NotNull(); + t.Date("in_service_date").NotNull(); + t.Int64("supplier_id"); + t.String("document_reference", 60); + t.String("location", 100); + t.String("serial_number", 60); + t.Decimal("quantity").NotNull().Default(1m); + t.Decimal("cost").NotNull().Default(0m); + t.Decimal("civil_fund").NotNull().Default(0m); + t.Decimal("fiscal_fund").NotNull().Default(0m); + t.Decimal("civil_rate"); + t.Decimal("fiscal_rate"); + t.Decimal("residual_value").NotNull().Default(0m); + t.Bool("low_value").NotNull().Default(false); + t.String("status", 40).NotNull(); + t.Date("disposal_date"); + t.Int32("last_depreciation_year"); + t.String("notes", 500); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_fixed_assets_code", "code"); + t.Index("ix_fixed_assets_category", "category_id"); + t.ForeignKey("fk_fixed_assets_category", "category_id", "fixed_asset_categories", ReferentialAction.Restrict); + t.ForeignKey("fk_fixed_assets_supplier", "supplier_id", "parties", ReferentialAction.Restrict); + }); + + schema.CreateTable("fixed_asset_movements", t => + { + t.Id(); + t.Int64("asset_id").NotNull(); + t.String("kind", 40).NotNull(); + t.Date("movement_date").NotNull(); + t.Int32("year").NotNull(); + t.Decimal("cost_amount").NotNull().Default(0m); + t.Decimal("civil_amount").NotNull().Default(0m); + t.Decimal("fiscal_amount").NotNull().Default(0m); + t.Decimal("proceeds").NotNull().Default(0m); + t.Decimal("gain_loss").NotNull().Default(0m); + t.String("description", 200); + t.Int64("gl_entry_id"); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_fixed_asset_movements_asset", "asset_id", "movement_date"); + t.Index("ix_fixed_asset_movements_year", "year", "kind"); + t.ForeignKey("fk_fixed_asset_movements_asset", "asset_id", "fixed_assets", ReferentialAction.Cascade); + t.ForeignKey("fk_fixed_asset_movements_entry", "gl_entry_id", "gl_entries", ReferentialAction.Restrict); + }); + + schema.CreateTable("accruals", t => + { + t.Id(); + t.Int32("year").NotNull(); + t.String("kind", 40).NotNull(); + t.String("description", 200).NotNull(); + t.Int64("account_id").NotNull(); + t.Decimal("amount").NotNull().Default(0m); + t.Date("period_start").NotNull(); + t.Date("period_end").NotNull(); + t.Date("year_end").NotNull(); + t.Decimal("adjustment").NotNull().Default(0m); + t.String("source_family", 40); + t.Int64("source_document_id"); + t.String("document_number", 40); + t.Int64("party_id"); + t.Int64("gl_entry_id"); + t.Int64("reversal_entry_id"); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_accruals_year", "year"); + t.ForeignKey("fk_accruals_account", "account_id", "gl_accounts", ReferentialAction.Restrict); + t.ForeignKey("fk_accruals_entry", "gl_entry_id", "gl_entries", ReferentialAction.Restrict); + t.ForeignKey("fk_accruals_reversal", "reversal_entry_id", "gl_entries", ReferentialAction.Restrict); + }); + + schema.CreateTable("closing_runs", t => + { + t.Id(); + t.Int64("fiscal_year_id").NotNull(); + t.String("year_code", 10).NotNull(); + t.String("status", 40).NotNull(); + t.Int64("next_fiscal_year_id"); + t.Decimal("result").NotNull().Default(0m); + t.DateTimeUtc("locked_at"); + t.String("locked_by", 100); + t.AuditColumns(); + t.Unique("ux_closing_runs_year", "fiscal_year_id"); + t.ForeignKey("fk_closing_runs_year", "fiscal_year_id", "fiscal_years", ReferentialAction.Restrict); + }); + + schema.CreateTable("closing_steps", t => + { + t.Id(); + t.Int64("run_id").NotNull(); + t.Int32("number").NotNull(); + t.String("status", 40).NotNull(); + t.Int32("entries").NotNull().Default(0); + t.Decimal("amount").NotNull().Default(0m); + t.Text("messages"); + t.DateTimeUtc("executed_at"); + t.String("executed_by", 100); + t.AuditColumns(); + t.Unique("ux_closing_steps_number", "run_id", "number"); + t.ForeignKey("fk_closing_steps_run", "run_id", "closing_runs", ReferentialAction.Cascade); + }); + + schema.CreateTable("closing_prints", t => + { + t.Id(); + t.Int64("run_id").NotNull(); + t.String("kind", 20).NotNull(); + t.String("file_name", 100).NotNull(); + t.Int32("pages").NotNull().Default(0); + t.Bytes("content").NotNull(); + t.AuditColumns(); + t.Index("ix_closing_prints_run", "run_id"); + t.ForeignKey("fk_closing_prints_run", "run_id", "closing_runs", ReferentialAction.Cascade); + }); + + schema.CreateTable("intrastat_lists", t => + { + t.Id(); + t.String("flow", 40).NotNull(); + t.Int32("year").NotNull(); + t.Int32("period").NotNull(); + t.String("periodicity", 40).NotNull(); + t.String("status", 40).NotNull(); + t.Int32("progressive").NotNull().Default(1); + t.Decimal("goods_amount").NotNull().Default(0m); + t.Decimal("services_amount").NotNull().Default(0m); + t.Int32("problems").NotNull().Default(0); + t.String("file_name", 60); + t.String("protocol", 40); + t.DateTimeUtc("generated_at"); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_intrastat_lists_period", "flow", "year", "periodicity", "period"); + }); + + schema.CreateTable("intrastat_list_lines", t => + { + t.Id(); + t.Int64("list_id").NotNull(); + t.String("section", 40).NotNull(); + t.String("source_family", 40); + t.Int64("source_document_id"); + t.String("document_number", 40); + t.Date("document_date"); + t.Int64("party_id"); + t.String("country_code", 2).NotNull(); + t.String("vat_number", 20); + t.Decimal("amount").NotNull().Default(0m); + t.Decimal("currency_amount"); + t.Decimal("statistical_value"); + t.String("nomenclature_code", 10); + t.String("description", 200); + t.String("transaction_nature", 2); + t.String("delivery_terms", 3); + t.String("transport_mode", 1); + t.Decimal("net_mass"); + t.Decimal("supplementary_units"); + t.String("origin_country", 2); + t.String("province", 2); + t.String("supply_mode", 1); + t.String("payment_mode", 1); + t.String("payment_country", 2); + t.Int32("corrected_year"); + t.Int32("corrected_period"); + t.String("correction_sign", 1); + t.String("check", 40).NotNull(); + t.Bool("manual").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_intrastat_list_lines_list", "list_id", "section"); + t.ForeignKey("fk_intrastat_list_lines_list", "list_id", "intrastat_lists", ReferentialAction.Cascade); + }); + + schema.CreateTable("intent_declarations", t => + { + t.Id(); + t.String("direction", 40).NotNull(); + t.Int32("register_number").NotNull(); + t.Int32("year").NotNull(); + t.Int64("party_id").NotNull(); + t.String("number", 40).NotNull(); + t.Date("declaration_date").NotNull(); + t.String("protocol", 40).NotNull(); + t.Decimal("ceiling").NotNull().Default(0m); + t.Decimal("used").NotNull().Default(0m); + t.Date("valid_from").NotNull(); + t.Date("valid_to").NotNull(); + t.Int64("tax_code_id"); + t.String("status", 40).NotNull(); + t.String("notes", 500); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_intent_declarations_register", "direction", "year", "register_number"); + t.Index("ix_intent_declarations_party", "party_id", "valid_from"); + t.ForeignKey("fk_intent_declarations_party", "party_id", "parties", ReferentialAction.Restrict); + t.ForeignKey("fk_intent_declarations_tax", "tax_code_id", "tax_codes", ReferentialAction.Restrict); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/YearEndMaps.cs b/src/Khaemhat.Data/CompanyDatabase/YearEndMaps.cs new file mode 100644 index 0000000..1bec5b4 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/YearEndMaps.cs @@ -0,0 +1,141 @@ +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Parties; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to fixed_asset_categories. +public sealed class FixedAssetCategoryMap : EntityMap +{ + /// Creates the map. + public FixedAssetCategoryMap() + { + ToTable("fixed_asset_categories"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Description).MaxLength(100); + Map(x => x.MinisterialGroup).MaxLength(20); + } +} + +/// Map of to fixed_assets. +public sealed class FixedAssetMap : EntityMap +{ + /// Creates the map. + public FixedAssetMap() + { + ToTable("fixed_assets"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Description).MaxLength(200); + Map(x => x.DocumentReference).MaxLength(60); + Map(x => x.Location).MaxLength(100); + Map(x => x.SerialNumber).MaxLength(60); + Map(x => x.Notes).MaxLength(500); + } +} + +/// Map of to fixed_asset_movements. +public sealed class FixedAssetMovementMap : EntityMap +{ + /// Creates the map. + public FixedAssetMovementMap() + { + ToTable("fixed_asset_movements"); + Map(x => x.Description).MaxLength(200); + } +} + +/// Map of to accruals. +public sealed class AccrualDeferralMap : EntityMap +{ + /// Creates the map. + public AccrualDeferralMap() + { + ToTable("accruals"); + Map(x => x.Description).MaxLength(200); + Map(x => x.DocumentNumber).MaxLength(40); + } +} + +/// Map of to closing_runs. +public sealed class ClosingRunMap : EntityMap +{ + /// Creates the map. + public ClosingRunMap() + { + ToTable("closing_runs"); + Map(x => x.YearCode).MaxLength(10); + Map(x => x.LockedBy).MaxLength(100); + } +} + +/// Map of to closing_steps. +public sealed class ClosingStepMap : EntityMap +{ + /// Creates the map. + public ClosingStepMap() + { + ToTable("closing_steps"); + Map(x => x.ExecutedBy).MaxLength(100); + } +} + +/// Map of to closing_prints. +public sealed class ClosingPrintMap : EntityMap +{ + /// Creates the map. + public ClosingPrintMap() + { + ToTable("closing_prints"); + Map(x => x.Kind).MaxLength(20); + Map(x => x.FileName).MaxLength(100); + } +} + +/// Map of to intrastat_lists. +public sealed class IntrastatListMap : EntityMap +{ + /// Creates the map. + public IntrastatListMap() + { + ToTable("intrastat_lists"); + Map(x => x.FileName).MaxLength(60); + Map(x => x.Protocol).MaxLength(40); + } +} + +/// Map of to intrastat_list_lines. +public sealed class IntrastatListLineMap : EntityMap +{ + /// Creates the map. + public IntrastatListLineMap() + { + ToTable("intrastat_list_lines"); + Map(x => x.DocumentNumber).MaxLength(40); + Map(x => x.CountryCode).MaxLength(2); + Map(x => x.VatNumber).MaxLength(20); + Map(x => x.NomenclatureCode).MaxLength(10); + Map(x => x.Description).MaxLength(200); + Map(x => x.TransactionNature).MaxLength(2); + Map(x => x.DeliveryTerms).MaxLength(3); + Map(x => x.TransportMode).MaxLength(1); + Map(x => x.OriginCountry).MaxLength(2); + Map(x => x.Province).MaxLength(2); + Map(x => x.SupplyMode).MaxLength(1); + Map(x => x.PaymentMode).MaxLength(1); + Map(x => x.PaymentCountry).MaxLength(2); + Map(x => x.CorrectionSign).MaxLength(1); + } +} + +/// Map of to intent_declarations. +public sealed class IntentDeclarationMap : EntityMap +{ + /// Creates the map. + public IntentDeclarationMap() + { + ToTable("intent_declarations"); + Map(x => x.Number).MaxLength(40); + Map(x => x.Protocol).MaxLength(40); + Map(x => x.Notes).MaxLength(500); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs index feaa051..64d5011 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Features.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -88,8 +88,34 @@ public interface IFixedAssetRules /// The depreciation of the previous years. /// The depreciation, rounded to the cent. decimal YearlyDepreciation(decimal cost, decimal ratePercent, bool firstYear, decimal alreadyDepreciated); + + /// The fiscal coefficients the categories start from (Italy: DM 31/12/1988 and art. 103 TUIR). + IReadOnlyList Coefficients { get; } } +/// A fiscal depreciation coefficient with the accounts of the chart it goes with. +/// The code of the proposed category, such as MOB. +/// What it covers. +/// The ministerial group and species, such as XXII/22. +/// The yearly rate in percent. +/// Whether it is an intangible asset. +/// The account of the chart for the cost. +/// The account of the chart for the accumulated depreciation. +/// The account of the chart for the yearly charge. +/// The tax limit on the cost, if any (passenger cars). +/// The share of the charge that is deductible. +public sealed record DepreciationCoefficient( + string Code, + string Description, + string Group, + decimal Rate, + bool Intangible, + string AssetAccount, + string FundAccount, + string DepreciationAccount, + decimal? CostLimit = null, + decimal DeductiblePercent = 100m); + /// A tax payment code of the country's payment form (Italy: codice tributo F24). /// The code, such as 6001. /// What it pays. @@ -133,14 +159,89 @@ public interface ITaxPaymentFormExporter byte[] Export(TaxPaymentForm form); } +/// The accounts of the chart the year end posts to (Italy: the codes of the model chart). +/// Other receivables: the price of a disposal of an asset. +/// Gains on disposals (plusvalenze). +/// Losses on disposals (minusvalenze). +/// Accrued income (ratei attivi). +/// Prepaid expenses (risconti attivi). +/// Accrued expenses (ratei passivi). +/// Deferred income (risconti passivi). +/// Exchange gains. +/// Exchange losses. +/// Inventory of goods. +/// Opening inventory (cost). +/// Closing inventory (revenue side of the change). +/// Write-down of receivables (charge). +/// Allowance for doubtful receivables. +/// Severance pay (charge). +/// Severance pay fund. +/// Opening balance sheet account. +/// Closing balance sheet account. +/// Income summary account. +/// Result of the year (equity). +/// Share capital. +public sealed record YearEndAccountCodes( + string OtherReceivables, string Gains, string Losses, string AccruedIncome, string PrepaidExpenses, string AccruedExpenses, string DeferredIncome, + string ExchangeGains, string ExchangeLosses, string Inventory, string OpeningInventory, string ClosingInventory, string BadDebtCharge, + string BadDebtFund, string SeveranceCharge, string SeveranceFund, string OpeningBalance, string ClosingBalance, string IncomeSummary, string Result, + string Capital); + +/// The rules of the closing of the year (M10): its accounts and the proposals of the provisions. +public interface IClosingRules +{ + /// The accounts the closing posts to. + YearEndAccountCodes Accounts { get; } + + /// The share of the trade receivables proposed as write-down (Italy: 0.5%, art. 106 TUIR). + decimal BadDebtPercent { get; } + + /// The accounts proposed as candidates for prepaid expenses (insurance, rents, leasing, subscriptions). + IReadOnlyList PrepaidCandidates { get; } +} + +/// +/// The rules of the declarations of intent (Italy: dichiarazioni d'intento of the habitual exporters, art. 8 c. 1 lett. c +/// DPR 633/72; M10). +/// +public interface IIntentRules +{ + /// The nature of the VAT codes of the sales under a declaration (Italy: N3.5). + string Nature { get; } + + /// The share of the ceiling from which the screens warn (Italy: 90%). + decimal WarningPercent { get; } + + /// Whether a protocol of the receipt is well formed (Italy: 17 digits, a dash, 6 digits). + /// The protocol. + /// when valid. + bool ValidProtocol(string? protocol); +} + /// Which statement a schema line belongs to. public enum FinancialStatementKind { - /// Balance sheet (Italy: art. 2424 c.c.). - BalanceSheet = 0, + /// Balance sheet, assets (Italy: art. 2424 c.c., attivo). + Assets = 0, + + /// Balance sheet, liabilities and equity (Italy: art. 2424 c.c., passivo). + Liabilities = 1, /// Income statement (Italy: art. 2425 c.c.). - IncomeStatement = 1, + IncomeStatement = 2, +} + +/// How much detail the statements show. +public enum FinancialStatementForm +{ + /// Ordinary (Italy: artt. 2424 and 2425 c.c.). + Ordinary = 0, + + /// Abbreviated (Italy: art. 2435-bis c.c.). + Abbreviated = 1, + + /// Micro companies (Italy: art. 2435-ter c.c.). + Micro = 2, } /// A line of the legal financial statements. @@ -148,43 +249,168 @@ public enum FinancialStatementKind /// The legal description. /// The line it adds up into, if any. /// Whether accounts can be mapped to it. -public sealed record FinancialStatementLine(string Code, string Description, string? ParentCode, bool Postable); +/// +/// Whether the line shows credit minus debit (liabilities, revenues); otherwise debit minus credit (assets, costs). +/// +/// +/// For a computed line (such as the difference A - B), the top lines whose credit-minus-debit balances it adds up. +/// +public sealed record FinancialStatementLine( + string Code, + string Description, + string? ParentCode, + bool Postable, + bool CreditNormal = false, + IReadOnlyList? Totals = null); -/// The legal schema of the financial statements (arrives with the statements, M10). -public interface IFinancialStatementsSchema +/// The reclassified statements an analyst reads. +public enum ReclassificationKind { - /// The lines of a statement, in legal order. - /// The statement. - /// The lines. - IReadOnlyList Lines(FinancialStatementKind kind); + /// Balance sheet by liquidity and maturity (criterio finanziario). + Financial = 0, + + /// Income statement by value added. + ValueAdded = 1, } -/// A line of an Intrastat return. -/// The country of the counterparty. -/// The VAT number of the counterparty, without country prefix. -/// The amount in euro. -/// The combined nomenclature code (goods) or CPA code (services). -/// The nature of the transaction. -public sealed record IntrastatLine(string CountryCode, string VatNumber, decimal Amount, string? NomenclatureCode, string? TransactionNature); +/// A line of a reclassified statement. +/// The code, one of for the lines the ratios read. +/// What it shows. +/// The statement whose lines it adds up. +/// The legal lines (and their sub-lines) it adds up. +/// For a subtotal, the reclassified lines it adds up; a leading - subtracts. +/// Whether the sum is shown as debit minus credit (assets). +/// Whether it is a subtotal shown in bold. +public sealed record ReclassifiedLine( + string Code, + string Description, + FinancialStatementKind Source, + IReadOnlyList Lines, + IReadOnlyList? Totals = null, + bool Negate = false, + bool Subtotal = false); -/// An Intrastat return of a period. -/// The form, such as INTRA-1 bis. -/// The period. -/// The lines. -public sealed record IntrastatReturn(string Form, TaxPeriod Period, IReadOnlyList Lines); +/// The codes of the reclassified lines the ratios read. +public static class ReclassifiedCodes +{ + /// Fixed assets. + public const string FixedAssets = "IMM"; -/// Writes Intrastat returns in the customs format (arrives with Intrastat, M10). + /// Inventory. + public const string Inventory = "MAG"; + + /// Receivables and other deferred liquidity. + public const string Receivables = "LIQD"; + + /// Cash and banks. + public const string Liquidity = "LIQI"; + + /// Current assets. + public const string CurrentAssets = "AC"; + + /// Total assets (capitale investito). + public const string TotalAssets = "CI"; + + /// Equity with the result of the year. + public const string Equity = "PN"; + + /// Long-term liabilities. + public const string LongTermLiabilities = "PCONS"; + + /// Current liabilities. + public const string CurrentLiabilities = "PCORR"; + + /// Trade payables. + public const string Payables = "FORN"; + + /// Revenue from sales. + public const string Revenue = "RIC"; + + /// Purchases of goods and materials. + public const string Purchases = "ACQ"; + + /// Operating result (EBIT). + public const string OperatingResult = "RO"; + + /// Result of the year. + public const string Result = "RN"; +} + +/// The legal schema of the financial statements and the reclassified statements (M10). +public interface IFinancialStatementsSchema +{ + /// The line of the liabilities that holds the result of the year (Italy: A.IX). + string ResultLine { get; } + + /// The lines of a statement, in legal order. + /// The statement. + /// Ordinary, abbreviated or micro. + /// The lines. + IReadOnlyList Lines(FinancialStatementKind kind, FinancialStatementForm form); + + /// The line of a form that an ordinary line goes into. + /// The ordinary line, as written on the account. + /// The statement. + /// The form. + /// The line of the form, or when the code is not in the schema. + string? Collapse(string code, FinancialStatementKind kind, FinancialStatementForm form); + + /// The lines of a reclassified statement. + /// Which one. + /// The lines, in order. + IReadOnlyList Reclassification(ReclassificationKind kind); +} + +/// How often a flow of Intrastat lists is due, by category. +/// For goods. +/// For services. +public sealed record IntrastatDue(Khaemhat.Core.Accounting.IntrastatPeriodicity Goods, Khaemhat.Core.Accounting.IntrastatPeriodicity Services) +{ + /// The periodicity of the list: monthly when any category is monthly. + public Khaemhat.Core.Accounting.IntrastatPeriodicity List => + Goods == Khaemhat.Core.Accounting.IntrastatPeriodicity.Monthly || Services == Khaemhat.Core.Accounting.IntrastatPeriodicity.Monthly + ? Khaemhat.Core.Accounting.IntrastatPeriodicity.Monthly + : Goods == Khaemhat.Core.Accounting.IntrastatPeriodicity.Quarterly || Services == Khaemhat.Core.Accounting.IntrastatPeriodicity.Quarterly + ? Khaemhat.Core.Accounting.IntrastatPeriodicity.Quarterly + : Khaemhat.Core.Accounting.IntrastatPeriodicity.NotDue; +} + +/// A list of a period as the exporter writes it. +/// The list. +/// The lines that go into the file. +/// The VAT number of the company, without the country. +public sealed record IntrastatReturn( + Khaemhat.Core.Accounting.IntrastatList List, + IReadOnlyList Lines, + string DeclarantVat); + +/// The Intrastat rules and the customs file (Italy: elenchi INTRA, SCAMBI.CEE; M10). public interface IIntrastatExporter { - /// The forms the exporter writes. - IReadOnlyList Forms { get; } + /// The member states of the European Union (ISO 3166 alpha-2, with GR for Greece). + IReadOnlyCollection MemberStates { get; } - /// Writes a return. - /// The return. - /// The stream to write to. - /// Cancels the write. - /// A task that completes when the file is written. - Task WriteAsync(IntrastatReturn intrastatReturn, Stream output, CancellationToken cancellationToken); + /// How often the lists are due, from the amounts of the quarters before. + /// Sales or purchases. + /// The highest goods total of the four quarters before. + /// The highest services total of the four quarters before. + /// The periodicity of goods and services. + IntrastatDue Due(Khaemhat.Core.Accounting.IntrastatFlow flow, decimal goodsQuarterMax, decimal servicesQuarterMax); + + /// Whether a combined nomenclature code is well formed (8 digits). + /// The code. + /// when valid. + bool ValidNomenclature(string? code); + + /// The name of the file of a list. + /// The list. + /// The file name. + string FileName(IntrastatReturn intrastatReturn); + + /// Writes the file of a list. + /// The list. + /// The file, ASCII with CR LF. + byte[] Write(IntrastatReturn intrastatReturn); } /// A payment method of the base data. diff --git a/src/Khaemhat.Fiscal.Italy/CeeSchemaIt.cs b/src/Khaemhat.Fiscal.Italy/CeeSchemaIt.cs new file mode 100644 index 0000000..3d64704 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/CeeSchemaIt.cs @@ -0,0 +1,258 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The schema of the Italian financial statements (SPEC §11.7, issue #86, ADR 0043): balance sheet of art. 2424 c.c., +/// income statement of art. 2425 c.c., the abbreviated form of art. 2435-bis and the micro form of art. 2435-ter (same +/// lines as the abbreviated one), and the reclassified statements by liquidity and by value added. The accounts of the +/// chart carry the ordinary line (voce_cee); the nature of the account says which statement it belongs to. +/// +public sealed class CeeSchemaIt : IFinancialStatementsSchema +{ + private static readonly IReadOnlyList AssetsOrdinary = + [ + L("A", "Crediti verso soci per versamenti ancora dovuti", null), + H("B", "Immobilizzazioni", null), + H("B.I", "Immobilizzazioni immateriali", "B"), + L("B.I.1", "Costi di impianto e di ampliamento", "B.I"), + L("B.I.2", "Costi di sviluppo", "B.I"), + L("B.I.3", "Diritti di brevetto industriale e diritti di utilizzazione delle opere dell'ingegno", "B.I"), + L("B.I.4", "Concessioni, licenze, marchi e diritti simili", "B.I"), + L("B.I.5", "Avviamento", "B.I"), + L("B.I.6", "Immobilizzazioni in corso e acconti", "B.I"), + L("B.I.7", "Altre", "B.I"), + H("B.II", "Immobilizzazioni materiali", "B"), + L("B.II.1", "Terreni e fabbricati", "B.II"), + L("B.II.2", "Impianti e macchinario", "B.II"), + L("B.II.3", "Attrezzature industriali e commerciali", "B.II"), + L("B.II.4", "Altri beni", "B.II"), + L("B.II.5", "Immobilizzazioni in corso e acconti", "B.II"), + H("B.III", "Immobilizzazioni finanziarie", "B"), + L("B.III.1", "Partecipazioni", "B.III"), + L("B.III.2", "Crediti", "B.III"), + L("B.III.3", "Altri titoli", "B.III"), + L("B.III.4", "Strumenti finanziari derivati attivi", "B.III"), + H("C", "Attivo circolante", null), + H("C.I", "Rimanenze", "C"), + L("C.I.1", "Materie prime, sussidiarie e di consumo", "C.I"), + L("C.I.2", "Prodotti in corso di lavorazione e semilavorati", "C.I"), + L("C.I.3", "Lavori in corso su ordinazione", "C.I"), + L("C.I.4", "Prodotti finiti e merci", "C.I"), + L("C.I.5", "Acconti", "C.I"), + H("C.II", "Crediti", "C"), + L("C.II.1", "Verso clienti", "C.II"), + L("C.II.2", "Verso imprese controllate", "C.II"), + L("C.II.3", "Verso imprese collegate", "C.II"), + L("C.II.4", "Verso controllanti", "C.II"), + L("C.II.5", "Verso imprese sottoposte al controllo delle controllanti", "C.II"), + L("C.II.5-bis", "Crediti tributari", "C.II"), + L("C.II.5-ter", "Imposte anticipate", "C.II"), + L("C.II.5-quater", "Verso altri", "C.II"), + H("C.III", "Attività finanziarie che non costituiscono immobilizzazioni", "C"), + L("C.III.1", "Partecipazioni in imprese controllate", "C.III"), + L("C.III.4", "Altre partecipazioni", "C.III"), + L("C.III.5", "Strumenti finanziari derivati attivi", "C.III"), + L("C.III.6", "Altri titoli", "C.III"), + H("C.IV", "Disponibilità liquide", "C"), + L("C.IV.1", "Depositi bancari e postali", "C.IV"), + L("C.IV.2", "Assegni", "C.IV"), + L("C.IV.3", "Danaro e valori in cassa", "C.IV"), + L("D", "Ratei e risconti", null), + ]; + + private static readonly IReadOnlyList LiabilitiesOrdinary = + [ + H("A", "Patrimonio netto", null, true), + L("A.I", "Capitale", "A", true), + L("A.II", "Riserva da soprapprezzo delle azioni", "A", true), + L("A.III", "Riserve di rivalutazione", "A", true), + L("A.IV", "Riserva legale", "A", true), + L("A.V", "Riserve statutarie", "A", true), + L("A.VI", "Altre riserve", "A", true), + L("A.VII", "Riserva per operazioni di copertura dei flussi finanziari attesi", "A", true), + L("A.VIII", "Utili (perdite) portati a nuovo", "A", true), + L("A.IX", "Utile (perdita) dell'esercizio", "A", true), + L("A.X", "Riserva negativa per azioni proprie in portafoglio", "A", true), + H("B", "Fondi per rischi e oneri", null, true), + L("B.1", "Per trattamento di quiescenza e obblighi simili", "B", true), + L("B.2", "Per imposte, anche differite", "B", true), + L("B.3", "Strumenti finanziari derivati passivi", "B", true), + L("B.4", "Altri", "B", true), + L("C", "Trattamento di fine rapporto di lavoro subordinato", null, true), + H("D", "Debiti", null, true), + L("D.1", "Obbligazioni", "D", true), + L("D.2", "Obbligazioni convertibili", "D", true), + L("D.3", "Debiti verso soci per finanziamenti", "D", true), + L("D.4", "Debiti verso banche", "D", true), + L("D.5", "Debiti verso altri finanziatori", "D", true), + L("D.6", "Acconti", "D", true), + L("D.7", "Debiti verso fornitori", "D", true), + L("D.8", "Debiti rappresentati da titoli di credito", "D", true), + L("D.9", "Debiti verso imprese controllate", "D", true), + L("D.10", "Debiti verso imprese collegate", "D", true), + L("D.11", "Debiti verso controllanti", "D", true), + L("D.11-bis", "Debiti verso imprese sottoposte al controllo delle controllanti", "D", true), + L("D.12", "Debiti tributari", "D", true), + L("D.13", "Debiti verso istituti di previdenza e di sicurezza sociale", "D", true), + L("D.14", "Altri debiti", "D", true), + L("E", "Ratei e risconti", null, true), + ]; + + private static readonly IReadOnlyList IncomeOrdinary = + [ + H("A", "Valore della produzione", null, true), + L("A.1", "Ricavi delle vendite e delle prestazioni", "A", true), + L("A.2", "Variazioni delle rimanenze di prodotti in corso di lavorazione, semilavorati e finiti", "A", true), + L("A.3", "Variazioni dei lavori in corso su ordinazione", "A", true), + L("A.4", "Incrementi di immobilizzazioni per lavori interni", "A", true), + L("A.5", "Altri ricavi e proventi", "A", true), + H("B", "Costi della produzione", null), + L("B.6", "Per materie prime, sussidiarie, di consumo e di merci", "B"), + L("B.7", "Per servizi", "B"), + L("B.8", "Per godimento di beni di terzi", "B"), + L("B.9", "Per il personale", "B"), + L("B.9.a", "Salari e stipendi", "B.9"), + L("B.9.b", "Oneri sociali", "B.9"), + L("B.9.c", "Trattamento di fine rapporto", "B.9"), + L("B.9.d", "Trattamento di quiescenza e simili", "B.9"), + L("B.9.e", "Altri costi", "B.9"), + L("B.10", "Ammortamenti e svalutazioni", "B"), + L("B.10.a", "Ammortamento delle immobilizzazioni immateriali", "B.10"), + L("B.10.b", "Ammortamento delle immobilizzazioni materiali", "B.10"), + L("B.10.c", "Altre svalutazioni delle immobilizzazioni", "B.10"), + L("B.10.d", "Svalutazioni dei crediti compresi nell'attivo circolante e delle disponibilità liquide", "B.10"), + L("B.11", "Variazioni delle rimanenze di materie prime, sussidiarie, di consumo e merci", "B"), + L("B.12", "Accantonamenti per rischi", "B"), + L("B.13", "Altri accantonamenti", "B"), + L("B.14", "Oneri diversi di gestione", "B"), + T("A-B", "Differenza tra valore e costi della produzione (A - B)", "A", "B"), + H("C", "Proventi e oneri finanziari", null, true), + L("C.15", "Proventi da partecipazioni", "C", true), + L("C.16", "Altri proventi finanziari", "C", true), + L("C.17", "Interessi e altri oneri finanziari", "C"), + L("C.17-bis", "Utili e perdite su cambi", "C", true), + H("D", "Rettifiche di valore di attività e passività finanziarie", null, true), + L("D.18", "Rivalutazioni", "D", true), + L("D.19", "Svalutazioni", "D"), + T("RPI", "Risultato prima delle imposte (A - B + - C + - D)", "A", "B", "C", "D"), + L("20", "Imposte sul reddito dell'esercizio, correnti, differite e anticipate", null), + T("21", "Utile (perdita) dell'esercizio", "A", "B", "C", "D", "20"), + ]; + + // Art. 2435-bis: the balance sheet shows only the letters and the roman numerals; the income statement may group + // A.2-A.3, B.9.c-e, B.10.a-c and the sub-lines of C.16, D.18 and D.19 (Khaemhat groups B.9 and B.10). + private static readonly IReadOnlyList AssetsAbbreviated = + [ + L("A", "Crediti verso soci per versamenti ancora dovuti", null), + H("B", "Immobilizzazioni", null), + L("B.I", "Immobilizzazioni immateriali", "B"), + L("B.II", "Immobilizzazioni materiali", "B"), + L("B.III", "Immobilizzazioni finanziarie", "B"), + H("C", "Attivo circolante", null), + L("C.I", "Rimanenze", "C"), + L("C.II", "Crediti", "C"), + L("C.III", "Attività finanziarie che non costituiscono immobilizzazioni", "C"), + L("C.IV", "Disponibilità liquide", "C"), + L("D", "Ratei e risconti", null), + ]; + + private static readonly IReadOnlyList LiabilitiesAbbreviated = + [ + .. LiabilitiesOrdinary.Where(l => l.Code is "A" || l.ParentCode == "A"), + L("B", "Fondi per rischi e oneri", null, true), + L("C", "Trattamento di fine rapporto di lavoro subordinato", null, true), + L("D", "Debiti", null, true), + L("E", "Ratei e risconti", null, true), + ]; + + private static readonly IReadOnlyList IncomeAbbreviated = + [ + .. IncomeOrdinary.Where(l => !(l.ParentCode is "B.9" or "B.10")), + ]; + + private static readonly IReadOnlyList Financial = + [ + new(ReclassifiedCodes.FixedAssets, "Attivo immobilizzato", FinancialStatementKind.Assets, ["B"], Negate: true), + new(ReclassifiedCodes.Inventory, "Magazzino", FinancialStatementKind.Assets, ["C.I"], Negate: true), + new(ReclassifiedCodes.Receivables, "Liquidità differite", FinancialStatementKind.Assets, ["A", "C.II", "C.III", "D"], Negate: true), + new(ReclassifiedCodes.Liquidity, "Liquidità immediate", FinancialStatementKind.Assets, ["C.IV"], Negate: true), + new(ReclassifiedCodes.CurrentAssets, "Attivo corrente", FinancialStatementKind.Assets, [], [ReclassifiedCodes.Inventory, ReclassifiedCodes.Receivables, ReclassifiedCodes.Liquidity], Subtotal: true), + new(ReclassifiedCodes.TotalAssets, "Capitale investito", FinancialStatementKind.Assets, [], [ReclassifiedCodes.FixedAssets, ReclassifiedCodes.CurrentAssets], Subtotal: true), + new(ReclassifiedCodes.Equity, "Patrimonio netto", FinancialStatementKind.Liabilities, ["A"]), + new(ReclassifiedCodes.LongTermLiabilities, "Passività consolidate", FinancialStatementKind.Liabilities, ["B", "C", "D.1", "D.2", "D.3"]), + new(ReclassifiedCodes.Payables, "Debiti verso fornitori", FinancialStatementKind.Liabilities, ["D.7"]), + new("PCALT", "Altre passività correnti", FinancialStatementKind.Liabilities, ["D.4", "D.5", "D.6", "D.8", "D.9", "D.10", "D.11", "D.11-bis", "D.12", "D.13", "D.14", "E"]), + new(ReclassifiedCodes.CurrentLiabilities, "Passività correnti", FinancialStatementKind.Liabilities, [], [ReclassifiedCodes.Payables, "PCALT"], Subtotal: true), + new("FT", "Fonti di finanziamento", FinancialStatementKind.Liabilities, [], [ReclassifiedCodes.Equity, ReclassifiedCodes.LongTermLiabilities, ReclassifiedCodes.CurrentLiabilities], Subtotal: true), + ]; + + private static readonly IReadOnlyList ValueAdded = + [ + new(ReclassifiedCodes.Revenue, "Ricavi delle vendite e delle prestazioni", FinancialStatementKind.IncomeStatement, ["A.1"]), + new("VAR", "Variazioni delle rimanenze di prodotti e lavori interni", FinancialStatementKind.IncomeStatement, ["A.2", "A.3", "A.4"]), + new("ALT", "Altri ricavi e proventi", FinancialStatementKind.IncomeStatement, ["A.5"]), + new("VP", "Valore della produzione", FinancialStatementKind.IncomeStatement, [], [ReclassifiedCodes.Revenue, "VAR", "ALT"], Subtotal: true), + new(ReclassifiedCodes.Purchases, "Consumi di materie e merci", FinancialStatementKind.IncomeStatement, ["B.6", "B.11"]), + new("SERV", "Servizi e godimento di beni di terzi", FinancialStatementKind.IncomeStatement, ["B.7", "B.8"]), + new("ODG", "Oneri diversi di gestione", FinancialStatementKind.IncomeStatement, ["B.14"]), + new("VA", "Valore aggiunto", FinancialStatementKind.IncomeStatement, [], ["VP", ReclassifiedCodes.Purchases, "SERV", "ODG"], Subtotal: true), + new("PERS", "Costo del personale", FinancialStatementKind.IncomeStatement, ["B.9"]), + new("MOL", "Margine operativo lordo (EBITDA)", FinancialStatementKind.IncomeStatement, [], ["VA", "PERS"], Subtotal: true), + new("AMM", "Ammortamenti, svalutazioni e accantonamenti", FinancialStatementKind.IncomeStatement, ["B.10", "B.12", "B.13"]), + new(ReclassifiedCodes.OperatingResult, "Risultato operativo (EBIT)", FinancialStatementKind.IncomeStatement, [], ["MOL", "AMM"], Subtotal: true), + new("FIN", "Gestione finanziaria", FinancialStatementKind.IncomeStatement, ["C"]), + new("RETT", "Rettifiche di valore", FinancialStatementKind.IncomeStatement, ["D"]), + new("RAI", "Risultato prima delle imposte", FinancialStatementKind.IncomeStatement, [], [ReclassifiedCodes.OperatingResult, "FIN", "RETT"], Subtotal: true), + new("IMP", "Imposte sul reddito", FinancialStatementKind.IncomeStatement, ["20"]), + new(ReclassifiedCodes.Result, "Risultato netto", FinancialStatementKind.IncomeStatement, [], ["RAI", "IMP"], Subtotal: true), + ]; + + /// + public string ResultLine => "A.IX"; + + /// + public IReadOnlyList Lines(FinancialStatementKind kind, FinancialStatementForm form) => + (kind, form == FinancialStatementForm.Ordinary) switch + { + (FinancialStatementKind.Assets, true) => AssetsOrdinary, + (FinancialStatementKind.Assets, false) => AssetsAbbreviated, + (FinancialStatementKind.Liabilities, true) => LiabilitiesOrdinary, + (FinancialStatementKind.Liabilities, false) => LiabilitiesAbbreviated, + (_, true) => IncomeOrdinary, + _ => IncomeAbbreviated, + }; + + /// + public string? Collapse(string code, FinancialStatementKind kind, FinancialStatementForm form) + { + ArgumentNullException.ThrowIfNull(code); + var ordinary = Lines(kind, FinancialStatementForm.Ordinary); + if (!ordinary.Any(l => l.Code == code)) + { + return null; + } + + var lines = Lines(kind, form); + var current = code; + while (current is not null && !lines.Any(l => l.Code == current)) + { + current = ordinary.First(l => l.Code == current).ParentCode; + } + + return current; + } + + /// + public IReadOnlyList Reclassification(ReclassificationKind kind) => + kind == ReclassificationKind.Financial ? Financial : ValueAdded; + + private static FinancialStatementLine L(string code, string description, string? parent, bool credit = false) => + new(code, description, parent, true, credit); + + private static FinancialStatementLine H(string code, string description, string? parent, bool credit = false) => + new(code, description, parent, false, credit); + + private static FinancialStatementLine T(string code, string description, params string[] totals) => + new(code, description, null, false, true, totals); +} diff --git a/src/Khaemhat.Fiscal.Italy/ClosingRulesIt.cs b/src/Khaemhat.Fiscal.Italy/ClosingRulesIt.cs new file mode 100644 index 0000000..0ab2c1e --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ClosingRulesIt.cs @@ -0,0 +1,58 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The Italian rules of the closing (SPEC §11.7, issues #84-#85, ADR 0043): the accounts of the model chart the closing +/// posts to, the write-down of receivables deductible up to 0.5% a year (art. 106 TUIR) and the cost accounts whose +/// invoices usually straddle the year end (insurance, rents, leasing, rentals, software, subscriptions). +/// +public sealed class ClosingRulesIt : IClosingRules +{ + /// + public YearEndAccountCodes Accounts { get; } = new( + OtherReceivables: "06.01.001", + Gains: "31.01.005", + Losses: "27.01.006", + AccruedIncome: "08.01.001", + PrepaidExpenses: "08.01.002", + AccruedExpenses: "17.01.001", + DeferredIncome: "17.01.002", + ExchangeGains: "32.01.003", + ExchangeLosses: "28.01.005", + Inventory: "04.01.001", + OpeningInventory: "25.01.001", + ClosingInventory: "25.01.002", + BadDebtCharge: "24.02.001", + BadDebtFund: "05.02.002", + SeveranceCharge: "23.01.003", + SeveranceFund: "12.01.001", + OpeningBalance: "90.01.001", + ClosingBalance: "90.01.002", + IncomeSummary: "90.01.003", + Result: "10.02.002", + Capital: "10.01.001"); + + /// + public decimal BadDebtPercent => 0.5m; + + /// + public IReadOnlyList PrepaidCandidates { get; } = ["21.03.005", "21.03.006", "22.01.001", "22.01.002", "22.01.003", "27.01.008"]; +} + +/// +/// The Italian declarations of intent (SPEC §11.7, issue #83): sales without VAT with the nature N3.5 up to the ceiling +/// declared, the protocol of the receipt of the Agenzia delle Entrate (17 digits, a dash, 6 digits), a warning from 90%. +/// +public sealed class IntentRulesIt : IIntentRules +{ + /// + public string Nature => "N3.5"; + + /// + public decimal WarningPercent => 90m; + + /// + public bool ValidProtocol(string? protocol) => + protocol is { Length: 24 } p && p[17] == '-' && p[..17].All(char.IsAsciiDigit) && p[18..].All(char.IsAsciiDigit); +} diff --git a/src/Khaemhat.Fiscal.Italy/IntrastatExporterIt.cs b/src/Khaemhat.Fiscal.Italy/IntrastatExporterIt.cs new file mode 100644 index 0000000..1c5095b --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/IntrastatExporterIt.cs @@ -0,0 +1,161 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Core.Accounting; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The Italian Intrastat lists (SPEC §11.7, issue #83, ADR 0042): the thresholds that make the lists monthly, quarterly +/// or not due (from 2022: sales 50,000 euro per quarter for each category, purchases 350,000 euro for goods and 100,000 +/// euro for services, below which the purchases are not due) and the fixed-width file SCAMBI.CEE sent through the +/// customs or the Agenzia delle Entrate. +/// +/// +/// The file follows the published layout of the records (frontispiece type 0, then 1 goods, 2 goods corrections, 3 +/// services, 4 services corrections), every record padded to characters. It has not yet been +/// checked with the control software of the customs: the STATUS says so and the user validates it before the first send. +/// +public sealed class IntrastatExporterIt : IIntrastatExporter +{ + /// The length of every record of the file. + public const int RecordLength = 140; + + /// The sales threshold per quarter and category. + public const decimal SalesThreshold = 50_000m; + + /// The goods purchases threshold per quarter. + public const decimal GoodsPurchasesThreshold = 350_000m; + + /// The services purchases threshold per quarter. + public const decimal ServicesPurchasesThreshold = 100_000m; + + private static readonly string[] Members = + [ + "AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "ES", "FI", "FR", "GR", "HR", "HU", "IE", "IT", "LT", "LU", "LV", "MT", + "NL", "PL", "PT", "RO", "SE", "SI", "SK", + ]; + + /// + public IReadOnlyCollection MemberStates => Members; + + /// + public IntrastatDue Due(IntrastatFlow flow, decimal goodsQuarterMax, decimal servicesQuarterMax) => + flow == IntrastatFlow.Sales + ? new IntrastatDue( + goodsQuarterMax >= SalesThreshold ? IntrastatPeriodicity.Monthly : IntrastatPeriodicity.Quarterly, + servicesQuarterMax >= SalesThreshold ? IntrastatPeriodicity.Monthly : IntrastatPeriodicity.Quarterly) + : new IntrastatDue( + goodsQuarterMax >= GoodsPurchasesThreshold ? IntrastatPeriodicity.Monthly : IntrastatPeriodicity.NotDue, + servicesQuarterMax >= ServicesPurchasesThreshold ? IntrastatPeriodicity.Monthly : IntrastatPeriodicity.NotDue); + + /// + public bool ValidNomenclature(string? code) => code is { Length: 8 } && code.All(char.IsAsciiDigit); + + /// + public string FileName(IntrastatReturn intrastatReturn) => "SCAMBI.CEE"; + + /// + public byte[] Write(IntrastatReturn intrastatReturn) + { + ArgumentNullException.ThrowIfNull(intrastatReturn); + var list = intrastatReturn.List; + var lines = intrastatReturn.Lines.Where(l => l.Included).ToList(); + var sales = list.Flow == IntrastatFlow.Sales; + var prefix = "EUROX" + Digits(intrastatReturn.DeclarantVat, 11) + Number(list.Progressive, 6); + + var builder = new StringBuilder(); + var head = new StringBuilder(prefix) + .Append('0').Append(Number(0, 5)) + .Append(sales ? 'C' : 'A') + .Append(Number(list.Year % 100, 2)) + .Append(list.Periodicity == IntrastatPeriodicity.Quarterly ? 'T' : 'M') + .Append(Number(list.Period, 2)) + .Append(Digits(intrastatReturn.DeclarantVat, 11)) + .Append('0') // content: ordinary list + .Append('0') // special cases: none + .Append(new string(' ', 11)); // delegated party: none + foreach (var section in Enum.GetValues()) + { + var ofSection = lines.Where(l => l.Section == section).ToList(); + head.Append(Number(ofSection.Count, 5)).Append(Amount(ofSection.Sum(l => l.Amount), 13)); + } + + AppendRecord(builder, head.ToString()); + var progressive = 0; + foreach (var line in lines.OrderBy(l => l.Section).ThenBy(l => l.Id)) + { + progressive++; + var record = new StringBuilder(prefix) + .Append(((int)line.Section + 1).ToString(CultureInfo.InvariantCulture)) + .Append(Number(progressive, 5)); + switch (line.Section) + { + case IntrastatSection.Goods: + record.Append(Text(line.CountryCode, 2)).Append(Text(line.VatNumber, 12)).Append(Amount(line.Amount, 13)); + if (!sales) + { + record.Append(Amount(line.CurrencyAmount ?? 0m, 13)); + } + + record.Append(Text(line.TransactionNature, 2)).Append(Text(line.NomenclatureCode, 8)) + .Append(Amount(line.NetMass ?? 0m, 10)).Append(Amount(line.SupplementaryUnits ?? 0m, 10)) + .Append(Amount(line.StatisticalValue ?? line.Amount, 13)).Append(Text(line.DeliveryTerms, 1)) + .Append(Text(line.TransportMode, 1)).Append(Text(sales ? line.CountryCode : line.OriginCountry, 2)) + .Append(Text(line.Province, 2)); + break; + case IntrastatSection.GoodsCorrection: + case IntrastatSection.ServicesCorrection: + record.Append(Number(line.CorrectedPeriod ?? 0, 2)).Append(Number((line.CorrectedYear ?? 0) % 100, 2)) + .Append(Text(line.CountryCode, 2)).Append(Text(line.VatNumber, 12)) + .Append(Text(line.CorrectionSign ?? "+", 1)).Append(Amount(line.Amount, 13)) + .Append(Text(line.NomenclatureCode, 8)); + break; + default: + record.Append(Text(line.CountryCode, 2)).Append(Text(line.VatNumber, 12)).Append(Amount(line.Amount, 13)); + if (!sales) + { + record.Append(Amount(line.CurrencyAmount ?? 0m, 13)); + } + + record.Append(Text(line.DocumentNumber, 15)) + .Append(line.DocumentDate is { } date ? date.ToString("ddMMyy", CultureInfo.InvariantCulture) : "000000") + .Append(Text(line.NomenclatureCode, 6)).Append(Text(line.SupplyMode, 1)) + .Append(Text(line.PaymentMode, 1)).Append(Text(line.PaymentCountry ?? line.CountryCode, 2)); + break; + } + + AppendRecord(builder, record.ToString()); + } + + return Encoding.ASCII.GetBytes(builder.ToString()); + } + + private static void AppendRecord(StringBuilder builder, string record) + { + if (record.Length > RecordLength) + { + throw new InvalidOperationException("Intrastat record longer than " + RecordLength.ToString(CultureInfo.InvariantCulture) + "."); + } + + builder.Append(record.PadRight(RecordLength)).Append("\r\n"); + } + + private static string Number(int value, int length) => + Math.Abs(value).ToString(CultureInfo.InvariantCulture).PadLeft(length, '0')[^length..]; + + private static string Amount(decimal value, int length) => + ((long)Math.Round(Math.Abs(value), 0, MidpointRounding.AwayFromZero)).ToString(CultureInfo.InvariantCulture).PadLeft(length, '0')[^length..]; + + private static string Digits(string? value, int length) + { + var digits = new string((value ?? string.Empty).Where(char.IsAsciiDigit).ToArray()); + return digits.PadLeft(length, '0')[^length..]; + } + + private static string Text(string? value, int length) + { + var ascii = new string((value ?? string.Empty).Trim().ToUpperInvariant().Select(c => c is >= ' ' and <= '~' ? c : ' ').ToArray()); + return ascii.Length >= length ? ascii[..length] : ascii.PadRight(length); + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs index 3b055d1..d4bebdd 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs @@ -63,11 +63,14 @@ public sealed class WithholdingRulesIt : IWithholdingRules } } -/// Italian depreciation rules (DM 31/12/1988 coefficients arrive with the asset register, M10). +/// Italian depreciation rules: half rate in the first year, low value goods, DM 31/12/1988 coefficients. public sealed class FixedAssetRulesIt : IFixedAssetRules { private readonly ItalianTaxEngine _engine = new(); + /// + public IReadOnlyList Coefficients => MinisterialCoefficients.All; + /// public decimal FirstYearFactor => 0.5m; diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 1d823b9..f70004a 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -36,6 +36,10 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new LipeWriter()); AddFeature(new RibaCbiWriter()); AddFeature(new CbiStatementReader()); + AddFeature(new CeeSchemaIt()); + AddFeature(new IntrastatExporterIt()); + AddFeature(new ClosingRulesIt()); + AddFeature(new IntentRulesIt()); // 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/MinisterialCoefficients.cs b/src/Khaemhat.Fiscal.Italy/MinisterialCoefficients.cs new file mode 100644 index 0000000..5f115dd --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/MinisterialCoefficients.cs @@ -0,0 +1,34 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The depreciation coefficients the asset categories start from (SPEC §11.7, issue #82): the tangible assets use the +/// common coefficients of the table attached to the DM 31/12/1988 (the same in most groups for general assets), the +/// intangible ones the limits of art. 103 TUIR. The company can change every rate on its own categories, since the table +/// depends on the sector of activity. +/// +public static class MinisterialCoefficients +{ + private const string Decree = "DM 31/12/1988"; + private const string Tuir = "Art. 103 TUIR"; + + /// The coefficients, intangible first. + public static IReadOnlyList All { get; } = + [ + new("IMP", "Costi di impianto e di ampliamento", "Art. 108 TUIR", 20m, true, "01.01.001", "09.01.001", "24.01.001"), + new("SVI", "Costi di sviluppo", "Art. 108 TUIR", 20m, true, "01.01.002", "09.01.001", "24.01.001"), + new("SW", "Software e diritti di utilizzazione delle opere dell'ingegno", Tuir, 50m, true, "01.01.003", "09.01.001", "24.01.001"), + new("MAR", "Marchi e brevetti", Tuir, 5.56m, true, "01.01.004", "09.01.001", "24.01.001"), + new("AVV", "Avviamento", Tuir, 5.56m, true, "01.01.005", "09.01.001", "24.01.001"), + new("FAB", "Fabbricati strumentali", Decree, 3m, false, "02.01.002", "09.02.001", "24.01.002"), + new("IMG", "Impianti generici", Decree, 10m, false, "02.02.001", "09.02.002", "24.01.002"), + new("MAC", "Macchinari e impianti specifici", Decree, 15m, false, "02.02.002", "09.02.002", "24.01.002"), + new("ATT", "Attrezzature industriali e commerciali", Decree, 15m, false, "02.03.001", "09.02.003", "24.01.002"), + new("MOB", "Mobili e arredi d'ufficio", Decree, 12m, false, "02.04.001", "09.02.004", "24.01.002"), + new("EDP", "Macchine d'ufficio elettroniche e computer", Decree, 20m, false, "02.04.002", "09.02.005", "24.01.002"), + new("AUV", "Autovetture", Decree, 25m, false, "02.04.003", "09.02.006", "24.01.002", 18_075.99m, 20m), + new("AUC", "Autocarri e mezzi di trasporto", Decree, 20m, false, "02.04.004", "09.02.006", "24.01.002"), + new("BMV", "Beni di costo unitario non superiore a 516,46 euro", "Art. 102 c. 5 TUIR", 100m, false, "02.04.005", "09.02.004", "24.01.002"), + ]; +} diff --git a/src/Khaemhat.Web/Components/Pages/Assets/AssetsPage.razor b/src/Khaemhat.Web/Components/Pages/Assets/AssetsPage.razor new file mode 100644 index 0000000..d23e803 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Assets/AssetsPage.razor @@ -0,0 +1,476 @@ +@page "/cespiti" +@page "/cespiti/registro" +@attribute [Authorize] +@using Khaemhat.Application.Ledger +@using Khaemhat.Application.Modules +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Core.Accounting +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd +@using Khaemhat.Web.Components.Pages.Ledger +@inject ShellSession Session +@inject FixedAssetService AssetService +@inject PartyService Parties +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The register of the depreciable assets (SPEC §11.7, issue #82, mockup 048): the assets with their category, ministerial + rate, cost, fund and net value; the plan of the selected asset year by year, civil and fiscal; a new asset, its + disposal and the print of the register (libro cespiti). *@ + + + +
+
+
@T["Shell.Menu.Assets"] / @T["Shell.Menu.Assets.Register"]
+

@T["YearEnd.Assets.Heading"]

+
@T["YearEnd.Assets.Hint"]
+
+
+
+ @if (CanWrite) + { + + } + @T.Format("YearEnd.Assets.Depreciate", _year) + +
+
+ + @if (_categories.Count == 0 && _loaded) + { +
+ + @T["YearEnd.Assets.NoCategories"] + @T["Shell.Menu.Assets.Categories"] +
+ } + + + + +
+ + + + +
+ @if (_rows.Count == 0) + { +

@T["YearEnd.Assets.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var a = row.Asset; + + + + + + + + + + + + } + + + + + + + + + + +
@T["YearEnd.Fields.Code"]@T["YearEnd.Fields.Description"]@T["YearEnd.Fields.Category"]@T["YearEnd.Fields.Rate"]@T["YearEnd.Fields.InService"]@T["YearEnd.Fields.Cost"]@T["YearEnd.Fields.Fund"]@T["YearEnd.Fields.NetValue"]@T["YearEnd.Fields.Status"]
@a.Code@a.Description@row.Category.Description@YearEndScreens.Percent(T, a.CivilRate ?? row.Category.CivilRate)@T.Date(a.InServiceDate)@T.Money(a.Cost)@T.Money(a.CivilFund)@T.Money(a.Cost - a.CivilFund)@T[YearEndScreens.EnumKey(a.Status)]
@T.Format("YearEnd.Assets.Count", _rows.Count)@T.Money(_rows.Sum(r => r.Asset.Cost))@T.Money(_rows.Sum(r => r.Asset.CivilFund))@T.Money(_rows.Sum(r => r.Asset.Cost - r.Asset.CivilFund))
+
+ } +
+ + @if (_selected is { } view) + { +
+ + + + + + + + + + + + + + + @foreach (var y in view.CivilPlan) + { + var fiscal = view.FiscalPlan.FirstOrDefault(f => f.Year == y.Year); + + + + + + + + + + } + +
@T["YearEnd.Fields.Year"]@T["YearEnd.Fields.FundOpening"]@T["YearEnd.Fields.Rate"]@T["YearEnd.Assets.Civil"]@T["YearEnd.Assets.Fiscal"]@T["YearEnd.Fields.Fund"]@T["YearEnd.Fields.NetValue"]
@y.Year@T.Money(y.Opening)@YearEndScreens.Percent(T, y.Rate)@T.Money(y.Amount)@(fiscal is null ? null : T.Money(fiscal.Amount))@T.Money(y.Closing)@T.Money(y.NetValue)
+
+ +
+
@T["YearEnd.Fields.Category"]
@view.Category.Code · @view.Category.Description
+
@T["YearEnd.Fields.PurchaseDate"]
@T.Date(view.Asset.PurchaseDate)
+
@T["YearEnd.Fields.Supplier"]
@(view.SupplierName ?? "-")
+
@T["YearEnd.Fields.Document"]
@(view.Asset.DocumentReference ?? "-")
+
@T["YearEnd.Fields.Location"]
@(view.Asset.Location ?? "-")
+
@T["YearEnd.Fields.FiscalFund"]
@T.Money(view.Asset.FiscalFund)
+
@T["YearEnd.Fields.LastDepreciation"]
@(view.Asset.LastDepreciationYear?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-")
+
+ @if (view.Movements.Count > 0) + { +

@T["YearEnd.Assets.Movements"]

+
    + @foreach (var m in view.Movements) + { +
  • @T.Date(m.MovementDate) · @T[YearEndScreens.EnumKey(m.Kind)] · @T.Money(m.CostAmount != 0m ? m.CostAmount : m.CivilAmount)
  • + } +
+ } + @if (CanWrite && view.Asset.Status != AssetStatus.Disposed) + { +
+ + + +
+ } +
+
+ } + + + +
+ + + + + + + + + + + + + + + + + +
+
+
+ + +
+
+ + + +

@T["YearEnd.Assets.DisposeText"]

+
+ + + +
+
+
+ + +
+
+
+ +@code { + private bool _loaded; + private bool _busy; + private int _year; + private string? _text; + private long? _category; + private AssetStatus? _status; + private IReadOnlyList _categories = []; + private IReadOnlyList _rows = []; + private AssetView? _selected; + private bool _editOpen; + private AssetForm _form = new(); + private PartyRow? _supplier; + private bool _disposeOpen; + private DateOnly? _disposeDate; + private decimal? _proceeds; + private decimal? _costDisposed; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanWrite => Session.Permissions.Allows(YearEndPermissions.AssetWrite); + + private IReadOnlyList> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList> CategoryChoices => [.. _categories.Select(c => new KhOption(c.Id, c.Code + " · " + c.Description + " (" + YearEndScreens.Percent(T, c.CivilRate) + ")"))]; + + private IReadOnlyList> StatusChoices => [.. Enum.GetValues().Select(s => new KhOption(s, T[YearEndScreens.EnumKey(s)]))]; + + private IReadOnlyList Stats => + [ + new(T["YearEnd.Assets.Active"], T.Number(_rows.Count(r => r.Asset.Status == AssetStatus.Active))), + new(T["YearEnd.Fields.Cost"], T.Money(_rows.Sum(r => r.Asset.Cost))), + new(T["YearEnd.Fields.Fund"], T.Money(_rows.Sum(r => r.Asset.CivilFund))), + new(T["YearEnd.Fields.NetValue"], T.Money(_rows.Sum(r => r.Asset.Cost - r.Asset.CivilFund)), KhTone.Info), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _year = Today.Year; + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(YearEndPermissions.AssetRead) + && Session.Licenses.IsModuleActive(ModuleCodes.Assets)) + { + _categories = await AssetService.CategoriesAsync(actor, company); + await LoadAsync(); + } + + _loaded = true; + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _rows = await AssetService.ListAsync(actor, company, _text, _category, _status); + if (_selected is { } selected) + { + _selected = await AssetService.GetAsync(actor, company, selected.Asset.Id); + } + } + + private async Task SetTextAsync(string? text) + { + _text = text; + await LoadAsync(); + } + + private Task SetYearAsync(int year) + { + _year = year; + return Task.CompletedTask; + } + + private async Task SetCategoryAsync(long? category) + { + _category = category; + await LoadAsync(); + } + + private async Task SetStatusAsync(AssetStatus? status) + { + _status = status; + await LoadAsync(); + } + + private async Task SelectAsync(long id) + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _selected = await AssetService.GetAsync(actor, company, id); + } + } + + private async Task> SearchSuppliersAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken) + : []; + + private void NewAsset() + { + _form = new AssetForm { PurchaseDate = Today, InServiceDate = Today, Quantity = 1m }; + _supplier = null; + _editOpen = true; + } + + private void Edit(AssetView view) + { + var a = view.Asset; + _form = new AssetForm + { + Id = a.Id, + Code = a.Code, + Description = a.Description, + CategoryId = a.CategoryId, + PurchaseDate = a.PurchaseDate, + InServiceDate = a.InServiceDate, + Cost = a.Cost, + Quantity = a.Quantity, + DocumentReference = a.DocumentReference, + Location = a.Location, + SerialNumber = a.SerialNumber, + CivilRate = a.CivilRate, + FiscalRate = a.FiscalRate, + ResidualValue = a.ResidualValue, + LastYear = a.LastDepreciationYear, + SupplierId = a.SupplierId, + }; + _supplier = null; + _editOpen = true; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + var input = new AssetInput(_form.Id, _form.Code, _form.Description ?? string.Empty, _form.CategoryId ?? 0, _form.PurchaseDate ?? Today, _form.InServiceDate ?? Today, _form.Cost ?? 0m) + { + SupplierId = _supplier?.Id ?? _form.SupplierId, + DocumentReference = _form.DocumentReference, + Location = _form.Location, + SerialNumber = _form.SerialNumber, + Quantity = _form.Quantity ?? 1m, + CivilRate = _form.CivilRate, + FiscalRate = _form.FiscalRate, + ResidualValue = _form.ResidualValue ?? 0m, + LastDepreciationYear = _form.LastYear is { } y ? (int)y : null, + OpeningCivilFund = _form.OpeningCivilFund ?? 0m, + OpeningFiscalFund = _form.OpeningFiscalFund ?? 0m, + }; + _selected = await AssetService.SaveAsync(actor, company, input); + _editOpen = false; + Toasts.Show(ToastKind.Success, T["Ledger.Saved"], _selected.Asset.Code); + await LoadAsync(); + }); + + private void OpenDisposal() + { + _disposeDate = Today; + _proceeds = null; + _costDisposed = null; + _disposeOpen = true; + } + + private async Task DisposeAsync() => await RunAsync(async (actor, company) => + { + if (_selected is not { } view || _disposeDate is not { } date) + { + return; + } + + _selected = await AssetService.DisposeAsync(actor, company, view.Asset.Id, new DisposalInput(date, _proceeds ?? 0m, _costDisposed)); + _disposeOpen = false; + Toasts.Show(ToastKind.Success, T["YearEnd.Assets.Disposed"], view.Asset.Code); + await LoadAsync(); + }); + + private async Task DeleteAsync() => await RunAsync(async (actor, company) => + { + if (_selected is not { } view) + { + return; + } + + await AssetService.DeleteAsync(actor, company, view.Asset.Id); + _selected = null; + await LoadAsync(); + }); + + private async Task PrintAsync() => await RunAsync(async (actor, company) => + await LedgerScreens.DownloadAsync(JS, await AssetService.PrintRegisterAsync(actor, company, _year))); + + 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"], YearEndScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } + + private sealed class AssetForm + { + public long? Id { get; set; } + + public string? Code { get; set; } + + public string? Description { get; set; } + + public long? CategoryId { get; set; } + + public DateOnly? PurchaseDate { get; set; } + + public DateOnly? InServiceDate { get; set; } + + public decimal? Cost { get; set; } + + public decimal? Quantity { get; set; } + + public string? DocumentReference { get; set; } + + public string? Location { get; set; } + + public string? SerialNumber { get; set; } + + public decimal? CivilRate { get; set; } + + public decimal? FiscalRate { get; set; } + + public decimal? ResidualValue { get; set; } + + public decimal? LastYear { get; set; } + + public decimal? OpeningCivilFund { get; set; } + + public decimal? OpeningFiscalFund { get; set; } + + public long? SupplierId { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Assets/CategoriesPage.razor b/src/Khaemhat.Web/Components/Pages/Assets/CategoriesPage.razor new file mode 100644 index 0000000..62ef65f --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Assets/CategoriesPage.razor @@ -0,0 +1,223 @@ +@page "/cespiti/categorie" +@attribute [Authorize] +@using Khaemhat.Application.Ledger +@using Khaemhat.Application.Modules +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Core.Accounting +@using Khaemhat.Web.YearEnd +@using Khaemhat.Web.Components.Pages.Ledger +@inject ShellSession Session +@inject FixedAssetService AssetService +@inject LedgerService Ledger +@inject ToastService Toasts + +@* The categories of the fixed assets (SPEC §11.7, issue #82): the ministerial rates (DM 31/12/1988) and the accounts of + the asset, of the fund and of the depreciation; the standard categories of the fiscal pack with one click. *@ + + + +
+
+
@T["Shell.Menu.Assets"] / @T["Shell.Menu.Assets.Categories"]
+

@T["YearEnd.Categories.Heading"]

+
@T["YearEnd.Categories.Hint"]
+
+
+ @if (CanWrite) + { +
+ + +
+ } +
+ + + @if (_categories.Count == 0) + { +

@T["YearEnd.Categories.None"]

+ } + else + { + + + + + + + + + + + + + + + @foreach (var c in _categories) + { + + + + + + + + + + + } + +
@T["YearEnd.Fields.Code"]@T["YearEnd.Fields.Description"]@T["YearEnd.Fields.Class"]@T["YearEnd.Fields.CivilRate"]@T["YearEnd.Fields.FiscalRate"]@T["YearEnd.Fields.AssetAccount"]@T["YearEnd.Fields.FundAccount"]@T["YearEnd.Fields.DepreciationAccount"]
@c.Code@c.Description@T[YearEndScreens.EnumKey(c.Class)]@YearEndScreens.Percent(T, c.CivilRate)@YearEndScreens.Percent(T, c.FiscalRate)@AccountCode(c.AssetAccountId)@AccountCode(c.FundAccountId)@AccountCode(c.DepreciationAccountId)
+ } +
+ + + +
+ + + + + + + + + + + +
+
+
+ + +
+
+
+ +@code { + private bool _busy; + private bool _open; + private IReadOnlyList _categories = []; + private IReadOnlyList _accounts = []; + private FixedAssetCategory _form = new(); + private decimal? _civilRate; + private decimal? _fiscalRate; + private decimal? _costLimit; + private decimal? _deductible; + + private bool CanWrite => Session.Permissions.Allows(YearEndPermissions.AssetWrite); + + private IReadOnlyList> AssetAccounts => [.. _accounts.Where(a => a.Postable && a.Nature == AccountNature.Asset).Select(a => new KhOption(a.Id, a.Code + " · " + a.Description))]; + + private IReadOnlyList> CostAccounts => [.. _accounts.Where(a => a.Postable && a.Nature == AccountNature.Cost).Select(a => new KhOption(a.Id, a.Code + " · " + a.Description))]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(YearEndPermissions.AssetRead) + && Session.Licenses.IsModuleActive(ModuleCodes.Assets)) + { + try + { + _accounts = await Ledger.AccountsAsync(actor, company); + } + catch (AccessDeniedException) + { + _accounts = []; + } + + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _categories = await AssetService.CategoriesAsync(actor, company); + } + } + + private string? AccountCode(long? id) => id is { } a ? _accounts.FirstOrDefault(x => x.Id == a)?.Code : null; + + private void New() + { + _form = new FixedAssetCategory { CivilHalfFirstYear = true, DeductiblePercent = 100m }; + Load(); + _open = true; + } + + private void Edit(FixedAssetCategory category) + { + _form = new FixedAssetCategory + { + Id = category.Id, + Code = category.Code, + Description = category.Description, + Class = category.Class, + MinisterialGroup = category.MinisterialGroup, + CivilRate = category.CivilRate, + FiscalRate = category.FiscalRate, + CivilHalfFirstYear = category.CivilHalfFirstYear, + AssetAccountId = category.AssetAccountId, + FundAccountId = category.FundAccountId, + DepreciationAccountId = category.DepreciationAccountId, + DeductiblePercent = category.DeductiblePercent, + CostLimit = category.CostLimit, + RowVersion = category.RowVersion, + }; + Load(); + _open = true; + } + + private void Load() + { + _civilRate = _form.Id == 0 ? null : _form.CivilRate; + _fiscalRate = _form.Id == 0 ? null : _form.FiscalRate; + _costLimit = _form.CostLimit; + _deductible = _form.DeductiblePercent; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + _form.CivilRate = _civilRate ?? 0m; + _form.FiscalRate = _fiscalRate ?? _form.CivilRate; + _form.CostLimit = _costLimit; + _form.DeductiblePercent = _deductible ?? 100m; + await AssetService.SaveCategoryAsync(actor, company, _form); + _open = false; + Toasts.Show(ToastKind.Success, T["Ledger.Saved"], _form.Code); + await LoadAsync(); + }); + + private async Task StandardAsync() => await RunAsync(async (actor, company) => + { + var added = await AssetService.CreateStandardCategoriesAsync(actor, company); + Toasts.Show(ToastKind.Success, T.Format("YearEnd.Categories.Added", added)); + await LoadAsync(); + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], YearEndScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Assets/DepreciationPage.razor b/src/Khaemhat.Web/Components/Pages/Assets/DepreciationPage.razor new file mode 100644 index 0000000..6b1c300 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Assets/DepreciationPage.razor @@ -0,0 +1,186 @@ +@page "/cespiti/ammortamenti" +@attribute [Authorize] +@using Khaemhat.Application.Modules +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd +@using Khaemhat.Web.Components.Pages.Ledger +@inject ShellSession Session +@inject FixedAssetService AssetService +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The depreciation of a year (SPEC §11.7, issue #82): the civil and fiscal share of every asset, the difference between + them, the entry by category on the last day of the year and its undo while not final. The closing (step 2) posts + the same entry when it was not posted here. *@ + + + +
+
+
@T["Shell.Menu.Assets"] / @T["Shell.Menu.Assets.Depreciation"]
+

@T.Format("YearEnd.Depreciation.Heading", _year)

+
@T["YearEnd.Depreciation.Hint"]
+
+
+
+ @if (CanPost) + { + + + } + +
+
+ +
+ +
+ + + + + @if (_lines.Count == 0) + { +

@T["YearEnd.Depreciation.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + @foreach (var l in _lines) + { + + + + + + + + + + + + + + } + + + + + + + + + + + +
@T["YearEnd.Fields.Code"]@T["YearEnd.Fields.Description"]@T["YearEnd.Fields.Category"]@T["YearEnd.Fields.Cost"]@T["YearEnd.Fields.Fund"]@T["YearEnd.Fields.CivilRate"]@T["YearEnd.Assets.Civil"]@T["YearEnd.Fields.FiscalRate"]@T["YearEnd.Assets.Fiscal"]@T["YearEnd.Depreciation.Difference"]@T["YearEnd.Fields.Status"]
@l.Code@l.Description@l.CategoryCode@T.Money(l.Cost)@T.Money(l.CivilFund)@YearEndScreens.Percent(T, l.CivilRate)@T.Money(l.Civil)@YearEndScreens.Percent(T, l.FiscalRate)@T.Money(l.Fiscal)@(l.Difference == 0m ? null : T.Money(l.Difference))@T[l.Posted ? "YearEnd.Depreciation.Posted" : "YearEnd.Depreciation.ToPost"]
@T["Ledger.Balance.Totals"]@T.Money(_lines.Sum(l => l.Civil))@T.Money(_lines.Sum(l => l.Fiscal))@T.Money(_lines.Sum(l => l.Difference))
+
+ } +
@T["YearEnd.Depreciation.Footer"]
+
+
+ +@code { + private int _year; + private bool _busy; + private IReadOnlyList _lines = []; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanPost => Session.Permissions.Allows(YearEndPermissions.DepreciationPost); + + private IReadOnlyList> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList Stats => + [ + new(T["YearEnd.Depreciation.Assets"], T.Number(_lines.Count)), + new(T["YearEnd.Assets.Civil"], T.Money(_lines.Sum(l => l.Civil))), + new(T["YearEnd.Assets.Fiscal"], T.Money(_lines.Sum(l => l.Fiscal))), + new(T["YearEnd.Depreciation.Difference"], T.Money(_lines.Sum(l => l.Difference)), _lines.Sum(l => l.Difference) == 0m ? KhTone.Neutral : KhTone.Warning), + new(T["YearEnd.Fields.Status"], T[_lines.Count > 0 && _lines.All(l => l.Posted) ? "YearEnd.Depreciation.Posted" : "YearEnd.Depreciation.ToPost"], + _lines.Count > 0 && _lines.All(l => l.Posted) ? KhTone.Ok : KhTone.Info), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _year = Today.Year; + if (Session.Actor is { } && Session.Company is { } && Session.Permissions.Allows(YearEndPermissions.AssetRead) && Session.Licenses.IsModuleActive(ModuleCodes.Assets)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _lines = await AssetService.DepreciationAsync(actor, company, _year); + } + } + + private async Task SetYearAsync(int year) + { + _year = year; + await LoadAsync(); + } + + private async Task PostAsync() => await RunAsync(async (actor, company) => + { + var amount = await AssetService.PostDepreciationAsync(actor, company, _year); + Toasts.Show(ToastKind.Success, T["YearEnd.Depreciation.PostedToast"], T.Money(amount)); + await LoadAsync(); + }); + + private async Task UndoAsync() => await RunAsync(async (actor, company) => + { + await AssetService.UndoDepreciationAsync(actor, company, _year); + await LoadAsync(); + }); + + private async Task PrintAsync() => await RunAsync(async (actor, company) => + await LedgerScreens.DownloadAsync(JS, await AssetService.PrintRegisterAsync(actor, company, _year))); + + 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"], YearEndScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/IntentDeclarationsPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/IntentDeclarationsPage.razor new file mode 100644 index 0000000..db04492 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/IntentDeclarationsPage.razor @@ -0,0 +1,297 @@ +@page "/fatturazione-elettronica/dichiarazioni-intento" +@page "/vendite/dichiarazioni-intento" +@attribute [Authorize] +@using Khaemhat.Application.Modules +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Core.Parties +@using Khaemhat.Web.Components.Pages.Ledger +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd +@inject ShellSession Session +@inject IntentDeclarationService Intents +@inject PartyService Parties +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The declarations of intent of the habitual exporters (SPEC §11.7, issue #83, mockup 061): received from customers + (our sales without VAT, nature N3.5, up to the ceiling) or issued to suppliers; the ceiling used by the invoices, + a warning from 90% and the block at 100% when the invoice is confirmed; the register in order of receipt. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["Shell.Menu.EInvoicing.IntentDeclarations"]
+

@T[_direction == IntentDirection.Received ? "YearEnd.Intent.HeadingReceived" : "YearEnd.Intent.HeadingIssued"]

+
@T["YearEnd.Intent.Hint"]
+
+
+
+ @if (CanWrite) + { + + } + + +
+
+ +
+ +
+ + + @if (_rows.Count == 0) + { +

@T["YearEnd.Intent.None"]

+ } + else + { + + + + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var d = row.Declaration; + + + + + + + + + + + + + } + +
@T["YearEnd.Intent.Number"]@T["YearEnd.Fields.Date"]@T[_direction == IntentDirection.Received ? "YearEnd.Intent.Customer" : "YearEnd.Intent.Supplier"]@T["YearEnd.Fields.Code"]@T["YearEnd.Intent.Protocol"]@T["YearEnd.Intent.Ceiling"]@T["YearEnd.Intent.Used"]@T["YearEnd.Intent.Remaining"]@T["YearEnd.Fields.Year"]@T["YearEnd.Fields.Status"]
@d.Number@T.Date(d.DeclarationDate)@row.PartyName@row.PartyCode@d.Protocol@T.Money(d.Ceiling)@T.Money(d.Used)@T.Money(d.Remaining)@d.Year@StatusText(row)
+ } +
@T["YearEnd.Intent.Footer"]
+
+ + + +
+ @if (_form.Id is null) + { + + } + else + { + + } + + + + + + + @if (_direction == IntentDirection.Issued) + { + + } + +
+
+
+ @if (_form.Id is { } && CanWrite) + { + + + } + + +
+
+
+ +@code { + private bool _busy; + private IntentDirection _direction = IntentDirection.Received; + private int? _year; + private IReadOnlyList _rows = []; + private bool _open; + private IntentForm _form = new(); + private PartyRow? _party; + private string? _partyName; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanWrite => Session.Permissions.Allows(YearEndPermissions.IntentWrite); + + private IReadOnlyList DirectionTabs => + [ + new(nameof(IntentDirection.Received), "download", T["YearEnd.Intent.Received"]), + new(nameof(IntentDirection.Issued), "upload", T["YearEnd.Intent.Issued"]), + ]; + + private IReadOnlyList> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private string StatusText(IntentRow row) => row.Declaration.Status switch + { + IntentStatus.Active when row.Warning => T.Format("YearEnd.Intent.AtWarning", row.Declaration.UsedPercent), + IntentStatus.Active => T.Format("YearEnd.Intent.ActivePercent", row.Declaration.UsedPercent), + _ => T[YearEndScreens.EnumKey(row.Declaration.Status)], + }; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _year = Today.Year; + if (Session.Actor is { } && Session.Company is { } && Session.Permissions.Allows(YearEndPermissions.IntentRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _rows = await Intents.ListAsync(actor, company, _direction, _year); + } + } + + private async Task SetDirectionAsync(string id) + { + _direction = Enum.Parse(id); + await LoadAsync(); + } + + private async Task SetYearAsync(int? year) + { + _year = year; + await LoadAsync(); + } + + private async Task> SearchPartiesAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, _direction == IntentDirection.Received ? PartyArchive.Customers : PartyArchive.Suppliers, text, cancellationToken) + : []; + + private void New() + { + _form = new IntentForm { DeclarationDate = Today, ValidFrom = new DateOnly(Today.Year, 1, 1), ValidTo = new DateOnly(Today.Year, 12, 31) }; + _party = null; + _open = true; + } + + private void Edit(IntentRow row) + { + var d = row.Declaration; + _form = new IntentForm + { + Id = d.Id, PartyId = d.PartyId, Number = d.Number, DeclarationDate = d.DeclarationDate, Protocol = d.Protocol, Ceiling = d.Ceiling, + ValidFrom = d.ValidFrom, ValidTo = d.ValidTo, Used = d.Used, Notes = d.Notes, TaxCodeId = d.TaxCodeId, + }; + _partyName = row.PartyCode + " · " + row.PartyName; + _open = true; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + var input = new IntentInput( + _form.Id, _direction, _party?.Id ?? _form.PartyId ?? 0, _form.Number ?? string.Empty, _form.DeclarationDate ?? Today, _form.Protocol ?? string.Empty, + _form.Ceiling ?? 0m, _form.ValidFrom ?? Today, _form.ValidTo ?? Today) + { + Notes = _form.Notes, + Used = _form.Used ?? 0m, + TaxCodeId = _form.TaxCodeId, + }; + var saved = await Intents.SaveAsync(actor, company, input); + _open = false; + Toasts.Show(ToastKind.Success, T["Ledger.Saved"], saved.Number); + await LoadAsync(); + }); + + private async Task RevokeAsync() => await RunAsync(async (actor, company) => + { + if (_form.Id is { } id) + { + await Intents.RevokeAsync(actor, company, id); + _open = false; + await LoadAsync(); + } + }); + + private async Task DeleteAsync() => await RunAsync(async (actor, company) => + { + if (_form.Id is { } id) + { + await Intents.DeleteAsync(actor, company, id); + _open = false; + await LoadAsync(); + } + }); + + private async Task PrintAsync() => await RunAsync(async (actor, company) => + await LedgerScreens.DownloadAsync(JS, await Intents.PrintRegisterAsync(actor, company, _direction, _year ?? Today.Year))); + + 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"], YearEndScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } + + private sealed class IntentForm + { + public long? Id { get; set; } + + public long? PartyId { get; set; } + + public string? Number { get; set; } + + public DateOnly? DeclarationDate { get; set; } + + public string? Protocol { get; set; } + + public decimal? Ceiling { get; set; } + + public DateOnly? ValidFrom { get; set; } + + public DateOnly? ValidTo { get; set; } + + public decimal? Used { get; set; } + + public string? Notes { get; set; } + + public long? TaxCodeId { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/IntrastatPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/IntrastatPage.razor new file mode 100644 index 0000000..b2d91dd --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/IntrastatPage.razor @@ -0,0 +1,401 @@ +@page "/fatturazione-elettronica/intrastat" +@attribute [Authorize] +@using Khaemhat.Application.Modules +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Core.Accounting +@using Khaemhat.Web.Components.Pages.Ledger +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd +@inject ShellSession Session +@inject IntrastatService Intrastat +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The Intrastat lists (SPEC §11.7, issue #83, mockup 049): the periodicity from the thresholds of the four quarters + before, the list of a month or quarter generated from the invoices with the parties of the other member states + (nomenclature from the item, net mass from its weight times the quantity), the checks of every line, the lines typed + by hand, the file SCAMBI.CEE for the customs and the protocol once sent. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["Shell.Menu.EInvoicing.Intrastat"]
+

@T["YearEnd.Intrastat.Heading"]

+
@T["YearEnd.Intrastat.Hint"]
+
+
+ + + +
+ + + + + +
+
+ @if (CanWrite) + { + + + } + @if (CanExport) + { + + + } +
+
+ + @if (_due is { } due) + { +

@T.Format("YearEnd.Intrastat.DueText", T[YearEndScreens.EnumKey(due.Goods)], T[YearEndScreens.EnumKey(due.Services)])

+ } + + + @if (_view is null) + { +

@T["YearEnd.Intrastat.NoList"]

+ } + else if (Lines.Count == 0) + { +

@T["YearEnd.Intrastat.NoLines"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + + @foreach (var line in Lines) + { + + + + + + + + + + + + + + + } + +
@T["YearEnd.Fields.Document"]@T["YearEnd.Intrastat.Counterparty"]@T["YearEnd.Intrastat.Country"]@T["YearEnd.Intrastat.Vat"]@T["YearEnd.Intrastat.Code"]@T["YearEnd.Fields.Description"]@T["YearEnd.Intrastat.Nature"]@T["YearEnd.Intrastat.Delivery"]@T["YearEnd.Intrastat.Transport"]@T["YearEnd.Intrastat.Value"]@T["YearEnd.Intrastat.Mass"]@T["YearEnd.Intrastat.Check"]
@(line.DocumentNumber ?? T["YearEnd.Intrastat.Manual"])@(line.PartyId is { } p && _view.PartyNames.TryGetValue(p, out var name) ? name : null)@line.CountryCode@line.VatNumber@line.NomenclatureCode@line.Description@line.TransactionNature@line.DeliveryTerms@line.TransportMode@T.Money(line.Amount)@(line.NetMass is { } m ? T.Number(m, 0) : null) + @T[YearEndScreens.EnumKey(line.Check)] + @if (line.Section is not IntrastatSection.Goods) + { + @T[YearEndScreens.EnumKey(line.Section)] + } +
+
+ } +
@T["YearEnd.Intrastat.Footer"]
+
+ + @if (_lists.Count > 0) + { + + + + + + + + + + + + + + + @foreach (var list in _lists) + { + + + + + + + + + + } + +
@T["YearEnd.Intrastat.Flow"]@T["YearEnd.Intrastat.Period"]@T["YearEnd.Intrastat.Goods"]@T["YearEnd.Intrastat.Services"]@T["YearEnd.Intrastat.Problems"]@T["YearEnd.Fields.Status"]@T["YearEnd.Intrastat.Protocol"]
@T[YearEndScreens.EnumKey(list.Flow)]@PeriodOf(list.Periodicity, list.Period)@T.Money(list.GoodsAmount)@T.Money(list.ServicesAmount)@list.Problems@T[YearEndScreens.EnumKey(list.Status)]@list.Protocol
+
+ } + + + +
+ + + + + + + + + + +
+
+
+ @if (_line.Id != 0) + { + + } + + +
+
+ + + +

@T["YearEnd.Intrastat.SentText"]

+
+ +
+
+
+ + +
+
+
+ +@code { + private bool _busy; + private IntrastatFlow _flow; + private int _year; + private IntrastatPeriodicity _periodicity = IntrastatPeriodicity.Monthly; + private int _period; + private IntrastatSection? _section; + private IReadOnlyList _lists = []; + private IntrastatListView? _view; + private Khaemhat.Fiscal.Abstractions.IntrastatDue? _due; + private bool _lineOpen; + private IntrastatListLine _line = new(); + private decimal? _amount; + private decimal? _mass; + private bool _sentOpen; + private string? _protocol; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanWrite => Session.Permissions.Allows(YearEndPermissions.IntrastatWrite); + + private bool CanExport => Session.Permissions.Allows(YearEndPermissions.IntrastatExport); + + private bool Sent => _view?.List.Status == IntrastatStatus.Sent; + + private IReadOnlyList Lines => _view is null ? [] : [.. _view.Lines.Where(l => _section is null || l.Section == _section)]; + + private string PeriodText => PeriodOf(_periodicity, _period); + + private IReadOnlyList> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList> PeriodicityChoices => + [new(IntrastatPeriodicity.Monthly, T[YearEndScreens.EnumKey(IntrastatPeriodicity.Monthly)]), new(IntrastatPeriodicity.Quarterly, T[YearEndScreens.EnumKey(IntrastatPeriodicity.Quarterly)])]; + + private IReadOnlyList> PeriodChoices => + [.. Enumerable.Range(1, _periodicity == IntrastatPeriodicity.Monthly ? 12 : 4).Select(p => new KhOption(p, PeriodOf(_periodicity, p)))]; + + private IReadOnlyList> SectionChoices => [.. Enum.GetValues().Select(s => new KhOption(s, T[YearEndScreens.EnumKey(s)]))]; + + private IReadOnlyList Stats + { + get + { + var sales = _view?.List.Flow == IntrastatFlow.Sales; + var purchases = _view?.List.Flow == IntrastatFlow.Purchases; + return + [ + new(T["YearEnd.Intrastat.Period"], PeriodText + " · " + T[YearEndScreens.EnumKey(_periodicity)].ToLowerInvariant()), + new(T["YearEnd.Intrastat.SalesGoods"], T.Money(sales ? _view!.List.GoodsAmount : 0m)), + new(T["YearEnd.Intrastat.SalesServices"], T.Money(sales ? _view!.List.ServicesAmount : 0m)), + new(T["YearEnd.Intrastat.PurchaseGoods"], T.Money(purchases ? _view!.List.GoodsAmount : 0m)), + new(T["YearEnd.Intrastat.PurchaseServices"], T.Money(purchases ? _view!.List.ServicesAmount : 0m)), + new(T["YearEnd.Intrastat.Problems"], T.Number(_view?.List.Problems ?? 0), (_view?.List.Problems ?? 0) > 0 ? KhTone.Warning : KhTone.Ok), + ]; + } + } + + private string PeriodOf(IntrastatPeriodicity periodicity, int period) => + periodicity == IntrastatPeriodicity.Monthly + ? T.Culture.DateTimeFormat.GetMonthName(Math.Clamp(period, 1, 12)) + " " + _year.ToString(System.Globalization.CultureInfo.InvariantCulture) + : T.Format("YearEnd.Intrastat.Quarter", period, _year); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + var previous = Today.AddMonths(-1); + _year = previous.Year; + _period = previous.Month; + if (Session.Actor is { } && Session.Company is { } && Session.Permissions.Allows(YearEndPermissions.IntrastatRead) && Session.Licenses.IsModuleActive(ModuleCodes.Intrastat)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _lists = await Intrastat.ListsAsync(actor, company, _year); + var quarter = _periodicity == IntrastatPeriodicity.Monthly ? ((_period - 1) / 3) + 1 : _period; + _due = await Intrastat.DueAsync(actor, company, _flow, _year, quarter); + var list = _lists.FirstOrDefault(l => l.Flow == _flow && l.Periodicity == _periodicity && l.Period == _period); + _view = list is null ? null : await Intrastat.GetAsync(actor, company, list.Id); + } + + private async Task SetFlowAsync(IntrastatFlow flow) + { + _flow = flow; + await LoadAsync(); + } + + private async Task SetYearAsync(int year) + { + _year = year; + await LoadAsync(); + } + + private async Task SetPeriodicityAsync(IntrastatPeriodicity periodicity) + { + _periodicity = periodicity; + _period = Math.Min(_period, periodicity == IntrastatPeriodicity.Monthly ? 12 : 4); + await LoadAsync(); + } + + private async Task SetPeriodAsync(int period) + { + _period = period; + await LoadAsync(); + } + + private async Task OpenAsync(IntrastatList list) + { + _flow = list.Flow; + _periodicity = list.Periodicity; + _period = list.Period; + await LoadAsync(); + } + + private async Task GenerateAsync() => await RunAsync(async (actor, company) => + { + _view = await Intrastat.GenerateAsync(actor, company, _flow, _year, _periodicity, _period); + Toasts.Show(ToastKind.Success, T["YearEnd.Intrastat.Generated"], T.Format("YearEnd.Intrastat.GeneratedText", _view.Lines.Count, _view.List.Problems)); + _lists = await Intrastat.ListsAsync(actor, company, _year); + }); + + private void NewLine() + { + _line = new IntrastatListLine { ListId = _view?.List.Id ?? 0, Section = IntrastatSection.Goods, TransactionNature = "11", DeliveryTerms = "DAP", TransportMode = "3" }; + _amount = null; + _mass = null; + _lineOpen = true; + } + + private void EditLine(IntrastatListLine line) + { + _line = new IntrastatListLine + { + Id = line.Id, ListId = line.ListId, Section = line.Section, SourceFamily = line.SourceFamily, SourceDocumentId = line.SourceDocumentId, + DocumentNumber = line.DocumentNumber, DocumentDate = line.DocumentDate, PartyId = line.PartyId, CountryCode = line.CountryCode, VatNumber = line.VatNumber, + Amount = line.Amount, CurrencyAmount = line.CurrencyAmount, StatisticalValue = line.StatisticalValue, NomenclatureCode = line.NomenclatureCode, + Description = line.Description, TransactionNature = line.TransactionNature, DeliveryTerms = line.DeliveryTerms, TransportMode = line.TransportMode, + NetMass = line.NetMass, SupplementaryUnits = line.SupplementaryUnits, OriginCountry = line.OriginCountry, Province = line.Province, + SupplyMode = line.SupplyMode, PaymentMode = line.PaymentMode, PaymentCountry = line.PaymentCountry, CorrectedYear = line.CorrectedYear, + CorrectedPeriod = line.CorrectedPeriod, CorrectionSign = line.CorrectionSign, RowVersion = line.RowVersion, + }; + _amount = line.Amount; + _mass = line.NetMass; + _lineOpen = true; + } + + private async Task SaveLineAsync() => await RunAsync(async (actor, company) => + { + _line.Amount = _amount ?? 0m; + _line.NetMass = _mass; + _view = await Intrastat.SaveLineAsync(actor, company, _line); + _lineOpen = false; + _lists = await Intrastat.ListsAsync(actor, company, _year); + }); + + private async Task DeleteLineAsync() => await RunAsync(async (actor, company) => + { + await Intrastat.DeleteLineAsync(actor, company, _line.Id); + _lineOpen = false; + await LoadAsync(); + }); + + private async Task ExportAsync() => await RunAsync(async (actor, company) => + { + if (_view is { } view) + { + await LedgerScreens.DownloadAsync(JS, await Intrastat.ExportAsync(actor, company, view.List.Id)); + await LoadAsync(); + } + }); + + private async Task MarkSentAsync() => await RunAsync(async (actor, company) => + { + if (_view is { } view) + { + await Intrastat.MarkSentAsync(actor, company, view.List.Id, _protocol); + _sentOpen = false; + await LoadAsync(); + } + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], YearEndScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/AccrualsPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/AccrualsPage.razor new file mode 100644 index 0000000..c70414e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/AccrualsPage.razor @@ -0,0 +1,302 @@ +@page "/contabilita/ratei-risconti" +@attribute [Authorize] +@using Khaemhat.Application.Ledger +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Core.Accounting +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd +@inject ShellSession Session +@inject AccrualService Accruals +@inject LedgerService Ledger +@inject ToastService Toasts +@inject TimeProvider Clock + +@* The accruals and deferrals and the exchange differences of the year end (SPEC §11.7, issue #84): ratei and risconti + typed or proposed from the costs that straddle the year end, the share computed by days; the open items in foreign + currency valued at the rate of the last day. Step 3 of the closing posts both; step 8 reverses them. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Shell.Menu.Ledger.Accruals"]
+

@T.Format("YearEnd.Accruals.Heading", _year)

+
@T["YearEnd.Accruals.Hint"]
+
+
+
+ + + @T["Shell.Menu.Ledger.Closing"] +
+
+ +
+ +
+ + + + + @if (_rows.Count == 0) + { +

@T["YearEnd.Accruals.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var a = row.Accrual; + var days = AccrualDeferralCalculator.Days(a.PeriodStart, a.PeriodEnd, a.YearEnd); + + + + + + + + + + + + } + +
@T["YearEnd.Fields.Kind"]@T["YearEnd.Fields.Description"]@T["Ledger.Fields.Account"]@T["Ledger.Fields.Party"]@T["YearEnd.Accruals.Period"]@T["YearEnd.Fields.Amount"]@T["YearEnd.Accruals.Days"]@T["YearEnd.Accruals.Adjustment"]@T["YearEnd.Fields.Status"]
@T[YearEndScreens.EnumKey(a.Kind)]@a.Description @(a.DocumentNumber is { } n ? " · " + n : null)@row.AccountCode@row.PartyName@T.Date(a.PeriodStart) - @T.Date(a.PeriodEnd)@T.Money(a.Amount)@(a.Kind is AccrualKind.AccruedIncome or AccrualKind.AccruedExpense ? days.Within : days.After)/@days.Total@T.Money(a.Adjustment)@T[a.GlEntryId is null ? "YearEnd.Accruals.ToPost" : "YearEnd.Accruals.Posted"]
+
+ } +
+ + + @if (_differences.Count == 0) + { +

@T["YearEnd.Accruals.NoExchange"]

+ } + else + { + + + + + + + + + + + + + + + @foreach (var d in _differences) + { + + + + + + + + + + + } + +
@T["Ledger.Fields.Document"]@T["Ledger.Fields.Party"]@T["YearEnd.Accruals.Currency"]@T["YearEnd.Accruals.ResidualCurrency"]@T["YearEnd.Accruals.DocumentRate"]@T["YearEnd.Accruals.YearEndRate"]@T["YearEnd.Accruals.ResidualEuro"]@T["YearEnd.Accruals.Difference"]
@d.DocumentNumber@d.PartyName@d.CurrencyCode@T.Number(d.ResidualCurrency, 2)@T.Number(d.DocumentRate, 4)@(d.YearEndRate is { } r ? T.Number(r, 4) : T["YearEnd.Accruals.RateMissing"])@T.Money(d.ResidualEuro)@T.Money(d.Difference)
+ } +
@T["YearEnd.Accruals.Footer"]
+
+ + + +
+ + + + + + +
+ @if (_amount is { } amount && _start is { } start && _end is { } end) + { +

@T.Format("YearEnd.Accruals.Preview", T.Money(AccrualDeferralCalculator.Share(_form.Kind, amount, start, end, new DateOnly(_year, 12, 31))))

+ } +
+
+ @if (_form.Id != 0 && _form.GlEntryId is null) + { + + } + + +
+
+
+ +@code { + private bool _busy; + private int _year; + private IReadOnlyList _rows = []; + private IReadOnlyList _differences = []; + private IReadOnlyList _accounts = []; + private bool _open; + private AccrualDeferral _form = new(); + private long? _account; + private decimal? _amount; + private DateOnly? _start; + private DateOnly? _end; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private IReadOnlyList> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList> AccountChoices + { + get + { + var nature = _form.Kind is AccrualKind.AccruedIncome or AccrualKind.DeferredIncome ? AccountNature.Revenue : AccountNature.Cost; + return [.. _accounts.Where(a => a.Postable && a.Nature == nature).Select(a => new KhOption(a.Id, a.Code + " · " + a.Description))]; + } + } + + private IReadOnlyList Stats => + [ + new(T[YearEndScreens.EnumKey(AccrualKind.AccruedIncome)], T.Money(Sum(AccrualKind.AccruedIncome))), + new(T[YearEndScreens.EnumKey(AccrualKind.AccruedExpense)], T.Money(Sum(AccrualKind.AccruedExpense))), + new(T[YearEndScreens.EnumKey(AccrualKind.PrepaidExpense)], T.Money(Sum(AccrualKind.PrepaidExpense))), + new(T[YearEndScreens.EnumKey(AccrualKind.DeferredIncome)], T.Money(Sum(AccrualKind.DeferredIncome))), + new(T["YearEnd.Accruals.Difference"], T.Money(_differences.Sum(d => d.Gain ? Math.Abs(d.Difference) : -Math.Abs(d.Difference))), KhTone.Info), + ]; + + private decimal Sum(AccrualKind kind) => _rows.Where(r => r.Accrual.Kind == kind).Sum(r => r.Accrual.Adjustment); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _year = Today.Month <= 4 ? Today.Year - 1 : Today.Year; + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(YearEndPermissions.YearClose) + && Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting)) + { + _accounts = await Ledger.AccountsAsync(actor, company); + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + try + { + _rows = await Accruals.ListAsync(actor, company, _year); + _differences = await Accruals.ExchangeDifferencesAsync(actor, company, _year); + } + catch (KeyNotFoundException) + { + _rows = []; + _differences = []; + } + } + + private async Task SetYearAsync(int year) + { + _year = year; + await LoadAsync(); + } + + private void New() + { + _form = new AccrualDeferral { Year = _year, Kind = AccrualKind.PrepaidExpense }; + _account = null; + _amount = null; + _start = null; + _end = null; + _open = true; + } + + private void Edit(AccrualDeferral accrual) + { + _form = new AccrualDeferral + { + Id = accrual.Id, Year = accrual.Year, Kind = accrual.Kind, Description = accrual.Description, AccountId = accrual.AccountId, PartyId = accrual.PartyId, + DocumentNumber = accrual.DocumentNumber, GlEntryId = accrual.GlEntryId, RowVersion = accrual.RowVersion, + }; + _account = accrual.AccountId; + _amount = accrual.Amount; + _start = accrual.PeriodStart; + _end = accrual.PeriodEnd; + _open = true; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + _form.Year = _year; + _form.AccountId = _account ?? 0; + _form.Amount = _amount ?? 0m; + _form.PeriodStart = _start ?? Today; + _form.PeriodEnd = _end ?? Today; + await Accruals.SaveAsync(actor, company, _form); + _open = false; + await LoadAsync(); + }); + + private async Task DeleteAsync() => await RunAsync(async (actor, company) => + { + await Accruals.DeleteAsync(actor, company, _form.Id); + _open = false; + await LoadAsync(); + }); + + private async Task ProposeAsync() => await RunAsync(async (actor, company) => + { + var added = await Accruals.ProposeAsync(actor, company, _year); + Toasts.Show(ToastKind.Success, T.Format("YearEnd.Accruals.Proposed", added)); + await LoadAsync(); + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], YearEndScreens.Errors(T, ex)); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], T["yearend.not-found"]); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/BalancePage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/BalancePage.razor index 2a1a52b..6961686 100644 --- a/src/Khaemhat.Web/Components/Pages/Ledger/BalancePage.razor +++ b/src/Khaemhat.Web/Components/Pages/Ledger/BalancePage.razor @@ -6,6 +6,7 @@ @using Khaemhat.Core.Accounting @using Khaemhat.Core.Tables @using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd @inject ShellSession Session @inject LedgerQueryService Queries @inject TableService Tables @@ -15,81 +16,100 @@ @* 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. *@ + period; the print of the trial balance and of the general journal, provisional or of the final entries. The other + tabs (issue #86, mockup 051) show the financial statements of the year of the end date: CEE, reclassified, ratios. *@
@T["Shell.Menu.Ledger"] / @T["Ledger.Balance.Title"]
-

@T["Ledger.Balance.Heading"]

-
@T["Ledger.Balance.Hint"]
+

@(_tab == "trial" ? T["Ledger.Balance.Heading"] : T.Format("YearEnd.Statements.Heading", _year))

+
@(_tab == "trial" ? T["Ledger.Balance.Hint"] : T["YearEnd.Statements.Hint"])
+
+ +
+
+ + @if (_tab != "trial") + { +
+ + @if (Session.Permissions.Allows(Khaemhat.Application.YearEnd.YearEndPermissions.YearClose)) + { + @T["Shell.Menu.Ledger.Closing"] + } +
+ + } + else + {
- - -
- - - - - -
- @if (_balance is { } balance) - { - - @if (balance.Lines.Count == 0) + +
+ + + + + +
+ @if (_balance is { } balance) { -

@T["Ledger.Balance.None"]

- } - else - { -
- - - - - - - - - - - - - - @foreach (var line in balance.Lines.Where(l => l.Level <= _level)) - { + + @if (balance.Lines.Count == 0) + { +

@T["Ledger.Balance.None"]

+ } + else + { +
+
@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.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"]
@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))
-
+ + + @foreach (var line in balance.Lines.Where(l => l.Level <= _level)) + { + + @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 { @@ -100,12 +120,24 @@ private bool _drafts; private bool _busy; private TrialBalance? _balance; + private string _tab = "trial"; + private int _year; 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 Tabs => + [ + new("trial", "list", T["YearEnd.Statements.Tabs.Trial"]), + new("cee", "layers", T["YearEnd.Statements.Tabs.Cee"]), + new("reclassified", "chart", T["YearEnd.Statements.Tabs.Reclassified"]), + new("ratios", "coins", T["YearEnd.Statements.Tabs.Ratios"]), + ]; + + private IReadOnlyList> YearChoices => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + private IReadOnlyList> LevelChoices => [ new(1, T["Ledger.Accounts.Level1"]), @@ -127,6 +159,7 @@ await Session.EnsureLoadedAsync(); _from = new DateOnly(Today.Year, 1, 1); _to = Today; + _year = Today.Month <= 4 ? Today.Year - 1 : Today.Year; if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(LedgerPermissions.EntryRead) && Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting)) { diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/ClosingPage.razor b/src/Khaemhat.Web/Components/Pages/Ledger/ClosingPage.razor new file mode 100644 index 0000000..06cc784 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/ClosingPage.razor @@ -0,0 +1,308 @@ +@page "/contabilita/chiusura" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Core.Accounting +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd +@inject ShellSession Session +@inject ClosingService Closing +@inject ToastService Toasts +@inject IJSRuntime JS + +@* The guided closing of a fiscal year (SPEC §11.7, issue #85, mockup 050, ADR 0042): nine steps run one after the + other, each repeatable and undoable until the final prints of step 9; then the lock makes the year read only. *@ + + + +
+
+
@T["Shell.Menu.Ledger"] / @T["Shell.Menu.Ledger.Closing"]
+

@T.Format("YearEnd.Closing.Heading", _view?.Year.Code ?? string.Empty)

+
@T["YearEnd.Closing.Hint"]
+
+
+ @if (_view is { } header) + { +
+ @foreach (var year in header.Years.Where(y => y.StartDate.Year >= header.Year.StartDate.Year).Take(2)) + { + @year.Code · @T[YearEndScreens.EnumKey(year.Status)] + } +
+ } +
+ + @if (_view is { } view) + { +
+ + @if (!Locked && view.NextStep is { } next) + { + + } + @if (!Locked && view.LastDone is { } last && last < ClosingService.StepCount) + { + + + } + @T["YearEnd.Closing.CheckAccruals"] + @T["YearEnd.Statements.Title"] + @if (!Locked) + { + + } +
+ @T[Locked ? "YearEnd.Closing.LockedNote" : "YearEnd.Closing.ProvisionalNote"] +
+ + +
+ +
+
+ + + + + + + + + + + + + + @foreach (var step in view.Steps) + { + var n = step.Number.ToString(System.Globalization.CultureInfo.InvariantCulture); + + + + + + + + + + } + +
#@T["YearEnd.Closing.Step"]@T["YearEnd.Fields.Description"]@T["YearEnd.Closing.Entries"]@T["YearEnd.Fields.Amount"]@T["YearEnd.Closing.Outcome"]@T["YearEnd.Closing.Executed"]
@step.Number@T.Format("YearEnd.Closing.Steps." + n + ".Title", NextYearCode(view)) + @T["YearEnd.Closing.Steps." + n + ".Detail"] + @foreach (var message in Messages(step)) + { + var (tone, text) = YearEndScreens.Message(T, message); +
+ @if (tone != KhTone.Neutral) + { + + } + @text +
+ } +
@(step.Status == ClosingStepStatus.Pending ? "—" : T.Number(step.Entries))@(step.Amount == 0m ? null : T.Money(step.Amount))@T[YearEndScreens.EnumKey(step.Status)]@(step.ExecutedAt is { } at ? T.Date(DateOnly.FromDateTime(at.ToLocalTime())) + " " + at.ToLocalTime().ToString("HH:mm", T.Culture) + " · " + step.ExecutedBy : null)
+
+
+ + @if (view.Prints.Count > 0) + { + + + + + + + + + + + + @foreach (var print in view.Prints) + { + + + + + + + } + +
@T["YearEnd.Closing.PrintKind"]@T["YearEnd.Closing.File"]@T["YearEnd.Closing.Pages"]
@PrintKind(print.Kind)@print.FileName@print.Pages
+
+ } + +
@T.Format("YearEnd.Closing.Footer", T.Date(view.Year.EndDate.AddDays(1)))
+ + +

@T["YearEnd.Closing.FinalText"]

+
+ + +
+
+ + +

@T.Format("YearEnd.Closing.LockText", view.Year.Code, T.Date(view.Year.EndDate))

+
+ + +
+
+ } + else if (_loaded) + { +

@T["YearEnd.Closing.NoYear"]

+ } +
+ +@code { + private ClosingView? _view; + private bool _loaded; + private bool _busy; + private int? _confirmStep; + private bool _confirmLock; + + private bool Locked => _view?.Run?.Status == ClosingStatus.Locked; + + private IReadOnlyList Phases => + [ + new(T["YearEnd.Closing.Phases.Checks"]), + new(T["YearEnd.Closing.Phases.Adjustments"]), + new(T["YearEnd.Closing.Phases.Closing"]), + new(T["YearEnd.Closing.Phases.Opening"]), + new(T["YearEnd.Closing.Phases.Prints"]), + ]; + + private static int PhaseIndex(ClosingView view) => view.NextStep switch + { + null => 5, + 1 => 0, + <= 5 => 1, + <= 7 => 2, + 8 => 3, + _ => 4, + }; + + private static IReadOnlyList> YearChoices(ClosingView view) => [.. view.Years.Select(y => new KhOption(y.Id, y.Code))]; + + private static string NextYearCode(ClosingView view) => + view.Years.FirstOrDefault(y => y.StartDate == view.Year.EndDate.AddDays(1))?.Code + ?? view.Year.EndDate.AddDays(1).Year.ToString(System.Globalization.CultureInfo.InvariantCulture); + + private static IEnumerable Messages(ClosingStep step) => + string.IsNullOrEmpty(step.Messages) ? [] : step.Messages.Split('\n', StringSplitOptions.RemoveEmptyEntries); + + private string PrintKind(string kind) => kind.StartsWith("vat-", StringComparison.Ordinal) + ? T.Format("YearEnd.Closing.PrintKinds.vat", kind[4..]) + : T.Contains("YearEnd.Closing.PrintKinds." + kind) ? T["YearEnd.Closing.PrintKinds." + kind] : kind; + + private static KhTone ToneOf(FiscalYearStatus status) => status switch + { + FiscalYearStatus.Open => KhTone.Info, + FiscalYearStatus.Closing => KhTone.Warning, + _ => KhTone.Neutral, + }; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Permissions.Allows(YearEndPermissions.YearClose) && Session.Licenses.IsModuleActive(Khaemhat.Application.Modules.ModuleCodes.Accounting)) + { + await LoadAsync(null); + } + } + + private async Task LoadAsync(long? yearId) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + try + { + _view = await Closing.GetAsync(actor, company, yearId); + } + catch (KeyNotFoundException) + { + _view = null; + } + + _loaded = true; + } + + private async Task SetYearAsync(long yearId) => await LoadAsync(yearId); + + private async Task AskRunAsync(int number) + { + if (number == ClosingService.StepCount) + { + _confirmStep = number; + return; + } + + await RunAsync(number); + } + + private async Task ConfirmRunAsync() + { + var number = _confirmStep ?? ClosingService.StepCount; + _confirmStep = null; + await RunAsync(number); + } + + private async Task RunAsync(int number) => await ActAsync(async (actor, company, yearId) => + { + _view = await Closing.RunStepAsync(actor, company, yearId, number); + var step = _view.Steps.FirstOrDefault(s => s.Number == number); + Toasts.Show(step?.Status == ClosingStepStatus.Failed ? ToastKind.Error : ToastKind.Success, T.Format("YearEnd.Closing.StepDone", number), + step is null ? null : T[YearEndScreens.EnumKey(step.Status)]); + }); + + private async Task UndoAsync(int number) => await ActAsync(async (actor, company, yearId) => + { + _view = await Closing.UndoStepAsync(actor, company, yearId, number); + Toasts.Show(ToastKind.Success, T.Format("YearEnd.Closing.StepUndone", number)); + }); + + private async Task LockAsync() => await ActAsync(async (actor, company, yearId) => + { + _confirmLock = false; + _view = await Closing.LockAsync(actor, company, yearId); + Toasts.Show(ToastKind.Success, T["YearEnd.Closing.Locked"], _view.Year.Code); + }); + + private async Task DownloadAsync(long printId) => await ActAsync(async (actor, company, _) => + await LedgerScreens.DownloadAsync(JS, await Closing.PrintAsync(actor, company, printId))); + + private async Task ActAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _view is not { } view) + { + return; + } + + _busy = true; + try + { + await action(actor, company, view.Year.Id); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], YearEndScreens.Errors(T, ex)); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], T["yearend.not-found"]); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/LedgerGuard.razor b/src/Khaemhat.Web/Components/Pages/Ledger/LedgerGuard.razor index d5c4c22..4aaea9f 100644 --- a/src/Khaemhat.Web/Components/Pages/Ledger/LedgerGuard.razor +++ b/src/Khaemhat.Web/Components/Pages/Ledger/LedgerGuard.razor @@ -13,12 +13,12 @@ else if (Session.Company is null)

@T["Ledger.NoCompany"]

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

@T["Ledger.NoModule.Title"]

-

@T["Ledger.NoModule.Lead"]

+

@T[NoModuleKey + "Title"]

+

@T[NoModuleKey + "Lead"]

} else if (!Session.Permissions.Allows(Permission)) @@ -42,10 +42,16 @@ else [Parameter, EditorRequired] public string Permission { get; set; } = string.Empty; + /// The module the page needs (the ledger by default; the fixed assets and Intrastat have their own). + [Parameter] + public string Module { get; set; } = ModuleCodes.Accounting; + /// The page. [Parameter] public RenderFragment? ChildContent { get; set; } + private string NoModuleKey => Module == ModuleCodes.Accounting ? "Ledger.NoModule." : "YearEnd.NoModule." + Module + "."; + /// protected override async Task OnInitializedAsync() { diff --git a/src/Khaemhat.Web/Components/Pages/Ledger/StatementsView.razor b/src/Khaemhat.Web/Components/Pages/Ledger/StatementsView.razor new file mode 100644 index 0000000..d39ad23 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Ledger/StatementsView.razor @@ -0,0 +1,319 @@ +@using Khaemhat.Application.Security +@using Khaemhat.Application.YearEnd +@using Khaemhat.Core.Accounting +@using Khaemhat.Fiscal.Abstractions +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.YearEnd +@inject ShellSession Session +@inject FinancialStatementsService Statements +@inject ToastService Toasts +@inject IJSRuntime JS + +@* The financial statements of a year (SPEC §11.7, issue #86, mockup 051, ADR 0043): the legal balance sheet and income + statement in the chosen form with the year before and the change; a click on a line shows its accounts. Also the + statements reclassified by liquidity and by value added and the ratios. *@ +
+ @if (Tab == "cee") + { + + + @if (Session.Permissions.Allows(YearEndPermissions.AccountantExport)) + { + + } + } + else if (Tab == "reclassified") + { + + } +
+ +@if (Tab == "cee" && _statements is { } s) +{ + + @if (s.Unmapped.Count > 0) + { +
+ @T.Format("YearEnd.Statements.Unmapped", s.Unmapped.Count) + @string.Join(", ", s.Unmapped.Take(8).Select(u => u.Code + " " + T.Money(u.Balance))) +
+ } +
+
+ + @Table(s.Assets, FinancialStatementKind.Assets, s.TotalAssets, "YearEnd.Statements.TotalAssets") + + + @Table(s.Liabilities, FinancialStatementKind.Liabilities, s.TotalLiabilities, "YearEnd.Statements.TotalLiabilities") + +
+
+ + @Table(s.Income, FinancialStatementKind.IncomeStatement, s.Result, "YearEnd.Statements.Result") + +
+
+} +else if (Tab == "reclassified") +{ + + + + + + + + + + + + @foreach (var row in _reclassified) + { + + + + + + + } + +
@T["YearEnd.Statements.Line"]@Year@(Year - 1)Δ %
@Text(row.Code, row.Description)@T.Money(row.Current)@T.Money(row.Previous)@YearEndScreens.Delta(T, row.Current, row.Previous)
+
+} +else if (Tab == "ratios") +{ + + + + + + + + + + + + @foreach (var ratio in _ratios) + { + + + + + + + } + +
@T["YearEnd.Statements.Ratio"]@T["YearEnd.Statements.Formula"]@Year@(Year - 1)
@T["YearEnd.Statements.RatioNames." + ratio.Current.Code]@T["YearEnd.Statements.RatioFormulas." + ratio.Current.Code]@RatioText(ratio.Current)@RatioText(ratio.Previous)
+
+} + + + + @if (_drill is { } drill) + { + @if (drill.Accounts.Count == 0) + { +

@T["YearEnd.Statements.NoAccounts"]

+ } + else + { + + + + + + + + + + + @foreach (var account in drill.Accounts) + { + + + + + + + } + + + + + + + + +
@T["Ledger.Fields.Account"]@T["Ledger.Fields.Description"]@Year@(Year - 1)
@account.Code@account.Description@T.Money(account.Current)@T.Money(account.Previous)
@T["Ledger.Balance.Totals"]@T.Money(drill.Accounts.Sum(a => a.Current))@T.Money(drill.Accounts.Sum(a => a.Previous))
+ } + } +
+
+ +
+
+ +@code { + private FinancialStatementForm _form; + private ReclassificationKind _kind; + private FinancialStatements? _statements; + private IReadOnlyList _reclassified = []; + private IReadOnlyList _ratios = []; + private Drill? _drill; + private bool _busy; + private (int Year, string Tab)? _loadedFor; + + /// The year. + [Parameter] + public int Year { get; set; } + + /// The view: cee, reclassified or ratios. + [Parameter] + public string Tab { get; set; } = "cee"; + + private sealed record Drill(string Title, IReadOnlyList Accounts); + + private string Text(string code, string description) => + T.Contains("YearEnd.Statements.Lines." + code) ? T["YearEnd.Statements.Lines." + code] : description; + + private static string? Bold(bool bold) => bold ? "font-weight:600" : null; + + private string RatioText(FinancialRatio ratio) => ratio.Value is not { } value + ? "—" + : ratio.Percent ? YearEndScreens.Percent(T, value) + : ratio.DaysUnit ? T.Format("YearEnd.Statements.Days", T.Number(value, 0)) + : T.Number(value, 2); + + private IReadOnlyList Stats(FinancialStatements s) => + [ + new(T["YearEnd.Statements.TotalAssets"], T.Money(s.TotalAssets.Current)), + new(T["YearEnd.Statements.TotalLiabilities"], T.Money(s.TotalLiabilities.Current)), + new(T["YearEnd.Statements.Result"], T.Money(s.Result.Current), s.Result.Current >= 0m ? KhTone.Ok : KhTone.Warning), + new(T["Ledger.Balance.Check"], T[s.Balanced ? "Ledger.Balance.Balanced" : "Ledger.Balance.NotBalanced"], s.Balanced ? KhTone.Ok : KhTone.Error), + ]; + + private RenderFragment Table(IReadOnlyList rows, FinancialStatementKind kind, (decimal Current, decimal Previous) total, string totalKey) => __builder => + { + + + + + + + + + + + + @foreach (var row in rows) + { + + + + + + + } + + + + + + + + + +
@T["YearEnd.Statements.Line"]@Year@(Year - 1)Δ %
+ @row.Code @Text(row.Code, row.Description) + @T.Money(row.Current)@T.Money(row.Previous)@YearEndScreens.Delta(T, row.Current, row.Previous)
@T[totalKey]@T.Money(total.Current)@T.Money(total.Previous)@YearEndScreens.Delta(T, total.Current, total.Previous)
+ }; + + /// + protected override async Task OnParametersSetAsync() + { + if (_loadedFor != (Year, Tab)) + { + _loadedFor = (Year, Tab); + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + try + { + switch (Tab) + { + case "cee": + _statements = await Statements.StatementsAsync(actor, company, Year, _form); + break; + case "reclassified": + _reclassified = await Statements.ReclassifiedAsync(actor, company, Year, _kind); + break; + default: + _ratios = await Statements.RatiosAsync(actor, company, Year); + break; + } + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Ledger.NotDone"], YearEndScreens.Errors(T, ex)); + } + } + + private async Task SetFormAsync(FinancialStatementForm form) + { + _form = form; + await LoadAsync(); + } + + private async Task SetKindAsync(ReclassificationKind kind) + { + _kind = kind; + await LoadAsync(); + } + + private async Task DrillAsync(FinancialStatementKind kind, StatementRow row) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + var accounts = await Statements.AccountsAsync(actor, company, Year, kind, row.Code); + _drill = new Drill(row.Code + " · " + Text(row.Code, row.Description), accounts); + } + + private async Task PrintAsync() => await RunAsync(async (actor, company) => + await LedgerScreens.DownloadAsync(JS, await Statements.PrintAsync(actor, company, Year, _form))); + + private async Task ExportAsync() => await RunAsync(async (actor, company) => + await LedgerScreens.DownloadAsync(JS, await Statements.AccountantExportAsync(actor, company, Year))); + + 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"], YearEndScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index b6b9631..1a933fd 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -164,6 +164,14 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); + // The year end (ADR 0041-0043): fixed assets, Intrastat, declarations of intent, accruals, closing, statements. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + // The schedule and the treasury (ADR 0038): collections, remittances, reconciliation, reminders, cash flow. services.AddSingleton(); services.AddSingleton(); @@ -222,6 +230,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.AddSingleton(); diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index 6d5ff25..3ece84b 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -173,6 +173,7 @@ public static class SeedCommand await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); + await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{code}: completato in {watch.Elapsed.TotalSeconds:0.0} s.")); diff --git a/src/Khaemhat.Web/Resources/it-IT/Ledger.json b/src/Khaemhat.Web/Resources/it-IT/Ledger.json index b521206..8ceb892 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Ledger.json +++ b/src/Khaemhat.Web/Resources/it-IT/Ledger.json @@ -365,7 +365,11 @@ "Recurring": "Ricorrente", "Reversal": "Storno", "Withholding": "Ritenuta", - "Treasury": "Tesoreria" + "Treasury": "Tesoreria", + "FixedAsset": "Cespiti", + "Accrual": "Ratei e risconti", + "ExchangeDifference": "Differenze di cambio", + "Closing": "Chiusura esercizio" }, "RecurrenceFrequency": { "Monthly": "Mensile", diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index b019147..758ab72 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -95,6 +95,8 @@ "VatSettlement": "Liquidazione IVA", "Withholdings": "Ritenute e F24", "StampDuty": "Bollo virtuale", + "Accruals": "Ratei e risconti", + "Closing": "Chiusura esercizio", "Statements": "Bilancio" }, "Finance": { @@ -115,12 +117,14 @@ "Notifications": "Notifiche SDI", "Conservation": "Conservazione", "Channels": "Canali di trasmissione", + "Intrastat": "Intrastat", "IntentDeclarations": "Dichiarazioni d'intento" }, "Assets": { "_": "Cespiti", "Register": "Registro cespiti", - "Depreciation": "Ammortamenti" + "Depreciation": "Ammortamenti", + "Categories": "Categorie" }, "Services": { "_": "Servizi", diff --git a/src/Khaemhat.Web/Resources/it-IT/YearEnd.json b/src/Khaemhat.Web/Resources/it-IT/YearEnd.json new file mode 100644 index 0000000..a041e7b --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/YearEnd.json @@ -0,0 +1,512 @@ +{ + "YearEnd": { + "All": "Tutti", + "Search": "Cerca", + "NoModule": { + "ASSET": { + "Title": "Cespiti non attivi", + "Lead": "La licenza di questa azienda non comprende il modulo Cespiti (ASSET). Attivalo da Amministrazione, Licenze." + }, + "INTRA": { + "Title": "Intrastat non attivo", + "Lead": "La licenza di questa azienda non comprende il modulo Intrastat (INTRA). Attivalo da Amministrazione, Licenze." + }, + "CORE": { + "Title": "Funzione non disponibile", + "Lead": "La licenza di questa azienda non comprende il modulo di base (CORE)." + } + }, + "Fields": { + "Year": "Esercizio", + "Category": "Categoria", + "Status": "Stato", + "Code": "Codice", + "Description": "Descrizione", + "Rate": "Aliquota", + "InService": "Entrata in funzione", + "Cost": "Costo storico", + "Fund": "Fondo", + "NetValue": "Valore netto", + "PurchaseDate": "Data acquisto", + "Supplier": "Fornitore", + "Document": "Documento", + "Location": "Ubicazione", + "FiscalFund": "Fondo fiscale", + "LastDepreciation": "Ultimo ammortamento", + "Quantity": "Quantità", + "Serial": "Matricola", + "CivilRate": "Aliquota civilistica %", + "FiscalRate": "Aliquota fiscale %", + "ResidualValue": "Valore residuo", + "OpeningCivilFund": "Fondo civilistico iniziale", + "OpeningFiscalFund": "Fondo fiscale iniziale", + "Date": "Data", + "Proceeds": "Corrispettivo", + "CostDisposed": "Costo dismesso", + "Opening": "Cespite già in uso", + "FundOpening": "Fondo iniziale", + "Class": "Tipo", + "AssetAccount": "Conto del cespite", + "FundAccount": "Conto del fondo", + "DepreciationAccount": "Conto di ammortamento", + "CostLimit": "Limite di costo fiscale", + "Deductible": "Deducibilità %", + "Notes": "Note", + "Kind": "Tipo", + "Amount": "Importo" + }, + "Assets": { + "Title": "Registro cespiti", + "Heading": "Registro cespiti", + "Hint": "I beni ammortizzabili con il piano civilistico e fiscale, i movimenti, le dismissioni e la stampa del registro.", + "New": "Nuovo cespite", + "EditTitle": "Cespite", + "Depreciate": "Ammortamenti {0}", + "Print": "Stampa registro", + "NoCategories": "Prima di registrare un cespite crea le categorie (Cespiti, Categorie: c'è anche il pulsante per le categorie ministeriali standard).", + "SearchHint": "Codice, descrizione, matricola", + "None": "Nessun cespite.", + "Count": "{0} cespiti", + "Plan": "Piano di ammortamento {0} · {1}", + "PlanTitle": "Piano di ammortamento", + "Civil": "Civilistico", + "Fiscal": "Fiscale", + "Detail": "Dettaglio", + "Movements": "Movimenti", + "Dispose": "Dismetti", + "DisposeText": "La dismissione chiude il cespite (o ne riduce il costo se parziale), registra la quota dell'anno fino alla data e la plusvalenza o minusvalenza.", + "Disposed": "Cespite dismesso", + "CodeHint": "Vuoto: il prossimo numero della categoria", + "RateHint": "Vuoto: l'aliquota della categoria", + "LastYearHint": "Ultimo esercizio già ammortizzato fuori da Khaemhat", + "OpeningHint": "Cespite acquistato prima dell'avvio: i fondi iniziali entrano con la scrittura di apertura", + "CostDisposedHint": "Vuoto: tutto il costo residuo (dismissione totale)", + "Active": "Attivi" + }, + "Depreciation": { + "Title": "Ammortamenti", + "Heading": "Ammortamenti {0}", + "Hint": "Quota civilistica e fiscale di ogni cespite; la scrittura per categoria al 31/12 si annulla finché le registrazioni non sono definitive.", + "Post": "Registra ammortamenti", + "Undo": "Annulla registrazione", + "None": "Nessun cespite da ammortizzare nell'esercizio.", + "Difference": "Differenza civ./fisc.", + "Posted": "Registrato", + "ToPost": "Da registrare", + "Footer": "La differenza tra quota civilistica e fiscale è una variazione in dichiarazione dei redditi e non genera scritture. Il passo 2 della chiusura registra gli ammortamenti se non sono già registrati.", + "Assets": "Cespiti", + "PostedToast": "Ammortamenti registrati" + }, + "Categories": { + "Title": "Categorie cespiti", + "Heading": "Categorie cespiti", + "Hint": "Coefficienti ministeriali (DM 31/12/1988) e conti del cespite, del fondo e dell'ammortamento.", + "New": "Nuova categoria", + "Standard": "Categorie standard", + "None": "Nessuna categoria. Usa Categorie standard per crearle dal pacchetto fiscale.", + "EditTitle": "Categoria cespiti", + "LimitHint": "Ad esempio 18.075,99 per le autovetture", + "HalfFirstYear": "Metà aliquota civilistica nel primo esercizio", + "Added": "Categorie create: {0}" + }, + "Intrastat": { + "Title": "Intrastat", + "Heading": "Elenchi Intrastat", + "Hint": "Cessioni e acquisti intracomunitari di beni e servizi: elenchi generati dai documenti, rettifiche, file SCAMBI.CEE per l'Agenzia delle Dogane.", + "Flow": "Flusso", + "Periodicity": "Periodicità", + "Period": "Periodo", + "Section": "Sezione", + "Generate": "Genera {0}", + "AddLine": "Aggiungi riga", + "File": "File SCAMBI.CEE", + "MarkSent": "Segna come inviato", + "DueText": "Periodicità dovuta in base ai trimestri precedenti: beni {0}, servizi {1}.", + "NoList": "Nessun elenco per il periodo: usa Genera.", + "NoLines": "L'elenco non ha righe.", + "Counterparty": "Controparte", + "Country": "Paese", + "Vat": "Partita IVA", + "Code": "Nomenclatura / CPA", + "Nature": "Natura", + "Delivery": "Consegna", + "Transport": "Trasporto", + "Value": "Ammontare €", + "Mass": "Massa netta kg", + "Check": "Controllo", + "Manual": "Manuale", + "Footer": "Le soglie di periodicità e il tracciato seguono la determinazione dell'Agenzia delle Dogane; prima dell'invio verificare il file con il software di controllo delle Dogane.", + "Lists": "Elenchi {0}", + "Goods": "Beni", + "Services": "Servizi", + "Problems": "Da completare", + "Protocol": "Protocollo di invio", + "LineTitle": "Riga Intrastat", + "SentText": "Indica il protocollo ricevuto dopo l'invio telematico: l'elenco diventa di sola lettura.", + "SalesGoods": "Cessioni di beni", + "SalesServices": "Servizi resi", + "PurchaseGoods": "Acquisti di beni", + "PurchaseServices": "Servizi ricevuti", + "Quarter": "{0}° trimestre {1}", + "Generated": "Elenco generato", + "GeneratedText": "{0} righe, {1} da completare." + }, + "Intent": { + "Title": "Dichiarazioni d'intento", + "HeadingReceived": "Dichiarazioni d'intento ricevute", + "HeadingIssued": "Dichiarazioni d'intento emesse", + "Hint": "Esportatori abituali: plafond, consumo dalle fatture in N3.5, avviso al 90% e blocco dell'emissione oltre il plafond.", + "New": "Nuova dichiarazione", + "EditTitle": "Dichiarazione d'intento", + "Register": "Stampa registro", + "Received": "Ricevute (clienti)", + "Issued": "Emesse (fornitori)", + "None": "Nessuna dichiarazione per l'anno.", + "Number": "Numero", + "Customer": "Cliente", + "Supplier": "Fornitore", + "Protocol": "Protocollo telematico", + "ProtocolHint": "17 cifre più 6 di progressivo, separati da trattino o barra", + "Ceiling": "Plafond", + "Used": "Utilizzato", + "UsedHint": "Il consumo si aggiorna da solo con le fatture emesse; qui si corregge solo l'iniziale", + "Remaining": "Residuo", + "ValidFrom": "Valida dal", + "ValidTo": "Valida al", + "Footer": "Le fatture al cliente con codice IVA di natura N3.5 riportano gli estremi della dichiarazione; l'emissione è rifiutata senza dichiarazione valida o oltre il plafond.", + "Revoke": "Revoca", + "AtWarning": "Plafond utilizzato al {0:N1}%", + "ActivePercent": "{0:N1}%" + }, + "Accruals": { + "Title": "Ratei e risconti", + "Heading": "Ratei e risconti {0}", + "Hint": "Costi e ricavi a cavallo dell'esercizio ripartiti per giorni, e differenze di cambio sulle partite in valuta al 31/12.", + "New": "Nuovo rateo o risconto", + "Propose": "Proponi dai documenti", + "ListTitle": "Ratei e risconti", + "EditTitle": "Rateo o risconto", + "None": "Nessun rateo o risconto per l'esercizio.", + "Period": "Competenza", + "Days": "Giorni", + "Adjustment": "Rettifica", + "Posted": "Registrato", + "ToPost": "Da registrare", + "ExchangeTitle": "Differenze di cambio al 31/12", + "NoExchange": "Nessuna partita aperta in valuta.", + "Currency": "Valuta", + "ResidualCurrency": "Residuo in valuta", + "DocumentRate": "Cambio documento", + "YearEndRate": "Cambio al 31/12", + "ResidualEuro": "Residuo €", + "Difference": "Utile / perdita su cambi", + "RateMissing": "manca", + "Footer": "Il passo 3 della chiusura registra ratei, risconti e differenze di cambio; il passo 8 li storna il primo giorno dell'esercizio successivo. I cambi si inseriscono in Tabelle azienda, Valute.", + "Start": "Competenza dal", + "End": "Competenza al", + "Preview": "Rettifica calcolata: {0}", + "Proposed": "Risconti proposti: {0}" + }, + "Closing": { + "Title": "Chiusura esercizio", + "Heading": "Chiusura esercizio {0}", + "Hint": "Nove passi in ordine: ognuno si ripete o si annulla finché non si eseguono le stampe definitive; poi il blocco.", + "Run": "Esegui passo {0}", + "Repeat": "Ripeti passo {0}", + "Undo": "Annulla passo {0}", + "CheckAccruals": "Verifica ratei/risconti", + "Lock": "Blocca esercizio", + "LockedNote": "Esercizio bloccato: sola lettura.", + "ProvisionalNote": "Le scritture di assestamento restano provvisorie fino al passo 9.", + "Step": "Passo", + "Entries": "Reg.", + "Outcome": "Esito", + "Executed": "Eseguito", + "Prints": "Stampe definitive", + "PrintKind": "Stampa", + "File": "File", + "Pages": "Pagine", + "Download": "Scarica", + "PrintKinds": { + "journal": "Libro giornale", + "assets": "Registro cespiti", + "statements": "Bilancio CEE", + "vat": "Registro IVA {0}" + }, + "Footer": "Ogni passo è ripetibile e annullabile fino alle stampe; le registrazioni generate sono marcate con il passo della chiusura. Dopo il blocco l'esercizio è di sola lettura e si registra solo dal {0}.", + "FinalText": "Il passo 9 rende definitive tutte le registrazioni dell'esercizio, numera il libro giornale e conserva le stampe. Non si può annullare.", + "LockText": "Bloccare l'esercizio {0}? Dopo il blocco non si registra più nulla con data fino al {1}.", + "Locked": "Esercizio bloccato", + "NoYear": "Nessun esercizio: crealo in Tabelle azienda, Esercizi.", + "StepDone": "Passo {0} eseguito", + "StepUndone": "Passo {0} annullato", + "Phases": { + "Checks": "Controlli", + "Adjustments": "Assestamento", + "Closing": "Chiusura", + "Opening": "Apertura", + "Prints": "Stampe" + }, + "Steps": { + "1": { + "Title": "Controlli preliminari", + "Detail": "Nessuna provvisoria, registrazioni quadrate, bilancio di verifica in pareggio, conti senza voce di bilancio" + }, + "2": { + "Title": "Ammortamenti", + "Detail": "Quote civilistiche dei cespiti, per categoria" + }, + "3": { + "Title": "Ratei e risconti", + "Detail": "Ratei, risconti e differenze di cambio al 31/12" + }, + "4": { + "Title": "Rimanenze finali", + "Detail": "Storno delle rimanenze iniziali e rimanenze finali al costo medio ponderato" + }, + "5": { + "Title": "Accantonamenti", + "Detail": "Svalutazione crediti e TFR" + }, + "6": { + "Title": "Chiusura conti economici", + "Detail": "Giroconto a Conto economico e rilevazione del risultato" + }, + "7": { + "Title": "Chiusura conti patrimoniali", + "Detail": "A Stato patrimoniale finale, per conto e per soggetto" + }, + "8": { + "Title": "Apertura esercizio {0}", + "Detail": "Riporto di saldi e partite, storno di ratei e risconti" + }, + "9": { + "Title": "Stampe definitive", + "Detail": "Libro giornale, registri IVA, registro cespiti, bilancio" + } + } + }, + "Statements": { + "Title": "Bilancio", + "Heading": "Bilancio d'esercizio {0}", + "Hint": "Stato patrimoniale e conto economico civilistici con l'anno precedente, riclassificazioni e indici; clic su una voce per vederne i conti.", + "Form": "Schema", + "Print": "Stampa bilancio", + "Export": "Esporta per il commercialista", + "Reclassification": "Riclassificazione", + "Unmapped": "{0} conti con saldo senza voce di bilancio:", + "Assets": "Stato patrimoniale · Attivo", + "Liabilities": "Stato patrimoniale · Passivo", + "Income": "Conto economico", + "TotalAssets": "Totale attivo", + "TotalLiabilities": "Totale passivo", + "Result": "Risultato d'esercizio", + "Line": "Voce", + "Ratios": "Indici di bilancio", + "Ratio": "Indice", + "Formula": "Formula", + "NoAccounts": "Nessun conto con saldo nella voce.", + "DrillHint": "Clic: i conti della voce", + "Days": "{0} giorni", + "Tabs": { + "Trial": "Verifica", + "Cee": "CEE", + "Reclassified": "Riclassificato", + "Ratios": "Indici" + }, + "RatioNames": { + "ROE": "ROE", + "ROI": "ROI", + "ROS": "ROS", + "TURNOVER": "Rotazione del capitale investito", + "CURRENT": "Indice di disponibilità", + "QUICK": "Indice di liquidità", + "EQUITY": "Indipendenza finanziaria", + "LEVERAGE": "Leva finanziaria", + "COVERAGE": "Copertura delle immobilizzazioni", + "DSO": "Giorni medi di incasso", + "DPO": "Giorni medi di pagamento" + }, + "RatioFormulas": { + "ROE": "Risultato / Patrimonio netto", + "ROI": "Risultato operativo / Totale attivo", + "ROS": "Risultato operativo / Ricavi", + "TURNOVER": "Ricavi / Totale attivo", + "CURRENT": "Attivo circolante / Debiti a breve", + "QUICK": "(Attivo circolante - Rimanenze) / Debiti a breve", + "EQUITY": "Patrimonio netto / Totale attivo", + "LEVERAGE": "Totale attivo / Patrimonio netto", + "COVERAGE": "(Patrimonio netto + Debiti a lungo) / Immobilizzazioni", + "DSO": "Crediti verso clienti per giorni / Ricavi", + "DPO": "Debiti verso fornitori per giorni / Acquisti" + } + }, + "Enums": { + "AssetStatus": { + "Active": "In ammortamento", + "Depreciated": "Ammortizzato", + "Disposed": "Dismesso" + }, + "AssetClass": { + "Tangible": "Materiale", + "Intangible": "Immateriale" + }, + "AssetMovementKind": { + "Purchase": "Acquisto", + "Increase": "Incremento", + "Revaluation": "Rivalutazione", + "Depreciation": "Ammortamento", + "PartialDisposal": "Dismissione parziale", + "Disposal": "Dismissione", + "Opening": "Apertura" + }, + "IntrastatFlow": { + "Sales": "Cessioni", + "Purchases": "Acquisti" + }, + "IntrastatPeriodicity": { + "Monthly": "Mensile", + "Quarterly": "Trimestrale", + "NotDue": "Non dovuto" + }, + "IntrastatSection": { + "Goods": "Beni", + "GoodsCorrection": "Rettifiche beni", + "Services": "Servizi", + "ServicesCorrection": "Rettifiche servizi" + }, + "IntrastatCheck": { + "Ok": "Completa", + "MissingNomenclature": "Manca la nomenclatura", + "MissingMass": "Manca la massa netta", + "MissingVatNumber": "Manca la partita IVA", + "OutsideEu": "Fuori UE", + "MissingServiceCode": "Manca il codice CPA" + }, + "IntrastatStatus": { + "Draft": "Bozza", + "Generated": "File generato", + "Sent": "Inviato" + }, + "IntentStatus": { + "Active": "Attiva", + "Exhausted": "Esaurita", + "Revoked": "Revocata" + }, + "IntentDirection": { + "Received": "Ricevuta", + "Issued": "Emessa" + }, + "ClosingStepStatus": { + "Pending": "In attesa", + "Done": "Eseguito", + "Passed": "Superato", + "ToVerify": "Da verificare", + "Failed": "Non superato" + }, + "AccrualKind": { + "AccruedIncome": "Rateo attivo", + "AccruedExpense": "Rateo passivo", + "PrepaidExpense": "Risconto attivo", + "DeferredIncome": "Risconto passivo" + }, + "FinancialStatementForm": { + "Ordinary": "Ordinario", + "Abbreviated": "Abbreviato", + "Micro": "Micro-impresa" + }, + "ReclassificationKind": { + "Financial": "Stato patrimoniale finanziario", + "ValueAdded": "Conto economico a valore aggiunto" + }, + "FiscalYearStatus": { + "Open": "aperto", + "Closing": "in chiusura", + "Closed": "chiuso" + } + } + }, + "yearend": { + "not-found": "Elemento non trovato.", + "code-required": "Il codice è obbligatorio.", + "code-taken": "Codice già usato.", + "description-required": "La descrizione è obbligatoria.", + "entries-final": "Le registrazioni sono già definitive.", + "amount-required": "Indica un importo maggiore di zero." + }, + "assets": { + "category-required": "Scegli la categoria.", + "category-accounts": "La categoria {0} non ha i conti del cespite, del fondo e dell'ammortamento.", + "rate-range": "L'aliquota deve essere tra 0 e 100.", + "cost-required": "Indica il costo storico.", + "fund-too-high": "Il fondo non può superare il costo.", + "service-before-purchase": "L'entrata in funzione non può precedere l'acquisto.", + "posted": "Il cespite ha ammortamenti registrati: non si modifica il costo né si elimina.", + "disposed": "Il cespite è già dismesso.", + "disposal-too-high": "Il costo dismesso supera il costo residuo.", + "later-depreciation": "Esistono ammortamenti di esercizi successivi." + }, + "accruals": { + "account-required": "Scegli il conto di costo o di ricavo.", + "period-order": "La fine della competenza precede l'inizio.", + "period-outside": "La competenza deve stare a cavallo della fine dell'esercizio.", + "posted": "Già registrato dalla chiusura: annulla prima il passo 3." + }, + "intent": { + "party-required": "Scegli il cliente o il fornitore.", + "number-required": "Il numero è obbligatorio.", + "protocol-invalid": "Il protocollo telematico non è valido (17 cifre, trattino, 6 cifre).", + "validity-order": "La fine della validità precede l'inizio.", + "ceiling-required": "Indica il plafond.", + "ceiling-below-used": "Il plafond non può essere inferiore all'utilizzato.", + "tax-code-nature": "Una vendita con dichiarazione d'intento richiede un codice IVA di natura N3.5.", + "no-declaration": "Il cliente non ha una dichiarazione d'intento valida alla data del documento.", + "ceiling-exceeded": "L'importo supera il plafond residuo della dichiarazione d'intento.", + "used": "La dichiarazione è già usata da documenti: si può solo revocare." + }, + "intrastat": { + "sent": "L'elenco è già inviato.", + "period-invalid": "Periodo non valido per la periodicità.", + "country-not-member": "Il paese non è uno stato membro UE.", + "company-vat-missing": "Manca la partita IVA dell'azienda.", + "incomplete": "L'elenco ha righe da completare." + }, + "closing": { + "not-started": "La chiusura non è iniziata.", + "locked": "L'esercizio è bloccato.", + "step-order": "Esegui i passi in ordine.", + "later-step-done": "Un passo successivo è già eseguito: annulla prima quello.", + "checks-failed": "I controlli preliminari non sono superati.", + "step-irreversible": "Le stampe definitive non si annullano.", + "previous-open": "Un esercizio precedente non è chiuso.", + "year-not-ended": "L'esercizio non è ancora terminato.", + "steps-pending": "Ci sono passi da eseguire.", + "account-missing": "Manca il conto {0} nel piano dei conti.", + "unbalanced": "La chiusura dei conti patrimoniali non quadra ({0}).", + "check-drafts": "{0} registrazioni provvisorie da confermare o eliminare.", + "check-unbalanced": "{0} registrazioni non quadrate.", + "check-trial-balance": "Il bilancio di verifica non è in pareggio ({0}).", + "check-unmapped": "Conto {0} senza voce di bilancio (saldo {1}).", + "check-year-not-ended": "L'esercizio termina il {0}: la chiusura è anticipata.", + "check-previous-open": "L'esercizio {0} non è ancora chiuso.", + "check-ok": "Controlli superati.", + "nothing-to-post": "Niente da registrare.", + "depreciation-none": "Nessun ammortamento da registrare (o già registrato).", + "depreciation-posted": "Ammortamenti registrati: {0}.", + "accruals-posted": "Ratei e risconti registrati: {0}.", + "exchange-posted": "Differenze di cambio registrate: {0}.", + "rate-missing": "Manca il cambio al 31/12 per {0}.", + "inventory-opening": "Storno rimanenze iniziali: {0}.", + "inventory-closing": "Rimanenze finali: {0} ({1} articoli, costo medio ponderato).", + "bad-debt": "Svalutazione crediti: {0} su {1} di crediti.", + "severance": "TFR stimato da accantonare: {0} su {1} di retribuzioni: verificare con il consulente del lavoro.", + "profit": "Utile d'esercizio: {0}.", + "loss": "Perdita d'esercizio: {0}.", + "balance-closed": "{0} saldi chiusi a Stato patrimoniale finale ({1}).", + "year-created": "Creato l'esercizio {0}.", + "opening-posted": "Riaperti i conti nell'esercizio {0}.", + "adjustments-reversed": "Stornati {0} ratei e risconti.", + "finalized": "Registrazioni rese definitive: {0}.", + "prints": "Stampe conservate: {0}." + } +} diff --git a/src/Khaemhat.Web/Shell/HelpLinks.cs b/src/Khaemhat.Web/Shell/HelpLinks.cs index eaff9b1..02ef595 100644 --- a/src/Khaemhat.Web/Shell/HelpLinks.cs +++ b/src/Khaemhat.Web/Shell/HelpLinks.cs @@ -20,8 +20,13 @@ public static class HelpLinks ("/magazzino", "Magazzino"), ("/contabilita/liquidazione-iva", "IVA"), ("/contabilita/registri-iva", "IVA"), + ("/contabilita/chiusura", "Chiusura-e-bilancio"), + ("/contabilita/bilancio", "Chiusura-e-bilancio"), + ("/contabilita/ratei-risconti", "Chiusura-e-bilancio"), ("/contabilita", "Contabilita"), ("/scadenzario", "Scadenzario"), + ("/fatturazione-elettronica/intrastat", "Intrastat"), + ("/fatturazione-elettronica/dichiarazioni-intento", "Dichiarazioni-d-intento"), ("/fatturazione-elettronica", "Fatturazione-elettronica"), ("/cespiti", "Cespiti"), ("/servizi", "Servizi"), diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 4af9a07..7028999 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -73,14 +73,15 @@ public static class MenuCatalog ("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")), + ("Shell.Menu.Ledger.StampDuty", "bollo"), ("Shell.Menu.Ledger.Accruals", "ratei-risconti"), + ("Shell.Menu.Ledger.Closing", "chiusura"), ("Shell.Menu.Ledger.Statements", "bilancio")), Area("Shell.Menu.Finance", "coins", "/scadenzario", ModuleCodes.Finance, "finance.schedule.read", null, ("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Receipts", "incassi"), ("Shell.Menu.Finance.Payments", "pagamenti"), ("Shell.Menu.Finance.Dunning", "solleciti"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Mandates", "mandati"), ("Shell.Menu.Finance.Reconciliation", "riconciliazione"), ("Shell.Menu.Finance.CashFlow", "flusso-di-cassa")), EInvoicing(), - Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10", - ("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")), + Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", null, + ("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti"), ("Shell.Menu.Assets.Categories", "categorie")), Area("Shell.Menu.Services", "wrench", "/servizi", ModuleCodes.Services, null, "M12", ("Shell.Menu.Services.Contracts", "contratti"), ("Shell.Menu.Services.Interventions", "interventi")), Area("Shell.Menu.Channels", "globe", "/canali", ModuleCodes.Channels, null, "M12", @@ -125,7 +126,10 @@ public static class MenuCatalog // An entry delivered before the rest of its area (the guided import of M4 under the administration of M13). private static MenuItem WithChild(MenuItem area, MenuItem child) => area with { Children = [.. area.Children, child] }; - /// The electronic invoice (M9): each page has its own permission; the intent declarations come with M10. + /// + /// The electronic invoice (M9): each page has its own permission; Intrastat (module INTRA) and the declarations of + /// intent (M10, module CORE) sit here as in mockups 049 and 061. + /// private static MenuItem EInvoicing() { const string href = "/fatturazione-elettronica"; @@ -141,7 +145,8 @@ public static class MenuCatalog Child("Shell.Menu.EInvoicing.Notifications", "notifiche", "einvoice.document.read"), Child("Shell.Menu.EInvoicing.Conservation", "conservazione", "einvoice.document.read"), Child("Shell.Menu.EInvoicing.Channels", "canali", "einvoice.channel.manage"), - Child("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento", "einvoice.document.read", "M10"), + new MenuItem("Shell.Menu.EInvoicing.Intrastat", icon, href + "/intrastat", ModuleCodes.Intrastat, "intrastat.list.read", null), + new MenuItem("Shell.Menu.EInvoicing.IntentDeclarations", icon, href + "/dichiarazioni-intento", ModuleCodes.Core, "sales.intent.read", null), ], }; } diff --git a/src/Khaemhat.Web/YearEnd/YearEndScreens.cs b/src/Khaemhat.Web/YearEnd/YearEndScreens.cs new file mode 100644 index 0000000..828b905 --- /dev/null +++ b/src/Khaemhat.Web/YearEnd/YearEndScreens.cs @@ -0,0 +1,175 @@ +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Parties; +using Khaemhat.Web.Tables; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.YearEnd; + +/// +/// What the screens of the year end share (M10, mockups 048-051 and 061): addresses, texts of enums, errors with their +/// values and the messages of the steps of the closing. +/// +public static class YearEndScreens +{ + /// The address of the fixed assets. + public const string AssetsPath = "/cespiti"; + + /// The address of the Intrastat lists. + public const string IntrastatPath = "/fatturazione-elettronica/intrastat"; + + /// The address of the declarations of intent. + public const string IntentPath = "/fatturazione-elettronica/dichiarazioni-intento"; + + /// The address of the closing. + public const string ClosingPath = "/contabilita/chiusura"; + + /// The page of the accruals and deferrals. + public const string AccrualsPath = "/contabilita/ratei-risconti"; + + /// The key of the text of an enum value. + /// The value. + /// The key. + public static string EnumKey(Enum value) + { + ArgumentNullException.ThrowIfNull(value); + return "YearEnd.Enums." + value.GetType().Name + "." + value; + } + + /// The choices of an enum. + /// The enum. + /// The texts. + /// The choices. + 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, with the values some carry (code:value). + /// The texts. + /// The refusal. + /// The messages. + public static string Errors(ITexts texts, ValidationFailedException exception) + { + ArgumentNullException.ThrowIfNull(texts); + ArgumentNullException.ThrowIfNull(exception); + return string.Join(" ", exception.Errors.Select(e => Error(texts, e)).Distinct(StringComparer.Ordinal)); + } + + /// The text of one error. + /// The texts. + /// The error, Field:code:value or code:value. + /// The message. + public static string Error(ITexts texts, string error) + { + ArgumentNullException.ThrowIfNull(texts); + ArgumentNullException.ThrowIfNull(error); + var (field, code) = TableValues.SplitError(error); + if (field is not null && field.Contains('.', StringComparison.Ordinal)) + { + code = error; + } + + var parts = code.Split(':', 2); + if (!texts.Contains(parts[0])) + { + return code; + } + + return parts.Length == 1 ? texts[parts[0]] : texts.Format(parts[0], parts[1]); + } + + /// A message of a step of the closing: code|value|value, a leading ! a warning, - an error. + /// The texts. + /// The message. + /// The tone and the text. + public static (KhTone Tone, string Text) Message(ITexts texts, string message) + { + ArgumentNullException.ThrowIfNull(texts); + ArgumentNullException.ThrowIfNull(message); + var tone = message.StartsWith('!') ? KhTone.Warning : message.StartsWith('-') ? KhTone.Error : KhTone.Neutral; + var parts = message.TrimStart('!', '-').Split('|'); + if (!texts.Contains(parts[0])) + { + return (tone, string.Join(" ", parts)); + } + + return (tone, parts.Length == 1 ? texts[parts[0]] : texts.Format(parts[0], [.. parts.Skip(1).Cast()])); + } + + /// The tone of the state of a step of the closing. + /// The state. + /// The tone. + public static KhTone ToneOf(ClosingStepStatus status) => status switch + { + ClosingStepStatus.Done or ClosingStepStatus.Passed => KhTone.Ok, + ClosingStepStatus.ToVerify => KhTone.Warning, + ClosingStepStatus.Failed => KhTone.Error, + _ => KhTone.Neutral, + }; + + /// The tone of the state of a fixed asset. + /// The state. + /// The tone. + public static KhTone ToneOf(AssetStatus status) => status switch + { + AssetStatus.Active => KhTone.Ok, + AssetStatus.Depreciated => KhTone.Info, + _ => KhTone.Neutral, + }; + + /// The tone of the check of an Intrastat line. + /// The check. + /// The tone. + public static KhTone ToneOf(IntrastatCheck check) => check switch + { + IntrastatCheck.Ok => KhTone.Ok, + IntrastatCheck.OutsideEu => KhTone.Neutral, + _ => KhTone.Warning, + }; + + /// The tone of a declaration of intent. + /// The declaration. + /// Whether it is above the warning share. + /// The tone. + public static KhTone ToneOf(IntentDeclaration declaration, bool warning) + { + ArgumentNullException.ThrowIfNull(declaration); + return declaration.Status switch + { + IntentStatus.Active => warning ? KhTone.Warning : KhTone.Ok, + IntentStatus.Exhausted => KhTone.Neutral, + _ => KhTone.Error, + }; + } + + /// A percent for the screens. + /// The texts. + /// The value. + /// The text. + public static string Percent(ITexts texts, decimal value) + { + ArgumentNullException.ThrowIfNull(texts); + return value.ToString("#,##0.##", texts.Culture) + "%"; + } + + /// The change from one year to the next, as a percent. + /// The texts. + /// The year. + /// The year before. + /// The text, empty when the year before is zero. + public static string Delta(ITexts texts, decimal current, decimal previous) + { + ArgumentNullException.ThrowIfNull(texts); + if (previous == 0m) + { + return string.Empty; + } + + var delta = Math.Round((current - previous) / Math.Abs(previous) * 100m, 1, MidpointRounding.AwayFromZero); + return (delta > 0m ? "+" : string.Empty) + delta.ToString("0.0", texts.Culture) + "%"; + } +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 5472296..f857ba9 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -436,6 +436,13 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } .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); } } +/* Financial statements (M10): the two halves side by side, the legal descriptions wrapping beside fixed amounts. */ +.kh-stmt-two { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; align-items: start; } +table.grid.kh-stmt { table-layout: fixed; width: 100%; } +table.grid.kh-stmt td:first-child { white-space: normal; overflow-wrap: anywhere; height: auto; padding-top: 5px; padding-bottom: 5px; } +.kh-stmt col.amt { width: 104px; } +.kh-stmt col.pct { width: 58px; } +@media (max-width: 1100px) { .kh-stmt-two { grid-template-columns: minmax(0, 1fr); } } /* Schedule and treasury (M8): aging tiles, the remittance form beside its effects, the bars of the cash flow. */ .kh-aging { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin: 10px 0 12px; } diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index ca438a5..0d9ba8d 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -87,6 +87,8 @@ public sealed class MappingTests "payments", "payment_lines", "remittances", "remittance_lines", "sdd_mandates", "bank_statements", "bank_statement_lines", "bank_match_rules", "dunning_levels", "dunning_letters", "e_invoices", "e_invoice_notifications", "e_invoice_inbox", "e_invoice_channels", "e_invoice_routing", "e_invoice_conservation", + "fixed_asset_categories", "fixed_assets", "fixed_asset_movements", "accruals", "closing_runs", "closing_steps", "closing_prints", + "intrastat_lists", "intrastat_list_lines", "intent_declarations", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/ItalyFiscalPackTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/ItalyFiscalPackTests.cs index edc2c5f..67e5a9a 100644 --- a/tests/Khaemhat.Fiscal.Italy.Tests/ItalyFiscalPackTests.cs +++ b/tests/Khaemhat.Fiscal.Italy.Tests/ItalyFiscalPackTests.cs @@ -22,6 +22,8 @@ public sealed class ItalyFiscalPackTests Assert.IsTrue(Pack.Supports()); Assert.IsTrue(Pack.Supports()); Assert.IsTrue(Pack.Supports()); + Assert.IsTrue(Pack.Supports()); + Assert.IsTrue(Pack.Supports()); Assert.AreSame(Pack.TaxCodes, Pack.GetFeature()); Assert.AreSame(Pack.Calendar, Pack.Require()); } @@ -29,10 +31,10 @@ public sealed class ItalyFiscalPackTests [TestMethod] public void Require_OfAFeatureNotYetDelivered_SaysWhichOne() { - var ex = Assert.ThrowsExactly(() => Pack.Require()); + var ex = Assert.ThrowsExactly(() => Pack.Require()); Assert.AreEqual("IT", ex.CountryCode); - Assert.AreEqual(nameof(IIntrastatExporter), ex.Feature); + Assert.AreEqual(nameof(IFutureFeature), ex.Feature); } [TestMethod] @@ -49,6 +51,9 @@ public sealed class ItalyFiscalPackTests [TestMethod] public void Catalog_RefusesTwoPacksForOneCountry() => Assert.ThrowsExactly(() => new FiscalPackCatalog([Pack, new ItalyFiscalPack()])); + + /// A feature no pack delivers. + public interface IFutureFeature; } [TestClass] diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/YearEndRulesTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/YearEndRulesTests.cs new file mode 100644 index 0000000..72d43a6 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/YearEndRulesTests.cs @@ -0,0 +1,195 @@ +using System.Text; +using Khaemhat.Core.Accounting; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +[TestClass] +public sealed class CeeSchemaItTests +{ + private static readonly CeeSchemaIt Schema = new(); + + [TestMethod] + public void Ordinary_HasTheLinesOfTheCivilCode() + { + var assets = Schema.Lines(FinancialStatementKind.Assets, FinancialStatementForm.Ordinary); + var liabilities = Schema.Lines(FinancialStatementKind.Liabilities, FinancialStatementForm.Ordinary); + var income = Schema.Lines(FinancialStatementKind.IncomeStatement, FinancialStatementForm.Ordinary); + + Assert.IsTrue(assets.Any(l => l.Code == "C.II.5-quater")); + Assert.IsTrue(liabilities.Single(l => l.Code == "A.IX").CreditNormal); + Assert.AreEqual("21", income[^1].Code); + CollectionAssert.AreEqual(new[] { "A", "B", "C", "D", "20" }, income[^1].Totals!.ToArray()); + Assert.IsFalse(income.Single(l => l.Code == "C.17").CreditNormal); + Assert.IsTrue(income.Single(l => l.Code == "C.17-bis").CreditNormal); + } + + [TestMethod] + public void Lines_HaveUniqueCodesAndKnownParents() + { + foreach (var kind in Enum.GetValues()) + { + foreach (var form in Enum.GetValues()) + { + var lines = Schema.Lines(kind, form); + var codes = lines.Select(l => l.Code).ToHashSet(StringComparer.Ordinal); + + Assert.HasCount(lines.Count, codes, $"{kind} {form}"); + Assert.IsTrue(lines.All(l => l.ParentCode is null || codes.Contains(l.ParentCode)), $"{kind} {form}"); + } + } + } + + [TestMethod] + [DataRow("B.II.4", FinancialStatementKind.Assets, "B.II")] + [DataRow("C.II.5-bis", FinancialStatementKind.Assets, "C.II")] + [DataRow("D.7", FinancialStatementKind.Liabilities, "D")] + [DataRow("A.IX", FinancialStatementKind.Liabilities, "A.IX")] + [DataRow("B.9.a", FinancialStatementKind.IncomeStatement, "B.9")] + [DataRow("B.10.d", FinancialStatementKind.IncomeStatement, "B.10")] + [DataRow("C.17-bis", FinancialStatementKind.IncomeStatement, "C.17-bis")] + public void Abbreviated_CollapsesToTheRomanNumerals(string code, FinancialStatementKind kind, string expected) + { + Assert.AreEqual(expected, Schema.Collapse(code, kind, FinancialStatementForm.Abbreviated)); + Assert.AreEqual(expected, Schema.Collapse(code, kind, FinancialStatementForm.Micro)); + Assert.AreEqual(code, Schema.Collapse(code, kind, FinancialStatementForm.Ordinary)); + } + + [TestMethod] + public void Collapse_OfAnUnknownCodeIsNull() => + Assert.IsNull(Schema.Collapse("Z.9", FinancialStatementKind.Assets, FinancialStatementForm.Ordinary)); + + [TestMethod] + public void EveryLineOfTheChart_IsInTheSchema() + { + var template = new ItalianLedgerTemplate(); + var missing = template.Accounts + .Where(a => !string.IsNullOrEmpty(a.StatementLine)) + .Where(a => Schema.Collapse(a.StatementLine!, KindOf(a.Nature), FinancialStatementForm.Ordinary) is null) + .Select(a => a.Code + " " + a.StatementLine) + .ToList(); + + Assert.IsEmpty(missing, string.Join(", ", missing)); + } + + [TestMethod] + public void Reclassifications_ReferToKnownLines() + { + foreach (var kind in Enum.GetValues()) + { + var lines = Schema.Reclassification(kind); + var codes = new HashSet(StringComparer.Ordinal); + foreach (var line in lines) + { + var schema = Schema.Lines(line.Source, FinancialStatementForm.Ordinary).Select(l => l.Code).ToHashSet(); + Assert.IsTrue(line.Lines.All(schema.Contains), line.Code); + Assert.IsTrue((line.Totals ?? []).All(t => codes.Contains(t.TrimStart('-'))), line.Code); + codes.Add(line.Code); + } + } + } + + private static FinancialStatementKind KindOf(AccountNature nature) => nature switch + { + AccountNature.Asset => FinancialStatementKind.Assets, + AccountNature.Liability => FinancialStatementKind.Liabilities, + _ => FinancialStatementKind.IncomeStatement, + }; +} + +[TestClass] +public sealed class IntrastatExporterItTests +{ + private static readonly IntrastatExporterIt Exporter = new(); + + [TestMethod] + [DataRow(49_999.99, 0, IntrastatPeriodicity.Quarterly, IntrastatPeriodicity.Quarterly)] + [DataRow(50_000, 0, IntrastatPeriodicity.Monthly, IntrastatPeriodicity.Quarterly)] + [DataRow(0, 60_000, IntrastatPeriodicity.Quarterly, IntrastatPeriodicity.Monthly)] + public void Sales_AreMonthlyFrom50000PerQuarter(double goods, double services, IntrastatPeriodicity g, IntrastatPeriodicity s) + { + var due = Exporter.Due(IntrastatFlow.Sales, (decimal)goods, (decimal)services); + + Assert.AreEqual(g, due.Goods); + Assert.AreEqual(s, due.Services); + } + + [TestMethod] + public void Purchases_AreDueOnlyAboveTheThresholds() + { + var below = Exporter.Due(IntrastatFlow.Purchases, 349_999m, 99_999m); + var goods = Exporter.Due(IntrastatFlow.Purchases, 350_000m, 0m); + var services = Exporter.Due(IntrastatFlow.Purchases, 0m, 100_000m); + + Assert.AreEqual(IntrastatPeriodicity.NotDue, below.List); + Assert.AreEqual(IntrastatPeriodicity.Monthly, goods.Goods); + Assert.AreEqual(IntrastatPeriodicity.NotDue, goods.Services); + Assert.AreEqual(IntrastatPeriodicity.Monthly, services.List); + } + + [TestMethod] + [DataRow("73043100", true)] + [DataRow("7304310", false)] + [DataRow("7304310A", false)] + [DataRow(null, false)] + public void Nomenclature_IsEightDigits(string? code, bool valid) => Assert.AreEqual(valid, Exporter.ValidNomenclature(code)); + + [TestMethod] + public void MemberStates_AreTheTwentySevenWithGreeceAsGR() + { + Assert.HasCount(27, Exporter.MemberStates); + Assert.Contains("GR", Exporter.MemberStates); + Assert.DoesNotContain("NO", Exporter.MemberStates); + } + + [TestMethod] + public void File_HasAFrontispieceAndOneFixedRecordPerIncludedLine() + { + var list = new IntrastatList { Flow = IntrastatFlow.Sales, Year = 2026, Period = 10, Periodicity = IntrastatPeriodicity.Monthly, Progressive = 3 }; + IntrastatListLine[] lines = + [ + new() { Id = 1, Section = IntrastatSection.Goods, CountryCode = "AT", VatNumber = "U12345678", Amount = 12_400.40m, NomenclatureCode = "73043100", TransactionNature = "11", NetMass = 820m, DeliveryTerms = "DAP", TransportMode = "3", Province = "TO" }, + new() { Id = 2, Section = IntrastatSection.Services, CountryCode = "DE", VatNumber = "123456789", Amount = 900m, NomenclatureCode = "711210", SupplyMode = "I", PaymentMode = "B", DocumentNumber = "FV 2026/0101", DocumentDate = new DateOnly(2026, 10, 12) }, + new() { Id = 3, Section = IntrastatSection.Goods, CountryCode = "NO", Amount = 5_000m, Check = IntrastatCheck.OutsideEu }, + ]; + + var text = Encoding.ASCII.GetString(Exporter.Write(new IntrastatReturn(list, lines, "01234567890"))); + var records = text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); + + Assert.HasCount(3, records); + Assert.IsTrue(records.All(r => r.Length == IntrastatExporterIt.RecordLength)); + Assert.StartsWith("EUROX01234567890000003000000C26M10", records[0]); + Assert.Contains("000010000000012400", records[0]); + Assert.StartsWith("EUROX01234567890000003100001AT", records[1]); + Assert.StartsWith("EUROX01234567890000003300002DE", records[2]); + Assert.AreEqual("SCAMBI.CEE", Exporter.FileName(new IntrastatReturn(list, lines, "01234567890"))); + } +} + +[TestClass] +public sealed class MinisterialCoefficientsTests +{ + [TestMethod] + public void Coefficients_UseAccountsOfTheChart() + { + var accounts = new ItalianLedgerTemplate().Accounts.Select(a => a.Code).ToHashSet(StringComparer.Ordinal); + var missing = MinisterialCoefficients.All + .SelectMany(c => new[] { c.AssetAccount, c.FundAccount, c.DepreciationAccount }) + .Where(code => !accounts.Contains(code)) + .ToList(); + + Assert.IsEmpty(missing, string.Join(", ", missing)); + Assert.HasCount(MinisterialCoefficients.All.Count, MinisterialCoefficients.All.Select(c => c.Code).Distinct().ToList()); + } + + [TestMethod] + public void Cars_HaveTheTaxLimits() + { + var car = MinisterialCoefficients.All.Single(c => c.Code == "AUV"); + + Assert.AreEqual(25m, car.Rate); + Assert.AreEqual(18_075.99m, car.CostLimit); + Assert.AreEqual(20m, car.DeductiblePercent); + Assert.AreSame(MinisterialCoefficients.All, new FixedAssetRulesIt().Coefficients); + } +} diff --git a/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs b/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs index 4ec9def..3aa3044 100644 --- a/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs +++ b/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs @@ -50,11 +50,12 @@ internal static partial class TestInstance /// Builds and starts an instance with changes to its services (fake external services). /// The changes. /// Cancellation. + /// More arguments, which win over the defaults (another system database). /// The running instance, its address and the company code. public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync( - Action? configureServices, CancellationToken cancellationToken) + Action? configureServices, CancellationToken cancellationToken, params string[] extra) { - var app = KhaemhatApp.Build(Arguments(out var company), configureServices); + var app = KhaemhatApp.Build(Arguments(out var company, extra), configureServices); await app.StartAsync(cancellationToken); var address = new Uri(app.Urls.First()); using var client = new HttpClient { BaseAddress = address }; diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index e090f77..4254b45 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -6,6 +6,7 @@ using Khaemhat.Core.Accounting; using Khaemhat.Core.Tax; using Khaemhat.Web.Ledger; using Khaemhat.Web.Shell; +using Khaemhat.Web.YearEnd; namespace Khaemhat.Web.Tests.Shell; @@ -118,6 +119,36 @@ public sealed partial class LocalizationRulesTests Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k)))); } + [TestMethod] + public void YearEndEnumsErrorsAndMessages_HaveTexts() + { + var keys = new List(); + foreach (var type in new[] + { + typeof(AssetStatus), typeof(AssetClass), typeof(AssetMovementKind), typeof(IntrastatFlow), typeof(IntrastatPeriodicity), + typeof(IntrastatSection), typeof(IntrastatCheck), typeof(IntrastatStatus), typeof(Khaemhat.Core.Parties.IntentStatus), + typeof(Khaemhat.Core.Parties.IntentDirection), typeof(ClosingStepStatus), typeof(AccrualKind), + typeof(Khaemhat.Fiscal.Abstractions.FinancialStatementForm), typeof(Khaemhat.Fiscal.Abstractions.ReclassificationKind), + typeof(Khaemhat.Core.Tables.FiscalYearStatus), + }) + { + keys.AddRange(Enum.GetValues(type).Cast().Select(YearEndScreens.EnumKey)); + } + + keys.AddRange(typeof(Khaemhat.Application.YearEnd.YearEndErrors).GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!)); + keys.AddRange(Enumerable.Range(1, Khaemhat.Application.YearEnd.ClosingService.StepCount) + .SelectMany(n => new[] { "YearEnd.Closing.Steps." + n + ".Title", "YearEnd.Closing.Steps." + n + ".Detail" })); + keys.AddRange(Khaemhat.Core.Accounting.FinancialRatios.Compute(new RatioInputs(0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 365)) + .SelectMany(r => new[] { "YearEnd.Statements.RatioNames." + r.Code, "YearEnd.Statements.RatioFormulas." + r.Code })); + + // The messages of the closing steps, as the service writes them: "code|value", "!code" a warning, "-code" an error. + var service = File.ReadAllText(Path.Combine(Repository.Root, "src", "Khaemhat.Application", "YearEnd", "ClosingService.cs")); + keys.AddRange(MessagePattern().Matches(service).Select(m => m.Groups[1].Value).Distinct()); + + Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k)))); + } + [TestMethod] public void TextFiles_AvoidCharactersGiteaFlagsAsAmbiguous() { @@ -295,6 +326,9 @@ 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|Ledger)\\.[A-Za-z0-9_.]+)\"")] + [GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport|Ledger|YearEnd)\\.[A-Za-z0-9_.]+)\"")] private static partial Regex KeyPattern(); + + [GeneratedRegex(@"""[!-]?(closing\.[a-z-]+)[|""]")] + private static partial Regex MessagePattern(); } diff --git a/tests/Khaemhat.Web.Tests/YearEnd/YearEndTests.cs b/tests/Khaemhat.Web.Tests/YearEnd/YearEndTests.cs new file mode 100644 index 0000000..dc30ff5 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/YearEnd/YearEndTests.cs @@ -0,0 +1,311 @@ +using System.IO.Compression; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Application.Seeding; +using Khaemhat.Application.YearEnd; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.YearEnd; + +/// +/// The year end on a real instance (issues #82-#87): the guided closing of the demo year from the checks to the lock, +/// with the statements that balance before and the accounts that are zero after; the life of a fixed asset; the +/// ceiling of a declaration of intent that stops an invoice; the Intrastat list of the intra-EU sale and its file; the +/// export for the accountant. On SQLite, and on PostgreSQL when KHAEMHAT_TEST_PG names a server. +/// +[TestClass] +public sealed class YearEndTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + public TestContext TestContext { get; set; } = null!; + + private static DateOnly Today => DateOnly.FromDateTime(DateTime.Now); + + [TestMethod] + [DataRow("sqlite")] + [DataRow("postgres")] + public async Task DemoYear_ClosesFromTheChecksToTheLock(string engine) + { + var (app, company) = await StartAsync(engine); + await using (app) + { + await SeedAsync(app.Services, company); + var closing = app.Services.GetRequiredService(); + var statements = app.Services.GetRequiredService(); + var queries = app.Services.GetRequiredService(); + var year = Today.Year; + + // Before the closing the statements balance, the result included, and every account has its line. + var before = await statements.StatementsAsync(Root, company, year, FinancialStatementForm.Ordinary); + TestContext.WriteLine($"Assets {before.TotalAssets.Current} liabilities {before.TotalLiabilities.Current} result {before.Result.Current}"); + Assert.IsEmpty(before.Unmapped, string.Join(", ", before.Unmapped.Select(u => u.Code + " " + u.Balance))); + Assert.IsTrue(before.Balanced, $"Assets {before.TotalAssets.Current} liabilities {before.TotalLiabilities.Current}"); + Assert.IsGreaterThan(0m, before.TotalAssets.Current); + var abbreviated = await statements.StatementsAsync(Root, company, year, FinancialStatementForm.Abbreviated); + Assert.AreEqual(before.TotalAssets.Current, abbreviated.TotalAssets.Current, "The forms differ in detail, not in totals."); + Assert.AreEqual(before.Result.Current, abbreviated.Result.Current); + Assert.HasCount(11, await statements.RatiosAsync(Root, company, year)); + Assert.IsNotEmpty(await statements.ReclassifiedAsync(Root, company, year, ReclassificationKind.Financial)); + Assert.IsNotEmpty(await statements.ReclassifiedAsync(Root, company, year, ReclassificationKind.ValueAdded)); + + // The nine steps in order; the third undone and run again on the way. + var view = await closing.GetAsync(Root, company); + Assert.AreEqual(year.ToString(System.Globalization.CultureInfo.InvariantCulture), view.Year.Code); + var yearId = view.Year.Id; + FinancialStatements? adjusted = null; + for (var number = 1; number <= ClosingService.StepCount; number++) + { + view = await closing.RunStepAsync(Root, company, yearId, number); + if (number == 3) + { + view = await closing.UndoStepAsync(Root, company, yearId, 3); + Assert.AreEqual(ClosingStepStatus.Pending, view.Steps[2].Status); + view = await closing.RunStepAsync(Root, company, yearId, 3); + } + + var step = view.Steps[number - 1]; + TestContext.WriteLine($"{number}: {step.Status} {step.Entries} {step.Amount} {step.Messages?.Replace('\n', ' ')}"); + Assert.AreNotEqual(ClosingStepStatus.Failed, step.Status, step.Messages); + Assert.AreNotEqual(ClosingStepStatus.Pending, step.Status); + if (number == 5) + { + adjusted = await statements.StatementsAsync(Root, company, year, FinancialStatementForm.Ordinary); + Assert.IsTrue(adjusted.Balanced, "The adjustments keep the statements balanced."); + } + + if (number == 7) + { + // Every account is zero once the income statement and the balance sheet are closed. + var closed = await queries.TrialBalanceAsync(Root, company, new DateOnly(year, 1, 1), new DateOnly(year, 12, 31)); + var open = closed.Lines.Where(l => l.Level == 3 && l.Closing != 0m).Select(l => l.Code + " " + l.Closing).ToList(); + Assert.IsEmpty(open, string.Join(", ", open)); + } + } + + Assert.IsNull(view.NextStep); + Assert.AreEqual(adjusted!.Result.Current, view.Run!.Result, "The result of step 6 is the result of the adjusted statements."); + + // The next year opens with the same balances, the accruals reversed. + var next = view.Years.Single(y => y.StartDate == new DateOnly(year + 1, 1, 1)); + var opening = await queries.TrialBalanceAsync(Root, company, next.StartDate, next.StartDate); + Assert.IsTrue(opening.Balanced); + Assert.IsGreaterThan(0m, opening.TotalDebit); + var reopened = await statements.StatementsAsync(Root, company, year + 1, FinancialStatementForm.Ordinary); + Assert.AreEqual(adjusted.TotalAssets.Current, reopened.TotalAssets.Previous, "The year before of the next year is this year."); + Assert.IsTrue(reopened.Balanced, "The next year opens with the balances of the year closed."); + + // The final prints are kept, the last step cannot be undone, then the lock. + Assert.IsGreaterThanOrEqualTo(3, view.Prints.Count); + foreach (var print in view.Prints) + { + var file = await closing.PrintAsync(Root, company, print.Id); + Assert.IsTrue(Encoding.ASCII.GetString(file.Content, 0, 5).StartsWith("%PDF", StringComparison.Ordinal), print.FileName); + } + + var irreversible = await Assert.ThrowsExactlyAsync(() => closing.UndoStepAsync(Root, company, yearId, ClosingService.StepCount)); + StringAssert.Contains(string.Join(" ", irreversible.Errors), YearEndErrors.StepIrreversible); + view = await closing.LockAsync(Root, company, yearId); + Assert.AreEqual(FiscalYearStatus.Closed, view.Year.Status); + Assert.AreEqual(ClosingStatus.Locked, view.Run!.Status); + await Assert.ThrowsExactlyAsync(() => closing.LockAsync(Root, company, yearId)); + + // The export for the accountant: chart, trial balance, journal and statements. + var export = await statements.AccountantExportAsync(Root, company, year); + using var zip = new ZipArchive(new MemoryStream(export.Content)); + CollectionAssert.IsSubsetOf( + new[] { "piano-dei-conti.csv", "bilancio-di-verifica.csv", "movimenti.csv", "stato-patrimoniale.csv", "conto-economico.csv" }, + zip.Entries.Select(e => e.Name).ToList()); + await app.StopAsync(); + } + } + + [TestMethod] + [DataRow("sqlite")] + [DataRow("postgres")] + public async Task FixedAsset_IsDepreciated_UndoneAndDisposed(string engine) + { + var (app, company) = await StartAsync(engine); + await using (app) + { + await SeedAsync(app.Services, company); + var assets = app.Services.GetRequiredService(); + var year = Today.Year; + var rows = await assets.ListAsync(Root, company); + Assert.HasCount(4, rows, "The demo assets."); + var categories = await assets.CategoriesAsync(Root, company); + var edp = categories.Single(c => c.Code == "EDP"); + + // A computer bought this year: half the rate in the first year, civil and fiscal alike. + var view = await assets.SaveAsync(Root, company, new AssetInput(null, null, "Notebook di prova", edp.Id, new DateOnly(year, 1, 10), new DateOnly(year, 1, 10), 1_200m)); + Assert.AreEqual(AssetStatus.Active, view.Asset.Status); + var line = (await assets.DepreciationAsync(Root, company, year)).Single(l => l.AssetId == view.Asset.Id); + Assert.AreEqual(Math.Round(1_200m * edp.CivilRate / 100m / 2m, 2), line.Civil); + Assert.AreEqual(line.Civil, line.Fiscal); + + var posted = await assets.PostDepreciationAsync(Root, company, year); + Assert.IsGreaterThan(0m, posted); + Assert.IsTrue((await assets.DepreciationAsync(Root, company, year)).All(l => l.Posted || l.Civil == 0m)); + await Assert.ThrowsExactlyAsync(() => assets.DeleteAsync(Root, company, view.Asset.Id)); + await assets.UndoDepreciationAsync(Root, company, year); + Assert.IsTrue((await assets.DepreciationAsync(Root, company, year)).All(l => !l.Posted)); + + // The van sold: the share of the year to the date, then the gain or the loss. + var van = rows.Single(r => r.Category.Code == "AUC").Asset; + var sold = await assets.DisposeAsync(Root, company, van.Id, new DisposalInput(Today, 15_000m)); + Assert.AreEqual(AssetStatus.Disposed, sold.Asset.Status); + Assert.IsTrue(sold.Movements.Any(m => m.Kind == AssetMovementKind.Disposal)); + await Assert.ThrowsExactlyAsync(() => assets.DisposeAsync(Root, company, van.Id, new DisposalInput(Today, 1m))); + var register = await assets.PrintRegisterAsync(Root, company, year); + Assert.IsGreaterThan(1000, register.Content.Length); + await app.StopAsync(); + } + } + + [TestMethod] + [DataRow("sqlite")] + [DataRow("postgres")] + public async Task DeclarationOfIntent_StopsTheInvoiceAboveTheCeiling(string engine) + { + var (app, company) = await StartAsync(engine); + await using (app) + { + await SeedAsync(app.Services, company); + var intents = app.Services.GetRequiredService(); + var received = await intents.ListAsync(Root, company, IntentDirection.Received, Today.Year); + var idrotermica = received.Single(r => r.PartyName == "Idrotermica Piemonte S.r.l."); + Assert.IsGreaterThan(0m, idrotermica.Declaration.Used, "The demo invoice under the declaration uses the ceiling."); + var coverage = await intents.CoverageAsync(Root, company, idrotermica.Declaration.PartyId, Today); + Assert.AreEqual(idrotermica.Declaration.Id, coverage.Declaration?.Id); + + // An invoice above what is left is refused when it is issued; a customer without declaration too. + var documents = app.Services.GetRequiredService(); + var refused = await InvoiceAsync(app.Services, company, idrotermica.Declaration.PartyId, 1_000_000m); + var error = await Assert.ThrowsExactlyAsync(() => documents.ConfirmAsync(Root, company, refused.Family, refused.Header.Id)); + StringAssert.Contains(string.Join(" ", error.Errors), YearEndErrors.CeilingExceeded); + + long rossi; + await using (var uow = await app.Services.GetRequiredService().CreateAsync(DatabaseScope.Company(company))) + { + rossi = (await uow.Repository().FindAsync(Query.For().Where(p => p.Name == "Rossi Impianti S.r.l.")))!.Id; + } + + var none = await InvoiceAsync(app.Services, company, rossi, 1m); + error = await Assert.ThrowsExactlyAsync(() => documents.ConfirmAsync(Root, company, none.Family, none.Header.Id)); + StringAssert.Contains(string.Join(" ", error.Errors), YearEndErrors.NoDeclaration); + + // Within the ceiling the invoice goes, and the ceiling used grows by its amount. + var small = await InvoiceAsync(app.Services, company, idrotermica.Declaration.PartyId, 1m); + await documents.ConfirmAsync(Root, company, small.Family, small.Header.Id); + var after = (await intents.ListAsync(Root, company, IntentDirection.Received, Today.Year)).Single(r => r.Declaration.Id == idrotermica.Declaration.Id); + Assert.AreEqual(idrotermica.Declaration.Used + small.Lines.Sum(l => l.TaxableAmount), after.Declaration.Used); + var register = await intents.PrintRegisterAsync(Root, company, IntentDirection.Received, Today.Year); + Assert.IsGreaterThan(500, register.Content.Length); + await app.StopAsync(); + } + } + + [TestMethod] + [DataRow("sqlite")] + [DataRow("postgres")] + public async Task Intrastat_ListOfTheIntraEuSale_IsGeneratedExportedAndSent(string engine) + { + var (app, company) = await StartAsync(engine); + await using (app) + { + await SeedAsync(app.Services, company); + var intrastat = app.Services.GetRequiredService(); + var view = await intrastat.GenerateAsync(Root, company, IntrastatFlow.Sales, Today.Year, IntrastatPeriodicity.Monthly, Today.Month); + foreach (var l in view.Lines) + { + TestContext.WriteLine($"{l.Section} {l.CountryCode} {l.VatNumber} {l.NomenclatureCode} {l.Amount} {l.NetMass} {l.Check}"); + } + + var austria = view.Lines.Where(l => l.CountryCode == "AT").ToList(); + Assert.IsNotEmpty(austria, "The sale to Bergwerk Bau."); + Assert.IsTrue(austria.All(l => l.Section == IntrastatSection.Goods && l.NetMass > 0m && l.Check == IntrastatCheck.Ok)); + Assert.AreEqual(view.Lines.Where(l => l.Section == IntrastatSection.Goods).Sum(l => l.Amount), view.List.GoodsAmount); + + var file = await intrastat.ExportAsync(Root, company, view.List.Id); + var text = Encoding.ASCII.GetString(file.Content); + StringAssert.StartsWith(text, "EUROX"); + StringAssert.Contains(text, "AT"); + await intrastat.MarkSentAsync(Root, company, view.List.Id, "26111312345"); + var sent = await intrastat.GetAsync(Root, company, view.List.Id); + Assert.AreEqual(IntrastatStatus.Sent, sent!.List.Status); + await Assert.ThrowsExactlyAsync(() => intrastat.DeleteLineAsync(Root, company, austria[0].Id)); + await app.StopAsync(); + } + } + + private async Task<(Microsoft.AspNetCore.Builder.WebApplication App, string Company)> StartAsync(string engine) + { + if (engine == "sqlite") + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + return (app, company); + } + + var server = Environment.GetEnvironmentVariable("KHAEMHAT_TEST_PG"); + if (string.IsNullOrEmpty(server)) + { + Assert.Inconclusive("KHAEMHAT_TEST_PG is not set: PostgreSQL test skipped."); + } + + var root = server[..(server.LastIndexOf('/') + 1)]; + var id = Guid.NewGuid().ToString("N")[..8]; + var (pgApp, _, pgCompany) = await TestInstance.StartAsync(null, CancellationToken.None, "--KHAEMHAT_SYSTEM_DB=" + root + "khs_" + id); + TestContext.WriteLine("PostgreSQL system database khs_" + id); + return (pgApp, pgCompany); + } + + private static async Task InvoiceAsync(IServiceProvider services, string company, long partyId, decimal quantity) + { + var engine = services.GetRequiredService(); + var editor = services.GetRequiredService(); + long item; + long ni8c; + await using (var uow = await services.GetRequiredService().CreateAsync(DatabaseScope.Company(company))) + { + item = (await uow.Repository().FindAsync(Query.For().Where(i => i.IsDemo && i.Kind == ItemKind.Goods).OrderBy(i => i.Id)))!.Id; + ni8c = (await uow.Repository().FindAsync(Query.For().Where(t => t.Code == "NI8C")))!.Id; + } + + var record = await engine.NewAsync(Root, company, "FI"); + record.Header.DocumentDate = Today; + await editor.ApplyPartyAsync(Root, company, record, partyId); + var line = new SaleDocumentLine { Quantity = quantity }; + await editor.FillLineAsync(Root, company, record, line, item); + line.TaxCodeId = ni8c; + record.Lines.Add(line); + return await engine.SaveAsync(Root, company, record); + } + + private static async Task SeedAsync(IServiceProvider services, string company) + { + var activation = await services.GetRequiredService().ActivateAsync(Root, "KH-TEST-ALL-0000-9999"); + Assert.IsTrue(activation.Succeeded, activation.Outcome); + await services.GetRequiredService().RunAsync(company, SeedKind.Demo); + var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + await services.GetRequiredService().SeedAsync(company, context); + } +}