diff --git a/CHANGELOG.md b/CHANGELOG.md index ca5e538..3938e83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,57 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. ## [Unreleased] +## [0.8.0] - 2026-11-13 + +M8 - Scadenzario e tesoreria. Le partite aperte di clienti e fornitori si chiudono con incassi e pagamenti che si +contabilizzano da soli; distinte RiBa, SDD e bonifici SEPA con il file per l'home banking, presentazione, accredito +e insoluti; riconciliazione dell'estratto conto con abbinamento automatico; solleciti con interessi di mora e flusso +di cassa. + +### Added +- Scadenzario (#69, ADR 0038): partite aperte di clienti e fornitori dalla contabilità con stati, aging in cinque + fasce, filtri, modifica di scadenza, metodo, banca e contestazione, estratto conto della controparte con gli + interessi di mora, export CSV. +- Incassi e pagamenti (#69): su più partite della stessa controparte, totali o parziali, con abbuoni, spese bancarie, + differenze cambio e note di credito; registrazione `INC` o `PAG` nella stessa transazione; annullamento con storno; + la ritenuta d'acconto di una parcella diventa dovuta quando la fattura è saldata. Elenchi *Incassi* e *Pagamenti*. +- Distinte (#70): RiBa nel tracciato CBI (`RibaCbiWriter`), SDD core e B2B in `pain.008.001.08` e bonifici SEPA in + `pain.001.001.09` (`SepaXmlWriter`); candidati con controllo di IBAN, ABI/CAB e mandato; bozza, file, presentazione + su *Effetti all'incasso* o con anticipo *salvo buon fine*, accredito, insoluto con riapertura della partita e + spese come nuova partita del cliente. +- Mandati SDD (#70) con riferimento univoco, schema core o B2B, firma, revoca, sequenza FRST/RCUR. +- Riconciliazione bancaria (#71): import di estratti CSV (colonne riconosciute dall'intestazione), CBI e CAMT.053 + senza doppioni (impronta dei movimenti); proposte con confidenza da partite, incassi e pagamenti registrati, F24, + accrediti e insoluti di distinte e regole salvate (`BankMatcher`); conferma singola o di tutte le proposte dal + 90%; abbinamento manuale, registrazione su conto con regola, *Ignora*, *Annulla abbinamento*; saldo banca, saldo + contabile e differenza. +- Solleciti (#72): tre livelli modificabili con giorni, modello, canali (e-mail, PEC, lettera PDF), interessi di + mora, avviso all'agente e blocco del cliente; proposta di invio che esclude PA, partite contestate e in distinta; + anteprima PDF, invio con la coda di posta, lettere in un PDF unico, registro degli invii; attività programmata + `finance.dunning` nei giorni feriali alle 7:00 per i livelli automatici. +- Interessi di mora del D.Lgs. 231/2002 nel pacchetto italiano (`LatePaymentRulesIt`): tasso BCE del semestre più + 8 punti, 10,15% nel primo semestre 2026 e 10,40% nel secondo. +- Flusso di cassa (#72) a 30-365 giorni per settimana o mese da partite, effetti presentati, ordini non fatturati, + registrazioni ricorrenti e F24, con le fonti selezionabili e il punto più basso. +- Scadenze di incassi e pagamenti e crediti scaduti sulla Home (`TreasuryFeedSource`). +- Menu *Scadenzario* con otto voci; testi in `Resources/it-IT/Treasury.json`; permessi `finance.schedule.*`, + `finance.payment.*`, `finance.bank.reconcile`. +- Tesoreria nei dati di esempio con il modulo FIN (#73): banca, versamento dei soci, incassi e pagamenti, distinta + accreditata con un insoluto, distinta s.b.f. in bozza, mandato, estratto CSV da riconciliare con una regola, primo + sollecito. +- Tabelle `payments`, `payment_lines`, `remittances`, `remittance_lines`, `sdd_mandates`, `bank_statements`, + `bank_statement_lines`, `bank_match_rules`, `dunning_levels`, `dunning_letters`; nuove colonne di + `gl_open_items` e `bank_accounts.creditor_id` (migrazione `M20261113_003`). +- Conti *Perdite su cambi*, *Utili su cambi* e *Interessi di mora attivi* nel piano dei conti PMI standard (240 conti). +- ADR 0038; pagina wiki *Scadenzario* completa con le schermate. + +### Changed +- La rettifica della registrazione di un documento mantiene le partite già incassate o pagate. +- Il menu *Fatturazione elettronica* mostra M9 come milestone. + +### Fixed +- Le strisce di riepilogo non si schiacciano più nelle pagine più alte della finestra. + ## [0.7.0] - 2026-11-13 M7 - Contabilità generale e IVA. Ogni fattura, nota e autofattura si contabilizza da sola nella stessa transazione, diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index ae039ba..b87cc6b 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -732,6 +732,7 @@ Migrazioni applicate in ordine: - `core` 20261112003 `create_documents` (M20261112_003_CreateDocuments) - `core` 20261113001 `create_inventory` (M20261113_001_CreateInventory) - `core` 20261113002 `create_ledger` (M20261113_002_CreateLedger) +- `core` 20261113003 `create_treasury` (M20261113_003_CreateTreasury) #### `attachments` @@ -799,9 +800,91 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `creditor_id` | String(35) | sì | | | - indice unico `ux_bank_accounts_code` su `code` +#### `bank_match_rules` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `name` | String(100) | no | | | +| `pattern` | String(100) | no | | | +| `direction` | String(40) | no | | | +| `account_id` | Int64 | no | | -> `gl_accounts` (Restrict) | +| `template_code` | String(10) | sì | | | +| `entry_description` | String(200) | sì | | | +| `disabled` | Bool | no | `false` | | +| `uses` | Int32 | no | `0` | | +| `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` | | + +#### `bank_statement_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `statement_id` | Int64 | no | | -> `bank_statements` (Cascade) | +| `bank_account_id` | Int64 | no | | | +| `booking_date` | Date | no | | | +| `value_date` | Date | sì | | | +| `amount` | Decimal(19,6) | no | `0` | | +| `description` | String(500) | no | | | +| `reference` | String(60) | sì | | | +| `counterparty_name` | String(140) | sì | | | +| `counterparty_iban` | String(34) | sì | | | +| `bank_code` | String(40) | sì | | | +| `fingerprint` | String(64) | no | | | +| `status` | String(40) | no | | | +| `match_kind` | String(40) | no | | | +| `confidence` | Int32 | no | `0` | | +| `proposal` | String(300) | sì | | | +| `targets` | String(300) | sì | | | +| `party_id` | Int64 | sì | | | +| `rule_id` | Int64 | sì | | | +| `payment_id` | Int64 | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `matched_at` | DateTimeUtc | sì | | | +| `matched_by` | String(100) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_bank_statement_lines_date` su `bank_account_id`, `booking_date` +- indice `ix_bank_statement_lines_statement` su `statement_id` +- indice unico `ux_bank_statement_lines_fingerprint` su `bank_account_id`, `fingerprint` + +#### `bank_statements` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `bank_account_id` | Int64 | no | | -> `bank_accounts` (Restrict) | +| `format` | String(40) | no | | | +| `file_name` | String(200) | sì | | | +| `from_date` | Date | no | | | +| `to_date` | Date | no | | | +| `opening_balance` | Decimal(19,6) | sì | | | +| `closing_balance` | Decimal(19,6) | sì | | | +| `movement_count` | Int32 | no | `0` | | +| `attachment_id` | Int64 | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_bank_statements_account` su `bank_account_id`, `to_date` + #### `carriers` | Colonna | Tipo | Null | Default | Note | @@ -1109,6 +1192,55 @@ Migrazioni applicate in ordine: - indice unico `ux_document_types_code` su `code` +#### `dunning_letters` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Restrict) | +| `level` | Int32 | no | | | +| `sent_on` | Date | no | | | +| `channel` | String(60) | no | | | +| `recipients` | String(300) | sì | | | +| `subject` | String(200) | no | | | +| `item_count` | Int32 | no | `0` | | +| `overdue_amount` | Decimal(19,6) | no | `0` | | +| `interest` | Decimal(19,6) | no | `0` | | +| `status` | String(40) | no | | | +| `attachment_id` | Int64 | sì | | | +| `mail_id` | Int64 | sì | | | +| `sent_by` | String(100) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_dunning_letters_party` su `party_id`, `sent_on` + +#### `dunning_levels` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `level` | Int32 | no | | | +| `days_after_due` | Int32 | no | | | +| `name` | String(100) | no | | | +| `subject` | String(200) | no | | | +| `body` | Text | no | | | +| `channel` | String(60) | no | | | +| `charge_interest` | Bool | no | `false` | | +| `action` | String(40) | no | | | +| `automatic` | 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_dunning_levels_level` su `level` + #### `exchange_rates` | Colonna | Tipo | Null | Default | Note | @@ -1359,10 +1491,20 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `status` | String(40) | no | `'Open'` | | +| `disputed` | Bool | no | `false` | | +| `bank_account_id` | Int64 | sì | | | +| `remittance_id` | Int64 | sì | | | +| `unpaid_count` | Int32 | no | `0` | | +| `parent_id` | Int64 | sì | | | +| `dunning_level` | Int32 | no | `0` | | +| `last_dunning_date` | Date | sì | | | +| `notes` | String(200) | sì | | | - indice `ix_gl_open_items_due` su `closed`, `due_date` - indice `ix_gl_open_items_entry` su `entry_id` - indice `ix_gl_open_items_party` su `party_id`, `closed`, `due_date` +- indice `ix_gl_open_items_schedule` su `direction`, `status`, `due_date` #### `gl_recurring_entries` @@ -2107,6 +2249,25 @@ Migrazioni applicate in ordine: - indice unico `ux_party_sales_terms_party` su `party_id` +#### `payment_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `payment_id` | Int64 | no | | -> `payments` (Cascade) | +| `open_item_id` | Int64 | no | | -> `gl_open_items` (Restrict) | +| `amount` | Decimal(19,6) | no | `0` | | +| `allowance` | Decimal(19,6) | no | `0` | | +| `exchange_difference` | Decimal(19,6) | no | `0` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_payment_lines_item` su `open_item_id` +- indice `ix_payment_lines_payment` su `payment_id` + #### `payment_methods` | Colonna | Tipo | Null | Default | Note | @@ -2165,6 +2326,38 @@ Migrazioni applicate in ordine: - indice unico `ux_payment_terms_code` su `code` +#### `payments` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `direction` | String(40) | no | | | +| `party_id` | Int64 | no | | -> `parties` (Restrict) | +| `payment_date` | Date | no | | | +| `payment_method_id` | Int64 | sì | | | +| `bank_account_id` | Int64 | sì | | | +| `account_id` | Int64 | sì | | | +| `amount` | Decimal(19,6) | no | `0` | | +| `allowance_amount` | Decimal(19,6) | no | `0` | | +| `exchange_difference` | Decimal(19,6) | no | `0` | | +| `fees` | Decimal(19,6) | no | `0` | | +| `reference` | String(60) | sì | | | +| `template_code` | String(10) | sì | | | +| `notes` | String(500) | sì | | | +| `origin` | String(40) | no | | | +| `remittance_id` | Int64 | sì | | -> `remittances` (Restrict) | +| `statement_line_id` | Int64 | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_payments_date` su `direction`, `payment_date` +- indice `ix_payments_party` su `party_id`, `payment_date` + #### `price_lists` | Colonna | Tipo | Null | Default | Note | @@ -2474,6 +2667,64 @@ Migrazioni applicate in ordine: - indice `ix_purchase_orders_status` su `status` - indice unico `ux_purchase_orders_number` su `numerator_id`, `number` +#### `remittance_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `remittance_id` | Int64 | no | | -> `remittances` (Cascade) | +| `open_item_id` | Int64 | no | | -> `gl_open_items` (Restrict) | +| `party_id` | Int64 | no | | | +| `amount` | Decimal(19,6) | no | `0` | | +| `due_date` | Date | no | | | +| `iban` | String(34) | sì | | | +| `mandate_id` | Int64 | sì | | -> `sdd_mandates` (Restrict) | +| `end_to_end_id` | String(35) | sì | | | +| `status` | String(40) | no | | | +| `unpaid_on` | Date | sì | | | +| `unpaid_fees` | Decimal(19,6) | no | `0` | | +| `unpaid_entry_id` | Int64 | sì | | | +| `payment_id` | Int64 | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_remittance_lines_item` su `open_item_id` +- indice `ix_remittance_lines_remittance` su `remittance_id` + +#### `remittances` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `year` | Int32 | no | | | +| `number` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `bank_account_id` | Int64 | no | | -> `bank_accounts` (Restrict) | +| `presentation_date` | Date | no | | | +| `due_until` | Date | no | | | +| `advance` | Bool | no | `false` | | +| `status` | String(40) | no | | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `item_count` | Int32 | no | `0` | | +| `message_id` | String(35) | sì | | | +| `attachment_id` | Int64 | sì | | | +| `file_name` | String(100) | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `credited_on` | Date | sì | | | +| `credit_entry_id` | Int64 | 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 unico `ux_remittances_number` su `year`, `number` + #### `role_permissions` | Colonna | Tipo | Null | Default | Note | @@ -2939,6 +3190,31 @@ Migrazioni applicate in ordine: Chiave primaria: `module`, `version`. +#### `sdd_mandates` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Restrict) | +| `reference` | String(35) | no | | | +| `signature_date` | Date | no | | | +| `scheme` | String(40) | no | | | +| `iban` | String(34) | no | | | +| `bic` | String(11) | sì | | | +| `one_off` | Bool | no | `false` | | +| `last_collection_date` | Date | sì | | | +| `revoked` | Bool | no | `false` | | +| `notes` | String(200) | 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_sdd_mandates_party` su `party_id` +- indice unico `ux_sdd_mandates_reference` su `reference` + #### `shipping_terms` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/MODULES.md b/docs/MODULES.md index cc50ec4..e557545 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -206,14 +206,14 @@ menu *Fatturazione elettronica* se `EINV` è attivo e da *Contabilità* se è at | Voce | Contenuto | |---|---| | Licenza | `FIN` | -| Responsabilità | partite aperte e aging, incassi e pagamenti con abbuoni e differenze cambio, insoluti, distinte RiBa (CBI), SDD (`pain.008`), bonifici SEPA (`pain.001`), riconciliazione bancaria (CSV/CBI/CAMT.053), solleciti a livelli con interessi di mora, flusso di cassa 90 giorni | -| Entità | `OpenItem`, `Payment(+Line)`, `Remittance(+Line)`, `SddMandate`, `BankStatement(+Line)`, `BankMatchRule`, `DunningRun(+Line)`, `DunningLevel` | -| Servizi | `OpenItemService`, `PaymentService`, `RemittanceService`, `SddMandateService`, `BankStatementImportService`, `BankReconciliationService`, `DunningService`, `CashFlowForecastService`, `AgingReportService`, `InstallmentPoster` | -| Maschere e mockup | partite e aging (053, `OpenItemsPage`), registra incasso (054, `PaymentDialog`), distinte (055, `RemittancePage`), solleciti (056, `DunningPage`), riconciliazione (057, `BankReconciliationPage`) | -| Permessi | proposte: `finance.open_item.read`, `finance.payment.write`, `finance.remittance.write`, `finance.dunning.run`, `finance.reconciliation.write` | +| Responsabilità | partite aperte (le `gl_open_items` della contabilità) e aging, incassi e pagamenti con abbuoni, spese e differenze cambio, insoluti, distinte RiBa (CBI), SDD (`pain.008.001.08`), bonifici SEPA (`pain.001.001.09`), mandati, riconciliazione bancaria (CSV/CBI/CAMT.053), solleciti a livelli con interessi di mora, flusso di cassa 30-365 giorni, scadenze sulla Home | +| Entità | `OpenItem` (Ledger), `Payment(+Line)`, `Remittance(+Line)`, `SddMandate`, `BankStatement(+Line)`, `BankMatchRule`, `DunningLevel`, `DunningLetter` | +| Servizi | `ScheduleService`, `PaymentService`, `RemittanceService`, `MandateService`, `BankReconciliationService`, `DunningService` (+ job `finance.dunning`), `CashFlowService`, `TreasuryFeedSource`, `DemoTreasurySeeder`; nel core `AgingCalculator`, `PaymentAllocator`, `BankMatcher`, `SepaXmlWriter`, `CsvStatementReader`, `Camt053Reader`; nel pacchetto italiano `RibaCbiWriter`, `CbiStatementReader`, `LatePaymentRulesIt` (ADR 0038) | +| Maschere e mockup | partite e aging (053, `SchedulePage`), registra incasso (054, `PaymentDialog`), incassi e pagamenti (`PaymentsPage`), distinte (055, `RemittancesPage`), mandati (`MandatesPage`), solleciti (056, `DunningPage`), riconciliazione (057, `ReconciliationPage`), flusso di cassa (`CashFlowPage`) | +| Permessi | `finance.schedule.read`, `finance.schedule.write`, `finance.payment.read`, `finance.payment.write`, `finance.bank.reconcile` | | Log | Contabilità (proposta: SPEC §9.5 non ha una sezione "Tesoreria"); invio solleciti in E-mail/PEC | | Wiki | [Scadenzario](wiki/Scadenzario.md) | -| Milestone | M8 `v0.8.0` | +| Milestone | M8 `v0.8.0` (consegnata) | ### 3.11 EInvoicing — Fatturazione elettronica diff --git a/docs/STATUS.md b/docs/STATUS.md index 18e31f8..c0ac2fc 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:** M8 — Scadenzario e tesoreria (issue #69-#73), da iniziare. M7 chiusa: PR in `main`, tag -`v0.7.0`, immagine e release. -**Prossimo passo:** M8 dall'issue #69. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo +**Milestone corrente:** M9 — Fatturazione elettronica (issue #74-#81), da iniziare. M8 chiusa: PR in `main`, tag +`v0.8.0`, immagine e release. +**Prossimo passo:** M9 dall'issue #74. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile). 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,13 +13,15 @@ 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); chiusura delle partite con -incassi e pagamenti e IVA per cassa (M8). +bilancio dal file `khaemhat-coa.json`; scritture delle rimanenze e libro inventari (M10); 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). ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7. -- ADR 0001-0037. +- ADR 0001-0038. - 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`, @@ -88,6 +90,12 @@ incassi e pagamenti e IVA per cassa (M8). subite, dati CU, bollo virtuale con soglie, prospetto F24 con pagamento (#66); partitari, mastrini, bilancio di verifica, libro giornale (#67); contabilità nei dati di esempio con la liquidazione verificata a mano in un test, wiki *Contabilità*, *IVA* e *Fiscalità italiana* con le schermate (#68). Test: 754 verdi in locale, 23 di PostgreSQL saltati (girano in CI). +- **M8 (chiusa, `v0.8.0`):** scadenzario sulle partite della contabilità con aging, incassi e pagamenti multipli e + parziali con abbuoni, spese, cambi e storno (#69, ADR 0038); distinte RiBa CBI, SDD `pain.008` e bonifici + `pain.001` con presentazione, anticipo s.b.f., accredito e insoluti, mandati SDD (#70); riconciliazione bancaria + CSV/CBI/CAMT.053 senza doppioni con confidenza e regole (#71); solleciti a tre livelli con interessi di mora e job + automatico, flusso di cassa, scadenze sulla Home (#72); tesoreria nei dati di esempio con FIN, wiki *Scadenzario* + con le schermate (#73). Test: 823 verdi in locale, anche quelli di PostgreSQL (18) con un container locale. - 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, diff --git a/docs/adr/0038-scadenzario-e-tesoreria.md b/docs/adr/0038-scadenzario-e-tesoreria.md new file mode 100644 index 0000000..553b1de --- /dev/null +++ b/docs/adr/0038-scadenzario-e-tesoreria.md @@ -0,0 +1,70 @@ +# ADR 0038 - Scadenzario, distinte, riconciliazione bancaria e solleciti + +- **Stato:** accettata +- **Data:** 2026-11-13 +- **Modifica:** SPEC §11.8, §10.3; milestone M8, issue #69, #70, #71, #72 + +## Contesto + +SPEC §11.8 chiede lo scadenzario di clienti e fornitori con incassi e pagamenti (abbuoni, differenze cambio, +insoluti), le distinte RiBa, SDD e bonifici SEPA, i mandati, la riconciliazione bancaria con import CSV/CBI/CAMT.053 +e abbinamento automatico, i solleciti con interessi di mora e il flusso di cassa. Restavano aperti: dove vivono le +partite, come si contabilizzano distinte e insoluti, quali versioni dei tracciati produrre senza librerie esterne +(SPEC §1), come evitare i doppioni dell'estratto conto, come stimare la confidenza degli abbinamenti, dove stanno i +tassi di mora e cosa fa la demo senza licenza FIN. + +## Decisione + +1. **Le partite sono quelle della contabilità.** Lo scadenzario non ha una tabella sua: legge e aggiorna + `gl_open_items`, scritte dalla contabilizzazione dei documenti (ADR 0037). Incassi e pagamenti (`payments`, + `payment_lines`) chiudono le partite e scrivono **subito** la registrazione INC o PAG nella stessa transazione, + con abbuoni, spese e differenze cambio sui conti dei ruoli di registrazione del pacchetto fiscale + (`AllowanceIncome`, `AllowanceExpense`, `BankCharges`, `ExchangeGain`, `ExchangeLoss`). La rettifica di una + registrazione mantiene le partite già saldate. L'annullamento di un incasso storna la registrazione e riapre le + partite; la ritenuta d'acconto di una parcella diventa dovuta quando la fattura è saldata del tutto. +2. **Distinte in quattro passi.** Bozza (le partite passano *In distinta*) → file generato → presentazione → accredito. + RiBa e SDD alla presentazione spostano il credito da *Clienti* a *Effetti all'incasso* (`BillsForCollection`); con + il *salvo buon fine* la banca accredita subito su *Banche c/anticipi* (`BankAdvances`). L'accredito chiude il conto + effetti o l'anticipo. I bonifici SEPA pagano i fornitori già alla presentazione. L'**insoluto** riapre la partita + come *Insoluta*, riprende l'importo dalla banca e trasforma le spese in una **nuova partita** del cliente, così il + recupero passa dallo scadenzario come ogni altra rata. +3. **Tracciati scritti in casa.** RiBa nel tracciato CBI a record di 120 caratteri (IB, 14, 20, 30, 40, 50, 51, 70, + EF), scritto dal pacchetto italiano (`RibaCbiWriter`); SDD in `pain.008.001.08` e bonifici in `pain.001.001.09` + con `XmlWriter` (`SepaXmlWriter`, nel core perché SEPA non è solo italiano). Le specifiche CBI e gli schemi + ISO 20022 non si possono scaricare durante lo sviluppo: i tracciati seguono la documentazione pubblica nota e i + test controllano lunghezze, posizioni, totali e struttura. Il file va caricato a mano nell'home banking; il + collegamento diretto (CBI online, PSD2) è fuori da M8. +4. **Estratti conto senza doppioni.** Ogni movimento importato ha un'**impronta** SHA-256 di conto, data contabile, + importo, descrizione e riferimento normalizzati e del numero di movimenti uguali che lo precedono nello stesso + file; l'impronta è unica per conto, quindi rimportare un file o file sovrapposti salta i movimenti già presenti. + Il CSV si riconosce dalla riga di intestazione (separatore, nomi italiani o inglesi, colonne di entrate e uscite + o importo con segno); il CBI dai record RH/61-64/EF; CAMT.053 dallo spazio dei nomi. +5. **Confidenza a punti.** `BankMatcher` (core) assegna 50 punti all'importo esatto (40 se entro la tolleranza del + candidato, per esempio un insoluto con spese), +30 per un numero di documento, CRO o riferimento trovato nella + descrizione, +30 per le parole chiave del candidato, +25 per l'IBAN della controparte, +20 per il nome, e +10/+5/0/-10 + per la distanza fra le date (≤3, ≤15, ≤60, oltre). Una **regola** salvata che riconosce il testo vale 98. La + proposta si conferma a mano o in blocco sopra la soglia di **90**: sotto, la scelta resta all'utente. +6. **Interessi di mora nel pacchetto.** `ILatePaymentRules` (astrazioni) e `LatePaymentRulesIt` portano il tasso + del D.Lgs. 231/2002: tasso BCE di riferimento del semestre più 8 punti, da una **tabella semestrale** nel codice + (2,15% nel primo semestre 2026, 2,40% nel secondo) che va aggiornata a ogni comunicato del MEF; dopo l'ultima riga + vale l'ultimo tasso. Gli interessi si mostrano nei solleciti e nell'estratto conto, non si contabilizzano. +7. **Solleciti.** Tre livelli predefiniti (7, 20 e 45 giorni) modificabili; canali come flag (e-mail, PEC, lettera + PDF); esclusi PA, partite contestate e in distinta. L'invio usa la coda di posta dell'invio documenti (ADR 0034); le lettere si + scaricano in un PDF unico. L'attività `finance.dunning` (giorni feriali alle 7:00) invia solo i livelli + *Automatico* e solo per e-mail e PEC. +8. **Permessi.** Cinque codici: `finance.schedule.read`/`write`, `finance.payment.read`/`write`, + `finance.bank.reconcile`, tutti nel modulo `FIN`; le registrazioni chiedono anche `ACCT`. +9. **Demo solo con FIN.** `DemoTreasurySeeder` usa gli stessi servizi del programma, che controllano la licenza: + senza il modulo FIN attivo la demo salta la tesoreria invece di scrivere dati che l'azienda non potrebbe vedere. +10. **Flusso di cassa calcolato al momento.** Nessuna tabella: saldo contabile di banche e cassa, partite aperte, + effetti presentati senza anticipo, residuo degli ordini (30 giorni dopo la consegna), registrazioni ricorrenti + che muovono la banca e F24 non pagati; lo scaduto cade nel primo periodo. + +## Conseguenze + +- Contabilità e scadenzario non possono divergere: c'è una sola fonte delle partite. +- La tabella dei tassi di mora è una manutenzione semestrale del pacchetto italiano (gennaio e luglio). +- I tracciati vanno provati con l'home banking reale alla prima installazione; le differenze si correggono nel + pacchetto senza toccare i servizi. +- Il piano dei conti PMI standard guadagna *Perdite su cambi*, *Utili su cambi* e *Interessi di mora attivi* + (240 conti). diff --git a/docs/wiki/Acquisti.md b/docs/wiki/Acquisti.md index 26c7b32..acb0c49 100644 --- a/docs/wiki/Acquisti.md +++ b/docs/wiki/Acquisti.md @@ -11,7 +11,7 @@ per inversione contabile e acquisti dall'estero. > **In questa versione** ci sono ordini, ricevimenti, fatture e note di credito fornitore con protocollo, carico a > magazzino e costo medio, controllo dei prezzi rispetto a ordine e ricevimento, import delle fatture elettroniche e > autofatture in bozza con la loro scadenza. Dalla 0.7 le fatture e le note fornitore **si contabilizzano** da sole -> con i registri IVA (vedi [Contabilità](Contabilita) e [IVA](IVA)). Arrivano più avanti: i **pagamenti** e lo scadenzario (M8), il **file XML** delle autofatture e lo scarico dal canale SDI (M9). +> con i registri IVA (vedi [Contabilità](Contabilita) e [IVA](IVA)). Dalla 0.8 le fatture fornitore **si pagano** dallo [Scadenzario](Scadenzario), anche con le distinte di bonifici SEPA. Arrivano più avanti: il **file XML** delle autofatture e lo scarico dal canale SDI (M9). ## Dove si trova diff --git a/docs/wiki/Anagrafiche.md b/docs/wiki/Anagrafiche.md index a294942..45d458a 100644 --- a/docs/wiki/Anagrafiche.md +++ b/docs/wiki/Anagrafiche.md @@ -45,7 +45,8 @@ Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, * provincia), **Pagamento**, **Listino** (solo clienti), **Agente** e **Stato**; nei *Contatti* al posto di pagamento e listino c'è il **Tipo** (prospect o lead). Lo stato è un badge: *Attivo*, *Disattivato*, *Bloccato*, *PA · split*, *Privato*, *Impresa UE*, *Impresa extra-UE*, *Anche fornitore* / *Anche cliente*. Le colonne **Fatturato** e -**Scaduto** del mockup arrivano con le vendite (M5) e lo scadenzario (M9). +**Scaduto** del mockup arrivano con i report dei clienti (M12); lo scaduto di un cliente si vede già nello +[Scadenzario](Scadenzario) (*Estratto conto*). - Ricerca libera su codice, nome, partita IVA, codice fiscale e città. - Filtri rapidi: **Tipo** (solo contatti), **Soggetto**, **Agente**, **Stato**; all'apertura sono mostrate solo le diff --git a/docs/wiki/Attivita-programmate.md b/docs/wiki/Attivita-programmate.md index d14b60a..50e5500 100644 --- a/docs/wiki/Attivita-programmate.md +++ b/docs/wiki/Attivita-programmate.md @@ -148,6 +148,7 @@ Nella versione 0.7.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`) | `system.ecb-rates` | scarica i cambi di riferimento della BCE (richiede la rete) | nei giorni feriali alle 16:30 | | `inventory.rebuild` | ricostruisce il magazzino di ogni azienda attiva dai documenti in vigore (vedi [Magazzino](Magazzino#ricostruzione)) | la domenica alle 02:15 | | `ledger.recurring` | crea le registrazioni ricorrenti arrivate alla loro data in ogni azienda con la contabilità (vedi [Contabilità](Contabilita)) | ogni giorno alle 05:00 | +| `finance.dunning` | invia per e-mail e PEC i solleciti dei livelli segnati *Automatico* in ogni azienda con il modulo FIN (vedi [Scadenzario](Scadenzario#solleciti); richiede la rete) | nei giorni feriali alle 07:00 | Oltre alle attività degli amministratori, Khaemhat esegue sempre alcuni **job di sistema**: pulizia (log e sessioni secondo la retention), controllo della licenza, aggiornamento dei cambi BCE, lettura dell'inbox e dei canali SDI, diff --git a/docs/wiki/Contabilita.md b/docs/wiki/Contabilita.md index f4ccabd..e5cbf64 100644 --- a/docs/wiki/Contabilita.md +++ b/docs/wiki/Contabilita.md @@ -16,7 +16,8 @@ nella pagina [IVA](IVA); le regole italiane usate (piano dei conti modello, codi > prima nota manuale con castelletto IVA, la **contabilizzazione automatica** di fatture, note e autofatture, le > registrazioni ricorrenti, lo storno, le registrazioni definitive con il numero di libro giornale, i partitari con > estratto conto e partite, i mastrini, il bilancio di verifica e le stampe del bilancio e del libro giornale. -> Arrivano più avanti: **scadenzario**, incassi e pagamenti bancari e riconciliazione (M8), **chiusura +> 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. @@ -170,12 +171,12 @@ copiare; eliminando una ricorrente le registrazioni già generate restano. ## Piano dei conti ![Khaemhat 0.7.0 · piano dei conti con il mastrino di Clienti Italia](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-piano-dei-conti.png) -*L'albero dei 237 conti del modello PMI standard, il dettaglio del sottoconto 05.01.001 Clienti Italia (sottoconto, +*L'albero dei 240 conti del modello PMI standard, il dettaglio del sottoconto 05.01.001 Clienti Italia (sottoconto, attività, tipo Clienti, voce CEE C.II.1, con partitario) e il suo mastrino con il saldo progressivo.* Il piano dei conti ha tre livelli con codice **`MM.CC.SSS`**: **mastro** (`05` *Crediti verso clienti*), **conto** (`05.01` *Clienti*) e **sottoconto** (`05.01.001` *Clienti Italia*). Si registra solo sui sottoconti. Con le tabelle -di base dell'azienda viene caricato il modello **PMI standard** del pacchetto fiscale: 237 conti con le voci di +di base dell'azienda viene caricato il modello **PMI standard** del pacchetto fiscale: 240 conti con le voci di bilancio CEE già associate (vedi [Fiscalità italiana](Fiscalita-italiana#piano-dei-conti-modello)). | Campo | Significato | @@ -244,8 +245,8 @@ Scegliendo un soggetto si vedono: - le **partite**: una per rata di ogni documento, con data documento, numero della rata, **scadenza**, importo, pagato e **residuo**; le scadenze superate sono in rosso. *Mostra anche le partite chiuse* aggiunge quelle saldate. -In questa versione le partite nascono dai documenti; gli incassi e i pagamenti che le chiudono, i solleciti e lo -scadenzario arrivano con lo [Scadenzario](Scadenzario) (M8). +Le partite nascono dai documenti e si chiudono con gli incassi e i pagamenti registrati nello +[Scadenzario](Scadenzario), dove ci sono anche distinte, solleciti e riconciliazione bancaria. ## Bilancio di verifica e libro giornale diff --git a/docs/wiki/Dashboard.md b/docs/wiki/Dashboard.md index 1326c54..c66e044 100644 --- a/docs/wiki/Dashboard.md +++ b/docs/wiki/Dashboard.md @@ -74,7 +74,10 @@ Nella versione 0.3.0 le righe vengono da: | Fatto oggi | attività programmate riuscite oggi, una riga per attività con il numero di esecuzioni e l'ora dell'ultima | | Scadenze 30 giorni | fine della prova o scadenza della licenza (account di istanza) | -I moduli delle prossime versioni aggiungono le loro righe (scarti SDI, liquidazioni, incassi, ordini da evadere…). +Dalla 0.8 lo [Scadenzario](Scadenzario) aggiunge alle **Scadenze** gli incassi e i pagamenti dei prossimi giorni (al +massimo 12, area *Tesoreria*) e a **Da fare oggi** il totale dei crediti scaduti, con il link ai solleciti; servono +il modulo FIN e il permesso `finance.schedule.read`. I moduli delle prossime versioni aggiungono le loro righe +(scarti SDI, ordini da evadere…). Se una fonte non risponde, il widget mostra le altre e l'errore finisce nel [log](Log). I **promemoria** si scrivono nel campo in fondo al widget e si aggiungono con Invio (al massimo 20, di 300 caratteri diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index 7029ee1..160462c 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -160,7 +160,23 @@ l'azienda ha già documenti di vendita. | 3 fatture fornitore | una dal ricevimento con un prezzo più alto dell'ordine (vedi l'avviso sulle differenze), la parcella del commercialista, la fattura di un fornitore tedesco che aspetta la sua **integrazione AF18** | | 1 inventario aperto | 12 articoli già contati, due con una differenza | -Il caricamento non si ripete se l'azienda ha già documenti di acquisto o di magazzino. Il resto della tabella arriva con le milestone dei rispettivi moduli. +Il caricamento non si ripete se l'azienda ha già documenti di acquisto o di magazzino. + +**Da M7** documenti e fatture sono **contabilizzati** e ci sono un noleggio ricorrente, le liquidazioni IVA +confermate fino al mese precedente, le ritenute e il bollo virtuale (vedi [Contabilità](Contabilita) e [IVA](IVA)). + +**Da M8**, se la licenza comprende il modulo **FIN**, c'è anche la **tesoreria** (vedi [Scadenzario](Scadenzario)): + +| Dati | Che cosa mostrano | +|---|---| +| La banca *Banca Popolare Dimostrativa* | conto predefinito con IBAN, SIA, CUC e identificativo creditore; i versamenti dei soci al 1° gennaio | +| Incassi e pagamenti | i fornitori scaduti pagati con le spese, i clienti scaduti incassati (uno solo in parte), con il CRO | +| Distinte RiBa | una distinta presentata e accreditata con l'ultimo effetto **insoluto** e le spese; una distinta *salvo buon fine* in bozza con le scadenze dei prossimi 45 giorni | +| Mandato SDD | un mandato *Core* firmato da un cliente | +| Estratto conto | un CSV di quattro movimenti da riconciliare: il saldo della fattura incassata in parte, un pagamento già registrato, le commissioni riconosciute dalla regola *Canone e commissioni* e una spesa da registrare su conto | +| Solleciti | un primo sollecito già inviato al cliente con lo scaduto più vecchio | + +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/Fiscalita-italiana.md b/docs/wiki/Fiscalita-italiana.md index fcbaf26..41aee9d 100644 --- a/docs/wiki/Fiscalita-italiana.md +++ b/docs/wiki/Fiscalita-italiana.md @@ -1,7 +1,7 @@ # Fiscalità italiana > **Stato:** completa per la versione 0.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7) -> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14, ADR 0036, ADR 0037 +> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14, ADR 0036, ADR 0037, ADR 0038 Questa pagina raccoglie in un solo posto i **codici e le regole fiscali italiane** che Khaemhat usa: tipi documento SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, il **piano dei conti modello**, i **codici @@ -185,7 +185,7 @@ I dettagli operativi sono in [Fatturazione-elettronica](Fatturazione-elettronica ## Piano dei conti modello -Il pacchetto fiscale porta il piano dei conti **PMI standard**: **237 conti** in tre livelli con codice `MM.CC.SSS` +Il pacchetto fiscale porta il piano dei conti **PMI standard**: **240 conti** in tre livelli con codice `MM.CC.SSS` (mastro, conto, sottoconto), ognuno con natura, tipo e voce dello schema di bilancio civilistico (art. 2424 e 2425 c.c.). Si carica con le tabelle di base dell'azienda e si modifica liberamente da **Contabilità → Piano dei conti** (vedi [Contabilità](Contabilita#piano-dei-conti)). @@ -312,7 +312,7 @@ si esportano in CSV; la CU si invia con i servizi dell'Agenzia o dall'intermedia | Bollo virtuale | versamento trimestrale (vedi sopra), con la soglia dei 5.000 euro | elenco da confrontare con quello proposto dall'Agenzia | | Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nelle autofatture | | Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** | -| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali | con i solleciti dello scadenzario (M8) | +| Interessi di mora | D.Lgs. 231/2002 per i ritardi nelle transazioni commerciali: tasso BCE di riferimento del semestre + 8 punti (10,15% nel primo semestre 2026, 10,40% nel secondo) | nei solleciti e nell'estratto conto dello [Scadenzario](Scadenzario); la tabella dei tassi va aggiornata ogni semestre (ADR 0038) | ## Altri riferimenti usati dal programma diff --git a/docs/wiki/Guida-utente.md b/docs/wiki/Guida-utente.md index 422acc8..343a6f6 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.7 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7) +> **Stato:** completa per la versione 0.8 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.8.0 (M8) Questa pagina accompagna chi usa Khaemhat ogni giorno: dall'accesso alla fattura inviata al cliente, un passo per volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina che lo spiega per intero. Chi deve @@ -9,19 +9,19 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c ## Che cosa c'è in questa versione -| Area | In 0.7.0 | Arriva con | +| Area | In 0.8.0 | Arriva con | |---|---|---| | Accesso e sicurezza | password, verifica in due passaggi, codici di recupero, blocco dopo i tentativi sbagliati | — | | Interfaccia | menu, schede, ricerca globale, notifiche, aiuto F1, dashboard a widget, temi e colori | — | | Tabelle azienda | profilo azienda, esercizi, cambi, codici IVA, pagamenti, banche, depositi, tipi documento, numeratori e le altre tabelle di base | — | | Anagrafiche | clienti, fornitori, contatti, controlli di partita IVA e codice fiscale, VIES | CRM (lead, opportunità): M11 | | Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente, costo medio e ultimo costo dai movimenti | — | -| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail, scarico del magazzino e impegno, registrazione contabile automatica | incassi e scadenzario M8, XML SDI M9 | -| Acquisti | ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, controllo dei prezzi, import delle fatture elettroniche XML/P7M/ZIP, autofatture e integrazioni in bozza con scadenza, registrazione contabile e registri IVA | pagamenti M8, XML delle autofatture M9 | +| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail, scarico del magazzino e impegno, registrazione contabile automatica, incassi dallo scadenzario | XML SDI M9 | +| Acquisti | ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, controllo dei prezzi, import delle fatture elettroniche XML/P7M/ZIP, autofatture e integrazioni in bozza con scadenza, registrazione contabile e registri IVA, pagamenti dallo scadenzario | XML delle autofatture M9 | | Magazzino | giacenze per deposito, impegnato e ordinato, costo medio, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione | scritture delle rimanenze e libro inventari con la chiusura dell'esercizio M10 | | Contabilità | piano dei conti, causali, prima nota, contabilizzazione automatica dei documenti, registrazioni ricorrenti e definitive, partitari, mastrini, bilancio di verifica, libro giornale | chiusura dell'esercizio, bilancio CEE e cespiti M10 | | IVA | registri IVA, liquidazione con F24, acconto, file LIPE, ritenute d'acconto con prospetto F24 e dati CU, bollo virtuale | dichiarazioni d'intento M10 | -| Scadenzario | partite aperte dai documenti, visibili nei partitari | incassi, pagamenti, banche e solleciti M8 | +| Scadenzario | partite aperte con aging, incassi e pagamenti, distinte RiBa/SDD/bonifici SEPA con insoluti, mandati SDD, riconciliazione bancaria CSV/CBI/CAMT.053, solleciti con interessi di mora, flusso di cassa | collegamento diretto con la banca e report di tesoreria M12 | | Fatturazione elettronica | — | M9 | | 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 | @@ -155,14 +155,40 @@ confermati muovono il magazzino da soli: non serve registrare a parte carichi e **Inventario** guida il conteggio fisico (anche dal file del lettore di codici a barre) e registra le rettifiche; **Valorizzazione** calcola il valore del magazzino a una data con le classi ABC. Vedi [Magazzino](Magazzino). -## 10. Allegati +## 10. La contabilità + +![Prima nota](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/contabilita-prima-nota.png) + +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). + +## 11. Incassare, pagare e la banca + +![Partite aperte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-partite.png) + +**Scadenzario → Partite aperte** mostra che cosa devono pagarti i clienti e che cosa devi ai fornitori, con lo scaduto +per anzianità. Quando un cliente paga, seleziona le sue partite e premi **Registra incasso**: indichi data, banca e +importo (anche parziale, o con un abbuono) e Khaemhat chiude le partite e scrive la registrazione. Per i fornitori +passa a **Fornitori** e usa **Registra pagamento**. + +![Riconciliazione bancaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-riconciliazione.png) + +Le **Distinte RiBa/SDD** raccolgono gli effetti in scadenza e generano il file da caricare nell'home banking (anche i +bonifici ai fornitori); **Riconciliazione bancaria** importa l'estratto conto e propone per ogni movimento la partita +o la spesa corrispondente; **Solleciti** prepara i promemoria ai clienti in ritardo con gli interessi di mora; +**Flusso di cassa** mostra quanto ci sarà in banca nelle prossime settimane. Vedi [Scadenzario](Scadenzario). + +## 12. Allegati ![Pannello allegati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-pannello.png) Ogni anagrafica e ogni documento ha la scheda **Allegati**: carichi file dal computer, li vedi in anteprima, scarichi tutto in un archivio ZIP. I PDF che Khaemhat genera sono **versionati**: ogni stampa salvata o e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e file](Allegati-e-file). -## 11. Importare ed esportare +## 13. Importare ed esportare ![Mappatura delle colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png) @@ -170,7 +196,7 @@ e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e f CSV, Excel o JSON: scegli il file, abbini le colonne, guarda l'anteprima con gli errori riga per riga e conferma. Ogni radar esporta le righe visibili. Vedi [Import/Export](Import-Export). -## 12. Personalizzare +## 14. Personalizzare ![Il mio profilo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/preferenze-profilo.png) diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index d093f14..73c35f8 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -1,6 +1,6 @@ # Khaemhat -> **Stato:** completa per 0.7.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.7.0 (M7; sviluppo in corso) +> **Stato:** completa per 0.8.0 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.8.0 (M8; sviluppo in corso) ![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png) diff --git a/docs/wiki/IVA.md b/docs/wiki/IVA.md index 6755df5..9d4b391 100644 --- a/docs/wiki/IVA.md +++ b/docs/wiki/IVA.md @@ -17,8 +17,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. Arrivano più avanti: i **pagamenti delle fatture** dallo scadenzario, che oggi -> per le ritenute si registrano a mano (M8), le **dichiarazioni d'intento** e il plafond e l'**Intrastat** (M10), +> 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 > telematico** di F24, LIPE e CU. @@ -182,8 +182,9 @@ agenti), importo, data di pagamento della fattura e **stato**: ### Registrare il pagamento della fattura -La ritenuta operata diventa dovuta **quando paghi la fattura** del professionista (criterio di cassa). Finché i -pagamenti non arrivano con lo [Scadenzario](Scadenzario) (M8), si registra a mano: +La ritenuta operata diventa dovuta **quando paghi la fattura** del professionista (criterio di cassa). Se paghi la +fattura dallo [Scadenzario](Scadenzario) succede da solo, quando la fattura è saldata del tutto. Se l'hai pagata +fuori da Khaemhat, registralo a mano: 1. Sulla riga della ritenuta premi **Fattura pagata** e indica la data di pagamento. 2. Khaemhat scrive la registrazione **RIT** (*fornitore* in Dare, *Erario c/ritenute lavoro autonomo* in Avere) e diff --git a/docs/wiki/Modello-dati.md b/docs/wiki/Modello-dati.md index 8809548..014e7c7 100644 --- a/docs/wiki/Modello-dati.md +++ b/docs/wiki/Modello-dati.md @@ -30,7 +30,7 @@ volume `/data/files/`; nel database c'è la loro scheda (nome, tipo, di | Documenti | `sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`, `purchase_documents`, ciascuno con righe, castelletto IVA e rate; `document_links` per l'evasione | [Vendite](Vendite), [Acquisti](Acquisti) | | Magazzino | `inventory_entries` e righe, `item_balances` (giacenza, impegnato, ordinato per articolo e deposito) | [Magazzino](Magazzino) | | Contabilità e IVA | `gl_accounts`, `gl_entries` e righe, `vat_registers`, `vat_settlements` | [Contabilita](Contabilita), [IVA](IVA) | -| Scadenzario | `open_items` (partite), `payments` | [Scadenzario](Scadenzario) | +| Scadenzario | `gl_open_items` (partite), `payments` e righe, `remittances` e righe, `sdd_mandates`, `bank_statements` e righe, `bank_match_rules`, `dunning_levels`, `dunning_letters` | [Scadenzario](Scadenzario) | | CRM | `crm_leads`, `crm_opportunities`, `crm_activities`, `crm_campaigns`, `crm_tickets` | [CRM](CRM) | | Canali | `sales_channels`, `channel_orders` | [Canali-e-commerce](Canali-e-commerce) | | Utenti e sicurezza | `users`, `roles`, `role_permissions`, `user_sessions`, `api_keys` | [Utenti-e-permessi](Utenti-e-permessi) | diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index 099b967..a34a825 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). **Prossima:** M8. +**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0), M7 (0.7.0), M8 (0.8.0). **Prossima:** M9. | # | Milestone | Contenuto principale | Versione | |---|---|---|---| diff --git a/docs/wiki/Scadenzario.md b/docs/wiki/Scadenzario.md index ffe1b6d..b8ace56 100644 --- a/docs/wiki/Scadenzario.md +++ b/docs/wiki/Scadenzario.md @@ -1,165 +1,312 @@ # Scadenzario e tesoreria -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M8) -> **Modulo di licenza:** FIN · **Permessi principali:** `finance.openitem.read`, `finance.payment.post`, `finance.remittance.write`, `finance.bank.reconcile`, `finance.dunning.send` · **Specifica:** SPEC §11.8 +> **Stato:** completa per la versione 0.8 · **Ultima revisione:** 2026-11-13 · **Versione software:** 0.8.0 (M8) +> **Modulo di licenza:** FIN (con ACCT per le registrazioni) · **Permessi principali:** `finance.schedule.read`/`write` +> (scadenzario, distinte, mandati, solleciti, flusso di cassa), `finance.payment.read`/`write` (incassi e pagamenti), +> `finance.bank.reconcile` (riconciliazione bancaria) · **Specifica:** SPEC §11.8, ADR 0038 -## A cosa serve +Lo **scadenzario** tiene le **partite aperte** di clienti e fornitori, cioè le rate dei documenti ancora da incassare +o da pagare. Da qui si registrano **incassi e pagamenti** (con abbuoni, spese e differenze cambio), si preparano le +**distinte RiBa, SDD e bonifici SEPA** con il file per l'home banking, si gestiscono gli **insoluti**, si +**riconcilia** l'estratto conto della banca, si inviano i **solleciti** con gli interessi di mora e si guarda il +**flusso di cassa** dei prossimi mesi. Ogni operazione scrive da sola la sua registrazione in +[Contabilità](Contabilita): non serve passare dalla prima nota. -Lo scadenzario tiene le **partite aperte** di clienti e fornitori (le rate generate dai documenti), registra -**incassi e pagamenti** con abbuoni e spese, prepara le **distinte RiBa, SDD e bonifici SEPA**, gestisce gli -**insoluti**, **riconcilia** l'estratto conto della banca, invia i **solleciti** e mostra il **flusso di cassa**. -Ogni movimento genera da solo la registrazione contabile ([Contabilità](Contabilita)). +> **In questa versione** ci sono partite aperte con aging, incassi e pagamenti multipli e parziali, abbuoni, spese e +> differenze cambio, storno di un incasso, estratto conto del cliente con gli interessi di mora, distinte RiBa (CBI), SDD core e B2B +> (`pain.008`) e bonifici SEPA (`pain.001`) con presentazione, accredito e insoluti, mandati SDD, import +> dell'estratto conto CSV, CBI e CAMT.053 con abbinamento automatico e regole, solleciti su tre livelli con +> interessi di mora e invio automatico, flusso di cassa a 30-365 giorni e le scadenze sulla Home. Arrivano più +> avanti: il **blocco per fido** su ordini e documenti (con le vendite avanzate), il collegamento diretto con la +> banca (CBI online, PSD2) e le **stampe** dei report di tesoreria nella sezione [Report](Report) (M12). ## Dove si trova -Menu laterale **Scadenzario**: **Partite aperte**, **Incassi**, **Pagamenti**, **Solleciti**, **Distinte RiBa/SDD**, -**Riconciliazione bancaria**. +Menu laterale **Scadenzario** → *Partite aperte*, *Incassi*, *Pagamenti*, *Solleciti*, *Distinte RiBa/SDD*, +*Mandati SDD*, *Riconciliazione bancaria*, *Flusso di cassa*. -## Schermate +Il menu compare solo se la licenza comprende il modulo **FIN** e l'utente ha i permessi (vedi +[Licenze e moduli](Licenze-e-moduli) e [Utenti e permessi](Utenti-e-permessi)). Senza ACCT le partite esistono +comunque, ma le operazioni che scrivono in contabilità chiedono il modulo. -![053 · Partite aperte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/053-scadenzario-partite.png) -*Mockup 053 — partite aperte dei clienti con riquadri di aging (non scaduto, 1-30, 31-60, 61-90, oltre 90 giorni), selezione multipla e azioni Registra incasso, Sollecito, Distinta RiBa (anteprima ridotta)* +Prima di iniziare servono: -![054 · Registra incasso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/054-scadenzario-incasso.png) -*Mockup 054 — dialogo Registra incasso su due partite: cliente, data, metodo, importo, banca, riferimento CRO, causale INC; abbuono di € 10,00 sulla seconda rata e anteprima della registrazione che verrà generata* +- almeno un **conto bancario dell'azienda** in **Tabelle azienda → Banche aziendali** con IBAN, conto contabile e, per le + distinte, **codice SIA** (RiBa), **CUC** e **identificativo creditore SEPA** (SDD) — vedi + [Tabelle azienda](Tabelle-azienda); +- i **metodi di pagamento** con il codice MP della fattura elettronica (MP05 bonifico, MP12 RiBa, MP19-MP21 SDD…); +- per RiBa e SDD, le **coordinate bancarie del cliente** nella sua anagrafica ([Anagrafiche](Anagrafiche)). -![055 · Distinte](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/055-distinte-riba-sdd-sepa.png) -*Mockup 055 — distinta RiBa con banca di presentazione, date, importo, salvo buon fine e passi guidati; a destra gli effetti con il controllo (OK, IBAN mancante, scaduta da escludere)* +## Partite aperte -![056 · Solleciti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/056-solleciti-pagamento.png) -*Mockup 056 — proposta di invio dei solleciti per cliente con livello, canale e interessi di mora; sotto, la tabella dei tre livelli con giorni, modello, canale e azione* +![Khaemhat 0.8.0 · partite aperte dei clienti con aging e stati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-partite.png) +*Khaemhat 0.8.0 — partite aperte dei clienti di esempio: i riquadri di aging, i filtri, la selezione per registrare +l'incasso e gli stati (parziale, insoluta, scaduta, in distinta con il numero della distinta).* -![057 · Riconciliazione bancaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/057-riconciliazione-bancaria.png) -*Mockup 057 — movimenti dell'estratto conto con stato (abbinato, suggerito, insoluto, da abbinare), abbinamento proposto e confidenza; riquadri con saldo banca, saldo contabile e differenza* +Una **partita** è una rata di un documento: controparte, documento, numero della rata, scadenza, metodo, importo, +già incassato o pagato, residuo e stato. Le partite nascono dalla registrazione contabile delle fatture e delle note +di credito ([Vendite](Vendite), [Acquisti](Acquisti), [Contabilità](Contabilita)) secondo le condizioni di +pagamento; si vedono anche nei **partitari**. -## Partite e stati - -Una **partita** è una rata di un documento: controparte, documento, numero rata, scadenza, importo, pagato, residuo, -metodo di pagamento, banca, stato e registrazione collegata. Le partite nascono dalle condizioni di pagamento dei -documenti ([Vendite](Vendite), [Acquisti](Acquisti)) o dall'import delle partite di apertura -([Import-Export](Import-Export)). +In alto cinque **riquadri di aging** sommano il residuo per anzianità: *non scaduto*, *1-30*, *31-60*, *61-90* e +*oltre 90 giorni*. I badge accanto al titolo danno il totale aperto e il totale scaduto. | Stato | Significato | |---|---| -| **Aperta** | non ancora incassata/pagata, non scaduta | -| **Parziale** | incassata in parte | +| **Aperta** | non ancora incassata o pagata | +| **Parziale** | incassata o pagata in parte | | **Chiusa** | saldata | -| **Insoluta** | effetto tornato insoluto, riaperta con le spese | -| **In distinta** | inserita in una distinta RiBa/SDD presentata | -| **Contestata** | esclusa dai solleciti e dalle distinte finché non si risolve | +| **Insoluta** | effetto o addebito tornato indietro: la partita è di nuovo da incassare | +| **In distinta** | inserita in una distinta RiBa, SDD o bonifici: non si incassa a mano finché resta lì | -La griglia mostra anche i **giorni** rispetto alla scadenza (positivi se scaduta) e le etichette *Scaduta*, -*In scadenza*, *Aperta · split* (fatture in split payment). Il selettore **Clienti / Fornitori** cambia lato. +Oltre allo stato la griglia segnala **Scaduta** (in rosso), **In scadenza** entro 7 giorni e **Contestata** (una +partita contestata resta fuori da distinte e solleciti). La colonna **Gg** conta i giorni dalla scadenza: positivi +se scaduta, negativi se manca ancora tempo. + +**Filtri.** Ricerca per controparte o documento; **Mostra** (*Aperte*, *Scadute*, *Insolute*, *In distinta*, +*Contestate*, *Chiuse*, *Tutte*); **Metodo** di pagamento; il selettore **Clienti / Fornitori** cambia lato (dal +menu *Pagamenti → Registra pagamento* si arriva direttamente ai fornitori). **Esporta** scarica la griglia in CSV. + +![Khaemhat 0.8.0 · partite aperte dei fornitori](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-fornitori.png) +*Khaemhat 0.8.0 — Lo stesso elenco sul lato fornitori, con il pulsante Registra pagamento.* + +**Modificare una partita.** La matita apre la scheda della rata: si cambiano **scadenza**, **metodo**, **banca** e +**contestazione** (con una nota). L'importo no: si corregge il documento. + +**Estratto conto.** Selezionata una partita, **Estratto conto** mostra per quella controparte le partite aperte con +lo scaduto, gli interessi di mora maturati a oggi e gli incassi o pagamenti registrati. ## Registrare un incasso o un pagamento -1. In **Partite aperte** seleziona una o più partite dello stesso cliente e premi **Registra incasso**. -2. Compila **Data**, **Metodo** (es. bonifico MP05), **Importo**, **Banca azienda**, **Riferimento** (CRO) e - **Causale** (INC per gli incassi, PAG per i pagamenti). -3. Nella tabella *Partite da chiudere* distribuisci l'importo: per ogni rata **Incassato**, **Abbuono** e - **Residuo dopo**. -4. Leggi l'anteprima della prima nota che verrà generata (banca in dare, cliente in avere, abbuono sul suo conto). +![Khaemhat 0.8.0 · dialogo Registra incasso](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-incasso.png) +*Khaemhat 0.8.0 — Registra incasso su una partita del cliente: data, metodo, banca, riferimento, spese, la tabella +delle partite da chiudere e l'anteprima della registrazione.* + +1. In **Partite aperte** seleziona una o più partite della **stessa controparte** (le partite in distinta non si + selezionano) e premi **Registra incasso** (o **Registra pagamento** sul lato fornitori). +2. Compila **Data**, **Metodo**, **Banca** dell'azienda (o la cassa), **Riferimento** (CRO o TRN), eventuali + **Spese** bancarie e **Note**. +3. Nella tabella *Partite da chiudere* ogni rata propone tutto il residuo: abbassa l'importo per un incasso + **parziale** oppure indica un **abbuono** per chiudere la differenza (es. il cliente arrotonda per difetto). + *Residuo dopo* mostra cosa resta aperto. +4. Leggi l'anteprima: *Banca (D) / Clienti (A)* per un incasso, *Fornitori (D) / Banca (A)* per un pagamento, + con gli abbuoni sul loro conto. 5. Premi **Registra e chiudi partite**. -Regole: +Cosa succede: -- **Abbuoni**: piccola differenza fra dovuto e incassato chiusa come abbuono attivo o passivo. -- **Differenze cambio** per le partite in valuta, **spese** bancarie e **storno** dell'incasso sono gestiti nello - stesso movimento. -- Un pagamento a un professionista rileva la **ritenuta d'acconto** da versare ([IVA](IVA)). +- viene scritta la registrazione con causale **INC** (incassi) o **PAG** (pagamenti), collegata al movimento; +- gli **abbuoni** vanno su *abbuoni passivi* (concessi al cliente) o *abbuoni attivi* (ottenuti dal fornitore); +- le **spese** vanno su *spese bancarie*; per le partite in valuta la **differenza cambio** fra il cambio della + fattura e quello dell'incasso va su *utili* o *perdite su cambi*; +- le **note di credito** aperte della stessa controparte si possono selezionare insieme alle fatture: riducono + l'importo da incassare; +- per una fattura di un **professionista** con ritenuta d'acconto, quando la fattura è pagata del tutto la ritenuta + diventa **da versare** e compare in *Ritenute e F24* ([IVA](IVA)). + +**Incassi** e **Pagamenti** elencano i movimenti del periodo con controparte, documenti saldati, riferimento, banca, +origine (*Manuale*, *Distinta*, *Estratto conto*), importo, abbuoni, spese e la registrazione. La freccia +**Annulla** storna il movimento: la registrazione viene annullata e le partite tornano aperte com'erano. + +![Khaemhat 0.8.0 · l'elenco degli incassi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-incassi.png) +*Khaemhat 0.8.0 — Incassi del periodo con documento saldato, riferimento CRO, banca e registrazione contabile.* + +![Khaemhat 0.8.0 · l'elenco dei pagamenti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-pagamenti.png) +*Khaemhat 0.8.0 — Pagamenti ai fornitori con le spese bancarie e la freccia per annullarli.* ## Distinte RiBa, SDD e bonifici SEPA | Tipo | Uso | File prodotto | |---|---|---| -| **RiBa** | incasso di ricevute bancarie dai clienti | file CBI (tracciato standard RiBa) | -| **SDD core / B2B** | addebito diretto sul conto del cliente, con **mandati** | `pain.008` | -| **Bonifici SEPA** | pagamento dei fornitori | `pain.001` | -| MAV / RAV | gestiti come semplici scadenze | — | +| **RiBa (CBI)** | incasso delle ricevute bancarie dei clienti | file CBI RiBa a record di 120 caratteri | +| **SDD Core** | addebito diretto sul conto di un privato, con mandato | XML SEPA `pain.008.001.08` | +| **SDD B2B** | addebito diretto sul conto di un'impresa, con mandato B2B | XML SEPA `pain.008.001.08` | +| **Bonifici SEPA** | pagamento dei fornitori | XML SEPA `pain.001.001.09` | -1. **Distinte RiBa/SDD**, scegli **Tipo**, **Banca di presentazione**, **Data presentazione** e **Scadenze fino al**. -2. **Selezione effetti**: Khaemhat propone gli effetti; la colonna **Controllo** segnala *IBAN mancante* o - *Scaduta: escludere?*. -3. **Controlli**: IBAN, CIN, scadenze. -4. **Genera file CBI** (o il file SEPA): il file resta come allegato della distinta. -5. **Contabilizza distinta**: effetti attivi presentati in banca, con l'opzione **Salvo buon fine (anticipo)** per gli - anticipi s.b.f. -6. **Presentazione**: carica il file nell'home banking. +![Khaemhat 0.8.0 · nuova distinta RiBa con i passi guidati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-distinte.png) +*Khaemhat 0.8.0 — Nuova distinta: tipo, banca, date, salvo buon fine e i passi; a destra gli effetti candidati con il +controllo (qui due effetti scaduti da valutare).* -**Storico distinte** mostra le distinte precedenti. +### Creare una distinta -### Insoluti +1. **Distinte RiBa/SDD → Nuova distinta**: scegli **Tipo**, **Banca di presentazione**, **Data presentazione** e + **Scadenze fino al**. Per le RiBa puoi spuntare **Salvo buon fine (anticipo)** se la banca anticipa gli importi. +2. A destra compaiono gli effetti candidati (partite con metodo RiBa, SDD o bonifico, non contestate, non già in + distinta). La colonna **Controllo** segnala cosa non va: *IBAN mancante* (o ABI/CAB per le RiBa), *mandato mancante* (SDD), + *Scaduta: escludere?*. Spunta gli effetti da includere: totale e numero si aggiornano. +3. **Crea distinta**: la distinta nasce in **Bozza** con il numero dell'anno (es. 2026/002) e le partite passano + *In distinta*. -Quando un effetto torna insoluto (anche dalla riconciliazione bancaria), la partita viene **riaperta** con le -**spese** addebitate e la registrazione con causale **INS**; lo stato diventa *Insoluta*. +### Dalla bozza alla chiusura + +![Khaemhat 0.8.0 · dettaglio di una distinta in bozza](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-distinta-dettaglio.png) +*Khaemhat 0.8.0 — Storico distinte e dettaglio di una distinta s.b.f. in bozza, con gli effetti e le azioni.* + +Da **Storico distinte** si apre una distinta e si procede: + +| Passo | Azione | Effetto | +|---|---|---| +| 1 | **Genera file** | crea il file CBI o XML (scaricabile e conservato come allegato); stato *File generato* | +| 2 | **Contabilizza presentazione** | RiBa e SDD: i crediti passano da *Clienti* a *Effetti all'incasso* (con anticipo s.b.f. la banca accredita subito su *Banche c/anticipi*); bonifici: i fornitori sono pagati e la distinta si chiude | +| 3 | **Accredito** | alla scadenza la banca accredita: *Banca* in dare, *Effetti all'incasso* (o *Banche c/anticipi*) in avere; la distinta si chiude | +| — | **Insoluto** su una riga | l'effetto torna indietro: la partita torna *Insoluta*, la banca riprende l'importo e le **spese** dell'insoluto diventano una nuova partita del cliente | + +Finché la distinta è in bozza si può togliere una riga (la ✕) o **eliminarla** del tutto: le partite tornano +aperte. Il file va poi caricato nell'home banking: Khaemhat non lo invia alla banca. + +### Mandati SDD + +![Khaemhat 0.8.0 · mandati SEPA Direct Debit](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-mandati.png) +*Khaemhat 0.8.0 — Mandati SDD con riferimento univoco (UMR), data di firma, schema, IBAN, ultimo incasso e stato.* + +Ogni cliente che paga con addebito diretto deve aver firmato un **mandato**. In **Mandati SDD → Nuovo mandato** +indica cliente, **riferimento del mandato** (UMR, unico per creditore), data di firma, **schema** (*Core* per i +privati, *B2B* per le imprese), IBAN e BIC del debitore. Il primo addebito esce come **FRST**, i successivi come +**RCUR**. Un mandato **revocato** (o un mandato *una tantum* già usato) non vale più: la distinta segnala il cliente +come *mandato mancante*. ## Riconciliazione bancaria -1. **Riconciliazione bancaria**, scegli il conto e premi **Importa estratto conto**: formati **CSV**, **CBI** e - **CAMT.053**. -2. **Abbina automatico**: Khaemhat cerca l'abbinamento per importo, data, CRO/riferimento e nome, e indica una - **confidenza** in percentuale. -3. **Conferma suggeriti ≥ 90 %** conferma in blocco gli abbinamenti più sicuri; gli altri si confermano o si - correggono riga per riga. -4. Le righe senza documento (commissioni, F24, addebiti) si registrano direttamente; con una **regola salvata** - (es. "COMMISSIONI" → spese bancarie) i movimenti ricorrenti vengono riconosciuti in automatico. -5. I riquadri **Saldo banca**, **Saldo contabile** e **Differenza** mostrano cosa resta da abbinare. +![Khaemhat 0.8.0 · riconciliazione dell'estratto conto](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-riconciliazione.png) +*Khaemhat 0.8.0 — Movimenti dell'estratto conto con stato, abbinamento proposto e confidenza; in alto saldo banca, +saldo contabile e differenza.* -| Stato riga | Significato | -|---|---| -| **Abbinato** | collegato a incasso/pagamento registrato | -| **Suggerito** | abbinamento proposto, da confermare | -| **Da abbinare** | più candidati o nessuno | -| **Insoluto** | riapre la partita con le spese | +1. Scegli la **Banca** e premi **Importa estratto conto**. Formati accettati: + - **CSV** dell'home banking: Khaemhat riconosce da solo separatore e colonne dalla riga di intestazione + (*Data contabile*, *Data valuta*, *Descrizione*, *Importo* oppure *Entrate*/*Uscite*, anche in inglese); + - **CBI** (rendicontazione movimenti di conto corrente, record RH/61/62/63/64/EF); + - **CAMT.053** (XML ISO 20022). + I movimenti **già importati** vengono riconosciuti e saltati, anche se carichi due volte lo stesso file o due + file che si sovrappongono. +2. Khaemhat propone per ogni movimento cosa potrebbe essere, con una **confidenza** in percentuale: + + | Abbinamento | Quando | + |---|---| + | **Partite** | importo uguale al residuo di una o più partite della stessa controparte | + | **Movimento registrato** | un incasso o pagamento già registrato a mano | + | **F24** | un versamento di imposte registrato in *Ritenute e F24* | + | **Accredito distinta** / **Insoluto** | l'accredito di una distinta presentata o un effetto respinto | + | **Regola** | una **regola salvata** riconosce il testo (es. *COMMISSIONI* → spese bancarie) | + + La confidenza parte dall'importo (esatto o entro la tolleranza) e sale con il numero del documento o il CRO + nella descrizione, l'IBAN e il nome della controparte e la vicinanza delle date; una regola vale 98%. +3. **Conferma suggeriti ≥ 90%** conferma in blocco le proposte più sicure; le altre si confermano con ✓ o si + correggono riga per riga: + - ☰ **Abbina a partite** — scegli le partite: viene registrato l'incasso o il pagamento; + - € **Abbina a incasso o pagamento registrato** — collega un movimento già registrato a mano; + - 📖 **Registra su conto** — per le righe senza documento (commissioni, canoni, carburante) scegli il conto e, + se vuoi, salva una **regola** per le prossime volte; + - **Ignora** — il movimento non va riconciliato. + La freccia **Annulla abbinamento** riporta la riga da riconciliare e annulla quello che aveva registrato. +4. La striscia in alto mostra **saldo banca** (dall'ultimo estratto), **saldo contabile** del conto, **differenza** e + movimenti ancora da riconciliare. Le schede **Regole** ed **Estratti importati** elencano le regole salvate (con + quante volte sono state usate) e i file caricati. ## Solleciti -**Solleciti** (mockup 056) gestisce tre **livelli**, ciascuno con giorni di ritardo, modello, canale, interessi e -azione. Esempio del mockup: +![Khaemhat 0.8.0 · proposta di invio dei solleciti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-solleciti.png) +*Khaemhat 0.8.0 — Proposta di invio per cliente con prossimo livello, canale e interessi di mora; sotto i tre livelli.* + +I solleciti seguono tre **livelli**, ciascuno con i giorni dopo la scadenza, il modello del messaggio, i **canali** +(e-mail, PEC, lettera PDF), gli interessi di mora e un'**azione**: | Livello | Dopo (gg) | Modello | Canale | Interessi | Azione | |---|---|---|---|---|---| | 1 | 7 | Promemoria cortese | e-mail | no | — | -| 2 | 20 | Sollecito formale | PEC + e-mail | sì | notifica agente | -| 3 | 45 | Messa in mora | PEC + lettera PDF | sì | blocco cliente, notifica amministrazione | +| 2 | 20 | Sollecito | e-mail + PEC | sì | avvisa l'agente (in copia) | +| 3 | 45 | Diffida e blocco forniture | PEC + lettera PDF | sì | blocca il cliente | -- La **proposta di invio** elenca per cliente partite, scaduto, giorni massimi, ultimo sollecito, prossimo livello, - canale, interessi di mora e l'interruttore **Includi**. Sono esclusi per regola la PA e i clienti con partite - contestate. -- Gli **interessi di mora** seguono il D.Lgs. 231/2002 (transazioni commerciali); il tasso è un parametro aggiornato - periodicamente. -- **Anteprima** mostra i messaggi; **Invia N solleciti** li spedisce e li annota nel **registro invii**. -- Il livello 3 può **bloccare il cliente** (ordini e documenti richiedono un override). -- I solleciti si eseguono anche da **attività programmata** (riquadro *Prossima esecuzione*), vedi - [Automazioni](Automazioni). +![Khaemhat 0.8.0 · modifica di un livello di sollecito](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-sollecito-livello.png) +*Khaemhat 0.8.0 — Un livello si modifica con la matita: giorni, azione, canali, interessi, invio automatico, oggetto e +testo con i segnaposto.* -## Flusso di cassa e report +Nel testo si usano i **segnaposto** `{cliente}`, `{azienda}`, `{elenco}` (le partite scadute), `{totale}`, +`{interessi}`, `{riferimento}` e `{giorni}`. -| Report | Contenuto | +- La **Proposta di invio** elenca i clienti con partite scadute oltre i giorni del livello successivo a quello già + inviato: partite, scaduto, giorni massimi, ultimo sollecito, prossimo livello, canale e interessi. Sono esclusi per + regola la **pubblica amministrazione**, le partite **contestate** e quelle in distinta. L'interruttore + **Includi** toglie un cliente dall'invio. +- **Anteprima** scarica il PDF del sollecito del primo cliente incluso; **Invia N solleciti** mette in coda e-mail e + PEC con il PDF allegato (vedi [Impostazioni](Impostazioni) per SMTP e PEC) e scarica in un unico PDF le **lettere** + da stampare e spedire. Un cliente senza indirizzo e-mail o PEC viene saltato, con un avviso, se il livello non + prevede la lettera. +- Gli **interessi di mora** seguono il D.Lgs. 231/2002: tasso BCE di riferimento del semestre più 8 punti + (10,15% nel primo semestre 2026, 10,40% nel secondo), calcolati giorno per giorno sul residuo di ogni partita. + Gli interessi compaiono nel messaggio e nel PDF; non vengono addebitati in contabilità. +- Il livello con azione **Blocca il cliente** imposta il blocco nelle condizioni di vendita dell'anagrafica. +- Il **Registro invii** conserva ogni sollecito con data, livello, canale, destinatari, importo, interessi e stato + dell'invio. +- I livelli segnati **Automatico** partono da soli con l'attività programmata *Solleciti* (giorni feriali alle 7:00, + vedi [Attività programmate](Attivita-programmate)); solo e-mail e PEC, mai la lettera. + +## Flusso di cassa + +![Khaemhat 0.8.0 · flusso di cassa previsto a 90 giorni](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/scadenzario-flusso-di-cassa.png) +*Khaemhat 0.8.0 — Disponibilità di oggi, entrate e uscite previste per settimana con il saldo progressivo e i +movimenti che lo compongono.* + +Il **flusso di cassa** parte dalla disponibilità di oggi (saldo contabile di banche e cassa) e aggiunge, periodo per +periodo, i movimenti attesi da sei **fonti** che si accendono e spengono con le caselle: + +| Fonte | Da dove | |---|---| -| Scadenzario | partite per scadenza, cliente/fornitore, metodo | -| Aging | crediti per fasce di ritardo (come i riquadri del mockup 053) | -| Estratto conto | per cliente/fornitore, anche in PDF da inviare | -| **Flusso di cassa 90 giorni** | entrate e uscite previste da partite, distinte e saldi bancari | -| Insoluti | effetti tornati insoluti con spese | -| Posizione bancaria | saldi dei conti e effetti presentati | +| Incassi da clienti | partite aperte dei clienti e gli effetti presentati senza anticipo, alla loro scadenza | +| Pagamenti a fornitori | partite aperte dei fornitori | +| Ordini clienti / fornitori | il residuo degli ordini non ancora fatturati, 30 giorni dopo la consegna prevista (o la data dell'ordine) | +| Ricorrenti | le registrazioni ricorrenti della contabilità (affitti, noleggi…) che muovono la banca | +| Imposte | i versamenti F24 non ancora pagati (IVA, acconto, ritenute) alla loro scadenza | -Vedi [Report](Report). +L'**orizzonte** va da 30 a 365 giorni, il **periodo** è la settimana o il mese. Le partite già scadute cadono nel +primo periodo. La striscia riassume disponibilità di oggi, entrate e uscite previste, saldo finale e **punto più +basso** (in rosso se il conto andrebbe in negativo). + +## Sulla Home + +Con il permesso `finance.schedule.read` la [Dashboard](Dashboard) mostra: + +- nelle **Scadenze** gli incassi e i pagamenti dei prossimi giorni (al massimo 12), con il link alla partita; +- nelle **Cose da fare** il totale dei crediti scaduti, con il link ai solleciti. + +## Dati di esempio + +L'azienda demo (se la licenza comprende FIN) arriva con la banca *Banca Popolare Dimostrativa*, i versamenti dei +soci, incassi e pagamenti già registrati (uno parziale), una distinta RiBa accreditata con un **insoluto**, una +distinta s.b.f. in bozza, un mandato SDD, un estratto conto CSV da riconciliare con una regola per le commissioni e +un primo sollecito già inviato. Vedi [Dati di base e di esempio](Dati-di-base-e-esempio). ## Permessi e licenza -Serve il modulo **FIN** (e ACCT per le registrazioni contabili automatiche). I codici dei permessi in testa sono -indicativi (convenzione `modulo.entità.azione`, SPEC §7.2) e saranno fissati in sviluppo. +| Permesso | Cosa consente | +|---|---| +| `finance.schedule.read` | vedere partite, distinte, mandati, solleciti, flusso di cassa e le scadenze sulla Home | +| `finance.schedule.write` | modificare le partite, creare e presentare le distinte, gestire mandati e solleciti | +| `finance.payment.read` | vedere incassi e pagamenti | +| `finance.payment.write` | registrare e stornare incassi e pagamenti | +| `finance.bank.reconcile` | importare gli estratti conto, riconciliare, gestire le regole | + +Serve il modulo **FIN**; le registrazioni contabili chiedono anche **ACCT**. ## Domande frequenti -**Il cliente ha pagato due fatture con un bonifico solo.** Seleziona entrambe le partite e registra un unico incasso, -distribuendo l'importo. +**Il cliente ha pagato due fatture con un bonifico solo.** Seleziona entrambe le partite e registra un unico incasso: +l'importo si distribuisce sulle rate, la più vecchia per prima. Se il bonifico arriva dall'estratto conto, *Abbina a +partite* fa la stessa cosa. -**Ho caricato l'estratto conto due volte.** Il riconoscimento dei movimenti già importati non è ancora definito -dalla specifica: sarà stabilito in sviluppo e descritto qui. +**Ho caricato l'estratto conto due volte.** Nessun problema: i movimenti già presenti vengono riconosciuti +dall'impronta (banca, data, importo, descrizione, riferimento) e saltati; il messaggio dice quanti. + +**Ho registrato un incasso sbagliato.** In *Incassi* premi **Annulla** sulla riga: la registrazione viene stornata e +le partite riaperte. Se l'incasso veniva dalla riconciliazione, la riga dell'estratto torna *Da abbinare*. + +**Una RiBa è tornata insoluta.** Apri la distinta in *Storico distinte* e premi **Insoluto** sulla riga (o confermalo +dalla riconciliazione): la partita torna aperta e le spese diventano una nuova partita da addebitare al cliente. + +**Perché un cliente non compare tra i solleciti?** È una pubblica amministrazione, ha partite contestate o in +distinta, oppure il prossimo livello non è ancora maturato. ## Pagine correlate -[Contabilità](Contabilita) · [Vendite](Vendite) · [Acquisti](Acquisti) · [Anagrafiche](Anagrafiche) · [IVA](IVA) · -[Automazioni](Automazioni) · [Report](Report) · [Attività programmate](Attivita-programmate) +[Contabilità](Contabilita) · [IVA](IVA) · [Vendite](Vendite) · [Acquisti](Acquisti) · [Anagrafiche](Anagrafiche) · +[Tabelle azienda](Tabelle-azienda) · [Dashboard](Dashboard) · [Attività programmate](Attivita-programmate) · +[Fiscalità italiana](Fiscalita-italiana) · [Report](Report) diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md index a89de1e..38fe4f3 100644 --- a/docs/wiki/Tabelle-azienda.md +++ b/docs/wiki/Tabelle-azienda.md @@ -98,7 +98,7 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura | **Codici IVA** | aliquota, natura SDI, riferimento normativo, esigibilità, tipo, indetraibilità, conti IVA, validità (vedi sotto) | | **Metodi di pagamento** | codici SDI `MP01`…`MP23` (es. MP01 contanti, MP02 assegno, MP05 bonifico, MP08 carta di pagamento, MP12 RiBa, MP19 SEPA Direct Debit) | | **Condizioni di pagamento** | con righe: rata, giorni, fine mese, giorno fisso, percentuale, IVA sulla prima rata; tipo SDI `TP01` (a rate), `TP02` (completo), `TP03` (anticipo) | -| **Banche aziendali** | IBAN, BIC, conto contabile, codici SIA/CUC per RiBa e SDD | +| **Banche aziendali** | IBAN, BIC, conto contabile, codice SIA (RiBa), CUC e identificativo creditore SEPA (SDD), banca predefinita; usate da incassi, distinte e riconciliazione dello [Scadenzario](Scadenzario) | | **Agenti** | provvigione, iscrizione ENASARCO | | **Vettori** | corrieri e trasportatori | | **Porti** (condizioni di spedizione) | franco, assegnato… | diff --git a/docs/wiki/Vendite.md b/docs/wiki/Vendite.md index 6d2b9aa..6813c31 100644 --- a/docs/wiki/Vendite.md +++ b/docs/wiki/Vendite.md @@ -11,8 +11,8 @@ e si inviano per e-mail. > **In questa versione** i documenti hanno numeri, totali, castelletto IVA, bollo, ritenute, scadenze, collegamenti > riga per riga, stampa ed e-mail. Dalla 0.6 i documenti **muovono il magazzino** (DDT e fatture > accompagnatorie scaricano, gli ordini impegnano: vedi [Magazzino](Magazzino)). Dalla 0.7 fatture e note -> **si contabilizzano** da sole (vedi [Contabilità](Contabilita)). Arrivano più avanti: gli **incassi** e il controllo -> del fido (M8), il **file XML** per lo +> **si contabilizzano** da sole (vedi [Contabilità](Contabilita)). Dalla 0.8 gli **incassi** si registrano dallo [Scadenzario](Scadenzario). +> Arrivano più avanti: il controllo del fido, il **file XML** per lo > SDI (M9) e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la > funzione c'è. diff --git a/docs/wiki/img/scadenzario-distinta-dettaglio.png b/docs/wiki/img/scadenzario-distinta-dettaglio.png new file mode 100644 index 0000000..0a48714 Binary files /dev/null and b/docs/wiki/img/scadenzario-distinta-dettaglio.png differ diff --git a/docs/wiki/img/scadenzario-distinte.png b/docs/wiki/img/scadenzario-distinte.png new file mode 100644 index 0000000..8767846 Binary files /dev/null and b/docs/wiki/img/scadenzario-distinte.png differ diff --git a/docs/wiki/img/scadenzario-flusso-di-cassa.png b/docs/wiki/img/scadenzario-flusso-di-cassa.png new file mode 100644 index 0000000..6969be7 Binary files /dev/null and b/docs/wiki/img/scadenzario-flusso-di-cassa.png differ diff --git a/docs/wiki/img/scadenzario-fornitori.png b/docs/wiki/img/scadenzario-fornitori.png new file mode 100644 index 0000000..f3a8ebd Binary files /dev/null and b/docs/wiki/img/scadenzario-fornitori.png differ diff --git a/docs/wiki/img/scadenzario-incassi.png b/docs/wiki/img/scadenzario-incassi.png new file mode 100644 index 0000000..f5c93f4 Binary files /dev/null and b/docs/wiki/img/scadenzario-incassi.png differ diff --git a/docs/wiki/img/scadenzario-incasso.png b/docs/wiki/img/scadenzario-incasso.png new file mode 100644 index 0000000..8878201 Binary files /dev/null and b/docs/wiki/img/scadenzario-incasso.png differ diff --git a/docs/wiki/img/scadenzario-mandati.png b/docs/wiki/img/scadenzario-mandati.png new file mode 100644 index 0000000..bac7b49 Binary files /dev/null and b/docs/wiki/img/scadenzario-mandati.png differ diff --git a/docs/wiki/img/scadenzario-pagamenti.png b/docs/wiki/img/scadenzario-pagamenti.png new file mode 100644 index 0000000..5ece883 Binary files /dev/null and b/docs/wiki/img/scadenzario-pagamenti.png differ diff --git a/docs/wiki/img/scadenzario-partite.png b/docs/wiki/img/scadenzario-partite.png new file mode 100644 index 0000000..f1ac803 Binary files /dev/null and b/docs/wiki/img/scadenzario-partite.png differ diff --git a/docs/wiki/img/scadenzario-riconciliazione.png b/docs/wiki/img/scadenzario-riconciliazione.png new file mode 100644 index 0000000..cbdbd5a Binary files /dev/null and b/docs/wiki/img/scadenzario-riconciliazione.png differ diff --git a/docs/wiki/img/scadenzario-solleciti.png b/docs/wiki/img/scadenzario-solleciti.png new file mode 100644 index 0000000..ccea82e Binary files /dev/null and b/docs/wiki/img/scadenzario-solleciti.png differ diff --git a/docs/wiki/img/scadenzario-sollecito-livello.png b/docs/wiki/img/scadenzario-sollecito-livello.png new file mode 100644 index 0000000..b99283a Binary files /dev/null and b/docs/wiki/img/scadenzario-sollecito-livello.png differ diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index 2558e67..51c3d98 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -60,6 +60,7 @@ public sealed class JobScheduler new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true), new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600), new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800), + new("finance.dunning", "Solleciti automatici", Treasury.DunningJob.JobType, "0 7 * * 1-5", 1800, UsesNetwork: true), ]; private readonly IUnitOfWorkFactory _factory; diff --git a/src/Khaemhat.Application/Ledger/JournalEntryService.cs b/src/Khaemhat.Application/Ledger/JournalEntryService.cs index bf0fe2f..54048f5 100644 --- a/src/Khaemhat.Application/Ledger/JournalEntryService.cs +++ b/src/Khaemhat.Application/Ledger/JournalEntryService.cs @@ -502,7 +502,10 @@ public sealed class JournalEntryService cancellationToken).ConfigureAwait(false); entry.ReversedById = reversal.Id; await uow.Repository().UpdateAsync(entry, cancellationToken).ConfigureAwait(false); - await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0"), cancellationToken).ConfigureAwait(false); + // Items the treasury touched stay: a new posting of the document takes them over (ADR 0038). + await uow.ExecuteAsync( + SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0 AND remittance_id IS NULL AND unpaid_count = 0 AND NOT EXISTS (SELECT 1 FROM remittance_lines r WHERE r.open_item_id = gl_open_items.id) AND NOT EXISTS (SELECT 1 FROM payment_lines p WHERE p.open_item_id = gl_open_items.id)"), + cancellationToken).ConfigureAwait(false); return reversal; } diff --git a/src/Khaemhat.Application/Ledger/LedgerPoster.cs b/src/Khaemhat.Application/Ledger/LedgerPoster.cs index 6292366..9567b38 100644 --- a/src/Khaemhat.Application/Ledger/LedgerPoster.cs +++ b/src/Khaemhat.Application/Ledger/LedgerPoster.cs @@ -108,7 +108,6 @@ public sealed class LedgerPoster { Copy(entry, existing); await LedgerStore.UpdateAsync(uow, existing, lines, vat, cancellationToken).ConfigureAwait(false); - await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {existing.Id}"), cancellationToken).ConfigureAwait(false); result = existing; } else if (await SameAsync(uow, existing, lines, cancellationToken).ConfigureAwait(false)) @@ -150,6 +149,7 @@ public sealed class LedgerPoster return; } + await LedgerStore.EnsureUnpaidAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false); if (existing.Status == GlEntryStatus.Final) { await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false); @@ -385,25 +385,70 @@ public sealed class LedgerPoster var rows = installments.Count > 0 ? installments.Select(i => (i.Number, i.DueDate, i.Amount, i.PaymentMethodId)).ToList() : [(1, header.DocumentDate, header.NetAmount != 0m ? header.NetAmount : header.TotalAmount, header.PaymentMethodId)]; + // The items keep their identity by installment (ADR 0038): collections, payments and remittances point at them, + // so a new posting of the document changes them in place and never takes away what was already collected. var repository = uow.Repository(); - foreach (var (number, due, amount, method) in rows) + var current = (await repository.ListAsync( + Query.For().Where(o => o.SourceFamily == family && o.SourceDocumentId == header.Id), cancellationToken).ConfigureAwait(false)).Items + .Where(o => o.ParentId is null).ToList(); + var direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable; + foreach (var (number, due, value, method) in rows) { - await repository.InsertAsync(new OpenItem + var amount = sign * value; + var item = current.FirstOrDefault(o => o.Installment == number); + if (item is null) { - Direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable, - PartyId = partyId, - AccountId = accountId, - EntryId = entry.Id, - SourceFamily = family, - SourceDocumentId = header.Id, - DocumentNumber = entry.DocumentNumber, - DocumentDate = entry.DocumentDate ?? header.DocumentDate, - Installment = number, - DueDate = due, - Amount = sign * amount, - PaymentMethodId = method, - IsDemo = header.IsDemo, - }, cancellationToken).ConfigureAwait(false); + await repository.InsertAsync(new OpenItem + { + Direction = direction, + PartyId = partyId, + AccountId = accountId, + EntryId = entry.Id, + SourceFamily = family, + SourceDocumentId = header.Id, + DocumentNumber = entry.DocumentNumber, + DocumentDate = entry.DocumentDate ?? header.DocumentDate, + Installment = number, + DueDate = due, + Amount = amount, + PaymentMethodId = method, + IsDemo = header.IsDemo, + }, cancellationToken).ConfigureAwait(false); + continue; + } + + current.Remove(item); + if (item.PaidAmount != 0m && (Math.Sign(amount) != Math.Sign(item.PaidAmount) || Math.Abs(amount) < Math.Abs(item.PaidAmount))) + { + throw new ValidationFailedException(["Amount:" + LedgerErrors.OpenItemPaid]); + } + + item.Direction = direction; + item.PartyId = partyId; + item.AccountId = accountId; + item.EntryId = entry.Id; + item.DocumentNumber = entry.DocumentNumber; + item.DocumentDate = entry.DocumentDate ?? header.DocumentDate; + item.Amount = amount; + if (item.RemittanceId is null) + { + item.DueDate = due; + item.PaymentMethodId = method; + } + + item.Status = Core.Treasury.OpenItemStates.Of(item); + item.Closed = item.Status == Core.Treasury.OpenItemStatus.Closed; + await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + + foreach (var left in current) + { + if (left.PaidAmount != 0m || left.RemittanceId is not null || left.UnpaidCount > 0) + { + throw new ValidationFailedException(["Installments:" + LedgerErrors.OpenItemPaid]); + } + + await repository.DeleteAsync(left.Id, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Khaemhat.Application/Ledger/LedgerStore.cs b/src/Khaemhat.Application/Ledger/LedgerStore.cs index 280b07b..41b553d 100644 --- a/src/Khaemhat.Application/Ledger/LedgerStore.cs +++ b/src/Khaemhat.Application/Ledger/LedgerStore.cs @@ -115,12 +115,25 @@ internal static class LedgerStore /// Removes an entry with its lines, VAT lines and open items. public static async Task DeleteAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) { + await EnsureUnpaidAsync(uow, entryId, cancellationToken).ConfigureAwait(false); await RemoveLinesAsync(uow, entryId, cancellationToken).ConfigureAwait(false); await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false); await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET reversed_by_id = NULL WHERE reversed_by_id = {entryId}"), cancellationToken).ConfigureAwait(false); await uow.Repository().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false); } + /// Refuses when an open item of the entry was collected, paid or put in a remittance (ADR 0038). + public static async Task EnsureUnpaidAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) + { + var touched = await uow.QuerySingleAsync( + SqlFragment.Of($"SELECT COUNT(*) FROM gl_open_items o WHERE o.entry_id = {entryId} AND (o.paid_amount <> 0 OR o.remittance_id IS NOT NULL OR o.unpaid_count > 0 OR EXISTS (SELECT 1 FROM payment_lines p WHERE p.open_item_id = o.id) OR EXISTS (SELECT 1 FROM remittance_lines r WHERE r.open_item_id = o.id))"), + cancellationToken).ConfigureAwait(false) ?? 0L; + if (touched > 0) + { + throw new Security.ValidationFailedException(["Status:" + LedgerErrors.OpenItemPaid]); + } + } + /// The lines of an entry, in order. public static async Task> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) => (await uow.Repository().ListAsync(Query.For().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken) diff --git a/src/Khaemhat.Application/Ledger/TaxService.cs b/src/Khaemhat.Application/Ledger/TaxService.cs index 6cbca92..a68e7e6 100644 --- a/src/Khaemhat.Application/Ledger/TaxService.cs +++ b/src/Khaemhat.Application/Ledger/TaxService.cs @@ -425,47 +425,7 @@ public sealed class TaxService } var before = Copy(withholding); - var operated = withholding.Direction == WithholdingDirection.Operated; - var entry = await PostWithholdingAsync(uow, withholding, paidOn, operated ? "RIT" : "RITS", cancellationToken).ConfigureAwait(false); - withholding.InvoicePaidOn = paidOn; - withholding.GlEntryId = entry?.Id; - if (operated) - { - withholding.Status = WithholdingStatus.Due; - withholding.PaymentCode ??= PaymentCodeOf(withholding, withholdingRules); - var due = settlementRules.WithholdingDue(paidOn.Year, paidOn.Month); - var code = withholding.PaymentCode; - var payments = uow.Repository(); - var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture); - var year = paidOn.Year; - var payment = await payments.FindAsync( - Query.For().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year - && t.ReferencePeriod == period && t.PaidOn == null), - cancellationToken).ConfigureAwait(false); - if (payment is null) - { - payment = new TaxPayment - { - DueDate = due, - PaymentCode = code, - ReferenceYear = year, - ReferencePeriod = period, - Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!, - Amount = withholding.Amount, - Source = TaxPaymentSource.Withholding, - IsDemo = withholding.IsDemo, - }; - payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false); - } - else - { - payment.Amount += withholding.Amount; - await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false); - } - - withholding.TaxPaymentId = payment.Id; - } - + await ApplyInvoicePaidAsync(uow, withholding, paidOn, settlementRules, withholdingRules, cancellationToken).ConfigureAwait(false); await uow.Repository().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false); await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false); await uow.CommitAsync(cancellationToken).ConfigureAwait(false); @@ -491,35 +451,7 @@ public sealed class TaxService } var before = Copy(withholding); - if (withholding.TaxPaymentId is { } paymentId && await uow.Repository().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment) - { - payment.Amount -= withholding.Amount; - if (payment.Amount == 0m) - { - await uow.Repository().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false); - } - else - { - await uow.Repository().UpdateAsync(payment, cancellationToken).ConfigureAwait(false); - } - } - - if (withholding.GlEntryId is { } entryId && await uow.Repository().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry) - { - if (entry.Status == GlEntryStatus.Final) - { - await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false); - } - else - { - await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false); - } - } - - withholding.InvoicePaidOn = null; - withholding.GlEntryId = null; - withholding.TaxPaymentId = null; - withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered; + await UndoInvoicePaidAsync(uow, withholding, Today(), actor.UserName, cancellationToken).ConfigureAwait(false); await uow.Repository().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false); await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false); await uow.CommitAsync(cancellationToken).ConfigureAwait(false); @@ -751,6 +683,90 @@ public sealed class TaxService // The entry of a withholding when its invoice is paid: operated, supplier debit / withholdings payable credit; // suffered, withholdings credit debit / customer credit. The party keeps its own account when it has one. + /// Takes back the payment of the invoice of a withholding: its F24 share and its entry. The caller writes the withholding. + internal static async Task UndoInvoicePaidAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string? userName, CancellationToken cancellationToken) + { + if (withholding.TaxPaymentId is { } paymentId && await uow.Repository().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment) + { + payment.Amount -= withholding.Amount; + if (payment.Amount == 0m) + { + await uow.Repository().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false); + } + else + { + await uow.Repository().UpdateAsync(payment, cancellationToken).ConfigureAwait(false); + } + } + + if (withholding.GlEntryId is { } entryId && await uow.Repository().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry) + { + if (entry.Status == GlEntryStatus.Final) + { + await JournalEntryService.ReverseAsync(uow, entry, date, userName, cancellationToken).ConfigureAwait(false); + } + else + { + await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false); + } + } + + withholding.InvoicePaidOn = null; + withholding.GlEntryId = null; + withholding.TaxPaymentId = null; + withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered; + } + + /// + /// Makes a withholding due because its invoice was paid: the entry of the withholding and the F24 line of the month + /// (used also by the payments of the schedule, ADR 0038). The caller writes the withholding and the history. + /// + internal static async Task ApplyInvoicePaidAsync( + IUnitOfWork uow, Withholding withholding, DateOnly paidOn, IVatSettlementRules settlementRules, IWithholdingRules? withholdingRules, CancellationToken cancellationToken) + { + var operated = withholding.Direction == WithholdingDirection.Operated; + var entry = await PostWithholdingAsync(uow, withholding, paidOn, operated ? "RIT" : "RITS", cancellationToken).ConfigureAwait(false); + withholding.InvoicePaidOn = paidOn; + withholding.GlEntryId = entry?.Id; + if (operated) + { + withholding.Status = WithholdingStatus.Due; + withholding.PaymentCode ??= PaymentCodeOf(withholding, withholdingRules); + var due = settlementRules.WithholdingDue(paidOn.Year, paidOn.Month); + var code = withholding.PaymentCode; + var payments = uow.Repository(); + var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture); + var year = paidOn.Year; + var payment = await payments.FindAsync( + Query.For().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year + && t.ReferencePeriod == period && t.PaidOn == null), + cancellationToken).ConfigureAwait(false); + if (payment is null) + { + payment = new TaxPayment + { + DueDate = due, + PaymentCode = code, + ReferenceYear = year, + ReferencePeriod = period, + Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!, + Amount = withholding.Amount, + Source = TaxPaymentSource.Withholding, + IsDemo = withholding.IsDemo, + }; + payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false); + } + else + { + payment.Amount += withholding.Amount; + await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false); + } + + withholding.TaxPaymentId = payment.Id; + } + + } + private static async Task PostWithholdingAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string templateCode, CancellationToken cancellationToken) { if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found) diff --git a/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs new file mode 100644 index 0000000..bc950ab --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs @@ -0,0 +1,374 @@ +using System.Globalization; +using System.Numerics; +using System.Text; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Treasury; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Seeding; + +/// +/// The demo treasury (SPEC §14, issues #69-#72): the bank account of the company, the collections of the invoices +/// paid by transfer (one only in part), the payments to the suppliers, a RiBa remittance presented and credited with an +/// unpaid effect, a direct debit mandate, a bank statement still to reconcile with a saved rule for the fees, and the +/// first reminder already sent to a customer. It runs after the demo ledger, only when the treasury (FIN) is licensed and only once: when the company has +/// collections or remittances it adds nothing. +/// +/// Collections and payments. +/// The remittances. +/// The mandates. +/// The bank statements. +/// Reads and writes the company. +/// Whether the treasury is licensed. +/// Today. +public sealed class DemoTreasurySeeder( + PaymentService payments, RemittanceService remittances, MandateService mandates, BankReconciliationService reconciliation, IUnitOfWorkFactory factory, + ILicenseGate licenses, TimeProvider clock) + : ICompanySeeder +{ + /// The code of the demo bank account. + public const string BankCode = "BPD"; + + /// The capital paid into the bank on the first day of the year. + public const decimal OpeningBalance = 25000m; + + /// The account of the capital paid in by the shareholders. + public const string CapitalAccount = "10.01.004"; + + /// The fees of the unpaid effect. + public const decimal UnpaidFees = 6.50m; + + /// The monthly fee of the bank account, matched by a saved rule. + public const decimal AccountFee = 12.50m; + + private static readonly Actor Seed = Actor.System; + + /// + public int Order => 50; + + /// An Italian IBAN with its check digits computed from ABI, CAB and account. + /// The CIN letter. + /// The ABI code. + /// The CAB code. + /// The account number (12 characters). + /// The IBAN. + public static string Iban(char cin, string abi, string cab, string account) + { + ArgumentNullException.ThrowIfNull(abi); + ArgumentNullException.ThrowIfNull(cab); + ArgumentNullException.ThrowIfNull(account); + var bban = cin + abi + cab + account; + var digits = new StringBuilder(); + foreach (var c in bban + "IT00") + { + digits.Append(char.IsLetter(c) ? (c - 'A' + 10).ToString(CultureInfo.InvariantCulture) : c.ToString()); + } + + var check = 98 - (int)(BigInteger.Parse(digits.ToString(), CultureInfo.InvariantCulture) % 97); + return "IT" + check.ToString("00", CultureInfo.InvariantCulture) + bban; + } + + /// + public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.Finance)) + { + return; + } + + var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + long bankId; + 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) + { + return; + } + + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + bankId = await BankAsync(uow, cancellationToken).ConfigureAwait(false); + await OpeningAsync(uow, new DateOnly(today.Year, 1, 1), cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await CollectionsAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false); + await RibaAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false); + await MandateAsync(companyCode, today, cancellationToken).ConfigureAwait(false); + await StatementAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false); + await RemindersAsync(companyCode, today, cancellationToken).ConfigureAwait(false); + } + + private static async Task BankAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var banks = uow.Repository(); + var bank = await banks.FindAsync(Query.For().Where(b => b.Code == BankCode), cancellationToken).ConfigureAwait(false); + if (bank is null) + { + bank = new BankAccount + { + Code = BankCode, + Description = "Conto corrente ordinario", + BankName = "Banca Popolare Dimostrativa", + Iban = Iban('X', "05034", "01000", "000000012345"), + Bic = "DEMOITM1XXX", + SiaCode = "A1B2C", + CucCode = "DEMO1234", + CreditorId = "IT66ZZZ00000000000000000", + AccountCode = DemoLedgerSeeder.BankAccount, + IsDefault = true, + IsDemo = true, + }; + bank.Id = await banks.InsertAsync(bank, cancellationToken).ConfigureAwait(false); + } + + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + if (profile is not null && profile.DefaultBankAccountId is null) + { + profile.DefaultBankAccountId = bank.Id; + await uow.Repository().UpdateAsync(profile, cancellationToken).ConfigureAwait(false); + } + + await CustomerBanksAsync(uow, cancellationToken).ConfigureAwait(false); + return bank.Id; + } + + // The shareholders paid the capital into the bank on the first day of the year, so the account starts in credit. + private static async Task OpeningAsync(IUnitOfWork uow, DateOnly day, CancellationToken cancellationToken) + { + var bank = await LedgerStore.AccountAsync(uow, DemoLedgerSeeder.BankAccount, cancellationToken).ConfigureAwait(false); + var capital = await LedgerStore.AccountAsync(uow, CapitalAccount, cancellationToken).ConfigureAwait(false); + if (bank is null || capital is null) + { + return; + } + + await TreasuryStore.PostAsync(uow, "GIRO", day, "Versamento soci in conto capitale", null, + [new PaymentPostedLine(bank.Id, null, null, null, OpeningBalance, 0m), new PaymentPostedLine(capital.Id, null, null, null, 0m, OpeningBalance)], true, cancellationToken) + .ConfigureAwait(false); + } + + // The customers who pay by RiBa or direct debit need the coordinates of their bank: the demo parties that have none + // get one, so the remittances are complete. + private static async Task CustomerBanksAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var collected = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .Where(m => m.Code is "RIBA" or "SDD" or "SDDB").Select(m => (long?)m.Id).ToList(); + var receivable = OpenItemDirection.Receivable; + var parties = (await uow.Repository().ListAsync( + Query.For().Where(o => o.Direction == receivable && !o.Closed && collected.Contains(o.PaymentMethodId)), cancellationToken).ConfigureAwait(false)).Items + .Select(o => o.PartyId).Distinct().Order().ToList(); + (string Abi, string Cab, string Name)[] branches = [("03069", "01000", "Banca del Territorio"), ("02008", "30330", "Banca Subalpina"), ("05696", "11000", "Credito Cooperativo Demo")]; + var n = 0; + foreach (var partyId in parties) + { + var accounts = uow.Repository(); + if (await accounts.CountAsync(Query.For().Where(a => a.PartyId == partyId), cancellationToken).ConfigureAwait(false) > 0) + { + continue; + } + + var branch = branches[n++ % branches.Length]; + await accounts.InsertAsync(new PartyBankAccount + { + PartyId = partyId, + Iban = Iban('K', branch.Abi, branch.Cab, (100000 + partyId).ToString("000000000000", CultureInfo.InvariantCulture)), + BankName = branch.Name, + BankCode = branch.Abi, + BranchCode = branch.Cab, + IsDefault = true, + }, cancellationToken).ConfigureAwait(false); + } + } + + // The invoices paid by transfer or on the spot are collected on their due date when it is more than three weeks + // ago; the oldest of one customer only in half, so the schedule shows a partial item. The suppliers, RiBa included, + // are paid on their due date when it is more than a week ago. + private async Task CollectionsAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken) + { + List items; + Dictionary methods; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) + { + var limit = today.AddDays(-7); + var customers = today.AddDays(-21); + items = [.. (await uow.Repository().ListAsync( + Query.For().Where(o => !o.Closed && o.DueDate <= limit).OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items + .Where(o => o.Direction == OpenItemDirection.Payable || o.DueDate <= customers)]; + methods = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id); + } + + var partialDone = false; + foreach (var item in items.Where(i => i.Residual > 0m)) + { + var method = item.PaymentMethodId is { } m ? methods.GetValueOrDefault(m) : null; + var receivable = item.Direction == OpenItemDirection.Receivable; + if (receivable && method?.Code is "RIBA" or "SDD" or "SDDB") + { + continue; + } + + var amount = item.Residual; + if (receivable && !partialDone && method?.Code == "BON") + { + // The first transfer collected only in half: the rest stays overdue for the reminders. + amount = Math.Round(item.Residual / 2m, 2, MidpointRounding.AwayFromZero); + partialDone = true; + } + + await payments.RegisterAsync(Seed, companyCode, new PaymentInput( + receivable ? PaymentDirection.Receipt : PaymentDirection.Disbursement, item.PartyId, item.DueDate, item.PaymentMethodId, bankId, + receivable ? 0m : 1.50m, "CRO " + item.Id.ToString("000000", CultureInfo.InvariantCulture), null, + [new PaymentLineInput(item.Id, amount)]), cancellationToken).ConfigureAwait(false); + } + } + + // The RiBa due before today in a remittance presented and credited, the effect of one customer back unpaid; + // those due in the next 45 days in a draft remittance ready for the file. + private async Task RibaAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken) + { + var due = (await remittances.CandidatesAsync(Seed, companyCode, RemittanceKind.Riba, today.AddDays(-1), cancellationToken).ConfigureAwait(false)) + .Where(c => c.Ready).ToList(); + if (due.Count > 0) + { + var presentation = due.Min(c => c.Row.Item.DueDate).AddDays(-20); + var remittance = await remittances.CreateAsync(Seed, companyCode, new RemittanceInput( + RemittanceKind.Riba, bankId, presentation, today.AddDays(-1), false, "Distinta dimostrativa", [.. due.Select(c => c.Row.Item.Id)]), cancellationToken).ConfigureAwait(false); + await remittances.PresentAsync(Seed, companyCode, remittance.Id, cancellationToken).ConfigureAwait(false); + var latest = due.Max(c => c.Row.Item.DueDate); + await remittances.CreditAsync(Seed, companyCode, remittance.Id, latest, cancellationToken).ConfigureAwait(false); + var lines = (await remittances.GetAsync(Seed, companyCode, remittance.Id, cancellationToken).ConfigureAwait(false))!.Value.Lines; + var unpaid = lines.OrderByDescending(l => l.Line.DueDate).First(); + var day = unpaid.Line.DueDate.AddDays(5); + await remittances.UnpaidAsync(Seed, companyCode, unpaid.Line.Id, day > today ? today : day, UnpaidFees, cancellationToken).ConfigureAwait(false); + } + + var next = (await remittances.CandidatesAsync(Seed, companyCode, RemittanceKind.Riba, today.AddDays(45), cancellationToken).ConfigureAwait(false)) + .Where(c => c.Ready && c.Row.Item.DueDate >= today && c.Row.Item.Status != OpenItemStatus.Unpaid).ToList(); + if (next.Count > 0) + { + await remittances.CreateAsync(Seed, companyCode, new RemittanceInput( + RemittanceKind.Riba, bankId, today, today.AddDays(45), true, "Da presentare con anticipo s.b.f.", [.. next.Select(c => c.Row.Item.Id)]), cancellationToken).ConfigureAwait(false); + } + } + + private async Task MandateAsync(string companyCode, DateOnly today, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var party = await uow.Repository().FindAsync(Query.For().Where(p => p.Name == "Idrotermica Piemonte S.r.l."), cancellationToken).ConfigureAwait(false); + if (party is null) + { + return; + } + + var account = await uow.Repository().FindAsync(Query.For().Where(a => a.PartyId == party.Id), cancellationToken).ConfigureAwait(false); + await mandates.SaveAsync(Seed, companyCode, new MandateInput( + null, party.Id, "KH-MND-" + party.Code, new DateOnly(today.Year, 1, 15), SddScheme.Core, account?.Iban ?? Iban('A', "06230", "10000", "000046012345"), null, false, + "Mandato firmato in sede"), cancellationToken).ConfigureAwait(false); + } + + // A statement of the last days in CSV: a transfer received for an open invoice, a transfer to a supplier + // already recorded, the monthly fee of the account (matched by a saved rule) and a movement nobody knows yet. + private async Task StatementAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken) + { + OpenItem? open; + Payment? paid; + string? openParty; + long? feeAccount; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) + { + var receivable = OpenItemDirection.Receivable; + // The customer who paid half pays the rest: the movement matches the item, which names the invoice. + open = (await uow.Repository().ListAsync( + Query.For().Where(o => o.Direction == receivable && !o.Closed && (o.Status == OpenItemStatus.Partial || o.Status == OpenItemStatus.Open)).OrderBy(o => o.DueDate), + cancellationToken).ConfigureAwait(false)).Items + .Where(o => o.Residual > 0m && o.DocumentNumber is not null && o.DueDate <= today) + .OrderByDescending(o => o.Status == OpenItemStatus.Partial).FirstOrDefault(); + openParty = open is null ? null : (await uow.Repository().GetAsync(open.PartyId, cancellationToken).ConfigureAwait(false))?.Name; + paid = await uow.Repository().FindAsync( + Query.For().Where(p => p.Direction == PaymentDirection.Disbursement).OrderByDescending(p => p.PaymentDate), cancellationToken).ConfigureAwait(false); + feeAccount = (await uow.Repository().FindAsync(Query.For().Where(a => a.Code == "21.03.011"), cancellationToken).ConfigureAwait(false))?.Id; + } + + if (feeAccount is { } fees) + { + await reconciliation.SaveRuleAsync(Seed, companyCode, new BankRuleInput(null, "Canone e commissioni", "COMMISSIONI", BankRuleDirection.Out, fees, "Canone mensile conto corrente", false), cancellationToken) + .ConfigureAwait(false); + } + + var culture = CultureInfo.GetCultureInfo("it-IT"); + var csv = new StringBuilder("Data contabile;Data valuta;Descrizione;Importo\r\n"); + void Row(DateOnly day, string text, decimal amount) => + csv.Append(day.ToString("dd/MM/yyyy", culture)).Append(';').Append(day.ToString("dd/MM/yyyy", culture)).Append(';').Append(text).Append(';') + .Append(amount.ToString("0.00", culture)).Append("\r\n"); + if (open is not null) + { + Row(today.AddDays(-4), "BONIFICO A VOSTRO FAVORE DA " + (openParty ?? string.Empty).ToUpperInvariant() + " SALDO FT " + open.DocumentNumber, open.Residual); + } + + if (paid is not null) + { + Row(paid.PaymentDate, "BONIFICO SEPA " + paid.Reference, -(paid.Amount + paid.Fees)); + } + + Row(today.AddDays(-3), "COMMISSIONI E CANONE MENSILE CONTO", -AccountFee); + Row(today.AddDays(-2), "PAGAMENTO POS CARBURANTE", -64.20m); + await reconciliation.ImportAsync(Seed, companyCode, bankId, "estratto-demo.csv", Encoding.UTF8.GetBytes(csv.ToString()), cancellationToken).ConfigureAwait(false); + } + + // The first reminder already sent ten days ago to the customer with the oldest overdue item. + private async Task RemindersAsync(string companyCode, DateOnly today, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var receivable = OpenItemDirection.Receivable; + var limit = today.AddDays(-20); + var overdue = (await uow.Repository().ListAsync( + Query.For().Where(o => o.Direction == receivable && !o.Closed && o.DueDate <= limit && o.Status != OpenItemStatus.InRemittance).OrderBy(o => o.DueDate), cancellationToken) + .ConfigureAwait(false)).Items.Where(o => o.Residual > 0m).ToList(); + var parties = await TreasuryStore.PartiesAsync(uow, overdue.Select(o => o.PartyId), cancellationToken).ConfigureAwait(false); + var first = overdue.FirstOrDefault(o => parties.TryGetValue(o.PartyId, out var p) && p.SubjectType != SubjectType.PublicAdministration); + if (first is null) + { + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return; + } + + var party = parties[first.PartyId]; + var items = overdue.Where(o => o.PartyId == first.PartyId).ToList(); + var sent = today.AddDays(-10); + await uow.Repository().InsertAsync(new DunningLetter + { + PartyId = party.Id, + Level = 1, + SentOn = sent, + Channel = DunningChannel.Email, + Recipients = party.Email, + Subject = "Promemoria scadenze", + ItemCount = items.Count, + OverdueAmount = items.Sum(i => i.Residual), + Status = DunningLetterStatus.Sent, + SentBy = "demo", + IsDemo = true, + }, cancellationToken).ConfigureAwait(false); + foreach (var item in items) + { + item.DunningLevel = 1; + item.LastDunningDate = sent; + await uow.Repository().UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Application/Treasury/BankReconciliationService.cs b/src/Khaemhat.Application/Treasury/BankReconciliationService.cs new file mode 100644 index 0000000..b356874 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/BankReconciliationService.cs @@ -0,0 +1,925 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Treasury; + +/// The result of an import of a bank statement. +/// The statement. +/// The new movements. +/// The movements already imported and skipped. +/// The movements with a proposal. +public sealed record StatementImport(BankStatement Statement, int Added, int Duplicates, int Suggested); + +/// A movement with the name of its party. +/// The movement. +/// The customer or supplier of the match. +public sealed record StatementLineRow(BankStatementLine Line, string? PartyName); + +/// The position of a bank account: the ledger against the bank. +/// The bank account. +/// The balance of its ledger account to the day. +/// The closing balance of its last statement. +/// The day of that balance. +/// Movements still to reconcile. +/// Their sum. +public sealed record BankPosition(long BankAccountId, decimal BookBalance, decimal? BankBalance, DateOnly? BankBalanceDate, int ToMatch, decimal ToMatchAmount); + +/// A saved rule being written. +/// The rule, or . +/// The name. +/// The text looked for in the description. +/// Money in, out or both. +/// The account posted against the bank. +/// The description of the entry. +/// Not used. +public sealed record BankRuleInput(long? Id, string Name, string Pattern, BankRuleDirection Direction, long AccountId, string? EntryDescription, bool Disabled); + +/// +/// The bank reconciliation (SPEC §11.8, mockup 057, ADR 0038): import of CSV, CBI and CAMT.053 statements without +/// duplicates, proposals with confidence from open items, payments recorded, F24, remittances, unpaid effects and saved +/// rules, confirmation one by one or of every proposal above the threshold, manual matching, entries on an account and +/// the position of the bank against the ledger. +/// +public sealed class BankReconciliationService +{ + /// The confidence from which the proposals are confirmed together. + public const int AutoConfirmThreshold = 90; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The clock. + public BankReconciliationService(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 fingerprint of a movement: the same movement imported twice has the same one. + /// The bank account. + /// The movement. + /// How many equal movements came before it in the same file. + /// 64 hexadecimal characters. + public static string Fingerprint(long bankAccountId, StatementMovement movement, int occurrence) + { + ArgumentNullException.ThrowIfNull(movement); + var text = string.Join( + "|", + bankAccountId.ToString(CultureInfo.InvariantCulture), + movement.BookingDate.ToString("yyyyMMdd", CultureInfo.InvariantCulture), + movement.Amount.ToString("0.00", CultureInfo.InvariantCulture), + BankMatcher.Normalize(movement.Description), + BankMatcher.Normalize(movement.Reference), + occurrence.ToString(CultureInfo.InvariantCulture)); + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + } + + /// Reads a bank file of any supported format. + /// The file. + /// The fiscal pack (its readers, such as CBI). + /// The statement. + /// The format is not recognized or the file cannot be read. + public static StatementFile Read(byte[] content, IFiscalPack? pack) + { + ArgumentNullException.ThrowIfNull(content); + var head = content.AsSpan(0, Math.Min(content.Length, 4096)); + try + { + if (Camt053Reader.Recognizes(head)) + { + using var stream = new MemoryStream(content); + return Camt053Reader.Read(stream); + } + + if (pack?.GetFeature() is { } reader && reader.Recognizes(head)) + { + using var stream = new MemoryStream(content); + return reader.Read(stream); + } + + var text = Encoding.UTF8.GetString(head).TrimStart(''); + var firstLine = text.Split('\n', 2)[0].TrimEnd('\r'); + if (CsvStatementReader.Detect(firstLine) is { } layout) + { + using var stream = new MemoryStream(content); + return CsvStatementReader.Read(stream, layout); + } + } + catch (BankFileException) + { + throw new ValidationFailedException(["File:" + TreasuryErrors.StatementFormat]); + } + + throw new ValidationFailedException(["File:" + TreasuryErrors.StatementFormat]); + } + + /// The statements imported for a bank account. + /// Who reads. + /// The company. + /// The bank account. + /// Cancellation. + /// The statements, latest first. + public async Task> StatementsAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync( + Query.For().Where(s => s.BankAccountId == bankAccountId).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false)).Items; + } + + /// Imports a bank file: the movements already imported are skipped, the new ones get their proposals. + /// Who imports it. + /// The company. + /// The bank account. + /// The name of the file. + /// The file. + /// Cancellation. + /// What was imported. + public async Task ImportAsync(Actor actor, string companyCode, long bankAccountId, string? fileName, byte[] content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(content); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var file = Read(content, pack); + if (file.Movements.Count == 0) + { + throw new ValidationFailedException(["File:" + TreasuryErrors.StatementEmpty]); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var bank = await uow.Repository().GetAsync(bankAccountId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]); + if (!string.IsNullOrWhiteSpace(file.AccountIban) && !string.IsNullOrWhiteSpace(bank.Iban) + && !string.Equals(IbanValidator.Normalize(file.AccountIban), IbanValidator.Normalize(bank.Iban), StringComparison.Ordinal)) + { + throw new ValidationFailedException(["File:" + TreasuryErrors.StatementAccount]); + } + + var statement = new BankStatement + { + BankAccountId = bankAccountId, + Format = file.Format, + FileName = LedgerStore.Trim(fileName, 200), + FromDate = file.FromDate ?? file.Movements.Min(m => m.BookingDate), + ToDate = file.ToDate ?? file.Movements.Max(m => m.BookingDate), + OpeningBalance = file.OpeningBalance, + ClosingBalance = file.ClosingBalance, + }; + statement.Id = await uow.Repository().InsertAsync(statement, cancellationToken).ConfigureAwait(false); + var lines = uow.Repository(); + var seen = new Dictionary(StringComparer.Ordinal); + int added = 0, duplicates = 0; + foreach (var movement in file.Movements) + { + var key = Fingerprint(bankAccountId, movement, 0); + seen[key] = seen.TryGetValue(key, out var count) ? count + 1 : 0; + var fingerprint = Fingerprint(bankAccountId, movement, seen[key]); + if (await lines.CountAsync(Query.For().Where(l => l.BankAccountId == bankAccountId && l.Fingerprint == fingerprint), cancellationToken).ConfigureAwait(false) > 0) + { + duplicates++; + continue; + } + + await lines.InsertAsync(new BankStatementLine + { + StatementId = statement.Id, + BankAccountId = bankAccountId, + BookingDate = movement.BookingDate, + ValueDate = movement.ValueDate, + Amount = movement.Amount, + Description = LedgerStore.Trim(string.IsNullOrWhiteSpace(movement.Description) ? "-" : movement.Description.Trim(), 500)!, + Reference = LedgerStore.Trim(movement.Reference, 60), + CounterpartyName = LedgerStore.Trim(movement.CounterpartyName, 140), + CounterpartyIban = LedgerStore.Trim(movement.CounterpartyIban, 34), + BankCode = LedgerStore.Trim(movement.BankCode, 40), + Fingerprint = fingerprint, + Status = StatementLineStatus.ToMatch, + MatchKind = StatementMatchKind.None, + }, cancellationToken).ConfigureAwait(false); + added++; + } + + statement.MovementCount = added; + await uow.Repository().UpdateAsync(statement, cancellationToken).ConfigureAwait(false); + var suggested = await SuggestAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, statement.Id, null, statement, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return new StatementImport(statement, added, duplicates, suggested); + } + + /// The movements of a bank account. + /// Who reads. + /// The company. + /// The bank account. + /// Only those to reconcile (to match or suggested). + /// From this day. + /// Up to this day. + /// Cancellation. + /// The movements, by date. + public async Task> LinesAsync( + Actor actor, string companyCode, long bankAccountId, bool onlyOpen, DateOnly? from = null, DateOnly? to = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For().Where(l => l.BankAccountId == bankAccountId); + if (onlyOpen) + { + query = query.Where(l => l.Status == StatementLineStatus.ToMatch || l.Status == StatementLineStatus.Suggested); + } + + if (from is { } f) + { + query = query.Where(l => l.BookingDate >= f); + } + + if (to is { } t) + { + query = query.Where(l => l.BookingDate <= t); + } + + var lines = (await uow.Repository().ListAsync(query.OrderByDescending(l => l.BookingDate).OrderBy(l => l.Id), cancellationToken).ConfigureAwait(false)).Items; + var parties = await TreasuryStore.PartiesAsync(uow, lines.Where(l => l.PartyId is not null).Select(l => l.PartyId!.Value), cancellationToken).ConfigureAwait(false); + return [.. lines.Select(l => new StatementLineRow(l, l.PartyId is { } p ? parties.GetValueOrDefault(p)?.Name : null))]; + } + + /// The position of a bank account. + /// Who reads. + /// The company. + /// The bank account. + /// Cancellation. + /// The position. + public async Task PositionAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var bank = await uow.Repository().GetAsync(bankAccountId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var account = await LedgerStore.AccountAsync(uow, bank.AccountCode, cancellationToken).ConfigureAwait(false); + var today = TreasuryStore.Today(_clock); + var draft = nameof(GlEntryStatus.Draft); + var book = account is null + ? 0m + : await uow.QuerySingleAsync( + SqlFragment.Of($"SELECT SUM(debit - credit) FROM gl_entry_lines WHERE account_id = {account.Id} AND status <> {draft} AND entry_date <= {today}"), cancellationToken).ConfigureAwait(false) ?? 0m; + var last = await uow.Repository().FindAsync( + Query.For().Where(s => s.BankAccountId == bankAccountId && s.ClosingBalance != null).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false); + var open = (await uow.Repository().ListAsync( + Query.For().Where(l => l.BankAccountId == bankAccountId && (l.Status == StatementLineStatus.ToMatch || l.Status == StatementLineStatus.Suggested)), cancellationToken) + .ConfigureAwait(false)).Items; + return new BankPosition(bankAccountId, book, last?.ClosingBalance, last?.ToDate, open.Count, open.Sum(l => l.Amount)); + } + + /// Computes the proposals again for the movements to reconcile. + /// Who does it. + /// The company. + /// The bank account. + /// Cancellation. + /// The movements with a proposal. + public async Task RefreshAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var count = await SuggestAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return count; + } + + /// Confirms the proposal of a movement. + /// Who confirms. + /// The company. + /// The movement. + /// Cancellation. + /// The movement. + public async Task ConfirmAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + 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); + var line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false); + await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return line; + } + + /// Confirms every proposal at or above the threshold. + /// Who confirms. + /// The company. + /// The bank account. + /// Cancellation. + /// How many movements were reconciled. + public async Task ConfirmAllAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + 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); + var lines = (await uow.Repository().ListAsync( + Query.For().Where(l => l.BankAccountId == bankAccountId && l.Status == StatementLineStatus.Suggested && l.Confidence >= AutoConfirmThreshold) + .OrderBy(l => l.BookingDate).OrderBy(l => l.Id), cancellationToken).ConfigureAwait(false)).Items; + var done = 0; + var used = new HashSet(StringComparer.Ordinal); + foreach (var line in lines) + { + // Two movements proposing the same target: only the first is confirmed, the other waits. + if (line.Targets is { } targets && !used.Add(line.MatchKind + ":" + targets)) + { + continue; + } + + try + { + await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false); + done++; + } + catch (ValidationFailedException) + { + // A proposal no longer valid (the item was settled meanwhile) stays to be reviewed. + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return done; + } + + /// Reconciles a movement with open items chosen by hand: a collection or payment is recorded. + /// Who does it. + /// The company. + /// The movement. + /// The items, oldest first. + /// Cancellation. + /// The movement. + public async Task MatchItemsAsync(Actor actor, string companyCode, long lineId, IReadOnlyList openItemIds, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(openItemIds); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + 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); + var line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false); + line.MatchKind = StatementMatchKind.OpenItems; + line.Targets = string.Join(",", openItemIds.Select(i => i.ToString(CultureInfo.InvariantCulture))); + await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return line; + } + + /// Reconciles a movement with a collection or payment already recorded. + /// Who does it. + /// The company. + /// The movement. + /// The payment. + /// Cancellation. + /// The movement. + public async Task MatchPaymentAsync(Actor actor, string companyCode, long lineId, long paymentId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + 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); + var line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false); + line.MatchKind = StatementMatchKind.Payment; + line.Targets = paymentId.ToString(CultureInfo.InvariantCulture); + await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return line; + } + + /// Posts a movement on an account against the bank, and may save a rule for the next ones. + /// Who does it. + /// The company. + /// The movement. + /// The account. + /// The description of the entry. + /// The text of a rule to save, or . + /// Cancellation. + /// The movement. + public async Task PostAsync( + Actor actor, string companyCode, long lineId, long accountId, string? description, string? rulePattern, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + 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); + var line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false); + var account = await uow.Repository().GetAsync(accountId, cancellationToken).ConfigureAwait(false); + if (account is null || !account.Postable || account.Disabled || account.SubLedger) + { + throw new ValidationFailedException(["AccountId:" + LedgerErrors.AccountNotPostable]); + } + + long? ruleId = null; + if (!string.IsNullOrWhiteSpace(rulePattern)) + { + var rule = new BankMatchRule + { + Name = LedgerStore.Trim(rulePattern.Trim(), 100)!, + Pattern = LedgerStore.Trim(rulePattern.Trim().ToUpperInvariant(), 100)!, + Direction = line.Amount < 0m ? BankRuleDirection.Out : BankRuleDirection.In, + AccountId = accountId, + TemplateCode = "SPB", + EntryDescription = LedgerStore.Trim(string.IsNullOrWhiteSpace(description) ? null : description.Trim(), 200), + }; + ruleId = await uow.Repository().InsertAsync(rule, cancellationToken).ConfigureAwait(false); + } + + await PostEntryAsync(uow, pack, line, accountId, string.IsNullOrWhiteSpace(description) ? line.Description : description.Trim(), "SPB", cancellationToken).ConfigureAwait(false); + Matched(line, StatementMatchKind.Entry, actor.UserName); + line.RuleId = ruleId; + await uow.Repository().UpdateAsync(line, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return line; + } + + /// Leaves a movement out of the reconciliation (a transfer between own accounts already posted). + /// Who does it. + /// The company. + /// The movement. + /// Cancellation. + /// A task. + public async Task IgnoreAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false); + line.Status = StatementLineStatus.Ignored; + line.MatchedAt = _clock.GetUtcNow().UtcDateTime; + line.MatchedBy = actor.UserName; + await uow.Repository().UpdateAsync(line, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Takes a reconciliation back: the collection or entry it made is cancelled, a link to a payment is removed. + /// Credits and unpaid effects of remittances are taken back from the remittance. + /// + /// Who does it. + /// The company. + /// The movement. + /// Cancellation. + /// A task. + public async Task ResetAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var line = await uow.Repository().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var today = TreasuryStore.Today(_clock); + if (line.Status == StatementLineStatus.Matched) + { + switch (line.MatchKind) + { + case StatementMatchKind.OpenItems when line.PaymentId is { } paymentId: + if (await uow.Repository().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment) + { + await PaymentService.CancelAsync(uow, payment, today, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + break; + case StatementMatchKind.Payment when line.PaymentId is { } linked: + await uow.ExecuteAsync(SqlFragment.Of($"UPDATE payments SET statement_line_id = NULL WHERE id = {linked}"), cancellationToken).ConfigureAwait(false); + break; + case StatementMatchKind.Rule or StatementMatchKind.Entry: + await TreasuryStore.UndoEntryAsync(uow, line.GlEntryId, today, actor.UserName, cancellationToken).ConfigureAwait(false); + break; + case StatementMatchKind.RemittanceCredit or StatementMatchKind.Unpaid: + throw new ValidationFailedException(["Id:" + TreasuryErrors.FromRemittance]); + default: + break; + } + } + + line = await uow.Repository().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? line; + line.Status = StatementLineStatus.ToMatch; + line.MatchKind = StatementMatchKind.None; + line.Confidence = 0; + line.Proposal = null; + line.Targets = null; + line.PartyId = null; + line.RuleId = null; + line.PaymentId = null; + line.GlEntryId = null; + line.MatchedAt = null; + line.MatchedBy = null; + await uow.Repository().UpdateAsync(line, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// The saved rules. + /// Who reads. + /// The company. + /// Cancellation. + /// The rules, by name. + public async Task> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync(Query.For().OrderBy(r => r.Name), cancellationToken).ConfigureAwait(false)).Items; + } + + /// Writes a rule. + /// Who writes. + /// The company. + /// The rule. + /// Cancellation. + /// The rule. + public async Task SaveRuleAsync(Actor actor, string companyCode, BankRuleInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(input.Pattern) || string.IsNullOrWhiteSpace(input.Name) || input.AccountId <= 0) + { + throw new ValidationFailedException(["Pattern:" + TreasuryErrors.RulePattern]); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var rule = input.Id is { } id ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound) : new BankMatchRule(); + rule.Name = LedgerStore.Trim(input.Name.Trim(), 100)!; + rule.Pattern = LedgerStore.Trim(input.Pattern.Trim().ToUpperInvariant(), 100)!; + rule.Direction = input.Direction; + rule.AccountId = input.AccountId; + rule.TemplateCode ??= "SPB"; + rule.EntryDescription = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.EntryDescription) ? null : input.EntryDescription.Trim(), 200); + rule.Disabled = input.Disabled; + if (input.Id is null) + { + rule.Id = await repository.InsertAsync(rule, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(rule, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return rule; + } + + /// Deletes a rule. + /// Who does it. + /// The company. + /// The rule. + /// Cancellation. + /// A task. + public async Task DeleteRuleAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await uow.ExecuteAsync(SqlFragment.Of($"UPDATE bank_statement_lines SET rule_id = NULL WHERE rule_id = {id}"), cancellationToken).ConfigureAwait(false); + await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Gives the movements to reconcile of a bank account their best proposal. + internal static async Task SuggestAsync(IUnitOfWork uow, long bankAccountId, CancellationToken cancellationToken) + { + var lines = (await uow.Repository().ListAsync( + Query.For().Where(l => l.BankAccountId == bankAccountId && (l.Status == StatementLineStatus.ToMatch || l.Status == StatementLineStatus.Suggested)), + cancellationToken).ConfigureAwait(false)).Items; + if (lines.Count == 0) + { + return 0; + } + + var candidates = await CandidatesAsync(uow, bankAccountId, lines.Min(l => l.BookingDate).AddDays(-60), cancellationToken).ConfigureAwait(false); + var accounts = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id); + var rules = (await uow.Repository().ListAsync(Query.For().Where(r => !r.Disabled), cancellationToken).ConfigureAwait(false)).Items + .Select(r => new MatchRule(r.Id, r.Pattern, r.Direction, "Regola '" + r.Name + "' → " + (accounts.TryGetValue(r.AccountId, out var a) ? a.Code + " " + a.Description : string.Empty))) + .ToList(); + var count = 0; + foreach (var line in lines) + { + var movement = new StatementMovement(line.BookingDate, line.ValueDate, line.Amount, line.Description, line.Reference, line.CounterpartyName, line.CounterpartyIban, line.BankCode); + var best = BankMatcher.Best(movement, candidates, rules); + if (best is null) + { + line.Status = StatementLineStatus.ToMatch; + line.MatchKind = StatementMatchKind.None; + line.Confidence = 0; + line.Proposal = null; + line.Targets = null; + line.PartyId = null; + line.RuleId = null; + } + else + { + line.Status = StatementLineStatus.Suggested; + line.MatchKind = best.Kind; + line.Confidence = best.Confidence; + line.Proposal = LedgerStore.Trim(best.Label, 300); + line.Targets = LedgerStore.Trim(best.Targets, 300); + line.PartyId = best.PartyId; + line.RuleId = best.RuleId; + count++; + } + + await uow.Repository().UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + + return count; + } + + private static async Task> CandidatesAsync(IUnitOfWork uow, long bankAccountId, DateOnly since, CancellationToken cancellationToken) + { + var result = new List(); + var items = (await uow.Repository().ListAsync( + Query.For().Where(o => !o.Closed && o.Status != OpenItemStatus.InRemittance && !o.Disputed).OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items + .Where(o => o.Residual != 0m).ToList(); + var payments = (await uow.Repository().ListAsync( + Query.For().Where(p => p.StatementLineId == null && p.PaymentDate >= since && (p.BankAccountId == bankAccountId || p.BankAccountId == null)), cancellationToken).ConfigureAwait(false)).Items + .Where(p => p.Origin != PaymentOrigin.Remittance).ToList(); + var partyIds = items.Select(i => i.PartyId).Concat(payments.Select(p => p.PartyId)).Distinct().ToList(); + var parties = await TreasuryStore.PartiesAsync(uow, partyIds, cancellationToken).ConfigureAwait(false); + var ibans = new Dictionary>(); + foreach (var chunk in partyIds.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var account in (await uow.Repository().ListAsync(Query.For().Where(a => list.Contains(a.PartyId)), cancellationToken).ConfigureAwait(false)).Items) + { + (ibans.TryGetValue(account.PartyId, out var found) ? found : ibans[account.PartyId] = []).Add(IbanValidator.Normalize(account.Iban)); + } + } + + IReadOnlyList Names(long partyId) => parties.GetValueOrDefault(partyId) is { } p ? [p.Name, .. p.FiscalName is { } f ? new[] { f } : []] : []; + IReadOnlyList Ibans(long partyId) => ibans.GetValueOrDefault(partyId) ?? []; + foreach (var item in items) + { + var receivable = item.Direction == OpenItemDirection.Receivable; + var name = parties.GetValueOrDefault(item.PartyId)?.Name ?? string.Empty; + result.Add(new MatchCandidate( + StatementMatchKind.OpenItems, + item.Id.ToString(CultureInfo.InvariantCulture), + item.PartyId, + receivable ? item.Residual : -item.Residual, + item.DueDate, + (receivable ? "Incasso " : "Pagamento ") + (item.DocumentNumber ?? string.Empty) + " · " + name, + item.DocumentNumber is { } number ? [number] : [], + Names(item.PartyId), + Ibans(item.PartyId), + [])); + } + + // Several items of a party paid together. + foreach (var group in items.GroupBy(i => (i.PartyId, i.Direction)).Where(g => g.Count() > 1)) + { + var list = group.ToList(); + var receivable = group.Key.Direction == OpenItemDirection.Receivable; + var total = list.Sum(i => i.Residual); + result.Add(new MatchCandidate( + StatementMatchKind.OpenItems, + string.Join(",", list.Select(i => i.Id.ToString(CultureInfo.InvariantCulture))), + group.Key.PartyId, + receivable ? total : -total, + list.Max(i => i.DueDate), + (receivable ? "Incasso " : "Pagamento ") + list.Count.ToString(CultureInfo.InvariantCulture) + " partite · " + (parties.GetValueOrDefault(group.Key.PartyId)?.Name ?? string.Empty), + [.. list.Where(i => i.DocumentNumber is not null).Select(i => i.DocumentNumber!)], + Names(group.Key.PartyId), + Ibans(group.Key.PartyId), + [])); + } + + foreach (var payment in payments) + { + var receipt = payment.Direction == PaymentDirection.Receipt; + var money = receipt ? payment.Amount - payment.Fees : -(payment.Amount + payment.Fees); + result.Add(new MatchCandidate( + StatementMatchKind.Payment, + payment.Id.ToString(CultureInfo.InvariantCulture), + payment.PartyId, + money, + payment.PaymentDate, + (receipt ? "Incasso registrato " : "Pagamento registrato ") + payment.PaymentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + " · " + (parties.GetValueOrDefault(payment.PartyId)?.Name ?? string.Empty), + payment.Reference is { } reference ? [reference] : [], + Names(payment.PartyId), + Ibans(payment.PartyId), + [])); + } + + // F24 paid from this bank: one movement per day. + var linked = (await uow.QueryAsync(SqlFragment.Of($"SELECT gl_entry_id FROM bank_statement_lines WHERE gl_entry_id IS NOT NULL AND match_kind = {nameof(StatementMatchKind.TaxPayment)}"), cancellationToken) + .ConfigureAwait(false)).ToHashSet(); + var taxes = (await uow.Repository().ListAsync( + Query.For().Where(t => t.PaidOn != null && t.PaidOn >= since && t.GlEntryId != null), cancellationToken).ConfigureAwait(false)).Items + .Where(t => !linked.Contains(t.GlEntryId!.Value) && (t.BankAccountId is null || t.BankAccountId == bankAccountId)).ToList(); + foreach (var group in taxes.GroupBy(t => t.GlEntryId!.Value)) + { + var total = group.Sum(t => t.Amount); + result.Add(new MatchCandidate( + StatementMatchKind.TaxPayment, group.Key.ToString(CultureInfo.InvariantCulture), null, -total, group.First().PaidOn!.Value, + "Versamento F24 del " + group.First().PaidOn!.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), [], [], [], ["F24"])); + } + + // Remittances to credit and their effects that may come back unpaid. + var remittances = (await uow.Repository().ListAsync( + Query.For().Where(r => r.BankAccountId == bankAccountId && (r.Status == RemittanceStatus.Presented || r.Status == RemittanceStatus.Closed) && r.Kind != RemittanceKind.SepaCreditTransfer), + cancellationToken).ConfigureAwait(false)).Items; + foreach (var remittance in remittances) + { + var lines = await RemittanceService.LinesAsync(uow, remittance.Id, cancellationToken).ConfigureAwait(false); + if (remittance.Status == RemittanceStatus.Presented && !remittance.Advance) + { + var included = lines.Where(l => l.Status == RemittanceLineStatus.Included).ToList(); + if (included.Count > 0) + { + result.Add(new MatchCandidate( + StatementMatchKind.RemittanceCredit, remittance.Id.ToString(CultureInfo.InvariantCulture), null, included.Sum(l => l.Amount), included.Max(l => l.DueDate), + "Accredito distinta " + remittance.DisplayNumber, [remittance.DisplayNumber, .. remittance.MessageId is { } m ? new[] { m } : []], [], [], [])); + } + } + + foreach (var line in lines.Where(l => l.Status != RemittanceLineStatus.Unpaid)) + { + result.Add(new MatchCandidate( + StatementMatchKind.Unpaid, line.Id.ToString(CultureInfo.InvariantCulture), line.PartyId, -line.Amount, line.DueDate, + "Insoluto " + (parties.GetValueOrDefault(line.PartyId)?.Name ?? string.Empty) + " distinta " + remittance.DisplayNumber, + line.EndToEndId is { } e ? [e] : [], Names(line.PartyId), Ibans(line.PartyId), ["INSOLUT"], 30m)); + } + } + + return result; + } + + private async Task ApplyAsync(IUnitOfWork uow, IFiscalPack pack, BankStatementLine line, string? userName, CancellationToken cancellationToken) + { + var targets = (line.Targets ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(t => long.Parse(t, CultureInfo.InvariantCulture)).ToList(); + switch (line.MatchKind) + { + case StatementMatchKind.OpenItems: + { + var repository = uow.Repository(); + var items = new List(); + foreach (var id in targets) + { + items.Add(await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound])); + } + + if (items.Count == 0 || items.Select(i => (i.PartyId, i.Direction)).Distinct().Count() != 1 + || (items[0].Direction == OpenItemDirection.Receivable) != (line.Amount > 0m)) + { + throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]); + } + + var amount = Math.Abs(line.Amount); + var residuals = items.Select(i => Math.Abs(i.Residual)).ToList(); + if (amount > residuals.Sum()) + { + throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]); + } + + var allocation = PaymentAllocator.Allocate(residuals, amount); + var input = new PaymentInput( + line.Amount > 0m ? PaymentDirection.Receipt : PaymentDirection.Disbursement, + items[0].PartyId, + line.BookingDate, + null, + line.BankAccountId, + 0m, + line.Reference, + LedgerStore.Trim(line.Description, 500), + [.. items.Select((item, i) => new PaymentLineInput(item.Id, Math.Sign(item.Residual) * allocation[i])).Where(l => l.Amount != 0m)]); + var payment = await PaymentService.RegisterAsync(uow, pack, input, PaymentOrigin.BankStatement, null, line.Id, cancellationToken).ConfigureAwait(false); + line.PaymentId = payment.Id; + line.GlEntryId = payment.GlEntryId; + line.PartyId = payment.PartyId; + break; + } + + case StatementMatchKind.Payment: + { + var payment = await uow.Repository().GetAsync(targets.Single(), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound]); + if (payment.StatementLineId is not null) + { + throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchDone]); + } + + payment.StatementLineId = line.Id; + await uow.Repository().UpdateAsync(payment, cancellationToken).ConfigureAwait(false); + line.PaymentId = payment.Id; + line.GlEntryId = payment.GlEntryId; + line.PartyId = payment.PartyId; + break; + } + + case StatementMatchKind.TaxPayment: + line.GlEntryId = targets.Single(); + break; + + case StatementMatchKind.RemittanceCredit: + { + var remittance = await uow.Repository().GetAsync(targets.Single(), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound]); + await RemittanceService.CreditInsideAsync(uow, pack, remittance, line.BookingDate, cancellationToken).ConfigureAwait(false); + line.GlEntryId = remittance.CreditEntryId; + break; + } + + case StatementMatchKind.Unpaid: + { + var remittanceLine = await uow.Repository().GetAsync(targets.Single(), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound]); + var fees = Math.Max(0m, Math.Abs(line.Amount) - remittanceLine.Amount); + await RemittanceService.UnpaidInsideAsync(uow, pack, remittanceLine, line.BookingDate, fees, cancellationToken).ConfigureAwait(false); + line.GlEntryId = remittanceLine.UnpaidEntryId; + line.PartyId = remittanceLine.PartyId; + break; + } + + case StatementMatchKind.Rule: + { + var rule = line.RuleId is { } ruleId ? await uow.Repository().GetAsync(ruleId, cancellationToken).ConfigureAwait(false) : null; + if (rule is null) + { + throw new ValidationFailedException(["RuleId:" + TreasuryErrors.NotFound]); + } + + await PostEntryAsync(uow, pack, line, rule.AccountId, rule.EntryDescription ?? line.Description, rule.TemplateCode ?? "SPB", cancellationToken).ConfigureAwait(false); + rule.Uses++; + await uow.Repository().UpdateAsync(rule, cancellationToken).ConfigureAwait(false); + break; + } + + default: + throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]); + } + + Matched(line, line.MatchKind, userName); + await uow.Repository().UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + + private static async Task PostEntryAsync(IUnitOfWork uow, IFiscalPack pack, BankStatementLine line, long accountId, string description, string templateCode, CancellationToken cancellationToken) + { + var template = await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false); + var bank = await TreasuryStore.BankAsync(uow, line.BankAccountId, cancellationToken).ConfigureAwait(false); + var money = await TreasuryStore.MoneyAccountAsync(uow, bank, false, template?.Lines, pack.GetFeature(), cancellationToken).ConfigureAwait(false); + var amount = Math.Abs(line.Amount); + var text = LedgerStore.Trim(description, 200)!; + IReadOnlyList lines = line.Amount < 0m + ? [new PaymentPostedLine(accountId, null, null, text, amount, 0m), new PaymentPostedLine(money, null, null, text, 0m, amount)] + : [new PaymentPostedLine(money, null, null, text, amount, 0m), new PaymentPostedLine(accountId, null, null, text, 0m, amount)]; + var entry = await TreasuryStore.PostAsync(uow, templateCode, line.BookingDate, text, null, lines, line.IsDemo, cancellationToken).ConfigureAwait(false); + line.GlEntryId = entry.Id; + } + + private static async Task OpenLineAsync(IUnitOfWork uow, long lineId, CancellationToken cancellationToken) + { + var line = await uow.Repository().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + if (line.Status is StatementLineStatus.Matched or StatementLineStatus.Ignored) + { + throw new ValidationFailedException(["Id:" + TreasuryErrors.MatchDone]); + } + + return line; + } + + private void Matched(BankStatementLine line, StatementMatchKind kind, string? userName) + { + line.Status = StatementLineStatus.Matched; + line.MatchKind = kind; + line.MatchedAt = _clock.GetUtcNow().UtcDateTime; + line.MatchedBy = userName; + } +} diff --git a/src/Khaemhat.Application/Treasury/CashFlowService.cs b/src/Khaemhat.Application/Treasury/CashFlowService.cs new file mode 100644 index 0000000..8c7545e --- /dev/null +++ b/src/Khaemhat.Application/Treasury/CashFlowService.cs @@ -0,0 +1,251 @@ +using System.Globalization; +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.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Treasury; + +/// The balance of a bank or cash account in the ledger. +/// The bank account, or for the cash. +/// Its name. +/// Its ledger balance today. +public sealed record CashAccountBalance(long? BankAccountId, string Name, decimal Balance); + +/// The cash flow forecast. +/// The first day. +/// How many days. +/// The banks and the cash with their balance. +/// The money today. +/// The periods with what comes in, goes out and the balance after. +/// The movements forecast, by date. +/// The sources included. +public sealed record CashFlowForecast( + DateOnly From, int Days, IReadOnlyList Accounts, decimal Opening, IReadOnlyList Periods, IReadOnlyList Movements, + IReadOnlySet Sources); + +/// +/// The cash flow forecast (SPEC §11.8 report "flusso di cassa 90 gg", ADR 0038): the money of the banks and the cash +/// today and what the open items, the remittances presented, the orders not yet invoiced, the recurring entries and the +/// taxes to pay will move, week by week. The overdue items fall in the first week. +/// +public sealed class CashFlowService +{ + /// The days after the delivery when an order is expected to be paid. + public const int OrderPaymentDays = 30; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The clock. + public CashFlowService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _clock = clock; + } + + /// The forecast. + /// Who reads. + /// The company. + /// How many days ahead (30 to 365). + /// The sources to include, or for all. + /// The length of a period (7 for weeks, 30 for months). + /// Cancellation. + /// The forecast. + public async Task ForecastAsync( + Actor actor, string companyCode, int days = 90, IReadOnlySet? sources = null, int periodDays = 7, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + days = Math.Clamp(days, 30, 365); + var include = sources ?? Enum.GetValues().ToHashSet(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var today = TreasuryStore.Today(_clock); + var until = today.AddDays(days - 1); + var accounts = await BalancesAsync(uow, today, cancellationToken).ConfigureAwait(false); + var movements = new List(); + var parties = new Dictionary(); + + if (include.Contains(CashFlowSource.Receivables) || include.Contains(CashFlowSource.Payables)) + { + var items = (await uow.Repository().ListAsync( + Query.For().Where(o => !o.Closed && o.DueDate <= until), cancellationToken).ConfigureAwait(false)).Items; + foreach (var (id, party) in await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false)) + { + parties[id] = party.Name; + } + + foreach (var item in items.Where(i => i.Residual != 0m)) + { + var receivable = item.Direction == OpenItemDirection.Receivable; + if (!include.Contains(receivable ? CashFlowSource.Receivables : CashFlowSource.Payables)) + { + continue; + } + + movements.Add(new CashFlowMovement( + item.DueDate, receivable ? item.Residual : -item.Residual, receivable ? CashFlowSource.Receivables : CashFlowSource.Payables, + (item.DocumentNumber ?? string.Empty) + " · " + parties.GetValueOrDefault(item.PartyId))); + } + + if (include.Contains(CashFlowSource.Receivables)) + { + // Effects presented without advance: the bank credits them at maturity. + var presented = (await uow.Repository().ListAsync( + Query.For().Where(r => r.Status == RemittanceStatus.Presented && !r.Advance), cancellationToken).ConfigureAwait(false)).Items; + foreach (var remittance in presented) + { + foreach (var line in (await RemittanceService.LinesAsync(uow, remittance.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.Status == RemittanceLineStatus.Included)) + { + movements.Add(new CashFlowMovement(line.DueDate, line.Amount, CashFlowSource.Receivables, "Distinta " + remittance.DisplayNumber)); + } + } + } + } + + if (include.Contains(CashFlowSource.SaleOrders)) + { + movements.AddRange(await OrdersAsync(uow, 1m, CashFlowSource.SaleOrders, until, cancellationToken).ConfigureAwait(false)); + } + + if (include.Contains(CashFlowSource.PurchaseOrders)) + { + movements.AddRange(await OrdersAsync(uow, -1m, CashFlowSource.PurchaseOrders, until, cancellationToken).ConfigureAwait(false)); + } + + if (include.Contains(CashFlowSource.Recurring)) + { + movements.AddRange(await RecurringAsync(uow, today, until, cancellationToken).ConfigureAwait(false)); + } + + if (include.Contains(CashFlowSource.Taxes)) + { + var taxes = (await uow.Repository().ListAsync( + Query.For().Where(t => t.PaidOn == null && t.DueDate <= until), cancellationToken).ConfigureAwait(false)).Items; + movements.AddRange(taxes.Select(t => new CashFlowMovement(t.DueDate, -t.Amount, CashFlowSource.Taxes, "F24 " + t.PaymentCode + " · " + t.Description))); + } + + var opening = accounts.Sum(a => a.Balance); + var periods = CashFlowForecaster.Periods(opening, movements, today, days, periodDays); + return new CashFlowForecast(today, days, accounts, opening, periods, [.. movements.OrderBy(m => m.Date)], include); + } + + private static async Task> BalancesAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken) + { + var result = new List(); + var draft = nameof(GlEntryStatus.Draft); + var banks = (await uow.Repository().ListAsync(Query.For().OrderBy(b => b.Code), cancellationToken).ConfigureAwait(false)).Items; + var seen = new HashSet(); + foreach (var bank in banks) + { + if (await LedgerStore.AccountAsync(uow, bank.AccountCode, cancellationToken).ConfigureAwait(false) is not { } account || !seen.Add(account.Id)) + { + continue; + } + + var balance = await uow.QuerySingleAsync( + SqlFragment.Of($"SELECT SUM(debit - credit) FROM gl_entry_lines WHERE account_id = {account.Id} AND status <> {draft} AND entry_date <= {today}"), cancellationToken).ConfigureAwait(false) ?? 0m; + result.Add(new CashAccountBalance(bank.Id, bank.Code + " · " + (bank.BankName ?? bank.Description), balance)); + } + + var cash = await uow.QuerySingleAsync( + SqlFragment.Of($"SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l JOIN gl_accounts a ON a.id = l.account_id WHERE a.type = {nameof(AccountType.Cash)} AND l.status <> {draft} AND l.entry_date <= {today}"), + cancellationToken).ConfigureAwait(false); + if (cash is { } amount && amount != 0m) + { + result.Add(new CashAccountBalance(null, "Cassa", amount)); + } + + return result; + } + + private static async Task> OrdersAsync( + IUnitOfWork uow, decimal sign, CashFlowSource source, DateOnly until, CancellationToken cancellationToken) + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() + { + var orders = (await uow.Repository().ListAsync( + Query.For().Where(o => o.Status == DocumentStatus.Confirmed || o.Status == DocumentStatus.PartiallyFulfilled), cancellationToken).ConfigureAwait(false)).Items; + var result = new List(); + foreach (var chunk in orders.Chunk(200)) + { + var ids = chunk.Select(o => o.Id).ToList(); + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => ids.Contains(l.DocumentId)), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(l => l.DocumentId).ToDictionary(g => g.Key, g => g.ToList()); + foreach (var order in chunk) + { + var date = (order.DeliveryDate ?? order.DocumentDate).AddDays(OrderPaymentDays); + if (date > until || order.TaxableAmount == 0m || !lines.TryGetValue(order.Id, out var orderLines)) + { + continue; + } + + // What is still to deliver, with the VAT in the proportion of the order. + var taxable = orderLines.Where(l => l.Quantity != 0m).Sum(l => l.TaxableAmount * l.Residual / l.Quantity); + var gross = Math.Round(taxable * order.TotalAmount / order.TaxableAmount, 2, MidpointRounding.AwayFromZero); + if (gross != 0m) + { + result.Add(new CashFlowMovement(date, sign * gross, source, (order.DocumentNumber ?? order.Id.ToString(CultureInfo.InvariantCulture)))); + } + } + } + + return result; + } + + private static async Task> RecurringAsync(IUnitOfWork uow, DateOnly today, DateOnly until, CancellationToken cancellationToken) + { + var recurring = (await uow.Repository().ListAsync(Query.For().Where(r => !r.Disabled), cancellationToken).ConfigureAwait(false)).Items; + if (recurring.Count == 0) + { + return []; + } + + var moneyAccounts = new HashSet(); + foreach (var bank in (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items) + { + if (await LedgerStore.AccountAsync(uow, bank.AccountCode, cancellationToken).ConfigureAwait(false) is { } account) + { + moneyAccounts.Add(account.Id); + } + } + + foreach (var account in (await uow.Repository().ListAsync(Query.For().Where(a => a.Type == AccountType.Cash || a.Type == AccountType.Bank), cancellationToken).ConfigureAwait(false)).Items) + { + moneyAccounts.Add(account.Id); + } + + var result = new List(); + foreach (var entry in recurring) + { + var lines = await LedgerStore.LinesAsync(uow, entry.ModelEntryId, cancellationToken).ConfigureAwait(false); + var amount = lines.Where(l => moneyAccounts.Contains(l.AccountId)).Sum(l => l.Debit - l.Credit); + if (amount == 0m) + { + continue; + } + + for (var date = entry.NextDate; date <= until && (entry.EndDate is null || date <= entry.EndDate); date = RecurringEntryService.Next(date, entry.Frequency)) + { + if (date >= today) + { + result.Add(new CashFlowMovement(date, amount, CashFlowSource.Recurring, entry.Description)); + } + } + } + + return result; + } +} diff --git a/src/Khaemhat.Application/Treasury/DunningService.cs b/src/Khaemhat.Application/Treasury/DunningService.cs new file mode 100644 index 0000000..c44d229 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/DunningService.cs @@ -0,0 +1,606 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Application.Audit; +using Khaemhat.Data.Companies; +using Khaemhat.Application.Jobs; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Files; +using Khaemhat.Infrastructure.Mail; + +namespace Khaemhat.Application.Treasury; + +/// A customer to remind, with the level due and its overdue items. +/// The customer. +/// Its code. +/// Its name. +/// Its e-mail. +/// Its PEC. +/// The level due, or when none is due yet. +/// The highest level already sent for its items. +/// The overdue items. +/// Their residual. +/// The late payment interest to the day. +/// The days past due of the oldest item. +/// The last reminder. +/// The customer is blocked. +public sealed record DunningProposal( + long PartyId, string? PartyCode, string PartyName, string? Email, string? Pec, DunningLevel? Level, int CurrentLevel, IReadOnlyList Items, + decimal Overdue, decimal Interest, int MaxDays, DateOnly? LastSent, bool Blocked); + +/// A reminder sent, with the name of its customer. +/// The reminder. +/// The customer. +public sealed record DunningLetterRow(DunningLetter Letter, string PartyName); + +/// What a run of reminders did. +/// Reminders queued by e-mail or PEC. +/// Reminders to print (letter channel). +/// Customers left out, with the reason code. +/// The letters to print, one file, when any. +public sealed record DunningRun(int Sent, int Letters, IReadOnlyList<(string Party, string Reason)> Skipped, LedgerFile? Pdf); + +/// +/// The reminders (solleciti, SPEC §11.8, mockup 056, ADR 0038): levels after the due date with their texts and +/// channels, the proposal of the customers to remind (disputed items and public administrations left out), the +/// sending by e-mail, PEC or printed letter with the late payment interest of the pack, the log of what was sent, the +/// block of the customer at the last level, and the scheduled task for the automatic levels. +/// +public sealed class DunningService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly IMailQueue _mail; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The outgoing mail. + /// The clock. + public DunningService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, IMailQueue mail, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(mail); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _audit = audit; + _mail = mail; + _clock = clock; + } + + /// The levels given to a company that has none (mockup 056). + /// Three levels: 7, 20 and 45 days after the due date. + public static IReadOnlyList DefaultLevels() => + [ + new() + { + Level = 1, DaysAfterDue = 7, Name = "Promemoria cortese", Channel = DunningChannel.Email, Action = DunningAction.None, + Subject = "Promemoria scadenze - {azienda}", + Body = "Gentile {cliente},\n\nle ricordiamo che risultano scadute le seguenti partite:\n\n{elenco}\n\nTotale scaduto: {totale}.\n\nSe ha già provveduto al pagamento, la preghiamo di non tenere conto di questo messaggio.\n\nCordiali saluti\n{azienda}", + }, + new() + { + Level = 2, DaysAfterDue = 20, Name = "Sollecito", Channel = DunningChannel.Email | DunningChannel.Pec, Action = DunningAction.NotifyAgent, ChargeInterest = true, + Subject = "Sollecito di pagamento - {azienda}", + Body = "Gentile {cliente},\n\nnonostante il nostro precedente promemoria, risultano ancora scadute le seguenti partite:\n\n{elenco}\n\nTotale scaduto: {totale}. Interessi di mora maturati ({riferimento}): {interessi}.\n\nLa invitiamo a provvedere al pagamento entro 10 giorni.\n\nCordiali saluti\n{azienda}", + }, + new() + { + Level = 3, DaysAfterDue = 45, Name = "Diffida e blocco forniture", Channel = DunningChannel.Pec | DunningChannel.Letter, Action = DunningAction.BlockCustomer, ChargeInterest = true, + Subject = "Diffida ad adempiere - {azienda}", + Body = "Spettabile {cliente},\n\nle partite seguenti sono scadute da oltre {giorni} giorni:\n\n{elenco}\n\nTotale scaduto: {totale}, oltre agli interessi di mora ({riferimento}) per {interessi} e al risarcimento dei costi di recupero.\n\nVi diffidiamo a pagare entro 15 giorni; in mancanza procederemo al recupero del credito senza ulteriore avviso. Le forniture sono sospese fino al saldo.\n\n{azienda}", + }, + ]; + + /// The levels, created with the defaults when the company has none. + /// Who reads. + /// The company. + /// Cancellation. + /// The levels in order. + public async Task> LevelsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false); + } + + /// Writes a level. + /// Who writes. + /// The company. + /// The level (its Level number identifies it). + /// Cancellation. + /// The level. + public async Task SaveLevelAsync(Actor actor, string companyCode, DunningLevel level, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(level); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + if (level.Level is < 1 or > 9 || level.DaysAfterDue < 0 || string.IsNullOrWhiteSpace(level.Name) || string.IsNullOrWhiteSpace(level.Subject) || string.IsNullOrWhiteSpace(level.Body) + || level.Channel == DunningChannel.None) + { + throw new ValidationFailedException(["Level:" + TreasuryErrors.DunningLevel]); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var number = level.Level; + var existing = await repository.FindAsync(Query.For().Where(l => l.Level == number), cancellationToken).ConfigureAwait(false); + level.Name = LedgerStore.Trim(level.Name.Trim(), 100)!; + level.Subject = LedgerStore.Trim(level.Subject.Trim(), 200)!; + if (existing is null) + { + level.Id = await repository.InsertAsync(level, cancellationToken).ConfigureAwait(false); + } + else + { + level.Id = existing.Id; + await repository.UpdateAsync(level, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, level.Id, existing, level, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return level; + } + + /// The customers with overdue items and the level due for each. + /// Who reads. + /// The company. + /// Cancellation. + /// The proposals, the most overdue first. + public async Task> ProposalAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ProposalsAsync(uow, rules, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false); + } + + /// The reminders sent. + /// Who reads. + /// The company. + /// One customer. + /// Cancellation. + /// The reminders, latest first (at most 500). + public async Task> HistoryAsync(Actor actor, string companyCode, long? partyId = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For(); + if (partyId is { } party) + { + query = query.Where(l => l.PartyId == party); + } + + var letters = (await uow.Repository().ListAsync(query.OrderByDescending(l => l.SentOn).OrderByDescending(l => l.Id).Take(500), cancellationToken).ConfigureAwait(false)).Items; + var parties = await TreasuryStore.PartiesAsync(uow, letters.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false); + return [.. letters.Select(l => new DunningLetterRow(l, parties.GetValueOrDefault(l.PartyId)?.Name ?? string.Empty))]; + } + + /// The letter of the level due for a customer, as a PDF, without sending it. + /// Who reads. + /// The company. + /// The customer. + /// Cancellation. + /// The file. + public async Task PreviewAsync(Actor actor, string companyCode, long partyId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var today = TreasuryStore.Today(_clock); + var proposal = (await ProposalsAsync(uow, rules, today, cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.PartyId == partyId) + ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var levels = await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false); + var level = proposal.Level ?? levels.FirstOrDefault(l => l.Level == Math.Max(1, proposal.CurrentLevel)) ?? levels[0]; + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var party = await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false); + var pdf = await LetterAsync(profile, party, level, proposal, rules, today, cancellationToken).ConfigureAwait(false); + return new LedgerFile(FileName(proposal, level, today), PdfWriter.MediaType, pdf); + } + + /// Sends the reminders of the level due to customers. + /// Who sends them. + /// The company. + /// The customers. + /// Cancellation. + /// What was done. + public async Task SendAsync(Actor actor, string companyCode, IReadOnlyList partyIds, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(partyIds); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + return await RunAsync(company, partyIds.ToHashSet(), automaticOnly: false, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + /// Sends the automatic levels of a company (the scheduled task). + /// The company. + /// Cancellation. + /// What was done. + public Task RunAutomaticAsync(string companyCode, CancellationToken cancellationToken = default) => + RunAsync(Data.CompanyCodes.Normalize(companyCode), null, automaticOnly: true, "scheduler", cancellationToken); + + private static string FileName(DunningProposal proposal, DunningLevel level, DateOnly today) => + "sollecito-" + level.Level.ToString(CultureInfo.InvariantCulture) + "-" + (proposal.PartyCode ?? proposal.PartyId.ToString(CultureInfo.InvariantCulture)) + + "-" + today.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".pdf"; + + private static async Task> EnsureLevelsAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + var levels = (await repository.ListAsync(Query.For().OrderBy(l => l.Level), cancellationToken).ConfigureAwait(false)).Items; + if (levels.Count > 0) + { + return levels; + } + + var defaults = DefaultLevels(); + foreach (var level in defaults) + { + level.Id = await repository.InsertAsync(level, cancellationToken).ConfigureAwait(false); + } + + return defaults; + } + + private static async Task> ProposalsAsync(IUnitOfWork uow, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken) + { + var levels = await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false); + var receivable = OpenItemDirection.Receivable; + var items = (await uow.Repository().ListAsync( + Query.For().Where(o => o.Direction == receivable && !o.Closed && !o.Disputed && o.DueDate < today && o.Status != OpenItemStatus.InRemittance) + .OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items.Where(o => o.Residual > 0m).ToList(); + if (items.Count == 0) + { + return []; + } + + var rows = await ScheduleService.RowsAsync(uow, items, today, cancellationToken).ConfigureAwait(false); + var parties = await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false); + var blocked = (await uow.Repository().ListAsync(Query.For().Where(t => t.Blocked), cancellationToken).ConfigureAwait(false)).Items + .Select(t => t.PartyId).ToHashSet(); + var steps = levels.Select(l => new DunningStep(l.Level, l.DaysAfterDue)).ToList(); + var result = new List(); + foreach (var group in rows.GroupBy(r => r.Item.PartyId)) + { + if (!parties.TryGetValue(group.Key, out var party) || party.SubjectType == SubjectType.PublicAdministration) + { + continue; + } + + var list = group.ToList(); + var next = DunningRules.NextLevel( + [.. list.Select(r => new DunningItem(r.Item.Id, r.Item.DueDate, r.Item.Residual, r.Item.DunningLevel, r.Item.LastDunningDate, r.Item.Disputed))], steps, today); + var interest = rules is null ? 0m : list.Sum(r => LateInterestCalculator.Interest(r.Item.Residual, r.Item.DueDate, today, rules.RateOn)); + result.Add(new DunningProposal( + party.Id, party.Code, party.Name, party.Email, party.Pec, next is { } n ? levels.FirstOrDefault(l => l.Level == n) : null, + list.Max(r => r.Item.DunningLevel), list, list.Sum(r => r.Item.Residual), interest, list.Max(r => r.DaysOverdue), + list.Max(r => r.Item.LastDunningDate), blocked.Contains(party.Id))); + } + + return [.. result.OrderByDescending(p => p.Level is not null).ThenByDescending(p => p.MaxDays).ThenBy(p => p.PartyName, StringComparer.CurrentCultureIgnoreCase)]; + } + + private async Task RunAsync(string company, HashSet? partyIds, bool automaticOnly, string? userName, CancellationToken cancellationToken) + { + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var today = TreasuryStore.Today(_clock); + var proposals = (await ProposalsAsync(uow, rules, today, cancellationToken).ConfigureAwait(false)) + .Where(p => p.Level is not null && (partyIds is null || partyIds.Contains(p.PartyId)) && (!automaticOnly || p.Level.Automatic)).ToList(); + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var skipped = new List<(string, string)>(); + var printed = new List(); + int sent = 0, letters = 0; + foreach (var proposal in proposals) + { + var level = proposal.Level!; + var channel = level.Channel; + if (automaticOnly) + { + channel &= ~DunningChannel.Letter; + } + + var party = await uow.Repository().GetAsync(proposal.PartyId, cancellationToken).ConfigureAwait(false); + var recipients = new List(); + if (channel.HasFlag(DunningChannel.Email) && !string.IsNullOrWhiteSpace(party?.Email)) + { + recipients.Add(party.Email.Trim()); + } + + if (channel.HasFlag(DunningChannel.Pec) && !string.IsNullOrWhiteSpace(party?.Pec)) + { + recipients.Add(party.Pec.Trim()); + } + + var letter = channel.HasFlag(DunningChannel.Letter); + if (recipients.Count == 0 && !letter) + { + skipped.Add((proposal.PartyName, TreasuryErrors.DunningRecipient)); + continue; + } + + var pdf = await LetterAsync(profile, party, level, proposal, level.ChargeInterest ? rules : null, today, cancellationToken).ConfigureAwait(false); + var (subject, body) = Texts(profile, level, proposal, level.ChargeInterest ? rules : null); + var status = DunningLetterStatus.Sent; + if (recipients.Count > 0) + { + var cc = new List(); + if (level.Action == DunningAction.NotifyAgent && party?.SalespersonId is { } agentId + && await uow.Repository().GetAsync(agentId, cancellationToken).ConfigureAwait(false) is { Email: { Length: > 0 } agentMail }) + { + cc.Add(agentMail); + } + + var accepted = _mail.Enqueue(new OutgoingMail(recipients, subject, body) + { + Cc = cc, + ReplyTo = profile?.Email, + Attachments = [new MailAttachment(FileName(proposal, level, today), PdfWriter.MediaType, pdf)], + Reference = "dunning:" + proposal.PartyId.ToString(CultureInfo.InvariantCulture), + }); + status = accepted ? DunningLetterStatus.Queued : DunningLetterStatus.Failed; + if (accepted) + { + sent++; + } + } + + if (letter) + { + printed.Add(pdf); + letters++; + } + + if (status == DunningLetterStatus.Failed && !letter) + { + skipped.Add((proposal.PartyName, TreasuryErrors.DunningRecipient)); + } + + await uow.Repository().InsertAsync(new DunningLetter + { + PartyId = proposal.PartyId, + Level = level.Level, + SentOn = today, + Channel = channel, + Recipients = LedgerStore.Trim(string.Join(", ", recipients), 300), + Subject = LedgerStore.Trim(subject, 200)!, + ItemCount = proposal.Items.Count, + OverdueAmount = proposal.Overdue, + Interest = level.ChargeInterest ? proposal.Interest : 0m, + Status = status == DunningLetterStatus.Failed && letter ? DunningLetterStatus.Sent : status, + SentBy = userName, + IsDemo = proposal.Items.All(i => i.Item.IsDemo), + }, cancellationToken).ConfigureAwait(false); + foreach (var row in proposal.Items) + { + row.Item.DunningLevel = Math.Max(row.Item.DunningLevel, level.Level); + row.Item.LastDunningDate = today; + await uow.Repository().UpdateAsync(row.Item, cancellationToken).ConfigureAwait(false); + } + + if (level.Action == DunningAction.BlockCustomer) + { + var terms = uow.Repository(); + var partyId = proposal.PartyId; + var current = await terms.FindAsync(Query.For().Where(t => t.PartyId == partyId), cancellationToken).ConfigureAwait(false); + if (current is null) + { + await terms.InsertAsync(new PartySalesTerms { PartyId = partyId, Blocked = true }, cancellationToken).ConfigureAwait(false); + } + else if (!current.Blocked) + { + current.Blocked = true; + await terms.UpdateAsync(current, cancellationToken).ConfigureAwait(false); + } + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + LedgerFile? file = null; + if (printed.Count == 1) + { + file = new LedgerFile("solleciti-" + today.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".pdf", PdfWriter.MediaType, printed[0]); + } + else if (printed.Count > 1) + { + file = new LedgerFile( + "solleciti-" + today.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".pdf", + PdfWriter.MediaType, + await LettersAsync(uow, profile, proposals.Where(p => p.Level!.Channel.HasFlag(DunningChannel.Letter)).ToList(), rules, today, cancellationToken).ConfigureAwait(false)); + } + + return new DunningRun(sent, letters, skipped, file); + } + + private static (string Subject, string Body) Texts(CompanyProfile? profile, DunningLevel level, DunningProposal proposal, ILatePaymentRules? rules) + { + var culture = CultureInfo.GetCultureInfo("it-IT"); + var list = new StringBuilder(); + foreach (var row in proposal.Items) + { + list.Append("- ").Append(row.Item.DocumentNumber ?? "-").Append(" del ").Append(row.Item.DocumentDate.ToString("dd/MM/yyyy", culture)) + .Append(", scadenza ").Append(row.Item.DueDate.ToString("dd/MM/yyyy", culture)).Append(": ").Append(row.Item.Residual.ToString("C", culture)).Append('\n'); + } + + string Fill(string text) => text + .Replace("{cliente}", proposal.PartyName, StringComparison.Ordinal) + .Replace("{azienda}", profile?.LegalName ?? string.Empty, StringComparison.Ordinal) + .Replace("{elenco}", list.ToString().TrimEnd(), StringComparison.Ordinal) + .Replace("{totale}", proposal.Overdue.ToString("C", culture), StringComparison.Ordinal) + .Replace("{interessi}", (rules is null ? 0m : proposal.Interest).ToString("C", culture), StringComparison.Ordinal) + .Replace("{riferimento}", rules?.LegalReference ?? string.Empty, StringComparison.Ordinal) + .Replace("{giorni}", proposal.MaxDays.ToString(culture), StringComparison.Ordinal); + return (Fill(level.Subject), Fill(level.Body)); + } + + private static async Task LetterAsync( + CompanyProfile? profile, Party? party, DunningLevel level, DunningProposal proposal, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken) + { + using var buffer = new MemoryStream(); + await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = level.Name, Author = profile?.LegalName }, leaveOpen: true)) + { + await WriteLetterAsync(pdf, profile, party, level, proposal, rules, today, cancellationToken).ConfigureAwait(false); + await pdf.CloseAsync(cancellationToken).ConfigureAwait(false); + } + + return buffer.ToArray(); + } + + private static async Task LettersAsync( + IUnitOfWork uow, CompanyProfile? profile, IReadOnlyList proposals, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken) + { + using var buffer = new MemoryStream(); + await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = "Solleciti", Author = profile?.LegalName }, leaveOpen: true)) + { + foreach (var proposal in proposals) + { + var party = await uow.Repository().GetAsync(proposal.PartyId, cancellationToken).ConfigureAwait(false); + await WriteLetterAsync(pdf, profile, party, proposal.Level!, proposal, proposal.Level!.ChargeInterest ? rules : null, today, cancellationToken).ConfigureAwait(false); + } + + await pdf.CloseAsync(cancellationToken).ConfigureAwait(false); + } + + return buffer.ToArray(); + } + + private static async Task WriteLetterAsync( + PdfWriter pdf, CompanyProfile? profile, Party? party, DunningLevel level, DunningProposal proposal, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken) + { + const double margin = 56; + var width = PdfWriter.A4Width; + var page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + var y = PdfWriter.A4Height - margin; + page.DrawText(profile?.LegalName, margin, y, PdfFont.HelveticaBold, 12); + y -= 13; + page.DrawText(string.Join(" ", new[] { profile?.Address, profile?.StreetNumber }.Where(s => !string.IsNullOrWhiteSpace(s))), margin, y, PdfFont.Helvetica, 8.5); + y -= 10; + page.DrawText(string.Join(" ", new[] { profile?.PostalCode, profile?.City, profile?.ProvinceCode is null ? null : "(" + profile.ProvinceCode + ")" }.Where(s => !string.IsNullOrWhiteSpace(s))), margin, y, PdfFont.Helvetica, 8.5); + y -= 10; + page.DrawText("P. IVA " + profile?.VatNumber, margin, y, PdfFont.Helvetica, 8.5); + + // The address of the customer on the right, where the window of the envelope is. + var x = width - margin - 220; + var top = PdfWriter.A4Height - margin - 90; + page.DrawText("Spett.le", x, top, PdfFont.Helvetica, 9); + page.DrawText(party?.Name ?? proposal.PartyName, x, top - 13, PdfFont.HelveticaBold, 10); + page.DrawText(string.Join(" ", new[] { party?.Address, party?.StreetNumber }.Where(s => !string.IsNullOrWhiteSpace(s))), x, top - 26, PdfFont.Helvetica, 9); + page.DrawText(string.Join(" ", new[] { party?.PostalCode, party?.City, party?.Province is null ? null : "(" + party.Province + ")" }.Where(s => !string.IsNullOrWhiteSpace(s))), x, top - 38, PdfFont.Helvetica, 9); + if (!string.IsNullOrWhiteSpace(party?.Pec)) + { + page.DrawText("PEC " + party.Pec, x, top - 50, PdfFont.Helvetica, 8.5); + } + + var culture = CultureInfo.GetCultureInfo("it-IT"); + y = top - 90; + page.DrawText((profile?.City ?? string.Empty) + ", " + today.ToString("d MMMM yyyy", culture), margin, y, PdfFont.Helvetica, 9.5); + y -= 24; + var (subject, body) = Texts(profile, level, proposal, rules); + page.DrawText("Oggetto: " + subject, margin, y, PdfFont.HelveticaBold, 10); + y -= 20; + foreach (var paragraph in body.Replace("\r", string.Empty, StringComparison.Ordinal).Split("\n\n")) + { + if (paragraph.StartsWith("- ", StringComparison.Ordinal)) + { + // The list of items as a table. + page.DrawText("Documento", margin, y, PdfFont.HelveticaBold, 8.5); + page.DrawText("Data", margin + 150, y, PdfFont.HelveticaBold, 8.5); + page.DrawText("Scadenza", margin + 230, y, PdfFont.HelveticaBold, 8.5); + page.DrawTextRight("Giorni", margin + 340, y, PdfFont.HelveticaBold, 8.5); + page.DrawTextRight("Residuo", width - margin, y, PdfFont.HelveticaBold, 8.5); + page.DrawLine(margin, y - 3, width - margin, y - 3, 0.5, PdfColor.Gray(170)); + y -= 14; + foreach (var row in proposal.Items) + { + if (y < margin + 60) + { + page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + y = PdfWriter.A4Height - margin; + } + + page.DrawText(row.Item.DocumentNumber ?? "-", margin, y, PdfFont.Helvetica, 8.5); + page.DrawText(row.Item.DocumentDate.ToString("dd/MM/yyyy", culture), margin + 150, y, PdfFont.Helvetica, 8.5); + page.DrawText(row.Item.DueDate.ToString("dd/MM/yyyy", culture), margin + 230, y, PdfFont.Helvetica, 8.5); + page.DrawTextRight(row.DaysOverdue.ToString(culture), margin + 340, y, PdfFont.Helvetica, 8.5); + page.DrawTextRight(row.Item.Residual.ToString("N2", culture), width - margin, y, PdfFont.Helvetica, 8.5); + y -= 12; + } + + page.DrawLine(margin, y + 8, width - margin, y + 8, 0.5, PdfColor.Gray(170)); + page.DrawText("Totale scaduto", margin, y - 2, PdfFont.HelveticaBold, 9); + page.DrawTextRight(proposal.Overdue.ToString("N2", culture), width - margin, y - 2, PdfFont.HelveticaBold, 9); + y -= 22; + continue; + } + + if (y < margin + 60) + { + page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + y = PdfWriter.A4Height - margin; + } + + y = page.DrawParagraph(paragraph, margin, y, width - (2 * margin), PdfFont.Helvetica, 9.5, 13) - 8; + } + + } +} + +/// Sends the automatic reminders of every company (job finance.dunning, SPEC §11.8). +/// The companies. +/// The reminders. +/// The licence. +public sealed class DunningJob(ICompanyRegistry companies, DunningService service, ILicenseGate license) : IScheduledJob +{ + /// The job type. + public const string JobType = "finance.dunning"; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + if (!license.IsModuleActive(ModuleCodes.Finance)) + { + return "Modulo scadenzario e tesoreria non attivo."; + } + + int done = 0, sent = 0; + foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status is CompanyStatus.Disabled) + { + continue; + } + + var run = await service.RunAutomaticAsync(company.Code, cancellationToken).ConfigureAwait(false); + sent += run.Sent; + done++; + } + + return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {sent} solleciti in coda di invio."); + } +} diff --git a/src/Khaemhat.Application/Treasury/MandateService.cs b/src/Khaemhat.Application/Treasury/MandateService.cs new file mode 100644 index 0000000..b9e6780 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/MandateService.cs @@ -0,0 +1,200 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Treasury; + +/// A mandate being written. +/// The mandate, or for a new one. +/// The debtor. +/// The unique mandate reference (UMR). +/// The day it was signed. +/// Core or B2B. +/// The account of the debtor. +/// The BIC. +/// For one collection only. +/// Notes. +public sealed record MandateInput(long? Id, long PartyId, string Reference, DateOnly SignatureDate, SddScheme Scheme, string Iban, string? Bic, bool OneOff, string? Notes); + +/// A mandate with the name of its debtor. +/// The mandate. +/// The code of the debtor. +/// The name of the debtor. +public sealed record MandateRow(SddMandate Mandate, string? PartyCode, string PartyName); + +/// The SEPA direct debit mandates of the customers (SPEC §11.8, mockup 055, ADR 0038). +public sealed class MandateService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The history. + public MandateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + _factory = factory; + _permissions = permissions; + _audit = audit; + } + + /// The mandates, of a party or all. + /// Who reads. + /// The company. + /// One party. + /// Cancellation. + /// The mandates, by party and date. + public async Task> ListAsync(Actor actor, string companyCode, long? partyId = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For(); + if (partyId is { } party) + { + query = query.Where(m => m.PartyId == party); + } + + var mandates = (await uow.Repository().ListAsync(query.OrderByDescending(m => m.SignatureDate), cancellationToken).ConfigureAwait(false)).Items; + var parties = await TreasuryStore.PartiesAsync(uow, mandates.Select(m => m.PartyId), cancellationToken).ConfigureAwait(false); + return [.. mandates.Select(m => new MandateRow(m, parties.GetValueOrDefault(m.PartyId)?.Code, parties.GetValueOrDefault(m.PartyId)?.Name ?? string.Empty)) + .OrderBy(r => r.PartyName, StringComparer.CurrentCultureIgnoreCase)]; + } + + /// Writes a mandate. + /// Who writes. + /// The company. + /// The mandate. + /// Cancellation. + /// The mandate. + public async Task SaveAsync(Actor actor, string companyCode, MandateInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + var reference = (input.Reference ?? string.Empty).Trim(); + var iban = IbanValidator.Normalize(input.Iban); + var errors = new List(); + if (input.PartyId <= 0) + { + errors.Add("PartyId:" + TreasuryErrors.PartyRequired); + } + + if (reference.Length == 0 || reference.Length > 35) + { + errors.Add("Reference:" + TreasuryErrors.MandateReference); + } + + if (!IbanValidator.IsValid(iban)) + { + errors.Add("Iban:" + TreasuryErrors.IbanInvalid); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var same = await repository.FindAsync(Query.For().Where(m => m.Reference == reference), cancellationToken).ConfigureAwait(false); + if (same is not null && same.Id != input.Id) + { + throw new ValidationFailedException(["Reference:" + TreasuryErrors.MandateDuplicate]); + } + + var mandate = input.Id is { } id + ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound) + : new SddMandate(); + var before = input.Id is null ? null : Copy(mandate); + mandate.PartyId = input.PartyId; + mandate.Reference = reference; + mandate.SignatureDate = input.SignatureDate; + mandate.Scheme = input.Scheme; + mandate.Iban = iban; + mandate.Bic = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Bic) ? null : input.Bic.Trim().ToUpperInvariant(), 11); + mandate.OneOff = input.OneOff; + mandate.Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Notes) ? null : input.Notes.Trim(), 200); + if (input.Id is null) + { + mandate.Id = await repository.InsertAsync(mandate, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, mandate.Id, null, mandate, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(mandate, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, mandate.Id, before, mandate, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return mandate; + } + + /// Revokes a mandate or takes the revocation back. + /// Who does it. + /// The company. + /// The mandate. + /// Revoked or not. + /// Cancellation. + /// A task. + public async Task RevokeAsync(Actor actor, string companyCode, long id, bool revoked, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var mandate = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var before = Copy(mandate); + mandate.Revoked = revoked; + await uow.Repository().UpdateAsync(mandate, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, mandate.Id, before, mandate, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Deletes a mandate never used in a remittance. + /// Who does it. + /// The company. + /// The mandate. + /// 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, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var mandate = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + if (await uow.Repository().CountAsync(Query.For().Where(l => l.MandateId == id), cancellationToken).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["Id:" + TreasuryErrors.MandateUsed]); + } + + await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, mandate, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + private static SddMandate Copy(SddMandate m) => new() + { + Id = m.Id, + PartyId = m.PartyId, + Reference = m.Reference, + SignatureDate = m.SignatureDate, + Scheme = m.Scheme, + Iban = m.Iban, + Bic = m.Bic, + OneOff = m.OneOff, + Revoked = m.Revoked, + Notes = m.Notes, + }; +} diff --git a/src/Khaemhat.Application/Treasury/PaymentService.cs b/src/Khaemhat.Application/Treasury/PaymentService.cs new file mode 100644 index 0000000..2484112 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/PaymentService.cs @@ -0,0 +1,424 @@ +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.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Treasury; + +/// A line of a collection or payment being recorded. +/// The item. +/// The money for the item. +/// The allowance (abbuono) that closes it. +/// The exchange difference. +public sealed record PaymentLineInput(long OpenItemId, decimal Amount, decimal Allowance = 0m, decimal ExchangeDifference = 0m); + +/// A collection or payment being recorded (mockup 054). +/// Collection or payment. +/// The customer or supplier. +/// The day of the money. +/// The method. +/// The bank of the company; none with a cash method means the cash. +/// The bank fees. +/// The reference (CRO, cheque number). +/// Notes. +/// The items settled. +public sealed record PaymentInput( + PaymentDirection Direction, long PartyId, DateOnly Date, long? PaymentMethodId, long? BankAccountId, decimal Fees, string? Reference, string? Notes, + IReadOnlyList Lines); + +/// A collection or payment with what the grid shows. +/// The payment. +/// The party. +/// The bank (code). +/// The number of its entry. +/// The documents it settled. +public sealed record PaymentRow(Payment Payment, string PartyName, string? Bank, string? EntryNumber, string Documents); + +/// +/// Collections and payments (SPEC §11.8, mockup 054, ADR 0038): one payment settles one or more items of a party with +/// money, allowances and exchange differences; the entry is written at once (INC or PAG); the withholding of an +/// invoice becomes due when the invoice is fully paid; cancelling takes everything back. +/// +public sealed class PaymentService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The clock. + public PaymentService(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 collections or payments of a period. + /// Who reads. + /// The company. + /// Collections or payments. + /// From this day. + /// Up to this day. + /// One party. + /// Cancellation. + /// The rows, latest first. + public async Task> ListAsync( + Actor actor, string companyCode, PaymentDirection direction, DateOnly from, DateOnly to, long? partyId = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For().Where(p => p.Direction == direction && p.PaymentDate >= from && p.PaymentDate <= to); + if (partyId is { } party) + { + query = query.Where(p => p.PartyId == party); + } + + var payments = (await uow.Repository().ListAsync(query.OrderByDescending(p => p.PaymentDate).OrderByDescending(p => p.Id), cancellationToken).ConfigureAwait(false)).Items; + return await RowsAsync(uow, payments, cancellationToken).ConfigureAwait(false); + } + + /// A payment with its lines and their items. + /// Who reads. + /// The company. + /// The payment. + /// Cancellation. + /// The payment, its lines and the items, or . + public async Task<(PaymentRow Row, IReadOnlyList<(PaymentLine Line, OpenItem? Item)> Lines)?> GetAsync( + Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } payment) + { + return null; + } + + var lines = await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false); + var itemIds = lines.Select(l => l.OpenItemId).ToList(); + var items = (await uow.Repository().ListAsync(Query.For().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id); + var row = (await RowsAsync(uow, [payment], cancellationToken).ConfigureAwait(false))[0]; + return (row, [.. lines.Select(l => (l, items.GetValueOrDefault(l.OpenItemId)))]); + } + + /// Records a collection or payment and its entry. + /// Who records it. + /// The company. + /// The payment. + /// Cancellation. + /// The payment. + public async Task RegisterAsync(Actor actor, string companyCode, PaymentInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentWrite, cancellationToken).ConfigureAwait(false); + 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); + var payment = await RegisterAsync(uow, pack, input, PaymentOrigin.Manual, null, null, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, payment.Id, null, payment, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return payment; + } + + /// Cancels a collection or payment: its entry is deleted (or reversed when final) and its items reopen. + /// Who cancels it. + /// The company. + /// The payment. + /// Cancellation. + /// A task. + public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentWrite, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var payment = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + if (payment.Origin == PaymentOrigin.Remittance) + { + throw new ValidationFailedException(["Id:" + TreasuryErrors.FromRemittance]); + } + + await CancelAsync(uow, payment, TreasuryStore.Today(_clock), actor.UserName, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, payment.Id, payment, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Records a payment inside a transaction (manual, remittances, bank statements). + internal static async Task RegisterAsync( + IUnitOfWork uow, IFiscalPack pack, PaymentInput input, PaymentOrigin origin, long? remittanceId, long? statementLineId, CancellationToken cancellationToken) + { + var errors = new List(); + if (input.PartyId <= 0) + { + errors.Add("PartyId:" + TreasuryErrors.PartyRequired); + } + + var lines = input.Lines.Where(l => l.Amount != 0m || l.Allowance != 0m || l.ExchangeDifference != 0m).ToList(); + if (lines.Count == 0) + { + errors.Add("Lines:" + TreasuryErrors.ItemsRequired); + } + + if (input.Fees < 0m) + { + errors.Add("Fees:" + TreasuryErrors.AmountRequired); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + var itemRepository = uow.Repository(); + var direction = input.Direction == PaymentDirection.Receipt ? OpenItemDirection.Receivable : OpenItemDirection.Payable; + var items = new List<(PaymentLineInput Line, OpenItem Item)>(); + foreach (var line in lines) + { + var item = await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["Lines:" + TreasuryErrors.NotFound]); + if (item.PartyId != input.PartyId || item.Direction != direction) + { + throw new ValidationFailedException(["Lines:" + TreasuryErrors.ItemParty]); + } + + if (item.Status == OpenItemStatus.InRemittance && origin != PaymentOrigin.Remittance) + { + throw new ValidationFailedException(["Lines:" + TreasuryErrors.InRemittance]); + } + + var settled = line.Amount + line.Allowance + line.ExchangeDifference; + var residual = item.Residual; + if (settled == 0m || Math.Sign(settled) != Math.Sign(residual) || Math.Abs(settled) > Math.Abs(residual)) + { + throw new ValidationFailedException(["Lines:" + TreasuryErrors.OverSettled]); + } + + items.Add((line, item)); + } + + var bank = await TreasuryStore.BankAsync(uow, input.BankAccountId, cancellationToken).ConfigureAwait(false); + var method = input.PaymentMethodId is { } methodId ? await uow.Repository().GetAsync(methodId, cancellationToken).ConfigureAwait(false) : null; + var cash = input.BankAccountId is null && method is { NeedsBank: false }; + var templateCode = input.Direction == PaymentDirection.Receipt ? "INC" : "PAG"; + var template = await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false); + var ledger = pack.GetFeature(); + var templateLines = template?.Lines; + var money = await TreasuryStore.MoneyAccountAsync(uow, cash ? null : bank, cash, templateLines, ledger, cancellationToken).ConfigureAwait(false); + var accounts = new PaymentPostingAccounts( + money, + await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.Rounding, ledger, cancellationToken).ConfigureAwait(false), + await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.AllowanceIncome, ledger, cancellationToken).ConfigureAwait(false), + await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.ExchangeLoss, ledger, cancellationToken).ConfigureAwait(false), + await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.ExchangeGain, ledger, cancellationToken).ConfigureAwait(false), + await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.BankCharges, ledger, cancellationToken).ConfigureAwait(false)); + var party = (await TreasuryStore.PartiesAsync(uow, [input.PartyId], cancellationToken).ConfigureAwait(false)).GetValueOrDefault(input.PartyId); + var receipt = input.Direction == PaymentDirection.Receipt; + var description = (receipt ? "Incasso " : "Pagamento ") + (party?.Name ?? string.Empty) + + (items.Count == 1 && items[0].Item.DocumentNumber is { } number ? " doc. " + number : string.Empty); + IReadOnlyList posted; + try + { + posted = PaymentPosting.Build( + input.Direction, + accounts, + [.. items.Select(i => new PaymentPostingLine(i.Item.AccountId, i.Item.PartyId, i.Item.Id, TreasuryStore.ItemText(i.Item), i.Line.Amount, i.Line.Allowance, i.Line.ExchangeDifference))], + input.Fees, + description); + } + catch (PaymentAccountMissingException) + { + throw new ValidationFailedException(["Lines:" + TreasuryErrors.AccountMissing]); + } + + var demo = items.All(i => i.Item.IsDemo); + var entry = await TreasuryStore.PostAsync(uow, templateCode, input.Date, description, input.PartyId, posted, demo, cancellationToken).ConfigureAwait(false); + var payment = new Payment + { + Direction = input.Direction, + PartyId = input.PartyId, + PaymentDate = input.Date, + PaymentMethodId = input.PaymentMethodId, + BankAccountId = cash ? null : bank?.Id, + AccountId = money, + Amount = items.Sum(i => i.Line.Amount), + AllowanceAmount = items.Sum(i => i.Line.Allowance), + ExchangeDifference = items.Sum(i => i.Line.ExchangeDifference), + Fees = input.Fees, + Reference = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Reference) ? null : input.Reference.Trim(), 60), + TemplateCode = templateCode, + Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Notes) ? null : input.Notes.Trim(), 500), + Origin = origin, + RemittanceId = remittanceId, + StatementLineId = statementLineId, + GlEntryId = entry.Id, + IsDemo = demo, + }; + payment.Id = await uow.Repository().InsertAsync(payment, cancellationToken).ConfigureAwait(false); + var lineRepository = uow.Repository(); + foreach (var (line, item) in items) + { + await lineRepository.InsertAsync(new PaymentLine + { + PaymentId = payment.Id, + OpenItemId = item.Id, + Amount = line.Amount, + Allowance = line.Allowance, + ExchangeDifference = line.ExchangeDifference, + }, cancellationToken).ConfigureAwait(false); + TreasuryStore.Settle(item, line.Amount + line.Allowance + line.ExchangeDifference); + await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + + await WithholdingsAsync(uow, pack, items.Select(i => i.Item), input.Date, cancellationToken).ConfigureAwait(false); + return payment; + } + + /// Cancels a payment inside a transaction. + internal static async Task CancelAsync(IUnitOfWork uow, Payment payment, DateOnly today, string? userName, CancellationToken cancellationToken) + { + var lines = await LinesAsync(uow, payment.Id, cancellationToken).ConfigureAwait(false); + var itemRepository = uow.Repository(); + var reopened = new List(); + foreach (var line in lines) + { + if (await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) is not { } item) + { + continue; + } + + TreasuryStore.Settle(item, -line.Settled); + await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + reopened.Add(item); + } + + // The withholdings of invoices no longer paid go back to waiting, unless already paid with the F24. + foreach (var document in reopened.Where(i => i.SourceDocumentId is not null).Select(i => (i.SourceFamily, Id: i.SourceDocumentId!.Value)).Distinct()) + { + var family = document.SourceFamily; + var documentId = document.Id; + var withholdings = (await uow.Repository().ListAsync( + Query.For().Where(w => w.SourceFamily == family && w.SourceDocumentId == documentId && w.InvoicePaidOn != null), cancellationToken).ConfigureAwait(false)).Items; + foreach (var withholding in withholdings) + { + if (withholding.Status == WithholdingStatus.Paid) + { + throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]); + } + + await TaxService.UndoInvoicePaidAsync(uow, withholding, today, userName, cancellationToken).ConfigureAwait(false); + await uow.Repository().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false); + } + } + + await uow.Repository().DeleteAsync(payment.Id, cancellationToken).ConfigureAwait(false); + await TreasuryStore.UndoEntryAsync(uow, payment.GlEntryId, today, userName, cancellationToken).ConfigureAwait(false); + if (payment.StatementLineId is { } lineId && await uow.Repository().GetAsync(lineId, cancellationToken).ConfigureAwait(false) is { } statementLine) + { + statementLine.Status = StatementLineStatus.ToMatch; + statementLine.MatchKind = StatementMatchKind.None; + statementLine.PaymentId = null; + statementLine.MatchedAt = null; + statementLine.MatchedBy = null; + await uow.Repository().UpdateAsync(statementLine, cancellationToken).ConfigureAwait(false); + } + } + + internal static async Task> LinesAsync(IUnitOfWork uow, long paymentId, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().Where(l => l.PaymentId == paymentId).OrderBy(l => l.Id), cancellationToken).ConfigureAwait(false)).Items; + + // An invoice with a withholding fully paid makes the withholding due (operated) or posted (suffered), as + // TaxService.InvoicePaidAsync does by hand. + private static async Task WithholdingsAsync(IUnitOfWork uow, IFiscalPack pack, IEnumerable items, DateOnly date, CancellationToken cancellationToken) + { + var settlementRules = pack.GetFeature(); + if (settlementRules is null) + { + return; + } + + var withholdingRules = pack.GetFeature(); + foreach (var document in items.Where(i => i.Closed && i.SourceDocumentId is not null).Select(i => (i.SourceFamily, Id: i.SourceDocumentId!.Value)).Distinct()) + { + var family = document.SourceFamily; + var documentId = document.Id; + var open = await uow.Repository().CountAsync( + Query.For().Where(o => o.SourceFamily == family && o.SourceDocumentId == documentId && !o.Closed), cancellationToken).ConfigureAwait(false); + if (open > 0) + { + continue; + } + + var withholdings = (await uow.Repository().ListAsync( + Query.For().Where(w => w.SourceFamily == family && w.SourceDocumentId == documentId && w.InvoicePaidOn == null), cancellationToken).ConfigureAwait(false)).Items; + foreach (var withholding in withholdings) + { + await TaxService.ApplyInvoicePaidAsync(uow, withholding, date, settlementRules, withholdingRules, cancellationToken).ConfigureAwait(false); + await uow.Repository().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false); + } + } + } + + private static async Task> RowsAsync(IUnitOfWork uow, IReadOnlyList payments, CancellationToken cancellationToken) + { + if (payments.Count == 0) + { + return []; + } + + var parties = await TreasuryStore.PartiesAsync(uow, payments.Select(p => p.PartyId), cancellationToken).ConfigureAwait(false); + var banks = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(b => b.Id); + var entryIds = payments.Where(p => p.GlEntryId is not null).Select(p => p.GlEntryId!.Value).ToList(); + var entries = new Dictionary(); + foreach (var chunk in entryIds.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var entry in (await uow.Repository().ListAsync(Query.For().Where(e => list.Contains(e.Id)), cancellationToken).ConfigureAwait(false)).Items) + { + entries[entry.Id] = entry.EntryNumber; + } + } + + var ids = payments.Select(p => p.Id).ToList(); + var documents = new Dictionary>(); + foreach (var chunk in ids.Chunk(500)) + { + var list = chunk.ToList(); + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => list.Contains(l.PaymentId)), cancellationToken).ConfigureAwait(false)).Items; + var itemIds = lines.Select(l => l.OpenItemId).Distinct().ToList(); + var items = (await uow.Repository().ListAsync(Query.For().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id); + foreach (var line in lines) + { + if (items.TryGetValue(line.OpenItemId, out var item) && item.DocumentNumber is { } number) + { + (documents.TryGetValue(line.PaymentId, out var found) ? found : documents[line.PaymentId] = []).Add(number); + } + } + } + + return [.. payments.Select(p => new PaymentRow( + p, + parties.GetValueOrDefault(p.PartyId)?.Name ?? string.Empty, + p.BankAccountId is { } b ? banks.GetValueOrDefault(b)?.Code : null, + p.GlEntryId is { } e ? entries.GetValueOrDefault(e) : null, + string.Join(", ", documents.GetValueOrDefault(p.Id)?.Distinct(StringComparer.Ordinal) ?? [])))]; + } +} diff --git a/src/Khaemhat.Application/Treasury/RemittanceService.cs b/src/Khaemhat.Application/Treasury/RemittanceService.cs new file mode 100644 index 0000000..64cfe14 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/RemittanceService.cs @@ -0,0 +1,841 @@ +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.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Treasury; + +/// An item that can go in a remittance, with what is missing for the file. +/// The item. +/// The IBAN of the customer or supplier (of the mandate for direct debits). +/// The mandate of a direct debit. +/// The error codes that keep it out of the file. +public sealed record RemittanceCandidate(ScheduleRow Row, string? Iban, SddMandate? Mandate, IReadOnlyList Problems) +{ + /// Ready for the file. + public bool Ready => Problems.Count == 0; +} + +/// A new remittance. +/// RiBa, direct debits or credit transfers. +/// The bank of the company. +/// The day it goes to the bank. +/// The last due date of its items. +/// Advanced subject to collection (salvo buon fine). +/// Notes. +/// The items. +public sealed record RemittanceInput(RemittanceKind Kind, long BankAccountId, DateOnly PresentationDate, DateOnly DueUntil, bool Advance, string? Notes, IReadOnlyList OpenItemIds); + +/// A remittance with its bank. +/// The remittance. +/// The bank (code and name). +public sealed record RemittanceRow(Remittance Remittance, string Bank); + +/// A line of a remittance with its item and party. +/// The line. +/// The item. +/// The party. +/// The reference of the mandate. +public sealed record RemittanceLineRow(RemittanceLine Line, OpenItem? Item, string PartyName, string? Mandate); + +/// +/// The remittances (distinte, SPEC §11.8, mockup 055, ADR 0038): RiBa in the CBI file of the pack, SEPA direct +/// debits (pain.008) with their mandates, SEPA credit transfers to suppliers (pain.001). A remittance is +/// drafted from the items due, its file generated, then presented (the effects move to the bills account, or the +/// transfers pay the suppliers), credited at maturity, with the unpaid effects reopened with their fees. +/// +public sealed class RemittanceService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The clock. + public RemittanceService(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 direction of the items of a kind of remittance. + /// The kind. + /// Payables for credit transfers, receivables otherwise. + public static OpenItemDirection DirectionOf(RemittanceKind kind) => + kind == RemittanceKind.SepaCreditTransfer ? OpenItemDirection.Payable : OpenItemDirection.Receivable; + + /// The remittances of a year. + /// Who reads. + /// The company. + /// The year. + /// Cancellation. + /// The remittances, latest first. + public async Task> ListAsync(Actor actor, string companyCode, int year, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var list = (await uow.Repository().ListAsync( + Query.For().Where(r => r.Year == year).OrderByDescending(r => r.Number), cancellationToken).ConfigureAwait(false)).Items; + var banks = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(b => b.Id); + return [.. list.Select(r => new RemittanceRow(r, banks.TryGetValue(r.BankAccountId, out var b) ? b.Code + " · " + (b.BankName ?? b.Description) : string.Empty))]; + } + + /// A remittance with its lines. + /// Who reads. + /// The company. + /// The remittance. + /// Cancellation. + /// The remittance and its lines, or . + public async Task<(RemittanceRow Row, IReadOnlyList Lines)?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } remittance) + { + return null; + } + + var bank = await uow.Repository().GetAsync(remittance.BankAccountId, cancellationToken).ConfigureAwait(false); + var lines = await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false); + var itemIds = lines.Select(l => l.OpenItemId).ToList(); + var items = (await uow.Repository().ListAsync(Query.For().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id); + var parties = await TreasuryStore.PartiesAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false); + var mandates = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id); + return ( + new RemittanceRow(remittance, bank is null ? string.Empty : bank.Code + " · " + (bank.BankName ?? bank.Description)), + [.. lines.Select(l => new RemittanceLineRow( + l, items.GetValueOrDefault(l.OpenItemId), parties.GetValueOrDefault(l.PartyId)?.Name ?? string.Empty, + l.MandateId is { } m ? mandates.GetValueOrDefault(m)?.Reference : null))]); + } + + /// The items that can go in a remittance of a kind, due up to a day. + /// Who reads. + /// The company. + /// The kind. + /// The last due date. + /// Cancellation. + /// The candidates, by due date. + public async Task> CandidatesAsync( + Actor actor, string companyCode, RemittanceKind kind, DateOnly dueUntil, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var direction = DirectionOf(kind); + var items = (await uow.Repository().ListAsync( + Query.For().Where(o => o.Direction == direction && !o.Closed && !o.Disputed && o.DueDate <= dueUntil + && (o.Status == OpenItemStatus.Open || o.Status == OpenItemStatus.Partial || o.Status == OpenItemStatus.Unpaid)).OrderBy(o => o.DueDate).OrderBy(o => o.Id), + cancellationToken).ConfigureAwait(false)).Items; + var methods = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id); + var kinds = pack.GetFeature(); + var chosen = items.Where(i => i.Residual > 0m && Fits(kind, i.PaymentMethodId is { } m && methods.TryGetValue(m, out var method) ? kinds?.KindOf(method.EInvoiceCode) : null)).ToList(); + var rows = await ScheduleService.RowsAsync(uow, chosen, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false); + var context = await PartyBanksAsync(uow, chosen.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false); + return [.. rows.Select(r => Candidate(kind, r, context))]; + } + + /// Drafts a remittance with items; they are reserved for it. + /// Who drafts it. + /// The company. + /// The remittance. + /// Cancellation. + /// The remittance. + public async Task CreateAsync(Actor actor, string companyCode, RemittanceInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + if (input.OpenItemIds.Count == 0) + { + throw new ValidationFailedException(["OpenItemIds:" + TreasuryErrors.RemittanceEmpty]); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + _ = await uow.Repository().GetAsync(input.BankAccountId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]); + var year = input.PresentationDate.Year; + var number = (int)((await uow.QuerySingleAsync(SqlFragment.Of($"SELECT MAX(number) FROM remittances WHERE year = {year}"), cancellationToken).ConfigureAwait(false) ?? 0L) + 1L); + var remittance = new Remittance + { + Year = year, + Number = number, + Kind = input.Kind, + BankAccountId = input.BankAccountId, + PresentationDate = input.PresentationDate, + DueUntil = input.DueUntil, + Advance = input.Advance && input.Kind != RemittanceKind.SepaCreditTransfer, + Status = RemittanceStatus.Draft, + Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Notes) ? null : input.Notes.Trim(), 500), + }; + remittance.Id = await uow.Repository().InsertAsync(remittance, cancellationToken).ConfigureAwait(false); + var itemRepository = uow.Repository(); + var direction = DirectionOf(input.Kind); + var items = new List(); + foreach (var id in input.OpenItemIds.Distinct()) + { + var item = await itemRepository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["OpenItemIds:" + TreasuryErrors.NotFound]); + if (item.Direction != direction || item.Closed || item.Residual <= 0m || item.Status == OpenItemStatus.InRemittance || item.Disputed) + { + throw new ValidationFailedException(["OpenItemIds:" + TreasuryErrors.RemittanceItem]); + } + + items.Add(item); + } + + var banks = await PartyBanksAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false); + var lines = uow.Repository(); + foreach (var item in items) + { + var mandate = MandateOf(input.Kind, item.PartyId, banks); + var line = new RemittanceLine + { + RemittanceId = remittance.Id, + OpenItemId = item.Id, + PartyId = item.PartyId, + Amount = item.Residual, + DueDate = item.DueDate, + Iban = mandate?.Iban ?? banks.Accounts.GetValueOrDefault(item.PartyId)?.Iban, + MandateId = mandate?.Id, + Status = RemittanceLineStatus.Included, + }; + line.Id = await lines.InsertAsync(line, cancellationToken).ConfigureAwait(false); + line.EndToEndId = EndToEnd(remittance, line); + await lines.UpdateAsync(line, cancellationToken).ConfigureAwait(false); + item.RemittanceId = remittance.Id; + item.Status = OpenItemStatus.InRemittance; + await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + + remittance.ItemCount = items.Count; + remittance.TotalAmount = items.Sum(i => i.Residual); + remittance.IsDemo = items.All(i => i.IsDemo); + await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, remittance.Id, null, remittance, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return remittance; + } + + /// Takes a line out of a remittance not presented. + /// Who does it. + /// The company. + /// The line. + /// Cancellation. + /// A task. + public async Task RemoveLineAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var line = await uow.Repository().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var remittance = await EditableAsync(uow, line.RemittanceId, cancellationToken).ConfigureAwait(false); + await ReleaseAsync(uow, line, cancellationToken).ConfigureAwait(false); + await uow.Repository().DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false); + remittance.ItemCount--; + remittance.TotalAmount -= line.Amount; + remittance.Status = RemittanceStatus.Draft; + await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Deletes a remittance not presented; its items are free again. + /// Who does it. + /// The company. + /// The remittance. + /// 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, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var remittance = await EditableAsync(uow, id, cancellationToken).ConfigureAwait(false); + foreach (var line in await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false)) + { + await ReleaseAsync(uow, line, cancellationToken).ConfigureAwait(false); + } + + await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, remittance, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Writes the file of a remittance for the bank (CBI for RiBa, XML for SEPA). + /// Who does it. + /// The company. + /// The remittance. + /// Cancellation. + /// The file. + public async Task FileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false); + 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); + var remittance = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var lines = (await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false)).Where(l => l.Status != RemittanceLineStatus.Unpaid).ToList(); + if (lines.Count == 0) + { + throw new ValidationFailedException(["Lines:" + TreasuryErrors.RemittanceEmpty]); + } + + var bank = await uow.Repository().GetAsync(remittance.BankAccountId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]); + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var errors = new List(); + if (!IbanValidator.IsValid(bank.Iban) + || (remittance.Kind == RemittanceKind.Riba && string.IsNullOrWhiteSpace(bank.SiaCode)) + || (remittance.Kind is RemittanceKind.SddCore or RemittanceKind.SddB2b && string.IsNullOrWhiteSpace(bank.CreditorId))) + { + errors.Add("BankAccountId:" + TreasuryErrors.RemittanceBank); + } + + var parties = await TreasuryStore.PartiesAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false); + var partyBanks = await PartyBanksAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false); + var itemIds = lines.Select(l => l.OpenItemId).ToList(); + var items = (await uow.Repository().ListAsync(Query.For().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id); + var fileItems = new List(); + var number = 0; + foreach (var line in lines) + { + var party = parties.GetValueOrDefault(line.PartyId); + var mandate = line.MandateId is { } m ? partyBanks.Mandates.FirstOrDefault(x => x.Id == m) : null; + if (remittance.Kind != RemittanceKind.Riba && !IbanValidator.IsValid(line.Iban)) + { + errors.Add("Lines:" + TreasuryErrors.RemittanceIban); + } + + if (remittance.Kind == RemittanceKind.Riba && string.IsNullOrWhiteSpace(line.Iban) && partyBanks.Accounts.GetValueOrDefault(line.PartyId) is not { BankCode: not null, BranchCode: not null }) + { + errors.Add("Lines:" + TreasuryErrors.RemittanceIban); + } + + if (remittance.Kind is RemittanceKind.SddCore or RemittanceKind.SddB2b && (mandate is null || mandate.Revoked)) + { + errors.Add("Lines:" + TreasuryErrors.RemittanceMandate); + } + + var item = items.GetValueOrDefault(line.OpenItemId); + var account = partyBanks.Accounts.GetValueOrDefault(line.PartyId); + fileItems.Add(new BankFileItem( + ++number, + party?.Code ?? line.PartyId.ToString(CultureInfo.InvariantCulture), + party?.Name ?? string.Empty, + party?.TaxCode ?? party?.VatNumber, + party?.Address is null ? null : party.Address + (party.StreetNumber is null ? string.Empty : " " + party.StreetNumber), + party?.PostalCode, + party?.City, + party?.Province, + party?.CountryCode ?? "IT", + line.Iban ?? account?.Iban, + mandate?.Bic ?? account?.Bic, + account?.BankName, + line.Amount, + line.DueDate, + item is null ? remittance.DisplayNumber : TreasuryStore.ItemText(item), + line.EndToEndId ?? EndToEnd(remittance, line), + mandate?.Reference, + mandate?.SignatureDate, + mandate is null ? SddSequence.Recurrent : mandate.OneOff ? SddSequence.OneOff : mandate.LastCollectionDate is null ? SddSequence.First : SddSequence.Recurrent)); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException([.. errors.Distinct(StringComparer.Ordinal)]); + } + + var messageId = LedgerStore.Trim("KH" + remittance.Year.ToString(CultureInfo.InvariantCulture) + remittance.Number.ToString("000", CultureInfo.InvariantCulture) + + "T" + _clock.GetUtcNow().ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture), 35)!; + var fileRemittance = new BankFileRemittance( + remittance.Kind, + messageId, + _clock.GetLocalNow().DateTime, + remittance.Kind == RemittanceKind.SepaCreditTransfer ? remittance.PresentationDate : lines.Min(l => l.DueDate), + new BankFileCompany( + profile?.LegalName ?? string.Empty, profile?.TaxCode ?? profile?.VatNumber, profile?.Address, profile?.PostalCode, profile?.City, profile?.ProvinceCode, + profile?.AddressCountry ?? profile?.Country ?? "IT", bank.Iban ?? string.Empty, bank.Bic, bank.SiaCode, bank.CucCode, bank.CreditorId), + fileItems); + BankFile file; + try + { + file = remittance.Kind switch + { + RemittanceKind.SepaCreditTransfer => SepaXmlWriter.CreditTransfer(fileRemittance), + RemittanceKind.SddCore or RemittanceKind.SddB2b => SepaXmlWriter.DirectDebit(fileRemittance), + _ => pack.GetFeature() is { } writer && writer.Supports(remittance.Kind) + ? writer.Write(fileRemittance) + : throw new ValidationFailedException(["Kind:" + TreasuryErrors.RemittanceFormat]), + }; + } + catch (BankFileException) + { + throw new ValidationFailedException(["Lines:" + TreasuryErrors.RemittanceFormat]); + } + + remittance.MessageId = messageId; + remittance.FileName = LedgerStore.Trim(file.FileName, 100); + if (remittance.Status == RemittanceStatus.Draft) + { + remittance.Status = RemittanceStatus.Generated; + } + + await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return new LedgerFile(file.FileName, file.ContentType, file.Content); + } + + /// + /// Presents a remittance to the bank: RiBa and direct debits move the receivables to the bills account (and the + /// advance to the bank when advanced); credit transfers pay the suppliers and close the remittance. + /// + /// Who does it. + /// The company. + /// The remittance. + /// Cancellation. + /// The remittance. + public async Task PresentAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentWrite, cancellationToken).ConfigureAwait(false); + 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); + var remittance = await EditableAsync(uow, id, cancellationToken).ConfigureAwait(false); + var before = Copy(remittance); + var lines = await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false); + if (lines.Count == 0) + { + throw new ValidationFailedException(["Lines:" + TreasuryErrors.RemittanceEmpty]); + } + + var itemRepository = uow.Repository(); + var lineRepository = uow.Repository(); + if (remittance.Kind == RemittanceKind.SepaCreditTransfer) + { + foreach (var group in lines.GroupBy(l => l.PartyId)) + { + foreach (var line in group) + { + var item = await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false); + if (item is not null) + { + // The transfer pays the item: it leaves the remittance state for the payment to settle it. + item.Status = item.PaidAmount != 0m ? OpenItemStatus.Partial : OpenItemStatus.Open; + await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + } + + var payment = await PaymentService.RegisterAsync( + uow, + pack, + new PaymentInput(PaymentDirection.Disbursement, group.Key, remittance.PresentationDate, null, remittance.BankAccountId, 0m, "Distinta " + remittance.DisplayNumber, null, + [.. group.Select(l => new PaymentLineInput(l.OpenItemId, l.Amount))]), + PaymentOrigin.Remittance, + remittance.Id, + null, + cancellationToken).ConfigureAwait(false); + foreach (var line in group) + { + line.Status = RemittanceLineStatus.Paid; + line.PaymentId = payment.Id; + await lineRepository.UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + } + + remittance.Status = RemittanceStatus.Closed; + remittance.CreditedOn = remittance.PresentationDate; + } + else + { + var ledger = pack.GetFeature(); + var template = await LedgerStore.TemplateAsync(uow, "DIST", cancellationToken).ConfigureAwait(false); + var bills = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BillsForCollection, ledger, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]); + var posted = new List(); + foreach (var line in lines) + { + var item = await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["Lines:" + TreasuryErrors.NotFound]); + posted.Add(new PaymentPostedLine(item.AccountId, item.PartyId, item.Id, TreasuryStore.ItemText(item), 0m, line.Amount)); + item.PaidAmount += line.Amount; + item.Status = OpenItemStatus.InRemittance; + item.Closed = false; + await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + + var total = lines.Sum(l => l.Amount); + posted.Insert(0, new PaymentPostedLine(bills, null, null, "Effetti all'incasso distinta " + remittance.DisplayNumber, total, 0m)); + var entry = await TreasuryStore.PostAsync(uow, "DIST", remittance.PresentationDate, "Presentazione distinta " + remittance.DisplayNumber, null, posted, remittance.IsDemo, cancellationToken).ConfigureAwait(false); + remittance.GlEntryId = entry.Id; + if (remittance.Advance) + { + var advance = await LedgerStore.TemplateAsync(uow, "ANT", cancellationToken).ConfigureAwait(false); + var bank = await TreasuryStore.BankAsync(uow, remittance.BankAccountId, cancellationToken).ConfigureAwait(false); + var money = await TreasuryStore.MoneyAccountAsync(uow, bank, false, advance?.Lines, ledger, cancellationToken).ConfigureAwait(false); + var advances = await TreasuryStore.RoleAccountAsync(uow, advance?.Lines, PostingRole.BankAdvances, ledger, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]); + var text = "Anticipo s.b.f. distinta " + remittance.DisplayNumber; + var credit = await TreasuryStore.PostAsync( + uow, "ANT", remittance.PresentationDate, text, null, + [new PaymentPostedLine(money, null, null, text, total, 0m), new PaymentPostedLine(advances, null, null, text, 0m, total)], remittance.IsDemo, cancellationToken).ConfigureAwait(false); + remittance.CreditEntryId = credit.Id; + } + + remittance.Status = RemittanceStatus.Presented; + await MarkMandatesAsync(uow, lines, cancellationToken).ConfigureAwait(false); + } + + await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, remittance.Id, before, remittance, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return remittance; + } + + /// Records the credit at maturity of a presented remittance: the effects not unpaid are collected. + /// Who does it. + /// The company. + /// The remittance. + /// The day of the credit. + /// Cancellation. + /// The remittance. + public async Task CreditAsync(Actor actor, string companyCode, long id, DateOnly creditedOn, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentWrite, cancellationToken).ConfigureAwait(false); + 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); + var remittance = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + if (remittance.Status != RemittanceStatus.Presented) + { + throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]); + } + + var before = Copy(remittance); + await CreditInsideAsync(uow, pack, remittance, creditedOn, cancellationToken).ConfigureAwait(false); + await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, remittance.Id, before, remittance, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return remittance; + } + + /// + /// Records an unpaid effect or direct debit (insoluto): the receivable reopens as unpaid, the bank takes the money + /// back (or the bills account is closed before the credit) and the fees become a new item of the customer. + /// + /// Who does it. + /// The company. + /// The line of the remittance. + /// The day the bank returned it. + /// The fees charged by the bank, debited to the customer. + /// Cancellation. + /// The line. + public async Task UnpaidAsync(Actor actor, string companyCode, long lineId, DateOnly date, decimal fees, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentWrite, cancellationToken).ConfigureAwait(false); + 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); + var line = await uow.Repository().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var remittance = await uow.Repository().GetAsync(line.RemittanceId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + if (remittance.Kind == RemittanceKind.SepaCreditTransfer || remittance.Status is not (RemittanceStatus.Presented or RemittanceStatus.Closed) || line.Status == RemittanceLineStatus.Unpaid) + { + throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]); + } + + await UnpaidInsideAsync(uow, pack, line, date, fees, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, line.Id, null, line, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return line; + } + + /// Credits a presented remittance inside a transaction (also from the bank reconciliation). + internal static async Task CreditInsideAsync(IUnitOfWork uow, IFiscalPack pack, Remittance remittance, DateOnly creditedOn, CancellationToken cancellationToken) + { + if (remittance.Status != RemittanceStatus.Presented) + { + throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]); + } + + var lines = (await LinesAsync(uow, remittance.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.Status == RemittanceLineStatus.Included).ToList(); + var total = lines.Sum(l => l.Amount); + if (total != 0m) + { + var ledger = pack.GetFeature(); + var template = await LedgerStore.TemplateAsync(uow, "ACCR", cancellationToken).ConfigureAwait(false); + var bills = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BillsForCollection, ledger, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]); + var debit = remittance.Advance + ? await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BankAdvances, ledger, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]) + : await TreasuryStore.MoneyAccountAsync( + uow, await TreasuryStore.BankAsync(uow, remittance.BankAccountId, cancellationToken).ConfigureAwait(false), false, template?.Lines, ledger, cancellationToken).ConfigureAwait(false); + var text = "Accredito distinta " + remittance.DisplayNumber; + var entry = await TreasuryStore.PostAsync( + uow, "ACCR", creditedOn, text, null, [new PaymentPostedLine(debit, null, null, text, total, 0m), new PaymentPostedLine(bills, null, null, text, 0m, total)], + remittance.IsDemo, cancellationToken).ConfigureAwait(false); + remittance.CreditEntryId ??= entry.Id; + if (remittance.Advance) + { + // The advance entry stays the credit entry; the closing of the bills is kept in the notes of the history. + remittance.Notes = LedgerStore.Trim((remittance.Notes is null ? string.Empty : remittance.Notes + " · ") + "Chiusura effetti " + entry.EntryNumber, 500); + } + else + { + remittance.CreditEntryId = entry.Id; + } + } + + var itemRepository = uow.Repository(); + foreach (var line in lines) + { + if (await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) is { } item) + { + item.Status = item.Residual == 0m ? OpenItemStatus.Closed : OpenItemStatus.Partial; + item.Closed = item.Residual == 0m; + await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + + line.Status = RemittanceLineStatus.Paid; + await uow.Repository().UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + + remittance.Status = RemittanceStatus.Closed; + remittance.CreditedOn = creditedOn; + await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false); + } + + /// Records an unpaid effect inside a transaction (also from the bank reconciliation). + internal static async Task UnpaidInsideAsync(IUnitOfWork uow, IFiscalPack pack, RemittanceLine line, DateOnly date, decimal fees, CancellationToken cancellationToken) + { + if (fees < 0m) + { + throw new ValidationFailedException(["Fees:" + TreasuryErrors.AmountRequired]); + } + + var remittance = await uow.Repository().GetAsync(line.RemittanceId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + if (remittance.Kind == RemittanceKind.SepaCreditTransfer || remittance.Status is not (RemittanceStatus.Presented or RemittanceStatus.Closed) || line.Status == RemittanceLineStatus.Unpaid) + { + throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]); + } + + var item = await uow.Repository().GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var ledger = pack.GetFeature(); + var template = await LedgerStore.TemplateAsync(uow, "INS", cancellationToken).ConfigureAwait(false); + var bank = await TreasuryStore.BankAsync(uow, remittance.BankAccountId, cancellationToken).ConfigureAwait(false); + var money = await TreasuryStore.MoneyAccountAsync(uow, bank, false, template?.Lines, ledger, cancellationToken).ConfigureAwait(false); + var text = "Insoluto " + TreasuryStore.ItemText(item); + var posted = new List { new(item.AccountId, item.PartyId, item.Id, text, line.Amount, 0m) }; + if (line.Status == RemittanceLineStatus.Paid) + { + // Already credited: the bank takes the money back. + posted.Add(new PaymentPostedLine(money, null, null, text, 0m, line.Amount)); + } + else + { + var bills = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BillsForCollection, ledger, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]); + posted.Add(new PaymentPostedLine(bills, null, null, text, 0m, line.Amount)); + if (remittance.Advance) + { + var advances = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BankAdvances, ledger, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]); + posted.Add(new PaymentPostedLine(advances, null, null, "Rientro anticipo " + text, line.Amount, 0m)); + posted.Add(new PaymentPostedLine(money, null, null, "Rientro anticipo " + text, 0m, line.Amount)); + } + } + + if (fees > 0m) + { + posted.Add(new PaymentPostedLine(item.AccountId, item.PartyId, null, "Spese insoluto", fees, 0m)); + posted.Add(new PaymentPostedLine(money, null, null, "Spese insoluto", 0m, fees)); + } + + var entry = await TreasuryStore.PostAsync(uow, "INS", date, text, item.PartyId, posted, item.IsDemo, cancellationToken).ConfigureAwait(false); + item.PaidAmount -= line.Amount; + item.RemittanceId = null; + item.UnpaidCount++; + item.Status = OpenItemStatus.Unpaid; + item.Status = OpenItemStates.Of(item); + item.Closed = false; + await uow.Repository().UpdateAsync(item, cancellationToken).ConfigureAwait(false); + if (fees > 0m) + { + await uow.Repository().InsertAsync(new OpenItem + { + Direction = item.Direction, + PartyId = item.PartyId, + AccountId = item.AccountId, + EntryId = entry.Id, + SourceFamily = item.SourceFamily, + SourceDocumentId = item.SourceDocumentId, + DocumentNumber = item.DocumentNumber, + DocumentDate = item.DocumentDate, + Installment = item.Installment, + DueDate = date, + Amount = fees, + PaymentMethodId = item.PaymentMethodId, + Status = OpenItemStatus.Open, + ParentId = item.Id, + Notes = "Spese insoluto", + IsDemo = item.IsDemo, + }, cancellationToken).ConfigureAwait(false); + } + + line.Status = RemittanceLineStatus.Unpaid; + line.UnpaidOn = date; + line.UnpaidFees = fees; + line.UnpaidEntryId = entry.Id; + await uow.Repository().UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + + internal static async Task> LinesAsync(IUnitOfWork uow, long remittanceId, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().Where(l => l.RemittanceId == remittanceId).OrderBy(l => l.DueDate).OrderBy(l => l.Id), cancellationToken) + .ConfigureAwait(false)).Items; + + private static bool Fits(RemittanceKind kind, RemittanceKind? methodKind) => kind switch + { + RemittanceKind.SepaCreditTransfer => methodKind is null or RemittanceKind.SepaCreditTransfer, + _ => methodKind == kind, + }; + + private static RemittanceCandidate Candidate(RemittanceKind kind, ScheduleRow row, PartyBanks banks) + { + var problems = new List(); + var mandate = MandateOf(kind, row.Item.PartyId, banks); + var account = banks.Accounts.GetValueOrDefault(row.Item.PartyId); + var iban = mandate?.Iban ?? account?.Iban; + if (kind is RemittanceKind.SddCore or RemittanceKind.SddB2b) + { + if (mandate is null) + { + problems.Add(TreasuryErrors.RemittanceMandate); + } + } + else if (kind == RemittanceKind.Riba) + { + if (string.IsNullOrWhiteSpace(iban) && account is not { BankCode: not null, BranchCode: not null }) + { + problems.Add(TreasuryErrors.RemittanceIban); + } + } + else if (!IbanValidator.IsValid(iban)) + { + problems.Add(TreasuryErrors.RemittanceIban); + } + + return new RemittanceCandidate(row, iban, mandate, problems); + } + + private static SddMandate? MandateOf(RemittanceKind kind, long partyId, PartyBanks banks) + { + if (kind is not (RemittanceKind.SddCore or RemittanceKind.SddB2b)) + { + return null; + } + + var scheme = kind == RemittanceKind.SddB2b ? SddScheme.B2b : SddScheme.Core; + return banks.Mandates.Where(m => m.PartyId == partyId && !m.Revoked && m.Scheme == scheme && !(m.OneOff && m.LastCollectionDate is not null)) + .OrderByDescending(m => m.SignatureDate).FirstOrDefault(); + } + + private static async Task PartyBanksAsync(IUnitOfWork uow, IEnumerable partyIds, CancellationToken cancellationToken) + { + var ids = partyIds.Distinct().ToList(); + var accounts = new Dictionary(); + var mandates = new List(); + foreach (var chunk in ids.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var account in (await uow.Repository().ListAsync( + Query.For().Where(a => list.Contains(a.PartyId)).OrderByDescending(a => a.IsDefault).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items) + { + accounts.TryAdd(account.PartyId, account); + } + + mandates.AddRange((await uow.Repository().ListAsync(Query.For().Where(m => list.Contains(m.PartyId)), cancellationToken).ConfigureAwait(false)).Items); + } + + return new PartyBanks(accounts, mandates); + } + + private static async Task EditableAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + var remittance = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + if (remittance.Status is not (RemittanceStatus.Draft or RemittanceStatus.Generated)) + { + throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]); + } + + return remittance; + } + + private static async Task ReleaseAsync(IUnitOfWork uow, RemittanceLine line, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) is not { } item || item.RemittanceId != line.RemittanceId) + { + return; + } + + item.RemittanceId = null; + item.Status = OpenItemStatus.Open; + item.Status = OpenItemStates.Of(item); + item.Closed = item.Status == OpenItemStatus.Closed; + await uow.Repository().UpdateAsync(item, cancellationToken).ConfigureAwait(false); + } + + private static async Task MarkMandatesAsync(IUnitOfWork uow, IReadOnlyList lines, CancellationToken cancellationToken) + { + foreach (var group in lines.Where(l => l.MandateId is not null).GroupBy(l => l.MandateId!.Value)) + { + if (await uow.Repository().GetAsync(group.Key, cancellationToken).ConfigureAwait(false) is { } mandate) + { + mandate.LastCollectionDate = group.Max(l => l.DueDate); + await uow.Repository().UpdateAsync(mandate, cancellationToken).ConfigureAwait(false); + } + } + } + + private static string EndToEnd(Remittance remittance, RemittanceLine line) => + "KH" + remittance.Year.ToString(CultureInfo.InvariantCulture) + remittance.Number.ToString("000", CultureInfo.InvariantCulture) + "-" + line.Id.ToString(CultureInfo.InvariantCulture); + + private static Remittance Copy(Remittance r) => new() + { + Id = r.Id, + Year = r.Year, + Number = r.Number, + Kind = r.Kind, + Status = r.Status, + TotalAmount = r.TotalAmount, + ItemCount = r.ItemCount, + GlEntryId = r.GlEntryId, + CreditedOn = r.CreditedOn, + CreditEntryId = r.CreditEntryId, + }; + + private sealed record PartyBanks(Dictionary Accounts, List Mandates); +} diff --git a/src/Khaemhat.Application/Treasury/ScheduleService.cs b/src/Khaemhat.Application/Treasury/ScheduleService.cs new file mode 100644 index 0000000..8205af5 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/ScheduleService.cs @@ -0,0 +1,363 @@ +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.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Treasury; + +/// The payment methods and the bank accounts of the company. +/// The payment methods in use. +/// The bank accounts in use. +public sealed record TreasuryChoices(IReadOnlyList Methods, IReadOnlyList Banks); + +/// Which items the schedule shows. +public enum ScheduleView +{ + /// Not closed: open, partial, unpaid, in remittance. + Open = 0, + + /// Not closed and past due. + Overdue = 1, + + /// Returned effects not collected again. + Unpaid = 2, + + /// In a remittance not credited yet. + InRemittance = 3, + + /// Disputed by the customer or the company. + Disputed = 4, + + /// Closed. + Closed = 5, + + /// Everything. + All = 6, +} + +/// The filter of the schedule. +/// Receivables or payables. +/// Which items. +/// One customer or supplier. +/// Due from this day. +/// Due up to this day. +/// One payment method. +/// Part of the party name or of the document number. +public sealed record ScheduleFilter( + OpenItemDirection Direction, ScheduleView View = ScheduleView.Open, long? PartyId = null, DateOnly? From = null, DateOnly? To = null, + long? PaymentMethodId = null, string? Search = null); + +/// An item of the schedule with what the grid shows. +/// The item. +/// The code of the party. +/// The name of the party. +/// The payment method (code). +/// The payment method (description). +/// Days past due (negative when not due). +/// The number of the remittance that holds it. +public sealed record ScheduleRow(OpenItem Item, string? PartyCode, string PartyName, string? Method, string? MethodDescription, int DaysOverdue, string? Remittance); + +/// The schedule: the rows of the filter and the aging of what is open. +/// The rows, by due date. +/// The residual by age of the open items of the filter. +/// The residual of the rows. +/// The overdue residual of the rows. +/// The residual due in the next 30 days. +public sealed record ScheduleResult(IReadOnlyList Rows, AgingBuckets Aging, decimal Residual, decimal Overdue, decimal DueIn30Days); + +/// A change of an item by hand. +/// The due date. +/// The payment method. +/// The bank of the company it is collected on. +/// Disputed: left out of reminders and remittances. +/// Notes. +public sealed record OpenItemChange(DateOnly DueDate, long? PaymentMethodId, long? BankAccountId, bool Disputed, string? Notes); + +/// The statement of account of a party. +/// The party. +/// Receivables or payables. +/// The day of the statement. +/// The items not closed, by due date. +/// The collections or payments of the last twelve months. +/// What is left. +/// What is past due. +/// The late payment interest to the day, when the pack has the rules. +public sealed record PartyStatement(Party Party, OpenItemDirection Direction, DateOnly Day, IReadOnlyList Items, IReadOnlyList Payments, decimal Residual, decimal Overdue, decimal Interest); + +/// +/// The schedule (scadenzario, SPEC §11.8, mockup 053, ADR 0038): the open items of the ledger with their state, the +/// aging by bucket, the change of due date, method, bank and dispute, the statement of account and the export. +/// +public sealed class ScheduleService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The clock. + public ScheduleService(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 items of a filter with the aging. + /// Who reads. + /// The company. + /// The filter. + /// Cancellation. + /// The schedule. + public async Task ItemsAsync(Actor actor, string companyCode, ScheduleFilter filter, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(filter); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await LoadAsync(uow, filter, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false); + } + + /// An item with its row. + /// Who reads. + /// The company. + /// The item. + /// Cancellation. + /// The row, or . + public async Task ItemAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item) + { + return null; + } + + return (await RowsAsync(uow, [item], TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false))[0]; + } + + /// Changes due date, method, bank, dispute and notes of an item. + /// Who changes it. + /// The company. + /// The item. + /// The change. + /// Cancellation. + /// The item. + public async Task UpdateAsync(Actor actor, string companyCode, long id, OpenItemChange change, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(change); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, 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 item = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var before = Copy(item); + if (item.Status == OpenItemStatus.InRemittance && (change.DueDate != item.DueDate || change.PaymentMethodId != item.PaymentMethodId)) + { + throw new ValidationFailedException(["DueDate:" + TreasuryErrors.InRemittance]); + } + + item.DueDate = change.DueDate; + item.PaymentMethodId = change.PaymentMethodId; + item.BankAccountId = change.BankAccountId; + item.Disputed = change.Disputed; + item.Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(change.Notes) ? null : change.Notes.Trim(), 200); + await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, item.Id, before, item, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return item; + } + + /// The statement of account of a party (estratto conto). + /// Who reads. + /// The company. + /// The party. + /// Receivables or payables. + /// Cancellation. + /// The statement. + public async Task StatementAsync(Actor actor, string companyCode, long partyId, OpenItemDirection direction, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var party = await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound); + var today = TreasuryStore.Today(_clock); + var result = await LoadAsync(uow, new ScheduleFilter(direction, ScheduleView.Open, partyId), today, cancellationToken).ConfigureAwait(false); + var since = today.AddYears(-1); + var paymentDirection = direction == OpenItemDirection.Receivable ? PaymentDirection.Receipt : PaymentDirection.Disbursement; + var payments = (await uow.Repository().ListAsync( + Query.For().Where(p => p.PartyId == partyId && p.Direction == paymentDirection && p.PaymentDate >= since).OrderByDescending(p => p.PaymentDate), + cancellationToken).ConfigureAwait(false)).Items; + var interest = rules is null || direction != OpenItemDirection.Receivable + ? 0m + : result.Rows.Where(r => r.Item.Residual > 0m && r.Item.DueDate < today).Sum(r => LateInterestCalculator.Interest(r.Item.Residual, r.Item.DueDate, today, rules.RateOn)); + return new PartyStatement(party, direction, today, result.Rows, payments, result.Residual, result.Overdue, interest); + } + + /// The rows of a filter as a CSV file. + /// Who reads. + /// The company. + /// The filter. + /// Cancellation. + /// The file. + public async Task ExportAsync(Actor actor, string companyCode, ScheduleFilter filter, CancellationToken cancellationToken = default) + { + var result = await ItemsAsync(actor, companyCode, filter, cancellationToken).ConfigureAwait(false); + using var output = new MemoryStream(); + await using (var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true)) + { + await csv.WriteRowAsync(["Codice", "Soggetto", "Documento", "Data documento", "Rata", "Scadenza", "Importo", "Pagato", "Residuo", "Stato", "Modalità", "Giorni scaduto", "Distinta", "Contestata", "Note"], cancellationToken).ConfigureAwait(false); + foreach (var row in result.Rows) + { + var item = row.Item; + await csv.WriteRowAsync( + [row.PartyCode, row.PartyName, item.DocumentNumber, item.DocumentDate, item.Installment, item.DueDate, item.Amount, item.PaidAmount, item.Residual, + item.Status.ToString(), row.Method, Math.Max(0, row.DaysOverdue), row.Remittance, item.Disputed ? "Sì" : "No", item.Notes], + cancellationToken).ConfigureAwait(false); + } + + await csv.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + var name = (filter.Direction == OpenItemDirection.Receivable ? "scadenzario-clienti-" : "scadenzario-fornitori-") + + TreasuryStore.Today(_clock).ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".csv"; + return new LedgerFile(name, "text/csv", output.ToArray()); + } + + /// The items due in the next days, for the dashboard (receivables and payables). + /// Who reads. + /// The company. + /// How many days ahead. + /// How many rows at most. + /// Cancellation. + /// The rows, by due date, overdue first. + public async Task> DueSoonAsync(Actor actor, string companyCode, int days = 30, int take = 8, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var today = TreasuryStore.Today(_clock); + var until = today.AddDays(days); + var items = (await uow.Repository().ListAsync( + Query.For().Where(o => !o.Closed && o.DueDate <= until).OrderBy(o => o.DueDate).OrderBy(o => o.Id).Take(take), cancellationToken).ConfigureAwait(false)).Items; + return await RowsAsync(uow, items, today, cancellationToken).ConfigureAwait(false); + } + + /// The payment methods and the bank accounts in use, for the choices of the treasury screens. + /// Who reads. + /// The company. + /// Cancellation. + /// The choices, by code. + public async Task ChoicesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var methods = (await uow.Repository().ListAsync(Query.For().Where(m => !m.Disabled).OrderBy(m => m.Code), cancellationToken).ConfigureAwait(false)).Items; + var banks = (await uow.Repository().ListAsync(Query.For().Where(b => !b.Disabled).OrderBy(b => b.Code), cancellationToken).ConfigureAwait(false)).Items; + return new TreasuryChoices(methods, banks); + } + + internal static async Task LoadAsync(IUnitOfWork uow, ScheduleFilter filter, DateOnly today, CancellationToken cancellationToken) + { + var direction = filter.Direction; + var query = Query.For().Where(o => o.Direction == direction); + if (filter.PartyId is { } party) + { + query = query.Where(o => o.PartyId == party); + } + + if (filter.From is { } from) + { + query = query.Where(o => o.DueDate >= from); + } + + if (filter.To is { } to) + { + query = query.Where(o => o.DueDate <= to); + } + + if (filter.PaymentMethodId is { } method) + { + query = query.Where(o => o.PaymentMethodId == method); + } + + query = filter.View switch + { + ScheduleView.Open => query.Where(o => !o.Closed), + ScheduleView.Overdue => query.Where(o => !o.Closed && o.DueDate < today && o.Status != OpenItemStatus.InRemittance), + ScheduleView.Unpaid => query.Where(o => o.Status == OpenItemStatus.Unpaid), + ScheduleView.InRemittance => query.Where(o => o.Status == OpenItemStatus.InRemittance), + ScheduleView.Disputed => query.Where(o => o.Disputed && !o.Closed), + ScheduleView.Closed => query.Where(o => o.Closed), + _ => query, + }; + var items = (await uow.Repository().ListAsync(query.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items; + var rows = await RowsAsync(uow, items, today, cancellationToken).ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(filter.Search)) + { + var search = filter.Search.Trim(); + rows = [.. rows.Where(r => r.PartyName.Contains(search, StringComparison.OrdinalIgnoreCase) + || (r.PartyCode?.Contains(search, StringComparison.OrdinalIgnoreCase) ?? false) + || (r.Item.DocumentNumber?.Contains(search, StringComparison.OrdinalIgnoreCase) ?? false))]; + } + + var open = rows.Where(r => !r.Item.Closed && r.Item.Status != OpenItemStatus.InRemittance).ToList(); + var aging = AgingCalculator.Of(open.Select(r => (r.Item.DueDate, r.Item.Residual)), today); + var limit = today.AddDays(30); + return new ScheduleResult( + rows, + aging, + rows.Where(r => !r.Item.Closed).Sum(r => r.Item.Residual), + open.Where(r => r.Item.DueDate < today).Sum(r => r.Item.Residual), + open.Where(r => r.Item.DueDate >= today && r.Item.DueDate <= limit).Sum(r => r.Item.Residual)); + } + + internal static async Task> RowsAsync(IUnitOfWork uow, IReadOnlyList items, DateOnly today, CancellationToken cancellationToken) + { + var parties = await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false); + var methods = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id); + var remittanceIds = items.Where(i => i.RemittanceId is not null).Select(i => i.RemittanceId!.Value).Distinct().ToList(); + var remittances = remittanceIds.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(r => remittanceIds.Contains(r.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id); + return [.. items.Select(i => + { + var party = parties.GetValueOrDefault(i.PartyId); + var method = i.PaymentMethodId is { } m ? methods.GetValueOrDefault(m) : null; + var remittance = i.RemittanceId is { } r ? remittances.GetValueOrDefault(r) : null; + return new ScheduleRow(i, party?.Code, party?.Name ?? string.Empty, method?.Code, method?.Description, AgingCalculator.DaysOverdue(i.DueDate, today), remittance?.DisplayNumber); + })]; + } + + private static OpenItem Copy(OpenItem o) => new() + { + Id = o.Id, + DueDate = o.DueDate, + PaymentMethodId = o.PaymentMethodId, + BankAccountId = o.BankAccountId, + Disputed = o.Disputed, + Notes = o.Notes, + Status = o.Status, + PaidAmount = o.PaidAmount, + }; +} diff --git a/src/Khaemhat.Application/Treasury/TreasuryFeedSource.cs b/src/Khaemhat.Application/Treasury/TreasuryFeedSource.cs new file mode 100644 index 0000000..2c4b377 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/TreasuryFeedSource.cs @@ -0,0 +1,79 @@ +using System.Globalization; +using Khaemhat.Application.Dashboard; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Application.Treasury; + +/// +/// The schedule on the dashboard (SPEC §10.3): the collections and payments due in the next days among the deadlines, +/// and the customers' items past due among the things to do. Only for who may see the schedule of the company. +/// +/// The schedule. +/// The permissions, licence included. +/// The texts. +public sealed class TreasuryFeedSource(ScheduleService schedule, PermissionService permissions, ITexts texts) : IDeadlineSource, ITodoSource +{ + /// The text key of the area. + public const string Area = "Dashboard.Areas.Treasury"; + + /// The most deadlines of the schedule on the dashboard. + public const int MaxDeadlines = 12; + + private const string Href = "/scadenzario/scadenze"; + + /// + public async Task> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (!await AllowedAsync(context, cancellationToken).ConfigureAwait(false)) + { + return []; + } + + var days = Math.Max(0, until.DayNumber - context.Today.DayNumber); + var rows = await schedule.DueSoonAsync(context.Actor, context.Actor.CompanyCode!, days, MaxDeadlines * 2, cancellationToken).ConfigureAwait(false); + return [.. rows.Where(r => r.Item.DueDate >= context.Today && r.Item.Status != OpenItemStatus.InRemittance).Take(MaxDeadlines).Select(r => + { + var receivable = r.Item.Direction == OpenItemDirection.Receivable; + return new FeedItem( + "openitem-" + r.Item.Id.ToString(CultureInfo.InvariantCulture), + texts.Format(receivable ? "Dashboard.Feed.DueReceivable" : "Dashboard.Feed.DuePayable", r.PartyName, texts.Money(r.Item.Residual)), + Area, + receivable ? FeedTone.Info : FeedTone.Warning) + { + Detail = r.Item.DocumentNumber, + When = new DateTimeOffset(r.Item.DueDate.ToDateTime(TimeOnly.MinValue), context.Now.Offset), + Href = Href + (receivable ? string.Empty : "?vista=fornitori"), + }; + })]; + } + + /// + public async Task> GetAsync(FeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (!await AllowedAsync(context, cancellationToken).ConfigureAwait(false)) + { + return []; + } + + var overdue = await schedule.ItemsAsync(context.Actor, context.Actor.CompanyCode!, new ScheduleFilter(OpenItemDirection.Receivable, ScheduleView.Overdue), cancellationToken) + .ConfigureAwait(false); + return overdue.Rows.Count == 0 + ? [] + : + [ + new FeedItem("openitems-overdue", texts.Format("Dashboard.Feed.Overdue", overdue.Rows.Count, texts.Money(overdue.Overdue)), Area, FeedTone.Error) + { + Priority = 40, + Href = "/scadenzario/solleciti", + }, + ]; + } + + private async Task AllowedAsync(FeedContext context, CancellationToken cancellationToken) => + context.Actor.CompanyCode is not null && (await permissions.CheckAsync(context.Actor, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false)).Allowed; +} diff --git a/src/Khaemhat.Application/Treasury/TreasuryStore.cs b/src/Khaemhat.Application/Treasury/TreasuryStore.cs new file mode 100644 index 0000000..a0f3a48 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/TreasuryStore.cs @@ -0,0 +1,169 @@ +using System.Globalization; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Security; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Treasury; + +/// The permissions of the schedule and the treasury (module FIN, ). +public static class TreasuryPermissions +{ + /// See the schedule, the remittances, the reminders and the cash flow. + public const string ScheduleRead = "finance.schedule.read"; + + /// Change due dates, disputes, remittances, mandates and reminders. + public const string ScheduleWrite = "finance.schedule.write"; + + /// See collections and payments. + public const string PaymentRead = "finance.payment.read"; + + /// Record collections and payments. + public const string PaymentWrite = "finance.payment.write"; + + /// Import bank statements and reconcile them. + public const string BankReconcile = "finance.bank.reconcile"; +} + +/// +/// What the services of the treasury share (ADR 0038): the bank and money accounts, the accounts of the roles with the +/// fallback on the chart of the fiscal pack, the entries written by the treasury and the settlement of the items. +/// +internal static class TreasuryStore +{ + /// The day of the company clock. + public static DateOnly Today(TimeProvider clock) => DateOnly.FromDateTime(clock.GetLocalNow().DateTime); + + /// A bank account of the company, or the preferred one. + public static async Task BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken) + { + var banks = uow.Repository(); + if (id is { } bankId) + { + return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]); + } + + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + if (profile?.DefaultBankAccountId is { } defaultId && await banks.GetAsync(defaultId, cancellationToken).ConfigureAwait(false) is { } preferred) + { + return preferred; + } + + return await banks.FindAsync(Query.For().Where(b => b.IsDefault), cancellationToken).ConfigureAwait(false) + ?? await banks.FindAsync(Query.For().OrderBy(b => b.Id), cancellationToken).ConfigureAwait(false); + } + + /// + /// The account of a role: the line of the template when it has one, otherwise the account the fiscal pack gives + /// the role (companies created before a template got the line). + /// + public static async Task RoleAccountAsync( + IUnitOfWork uow, IReadOnlyList? lines, PostingRole role, ILedgerTemplate? pack, CancellationToken cancellationToken) + { + if (lines?.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId is { } fromTemplate) + { + return fromTemplate; + } + + return (await LedgerStore.AccountAsync(uow, pack?.AccountOf(role), cancellationToken).ConfigureAwait(false))?.Id; + } + + /// The account the money moves on: the ledger account of the bank, or cash for a method without bank. + public static async Task MoneyAccountAsync( + IUnitOfWork uow, BankAccount? bank, bool cash, IReadOnlyList? lines, ILedgerTemplate? pack, CancellationToken cancellationToken) + { + long? account = null; + if (cash) + { + account = await RoleAccountAsync(uow, lines, PostingRole.Cash, pack, cancellationToken).ConfigureAwait(false); + } + + account ??= (await LedgerStore.AccountAsync(uow, bank?.AccountCode, cancellationToken).ConfigureAwait(false))?.Id; + account ??= await RoleAccountAsync(uow, lines, PostingRole.Bank, pack, cancellationToken).ConfigureAwait(false); + return account ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.MoneyAccountMissing]); + } + + /// Writes a posted entry of the treasury from its lines. + public static async Task PostAsync( + IUnitOfWork uow, string templateCode, DateOnly date, string description, long? partyId, IReadOnlyList lines, bool demo, + CancellationToken cancellationToken) + { + var template = await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false); + var entry = new GlEntry + { + EntryDate = date, + JournalTemplateId = template?.Template.Id, + TemplateCode = template?.Template.Code ?? templateCode, + Description = LedgerStore.Trim(description, 200)!, + Status = GlEntryStatus.Posted, + Source = GlEntrySource.Treasury, + PartyId = partyId, + IsDemo = demo, + }; + return await LedgerStore.InsertAsync( + uow, entry, [.. lines.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, l.Description, l.Debit, l.Credit))], [], cancellationToken).ConfigureAwait(false); + } + + /// Takes back an entry of the treasury: deleted while posted, reversed when final. + public static async Task UndoEntryAsync(IUnitOfWork uow, long? entryId, DateOnly date, string? userName, CancellationToken cancellationToken) + { + if (entryId is not { } id || await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } entry) + { + return; + } + + if (entry.Status == GlEntryStatus.Final) + { + if (entry.ReversedById is null) + { + await JournalEntryService.ReverseAsync(uow, entry, date < entry.EntryDate ? entry.EntryDate : date, userName, cancellationToken).ConfigureAwait(false); + } + } + else + { + await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false); + } + } + + /// Moves what an item has settled and gives it its state. + public static void Settle(OpenItem item, decimal delta) + { + item.PaidAmount += delta; + item.Status = OpenItemStates.Of(item); + item.Closed = item.Status == OpenItemStatus.Closed; + } + + /// The names and codes of parties. + public static async Task> PartiesAsync(IUnitOfWork uow, IEnumerable ids, CancellationToken cancellationToken) + { + var set = ids.Distinct().ToList(); + if (set.Count == 0) + { + return []; + } + + var result = new Dictionary(); + foreach (var chunk in set.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var party in (await uow.Repository().ListAsync(Query.For().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items) + { + result[party.Id] = party; + } + } + + return result; + } + + /// The description of an item in entries and files. + public static string ItemText(OpenItem item) => + LedgerStore.Trim( + (item.DocumentNumber is null ? "Scadenza" : "Doc. " + item.DocumentNumber) + " del " + item.DocumentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + + (item.Installment > 1 ? " rata " + item.Installment.ToString(CultureInfo.InvariantCulture) : string.Empty), 200)!; +} diff --git a/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs b/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs index 418334d..6e0daf5 100644 --- a/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs +++ b/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs @@ -122,6 +122,9 @@ public static class LedgerErrors /// The account of the bank is missing. public const string BankAccountMissing = "ledger.bank.account-missing"; + /// An open item already collected, paid or in a remittance cannot go below what was settled or go away. + public const string OpenItemPaid = "ledger.open-item.paid"; + /// The final print of a VAT register must follow the last one. public const string PrintOrder = "vat.register.print-order"; } diff --git a/src/Khaemhat.Core/Accounting/Ledger.cs b/src/Khaemhat.Core/Accounting/Ledger.cs index 662276e..15c77c0 100644 --- a/src/Khaemhat.Core/Accounting/Ledger.cs +++ b/src/Khaemhat.Core/Accounting/Ledger.cs @@ -2,6 +2,7 @@ using Khaemhat.Core.Documents; using Khaemhat.Core.Entities; using Khaemhat.Core.Tables; using Khaemhat.Core.Tax; +using Khaemhat.Core.Treasury; namespace Khaemhat.Core.Accounting; @@ -179,6 +180,27 @@ public enum PostingRole /// VAT of split payment, due by the public customer. SplitPaymentVat = 15, + + /// Allowances received and rounding in favour (abbuoni attivi). + AllowanceIncome = 16, + + /// Bank fees and charges. + BankCharges = 17, + + /// Effects and direct debits presented for collection (effetti all'incasso). + BillsForCollection = 18, + + /// Advances of the bank on effects presented subject to collection (banche c/anticipi). + BankAdvances = 19, + + /// Exchange gains. + ExchangeGain = 20, + + /// Exchange losses. + ExchangeLoss = 21, + + /// Late payment interest charged to customers. + LateInterest = 22, } /// A line of a journal template (gl_journal_template_lines). @@ -239,6 +261,9 @@ public enum GlEntrySource /// The payment of an invoice with a withholding. Withholding = 6, + + /// A collection, a payment or a remittance of the schedule (M8). + Treasury = 7, } /// @@ -476,8 +501,38 @@ public sealed class OpenItem : Entity, IDemoMarkable /// Fully settled. public bool Closed { get; set; } + /// The state in the schedule (M8). + public OpenItemStatus Status { get; set; } + + /// Contested by the customer or with the supplier: left out of reminders and remittances. + public bool Disputed { get; set; } + + /// The bank account of the company that collects or pays it (from the document). + public long? BankAccountId { get; set; } + + /// The remittance it is in. + public long? RemittanceId { get; set; } + + /// The times it came back unpaid. + public int UnpaidCount { get; set; } + + /// The item it was split from: the bank fees of an unpaid effect. + public long? ParentId { get; set; } + + /// The level of the last reminder. + public int DunningLevel { get; set; } + + /// The day of the last reminder. + public DateOnly? LastDunningDate { get; set; } + + /// Notes (the reason of a dispute). + public string? Notes { get; set; } + /// public bool IsDemo { get; set; } + + /// What is left to collect or pay. + public decimal Residual => Amount - PaidAmount; } /// How often a recurring entry repeats. diff --git a/src/Khaemhat.Core/Tables/BaseTables.cs b/src/Khaemhat.Core/Tables/BaseTables.cs index e5ca6fa..ed0441a 100644 --- a/src/Khaemhat.Core/Tables/BaseTables.cs +++ b/src/Khaemhat.Core/Tables/BaseTables.cs @@ -207,6 +207,9 @@ public sealed class BankAccount : CodedEntity /// The ledger account (M7). public string? AccountCode { get; set; } + /// The SEPA creditor identifier for direct debits (M8). + public string? CreditorId { get; set; } + /// The account proposed on documents. public bool IsDefault { get; set; } } diff --git a/src/Khaemhat.Core/Treasury/BankFiles.cs b/src/Khaemhat.Core/Treasury/BankFiles.cs new file mode 100644 index 0000000..fe94fb3 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/BankFiles.cs @@ -0,0 +1,232 @@ +namespace Khaemhat.Core.Treasury; + +/// What a remittance (distinta) carries to the bank. +public enum RemittanceKind +{ + /// Italian bank receipts (ricevute bancarie), CBI fixed-width file. + Riba = 0, + + /// SEPA direct debit, core scheme (consumers and companies), ISO 20022 pain.008. + SddCore = 1, + + /// SEPA direct debit, business-to-business scheme, ISO 20022 pain.008. + SddB2b = 2, + + /// SEPA credit transfers to suppliers, ISO 20022 pain.001. + SepaCreditTransfer = 3, +} + +/// The sequence of a direct debit under its mandate. +public enum SddSequence +{ + /// The first debit of a recurrent mandate (FRST). + First = 0, + + /// A following debit (RCUR). + Recurrent = 1, + + /// The last debit (FNAL). + Final = 2, + + /// A one-off mandate (OOFF). + OneOff = 3, +} + +/// +/// The company in a bank file: the creditor of receipts and direct debits, the debtor of credit transfers. +/// +/// The company name. +/// The VAT number or tax code. +/// The street and number. +/// The postal code. +/// The town. +/// The province, two letters. +/// The country, ISO 3166 alpha-2. +/// The IBAN of the company account, compact. +/// The BIC of the company bank, if known. +/// The SIA code of the company (RiBa sender), five characters. +/// The CBI CUC code (initiating party of SEPA files in Italy). +/// The SEPA creditor identifier of direct debits, such as IT66ZZZA1B2C3D4E5F6G7H8. +public sealed record BankFileCompany( + string Name, + string? TaxCode, + string? Address, + string? PostalCode, + string? City, + string? Province, + string CountryCode, + string Iban, + string? Bic, + string? SiaCode, + string? CucCode, + string? CreditorId); + +/// One effect, debit or transfer of a remittance. +/// The progressive number in the file, from 1. +/// The code of the customer or supplier in the company (RiBa debtor code). +/// The customer (debtor) or supplier (creditor). +/// Its VAT number or tax code. +/// Its street and number. +/// Its postal code. +/// Its town. +/// Its province. +/// Its country. +/// Its IBAN, compact (for RiBa only ABI and CAB are used). +/// Its BIC, if known. +/// Its bank, for the RiBa description. +/// The amount, positive, in euro. +/// The due date (RiBa), the collection date (SDD) or the execution date (transfers). +/// The remittance information: the invoices paid, such as FT 2026/000388 del 31/08/2026. +/// The end-to-end identifier, unique in the company, at most 35 characters. +/// The direct debit mandate reference (UMR). +/// The date the mandate was signed. +/// The sequence of the direct debit. +public sealed record BankFileItem( + int Number, + string? CounterpartyCode, + string CounterpartyName, + string? CounterpartyTaxCode, + string? Address, + string? PostalCode, + string? City, + string? Province, + string CountryCode, + string? Iban, + string? Bic, + string? BankName, + decimal Amount, + DateOnly DueDate, + string Reference, + string EndToEndId, + string? MandateId = null, + DateOnly? MandateDate = null, + SddSequence Sequence = SddSequence.Recurrent); + +/// A remittance as the bank file writers read it. +/// What it carries. +/// The unique identifier of the file (also the RiBa support name), at most 35 characters. +/// When the file is created, local time. +/// The presentation date (RiBa), or the requested execution date of transfers. +/// The company and its account. +/// The effects, debits or transfers. +public sealed record BankFileRemittance( + RemittanceKind Kind, + string MessageId, + DateTime CreatedAt, + DateOnly ExecutionDate, + BankFileCompany Company, + IReadOnlyList Items) +{ + /// The total of the items. + public decimal Total => Items.Sum(i => i.Amount); +} + +/// A file written for the bank. +/// The proposed name. +/// The media type. +/// The bytes. +public sealed record BankFile(string FileName, string ContentType, byte[] Content); + +/// The formats of a bank statement. +public enum StatementFormat +{ + /// A CSV export of the home banking, with a layout. + Csv = 0, + + /// ISO 20022 camt.053 (bank to customer statement). + Camt053 = 1, + + /// The Italian CBI statement (rendicontazione movimenti, records RH, 61-64, EF). + Cbi = 2, +} + +/// A movement of a bank statement. +/// The booking date. +/// The value date. +/// The amount: positive for money in, negative for money out. +/// The description of the movement, on one line. +/// The bank reference (CRO, TRN, end-to-end id), if any. +/// The other party, if the file says it. +/// Its IBAN, if the file says it. +/// The bank transaction code (CBI causale, ISO domain/family), if any. +public sealed record StatementMovement( + DateOnly BookingDate, + DateOnly? ValueDate, + decimal Amount, + string Description, + string? Reference = null, + string? CounterpartyName = null, + string? CounterpartyIban = null, + string? BankCode = null); + +/// A bank statement read from a file. +/// The format. +/// The IBAN of the account, if the file says it. +/// The currency, if the file says it. +/// The first day. +/// The last day. +/// The opening balance, if the file says it. +/// The closing balance, if the file says it. +/// The movements, in the order of the file. +public sealed record StatementFile( + StatementFormat Format, + string? AccountIban, + string? Currency, + DateOnly? FromDate, + DateOnly? ToDate, + decimal? OpeningBalance, + decimal? ClosingBalance, + IReadOnlyList Movements); + +/// +/// The columns of a CSV statement. Column indexes are zero-based. The amount is either one signed column +/// () or two columns of money in and money out (, +/// , both read as positive numbers). +/// +/// The field separator. +/// The rows to skip before the movements. +/// The booking date. +/// The value date. +/// The description. +/// A signed amount. +/// Money in. +/// Money out. +/// The bank reference. +/// The date format, such as dd/MM/yyyy. +/// Numbers are written 1.234,56 (otherwise 1,234.56). +public sealed record CsvStatementLayout( + char Separator, + int HeaderRows, + int DateColumn, + int? ValueDateColumn, + int DescriptionColumn, + int? AmountColumn, + int? CreditColumn, + int? DebitColumn, + int? ReferenceColumn, + string DateFormat = "dd/MM/yyyy", + bool DecimalComma = true); + +/// A bank file that cannot be read or written. +public sealed class BankFileException : Exception +{ + /// Creates the exception. + public BankFileException() + { + } + + /// Creates the exception. + /// What is wrong, with the line or element (logged; the screens show a generic text). + public BankFileException(string message) + : base(message) + { + } + + /// Creates the exception. + /// What is wrong. + /// The cause. + public BankFileException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/src/Khaemhat.Core/Treasury/Camt053Reader.cs b/src/Khaemhat.Core/Treasury/Camt053Reader.cs new file mode 100644 index 0000000..11f4bd7 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/Camt053Reader.cs @@ -0,0 +1,270 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using System.Xml.Linq; + +namespace Khaemhat.Core.Treasury; + +/// +/// Reads ISO 20022 bank to customer statements (camt.053.001.xx, any version): the elements are found by their +/// local names, so the version of the namespace does not matter. +/// +/// +/// +/// account: Stmt/Acct/Id/IBAN and Stmt/Acct/Ccy (or the currency of the first amount); +/// balances: OPBD (or PRCD) as opening, CLBD as closing, negative when CdtDbtInd is DBIT; +/// period: FrToDt, otherwise the first and last booking dates; +/// each Ntry: amount signed by CdtDbtInd, BookgDt, ValDt, AcctSvcrRef or the +/// end-to-end id as reference, BkTxCd as bank code (Domn/Fmly/SubFmly or the proprietary code), the +/// description from AddtlNtryInf or the unstructured remittance information, the counterparty from +/// RltdPties (the debtor of a credit, the creditor of a debit); +/// entries with status PDNG or INFO are not booked and are skipped. +/// +/// When a file has several Stmt of the same account their entries are read in order; balances come from the first +/// opening and the last closing. +/// +public static class Camt053Reader +{ + /// Whether the start of a file looks like a camt.053 statement. + /// The first bytes of the file. + /// when the head is XML naming camt.053 or BkToCstmrStmt. + public static bool Recognizes(ReadOnlySpan head) + { + var text = Encoding.UTF8.GetString(head); + return text.TrimStart('', ' ', '\t', '\r', '\n').StartsWith('<') + && (text.Contains("camt.053", StringComparison.Ordinal) || text.Contains("BkToCstmrStmt", StringComparison.Ordinal)); + } + + /// Reads a statement. + /// The file. + /// The statement. + /// The file is not a readable camt.053 statement. + public static StatementFile Read(Stream content) + { + ArgumentNullException.ThrowIfNull(content); + XDocument document; + try + { + var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreComments = true }; + using var reader = XmlReader.Create(content, settings); + document = XDocument.Load(reader); + } + catch (XmlException ex) + { + throw new BankFileException($"The statement is not well-formed XML (line {ex.LineNumber}).", ex); + } + + var root = document.Root; + var statement = root is null ? null : Child(root, "BkToCstmrStmt"); + var statements = statement is null ? [] : Children(statement, "Stmt").ToList(); + if (statements.Count == 0) + { + throw new BankFileException("The file has no camt.053 statement (Document/BkToCstmrStmt/Stmt)."); + } + + string? iban = null; + string? currency = null; + decimal? opening = null; + decimal? previousClosing = null; + decimal? closing = null; + DateOnly? from = null; + DateOnly? to = null; + var movements = new List(); + foreach (var stmt in statements) + { + var account = Child(stmt, "Acct"); + var accountIban = Value(Path(account, "Id", "IBAN"))?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + if (iban is not null && accountIban is not null && !string.Equals(iban, accountIban, StringComparison.Ordinal)) + { + throw new BankFileException($"The file has statements of two accounts ({iban}, {accountIban})."); + } + + iban ??= accountIban; + currency ??= Value(Child(account, "Ccy")); + foreach (var balance in Children(stmt, "Bal")) + { + var code = Value(Path(balance, "Tp", "CdOrPrtry", "Cd")) ?? Value(Path(balance, "Tp", "CdOrPrtry", "Prtry")); + var amountElement = Child(balance, "Amt"); + currency ??= amountElement?.Attribute("Ccy")?.Value; + var amount = Signed(amountElement, balance, "balance"); + switch (code) + { + case "OPBD": + opening ??= amount; + break; + case "PRCD": + previousClosing ??= amount; + break; + case "CLBD": + closing = amount; + break; + default: + break; + } + } + + var period = Child(stmt, "FrToDt"); + if (period is not null) + { + var start = DateOf(Child(period, "FrDtTm")); + var end = DateOf(Child(period, "ToDtTm")); + from = Min(from, start); + to = Max(to, end); + } + + var number = 0; + foreach (var entry in Children(stmt, "Ntry")) + { + number++; + var status = Value(Child(entry, "Sts")) ?? Value(Path(entry, "Sts", "Cd")); + if (status is "PDNG" or "INFO") + { + continue; + } + + movements.Add(Entry(entry, number)); + } + } + + if (movements.Count > 0) + { + from ??= movements.Min(m => m.BookingDate); + to ??= movements.Max(m => m.BookingDate); + } + + return new StatementFile(StatementFormat.Camt053, iban, currency, from, to, opening ?? previousClosing, closing, movements); + } + + private static StatementMovement Entry(XElement entry, int number) + { + var where = string.Create(CultureInfo.InvariantCulture, $"entry {number}"); + var amount = Signed(Child(entry, "Amt"), entry, where); + var booking = DateOf(Child(entry, "BookgDt")) ?? DateOf(Child(entry, "ValDt")) + ?? throw new BankFileException($"The {where} has no booking date."); + var value = DateOf(Child(entry, "ValDt")); + var transactions = Path(entry, "NtryDtls")?.Elements().Where(e => e.Name.LocalName == "TxDtls").ToList() ?? []; + + var reference = Value(Child(entry, "AcctSvcrRef")); + if (reference is null) + { + reference = transactions + .Select(t => Value(Path(t, "Refs", "EndToEndId")) ?? Value(Path(t, "Refs", "AcctSvcrRef"))) + .FirstOrDefault(r => r is not null && r != "NOTPROVIDED"); + } + + var description = Value(Child(entry, "AddtlNtryInf")); + if (description is null) + { + var lines = transactions + .SelectMany(t => Children(Child(t, "RmtInf"), "Ustrd")) + .Select(Value) + .OfType() + .ToList(); + description = lines.Count > 0 ? string.Join(" ", lines) : null; + } + + description ??= transactions.Select(t => Value(Child(t, "AddtlTxInf"))).FirstOrDefault(d => d is not null); + + var codes = Child(entry, "BkTxCd"); + string? bankCode = null; + var domain = Child(codes, "Domn"); + if (domain is not null) + { + bankCode = string.Join( + "/", + new[] { Value(Child(domain, "Cd")), Value(Path(domain, "Fmly", "Cd")), Value(Path(domain, "Fmly", "SubFmlyCd")) }.OfType()); + } + + if (string.IsNullOrEmpty(bankCode)) + { + bankCode = Value(Path(codes, "Prtry", "Cd")); + } + + // The other party: who paid a credit, who was paid by a debit. + var side = amount >= 0m ? "Dbtr" : "Cdtr"; + string? counterparty = null; + string? counterpartyIban = null; + foreach (var transaction in transactions) + { + var parties = Child(transaction, "RltdPties"); + var party = Child(parties, side); + counterparty ??= Value(Child(party, "Nm")) ?? Value(Path(party, "Pty", "Nm")); + counterpartyIban ??= Value(Path(parties, side + "Acct", "Id", "IBAN"))?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + } + + return new StatementMovement( + booking, + value, + amount, + OneLine(description), + reference, + counterparty is null ? null : OneLine(counterparty), + counterpartyIban, + string.IsNullOrEmpty(bankCode) ? null : bankCode); + } + + private static decimal Signed(XElement? amountElement, XElement owner, string where) + { + var text = Value(amountElement); + if (text is null || !decimal.TryParse(text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var amount)) + { + throw new BankFileException($"The {where} has no readable amount."); + } + + return Value(Child(owner, "CdtDbtInd")) == "DBIT" ? -amount : amount; + } + + private static DateOnly? DateOf(XElement? element) + { + if (element is null) + { + return null; + } + + var text = Value(Child(element, "Dt")) ?? Value(Child(element, "DtTm")) ?? Value(element); + if (text is null) + { + return null; + } + + if (DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + { + return date; + } + + // Date and time: keep the local date as written, whatever the offset. + return text.Length >= 10 && DateOnly.TryParseExact(text[..10], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) + ? day + : null; + } + + private static DateOnly? Min(DateOnly? a, DateOnly? b) => a is null ? b : b is null ? a : a < b ? a : b; + + private static DateOnly? Max(DateOnly? a, DateOnly? b) => a is null ? b : b is null ? a : a > b ? a : b; + + private static XElement? Child(XElement? parent, string localName) => + parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName); + + private static IEnumerable Children(XElement? parent, string localName) => + parent?.Elements().Where(e => e.Name.LocalName == localName) ?? []; + + private static XElement? Path(XElement? parent, params string[] localNames) + { + var current = parent; + foreach (var name in localNames) + { + current = Child(current, name); + } + + return current; + } + + private static string? Value(XElement? element) + { + var text = element?.Value.Trim(); + return string.IsNullOrEmpty(text) ? null : text; + } + + private static string OneLine(string? text) => + text is null ? string.Empty : string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); +} diff --git a/src/Khaemhat.Core/Treasury/CsvStatementReader.cs b/src/Khaemhat.Core/Treasury/CsvStatementReader.cs new file mode 100644 index 0000000..2767c21 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/CsvStatementReader.cs @@ -0,0 +1,400 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Core.Treasury; + +/// +/// Reads the CSV exports of home banking with a , and guesses the layout from the header +/// row of the common Italian and English exports. +/// +/// +/// +/// The file is UTF-8 (with or without BOM); when it is not valid UTF-8 it is read as Windows-1252. +/// Fields may be quoted, with doubled quotes inside; quoted fields may span lines. +/// Empty rows and the are skipped; so are rows without a date and +/// without an amount (titles, totals without figures). A row with a date and no amount, or an amount and no date, is an +/// error that names the row. +/// Numbers may carry a leading or trailing sign and the currency (€, EUR); the debit column is read as +/// money out whatever its sign. +/// +/// +public static class CsvStatementReader +{ + // The common date formats tried when the layout format does not fit (never month-first, which is ambiguous). + private static readonly string[] FallbackDateFormats = ["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "yyyy-MM-dd", "dd-MM-yyyy", "dd.MM.yyyy"]; + + // Windows-1252 differs from Latin-1 in 0x80-0x9F; the undefined positions stay as they are. + private static readonly char[] Windows1252High = + [ + '€', '\u0081', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u008D', 'Ž', '\u008F', + '\u0090', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u009D', 'ž', 'Ÿ', + ]; + + private static readonly string[] BookingDateNames = ["data contabile", "booking date", "data operazione", "data registrazione", "data", "date"]; + private static readonly string[] ValueDateNames = ["data valuta", "valuta", "value date"]; + private static readonly string[] DescriptionNames = ["descrizione operazione", "descrizione", "description", "causale", "dettagli", "details"]; + private static readonly string[] AmountNames = ["importo", "amount"]; + private static readonly string[] CreditNames = ["entrate", "avere", "accrediti", "accredito", "importo avere", "credit", "credits"]; + private static readonly string[] DebitNames = ["uscite", "dare", "addebiti", "addebito", "importo dare", "debit", "debits"]; + private static readonly string[] ReferenceNames = ["riferimento", "cro", "reference", "riferimento banca", "cro/trn"]; + private static readonly string[] EnglishNames = ["booking date", "value date", "description", "details", "amount", "credit", "credits", "debit", "debits", "reference", "date"]; + + /// Reads a statement. + /// The file. + /// Its columns. + /// The statement: no account, currency or balances, the period from the booking dates. + /// A row cannot be read; the message names it. + public static StatementFile Read(Stream content, CsvStatementLayout layout) + { + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(layout); + if (layout.AmountColumn is null && layout.CreditColumn is null && layout.DebitColumn is null) + { + throw new BankFileException("The CSV layout has no amount column."); + } + + var movements = new List(); + var index = 0; + foreach (var (row, fields) in Records(Decode(content), layout.Separator)) + { + if (index++ < layout.HeaderRows || fields.All(string.IsNullOrWhiteSpace)) + { + continue; + } + + var date = ParseDate(Field(fields, layout.DateColumn), layout.DateFormat); + var amount = Amount(fields, layout, row); + if (date is null) + { + if (amount is null) + { + continue; + } + + throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: the date '{Field(fields, layout.DateColumn)}' is not in the format {layout.DateFormat}.")); + } + + if (amount is null) + { + throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: there is no amount.")); + } + + var valueDate = layout.ValueDateColumn is { } valueColumn ? ParseDate(Field(fields, valueColumn), layout.DateFormat) : null; + var reference = layout.ReferenceColumn is { } referenceColumn ? OneLine(Field(fields, referenceColumn)) : string.Empty; + movements.Add(new StatementMovement( + date.Value, + valueDate, + amount.Value, + OneLine(Field(fields, layout.DescriptionColumn)), + reference.Length == 0 ? null : reference)); + } + + return new StatementFile( + StatementFormat.Csv, + null, + null, + movements.Count == 0 ? null : movements.Min(m => m.BookingDate), + movements.Count == 0 ? null : movements.Max(m => m.BookingDate), + null, + null, + movements); + } + + /// + /// Guesses the layout from the header row: the separator (;, tab or ,) and the columns from their + /// Italian or English names, without case and accents. Italian headers mean decimal comma, English ones decimal point; + /// the date format is dd/MM/yyyy (the reader also tries the other common day-first formats). + /// + /// The first row of the file. + /// The layout with one header row, or when a date, a description or an amount column is missing. + public static CsvStatementLayout? Detect(string headerLine) + { + if (string.IsNullOrWhiteSpace(headerLine)) + { + return null; + } + + var line = headerLine.TrimStart('').TrimEnd('\r', '\n'); + var separator = GuessSeparator(line); + var names = Records(line, separator).FirstOrDefault().Fields?.Select(NormalizeName).ToList() ?? []; + + var date = Find(names, BookingDateNames); + var description = Find(names, DescriptionNames); + var amount = Find(names, AmountNames); + var credit = Find(names, CreditNames); + var debit = Find(names, DebitNames); + if (date is null || description is null || (amount is null && credit is null && debit is null)) + { + return null; + } + + var valueDate = Find(names, ValueDateNames, except: date); + var reference = Find(names, ReferenceNames); + var english = EnglishNames.Contains(names[date.Value], StringComparer.Ordinal); + return new CsvStatementLayout( + separator, + HeaderRows: 1, + date.Value, + valueDate, + description.Value, + amount, + amount is null ? credit : null, + amount is null ? debit : null, + reference, + "dd/MM/yyyy", + DecimalComma: !english); + } + + /// Reads a number as the bank writes it. + /// The text, such as -1.234,56, 1.234,56-, +12,00 €. + /// Whether the decimal separator is the comma. + /// The number, or for an empty field. + /// The text is not a number. + public static decimal? ParseAmount(string? text, bool decimalComma) + { + var value = (text ?? string.Empty) + .Replace("EUR", string.Empty, StringComparison.OrdinalIgnoreCase) + .Replace("€", string.Empty, StringComparison.Ordinal) + .Replace(" ", string.Empty, StringComparison.Ordinal) + .Replace(" ", string.Empty, StringComparison.Ordinal) + .Replace("'", string.Empty, StringComparison.Ordinal); + if (value.Length == 0) + { + return null; + } + + var negative = false; + if (value.StartsWith('(') && value.EndsWith(')')) + { + negative = true; + value = value[1..^1]; + } + + if (value.Length > 0 && value[0] is '-' or '+') + { + negative ^= value[0] == '-'; + value = value[1..]; + } + else if (value.Length > 0 && value[^1] is '-' or '+') + { + negative ^= value[^1] == '-'; + value = value[..^1]; + } + + value = decimalComma + ? value.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') + : value.Replace(",", string.Empty, StringComparison.Ordinal); + if (value.Length == 0 || !value.All(c => char.IsAsciiDigit(c) || c == '.') + || !decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var number)) + { + throw new FormatException($"'{text}' is not an amount."); + } + + return negative ? -number : number; + } + + private static decimal? Amount(string[] fields, CsvStatementLayout layout, int row) + { + try + { + if (layout.AmountColumn is { } amountColumn) + { + return ParseAmount(Field(fields, amountColumn), layout.DecimalComma); + } + + var credit = layout.CreditColumn is { } creditColumn ? ParseAmount(Field(fields, creditColumn), layout.DecimalComma) : null; + var debit = layout.DebitColumn is { } debitColumn ? ParseAmount(Field(fields, debitColumn), layout.DecimalComma) : null; + return credit is null && debit is null ? null : Math.Abs(credit ?? 0m) - Math.Abs(debit ?? 0m); + } + catch (FormatException ex) + { + throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: {ex.Message}"), ex); + } + } + + private static DateOnly? ParseDate(string text, string format) + { + var value = text.Trim(); + if (value.Length == 0) + { + return null; + } + + string[] candidates = value.Contains(' ', StringComparison.Ordinal) ? [value, value[..value.IndexOf(' ', StringComparison.Ordinal)]] : [value]; + foreach (var candidate in candidates) + { + if (DateOnly.TryParseExact(candidate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) + || DateOnly.TryParseExact(candidate, FallbackDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) + { + return date; + } + } + + return null; + } + + private static string Field(string[] fields, int column) => column >= 0 && column < fields.Length ? fields[column] : string.Empty; + + private static string Decode(Stream content) + { + using var buffer = new MemoryStream(); + content.CopyTo(buffer); + var bytes = buffer.ToArray(); + var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0; + try + { + return new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes, start, bytes.Length - start); + } + catch (DecoderFallbackException) + { + var text = Encoding.Latin1.GetString(bytes).ToCharArray(); + for (var i = 0; i < text.Length; i++) + { + if (text[i] is >= '\u0080' and <= '\u009F') + { + text[i] = Windows1252High[text[i] - 0x80]; + } + } + + return new string(text); + } + } + + // The records of the text with the row number where each starts (from 1); quoted fields may contain separators, + // doubled quotes and line breaks. + private static IEnumerable<(int Row, string[] Fields)> Records(string text, char separator) + { + var fields = new List(); + var field = new StringBuilder(); + var quoted = false; + var line = 1; + var start = 1; + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + if (quoted) + { + if (c == '"') + { + if (i + 1 < text.Length && text[i + 1] == '"') + { + field.Append('"'); + i++; + } + else + { + quoted = false; + } + } + else + { + if (c == '\n') + { + line++; + } + + field.Append(c); + } + + continue; + } + + if (c == '"' && field.ToString().Trim().Length == 0) + { + field.Clear(); + quoted = true; + } + else if (c == separator) + { + fields.Add(field.ToString()); + field.Clear(); + } + else if (c is '\r' or '\n') + { + if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n') + { + i++; + } + + fields.Add(field.ToString()); + field.Clear(); + yield return (start, fields.ToArray()); + fields.Clear(); + line++; + start = line; + } + else + { + field.Append(c); + } + } + + if (field.Length > 0 || fields.Count > 0) + { + fields.Add(field.ToString()); + yield return (start, fields.ToArray()); + } + } + + private static char GuessSeparator(string line) + { + int semicolons = 0, tabs = 0, commas = 0; + var quoted = false; + foreach (var c in line) + { + if (c == '"') + { + quoted = !quoted; + } + else if (!quoted) + { + semicolons += c == ';' ? 1 : 0; + tabs += c == '\t' ? 1 : 0; + commas += c == ',' ? 1 : 0; + } + } + + return tabs > 0 && tabs >= semicolons && tabs >= commas ? '\t' : semicolons > 0 && semicolons >= commas ? ';' : ','; + } + + private static int? Find(List names, string[] candidates, int? except = null) + { + foreach (var candidate in candidates) + { + var index = names.FindIndex(n => string.Equals(n, candidate, StringComparison.Ordinal)); + if (index >= 0 && index != except) + { + return index; + } + } + + return null; + } + + // Lower case, no accents, no currency or parenthesised notes, single spaces: "Importo (EUR)" is "importo". + private static string NormalizeName(string name) + { + var builder = new StringBuilder(name.Length); + var depth = 0; + foreach (var c in name.Normalize(NormalizationForm.FormD)) + { + if (c == '(') + { + depth++; + } + else if (c == ')') + { + depth = Math.Max(0, depth - 1); + } + else if (depth == 0 && CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) + { + builder.Append(char.IsLetterOrDigit(c) || c == '/' ? char.ToLowerInvariant(c) : ' '); + } + } + + var words = builder.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries).Where(w => w is not ("eur" or "euro")).ToArray(); + return string.Join(" ", words); + } + + private static string OneLine(string text) => string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); +} diff --git a/src/Khaemhat.Core/Treasury/SepaXmlWriter.cs b/src/Khaemhat.Core/Treasury/SepaXmlWriter.cs new file mode 100644 index 0000000..db8be94 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/SepaXmlWriter.cs @@ -0,0 +1,515 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using Khaemhat.Core.Validation; + +namespace Khaemhat.Core.Treasury; + +/// +/// Writes SEPA remittances as ISO 20022 customer initiation messages, within the subset of the EPC rulebooks (2023): +/// credit transfers to suppliers as pain.001.001.09 and direct debits as pain.008.001.08. +/// +/// +/// +/// Every text is reduced to the SEPA Latin character set (a-z A-Z 0-9 / - ? : ( ) . , ' + and space): accented +/// letters lose the accent, anything else becomes a space, and texts are cut to the maxima of the schema (names 70, +/// remittance information 140, identifiers 35). Amounts have two decimals and a dot, the currency is always euro. +/// +/// +/// When the company has a CBI CUC code it goes in GrpHdr/InitgPty/Id/OrgId/Othr with issuer CBI, as +/// Italian banks require. A bank without a known BIC is written as FinInstnId/Othr/Id NOTPROVIDED. +/// +/// +public static class SepaXmlWriter +{ + /// The namespace of credit transfer initiations. + public const string CreditTransferNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"; + + /// The namespace of direct debit initiations. + public const string DirectDebitNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.008.001.08"; + + /// The media type of the files. + public const string ContentType = "application/xml"; + + private const int NameLength = 70; + private const int RemittanceLength = 140; + private const int IdLength = 35; + private const int AddressLineLength = 70; + private const int TownLength = 35; + private const int PostalCodeLength = 16; + private const decimal MaximumAmount = 999_999_999.99m; + private const string NotProvided = "NOTPROVIDED"; + + /// Writes a remittance of SEPA credit transfers (pain.001.001.09). + /// The remittance, of kind . + /// The file SCT_<MsgId>.xml. + /// The remittance cannot be written as SEPA credit transfers. + public static BankFile CreditTransfer(BankFileRemittance remittance) + { + ArgumentNullException.ThrowIfNull(remittance); + if (remittance.Kind != RemittanceKind.SepaCreditTransfer) + { + throw new BankFileException($"A remittance of kind {remittance.Kind} is not a SEPA credit transfer."); + } + + var header = Check(remittance); + var items = remittance.Items.Select((item, index) => CheckItem(item, index, debit: false)).ToList(); + var bytes = Write(CreditTransferNamespace, "CstmrCdtTrfInitn", xml => + { + GroupHeader(xml, header, items); + xml.WriteStartElement("PmtInf"); + xml.WriteElementString("PmtInfId", PaymentInformationId(header.MessageId, 1)); + xml.WriteElementString("PmtMtd", "TRF"); + xml.WriteElementString("BtchBookg", "true"); + xml.WriteElementString("NbOfTxs", Count(items.Count)); + xml.WriteElementString("CtrlSum", Amount(items.Sum(i => i.Amount))); + xml.WriteStartElement("PmtTpInf"); + xml.WriteStartElement("SvcLvl"); + xml.WriteElementString("Cd", "SEPA"); + xml.WriteEndElement(); + xml.WriteEndElement(); + xml.WriteStartElement("ReqdExctnDt"); + xml.WriteElementString("Dt", Date(remittance.ExecutionDate)); + xml.WriteEndElement(); + Party(xml, "Dbtr", header.Name, header.Country, header.Company.Address, header.Company.PostalCode, header.Company.City); + Account(xml, "DbtrAcct", header.Iban); + Agent(xml, "DbtrAgt", header.Bic); + xml.WriteElementString("ChrgBr", "SLEV"); + foreach (var item in items) + { + xml.WriteStartElement("CdtTrfTxInf"); + xml.WriteStartElement("PmtId"); + xml.WriteElementString("EndToEndId", item.EndToEndId); + xml.WriteEndElement(); + xml.WriteStartElement("Amt"); + InstructedAmount(xml, item.Amount); + xml.WriteEndElement(); + if (item.Bic is not null) + { + Agent(xml, "CdtrAgt", item.Bic); + } + + Party(xml, "Cdtr", item.Name, item.Country, item.Source.Address, item.Source.PostalCode, item.Source.City); + Account(xml, "CdtrAcct", item.Iban); + Remittance(xml, item.Reference); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + }); + + return new BankFile($"SCT_{FileSafe(header.MessageId)}.xml", ContentType, bytes); + } + + /// + /// Writes a remittance of SEPA direct debits (pain.008.001.08), with one payment information block for each + /// sequence and collection date. + /// + /// The remittance, of kind or . + /// The file SDD_<MsgId>.xml. + /// The remittance cannot be written as SEPA direct debits. + public static BankFile DirectDebit(BankFileRemittance remittance) + { + ArgumentNullException.ThrowIfNull(remittance); + if (remittance.Kind is not (RemittanceKind.SddCore or RemittanceKind.SddB2b)) + { + throw new BankFileException($"A remittance of kind {remittance.Kind} is not a SEPA direct debit."); + } + + var header = Check(remittance); + var creditorId = Text(remittance.Company.CreditorId, IdLength).Replace(" ", string.Empty, StringComparison.Ordinal); + if (creditorId.Length == 0) + { + throw new BankFileException("The company has no SEPA creditor identifier."); + } + + var items = remittance.Items.Select((item, index) => CheckItem(item, index, debit: true)).ToList(); + var groups = items + .GroupBy(i => (i.Source.DueDate, i.Source.Sequence)) + .OrderBy(g => g.Key.DueDate) + .ThenBy(g => g.Key.Sequence) + .ToList(); + var scheme = remittance.Kind == RemittanceKind.SddB2b ? "B2B" : "CORE"; + var bytes = Write(DirectDebitNamespace, "CstmrDrctDbtInitn", xml => + { + GroupHeader(xml, header, items); + var number = 0; + foreach (var group in groups) + { + var debits = group.ToList(); + xml.WriteStartElement("PmtInf"); + xml.WriteElementString("PmtInfId", PaymentInformationId(header.MessageId, ++number)); + xml.WriteElementString("PmtMtd", "DD"); + xml.WriteElementString("BtchBookg", "true"); + xml.WriteElementString("NbOfTxs", Count(debits.Count)); + xml.WriteElementString("CtrlSum", Amount(debits.Sum(i => i.Amount))); + xml.WriteStartElement("PmtTpInf"); + xml.WriteStartElement("SvcLvl"); + xml.WriteElementString("Cd", "SEPA"); + xml.WriteEndElement(); + xml.WriteStartElement("LclInstrm"); + xml.WriteElementString("Cd", scheme); + xml.WriteEndElement(); + xml.WriteElementString("SeqTp", SequenceCode(group.Key.Sequence)); + xml.WriteEndElement(); + xml.WriteElementString("ReqdColltnDt", Date(group.Key.DueDate)); + Party(xml, "Cdtr", header.Name, header.Country, header.Company.Address, header.Company.PostalCode, header.Company.City); + Account(xml, "CdtrAcct", header.Iban); + Agent(xml, "CdtrAgt", header.Bic); + xml.WriteElementString("ChrgBr", "SLEV"); + xml.WriteStartElement("CdtrSchmeId"); + xml.WriteStartElement("Id"); + xml.WriteStartElement("PrvtId"); + xml.WriteStartElement("Othr"); + xml.WriteElementString("Id", creditorId); + xml.WriteStartElement("SchmeNm"); + xml.WriteElementString("Prtry", "SEPA"); + xml.WriteEndElement(); + xml.WriteEndElement(); + xml.WriteEndElement(); + xml.WriteEndElement(); + xml.WriteEndElement(); + foreach (var item in debits) + { + xml.WriteStartElement("DrctDbtTxInf"); + xml.WriteStartElement("PmtId"); + xml.WriteElementString("EndToEndId", item.EndToEndId); + xml.WriteEndElement(); + InstructedAmount(xml, item.Amount); + xml.WriteStartElement("DrctDbtTx"); + xml.WriteStartElement("MndtRltdInf"); + xml.WriteElementString("MndtId", item.MandateId); + xml.WriteElementString("DtOfSgntr", Date(item.Source.MandateDate!.Value)); + xml.WriteEndElement(); + xml.WriteEndElement(); + Agent(xml, "DbtrAgt", item.Bic); + Party(xml, "Dbtr", item.Name, item.Country, item.Source.Address, item.Source.PostalCode, item.Source.City); + Account(xml, "DbtrAcct", item.Iban); + Remittance(xml, item.Reference); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + } + }); + + return new BankFile($"SDD_{FileSafe(header.MessageId)}.xml", ContentType, bytes); + } + + /// + /// A text in the SEPA Latin character set: accents removed, other characters replaced by spaces, spaces collapsed, + /// cut to a length. + /// + /// The text. + /// The maximum length. + /// The text, possibly empty. + public static string Text(string? value, int maxLength) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLength); + if (string.IsNullOrWhiteSpace(value)) + { + return string.Empty; + } + + var builder = new StringBuilder(value.Length); + foreach (var c in value.Normalize(NormalizationForm.FormD)) + { + if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark) + { + continue; + } + + var allowed = char.IsAsciiLetterOrDigit(c) || c is '/' or '-' or '?' or ':' or '(' or ')' or '.' or ',' or '\'' or '+' or ' '; + var next = allowed ? c : ' '; + if (next == ' ' && (builder.Length == 0 || builder[^1] == ' ')) + { + continue; + } + + builder.Append(next); + } + + var text = builder.ToString().Trim(); + return text.Length <= maxLength ? text : text[..maxLength].TrimEnd(); + } + + private static Header Check(BankFileRemittance remittance) + { + var company = remittance.Company ?? throw new BankFileException("The remittance has no company."); + if (remittance.Items is null || remittance.Items.Count == 0) + { + throw new BankFileException("The remittance has no items."); + } + + var messageId = Text(remittance.MessageId, IdLength); + if (messageId.Length == 0) + { + throw new BankFileException("The remittance has no message identifier."); + } + + var iban = IbanValidator.Normalize(company.Iban); + if (iban.Length == 0) + { + throw new BankFileException("The company account has no IBAN."); + } + + if (!IbanValidator.IsValid(iban)) + { + throw new BankFileException($"The IBAN of the company account {iban} is not valid."); + } + + var name = Text(company.Name, NameLength); + if (name.Length == 0) + { + throw new BankFileException("The company has no name."); + } + + return new Header(company, messageId, name, iban, Bic(company.Bic, "the company"), Country(company.CountryCode, iban), remittance.CreatedAt); + } + + private static Item CheckItem(BankFileItem item, int index, bool debit) + { + var where = $"item {index + 1}"; + if (item is null) + { + throw new BankFileException($"The {where} is missing."); + } + + var amount = Math.Round(item.Amount, 2, MidpointRounding.AwayFromZero); + if (amount <= 0m) + { + throw new BankFileException($"The amount of {where} must be positive: {item.Amount.ToString(CultureInfo.InvariantCulture)}."); + } + + if (amount > MaximumAmount) + { + throw new BankFileException($"The amount of {where} is over the SEPA maximum."); + } + + var iban = IbanValidator.Normalize(item.Iban); + if (iban.Length == 0) + { + throw new BankFileException($"The counterparty of {where} has no IBAN."); + } + + if (!IbanValidator.IsValid(iban)) + { + throw new BankFileException($"The IBAN {iban} of {where} is not valid."); + } + + var name = Text(item.CounterpartyName, NameLength); + if (name.Length == 0) + { + throw new BankFileException($"The counterparty of {where} has no name."); + } + + var endToEnd = Text(item.EndToEndId, IdLength); + var mandate = string.Empty; + if (debit) + { + mandate = Text(item.MandateId, IdLength); + if (mandate.Length == 0) + { + throw new BankFileException($"The direct debit of {where} has no mandate reference."); + } + + if (item.MandateDate is null) + { + throw new BankFileException($"The direct debit of {where} has no mandate signature date."); + } + } + + return new Item( + item, + name, + iban, + Bic(item.Bic, where), + Country(item.CountryCode, iban), + amount, + endToEnd.Length == 0 ? NotProvided : endToEnd, + Text(item.Reference, RemittanceLength), + mandate); + } + + private static string? Bic(string? value, string where) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + var bic = string.Concat(value.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant(); + var valid = bic.Length is 8 or 11 + && bic.All(char.IsAsciiLetterOrDigit) + && char.IsAsciiLetterUpper(bic[4]) && char.IsAsciiLetterUpper(bic[5]); + return valid ? bic : throw new BankFileException($"The BIC {bic} of {where} is not valid."); + } + + private static string Country(string? value, string iban) + { + var country = (value ?? string.Empty).Trim().ToUpperInvariant(); + return country.Length == 2 && country.All(char.IsAsciiLetterUpper) ? country : iban[..2]; + } + + private static byte[] Write(string ns, string root, Action body) + { + var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = true }; + using var buffer = new MemoryStream(); + using (var xml = XmlWriter.Create(buffer, settings)) + { + xml.WriteStartDocument(); + xml.WriteStartElement("Document", ns); + xml.WriteStartElement(root); + body(xml); + xml.WriteEndElement(); + xml.WriteEndElement(); + xml.WriteEndDocument(); + } + + return buffer.ToArray(); + } + + private static void GroupHeader(XmlWriter xml, Header header, List items) + { + xml.WriteStartElement("GrpHdr"); + xml.WriteElementString("MsgId", header.MessageId); + xml.WriteElementString("CreDtTm", header.CreatedAt.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture)); + xml.WriteElementString("NbOfTxs", Count(items.Count)); + xml.WriteElementString("CtrlSum", Amount(items.Sum(i => i.Amount))); + xml.WriteStartElement("InitgPty"); + xml.WriteElementString("Nm", header.Name); + var cuc = Text(header.Company.CucCode, IdLength).Replace(" ", string.Empty, StringComparison.Ordinal); + if (cuc.Length > 0) + { + xml.WriteStartElement("Id"); + xml.WriteStartElement("OrgId"); + xml.WriteStartElement("Othr"); + xml.WriteElementString("Id", cuc); + xml.WriteElementString("Issr", "CBI"); + xml.WriteEndElement(); + xml.WriteEndElement(); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + xml.WriteEndElement(); + } + + private static void Party(XmlWriter xml, string element, string name, string country, string? address, string? postalCode, string? city) + { + xml.WriteStartElement(element); + xml.WriteElementString("Nm", name); + xml.WriteStartElement("PstlAdr"); + var postal = Text(postalCode, PostalCodeLength); + var town = Text(city, TownLength); + if (postal.Length > 0 && town.Length > 0) + { + xml.WriteElementString("PstCd", postal); + } + + if (town.Length > 0) + { + xml.WriteElementString("TwnNm", town); + } + + xml.WriteElementString("Ctry", country); + var line = Text(address, AddressLineLength); + if (line.Length > 0) + { + xml.WriteElementString("AdrLine", line); + } + + xml.WriteEndElement(); + xml.WriteEndElement(); + } + + private static void Account(XmlWriter xml, string element, string iban) + { + xml.WriteStartElement(element); + xml.WriteStartElement("Id"); + xml.WriteElementString("IBAN", iban); + xml.WriteEndElement(); + xml.WriteEndElement(); + } + + private static void Agent(XmlWriter xml, string element, string? bic) + { + xml.WriteStartElement(element); + xml.WriteStartElement("FinInstnId"); + if (bic is not null) + { + xml.WriteElementString("BICFI", bic); + } + else + { + xml.WriteStartElement("Othr"); + xml.WriteElementString("Id", NotProvided); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + xml.WriteEndElement(); + } + + private static void InstructedAmount(XmlWriter xml, decimal amount) + { + xml.WriteStartElement("InstdAmt"); + xml.WriteAttributeString("Ccy", "EUR"); + xml.WriteString(Amount(amount)); + xml.WriteEndElement(); + } + + private static void Remittance(XmlWriter xml, string reference) + { + if (reference.Length > 0) + { + xml.WriteStartElement("RmtInf"); + xml.WriteElementString("Ustrd", reference); + xml.WriteEndElement(); + } + } + + private static string SequenceCode(SddSequence sequence) => sequence switch + { + SddSequence.First => "FRST", + SddSequence.Final => "FNAL", + SddSequence.OneOff => "OOFF", + _ => "RCUR", + }; + + private static string PaymentInformationId(string messageId, int number) + { + var suffix = string.Create(CultureInfo.InvariantCulture, $"-{number}"); + var room = IdLength - suffix.Length; + return (messageId.Length <= room ? messageId : messageId[..room]) + suffix; + } + + private static string Count(int count) => count.ToString(CultureInfo.InvariantCulture); + + private static string Amount(decimal amount) => amount.ToString("0.00", CultureInfo.InvariantCulture); + + private static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + + private static string FileSafe(string value) => + string.Concat(value.Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '.' ? c : '_')); + + private sealed record Header( + BankFileCompany Company, + string MessageId, + string Name, + string Iban, + string? Bic, + string Country, + DateTime CreatedAt); + + private sealed record Item( + BankFileItem Source, + string Name, + string Iban, + string? Bic, + string Country, + decimal Amount, + string EndToEndId, + string Reference, + string MandateId); +} diff --git a/src/Khaemhat.Core/Treasury/Treasury.cs b/src/Khaemhat.Core/Treasury/Treasury.cs new file mode 100644 index 0000000..1e36ab5 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/Treasury.cs @@ -0,0 +1,631 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Treasury; + +/// The state of an open item (SPEC §11.8, mockup 053). +public enum OpenItemStatus +{ + /// Nothing collected or paid. + Open = 0, + + /// Collected or paid in part. + Partial = 1, + + /// Settled. + Closed = 2, + + /// Returned unpaid by the bank (insoluto): open again, with the bank fees in an item of their own. + Unpaid = 3, + + /// In a remittance presented to the bank: the customer is settled, the effect is not collected yet. + InRemittance = 4, +} + +/// Whether money comes in or goes out. +public enum PaymentDirection +{ + /// A collection from a customer (incasso). + Receipt = 0, + + /// A payment to a supplier (pagamento). + Disbursement = 1, +} + +/// Where a collection or payment comes from. +public enum PaymentOrigin +{ + /// Recorded in the dialog of the schedule. + Manual = 0, + + /// The presentation of a remittance (effects, direct debits, transfers). + Remittance = 1, + + /// A movement of the bank statement matched in the reconciliation. + BankStatement = 2, +} + +/// +/// A collection or payment (SPEC §11.8, mockup 054, payments): money moved on a bank or cash account that +/// settles one or more open items of one customer or supplier, with allowances, exchange differences and bank fees. +/// Its entry (INC, PAG, or DIST for remittances) is written in the same transaction; a cancelled +/// payment loses its entry (or gets a reversal when final) and opens its items again. +/// +public sealed class Payment : Entity, IDemoMarkable +{ + /// In or out. + public PaymentDirection Direction { get; set; } + + /// The customer or supplier. + public long PartyId { get; set; } + + /// The day of the collection or payment. + public DateOnly PaymentDate { get; set; } + + /// The payment method. + public long? PaymentMethodId { get; set; } + + /// The bank account of the company, when the money goes through a bank. + public long? BankAccountId { get; set; } + + /// The ledger account of the money (bank, cash, effects for collection). + public long? AccountId { get; set; } + + /// The money moved (sum of the cash part of the lines), without fees. + public decimal Amount { get; set; } + + /// The allowances of the lines (positive: granted to the customer, or received from the supplier). + public decimal AllowanceAmount { get; set; } + + /// The exchange differences of the lines (positive: a loss on collections, a gain on payments). + public decimal ExchangeDifference { get; set; } + + /// The bank fees, a cost on the same account. + public decimal Fees { get; set; } + + /// The bank reference (CRO, TRN, cheque number). + public string? Reference { get; set; } + + /// The journal template of the entry. + public string? TemplateCode { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// Where it comes from. + public PaymentOrigin Origin { get; set; } + + /// The remittance, when it comes from one. + public long? RemittanceId { get; set; } + + /// The statement movement it was matched with. + public long? StatementLineId { get; set; } + + /// The entry. + public long? GlEntryId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// The part of a payment that settles one open item (payment_lines). +public sealed class PaymentLine : Entity +{ + /// The payment. + public long PaymentId { get; set; } + + /// The open item. + public long OpenItemId { get; set; } + + /// The money of this item (negative for a credit note set off). + public decimal Amount { get; set; } + + /// The allowance on this item. + public decimal Allowance { get; set; } + + /// The exchange difference on this item. + public decimal ExchangeDifference { get; set; } + + /// What the line settles: money, allowance and exchange difference. + public decimal Settled => Amount + Allowance + ExchangeDifference; +} + +/// The state of a remittance (mockup 055). +public enum RemittanceStatus +{ + /// Being prepared: effects can be added and removed. + Draft = 0, + + /// The file was written: it can still be written again, or the remittance posted. + Generated = 1, + + /// Posted: the customers are settled (effects) or the suppliers paid (transfers). + Presented = 2, + + /// Credited by the bank after the due dates: every effect collected or returned unpaid. + Closed = 3, +} + +/// +/// A remittance (distinta, SPEC §11.8, mockup 055, remittances): RiBa effects or SEPA direct debits presented +/// to a bank, or SEPA credit transfers to suppliers, numbered per year. +/// +public sealed class Remittance : Entity, IDemoMarkable +{ + /// The year of the number. + public int Year { get; set; } + + /// The number in the year. + public int Number { get; set; } + + /// What it carries. + public RemittanceKind Kind { get; set; } + + /// The bank of the company that receives it. + public long BankAccountId { get; set; } + + /// The day it is presented (or the transfers executed). + public DateOnly PresentationDate { get; set; } + + /// The last due date taken. + public DateOnly DueUntil { get; set; } + + /// Presented subject to collection with an advance (salvo buon fine): the bank credits it at once. + public bool Advance { get; set; } + + /// The state. + public RemittanceStatus Status { get; set; } + + /// The total of the effects. + public decimal TotalAmount { get; set; } + + /// The number of effects. + public int ItemCount { get; set; } + + /// The unique identifier written in the file. + public string? MessageId { get; set; } + + /// The attachment with the last file written. + public long? AttachmentId { get; set; } + + /// The name of the last file written. + public string? FileName { get; set; } + + /// The entry of the presentation (effects to the bank, or the advance). + public long? GlEntryId { get; set; } + + /// The day the bank credited the effects. + public DateOnly? CreditedOn { get; set; } + + /// The entry of the credit. + public long? CreditEntryId { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } + + /// The number as shown, such as 2026/018. + public string DisplayNumber => $"{Year}/{Number:000}"; +} + +/// The state of an effect of a remittance. +public enum RemittanceLineStatus +{ + /// In the remittance. + Included = 0, + + /// Collected (or the transfer executed). + Paid = 1, + + /// Returned unpaid. + Unpaid = 2, +} + +/// An effect, debit or transfer of a remittance (remittance_lines). +public sealed class RemittanceLine : Entity +{ + /// The remittance. + public long RemittanceId { get; set; } + + /// The open item. + public long OpenItemId { get; set; } + + /// The customer or supplier. + public long PartyId { get; set; } + + /// The amount. + public decimal Amount { get; set; } + + /// The due date. + public DateOnly DueDate { get; set; } + + /// The IBAN of the customer or supplier, as it was when the effect was added. + public string? Iban { get; set; } + + /// The direct debit mandate. + public long? MandateId { get; set; } + + /// The end-to-end identifier written in the file. + public string? EndToEndId { get; set; } + + /// The state. + public RemittanceLineStatus Status { get; set; } + + /// The day it was returned unpaid. + public DateOnly? UnpaidOn { get; set; } + + /// The bank fees of the unpaid effect, charged to the customer. + public decimal UnpaidFees { get; set; } + + /// The entry of the unpaid effect. + public long? UnpaidEntryId { get; set; } + + /// The payment that settled the item when the remittance was posted. + public long? PaymentId { get; set; } +} + +/// The scheme of a direct debit mandate. +public enum SddScheme +{ + /// Core: consumers and companies; the debtor can ask a refund for eight weeks. + Core = 0, + + /// Business to business: companies only, no refund, the debtor's bank must know the mandate. + B2b = 1, +} + +/// A SEPA direct debit mandate signed by a customer (sdd_mandates). +public sealed class SddMandate : Entity, IDemoMarkable +{ + /// The customer. + public long PartyId { get; set; } + + /// The unique mandate reference (UMR), at most 35 characters. + public string Reference { get; set; } = string.Empty; + + /// The day it was signed. + public DateOnly SignatureDate { get; set; } + + /// Core or B2B. + public SddScheme Scheme { get; set; } + + /// The account debited, compact. + public string Iban { get; set; } = string.Empty; + + /// The BIC of the debtor's bank. + public string? Bic { get; set; } + + /// A one-off mandate (a single debit). + public bool OneOff { get; set; } + + /// The day of the last collection: none means the next one is the first. + public DateOnly? LastCollectionDate { get; set; } + + /// Revoked by the customer: no more debits. + public bool Revoked { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A bank statement imported (bank_statements, mockup 057). +public sealed class BankStatement : Entity, IDemoMarkable +{ + /// The bank account of the company. + public long BankAccountId { get; set; } + + /// The format of the file. + public StatementFormat Format { get; set; } + + /// The name of the file. + public string? FileName { get; set; } + + /// The first day. + public DateOnly FromDate { get; set; } + + /// The last day. + public DateOnly ToDate { get; set; } + + /// The opening balance, if the file says it. + public decimal? OpeningBalance { get; set; } + + /// The closing balance, if the file says it. + public decimal? ClosingBalance { get; set; } + + /// The movements imported (the ones already imported before are skipped). + public int MovementCount { get; set; } + + /// The file, kept as an attachment. + public long? AttachmentId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// The state of a movement in the reconciliation (mockup 057). +public enum StatementLineStatus +{ + /// Nothing found: to match by hand. + ToMatch = 0, + + /// A match is proposed, with its confidence. + Suggested = 1, + + /// Matched and recorded. + Matched = 2, + + /// Left out on purpose (already recorded in another way). + Ignored = 3, +} + +/// What a movement is matched with. +public enum StatementMatchKind +{ + /// Nothing. + None = 0, + + /// Open items of one customer or supplier: a collection or payment is recorded. + OpenItems = 1, + + /// A collection or payment already recorded. + Payment = 2, + + /// The F24 of a due date: its payment is recorded. + TaxPayment = 3, + + /// A saved rule: an entry on its account is recorded. + Rule = 4, + + /// The credit of a remittance. + RemittanceCredit = 5, + + /// An effect returned unpaid. + Unpaid = 6, + + /// An entry of the ledger on the bank account already recorded. + Entry = 7, +} + +/// A movement of a bank statement (bank_statement_lines). +public sealed class BankStatementLine : Entity, IDemoMarkable +{ + /// The statement. + public long StatementId { get; set; } + + /// The bank account of the company. + public long BankAccountId { get; set; } + + /// The booking date. + public DateOnly BookingDate { get; set; } + + /// The value date. + public DateOnly? ValueDate { get; set; } + + /// Positive for money in, negative for money out. + public decimal Amount { get; set; } + + /// The description of the bank. + public string Description { get; set; } = string.Empty; + + /// The bank reference. + public string? Reference { get; set; } + + /// The other party, if known. + public string? CounterpartyName { get; set; } + + /// Its IBAN, if known. + public string? CounterpartyIban { get; set; } + + /// The bank transaction code. + public string? BankCode { get; set; } + + /// A hash of date, amount, description and reference: the same movement is never imported twice. + public string Fingerprint { get; set; } = string.Empty; + + /// The state. + public StatementLineStatus Status { get; set; } + + /// What it is (or would be) matched with. + public StatementMatchKind MatchKind { get; set; } + + /// The confidence of the proposal, 0-100. + public int Confidence { get; set; } + + /// The proposal, as shown. + public string? Proposal { get; set; } + + /// The ids the proposal points to (open items, payment, remittance line...), comma separated. + public string? Targets { get; set; } + + /// The party of the proposal. + public long? PartyId { get; set; } + + /// The rule of the proposal. + public long? RuleId { get; set; } + + /// The collection or payment recorded or matched. + public long? PaymentId { get; set; } + + /// The entry recorded or matched. + public long? GlEntryId { get; set; } + + /// When it was matched. + public DateTime? MatchedAt { get; set; } + + /// Who matched it. + public string? MatchedBy { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// Which movements a rule applies to. +public enum BankRuleDirection +{ + /// Money in and out. + Any = 0, + + /// Money in. + In = 1, + + /// Money out. + Out = 2, +} + +/// +/// A rule of the reconciliation (bank_match_rules): the movements whose description contains a text are +/// recorded on an account, such as bank fees on 21.03.011. +/// +public sealed class BankMatchRule : Entity, IDemoMarkable +{ + /// The name. + public string Name { get; set; } = string.Empty; + + /// The text looked for in the description, case and accents ignored. + public string Pattern { get; set; } = string.Empty; + + /// Money in, out or both. + public BankRuleDirection Direction { get; set; } + + /// The account the movement goes to (the other side is the bank). + public long AccountId { get; set; } + + /// The journal template of the entry. + public string? TemplateCode { get; set; } + + /// The description of the entry; empty for the description of the movement. + public string? EntryDescription { get; set; } + + /// Not applied. + public bool Disabled { get; set; } + + /// How many movements it recorded. + public int Uses { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// How a reminder is sent. +[Flags] +public enum DunningChannel +{ + /// Not sent: printed only. + None = 0, + + /// E-mail. + Email = 1, + + /// Certified e-mail (PEC). + Pec = 2, + + /// A PDF letter, kept as an attachment of the customer. + Letter = 4, +} + +/// What happens when a reminder of a level is sent. +public enum DunningAction +{ + /// Nothing else. + None = 0, + + /// The agent of the customer is notified. + NotifyAgent = 1, + + /// The customer is blocked (orders and deliveries) and the administration notified. + BlockCustomer = 2, +} + +/// A level of the reminders (dunning_levels, mockup 056). +public sealed class DunningLevel : Entity +{ + /// The level, from 1. + public int Level { get; set; } + + /// Days after the due date. + public int DaysAfterDue { get; set; } + + /// The name of the template, such as Promemoria cortese. + public string Name { get; set; } = string.Empty; + + /// The subject, with fields such as {{Cliente}}. + public string Subject { get; set; } = string.Empty; + + /// The text, with fields such as {{Elenco}} and {{Totale}}. + public string Body { get; set; } = string.Empty; + + /// How it is sent. + public DunningChannel Channel { get; set; } + + /// Late payment interest is computed and written. + public bool ChargeInterest { get; set; } + + /// What else happens. + public DunningAction Action { get; set; } + + /// Sent by the scheduled task without asking (e-mail and PEC only). + public bool Automatic { get; set; } +} + +/// The state of a reminder. +public enum DunningLetterStatus +{ + /// Waiting in the mail queue. + Queued = 0, + + /// Sent (or printed). + Sent = 1, + + /// Not sent. + Failed = 2, +} + +/// A reminder sent to a customer (dunning_letters): the log of the reminders. +public sealed class DunningLetter : Entity, IDemoMarkable +{ + /// The customer. + public long PartyId { get; set; } + + /// The level. + public int Level { get; set; } + + /// The day. + public DateOnly SentOn { get; set; } + + /// How it was sent. + public DunningChannel Channel { get; set; } + + /// The addresses. + public string? Recipients { get; set; } + + /// The subject. + public string Subject { get; set; } = string.Empty; + + /// The open items reminded. + public int ItemCount { get; set; } + + /// The overdue amount. + public decimal OverdueAmount { get; set; } + + /// The late payment interest written. + public decimal Interest { get; set; } + + /// The state. + public DunningLetterStatus Status { get; set; } + + /// The PDF letter. + public long? AttachmentId { get; set; } + + /// The message in the mail queue. + public long? MailId { get; set; } + + /// Who sent it (empty for the scheduled task). + public string? SentBy { get; set; } + + /// + public bool IsDemo { get; set; } +} diff --git a/src/Khaemhat.Core/Treasury/TreasuryErrors.cs b/src/Khaemhat.Core/Treasury/TreasuryErrors.cs new file mode 100644 index 0000000..0d581d9 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/TreasuryErrors.cs @@ -0,0 +1,95 @@ +namespace Khaemhat.Core.Treasury; + +/// The error codes of the schedule and the treasury; the interface translates them (Treasury.json). +public static class TreasuryErrors +{ + /// The record does not exist. + public const string NotFound = "treasury.not-found"; + + /// A collection or payment without customer or supplier. + public const string PartyRequired = "treasury.payment.party-required"; + + /// A collection or payment without items. + public const string ItemsRequired = "treasury.payment.items-required"; + + /// A collection or payment without amount. + public const string AmountRequired = "treasury.payment.amount-required"; + + /// The items belong to another party or the other direction. + public const string ItemParty = "treasury.payment.item-party"; + + /// An item would be settled for more than what is left. + public const string OverSettled = "treasury.payment.over-settled"; + + /// An item is in a remittance: it is settled by the remittance. + public const string InRemittance = "treasury.item.in-remittance"; + + /// The lines do not add up to the amount. + public const string Unbalanced = "treasury.payment.unbalanced"; + + /// An allowance, exchange difference or fee has no account. + public const string AccountMissing = "treasury.account-missing"; + + /// No bank or cash account to move the money. + public const string MoneyAccountMissing = "treasury.money-account-missing"; + + /// A collection made by a remittance or a bank statement is cancelled there. + public const string FromRemittance = "treasury.payment.from-remittance"; + + /// The remittance has no items. + public const string RemittanceEmpty = "treasury.remittance.empty"; + + /// The remittance is not in the state the operation needs. + public const string RemittanceStatus = "treasury.remittance.status"; + + /// The bank of the remittance has no IBAN, SIA or creditor identifier for the file. + public const string RemittanceBank = "treasury.remittance.bank"; + + /// An item has no bank coordinates (IBAN, or ABI and CAB for RiBa). + public const string RemittanceIban = "treasury.remittance.iban"; + + /// A direct debit item has no valid mandate. + public const string RemittanceMandate = "treasury.remittance.mandate"; + + /// The item cannot go in this kind of remittance. + public const string RemittanceItem = "treasury.remittance.item"; + + /// The file format is not available. + public const string RemittanceFormat = "treasury.remittance.format"; + + /// Another mandate has the reference. + public const string MandateDuplicate = "treasury.mandate.duplicate"; + + /// The mandate has no reference. + public const string MandateReference = "treasury.mandate.reference"; + + /// The IBAN is not valid. + public const string IbanInvalid = "treasury.iban-invalid"; + + /// The mandate is used by remittances. + public const string MandateUsed = "treasury.mandate.used"; + + /// The bank file is not recognized. + public const string StatementFormat = "treasury.statement.format"; + + /// The bank file has no movements. + public const string StatementEmpty = "treasury.statement.empty"; + + /// The bank file belongs to another bank account. + public const string StatementAccount = "treasury.statement.account"; + + /// The movement is already matched or ignored. + public const string MatchDone = "treasury.match.done"; + + /// The chosen items or payments do not add up to the movement. + public const string MatchAmount = "treasury.match.amount"; + + /// A rule without pattern or account. + public const string RulePattern = "treasury.rule.pattern"; + + /// The customer has no address for the reminder on the chosen channel. + public const string DunningRecipient = "treasury.dunning.recipient"; + + /// A level of reminders without name, subject or days. + public const string DunningLevel = "treasury.dunning.level"; +} diff --git a/src/Khaemhat.Core/Treasury/TreasuryRules.cs b/src/Khaemhat.Core/Treasury/TreasuryRules.cs new file mode 100644 index 0000000..8dc18ab --- /dev/null +++ b/src/Khaemhat.Core/Treasury/TreasuryRules.cs @@ -0,0 +1,716 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Core.Treasury; + +/// The residual of the open items by age (mockup 053). +/// Not due yet. +/// Overdue by 1 to 30 days. +/// Overdue by 31 to 60 days. +/// Overdue by 61 to 90 days. +/// Overdue by more than 90 days. +/// Items not due. +/// Items overdue by 1 to 30 days. +/// Items overdue by 31 to 60 days. +/// Items overdue by 61 to 90 days. +/// Items overdue by more than 90 days. +public sealed record AgingBuckets( + decimal NotDue, + decimal Days1To30, + decimal Days31To60, + decimal Days61To90, + decimal Over90, + int CountNotDue, + int Count1To30, + int Count31To60, + int Count61To90, + int CountOver90) +{ + /// Everything open. + public decimal Total => NotDue + Overdue; + + /// Everything overdue. + public decimal Overdue => Days1To30 + Days31To60 + Days61To90 + Over90; +} + +/// The age of open items (SPEC §11.8, AgingCalculator). +public static class AgingCalculator +{ + /// Days past the due date: negative while it is not due. + /// The due date. + /// Today. + /// The days. + public static int DaysOverdue(DateOnly dueDate, DateOnly today) => today.DayNumber - dueDate.DayNumber; + + /// Splits the residuals by age. + /// The due date and residual of each item. + /// Today. + /// The buckets. + public static AgingBuckets Of(IEnumerable<(DateOnly DueDate, decimal Residual)> items, DateOnly today) + { + ArgumentNullException.ThrowIfNull(items); + var sums = new decimal[5]; + var counts = new int[5]; + foreach (var (due, residual) in items) + { + if (residual == 0m) + { + continue; + } + + var days = DaysOverdue(due, today); + var bucket = days switch + { + <= 0 => 0, + <= 30 => 1, + <= 60 => 2, + <= 90 => 3, + _ => 4, + }; + sums[bucket] += residual; + counts[bucket]++; + } + + return new AgingBuckets(sums[0], sums[1], sums[2], sums[3], sums[4], counts[0], counts[1], counts[2], counts[3], counts[4]); + } +} + +/// Spreads a collection or payment over open items. +public static class PaymentAllocator +{ + /// + /// Gives the amount to the items in their order (the oldest first): each item takes up to its residual; credit + /// notes (negative residuals) are always taken whole, so they add to what the others can take. + /// + /// The residual of each item, in order. + /// The money. + /// What each item takes; what is left over is not given to anyone. + public static IReadOnlyList Allocate(IReadOnlyList residuals, decimal amount) + { + ArgumentNullException.ThrowIfNull(residuals); + var result = new decimal[residuals.Count]; + var left = amount; + for (var i = 0; i < residuals.Count; i++) + { + if (residuals[i] < 0m) + { + result[i] = residuals[i]; + left -= residuals[i]; + } + } + + for (var i = 0; i < residuals.Count; i++) + { + if (residuals[i] <= 0m || left <= 0m) + { + continue; + } + + var take = Math.Min(residuals[i], left); + result[i] = take; + left -= take; + } + + return result; + } +} + +/// The accounts of the entry of a collection or payment. +/// The bank, cash or effects account the money moves on. +/// Allowances granted (abbuoni passivi). +/// Allowances received (abbuoni attivi). +/// Exchange losses. +/// Exchange gains. +/// Bank fees. +public sealed record PaymentPostingAccounts(long Money, long? AllowanceExpense, long? AllowanceIncome, long? ExchangeLoss, long? ExchangeGain, long? BankCharges); + +/// A line of a collection or payment as the entry reads it. +/// The customers or suppliers account of the item. +/// The customer or supplier. +/// The item. +/// The description (the document). +/// The money. +/// The allowance. +/// The exchange difference. +public sealed record PaymentPostingLine(long ControlAccountId, long PartyId, long OpenItemId, string? Description, decimal Amount, decimal Allowance, decimal ExchangeDifference); + +/// A line of the entry written for a collection or payment. +/// The account. +/// The customer or supplier. +/// The item it settles. +/// The description. +/// Dare. +/// Avere. +public sealed record PaymentPostedLine(long AccountId, long? PartyId, long? OpenItemId, string? Description, decimal Debit, decimal Credit); + +/// The missing account of a collection or payment. +public sealed class PaymentAccountMissingException : InvalidOperationException +{ + /// Creates the exception. + public PaymentAccountMissingException() + { + } + + /// Creates the exception. + /// The role of the missing account. + public PaymentAccountMissingException(string message) + : base(message) + { + } + + /// Creates the exception. + /// The role. + /// The cause. + public PaymentAccountMissingException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// The entry of a collection or payment (mockup 054): a collection debits the money, credits the customer for what +/// each item settles and books allowances and exchange differences on their accounts; a payment the other way round. +/// Bank fees are a cost paid from the same money account. The entry always balances. +/// +public static class PaymentPosting +{ + /// Builds the lines. + /// Collection or payment. + /// The accounts. + /// The items settled. + /// The bank fees. + /// The description of the money line. + /// The lines, balanced. + /// An allowance, exchange difference or fee has no account. + public static IReadOnlyList Build( + PaymentDirection direction, PaymentPostingAccounts accounts, IReadOnlyList lines, decimal fees, string? description) + { + ArgumentNullException.ThrowIfNull(accounts); + ArgumentNullException.ThrowIfNull(lines); + var result = new List(); + var receipt = direction == PaymentDirection.Receipt; + + // Signed amounts: positive is Dare. + void Add(long account, long? party, long? item, string? text, decimal signed) + { + if (signed > 0m) + { + result.Add(new PaymentPostedLine(account, party, item, text, signed, 0m)); + } + else if (signed < 0m) + { + result.Add(new PaymentPostedLine(account, party, item, text, 0m, -signed)); + } + } + + static long Need(long? account, string role) => account ?? throw new PaymentAccountMissingException(role); + + var money = lines.Sum(l => l.Amount); + var allowance = lines.Sum(l => l.Allowance); + var exchange = lines.Sum(l => l.ExchangeDifference); + Add(accounts.Money, null, null, description, receipt ? money : -money); + if (allowance != 0m) + { + // A collection grants the allowance (a cost); a payment receives it (an income). The opposite sign swaps them. + var cost = receipt ? allowance > 0m : allowance < 0m; + var account = cost ? Need(accounts.AllowanceExpense, "AllowanceExpense") : Need(accounts.AllowanceIncome, "AllowanceIncome"); + Add(account, null, null, "Abbuono", receipt ? allowance : -allowance); + } + + if (exchange != 0m) + { + var loss = receipt ? exchange > 0m : exchange < 0m; + var account = loss ? Need(accounts.ExchangeLoss, "ExchangeLoss") : Need(accounts.ExchangeGain, "ExchangeGain"); + Add(account, null, null, "Differenza cambio", receipt ? exchange : -exchange); + } + + foreach (var line in lines) + { + var settled = line.Amount + line.Allowance + line.ExchangeDifference; + Add(line.ControlAccountId, line.PartyId, line.OpenItemId, line.Description, receipt ? -settled : settled); + } + + if (fees != 0m) + { + Add(Need(accounts.BankCharges, "BankCharges"), null, null, "Spese bancarie", fees); + Add(accounts.Money, null, null, "Spese bancarie", -fees); + } + + return result; + } +} + +/// Late payment interest (SPEC §11.8, D.Lgs. 231/2002 in Italy). +public static class LateInterestCalculator +{ + /// + /// The interest on a residual from the day after the due date to a day, at the yearly rate of each day (the rate + /// changes every half-year), on 365 days, rounded to the cent. + /// + /// The amount overdue. + /// The due date. + /// The last day counted. + /// The yearly rate in percent of a day. + /// The interest; zero when not overdue. + public static decimal Interest(decimal residual, DateOnly dueDate, DateOnly until, Func rateOn) + { + ArgumentNullException.ThrowIfNull(rateOn); + if (residual <= 0m || until <= dueDate) + { + return 0m; + } + + var total = 0m; + var day = dueDate.AddDays(1); + while (day <= until) + { + // One step per half-year: the rate is the same inside it. + var halfEnd = day.Month <= 6 ? new DateOnly(day.Year, 6, 30) : new DateOnly(day.Year, 12, 31); + var last = halfEnd < until ? halfEnd : until; + var days = last.DayNumber - day.DayNumber + 1; + total += residual * rateOn(day) / 100m * days / 365m; + day = last.AddDays(1); + } + + return Math.Round(total, 2, MidpointRounding.AwayFromZero); + } +} + +/// A possible match of a bank movement, built by the reconciliation from the open data of the company. +/// What it is. +/// The ids it points to, comma separated. +/// The customer or supplier. +/// The movement it expects: positive money in, negative money out. +/// The date it expects (due date, payment date). +/// The proposal as shown, such as Incasso FT/2026/000388. +/// Document numbers and references that may appear in the description. +/// Names of the party that may appear. +/// IBANs of the party. +/// Words that must appear for the candidate to count (such as INSOLUT, F24); empty for none. +/// How much more the movement may be (bank fees of an unpaid effect). +public sealed record MatchCandidate( + StatementMatchKind Kind, + string? Targets, + long? PartyId, + decimal Amount, + DateOnly Date, + string Label, + IReadOnlyList Keys, + IReadOnlyList Names, + IReadOnlyList Ibans, + IReadOnlyList Keywords, + decimal AmountTolerance = 0m); + +/// A saved rule as the matcher reads it. +/// The rule. +/// The text looked for. +/// Money in, out or both. +/// The proposal, such as Regola 'COMMISSIONI' → 21.03.011 Spese bancarie. +public sealed record MatchRule(long Id, string Pattern, BankRuleDirection Direction, string Label); + +/// The best match of a movement. +/// What it is. +/// The ids. +/// The party. +/// The rule. +/// 0-100. +/// As shown. +public sealed record MatchProposal(StatementMatchKind Kind, string? Targets, long? PartyId, long? RuleId, int Confidence, string Label); + +/// +/// Proposes what a bank movement is (SPEC §11.8, mockup 057, BankMatcher): by amount, date, document numbers +/// and references in the description, the name and IBAN of the party; saved rules for the recurring movements (fees, +/// commissions). The service records the proposals at or above the threshold the user confirms. +/// +public static class BankMatcher +{ + /// The words before a document number in bank descriptions. + private static readonly HashSet NumberPrefixes = new(StringComparer.Ordinal) + { + "FT", "FATT", "FATTURA", "FATTURE", "FAT", "FA", "N", "NR", "NUM", "DOC", "RIF", "FAT.", "INV", "INVOICE", + }; + + /// The best proposal for a movement, or when nothing fits. + /// The movement. + /// The candidates. + /// The rules. + /// The proposal. + public static MatchProposal? Best(StatementMovement movement, IEnumerable candidates, IEnumerable rules) + { + ArgumentNullException.ThrowIfNull(movement); + ArgumentNullException.ThrowIfNull(candidates); + ArgumentNullException.ThrowIfNull(rules); + var text = Normalize(movement.Description + " " + movement.Reference + " " + movement.CounterpartyName); + var tokens = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + MatchProposal? best = null; + foreach (var candidate in candidates) + { + var score = Score(movement, candidate, text, tokens); + if (score > 0 && (best is null || score > best.Confidence)) + { + best = new MatchProposal(candidate.Kind, candidate.Targets, candidate.PartyId, null, score, candidate.Label); + } + } + + if (best is { Confidence: >= 90 }) + { + return best; + } + + foreach (var rule in rules) + { + var direction = rule.Direction switch + { + BankRuleDirection.In => movement.Amount > 0m, + BankRuleDirection.Out => movement.Amount < 0m, + _ => true, + }; + var pattern = Normalize(rule.Pattern); + if (direction && pattern.Length > 0 && (" " + text + " ").Contains(" " + pattern, StringComparison.Ordinal)) + { + return new MatchProposal(StatementMatchKind.Rule, rule.Id.ToString(CultureInfo.InvariantCulture), null, rule.Id, 98, rule.Label); + } + } + + return best; + } + + /// The score of a candidate, 0 when it does not fit. + /// The movement. + /// The candidate. + /// 0-100. + public static int Score(StatementMovement movement, MatchCandidate candidate) + { + ArgumentNullException.ThrowIfNull(movement); + ArgumentNullException.ThrowIfNull(candidate); + var text = Normalize(movement.Description + " " + movement.Reference + " " + movement.CounterpartyName); + return Score(movement, candidate, text, text.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + } + + /// Upper case, no accents, only letters and digits separated by single spaces. + /// The text. + /// The normalised text. + public static string Normalize(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return string.Empty; + } + + var builder = new StringBuilder(text.Length); + var space = true; + foreach (var ch in text.Normalize(NormalizationForm.FormD)) + { + if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.NonSpacingMark) + { + continue; + } + + if (char.IsLetterOrDigit(ch)) + { + builder.Append(char.ToUpperInvariant(ch)); + space = false; + } + else if (!space) + { + builder.Append(' '); + space = true; + } + } + + return builder.ToString().TrimEnd(); + } + + /// + /// The items of one party whose residuals add up to an amount: first the oldest items in a row, then any pair or + /// triple among the first twelve. + /// + /// The id and residual of the items, oldest first. + /// The amount. + /// The ids, or an empty list. + public static IReadOnlyList Combination(IReadOnlyList<(long Id, decimal Residual)> items, decimal amount) + { + ArgumentNullException.ThrowIfNull(items); + var sum = 0m; + for (var i = 0; i < items.Count; i++) + { + sum += items[i].Residual; + if (sum == amount) + { + return [.. items.Take(i + 1).Select(x => x.Id)]; + } + } + + var n = Math.Min(items.Count, 12); + for (var i = 0; i < n; i++) + { + if (items[i].Residual == amount) + { + return [items[i].Id]; + } + } + + for (var i = 0; i < n; i++) + { + for (var j = i + 1; j < n; j++) + { + if (items[i].Residual + items[j].Residual == amount) + { + return [items[i].Id, items[j].Id]; + } + + for (var k = j + 1; k < n; k++) + { + if (items[i].Residual + items[j].Residual + items[k].Residual == amount) + { + return [items[i].Id, items[j].Id, items[k].Id]; + } + } + } + } + + return []; + } + + private static int Score(StatementMovement movement, MatchCandidate candidate, string text, string[] tokens) + { + var difference = movement.Amount - candidate.Amount; + var exact = Math.Abs(difference) < 0.005m; + var withinTolerance = candidate.AmountTolerance > 0m && Math.Sign(movement.Amount) == Math.Sign(candidate.Amount) + && Math.Abs(movement.Amount) >= Math.Abs(candidate.Amount) && Math.Abs(difference) <= candidate.AmountTolerance; + if (!exact && !withinTolerance) + { + return 0; + } + + if (candidate.Keywords.Count > 0 && !candidate.Keywords.Any(k => text.Contains(Normalize(k), StringComparison.Ordinal))) + { + return 0; + } + + var score = exact ? 50 : 40; + if (candidate.Keywords.Count > 0) + { + score += 30; + } + + if (candidate.Keys.Any(k => HasKey(text, tokens, k))) + { + score += 30; + } + + if (candidate.Ibans.Any(i => movement.CounterpartyIban is { } iban && string.Equals(Compact(iban), Compact(i), StringComparison.OrdinalIgnoreCase))) + { + score += 25; + } + + if (candidate.Names.Any(n => HasName(text, n))) + { + score += 20; + } + + var days = Math.Abs(movement.BookingDate.DayNumber - candidate.Date.DayNumber); + score += days switch + { + <= 3 => 10, + <= 15 => 5, + <= 60 => 0, + _ => -10, + }; + return Math.Clamp(score, 1, 100); + } + + private static bool HasKey(string text, string[] tokens, string key) + { + var normalized = Normalize(key); + if (normalized.Length == 0) + { + return false; + } + + if ((" " + text + " ").Contains(" " + normalized + " ", StringComparison.Ordinal)) + { + return true; + } + + // The number of a document without its prefix and leading zeros, after a word such as FT or FATT. + var parts = normalized.Split(' '); + var last = parts[^1].TrimStart('0'); + if (last.Length == 0 || !last.All(char.IsAsciiDigit)) + { + return false; + } + + for (var i = 1; i < tokens.Length; i++) + { + if (tokens[i].TrimStart('0') == last && NumberPrefixes.Contains(tokens[i - 1])) + { + return true; + } + } + + return false; + } + + private static bool HasName(string text, string name) + { + // The first two significant words of the name (Rossi Impianti S.r.l. → ROSSI IMPIANTI). + var words = Normalize(name).Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Where(w => w.Length >= 3 && w is not ("SRL" or "SPA" or "SNC" or "SAS" or "SRLS" or "DI" or "DEL" or "DELLA" or "E" or "C")) + .Take(2).ToList(); + return words.Count > 0 && words.All(w => (" " + text + " ").Contains(" " + w + " ", StringComparison.Ordinal)); + } + + private static string Compact(string iban) => iban.Replace(" ", string.Empty, StringComparison.Ordinal); +} + +/// An open item as the reminders read it. +/// The item. +/// The due date. +/// What is left. +/// The level of its last reminder. +/// The day of its last reminder. +/// Contested. +public sealed record DunningItem(long OpenItemId, DateOnly DueDate, decimal Residual, int Level, DateOnly? LastDunningDate, bool Disputed); + +/// A level as the reminders read it. +/// The level. +/// Days after the due date. +public sealed record DunningStep(int Level, int DaysAfterDue); + +/// Which reminder a customer gets next (SPEC §11.8, mockup 056, DunningRules). +public static class DunningRules +{ + /// Days between two reminders to the same customer. + public const int MinDaysBetween = 7; + + /// + /// The next level: the one after the highest already sent on the overdue items, once the oldest of them is + /// overdue by its days and a week has passed since the last reminder; none when nothing is overdue, the items are + /// contested or the last level was sent. + /// + /// The open items of the customer. + /// The levels. + /// Today. + /// The level, or . + public static int? NextLevel(IReadOnlyList items, IReadOnlyList levels, DateOnly today) + { + ArgumentNullException.ThrowIfNull(items); + ArgumentNullException.ThrowIfNull(levels); + var overdue = items.Where(i => !i.Disputed && i.Residual > 0m && i.DueDate < today).ToList(); + if (overdue.Count == 0 || levels.Count == 0) + { + return null; + } + + var maxDays = overdue.Max(i => AgingCalculator.DaysOverdue(i.DueDate, today)); + var current = overdue.Max(i => i.Level); + var last = overdue.Select(i => i.LastDunningDate).Where(d => d is not null).Max(); + if (last is { } l && today.DayNumber - l.DayNumber < MinDaysBetween) + { + return null; + } + + var next = levels.Where(s => s.Level > current).OrderBy(s => s.Level).FirstOrDefault(); + return next is not null && maxDays >= next.DaysAfterDue ? next.Level : null; + } +} + +/// What a forecast movement comes from. +public enum CashFlowSource +{ + /// Open items of customers. + Receivables = 0, + + /// Open items of suppliers. + Payables = 1, + + /// Customer orders not invoiced. + SaleOrders = 2, + + /// Supplier orders not invoiced. + PurchaseOrders = 3, + + /// Recurring entries on bank or cash. + Recurring = 4, + + /// Taxes to pay (F24). + Taxes = 5, +} + +/// A forecast movement. +/// When it is expected. +/// Positive in, negative out. +/// Where it comes from. +/// What it is. +public sealed record CashFlowMovement(DateOnly Date, decimal Amount, CashFlowSource Source, string Label); + +/// A period of the forecast. +/// The first day. +/// The last day. +/// Money in. +/// Money out (positive). +/// The balance at the end of the period. +public sealed record CashFlowPeriod(DateOnly From, DateOnly To, decimal In, decimal Out, decimal Balance); + +/// The cash flow forecast (SPEC §11.8, CashFlowForecastService): the balance period by period. +public static class CashFlowForecaster +{ + /// Spreads the movements over periods; the overdue ones count in the first period. + /// The money today on bank and cash. + /// The movements. + /// The first day. + /// How many days. + /// The days of a period. + /// The periods. + public static IReadOnlyList Periods(decimal opening, IEnumerable movements, DateOnly from, int days, int periodDays = 7) + { + ArgumentNullException.ThrowIfNull(movements); + ArgumentOutOfRangeException.ThrowIfLessThan(days, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(periodDays, 1); + var end = from.AddDays(days - 1); + var list = movements.Where(m => m.Date <= end).ToList(); + var result = new List(); + var balance = opening; + for (var start = from; start <= end; start = start.AddDays(periodDays)) + { + var stop = start.AddDays(periodDays - 1) > end ? end : start.AddDays(periodDays - 1); + var first = result.Count == 0; + var inPeriod = list.Where(m => (first && m.Date < start) || (m.Date >= start && m.Date <= stop)).ToList(); + var money = inPeriod.Where(m => m.Amount > 0m).Sum(m => m.Amount); + var spent = -inPeriod.Where(m => m.Amount < 0m).Sum(m => m.Amount); + balance += money - spent; + result.Add(new CashFlowPeriod(start, stop, money, spent, balance)); + } + + return result; + } +} + +/// The state of an open item in the schedule from its amounts (ADR 0038). +public static class OpenItemStates +{ + /// The state an item has after a change of its amounts. + /// The item. + /// In remittance while a remittance holds it; closed when nothing is left; partial when something was settled; unpaid after a returned effect; open otherwise. + public static OpenItemStatus Of(Accounting.OpenItem item) + { + ArgumentNullException.ThrowIfNull(item); + if (item.Status == OpenItemStatus.InRemittance && item.RemittanceId is not null) + { + return OpenItemStatus.InRemittance; + } + + if (item.Residual == 0m) + { + return OpenItemStatus.Closed; + } + + if (item.PaidAmount != 0m) + { + return OpenItemStatus.Partial; + } + + return item.UnpaidCount > 0 ? OpenItemStatus.Unpaid : OpenItemStatus.Open; + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs b/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs index 23bd9a4..ca8d095 100644 --- a/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/LedgerMaps.cs @@ -99,6 +99,7 @@ public sealed class OpenItemMap : EntityMap { ToTable("gl_open_items"); Map(x => x.DocumentNumber).MaxLength(30); + Map(x => x.Notes).MaxLength(200); } } diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs new file mode 100644 index 0000000..4090920 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs @@ -0,0 +1,252 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// The schedule and the treasury (SPEC §11.8, ADR 0038, issues #69-#72): the open items of the ledger get their state +/// in the schedule; collections and payments with their lines; remittances of effects, direct debits and transfers +/// with their lines; direct debit mandates; bank statements with their movements and the saved rules of the +/// reconciliation; the levels of the reminders and the log of the reminders sent. +/// +[Migration(20261113_003, "create_treasury")] +public sealed class M20261113_003_CreateTreasury : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.AlterTable("gl_open_items", t => + { + t.String("status", 40).NotNull().Default("Open"); + t.Bool("disputed").NotNull().Default(false); + t.Int64("bank_account_id"); + t.Int64("remittance_id"); + t.Int32("unpaid_count").NotNull().Default(0); + t.Int64("parent_id"); + t.Int32("dunning_level").NotNull().Default(0); + t.Date("last_dunning_date"); + t.String("notes", 200); + }); + schema.CreateIndex("gl_open_items", "ix_gl_open_items_schedule", false, "direction", "status", "due_date"); + schema.AlterTable("bank_accounts", t => t.String("creditor_id", 35)); + + schema.CreateTable("remittances", t => + { + t.Id(); + t.Int32("year").NotNull(); + t.Int32("number").NotNull(); + t.String("kind", 40).NotNull(); + t.Int64("bank_account_id").NotNull(); + t.Date("presentation_date").NotNull(); + t.Date("due_until").NotNull(); + t.Bool("advance").NotNull().Default(false); + t.String("status", 40).NotNull(); + t.Decimal("total_amount").NotNull().Default(0m); + t.Int32("item_count").NotNull().Default(0); + t.String("message_id", 35); + t.Int64("attachment_id"); + t.String("file_name", 100); + t.Int64("gl_entry_id"); + t.Date("credited_on"); + t.Int64("credit_entry_id"); + t.String("notes", 500); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_remittances_number", "year", "number"); + t.ForeignKey("fk_remittances_bank", "bank_account_id", "bank_accounts", ReferentialAction.Restrict); + }); + + schema.CreateTable("sdd_mandates", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("reference", 35).NotNull(); + t.Date("signature_date").NotNull(); + t.String("scheme", 40).NotNull(); + t.String("iban", 34).NotNull(); + t.String("bic", 11); + t.Bool("one_off").NotNull().Default(false); + t.Date("last_collection_date"); + t.Bool("revoked").NotNull().Default(false); + t.String("notes", 200); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_sdd_mandates_reference", "reference"); + t.Index("ix_sdd_mandates_party", "party_id"); + t.ForeignKey("fk_sdd_mandates_party", "party_id", "parties", ReferentialAction.Restrict); + }); + + schema.CreateTable("payments", t => + { + t.Id(); + t.String("direction", 40).NotNull(); + t.Int64("party_id").NotNull(); + t.Date("payment_date").NotNull(); + t.Int64("payment_method_id"); + t.Int64("bank_account_id"); + t.Int64("account_id"); + t.Decimal("amount").NotNull().Default(0m); + t.Decimal("allowance_amount").NotNull().Default(0m); + t.Decimal("exchange_difference").NotNull().Default(0m); + t.Decimal("fees").NotNull().Default(0m); + t.String("reference", 60); + t.String("template_code", 10); + t.String("notes", 500); + t.String("origin", 40).NotNull(); + t.Int64("remittance_id"); + t.Int64("statement_line_id"); + t.Int64("gl_entry_id"); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_payments_date", "direction", "payment_date"); + t.Index("ix_payments_party", "party_id", "payment_date"); + t.ForeignKey("fk_payments_party", "party_id", "parties", ReferentialAction.Restrict); + t.ForeignKey("fk_payments_remittance", "remittance_id", "remittances", ReferentialAction.Restrict); + }); + + schema.CreateTable("payment_lines", t => + { + t.Id(); + t.Int64("payment_id").NotNull(); + t.Int64("open_item_id").NotNull(); + t.Decimal("amount").NotNull().Default(0m); + t.Decimal("allowance").NotNull().Default(0m); + t.Decimal("exchange_difference").NotNull().Default(0m); + t.AuditColumns(); + t.Index("ix_payment_lines_payment", "payment_id"); + t.Index("ix_payment_lines_item", "open_item_id"); + t.ForeignKey("fk_payment_lines_payment", "payment_id", "payments", ReferentialAction.Cascade); + t.ForeignKey("fk_payment_lines_item", "open_item_id", "gl_open_items", ReferentialAction.Restrict); + }); + + schema.CreateTable("remittance_lines", t => + { + t.Id(); + t.Int64("remittance_id").NotNull(); + t.Int64("open_item_id").NotNull(); + t.Int64("party_id").NotNull(); + t.Decimal("amount").NotNull().Default(0m); + t.Date("due_date").NotNull(); + t.String("iban", 34); + t.Int64("mandate_id"); + t.String("end_to_end_id", 35); + t.String("status", 40).NotNull(); + t.Date("unpaid_on"); + t.Decimal("unpaid_fees").NotNull().Default(0m); + t.Int64("unpaid_entry_id"); + t.Int64("payment_id"); + t.AuditColumns(); + t.Index("ix_remittance_lines_remittance", "remittance_id"); + t.Index("ix_remittance_lines_item", "open_item_id"); + t.ForeignKey("fk_remittance_lines_remittance", "remittance_id", "remittances", ReferentialAction.Cascade); + t.ForeignKey("fk_remittance_lines_item", "open_item_id", "gl_open_items", ReferentialAction.Restrict); + t.ForeignKey("fk_remittance_lines_mandate", "mandate_id", "sdd_mandates", ReferentialAction.Restrict); + }); + + schema.CreateTable("bank_statements", t => + { + t.Id(); + t.Int64("bank_account_id").NotNull(); + t.String("format", 40).NotNull(); + t.String("file_name", 200); + t.Date("from_date").NotNull(); + t.Date("to_date").NotNull(); + t.Decimal("opening_balance"); + t.Decimal("closing_balance"); + t.Int32("movement_count").NotNull().Default(0); + t.Int64("attachment_id"); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_bank_statements_account", "bank_account_id", "to_date"); + t.ForeignKey("fk_bank_statements_bank", "bank_account_id", "bank_accounts", ReferentialAction.Restrict); + }); + + schema.CreateTable("bank_match_rules", t => + { + t.Id(); + t.String("name", 100).NotNull(); + t.String("pattern", 100).NotNull(); + t.String("direction", 40).NotNull(); + t.Int64("account_id").NotNull(); + t.String("template_code", 10); + t.String("entry_description", 200); + t.Bool("disabled").NotNull().Default(false); + t.Int32("uses").NotNull().Default(0); + t.DemoColumn(); + t.AuditColumns(); + t.ForeignKey("fk_bank_match_rules_account", "account_id", "gl_accounts", ReferentialAction.Restrict); + }); + + schema.CreateTable("bank_statement_lines", t => + { + t.Id(); + t.Int64("statement_id").NotNull(); + t.Int64("bank_account_id").NotNull(); + t.Date("booking_date").NotNull(); + t.Date("value_date"); + t.Decimal("amount").NotNull().Default(0m); + t.String("description", 500).NotNull(); + t.String("reference", 60); + t.String("counterparty_name", 140); + t.String("counterparty_iban", 34); + t.String("bank_code", 40); + t.String("fingerprint", 64).NotNull(); + t.String("status", 40).NotNull(); + t.String("match_kind", 40).NotNull(); + t.Int32("confidence").NotNull().Default(0); + t.String("proposal", 300); + t.String("targets", 300); + t.Int64("party_id"); + t.Int64("rule_id"); + t.Int64("payment_id"); + t.Int64("gl_entry_id"); + t.DateTimeUtc("matched_at"); + t.String("matched_by", 100); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_bank_statement_lines_fingerprint", "bank_account_id", "fingerprint"); + t.Index("ix_bank_statement_lines_date", "bank_account_id", "booking_date"); + t.Index("ix_bank_statement_lines_statement", "statement_id"); + t.ForeignKey("fk_bank_statement_lines_statement", "statement_id", "bank_statements", ReferentialAction.Cascade); + }); + + schema.CreateTable("dunning_levels", t => + { + t.Id(); + t.Int32("level").NotNull(); + t.Int32("days_after_due").NotNull(); + t.String("name", 100).NotNull(); + t.String("subject", 200).NotNull(); + t.Text("body").NotNull(); + t.String("channel", 60).NotNull(); + t.Bool("charge_interest").NotNull().Default(false); + t.String("action", 40).NotNull(); + t.Bool("automatic").NotNull().Default(false); + t.AuditColumns(); + t.Unique("ux_dunning_levels_level", "level"); + }); + + schema.CreateTable("dunning_letters", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.Int32("level").NotNull(); + t.Date("sent_on").NotNull(); + t.String("channel", 60).NotNull(); + t.String("recipients", 300); + t.String("subject", 200).NotNull(); + t.Int32("item_count").NotNull().Default(0); + t.Decimal("overdue_amount").NotNull().Default(0m); + t.Decimal("interest").NotNull().Default(0m); + t.String("status", 40).NotNull(); + t.Int64("attachment_id"); + t.Int64("mail_id"); + t.String("sent_by", 100); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_dunning_letters_party", "party_id", "sent_on"); + t.ForeignKey("fk_dunning_letters_party", "party_id", "parties", ReferentialAction.Restrict); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs index 32419c1..019f698 100644 --- a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs @@ -208,6 +208,7 @@ public sealed class BankAccountMap : EntityMap Map(x => x.Bic).MaxLength(11); Map(x => x.SiaCode).MaxLength(5); Map(x => x.CucCode).MaxLength(8); + Map(x => x.CreditorId).MaxLength(35); Map(x => x.AccountCode).MaxLength(20); } } diff --git a/src/Khaemhat.Data/CompanyDatabase/TreasuryMaps.cs b/src/Khaemhat.Data/CompanyDatabase/TreasuryMaps.cs new file mode 100644 index 0000000..4c5ce44 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/TreasuryMaps.cs @@ -0,0 +1,134 @@ +using Khaemhat.Core.Treasury; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to payments. +public sealed class PaymentMap : EntityMap +{ + /// Creates the map. + public PaymentMap() + { + ToTable("payments"); + Map(x => x.Reference).MaxLength(60); + Map(x => x.TemplateCode).MaxLength(10); + Map(x => x.Notes).MaxLength(500); + } +} + +/// Map of to payment_lines. +public sealed class PaymentLineMap : EntityMap +{ + /// Creates the map. + public PaymentLineMap() => ToTable("payment_lines"); +} + +/// Map of to remittances. +public sealed class RemittanceMap : EntityMap +{ + /// Creates the map. + public RemittanceMap() + { + ToTable("remittances"); + Map(x => x.MessageId).MaxLength(35); + Map(x => x.FileName).MaxLength(100); + Map(x => x.Notes).MaxLength(500); + } +} + +/// Map of to remittance_lines. +public sealed class RemittanceLineMap : EntityMap +{ + /// Creates the map. + public RemittanceLineMap() + { + ToTable("remittance_lines"); + Map(x => x.Iban).MaxLength(34); + Map(x => x.EndToEndId).MaxLength(35); + } +} + +/// Map of to sdd_mandates. +public sealed class SddMandateMap : EntityMap +{ + /// Creates the map. + public SddMandateMap() + { + ToTable("sdd_mandates"); + Map(x => x.Reference).MaxLength(35); + Map(x => x.Iban).MaxLength(34); + Map(x => x.Bic).MaxLength(11); + Map(x => x.Notes).MaxLength(200); + } +} + +/// Map of to bank_statements. +public sealed class BankStatementMap : EntityMap +{ + /// Creates the map. + public BankStatementMap() + { + ToTable("bank_statements"); + Map(x => x.FileName).MaxLength(200); + } +} + +/// Map of to bank_statement_lines. +public sealed class BankStatementLineMap : EntityMap +{ + /// Creates the map. + public BankStatementLineMap() + { + ToTable("bank_statement_lines"); + Map(x => x.Description).MaxLength(500); + Map(x => x.Reference).MaxLength(60); + Map(x => x.CounterpartyName).MaxLength(140); + Map(x => x.CounterpartyIban).MaxLength(34); + Map(x => x.BankCode).MaxLength(40); + Map(x => x.Fingerprint).MaxLength(64); + Map(x => x.Proposal).MaxLength(300); + Map(x => x.Targets).MaxLength(300); + Map(x => x.MatchedBy).MaxLength(100); + } +} + +/// Map of to bank_match_rules. +public sealed class BankMatchRuleMap : EntityMap +{ + /// Creates the map. + public BankMatchRuleMap() + { + ToTable("bank_match_rules"); + Map(x => x.Name).MaxLength(100); + Map(x => x.Pattern).MaxLength(100); + Map(x => x.TemplateCode).MaxLength(10); + Map(x => x.EntryDescription).MaxLength(200); + } +} + +/// Map of to dunning_levels. +public sealed class DunningLevelMap : EntityMap +{ + /// Creates the map. + public DunningLevelMap() + { + ToTable("dunning_levels"); + Map(x => x.Name).MaxLength(100); + Map(x => x.Subject).MaxLength(200); + Map(x => x.Channel).MaxLength(60); + } +} + +/// Map of to dunning_letters. +public sealed class DunningLetterMap : EntityMap +{ + /// Creates the map. + public DunningLetterMap() + { + ToTable("dunning_letters"); + Map(x => x.Channel).MaxLength(60); + Map(x => x.Recipients).MaxLength(300); + Map(x => x.Subject).MaxLength(200); + Map(x => x.SentBy).MaxLength(100); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Treasury.cs b/src/Khaemhat.Fiscal.Abstractions/Treasury.cs new file mode 100644 index 0000000..a0ace86 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/Treasury.cs @@ -0,0 +1,67 @@ +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Fiscal.Abstractions; + +/// +/// Writes the national remittance files the SEPA formats do not cover (Italy: RiBa in the CBI fixed-width layout). +/// SEPA credit transfers and direct debits are written by Khaemhat.Core.Treasury.SepaXmlWriter for every +/// country. +/// +public interface IRemittanceFileWriter +{ + /// Whether this writer writes a kind of remittance. + /// The kind. + /// when accepts it. + bool Supports(RemittanceKind kind); + + /// Writes the file. + /// The remittance. + /// The file. + /// A value cannot be written in the format. + BankFile Write(BankFileRemittance remittance); +} + +/// +/// Reads the national bank statement format of the country (Italy: CBI). CSV and camt.053 are read by +/// Khaemhat.Core.Treasury for every country. +/// +public interface IBankStatementReader +{ + /// The format read. + StatementFormat Format { get; } + + /// Whether the start of a file looks like this format. + /// The first bytes of the file (up to 4 KB). + /// when should be tried. + bool Recognizes(ReadOnlySpan head); + + /// Reads a statement. + /// The file. + /// The statement. + /// The file is not in the format. + StatementFile Read(Stream content); +} + +/// Late payment interest between companies (Italy: D.Lgs. 231/2002). +public interface ILatePaymentRules +{ + /// The yearly rate, in percent, that applies to the days of a half-year. + /// A day. + /// The reference rate of the half-year plus the margin. + decimal RateOn(DateOnly day); + + /// The law the interest comes from, for the letters (Italy: D.Lgs. 231/2002). + string LegalReference { get; } + + /// The fixed compensation for recovery costs, per invoice (Italy: 40 euro, art. 6). + decimal RecoveryCompensation { get; } +} + +/// Which remittance collects or pays the items of a payment method, by the code of the method in the pack. +public interface IRemittanceMethods +{ + /// The kind of remittance of a method. + /// The code of the method in the e-invoice (for Italy the MPxx codes). + /// The kind, or when the method does not go in remittances. + RemittanceKind? KindOf(string? methodCode); +} diff --git a/src/Khaemhat.Fiscal.Italy/CbiStatementReader.cs b/src/Khaemhat.Fiscal.Italy/CbiStatementReader.cs new file mode 100644 index 0000000..d58f970 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/CbiStatementReader.cs @@ -0,0 +1,232 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Core.Treasury; +using Khaemhat.Core.Validation; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Reads the CBI current account statement (rendicontazione movimenti di conto corrente, flow RH): records of +/// 120 characters, the RH header, the opening balance 61, each movement 62 with its description +/// lines 63, the closing balance 64 and the EF footer. +/// +/// +/// Positions are 1-based and inclusive, with position 1 a space and 2-3 the record type. Lines written without the +/// leading space (some banks trim it) are accepted, as are files without line breaks (records one after the other). +/// Amounts are 15 characters, either digits with two implied decimals or with the comma the bank writes; signs are +/// C (credit, money in) and D (debit, money out); dates are DDMMYY. +/// +/// RecordPositions read +/// RH4-8 sender ABI; 9-13 receiver SIA; 14-19 creation date; 20-39 support name. +/// 614-10 progressive; 52 CIN; 53-57 ABI; 58-62 CAB; 63-74 account; 75-77 currency; 78-83 +/// date of the opening balance; 84 sign; 85-99 opening balance; 100-101 country and 102-103 check digits of the +/// IBAN. +/// 624-10 progressive; 11-13 movement number; 14-19 value date; 20-25 booking date; 26 +/// sign; 27-41 amount; 42-43 CBI causale; 44-45 internal causale; 46-61 cheque number; 62-77 bank reference; 87-120 +/// description. +/// 634-10 progressive; 11-13 movement number; 14-120 more description, appended to the +/// movement before. +/// 644-10 progressive; 11-13 currency; 14-19 date of the closing balance; 20 sign; 21-35 +/// closing (book) balance. +/// EFend of the flow; nothing is read. +/// +/// The IBAN is rebuilt from country, check digits, CIN, ABI, CAB and account when they make a valid IBAN. A flow with +/// statements of two accounts is refused. +/// +public sealed class CbiStatementReader : IBankStatementReader +{ + private const int RecordLength = 120; + + /// + public StatementFormat Format => StatementFormat.Cbi; + + /// + public bool Recognizes(ReadOnlySpan head) + { + var text = Encoding.Latin1.GetString(head).TrimStart('', '\r', '\n'); + var end = text.IndexOfAny(['\r', '\n']); + var first = end < 0 ? text : text[..end]; + if (end < 0 && first.Length > RecordLength) + { + first = first[..RecordLength]; + } + + return (first.StartsWith(" RH", StringComparison.Ordinal) && first.Length == RecordLength) + || (first.StartsWith("RH", StringComparison.Ordinal) && first.Length is RecordLength or RecordLength - 1); + } + + /// + public StatementFile Read(Stream content) + { + ArgumentNullException.ThrowIfNull(content); + using var buffer = new MemoryStream(); + content.CopyTo(buffer); + var records = Records(Encoding.Latin1.GetString(buffer.ToArray())); + if (records.Count == 0 || records[0].Line[1..3] != "RH") + { + throw new BankFileException("The file is not a CBI statement: the first record is not RH."); + } + + string? iban = null; + string? currency = null; + decimal? opening = null; + decimal? closing = null; + DateOnly? from = null; + DateOnly? to = null; + var movements = new List(); + foreach (var (row, line) in records) + { + switch (line[1..3]) + { + case "61": + var accountIban = AccountIban(line); + if (iban is not null && accountIban is not null && iban != accountIban) + { + throw new BankFileException($"Row {row}: the flow has statements of two accounts ({iban}, {accountIban})."); + } + + iban ??= accountIban; + currency ??= Field(line, 75, 3) is { Length: > 0 } code ? code : null; + opening ??= Signed(line, 84, 85, row); + from ??= Date(Field(line, 78, 6), row); + break; + case "62": + var booking = Date(Field(line, 20, 6), row) ?? throw new BankFileException($"Row {row}: the movement has no booking date."); + var reference = Field(line, 62, 16); + var causale = Field(line, 42, 2); + movements.Add(new Movement( + booking, + Date(Field(line, 14, 6), row), + Signed(line, 26, 27, row), + new StringBuilder(Field(line, 87, 34)), + reference.Length == 0 ? null : reference, + causale.Length == 0 ? null : causale)); + break; + case "63": + if (movements.Count == 0) + { + throw new BankFileException($"Row {row}: a description record 63 comes before any movement."); + } + + movements[^1].Description.Append(' ').Append(Field(line, 14, 107)); + break; + case "64": + closing = Signed(line, 20, 21, row); + to = Date(Field(line, 14, 6), row) ?? to; + break; + default: + break; + } + } + + if (movements.Count > 0) + { + from ??= movements.Min(m => m.Booking); + to ??= movements.Max(m => m.Booking); + } + + return new StatementFile( + StatementFormat.Cbi, + iban, + currency, + from, + to, + opening, + closing, + [.. movements.Select(m => new StatementMovement( + m.Booking, + m.Value, + m.Amount, + string.Join(" ", m.Description.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries)), + m.Reference, + BankCode: m.Causale))]); + } + + // Records padded to 120 characters with the leading space restored; files without line breaks are cut every 120. + private static List<(int Row, string Line)> Records(string text) + { + var lines = text.Contains('\n', StringComparison.Ordinal) || text.Contains('\r', StringComparison.Ordinal) + ? text.Split(["\r\n", "\n", "\r"], StringSplitOptions.None) + : Enumerable.Range(0, (text.Length + RecordLength - 1) / RecordLength) + .Select(i => text.Substring(i * RecordLength, Math.Min(RecordLength, text.Length - (i * RecordLength)))) + .ToArray(); + var records = new List<(int, string)>(); + for (var i = 0; i < lines.Length; i++) + { + var line = lines[i].TrimStart(''); + if (line.Trim().Length == 0) + { + continue; + } + + if (line[0] != ' ') + { + line = " " + line; + } + + records.Add((i + 1, line.Length >= RecordLength ? line[..RecordLength] : line.PadRight(RecordLength))); + } + + return records; + } + + private static string Field(string line, int position, int length) => line.Substring(position - 1, length).Trim(); + + private static DateOnly? Date(string text, int row) + { + if (text.Length == 0 || text.All(c => c == '0')) + { + return null; + } + + return DateOnly.TryParseExact(text, "ddMMyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) + ? date + : throw new BankFileException($"Row {row}: '{text}' is not a date DDMMYY."); + } + + private static decimal Signed(string line, int signPosition, int amountPosition, int row) + { + var sign = line[signPosition - 1]; + if (sign is not ('C' or 'D')) + { + throw new BankFileException($"Row {row}: the sign at position {signPosition.ToString(CultureInfo.InvariantCulture)} is not C or D."); + } + + var amount = Amount(Field(line, amountPosition, 15), row); + return sign == 'D' ? -amount : amount; + } + + private static decimal Amount(string text, int row) + { + if (text.Contains(',', StringComparison.Ordinal)) + { + var value = text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.'); + if (decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var withComma)) + { + return withComma; + } + } + else if (text.Length > 0 && text.All(char.IsAsciiDigit)) + { + return decimal.Parse(text, NumberStyles.None, CultureInfo.InvariantCulture) / 100m; + } + + throw new BankFileException($"Row {row}: '{text}' is not an amount."); + } + + private static string? AccountIban(string line) + { + var bban = Field(line, 52, 1) + Field(line, 53, 5) + Field(line, 58, 5) + Field(line, 63, 12); + var iban = IbanValidator.Normalize(Field(line, 100, 2) + Field(line, 102, 2) + bban); + return IbanValidator.IsValid(iban) ? iban : null; + } + + private sealed record Movement( + DateOnly Booking, + DateOnly? Value, + decimal Amount, + StringBuilder Description, + string? Reference, + string? Causale); +} diff --git a/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv b/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv index 4d206da..2774f7d 100644 --- a/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv +++ b/src/Khaemhat.Fiscal.Italy/Data/piano-dei-conti.csv @@ -206,6 +206,7 @@ codice;descrizione;natura;tipo;voce_cee;partitario;iva 28.01.002;Interessi passivi su mutui;C;;C.17;; 28.01.003;Interessi sulla liquidazione IVA trimestrale;C;;C.17;; 28.01.004;Oneri finanziari diversi;C;;C.17;; +28.01.005;Perdite su cambi;C;;C.17-bis;; 29;Imposte sul reddito;C;;20;; 29.01;Imposte sul reddito dell'esercizio;C;;20;; 29.01.001;IRES dell'esercizio;C;;20;; @@ -231,6 +232,8 @@ codice;descrizione;natura;tipo;voce_cee;partitario;iva 32.01;Proventi finanziari;R;;C.16;; 32.01.001;Interessi attivi bancari;R;;C.16;; 32.01.002;Altri proventi finanziari;R;;C.16;; +32.01.003;Utili su cambi;R;;C.17-bis;; +32.01.004;Interessi di mora attivi;R;;C.16;; 90;Conti di apertura e chiusura;O;;;; 90.01;Conti di apertura e chiusura;O;;;; 90.01.001;Stato patrimoniale di apertura;O;;;; diff --git a/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs b/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs index cb71a0d..cf81448 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianLedgerTemplate.cs @@ -60,6 +60,27 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate /// The interest of quarterly VAT payers. public const string VatInterest = "28.01.003"; + /// Allowances received. + public const string AllowanceIncome = "31.01.004"; + + /// Bank fees. + public const string BankCharges = "21.03.011"; + + /// Effects and direct debits presented for collection. + public const string BillsForCollection = "05.02.001"; + + /// Advances of the bank on effects. + public const string BankAdvances = "13.01.001"; + + /// Exchange gains. + public const string ExchangeGain = "32.01.003"; + + /// Exchange losses. + public const string ExchangeLoss = "28.01.005"; + + /// Late payment interest charged to customers. + public const string LateInterest = "32.01.004"; + private readonly Lazy> _accounts = new(ReadAccounts); /// @@ -101,6 +122,13 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate PostingRole.StampDuty => StampDutyCost, PostingRole.Rounding => Rounding, PostingRole.VatSettlement => VatSettlement, + PostingRole.AllowanceIncome => AllowanceIncome, + PostingRole.BankCharges => BankCharges, + PostingRole.BillsForCollection => BillsForCollection, + PostingRole.BankAdvances => BankAdvances, + PostingRole.ExchangeGain => ExchangeGain, + PostingRole.ExchangeLoss => ExchangeLoss, + PostingRole.LateInterest => LateInterest, _ => null, }; @@ -157,11 +185,39 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate [ L(PostingRole.Bank, AccountSide.Debit, Bank), L(PostingRole.Customer, AccountSide.Credit, Customers), + L(PostingRole.Rounding, AccountSide.Debit, Rounding, "Abbuono passivo"), + L(PostingRole.ExchangeLoss, AccountSide.Debit, ExchangeLoss, "Differenza cambio"), + L(PostingRole.BankCharges, AccountSide.Debit, BankCharges, "Spese bancarie"), ]), new("PAG", "Pagamento a fornitore", JournalArea.Treasury, null, OpensItems: false, Reverses: false, [ L(PostingRole.Supplier, AccountSide.Debit, Suppliers), L(PostingRole.Bank, AccountSide.Credit, Bank), + L(PostingRole.AllowanceIncome, AccountSide.Credit, AllowanceIncome, "Abbuono attivo"), + L(PostingRole.ExchangeGain, AccountSide.Credit, ExchangeGain, "Differenza cambio"), + L(PostingRole.BankCharges, AccountSide.Debit, BankCharges, "Spese bancarie"), + ]), + new("DIST", "Presentazione effetti e addebiti SEPA", JournalArea.Treasury, null, OpensItems: false, Reverses: false, + [ + L(PostingRole.BillsForCollection, AccountSide.Debit, BillsForCollection), + L(PostingRole.Customer, AccountSide.Credit, Customers), + ]), + new("ANT", "Anticipo salvo buon fine", JournalArea.Treasury, null, OpensItems: false, Reverses: false, + [ + L(PostingRole.Bank, AccountSide.Debit, Bank), + L(PostingRole.BankAdvances, AccountSide.Credit, BankAdvances), + ]), + new("ACCR", "Accredito effetti a scadenza", JournalArea.Treasury, null, OpensItems: false, Reverses: false, + [ + L(PostingRole.Bank, AccountSide.Debit, Bank), + L(PostingRole.BankAdvances, AccountSide.Debit, BankAdvances), + L(PostingRole.BillsForCollection, AccountSide.Credit, BillsForCollection), + ]), + new("INS", "Effetto insoluto", JournalArea.Treasury, null, OpensItems: false, Reverses: false, + [ + L(PostingRole.Customer, AccountSide.Debit, Customers), + L(PostingRole.Bank, AccountSide.Credit, Bank), + L(PostingRole.BillsForCollection, AccountSide.Credit, BillsForCollection), ]), new("RIT", "Ritenuta d'acconto operata", JournalArea.Taxes, null, OpensItems: false, Reverses: false, [ diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index be01d51..2996c89 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -15,6 +15,8 @@ public sealed class ItalyFiscalPack : FiscalPackBase public ItalyFiscalPack() { AddFeature(new FatturaPaFormat()); + AddFeature(new LatePaymentRulesIt()); + AddFeature(new RemittanceMethodsIt()); AddFeature(new FatturaPaReader()); AddFeature(new IncomingInvoiceRulesIt()); AddFeature(new SelfInvoiceRulesIt()); @@ -27,6 +29,8 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new ItalianLedgerTemplate()); AddFeature(new VatSettlementRulesIt()); AddFeature(new LipeWriter()); + AddFeature(new RibaCbiWriter()); + AddFeature(new CbiStatementReader()); // 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/LatePaymentRulesIt.cs b/src/Khaemhat.Fiscal.Italy/LatePaymentRulesIt.cs new file mode 100644 index 0000000..3405f28 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/LatePaymentRulesIt.cs @@ -0,0 +1,56 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Late payment interest between companies (D.Lgs. 9 ottobre 2002, n. 231, art. 5): the reference rate is the rate of +/// the main refinancing operations of the European Central Bank on the first calendar day of the half-year, published +/// by the Ministry of Economy in the Gazzetta Ufficiale, plus eight points. The table below must get a row every +/// half-year (ADR 0038); after its last row the last rate applies. +/// +public sealed class LatePaymentRulesIt : ILatePaymentRules +{ + /// The points added to the reference rate. + public const decimal Margin = 8m; + + /// The ECB main refinancing rate on the first day of each half-year, in percent. + private static readonly (DateOnly From, decimal Rate)[] ReferenceRates = + [ + (new DateOnly(2022, 1, 1), 0.00m), + (new DateOnly(2022, 7, 1), 0.00m), + (new DateOnly(2023, 1, 1), 2.50m), + (new DateOnly(2023, 7, 1), 4.00m), + (new DateOnly(2024, 1, 1), 4.50m), + (new DateOnly(2024, 7, 1), 4.25m), + (new DateOnly(2025, 1, 1), 3.15m), + (new DateOnly(2025, 7, 1), 2.15m), + (new DateOnly(2026, 1, 1), 2.15m), + (new DateOnly(2026, 7, 1), 2.40m), + ]; + + /// + public string LegalReference => "D.Lgs. 231/2002"; + + /// + public decimal RecoveryCompensation => 40m; + + /// The reference rate of the half-year of a day, without the margin. + /// A day. + /// The rate in percent. + public static decimal ReferenceRateOn(DateOnly day) + { + var rate = ReferenceRates[0].Rate; + foreach (var (from, value) in ReferenceRates) + { + if (from <= day) + { + rate = value; + } + } + + return rate; + } + + /// + public decimal RateOn(DateOnly day) => ReferenceRateOn(day) + Margin; +} diff --git a/src/Khaemhat.Fiscal.Italy/RemittanceMethodsIt.cs b/src/Khaemhat.Fiscal.Italy/RemittanceMethodsIt.cs new file mode 100644 index 0000000..54f8431 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/RemittanceMethodsIt.cs @@ -0,0 +1,21 @@ +using Khaemhat.Core.Treasury; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The Italian payment methods (codes MPxx of FatturaPA) that go in remittances: RiBa (MP12), SEPA direct +/// debits core (MP19, MP20) and B2B (MP21), credit transfers for the payments to suppliers (MP05). +/// +public sealed class RemittanceMethodsIt : IRemittanceMethods +{ + /// + public RemittanceKind? KindOf(string? methodCode) => methodCode switch + { + "MP12" => RemittanceKind.Riba, + "MP19" or "MP20" => RemittanceKind.SddCore, + "MP21" => RemittanceKind.SddB2b, + "MP05" => RemittanceKind.SepaCreditTransfer, + _ => null, + }; +} diff --git a/src/Khaemhat.Fiscal.Italy/RibaCbiWriter.cs b/src/Khaemhat.Fiscal.Italy/RibaCbiWriter.cs new file mode 100644 index 0000000..5062930 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/RibaCbiWriter.cs @@ -0,0 +1,253 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Core.Treasury; +using Khaemhat.Core.Validation; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Writes a remittance of bank receipts (ricevute bancarie) in the CBI fixed-width layout "Ricevute bancarie": records +/// of 120 characters separated by CRLF, the IB header, for each receipt the records 14, 20, +/// 30, 40, 50, 51, 70, and the EF footer. Texts are upper case ASCII (accents +/// dropped) padded with spaces, numbers are zero padded, dates are DDMMYY and amounts are in cents. +/// +/// +/// Positions are 1-based and inclusive; position 1 of every record is a space and positions 2-3 the record type. +/// Fields not listed are spaces. +/// +/// RecordPositions +/// IB4-8 sender SIA code; 9-13 receiving bank ABI (from the company IBAN); 14-19 creation +/// date; 20-39 support name (the message id); 114 currency E. +/// 144-10 progressive; 23-28 due date; 29-33 causale 30000; 34-46 amount in cents; +/// 47 sign -; 48-52 ABI, 53-57 CAB, 58-69 account of the company; 70-74 ABI, 75-79 CAB of the debtor bank; 92-96 +/// company SIA code; 97 code type 4; 98-113 debtor code; 120 currency E. +/// 204-10 progressive; 11-34 creditor name; 35-58 street; 59-82 postal code, town and +/// province; 83-106 VAT number or tax code. +/// 304-10 progressive; 11-40 and 41-70 debtor name; 71-86 debtor tax code. +/// 404-10 progressive; 11-40 debtor street; 41-45 postal code; 46-67 town; 69-70 province; +/// 71-120 debtor bank and branch. +/// 504-10 progressive; 11-50 and 51-90 reference (the invoices paid); 101-116 creditor +/// tax code. +/// 514-10 progressive; 11-20 receipt number; 21-40 creditor name. +/// 704-10 progressive (closing record of the receipt). +/// EF4-8 sender SIA; 9-13 receiving ABI; 14-19 creation date; 20-39 support name; 46-52 +/// number of receipts; 53-67 total of the receipts in cents (the "negative" amounts, as the sign of record 14); 68-82 +/// zeros (positive amounts); 83-89 number of records, header and footer included; 114 currency E. +/// +/// +public sealed class RibaCbiWriter : IRemittanceFileWriter +{ + /// The length of every record. + public const int RecordLength = 120; + + /// The media type of the file. + public const string ContentType = "text/plain"; + + private const long MaximumItemCents = 9_999_999_999_999L; + private const long MaximumTotalCents = 999_999_999_999_999L; + + /// + public bool Supports(RemittanceKind kind) => kind == RemittanceKind.Riba; + + /// + public BankFile Write(BankFileRemittance remittance) + { + ArgumentNullException.ThrowIfNull(remittance); + if (remittance.Kind != RemittanceKind.Riba) + { + throw new BankFileException($"A remittance of kind {remittance.Kind} is not a remittance of bank receipts."); + } + + var company = remittance.Company ?? throw new BankFileException("The remittance has no company."); + if (remittance.Items is null || remittance.Items.Count == 0) + { + throw new BankFileException("The remittance has no receipts."); + } + + var sia = Text(company.SiaCode, 5).Trim(); + if (sia.Length != 5) + { + throw new BankFileException("The company has no SIA code (five characters) for bank receipts."); + } + + var companyIban = IbanValidator.Normalize(company.Iban); + if (!IbanValidator.IsValid(companyIban) || !companyIban.StartsWith("IT", StringComparison.Ordinal)) + { + throw new BankFileException($"The company account '{companyIban}' is not a valid Italian IBAN."); + } + + var (abi, cab, account) = BankCodes(companyIban); + var date = Date(DateOnly.FromDateTime(remittance.CreatedAt)); + var support = Text(remittance.MessageId, 20); + var creditorName = Text(company.Name, 24); + var creditorTaxCode = Text(company.TaxCode, 16); + + var records = new List(); + records.Add(Record("IB", (4, sia), (9, abi), (14, date), (20, support), (114, "E"))); + + long total = 0; + for (var i = 0; i < remittance.Items.Count; i++) + { + var item = remittance.Items[i]; + var progressive = Number(i + 1, 7); + var where = string.Create(CultureInfo.InvariantCulture, $"receipt {i + 1}"); + var cents = decimal.ToInt64(Math.Round(item.Amount * 100m, 0, MidpointRounding.AwayFromZero)); + if (cents <= 0) + { + throw new BankFileException($"The amount of {where} must be positive."); + } + + if (cents > MaximumItemCents) + { + throw new BankFileException($"The amount of {where} does not fit the 13 digits of the record."); + } + + total += cents; + if (total > MaximumTotalCents) + { + throw new BankFileException("The total of the remittance does not fit the 15 digits of the footer."); + } + + var debtorIban = IbanValidator.Normalize(item.Iban); + if (debtorIban.Length == 0) + { + throw new BankFileException($"The debtor of {where} has no IBAN (ABI and CAB of the paying bank)."); + } + + if (!IbanValidator.IsValid(debtorIban) || !debtorIban.StartsWith("IT", StringComparison.Ordinal)) + { + throw new BankFileException($"The IBAN of the debtor of {where} is not a valid Italian IBAN."); + } + + var (debtorAbi, debtorCab, _) = BankCodes(debtorIban); + var debtorName = Text(item.CounterpartyName, 60); + if (debtorName.Trim().Length == 0) + { + throw new BankFileException($"The debtor of {where} has no name."); + } + + var reference = Text(item.Reference, 80); + var place = string.Join(" ", new[] { Text(company.PostalCode, 5).Trim(), Text(company.City, 24).Trim(), Text(company.Province, 2).Trim() }.Where(s => s.Length > 0)); + + records.Add(Record( + "14", + (4, progressive), + (23, Date(item.DueDate)), + (29, "30000"), + (34, Number(cents, 13)), + (47, "-"), + (48, abi), + (53, cab), + (58, account), + (70, debtorAbi), + (75, debtorCab), + (92, sia), + (97, "4"), + (98, Text(item.CounterpartyCode, 16)), + (120, "E"))); + records.Add(Record( + "20", + (4, progressive), + (11, creditorName), + (35, Text(company.Address, 24)), + (59, Text(place, 24)), + (83, creditorTaxCode))); + records.Add(Record( + "30", + (4, progressive), + (11, Cut(debtorName, 0, 30)), + (41, Cut(debtorName, 30, 30)), + (71, Text(item.CounterpartyTaxCode, 16)))); + records.Add(Record( + "40", + (4, progressive), + (11, Text(item.Address, 30)), + (41, Text(item.PostalCode, 5)), + (46, Text(item.City, 22)), + (69, Text(item.Province, 2)), + (71, Text(item.BankName, 50)))); + records.Add(Record( + "50", + (4, progressive), + (11, Cut(reference, 0, 40)), + (51, Cut(reference, 40, 40)), + (101, creditorTaxCode))); + records.Add(Record( + "51", + (4, progressive), + (11, Number(item.Number, 10)), + (21, Text(company.Name, 20)))); + records.Add(Record("70", (4, progressive))); + } + + var count = remittance.Items.Count; + records.Add(Record( + "EF", + (4, sia), + (9, abi), + (14, date), + (20, support), + (46, Number(count, 7)), + (53, Number(total, 15)), + (68, Number(0, 15)), + (83, Number(records.Count + 1, 7)), + (114, "E"))); + + var text = string.Join("\r\n", records) + "\r\n"; + var name = string.Concat(Text(remittance.MessageId, 35).Trim().Select(c => char.IsAsciiLetterOrDigit(c) || c == '-' ? c : '_')); + return new BankFile($"RIBA_{name}.txt", ContentType, Encoding.ASCII.GetBytes(text)); + } + + /// + /// A text as the CBI records want it: upper case ASCII, accents dropped, other characters replaced by spaces, padded + /// with spaces or cut to a length. + /// + /// The text. + /// The length of the field. + /// The field, exactly characters. + public static string Text(string? value, int length) + { + var builder = new StringBuilder(); + foreach (var c in (value ?? string.Empty).Normalize(NormalizationForm.FormD).ToUpperInvariant()) + { + if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark) + { + continue; + } + + var next = c is >= ' ' and <= '~' ? c : ' '; + if (next == ' ' && (builder.Length == 0 || builder[^1] == ' ')) + { + continue; + } + + builder.Append(next); + } + + var text = builder.ToString().TrimEnd(); + return text.Length >= length ? text[..length] : text.PadRight(length); + } + + private static (string Abi, string Cab, string Account) BankCodes(string iban) => (iban[5..10], iban[10..15], iban[15..27]); + + private static string Cut(string text, int start, int length) => text.Substring(start, length); + + private static string Number(long value, int length) => value.ToString(CultureInfo.InvariantCulture).PadLeft(length, '0'); + + private static string Date(DateOnly date) => date.ToString("ddMMyy", CultureInfo.InvariantCulture); + + private static string Record(string type, params (int Position, string Value)[] fields) + { + var record = new char[RecordLength]; + Array.Fill(record, ' '); + record[1] = type[0]; + record[2] = type[1]; + foreach (var (position, value) in fields) + { + value.CopyTo(0, record, position - 1, Math.Min(value.Length, RecordLength - position + 1)); + } + + return new string(record); + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/CashFlowPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/CashFlowPage.razor new file mode 100644 index 0000000..efa7565 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/CashFlowPage.razor @@ -0,0 +1,203 @@ +@page "/scadenzario/flusso-di-cassa" +@attribute [Authorize] +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject CashFlowService CashFlow + +@* The cash flow forecast (SPEC §11.8, report "flusso di cassa 90 gg"): the money of the banks and the cash today and, + week by week or month by month, what comes in and goes out from the open items, the remittances presented, the + orders not yet invoiced, the recurring entries and the taxes still to pay. Overdue items fall in the first period. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.CashFlow.Title"]
+

@T["Treasury.CashFlow.Heading"]

+
@T["Treasury.CashFlow.Hint"]
+
+
+ + +
+ + + @foreach (var source in Enum.GetValues()) + { + + } +
+
+ + @if (_forecast is { } f) + { + var lowest = f.Periods.Count == 0 ? f.Opening : Math.Min(f.Opening, f.Periods.Min(p => p.Balance)); + + +
+ + + + + + + + + + + + + @foreach (var p in f.Periods) + { + var width = BarWidth(f, p.Balance); + + + + + + + + } + +
@T["Treasury.CashFlow.Period"]@T["Treasury.Reconciliation.In"]@T["Treasury.Reconciliation.Out"]@T["Treasury.CashFlow.Balance"]@T["Treasury.CashFlow.Chart"]
@T.Date(p.From) – @T.Date(p.To)@(p.In != 0m ? T.Money(p.In) : null)@(p.Out != 0m ? T.Money(p.Out) : null)@T.Money(p.Balance)
+
+ + + + @foreach (var a in f.Accounts) + { + + + + + } + + + + + + + +
@a.Name@T.Money(a.Balance)
@T["Treasury.Fields.Total"]@T.Money(f.Opening)
+
+
+ + + @if (f.Movements.Count == 0) + { +

@T["Treasury.CashFlow.NoMovements"]

+ } + else + { +
+ + + + + + + + + + + @foreach (var m in f.Movements) + { + + + + + + + } + +
@T["Treasury.Fields.Date"]@T["Treasury.CashFlow.Source"]@T["Treasury.Reconciliation.Description"]@T["Treasury.Fields.Amount"]
@T.Date(m.Date)@T[TreasuryScreens.EnumKey(m.Source)]@m.Label@T.Money(m.Amount)
+
+ } +
+ } +
+ +@code { + private int _days = 90; + private int _period = 7; + private readonly HashSet _sources = [.. Enum.GetValues()]; + private CashFlowForecast? _forecast; + + private IReadOnlyList> DayChoices => + [.. new[] { 30, 60, 90, 180, 365 }.Select(d => new KhOption(d, T.Format("Treasury.CashFlow.DaysText", d)))]; + + private IReadOnlyList> PeriodChoices => + [ + new(7, T["Treasury.CashFlow.Weeks"]), + new(30, T["Treasury.CashFlow.Months"]), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + await LoadAsync(); + } + } + + /// + /// The length of the bar of a balance, between the lowest and the highest of the forecast: the balances change little + /// against the money in the bank, so bars from zero would all look the same. + /// + private static int BarWidth(CashFlowForecast forecast, decimal balance) + { + var low = Math.Min(forecast.Opening, forecast.Periods.Min(p => p.Balance)); + var high = Math.Max(forecast.Opening, forecast.Periods.Max(p => p.Balance)); + return high == low ? 100 : (int)Math.Round(10m + ((balance - low) / (high - low) * 90m)); + } + + private IReadOnlyList Stats(CashFlowForecast f, decimal lowest) => + [ + new(T["Treasury.CashFlow.Today"], T.Money(f.Opening)), + new(T["Treasury.CashFlow.TotalIn"], T.Money(f.Periods.Sum(p => p.In)), KhTone.Ok), + new(T["Treasury.CashFlow.TotalOut"], T.Money(f.Periods.Sum(p => p.Out)), KhTone.Warning), + new(T["Treasury.CashFlow.End"], T.Money(f.Periods.Count == 0 ? f.Opening : f.Periods[^1].Balance)), + new(T["Treasury.CashFlow.Lowest"], T.Money(lowest), lowest < 0m ? KhTone.Error : KhTone.Neutral), + ]; + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _forecast = await CashFlow.ForecastAsync(actor, company, _days, _sources, _period); + } + } + + private async Task SetDaysAsync(int days) + { + _days = days; + await LoadAsync(); + } + + private async Task SetPeriodAsync(int period) + { + _period = period; + await LoadAsync(); + } + + private async Task ToggleAsync(CashFlowSource source, bool on) + { + if (on) + { + _sources.Add(source); + } + else + { + _sources.Remove(source); + } + + await LoadAsync(); + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/DunningPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/DunningPage.razor new file mode 100644 index 0000000..17d3e8e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/DunningPage.razor @@ -0,0 +1,370 @@ +@page "/scadenzario/solleciti" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject DunningService Dunning +@inject ToastService Toasts +@inject DialogService Dialogs +@inject IJSRuntime JS + +@* The reminders (SPEC §11.8, mockup 056): the customers with items past due by more days than the next level asks, + public administrations and disputed items left out; the level, the channel and the late interest of D.Lgs. + 231/2002; the letters sent by e-mail or PEC with the PDF attached, the third level that blocks the customer, the + history of what was sent. The scheduled task "Solleciti automatici" sends the levels marked automatic. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Dunning.Title"]
+

@T["Treasury.Dunning.Heading"]

+
+
+ @if (CanWrite) + { +
+ + +
+ } +
+ + + + + + @if (_tab == "proposal") + { + + @T["Treasury.Dunning.Rule"] + + @if (_proposal.Count == 0) + { +

@T["Treasury.Dunning.Nothing"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var p in _proposal) + { + + + + + + + + + + + + } + +
@T["Treasury.Fields.Customer"]@T["Treasury.Dunning.Items"]@T["Treasury.Schedule.Overdue"]@T["Treasury.Dunning.MaxDays"]@T["Treasury.Dunning.LastSent"]@T["Treasury.Dunning.NextLevel"]@T["Treasury.Dunning.Channel"]@T["Treasury.Statement.Interest"]@T["Treasury.Dunning.Include"]
@p.PartyName @(p.Blocked ? T["Treasury.Dunning.Blocked"] : null)@p.Items.Count@T.Money(p.Overdue)@p.MaxDays@(p.LastSent is { } last ? p.CurrentLevel + " · " + T.Date(last) : "—") + @if (p.Level is { } level) + { + @T.Format("Treasury.Dunning.Level", level.Level) + } + else + { + @T["Treasury.Dunning.Waiting"] + } + @(p.Level is { } l ? TreasuryScreens.ChannelText(T, l.Channel) : "—") @(p.Pec ?? p.Email)@T.Money(p.Interest) + @if (p.Level is not null) + { + var on = _included.Contains(p.PartyId); + + } +
+
+ } +
+
+ + + + + + + + + + + + + + + + + @foreach (var level in _levels) + { + + + + + + + + + + + } + +
@T["Treasury.Dunning.LevelColumn"]@T["Treasury.Dunning.After"]@T["Treasury.Dunning.Template"]@T["Treasury.Dunning.Channel"]@T["Treasury.Statement.Interest"]@T["Treasury.Dunning.Action"]@T["Treasury.Dunning.Automatic"]
@level.Level@level.DaysAfterDue@level.Name@TreasuryScreens.ChannelText(T, level.Channel)@T[level.ChargeInterest ? "Treasury.Dunning.InterestYes" : "Treasury.Dunning.InterestNo"]@T[TreasuryScreens.EnumKey(level.Action)]@T[level.Automatic ? "Common.Yes" : "Common.No"] + @if (CanWrite) + { + + } +
+
@T["Treasury.Dunning.Placeholders"]
+
+ } + else + { + + @if (_history.Count == 0) + { +

@T["Treasury.Dunning.NoHistory"]

+ } + else + { + + + + + + + + + + + + + + + + + @foreach (var row in _history) + { + var l = row.Letter; + + + + + + + + + + + + + } + +
@T["Treasury.Fields.Date"]@T["Treasury.Fields.Customer"]@T["Treasury.Dunning.LevelColumn"]@T["Treasury.Dunning.Channel"]@T["Treasury.Dunning.Recipients"]@T["Treasury.Dunning.Items"]@T["Treasury.Schedule.Overdue"]@T["Treasury.Statement.Interest"]@T["Treasury.Fields.Status"]@T["Treasury.Dunning.SentBy"]
@T.Date(l.SentOn)@row.PartyName@l.Level@TreasuryScreens.ChannelText(T, l.Channel)@l.Recipients@l.ItemCount@T.Money(l.OverdueAmount)@LedgerScreens.AmountText(T, l.Interest)@T[TreasuryScreens.EnumKey(l.Status)]@l.SentBy
+ } +
+ } + + + + @if (_level is { } level) + { +
+ + + + + + + + + + +
+

@T["Treasury.Dunning.Placeholders"]

+ } +
+
+ + +
+
+
+ +@code { + private string _tab = "proposal"; + private IReadOnlyList _proposal = []; + private IReadOnlyList _levels = []; + private IReadOnlyList _history = []; + private readonly HashSet _included = []; + private DunningLevel? _level; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private IReadOnlyList Tabs => + [ + new("proposal", "send", T["Treasury.Dunning.Proposal"], _proposal.Count(p => p.Level is not null)), + new("history", "clock", T["Treasury.Dunning.History"]), + ]; + + + private IReadOnlyList> Actions => TreasuryScreens.Choices(T); + + private IReadOnlyList Stats + { + get + { + var last = _history.Count == 0 ? null : _history[0].Letter; + return + [ + new(T["Treasury.Dunning.Customers"], _proposal.Count.ToString(T.Culture)), + new(T["Treasury.Dunning.OverdueTotal"], T.Money(_proposal.Sum(p => p.Overdue)), KhTone.Error), + new(T["Treasury.Dunning.Today"], _proposal.Count(p => p.Level is not null).ToString(T.Culture), KhTone.Warning), + new(T["Treasury.Dunning.LastRun"], last is null ? "—" : T.Date(last.SentOn) + " · " + _history.Count(h => h.Letter.SentOn == last.SentOn)), + new(T["Treasury.Dunning.Schedule"], T["Treasury.Dunning.ScheduleText"]), + ]; + } + } + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _levels = await Dunning.LevelsAsync(actor, company); + _proposal = await Dunning.ProposalAsync(actor, company); + _history = await Dunning.HistoryAsync(actor, company); + _included.Clear(); + _included.UnionWith(_proposal.Where(p => p.Level is not null).Select(p => p.PartyId)); + } + + private async Task SetTabAsync(string tab) + { + _tab = tab; + await LoadAsync(); + } + + private void Toggle(long partyId, bool on) + { + if (on) + { + _included.Add(partyId); + } + else + { + _included.Remove(partyId); + } + } + + private async Task PreviewAsync() => await RunAsync(async (actor, company) => + { + if (_proposal.FirstOrDefault(p => _included.Contains(p.PartyId)) is { } first) + { + await LedgerScreens.DownloadAsync(JS, await Dunning.PreviewAsync(actor, company, first.PartyId)); + } + }); + + private async Task SendAsync() + { + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Dunning.SendTitle"], T.Format("Treasury.Dunning.SendText", _included.Count), T["Treasury.Dunning.SendTitle"], T["Common.Cancel"]))) + { + return; + } + + await RunAsync(async (actor, company) => + { + var run = await Dunning.SendAsync(actor, company, [.. _included]); + Toasts.Show(run.Skipped.Count == 0 ? ToastKind.Success : ToastKind.Warning, T.Format("Treasury.Dunning.Sent", run.Sent, run.Letters), + run.Skipped.Count == 0 ? null : string.Join("; ", run.Skipped.Select(s => s.Party + ": " + (T.Contains(s.Reason) ? T[s.Reason] : s.Reason)))); + if (run.Pdf is { } pdf) + { + await LedgerScreens.DownloadAsync(JS, pdf); + } + + await LoadAsync(); + }); + } + + private void OpenLevel(DunningLevel level) => _level = new DunningLevel + { + Id = level.Id, + Level = level.Level, + DaysAfterDue = level.DaysAfterDue, + Name = level.Name, + Subject = level.Subject, + Body = level.Body, + Channel = level.Channel, + ChargeInterest = level.ChargeInterest, + Action = level.Action, + Automatic = level.Automatic, + }; + + private async Task SaveLevelAsync() => await RunAsync(async (actor, company) => + { + if (_level is { } level) + { + await Dunning.SaveLevelAsync(actor, company, level); + _level = null; + Toasts.Show(ToastKind.Success, T["Treasury.Saved"], null); + 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["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/FinanceGuard.razor b/src/Khaemhat.Web/Components/Pages/Treasury/FinanceGuard.razor new file mode 100644 index 0000000..8ccd736 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/FinanceGuard.razor @@ -0,0 +1,62 @@ +@using Khaemhat.Application.Modules +@inject ShellSession Session + +@* What every page of the schedule checks first: an open company, the module FIN in the licence and the permission. *@ +@if (!_loaded) +{ +

@T["Common.Loading"]

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

@T["Treasury.NoCompany"]

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

@T["Treasury.NoModule.Title"]

+

@T["Treasury.NoModule.Lead"]

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

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+ @T["Common.BackHome"] +
+} +else +{ + @ChildContent +} + +@code { + private bool _loaded; + + /// The permission the page needs. + [Parameter, EditorRequired] + public string Permission { get; set; } = string.Empty; + + /// The page. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// Whether the page may load its data: company, licence and permission. + /// The session. + /// The permission. + /// True when it may. + public static bool Allowed(ShellSession session, string permission) => + session is { Actor: not null, Company: not null } && session.Licenses.IsModuleActive(ModuleCodes.Finance) && session.Permissions.Allows(permission); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/MandatesPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/MandatesPage.razor new file mode 100644 index 0000000..7dd839d --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/MandatesPage.razor @@ -0,0 +1,217 @@ +@page "/scadenzario/mandati" +@attribute [Authorize] +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Parties +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject MandateService Mandates +@inject PartyService Parties +@inject ToastService Toasts +@inject DialogService Dialogs +@inject TimeProvider Clock + +@* The SEPA direct debit mandates of the customers (SPEC §11.8, mockup 055): the unique reference, the signature, the + scheme Core or B2B, the account of the debtor; a direct debit remittance takes only the items of customers with a + valid mandate, and the first collection of each mandate goes out as FRST, the next ones as RCUR. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Mandates.Title"]
+

@T["Treasury.Mandates.Heading"]

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

@T["Treasury.Mandates.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var m = row.Mandate; + + + + + + + + + + + } + +
@T["Treasury.Fields.Customer"]@T["Treasury.Mandates.Reference"]@T["Treasury.Mandates.Signed"]@T["Treasury.Mandates.Scheme"]@T["Treasury.Fields.Iban"]@T["Treasury.Mandates.LastCollection"]@T["Treasury.Fields.Status"]
@row.PartyName @row.PartyCode@m.Reference@T.Date(m.SignatureDate)@T[TreasuryScreens.EnumKey(m.Scheme)] @(m.OneOff ? "· " + T["Treasury.Mandates.OneOff"] : null)@m.Iban@(m.LastCollectionDate is { } last ? T.Date(last) : T["Treasury.Mandates.First"])@T[m.Revoked ? "Treasury.Mandates.Revoked" : "Treasury.Mandates.Active"] + @if (CanWrite) + { + + + + } +
+
+ } +
+ + + +
+ + + + + + + + +
+
+
+ + +
+
+
+ +@code { + private IReadOnlyList _rows = []; + private bool _busy; + private bool _editOpen; + private long? _editId; + private PartyRow? _party; + private string? _reference; + private DateOnly? _signed; + private SddScheme _scheme; + private bool _oneOff; + private string? _iban; + private string? _bic; + private string? _notes; + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private IReadOnlyList> Schemes => TreasuryScreens.Choices(T); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _rows = await Mandates.ListAsync(actor, company); + } + } + + 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, PartyArchive.Customers, text, cancellationToken) + : []; + + private async Task OpenEdit(MandateRow? row) + { + var m = row?.Mandate; + _editId = m?.Id; + _party = m is not null && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? (await Parties.RowsAsync(actor, company, [m.PartyId])).FirstOrDefault() + : null; + _reference = m?.Reference; + _signed = m?.SignatureDate ?? DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _scheme = m?.Scheme ?? SddScheme.Core; + _oneOff = m?.OneOff ?? false; + _iban = m?.Iban; + _bic = m?.Bic; + _notes = m?.Notes; + _editOpen = true; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + if (_party is { } party && _signed is { } signed) + { + await Mandates.SaveAsync(actor, company, new MandateInput(_editId, party.Id, _reference ?? string.Empty, signed, _scheme, _iban ?? string.Empty, _bic, _oneOff, _notes)); + _editOpen = false; + Toasts.Show(ToastKind.Success, T["Treasury.Saved"], null); + await LoadAsync(); + } + }); + + private async Task RevokeAsync(MandateRow row) => await RunAsync(async (actor, company) => + { + await Mandates.RevokeAsync(actor, company, row.Mandate.Id, !row.Mandate.Revoked); + await LoadAsync(); + }); + + private async Task DeleteAsync(MandateRow row) + { + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Mandates.Delete"], T.Format("Treasury.Mandates.DeleteText", row.Mandate.Reference), T["Treasury.Mandates.Delete"], T["Common.Cancel"], Danger: true))) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Mandates.DeleteAsync(actor, company, row.Mandate.Id); + 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["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/PaymentDialog.razor b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentDialog.razor new file mode 100644 index 0000000..1d5c271 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentDialog.razor @@ -0,0 +1,180 @@ +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Accounting +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject PaymentService Payments +@inject ToastService Toasts +@inject TimeProvider Clock + +@* Record a collection or a payment on the items chosen in the schedule (SPEC §11.8, mockup 054): the amount of each + item, an allowance that closes it for less, the fees of the bank; the entry is written by the treasury with the + template of collections or payments and the items are settled. *@ + + +
+ + + + + + + + +
+

@T["Treasury.Payment.Items"]

+
+ + + + + + + + + + + + + + @foreach (var line in _lines) + { + var item = line.Row.Item; + + + + + + + + + + } + + + + + + + + + + +
@T["Treasury.Fields.Document"]@T["Treasury.Fields.Installment"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Residual"]@T[Receipt ? "Treasury.Payment.Collected" : "Treasury.Payment.Paid"]@T["Treasury.Fields.Allowance"]@T["Treasury.Payment.ResidualAfter"]
@item.DocumentNumber@item.Installment@T.Date(item.DueDate)@T.Money(item.Residual)@T.Money(item.Residual - line.Amount - line.Allowance)
@T["Treasury.Fields.Total"]@T.Money(_lines.Sum(l => l.Row.Item.Residual))@T.Money(Total)@T.Money(_lines.Sum(l => l.Allowance))@T.Money(_lines.Sum(l => l.Row.Item.Residual - l.Amount - l.Allowance))
+
+
+ + @T.Format(Receipt ? "Treasury.Payment.EntryReceipt" : "Treasury.Payment.EntryPayment", T.Money(Total), T.Money(_lines.Sum(l => l.Allowance))) +
+
+
+ + +
+
+ +@code { + private List _lines = []; + private DateOnly? _date; + private long? _methodId; + private long? _bankId; + private string? _reference; + private decimal? _fees; + private string? _notes; + private bool _busy; + private IReadOnlyList? _shown; + + /// Whether the dialog is open. + [Parameter] + public bool Open { get; set; } + + /// The items to settle, all of one party and one direction. + [Parameter] + public IReadOnlyList Rows { get; set; } = []; + + /// The payment methods and the banks. + [Parameter] + public TreasuryChoices? Choices { get; set; } + + /// Closed without saving. + [Parameter] + public EventCallback OnClose { get; set; } + + /// Saved. + [Parameter] + public EventCallback OnSaved { get; set; } + + private bool Receipt => Rows.Count == 0 || Rows[0].Item.Direction == OpenItemDirection.Receivable; + + private string PartyName => Rows.Count == 0 ? string.Empty : (Rows[0].PartyCode is { } code ? code + " · " : string.Empty) + Rows[0].PartyName; + + private decimal Total => _lines.Sum(l => l.Amount); + + private IReadOnlyList> Methods => TreasuryScreens.MethodChoices(Choices?.Methods ?? []); + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(Choices?.Banks ?? []); + + /// + protected override void OnParametersSet() + { + if (!Open || ReferenceEquals(_shown, Rows)) + { + return; + } + + // A new set of items: the whole residual of each, the method of the first and the bank it names or the default. + _shown = Rows; + _lines = [.. Rows.Select(r => new Line(r) { Amount = r.Item.Residual })]; + _date = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _methodId = Rows.Select(r => r.Item.PaymentMethodId).FirstOrDefault(m => m is not null); + _bankId = Rows.Select(r => r.Item.BankAccountId).FirstOrDefault(b => b is not null) + ?? Choices?.Banks.FirstOrDefault(b => b.IsDefault)?.Id ?? Choices?.Banks.FirstOrDefault()?.Id; + _reference = null; + _fees = null; + _notes = null; + } + + private async Task CloseAsync() + { + _shown = null; + await OnClose.InvokeAsync(); + } + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _date is not { } date || Rows.Count == 0) + { + return; + } + + _busy = true; + try + { + var payment = await Payments.RegisterAsync(actor, company, new PaymentInput( + Receipt ? PaymentDirection.Receipt : PaymentDirection.Disbursement, Rows[0].Item.PartyId, date, _methodId, _bankId, _fees ?? 0m, _reference, _notes, + [.. _lines.Where(l => l.Amount != 0m || l.Allowance != 0m).Select(l => new PaymentLineInput(l.Row.Item.Id, l.Amount, l.Allowance))])); + Toasts.Show(ToastKind.Success, T[Receipt ? "Treasury.Payment.ReceiptSaved" : "Treasury.Payment.PaymentSaved"], T.Money(payment.Amount)); + _shown = null; + await OnSaved.InvokeAsync(payment); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } + + private sealed class Line(ScheduleRow row) + { + public ScheduleRow Row { get; } = row; + + public decimal Amount { get; set; } + + public decimal Allowance { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/PaymentsPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentsPage.razor new file mode 100644 index 0000000..07a21d5 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/PaymentsPage.razor @@ -0,0 +1,172 @@ +@page "/scadenzario/incassi" +@page "/scadenzario/pagamenti" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject PaymentService Payments +@inject ToastService Toasts +@inject DialogService Dialogs +@inject NavigationManager Navigation +@inject TimeProvider Clock + +@* The collections or the payments of a period (SPEC §11.8): who, when, how much, on which bank, the documents they + settled and their entry; cancelling one gives the items back and takes the entry away. Those born from a + remittance are cancelled from the remittance. *@ + + + +
+
+ +

@T[Title]

+
@T[Receipts ? "Treasury.Payments.ReceiptsHint" : "Treasury.Payments.PaymentsHint"]
+
+
+ +
+ + +
+ + + + @T.Format("Treasury.Payments.Total", _rows.Count, T.Money(_rows.Sum(r => r.Payment.Amount))) +
+ @if (_rows.Count == 0) + { +

@T["Treasury.Payments.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + @foreach (var row in _rows) + { + var p = row.Payment; + + + + + + + + + + + + + + } + +
@T["Treasury.Fields.Date"]@T[Receipts ? "Treasury.Fields.Customer" : "Treasury.Fields.Supplier"]@T["Treasury.Payments.Documents"]@T["Treasury.Fields.Reference"]@T["Treasury.Fields.Bank"]@T["Treasury.Payments.Origin"]@T["Treasury.Fields.Amount"]@T["Treasury.Fields.Allowance"]@T["Treasury.Fields.Fees"]@T["Treasury.Payments.Entry"]
@T.Date(p.PaymentDate)@row.PartyName@row.Documents@p.Reference@(row.Bank ?? T["Treasury.Payment.Cash"])@T[TreasuryScreens.EnumKey(p.Origin)]@T.Money(p.Amount)@LedgerScreens.AmountText(T, p.AllowanceAmount)@LedgerScreens.AmountText(T, p.Fees) + @if (p.GlEntryId is { } entry) + { + @row.EntryNumber + } + + @if (CanWrite && p.Origin != PaymentOrigin.Remittance) + { + + } +
+
+ } +
+
+ +@code { + private IReadOnlyList _rows = []; + private DateOnly? _from; + private DateOnly? _to; + private bool _busy; + + private bool Receipts => !Navigation.Uri.Contains("/pagamenti", StringComparison.OrdinalIgnoreCase); + + private string Title => Receipts ? "Treasury.Payments.Receipts" : "Treasury.Payments.Payments"; + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.PaymentWrite); + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _from ??= new DateOnly(today.Year, 1, 1); + _to ??= today.AddDays(30); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.PaymentRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to) + { + return; + } + + _rows = await Payments.ListAsync(actor, company, Receipts ? PaymentDirection.Receipt : PaymentDirection.Disbursement, from, to); + } + + private async Task SetFromAsync(DateOnly? date) + { + _from = date; + await LoadAsync(); + } + + private async Task SetToAsync(DateOnly? date) + { + _to = date; + await LoadAsync(); + } + + private async Task CancelAsync(PaymentRow row) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company + || !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Payments.Cancel"], T.Format("Treasury.Payments.CancelText", T.Money(row.Payment.Amount), row.PartyName), T["Treasury.Payments.Cancel"], T["Common.Cancel"]))) + { + return; + } + + _busy = true; + try + { + await Payments.CancelAsync(actor, company, row.Payment.Id); + Toasts.Show(ToastKind.Success, T["Treasury.Payments.Cancelled"], null); + await LoadAsync(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/ReconciliationPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/ReconciliationPage.razor new file mode 100644 index 0000000..1aac42a --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/ReconciliationPage.razor @@ -0,0 +1,604 @@ +@page "/scadenzario/riconciliazione" +@attribute [Authorize] +@using Khaemhat.Application.Ledger +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Accounting +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject BankReconciliationService Reconciliation +@inject ScheduleService Schedule +@inject PaymentService Payments +@inject LedgerService Ledger +@inject ToastService Toasts +@inject TimeProvider Clock + +@* Bank reconciliation (SPEC §11.8, mockup 057): the statement imported from CAMT.053, CBI or CSV, the movements + matched by amount, date, reference and name with open items, recorded payments, F24, remittance credits and unpaid + effects, or by the saved rules for the recurring ones; the proposals confirmed one by one or all those above 90%, + the rest matched by hand, posted to an account or ignored. The difference between the bank and the books is what is + still to reconcile. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Reconciliation.Title"]
+

@T["Treasury.Reconciliation.Title"]

+
+
+ + + +
+ + + + + + +
+ + + + @if (_tab == "lines") + { + + @if (_lines.Count == 0) + { +

@T["Treasury.Reconciliation.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var row in _lines) + { + var l = row.Line; + + + + + + + + + + + } + +
@T["Treasury.Fields.Date"]@T["Treasury.Reconciliation.Description"]@T["Treasury.Reconciliation.In"]@T["Treasury.Reconciliation.Out"]@T["Treasury.Fields.Status"]@T["Treasury.Reconciliation.Proposal"]@T["Treasury.Reconciliation.Confidence"]
@T.Date(l.BookingDate)@l.Description @row.PartyName@(l.Amount > 0m ? T.Money(l.Amount) : null)@(l.Amount < 0m ? T.Money(-l.Amount) : null)@T[TreasuryScreens.EnumKey(l.Status)] + @if (l.MatchKind != StatementMatchKind.None) + { + @T[TreasuryScreens.EnumKey(l.MatchKind)] · + } + @l.Proposal + @if (l.GlEntryId is { } entry) + { + @T["Treasury.Payments.Entry"] + } + @(l.Confidence > 0 ? l.Confidence + "%" : "—") + @if (l.Status == StatementLineStatus.Suggested) + { + + } + @if (l.Status is StatementLineStatus.ToMatch or StatementLineStatus.Suggested) + { + + + + + } + else + { + + } +
+
+ } +
@T["Treasury.Reconciliation.Footer"]
+
+ } + else if (_tab == "rules") + { + + + + + + @if (_rules.Count == 0) + { +

@T["Treasury.Rules.None"]

+ } + else + { + + + + + + + + + + + + + @foreach (var rule in _rules) + { + + + + + + + + + } + +
@T["Treasury.Rules.Name"]@T["Treasury.Rules.Pattern"]@T["Treasury.Rules.Direction"]@T["Treasury.Rules.Account"]@T["Treasury.Rules.Uses"]
@rule.Name@rule.Pattern@T[TreasuryScreens.EnumKey(rule.Direction)]@AccountText(rule.AccountId)@rule.Uses + + +
+ } +
+
+ } + else + { + + @if (_statements.Count == 0) + { +

@T["Treasury.Reconciliation.NoStatements"]

+ } + else + { + + + + + + + + + + + + + @foreach (var st in _statements) + { + + + + + + + + + } + +
@T["Treasury.Reconciliation.File"]@T["Treasury.Reconciliation.Format"]@T["Treasury.Fields.From"]@T["Treasury.Fields.To"]@T["Treasury.Reconciliation.Movements"]@T["Treasury.Reconciliation.Closing"]
@st.FileName@T[TreasuryScreens.EnumKey(st.Format)]@T.Date(st.FromDate)@T.Date(st.ToDate)@st.MovementCount@(st.ClosingBalance is { } c ? T.Money(c) : "—")
+ } +
+ } + + + + @if (_itemsFor is { } target) + { +

@target.Line.Description · @T.Money(target.Line.Amount)

+ + + + @foreach (var row in _items) + { + + + + + + + + } + +
@row.PartyName@row.Item.DocumentNumber@T.Date(row.Item.DueDate)@T.Money(row.Item.Residual)
+

@T.Format("Treasury.Reconciliation.Chosen", T.Money(_items.Where(r => _chosen.Contains(r.Item.Id)).Sum(r => r.Item.Residual)))

+ } +
+
+ + +
+
+ + + + @if (_paymentsFor is { } target) + { +

@target.Line.Description · @T.Money(target.Line.Amount)

+ @if (_payments.Count == 0) + { +

@T["Treasury.Payments.None"]

+ } + + + @foreach (var p in _payments) + { + + + + + + + + } + +
@T.Date(p.Payment.PaymentDate)@p.PartyName@p.Payment.Reference@T.Money(p.Payment.Amount + p.Payment.Fees)
+ } +
+
+ +
+
+ + + + @if (_postFor is { } target) + { +

@target.Line.Description · @T.Money(target.Line.Amount)

+
+ + + +
+ } +
+
+ + +
+
+ + + +
+ + + + + + +
+
+
+ + +
+
+
+ +@code { + private string _tab = "lines"; + private string _show = "open"; + private long? _bankId; + private TreasuryChoices? _choices; + private BankPosition? _position; + private IReadOnlyList _lines = []; + private IReadOnlyList _statements = []; + private IReadOnlyList _rules = []; + private IReadOnlyList _accounts = []; + private bool _busy; + + private StatementLineRow? _itemsFor; + private IReadOnlyList _items = []; + private readonly HashSet _chosen = []; + private StatementLineRow? _paymentsFor; + private IReadOnlyList _payments = []; + private StatementLineRow? _postFor; + private long? _postAccount; + private string? _postDescription; + private string? _postRule; + + private bool _ruleOpen; + private long? _ruleId; + private string? _ruleName; + private string? _rulePattern; + private BankRuleDirection _ruleDirection; + private long? _ruleAccount; + private string? _ruleDescription; + private bool _ruleDisabled; + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []); + + private IReadOnlyList> Shows => + [ + new("open", T["Treasury.Reconciliation.ShowOpen"]), + new("all", T["Treasury.All"]), + ]; + + private IReadOnlyList> Directions => TreasuryScreens.Choices(T); + + private IReadOnlyList> Accounts => [.. _accounts.Where(a => a.Postable && !a.Disabled).Select(a => new KhOption(a.Id, a.Code + " " + a.Description))]; + + private IReadOnlyList Tabs => + [ + new("lines", "list", T["Treasury.Reconciliation.Lines"], _position?.ToMatch), + new("rules", "zap", T["Treasury.Rules.Title"], _rules.Count), + new("statements", "file", T["Treasury.Reconciliation.Statements"]), + ]; + + private IReadOnlyList Stats + { + get + { + var bank = _choices?.Banks.FirstOrDefault(b => b.Id == _bankId); + var p = _position; + var difference = p?.BankBalance is { } balance ? balance - p.BookBalance : (decimal?)null; + return + [ + new(T["Treasury.Reconciliation.Account"], bank is null ? "—" : bank.BankName ?? bank.Description), + new(T["Treasury.Reconciliation.BankBalance"], p?.BankBalance is { } b ? T.Money(b) + (p.BankBalanceDate is { } d ? " · " + T.Date(d) : null) : "—"), + new(T["Treasury.Reconciliation.BookBalance"], p is null ? "—" : T.Money(p.BookBalance)), + new(T["Treasury.Reconciliation.Difference"], difference is { } diff ? T.Money(diff) : "—", difference is { } x && x != 0m ? KhTone.Warning : KhTone.Ok), + new(T["Treasury.Reconciliation.ToMatch"], p is null ? "—" : T.Format("Treasury.Reconciliation.ToMatchText", p.ToMatch, T.Money(p.ToMatchAmount))), + ]; + } + } + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (!FinanceGuard.Allowed(Session, TreasuryPermissions.BankReconcile)) + { + return; + } + + _choices = await Schedule.ChoicesAsync(Session.Actor!, Session.Company!.Code); + _bankId = _choices.Banks.FirstOrDefault(b => b.IsDefault)?.Id ?? _choices.Banks.FirstOrDefault()?.Id; + if (Session.Permissions.Allows(LedgerPermissions.EntryRead)) + { + _accounts = await Ledger.AccountsAsync(Session.Actor!, Session.Company.Code); + } + + _rules = await Reconciliation.RulesAsync(Session.Actor!, Session.Company.Code); + await LoadAsync(); + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _bankId is not { } bank) + { + return; + } + + _lines = await Reconciliation.LinesAsync(actor, company, bank, _show == "open"); + _position = await Reconciliation.PositionAsync(actor, company, bank); + _statements = await Reconciliation.StatementsAsync(actor, company, bank); + } + + private string AccountText(long id) => _accounts.FirstOrDefault(a => a.Id == id) is { } a ? a.Code + " " + a.Description : id.ToString(T.Culture); + + private async Task SetBankAsync(long? bank) + { + _bankId = bank; + await LoadAsync(); + } + + private async Task SetShowAsync(string show) + { + _show = show; + await LoadAsync(); + } + + private async Task ImportAsync(InputFileChangeEventArgs e) => await RunAsync(async (actor, company) => + { + if (_bankId is not { } bank) + { + return; + } + + using var buffer = new MemoryStream(); + await using (var stream = e.File.OpenReadStream(10 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + var result = await Reconciliation.ImportAsync(actor, company, bank, e.File.Name, buffer.ToArray()); + Toasts.Show(ToastKind.Success, T.Format("Treasury.Reconciliation.Imported", result.Added, result.Duplicates, result.Suggested), null); + await LoadAsync(); + }); + + private async Task RefreshAsync() => await RunAsync(async (actor, company) => + { + if (_bankId is { } bank) + { + var found = await Reconciliation.RefreshAsync(actor, company, bank); + Toasts.Show(ToastKind.Info, T.Format("Treasury.Reconciliation.Refreshed", found), null); + await LoadAsync(); + } + }); + + private async Task ConfirmAllAsync() => await RunAsync(async (actor, company) => + { + if (_bankId is { } bank) + { + var done = await Reconciliation.ConfirmAllAsync(actor, company, bank); + Toasts.Show(ToastKind.Success, T.Format("Treasury.Reconciliation.Confirmed", done), null); + await LoadAsync(); + } + }); + + private async Task ConfirmAsync(BankStatementLine line) => await RunAsync(async (actor, company) => + { + await Reconciliation.ConfirmAsync(actor, company, line.Id); + await LoadAsync(); + }); + + private async Task IgnoreAsync(BankStatementLine line) => await RunAsync(async (actor, company) => + { + await Reconciliation.IgnoreAsync(actor, company, line.Id); + await LoadAsync(); + }); + + private async Task ResetAsync(BankStatementLine line) => await RunAsync(async (actor, company) => + { + await Reconciliation.ResetAsync(actor, company, line.Id); + await LoadAsync(); + }); + + private async Task OpenItemsAsync(StatementLineRow row) + { + _itemsFor = row; + _chosen.Clear(); + await LoadItemsAsync(row.PartyName); + } + + private async Task LoadItemsAsync(string? search) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _itemsFor is not { } target) + { + return; + } + + var direction = target.Line.Amount > 0m ? OpenItemDirection.Receivable : OpenItemDirection.Payable; + _items = [.. (await Schedule.ItemsAsync(actor, company, new ScheduleFilter(direction, ScheduleView.Open, Search: string.IsNullOrWhiteSpace(search) ? null : search))).Rows + .Where(r => r.Item.Status != OpenItemStatus.InRemittance).Take(50)]; + } + + private async Task SearchItemsAsync(ChangeEventArgs e) => await LoadItemsAsync(e.Value?.ToString()); + + private void ToggleItem(long id, bool on) + { + if (on) + { + _chosen.Add(id); + } + else + { + _chosen.Remove(id); + } + } + + private async Task MatchItemsAsync() => await RunAsync(async (actor, company) => + { + if (_itemsFor is { } target) + { + await Reconciliation.MatchItemsAsync(actor, company, target.Line.Id, [.. _items.Where(r => _chosen.Contains(r.Item.Id)).OrderBy(r => r.Item.DueDate).Select(r => r.Item.Id)]); + _itemsFor = null; + await LoadAsync(); + } + }); + + private async Task OpenPaymentsAsync(StatementLineRow row) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _paymentsFor = row; + var day = row.Line.BookingDate; + var direction = row.Line.Amount > 0m ? PaymentDirection.Receipt : PaymentDirection.Disbursement; + _payments = [.. (await Payments.ListAsync(actor, company, direction, day.AddDays(-45), day.AddDays(15))).Where(p => p.Payment.StatementLineId is null)]; + } + + private async Task MatchPaymentAsync(long paymentId) => await RunAsync(async (actor, company) => + { + if (_paymentsFor is { } target) + { + await Reconciliation.MatchPaymentAsync(actor, company, target.Line.Id, paymentId); + _paymentsFor = null; + await LoadAsync(); + } + }); + + private Task OpenPostAsync(StatementLineRow row) + { + _postFor = row; + _postAccount = null; + _postDescription = row.Line.Description; + _postRule = null; + return Task.CompletedTask; + } + + private async Task PostAsync() => await RunAsync(async (actor, company) => + { + if (_postFor is { } target && _postAccount is { } account) + { + await Reconciliation.PostAsync(actor, company, target.Line.Id, account, _postDescription, string.IsNullOrWhiteSpace(_postRule) ? null : _postRule.Trim()); + _postFor = null; + _rules = await Reconciliation.RulesAsync(actor, company); + await LoadAsync(); + } + }); + + private Task OpenRuleAsync(BankMatchRule? rule) + { + _ruleId = rule?.Id; + _ruleName = rule?.Name; + _rulePattern = rule?.Pattern; + _ruleDirection = rule?.Direction ?? BankRuleDirection.Out; + _ruleAccount = rule?.AccountId; + _ruleDescription = rule?.EntryDescription; + _ruleDisabled = rule?.Disabled ?? false; + _ruleOpen = true; + return Task.CompletedTask; + } + + private async Task SaveRuleAsync() => await RunAsync(async (actor, company) => + { + if (_ruleAccount is { } account) + { + await Reconciliation.SaveRuleAsync(actor, company, new BankRuleInput(_ruleId, _ruleName ?? string.Empty, _rulePattern ?? string.Empty, _ruleDirection, account, _ruleDescription, _ruleDisabled)); + _ruleOpen = false; + _rules = await Reconciliation.RulesAsync(actor, company); + } + }); + + private async Task DeleteRuleAsync(BankMatchRule rule) => await RunAsync(async (actor, company) => + { + await Reconciliation.DeleteRuleAsync(actor, company, rule.Id); + _rules = await Reconciliation.RulesAsync(actor, company); + }); + + 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["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/RemittancesPage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/RemittancesPage.razor new file mode 100644 index 0000000..8ccfd10 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/RemittancesPage.razor @@ -0,0 +1,528 @@ +@page "/scadenzario/distinte" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject RemittanceService Remittances +@inject ScheduleService Schedule +@inject ToastService Toasts +@inject DialogService Dialogs +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The remittances (SPEC §11.8, mockup 055): RiBa in the CBI file, SEPA direct debits (pain.008) and SEPA credit + transfers to the suppliers (pain.001). A new remittance gathers the items due by a date with the method of its kind, + checks the bank coordinates and the mandates; then the file, the presentation with its entry, the credit of the + bank and the effects that come back unpaid, which reopen the item with the fees. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Remittances.Title"]
+

@T["Treasury.Remittances.Heading"]

+
@T["Treasury.Remittances.Hint"]
+
+
+ + + + @if (_tab == "new") + { +
+ +
+ + + + + + + @if (_kind != RemittanceKind.SepaCreditTransfer) + { + + } + +
+ + @if (CanWrite) + { + + } +
+ + @if (_candidates.Count == 0) + { +

@T["Treasury.Remittances.NoCandidates"]

+ } + else + { +
+ + + + + + + + + + + + + + + @foreach (var c in _candidates) + { + var item = c.Row.Item; + var late = item.DueDate < Today; + + + + + + + + + + + } + +
@T["Treasury.Select"]@T[_kind == RemittanceKind.SepaCreditTransfer ? "Treasury.Fields.Supplier" : "Treasury.Fields.Customer"]@T["Treasury.Fields.Document"]@T["Treasury.Fields.Installment"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Amount"]@T["Treasury.Remittances.PartyBank"]@T["Treasury.Remittances.Check"]
+ + @c.Row.PartyName@item.DocumentNumber@item.Installment@T.Date(item.DueDate)@T.Money(item.Residual)@TreasuryScreens.ShortIban(c.Iban) @(c.Mandate is { } m ? "· " + m.Reference : null) + @if (!c.Ready) + { + @string.Join(", ", c.Problems.Select(p => T[p])) + } + else if (late) + { + @T["Treasury.Remittances.Late"] + } + else + { + @T["Treasury.Remittances.Ok"] + } +
+
+ } +
@T["Treasury.Remittances.Footer"]
+
+
+ } + else + { + +
+ +
+ @if (_list.Count == 0) + { +

@T["Treasury.Remittances.None"]

+ } + else + { + + + + + + + + + + + + + + @foreach (var row in _list) + { + var r = row.Remittance; + + + + + + + + + + } + +
@T["Treasury.Fields.Number"]@T["Treasury.Remittances.Kind"]@T["Treasury.Fields.Bank"]@T["Treasury.Remittances.PresentationDate"]@T["Treasury.Remittances.Effects"]@T["Treasury.Fields.Total"]@T["Treasury.Fields.Status"]
@TreasuryScreens.Number(r)@T[TreasuryScreens.EnumKey(r.Kind)] @(r.Advance ? "· " + T["Treasury.Remittances.AdvanceShort"] : null)@row.Bank@T.Date(r.PresentationDate)@r.ItemCount@T.Money(r.TotalAmount)@T[TreasuryScreens.EnumKey(r.Status)]
+ } +
+ + @if (_open is { } open) + { + var rem = open.Row.Remittance; + + + @if (CanWrite) + { + @if (rem.Status is RemittanceStatus.Draft or RemittanceStatus.Generated) + { + + + + } + @if (rem.Status == RemittanceStatus.Presented) + { + + } + } + + + + + + + + + + + + + + + + + @foreach (var line in open.Lines) + { + var l = line.Line; + + + + + + + + + + + } + +
@T["Treasury.Fields.Party"]@T["Treasury.Fields.Document"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Iban"]@T["Treasury.Remittances.EndToEnd"]@T["Treasury.Fields.Amount"]@T["Treasury.Fields.Status"]
@line.PartyName@line.Item?.DocumentNumber@T.Date(l.DueDate)@TreasuryScreens.ShortIban(l.Iban) @(line.Mandate is { } m ? "· " + m : null)@l.EndToEndId@T.Money(l.Amount) + @T[TreasuryScreens.EnumKey(l.Status)] + @if (l.UnpaidOn is { } u) + { + @T.Date(u) · @T.Money(l.UnpaidFees) + } + + @if (CanWrite && rem.Status is RemittanceStatus.Draft or RemittanceStatus.Generated) + { + + } + else if (CanWrite && rem.Kind != RemittanceKind.SepaCreditTransfer && rem.Status is RemittanceStatus.Presented or RemittanceStatus.Closed && l.Status != RemittanceLineStatus.Unpaid) + { + + } +
+
+ + @(rem.FileName is { } file ? T.Format("Treasury.Remittances.FileName", file) : null) + @(rem.CreditedOn is { } credited ? " · " + T.Format("Treasury.Remittances.CreditedOn", T.Date(credited)) : null) + + @if (rem.GlEntryId is { } entry) + { + @T["Treasury.Remittances.Entry"] + } + @if (rem.CreditEntryId is { } credit) + { + @T["Treasury.Remittances.CreditEntry"] + } +
+
+
+ } + } + + + +

@T["Treasury.Remittances.CreditText"]

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

@T["Treasury.Remittances.UnpaidText"]

+
+ + +
+
+
+ + +
+
+
+ +@code { + private string _tab = "new"; + private RemittanceKind _kind = RemittanceKind.Riba; + private long? _bankId; + private DateOnly? _presentation; + private DateOnly? _dueUntil; + private bool _advance; + private string? _notes; + private IReadOnlyList _candidates = []; + private readonly HashSet _chosen = []; + private TreasuryChoices? _choices; + private int _year; + private IReadOnlyList _list = []; + private (RemittanceRow Row, IReadOnlyList Lines)? _open; + private bool _busy; + private bool _creditOpen; + private DateOnly? _creditOn; + private RemittanceLine? _unpaid; + private DateOnly? _unpaidOn; + private decimal? _unpaidFees; + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private decimal SelectedTotal => _candidates.Where(c => _chosen.Contains(c.Row.Item.Id)).Sum(c => c.Row.Item.Residual); + + private IReadOnlyList Tabs => + [ + new("new", "plus", T["Treasury.Remittances.New"]), + new("history", "list", T["Treasury.Remittances.History"]), + ]; + + private IReadOnlyList> Kinds => TreasuryScreens.Choices(T); + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []); + + private IReadOnlyList> Years => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))]; + + private IReadOnlyList Steps => + [ + new(T["Treasury.Remittances.Step.Select"], T.Format("Treasury.Remittances.Step.SelectText", _chosen.Count, _candidates.Count(c => !c.Ready))), + new(T["Treasury.Remittances.Step.Check"], T["Treasury.Remittances.Step.CheckText"]), + new(T["Treasury.Remittances.Step.File"], T[_kind == RemittanceKind.Riba ? "Treasury.Remittances.Step.FileCbi" : "Treasury.Remittances.Step.FileXml"]), + new(T["Treasury.Remittances.Step.Post"], T["Treasury.Remittances.Step.PostText"]), + new(T["Treasury.Remittances.Step.Credit"], T["Treasury.Remittances.Step.CreditText"]), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _year = Today.Year; + _presentation = Today; + _dueUntil = Today.AddDays(30); + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + _choices = await Schedule.ChoicesAsync(Session.Actor!, Session.Company!.Code); + _bankId = _choices.Banks.FirstOrDefault(b => b.IsDefault)?.Id ?? _choices.Banks.FirstOrDefault()?.Id; + await LoadCandidatesAsync(); + } + } + + private async Task LoadCandidatesAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _dueUntil is not { } until) + { + return; + } + + _candidates = await Remittances.CandidatesAsync(actor, company, _kind, until); + _chosen.Clear(); + _chosen.UnionWith(_candidates.Where(c => c.Ready && c.Row.Item.DueDate >= Today).Select(c => c.Row.Item.Id)); + } + + private async Task LoadListAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _list = await Remittances.ListAsync(actor, company, _year); + } + + private async Task SetTabAsync(string tab) + { + _tab = tab; + if (tab == "history") + { + await LoadListAsync(); + } + else + { + await LoadCandidatesAsync(); + } + } + + private async Task SetKindAsync(RemittanceKind kind) + { + _kind = kind; + await LoadCandidatesAsync(); + } + + private async Task SetDueUntilAsync(DateOnly? date) + { + _dueUntil = date; + await LoadCandidatesAsync(); + } + + private async Task SetYearAsync(int year) + { + _year = year; + _open = null; + await LoadListAsync(); + } + + private void Toggle(long id, bool on) + { + if (on) + { + _chosen.Add(id); + } + else + { + _chosen.Remove(id); + } + } + + private async Task OpenAsync(long id) => await RunAsync(async (actor, company) => _open = await Remittances.GetAsync(actor, company, id)); + + private async Task ReloadOpenAsync(long id) + { + await LoadListAsync(); + await OpenAsync(id); + } + + private async Task CreateAsync() => await RunAsync(async (actor, company) => + { + if (_bankId is { } bank && _presentation is { } presented && _dueUntil is { } until) + { + var remittance = await Remittances.CreateAsync(actor, company, new RemittanceInput(_kind, bank, presented, until, _advance, _notes, [.. _chosen])); + Toasts.Show(ToastKind.Success, T["Treasury.Remittances.Created"], TreasuryScreens.Number(remittance)); + _tab = "history"; + _year = remittance.Year; + await ReloadOpenAsync(remittance.Id); + } + }); + + private async Task FileAsync() => await RunAsync(async (actor, company) => + { + if (_open is { } open) + { + await LedgerScreens.DownloadAsync(JS, await Remittances.FileAsync(actor, company, open.Row.Remittance.Id)); + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private async Task PresentAsync() + { + if (_open is not { } open + || !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Remittances.Present"], T["Treasury.Remittances.PresentText"], T["Treasury.Remittances.Present"], T["Common.Cancel"]))) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Remittances.PresentAsync(actor, company, open.Row.Remittance.Id); + Toasts.Show(ToastKind.Success, T["Treasury.Remittances.Presented"], null); + await ReloadOpenAsync(open.Row.Remittance.Id); + }); + } + + private void OpenCredit(Remittance remittance) + { + _creditOn = remittance.DueUntil <= Today ? remittance.DueUntil : Today; + _creditOpen = true; + } + + private async Task CreditAsync() => await RunAsync(async (actor, company) => + { + if (_open is { } open && _creditOn is { } date) + { + await Remittances.CreditAsync(actor, company, open.Row.Remittance.Id, date); + _creditOpen = false; + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private void OpenUnpaid(RemittanceLine line) + { + _unpaid = line; + _unpaidOn = Today; + _unpaidFees = null; + } + + private async Task UnpaidAsync() => await RunAsync(async (actor, company) => + { + if (_open is { } open && _unpaid is { } line && _unpaidOn is { } date) + { + await Remittances.UnpaidAsync(actor, company, line.Id, date, _unpaidFees ?? 0m); + _unpaid = null; + Toasts.Show(ToastKind.Warning, T["Treasury.Remittances.UnpaidDone"], null); + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private async Task RemoveLineAsync(RemittanceLine line) => await RunAsync(async (actor, company) => + { + if (_open is { } open) + { + await Remittances.RemoveLineAsync(actor, company, line.Id); + await ReloadOpenAsync(open.Row.Remittance.Id); + } + }); + + private async Task DeleteAsync() + { + if (_open is not { } open + || !await Dialogs.ConfirmAsync(new ConfirmRequest(T["Treasury.Remittances.Delete"], T["Treasury.Remittances.DeleteText"], T["Treasury.Remittances.Delete"], T["Common.Cancel"]) { Danger = true })) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Remittances.DeleteAsync(actor, company, open.Row.Remittance.Id); + _open = null; + await LoadListAsync(); + }); + } + + 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["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Treasury/SchedulePage.razor b/src/Khaemhat.Web/Components/Pages/Treasury/SchedulePage.razor new file mode 100644 index 0000000..2740b59 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Treasury/SchedulePage.razor @@ -0,0 +1,397 @@ +@page "/scadenzario" +@page "/scadenzario/scadenze" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Treasury +@using Khaemhat.Core.Accounting +@using Khaemhat.Core.Treasury +@using Khaemhat.Web.Ledger +@using Khaemhat.Web.Treasury +@inject ShellSession Session +@inject ScheduleService Schedule +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The schedule (SPEC §11.8, mockups 053 and 054): the open items of customers and suppliers with the aging of what is + past due, the filters by state and party, the collection or payment of the items chosen, the change of due date, + method or dispute of one item, the statement of a party and the export of the grid. *@ + + + +
+
+
@T["Shell.Menu.Finance"] / @T["Treasury.Schedule.Title"]
+

@T["Treasury.Schedule.Heading"]

+
@T["Treasury.Schedule.Hint"]
+
+
+ @if (_result is { } r) + { + @T.Format("Treasury.Schedule.OpenTotal", T.Money(r.Residual)) + @T.Format("Treasury.Schedule.OverdueTotal", T.Money(r.Overdue)) + } +
+ + @if (_result is { } result) + { +
+ @T.Format("Treasury.Aging.Count", result.Aging.CountNotDue) + @T.Format("Treasury.Aging.Count", result.Aging.Count1To30) + @T.Format("Treasury.Aging.Count", result.Aging.Count31To60) + @T.Format("Treasury.Aging.Count", result.Aging.Count61To90) + @T.Format("Treasury.Aging.Count", result.Aging.CountOver90) +
+ } + + +
+ + + + +
+ + +
+ +
+
+ @if (CanPay) + { + + } + + @T["Treasury.Schedule.SelectHint"] +
+ @if (_result is not { Rows.Count: > 0 } rows) + { +

@T["Treasury.Schedule.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + + @foreach (var row in rows.Rows) + { + var item = row.Item; + var selectable = !item.Closed && item.Status != OpenItemStatus.InRemittance; + + + + + + + + + + + + + + + } + +
@T["Treasury.Select"]@T[_direction == OpenItemDirection.Receivable ? "Treasury.Fields.Customer" : "Treasury.Fields.Supplier"]@T["Treasury.Fields.Document"]@T["Treasury.Fields.Installment"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Days"]@T["Treasury.Fields.Method"]@T["Treasury.Fields.Amount"]@T[_direction == OpenItemDirection.Receivable ? "Treasury.Payment.Collected" : "Treasury.Payment.Paid"]@T["Treasury.Fields.Residual"]@T["Treasury.Fields.Status"]
+ @if (selectable) + { + + } + @row.PartyName + @if (item.EntryId > 0) + { + @item.DocumentNumber + } + else + { + @item.DocumentNumber + } + @item.Installment@T.Date(item.DueDate)@(item.Closed ? null : row.DaysOverdue.ToString(T.Culture))@(row.MethodDescription ?? row.Method)@T.Money(item.Amount)@T.Money(item.PaidAmount)@T.Money(item.Residual) + @TreasuryScreens.StatusText(T, item, Today) + @if (row.Remittance is { } remittance) + { + @remittance + } + + @if (CanWrite && !item.Closed) + { + + } +
+
+
+ @T.Format("Treasury.Schedule.Footer", rows.Rows.Count, _selected.Count, T.Money(SelectedRows.Sum(r => r.Item.Residual))) +
+ } +
+ + + + + + @if (_edit is { } edit) + { +

@T.Format("Treasury.Schedule.EditText", edit.Item.DocumentNumber ?? string.Empty, edit.Item.Installment, edit.PartyName)

+
+ + + + + +
+ } +
+
+ + +
+
+ + + + @if (_statement is { } st) + { +

@st.Party.Name · @T.Format("Treasury.Statement.At", T.Date(st.Day))

+
+ + + +
+ + + + + + + + + + + + @foreach (var row in st.Items) + { + + + + + + + + } + +
@T["Treasury.Fields.Document"]@T["Treasury.Fields.DueDate"]@T["Treasury.Fields.Amount"]@T["Treasury.Fields.Residual"]@T["Treasury.Fields.Status"]
@row.Item.DocumentNumber @(row.Item.Installment > 1 ? "· " + row.Item.Installment : null)@T.Date(row.Item.DueDate)@T.Money(row.Item.Amount)@T.Money(row.Item.Residual)@TreasuryScreens.StatusText(T, row.Item, st.Day)
+ @if (st.Payments.Count > 0) + { +

@T["Treasury.Statement.Payments"]

+ + + @foreach (var p in st.Payments) + { + + + + + + } + +
@T.Date(p.PaymentDate)@p.Reference@T.Money(p.Amount)
+ } + } +
+
+ +
+
+
+ +@code { + private OpenItemDirection _direction = OpenItemDirection.Receivable; + private ScheduleView _view = ScheduleView.Open; + private long? _methodId; + private string? _search; + private ScheduleResult? _result; + private TreasuryChoices? _choices; + private readonly HashSet _selected = []; + private bool _busy; + private bool _paymentOpen; + private IReadOnlyList _paymentRows = []; + private ScheduleRow? _edit; + private DateOnly? _editDue; + private long? _editMethod; + private long? _editBank; + private bool _editDisputed; + private string? _editNotes; + private PartyStatement? _statement; + + /// The direction asked by the address (?fornitori). + [SupplyParameterFromQuery(Name = "vista")] + public string? Side { get; set; } + + private DateOnly Today => DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + + private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite); + + private bool CanPay => Session.Permissions.Allows(TreasuryPermissions.PaymentWrite); + + private IEnumerable SelectedRows => _result?.Rows.Where(r => _selected.Contains(r.Item.Id)) ?? []; + + private bool OnePartySelected => _selected.Count > 0 && SelectedRows.Select(r => r.Item.PartyId).Distinct().Count() == 1; + + private IReadOnlyList> Views => TreasuryScreens.Choices(T); + + private IReadOnlyList> Methods => TreasuryScreens.MethodChoices(_choices?.Methods ?? []); + + private IReadOnlyList> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (string.Equals(Side, "fornitori", StringComparison.Ordinal)) + { + _direction = OpenItemDirection.Payable; + } + + if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead)) + { + _choices = await Schedule.ChoicesAsync(Session.Actor!, Session.Company!.Code); + await LoadAsync(); + } + } + + private ScheduleFilter Filter => new(_direction, _view, null, null, null, _methodId, string.IsNullOrWhiteSpace(_search) ? null : _search.Trim()); + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _result = await Schedule.ItemsAsync(actor, company, Filter); + _selected.IntersectWith(_result.Rows.Select(r => r.Item.Id)); + } + + private async Task SetDirectionAsync(OpenItemDirection direction) + { + _direction = direction; + _selected.Clear(); + await LoadAsync(); + } + + private async Task SetViewAsync(ScheduleView view) + { + _view = view; + await LoadAsync(); + } + + private async Task SetMethodAsync(long? method) + { + _methodId = method; + await LoadAsync(); + } + + private async Task SearchAsync(ChangeEventArgs e) + { + _search = e.Value?.ToString(); + await LoadAsync(); + } + + private void Toggle(long id, bool on) + { + if (on) + { + _selected.Add(id); + } + else + { + _selected.Remove(id); + } + } + + private void OpenPayment() + { + _paymentRows = [.. SelectedRows.OrderBy(r => r.Item.DueDate)]; + _paymentOpen = true; + } + + private async Task PaidAsync(Payment payment) + { + _paymentOpen = false; + _selected.Clear(); + await LoadAsync(); + } + + private void OpenEdit(ScheduleRow row) + { + _edit = row; + _editDue = row.Item.DueDate; + _editMethod = row.Item.PaymentMethodId; + _editBank = row.Item.BankAccountId; + _editDisputed = row.Item.Disputed; + _editNotes = row.Item.Notes; + } + + private async Task SaveEditAsync() => await RunAsync(async (actor, company) => + { + if (_edit is { } edit && _editDue is { } due) + { + await Schedule.UpdateAsync(actor, company, edit.Item.Id, new OpenItemChange(due, _editMethod, _editBank, _editDisputed, _editNotes)); + _edit = null; + Toasts.Show(ToastKind.Success, T["Treasury.Saved"], null); + await LoadAsync(); + } + }); + + private async Task StatementAsync() => await RunAsync(async (actor, company) => + { + if (SelectedRows.FirstOrDefault() is { } row) + { + _statement = await Schedule.StatementAsync(actor, company, row.Item.PartyId, _direction); + } + }); + + private async Task ExportAsync() => await RunAsync(async (actor, company) => await LedgerScreens.DownloadAsync(JS, await Schedule.ExportAsync(actor, company, Filter))); + + 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["Treasury.NotDone"], TreasuryScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 67ff05f..0f30e22 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -164,6 +164,16 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); + // The schedule and the treasury (ADR 0038): collections, remittances, reconciliation, reminders, cash flow. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + // The document engine (ADR 0032): one engine, the copies, a typed service per family. services.AddSingleton(); services.AddSingleton(); @@ -199,6 +209,8 @@ internal static class KhaemhatServices services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); @@ -232,6 +244,9 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + 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 4dbd532..a9c1922 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -134,6 +134,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); } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json index b09b36b..0f7cc77 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json +++ b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json @@ -50,7 +50,8 @@ }, "Areas": { "System": "Sistema", - "Notifications": "Avvisi" + "Notifications": "Avvisi", + "Treasury": "Tesoreria" }, "Coming": { "Text": "Questo widget si riempie con i dati di {0}, in arrivo con la milestone {1}. Intanto puoi già metterlo dove ti serve.", @@ -71,7 +72,10 @@ "TrialEnds": "Fine del periodo di prova", "JobRanOnce": "Attività programmata", "JobRanTimes": "Eseguita {0} volte oggi", - "JobFailed": "Attività «{0}» non riuscita" + "JobFailed": "Attività «{0}» non riuscita", + "DueReceivable": "Incasso da {0}: {1}", + "DuePayable": "Pagamento a {0}: {1}", + "Overdue": "{0} partite di clienti scadute da incassare ({1})" }, "Widgets": { "Kpi": { diff --git a/src/Khaemhat.Web/Resources/it-IT/Ledger.json b/src/Khaemhat.Web/Resources/it-IT/Ledger.json index 4e9ffbd..b521206 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Ledger.json +++ b/src/Khaemhat.Web/Resources/it-IT/Ledger.json @@ -364,7 +364,8 @@ "TaxPayment": "Versamento F24", "Recurring": "Ricorrente", "Reversal": "Storno", - "Withholding": "Ritenuta" + "Withholding": "Ritenuta", + "Treasury": "Tesoreria" }, "RecurrenceFrequency": { "Monthly": "Mensile", @@ -412,7 +413,14 @@ "StampDuty": "Bollo", "Rounding": "Arrotondamenti", "VatSettlement": "Erario c/IVA", - "SplitPaymentVat": "IVA split payment" + "SplitPaymentVat": "IVA split payment", + "AllowanceIncome": "Abbuoni attivi", + "BankCharges": "Spese bancarie", + "BillsForCollection": "Effetti all'incasso", + "BankAdvances": "Anticipi su effetti", + "ExchangeGain": "Utili su cambi", + "ExchangeLoss": "Perdite su cambi", + "LateInterest": "Interessi di mora attivi" }, "AccountSide": { "Debit": "Dare", @@ -497,6 +505,9 @@ }, "bank": { "account-missing": "Il conto bancario non ha un conto contabile e manca il conto banca predefinito." + }, + "open-item": { + "paid": "Il documento ha scadenze già incassate, pagate o in distinta: annulla prima l'incasso o togli la scadenza dalla distinta." } }, "vat": { diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index 90c9ed4..11b5622 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -99,10 +99,14 @@ }, "Finance": { "_": "Scadenzario", - "OpenItems": "Scadenze", - "Remittances": "Distinte RiBa e SEPA", + "OpenItems": "Partite aperte", + "Receipts": "Incassi", + "Payments": "Pagamenti", "Dunning": "Solleciti", - "Reconciliation": "Riconciliazione bancaria" + "Remittances": "Distinte RiBa/SDD", + "Mandates": "Mandati SDD", + "Reconciliation": "Riconciliazione bancaria", + "CashFlow": "Flusso di cassa" }, "EInvoicing": { "_": "Fatt. elettronica", diff --git a/src/Khaemhat.Web/Resources/it-IT/Tables.json b/src/Khaemhat.Web/Resources/it-IT/Tables.json index 127f764..efe423f 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Tables.json +++ b/src/Khaemhat.Web/Resources/it-IT/Tables.json @@ -252,6 +252,7 @@ "SiaCode": "Codice SIA", "CucCode": "Codice CUC", "AccountCode": "Conto contabile", + "CreditorId": "Identificativo creditore SEPA", "IsDefault": "Predefinito", "Symbol": "Simbolo", "Decimals": "Decimali", diff --git a/src/Khaemhat.Web/Resources/it-IT/Treasury.json b/src/Khaemhat.Web/Resources/it-IT/Treasury.json new file mode 100644 index 0000000..9041e41 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Treasury.json @@ -0,0 +1,444 @@ +{ + "Treasury": { + "NoCompany": "Scegli un'azienda per lavorare sullo scadenzario", + "NoModule": { + "Title": "Tesoreria non attiva", + "Lead": "La licenza di questa azienda non comprende il modulo Scadenzario e tesoreria (FIN). Attivalo da Amministrazione, Licenze." + }, + "NotDone": "Operazione non eseguita", + "Saved": "Salvato", + "All": "Tutti", + "Select": "Seleziona", + "Export": "Esporta", + "Fields": { + "Allowance": "Abbuono", + "Amount": "Importo", + "Bank": "Banca", + "Customer": "Cliente", + "Supplier": "Fornitore", + "Party": "Cliente o fornitore", + "Date": "Data", + "Days": "Gg", + "Document": "Documento", + "DueDate": "Scadenza", + "Fees": "Spese", + "From": "Dal", + "To": "Al", + "Iban": "IBAN", + "Installment": "Rata", + "Method": "Metodo", + "Notes": "Note", + "Number": "Numero", + "Reference": "Riferimento", + "Residual": "Residuo", + "Status": "Stato", + "Total": "Totale", + "Year": "Anno", + "Bic": "BIC" + }, + "Aging": { + "NotDue": "Non scaduto", + "Days1To30": "Scaduto 1-30 gg", + "Days31To60": "31-60 gg", + "Days61To90": "61-90 gg", + "Over90": "Oltre 90 gg", + "Count": "{0} partite" + }, + "Schedule": { + "Title": "Partite aperte", + "Heading": "Partite aperte", + "Hint": "Scadenze di clienti e fornitori con anzianità dello scaduto. Seleziona le partite di una controparte per registrare l'incasso o il pagamento.", + "OpenTotal": "Aperto {0}", + "OverdueTotal": "Scaduto {0}", + "Search": "Cerca controparte o documento", + "View": "Mostra", + "Direction": "Clienti o fornitori", + "Customers": "Clienti", + "Suppliers": "Fornitori", + "SelectHint": "Le partite scelte devono essere della stessa controparte.", + "None": "Nessuna partita con questi filtri.", + "Overdue": "Scaduta", + "DueSoon": "In scadenza", + "Disputed": "Contestata", + "Edit": "Modifica partita", + "EditText": "Partita {0} rata {1} di {2}: scadenza, metodo, banca e contestazione.", + "Footer": "{0} partite · {1} selezionate · residuo selezionato {2}" + }, + "Statement": { + "Open": "Estratto conto", + "Title": "Estratto conto", + "At": "situazione al {0}", + "Interest": "Interessi di mora", + "Payments": "Incassi e pagamenti registrati" + }, + "Payment": { + "NewReceipt": "Registra incasso", + "NewPayment": "Registra pagamento", + "Cash": "Cassa", + "Items": "Partite da chiudere", + "Collected": "Incassato", + "Paid": "Pagato", + "ResidualAfter": "Residuo dopo", + "Save": "Registra e chiudi partite", + "EntryReceipt": "Verrà generata la prima nota Banca (D) / Clienti (A) per {0}, con abbuoni per {1}.", + "EntryPayment": "Verrà generata la prima nota Fornitori (D) / Banca (A) per {0}, con abbuoni per {1}.", + "ReceiptSaved": "Incasso registrato", + "PaymentSaved": "Pagamento registrato" + }, + "Payments": { + "Receipts": "Incassi", + "Payments": "Pagamenti", + "ReceiptsHint": "Gli incassi dai clienti del periodo con i documenti saldati e la registrazione contabile.", + "PaymentsHint": "I pagamenti ai fornitori del periodo con i documenti saldati e la registrazione contabile.", + "Documents": "Documenti", + "Origin": "Origine", + "Entry": "Registrazione", + "Total": "{0} movimenti · {1}", + "None": "Nessun movimento nel periodo.", + "Cancel": "Annulla movimento", + "CancelText": "Annullare il movimento di {0} di {1}? Le partite tornano aperte e la registrazione viene eliminata o stornata.", + "Cancelled": "Movimento annullato" + }, + "Remittances": { + "Title": "Distinte", + "Heading": "Distinte RiBa / SDD / bonifici", + "Hint": "Raccogli gli effetti in scadenza, genera il file per l'home banking, contabilizza la presentazione, l'accredito e gli insoluti.", + "New": "Nuova distinta", + "History": "Storico distinte", + "Kind": "Tipo", + "Bank": "Banca di presentazione", + "PresentationDate": "Data presentazione", + "DueUntil": "Scadenze fino al", + "Effects": "Effetti", + "Advance": "Salvo buon fine (anticipo)", + "AdvanceShort": "s.b.f.", + "Create": "Crea distinta", + "Candidates": "Effetti proponibili", + "PartyBank": "Banca controparte", + "Check": "Controllo", + "Late": "Scaduta: escludere?", + "Ok": "OK", + "NoCandidates": "Nessuna partita con questo metodo entro la data scelta.", + "Footer": "Formati: RiBa (CBI), SDD core/B2B (pain.008), bonifici SEPA (pain.001) · gli insoluti tornano come partite riaperte con spese", + "None": "Nessuna distinta nell'anno.", + "Detail": "Distinta {0} n. {1}", + "Lines": "Effetti della distinta", + "FileCbi": "Genera file CBI", + "FileXml": "Genera file XML", + "Present": "Contabilizza presentazione", + "PresentText": "La distinta viene contabilizzata: gli effetti passano dai clienti alla banca (o i bonifici ai fornitori vengono registrati). Continuare?", + "Presented": "Distinta contabilizzata", + "Delete": "Elimina distinta", + "DeleteText": "Eliminare la distinta? Le partite tornano disponibili.", + "Created": "Distinta creata", + "Credit": "Registra accredito", + "CreditText": "La banca ha accreditato gli effetti: le partite si chiudono e l'anticipo, se c'è, viene estinto.", + "CreditedOnLabel": "Data accredito", + "CreditedOn": "accreditata il {0}", + "CreditEntry": "Registrazione accredito", + "Entry": "Registrazione presentazione", + "EndToEnd": "Riferimento", + "FileName": "file {0}", + "RemoveLine": "Togli dalla distinta", + "Unpaid": "Insoluto", + "UnpaidText": "L'effetto è tornato insoluto: la partita si riapre e le spese della banca vengono addebitate al cliente.", + "UnpaidDone": "Insoluto registrato", + "Step": { + "Select": "Selezione effetti", + "SelectText": "{0} selezionati · {1} esclusi", + "Check": "Controlli", + "CheckText": "IBAN, ABI/CAB, mandati, scadenze", + "File": "Generazione file", + "FileCbi": "tracciato CBI RiBa standard", + "FileXml": "XML SEPA pain.008 o pain.001", + "Post": "Contabilizzazione", + "PostText": "effetti attivi / clienti", + "Credit": "Accredito e insoluti", + "CreditText": "chiusura delle partite o riapertura con spese" + } + }, + "Mandates": { + "Title": "Mandati SDD", + "Heading": "Mandati SEPA Direct Debit", + "Hint": "Ogni cliente che paga con addebito diretto ha bisogno di un mandato firmato. Il primo incasso esce come FRST, i successivi come RCUR.", + "New": "Nuovo mandato", + "Edit": "Modifica mandato", + "None": "Nessun mandato registrato.", + "Reference": "Riferimento mandato (UMR)", + "Signed": "Firmato il", + "Scheme": "Schema", + "OneOff": "Una tantum", + "LastCollection": "Ultimo incasso", + "First": "Mai usato (FRST)", + "Active": "Valido", + "Revoked": "Revocato", + "Revoke": "Revoca", + "Restore": "Annulla revoca", + "Delete": "Elimina mandato", + "DeleteText": "Eliminare il mandato {0}?" + }, + "Dunning": { + "Title": "Solleciti", + "Heading": "Solleciti di pagamento", + "Preview": "Anteprima", + "Send": "Invia {0} solleciti", + "SendTitle": "Invia solleciti", + "SendText": "Inviare {0} solleciti per e-mail o PEC? Le lettere senza indirizzo vengono preparate in PDF.", + "Sent": "{0} inviati, {1} lettere", + "Proposal": "Proposta di invio", + "Rule": "regola: scaduto oltre i giorni del livello · escluse PA e partite contestate", + "Nothing": "Nessun cliente da sollecitare.", + "Items": "Partite", + "MaxDays": "Gg max", + "LastSent": "Ultimo sollecito", + "NextLevel": "Prossimo livello", + "Level": "Livello {0}", + "Waiting": "In attesa", + "Channel": "Canale", + "Include": "Includi", + "Blocked": "· bloccato", + "Levels": "Livelli e modelli", + "LevelColumn": "Livello", + "After": "Dopo (gg)", + "Template": "Modello", + "Action": "Azione", + "Automatic": "Automatico", + "InterestYes": "sì (D.Lgs. 231/2002)", + "InterestNo": "no", + "EditLevel": "Modifica livello", + "ChargeInterest": "Calcola interessi di mora", + "Subject": "Oggetto", + "Body": "Testo", + "Placeholders": "Segnaposti: {cliente} {azienda} {elenco} {totale} {interessi} {riferimento} {giorni}", + "History": "Registro invii", + "NoHistory": "Nessun sollecito inviato.", + "Recipients": "Destinatari", + "SentBy": "Inviato da", + "Customers": "Clienti con scaduto", + "OverdueTotal": "Scaduto totale", + "Today": "Da sollecitare oggi", + "LastRun": "Ultimo invio", + "Schedule": "Esecuzione automatica", + "ScheduleText": "giorni feriali alle 7:00" + }, + "Reconciliation": { + "Title": "Riconciliazione bancaria", + "Import": "Importa estratto conto", + "Auto": "Abbina automatico", + "ConfirmAll": "Conferma suggeriti ≥ 90%", + "ShowOpen": "Da riconciliare", + "Lines": "Movimenti", + "Statements": "Estratti importati", + "None": "Nessun movimento da riconciliare.", + "Description": "Descrizione", + "In": "Entrate", + "Out": "Uscite", + "Proposal": "Abbinamento proposto", + "Confidence": "Conf.", + "Confirm": "Conferma", + "MatchItems": "Abbina a partite", + "MatchPayment": "Abbina a incasso o pagamento registrato", + "Post": "Registra su conto", + "Ignore": "Ignora", + "Reset": "Annulla abbinamento", + "Match": "Abbina", + "Chosen": "Totale partite scelte {0}", + "EntryDescription": "Descrizione registrazione", + "SaveRule": "Salva come regola (testo da cercare)", + "SaveRuleHint": "Se scrivi un testo, i movimenti futuri che lo contengono verranno proposti su questo conto.", + "Footer": "Abbinamento per importo, data, CRO/riferimento e nome; regole salvate per i ricorrenti", + "NoStatements": "Nessun estratto conto importato.", + "File": "File", + "Format": "Formato", + "Movements": "Movimenti", + "Closing": "Saldo finale", + "Account": "Conto", + "BankBalance": "Saldo banca", + "BookBalance": "Saldo contabile", + "Difference": "Differenza", + "ToMatch": "Movimenti", + "ToMatchText": "{0} da riconciliare · {1}", + "Imported": "{0} movimenti importati, {1} già presenti, {2} con proposta", + "Refreshed": "{0} proposte trovate", + "Confirmed": "{0} movimenti riconciliati" + }, + "Rules": { + "Title": "Regole", + "New": "Nuova regola", + "Edit": "Regola di abbinamento", + "None": "Nessuna regola salvata.", + "Name": "Nome", + "Pattern": "Testo da cercare", + "PatternHint": "Senza distinzione tra maiuscole e minuscole.", + "Direction": "Movimenti", + "Account": "Conto", + "Uses": "Usi", + "Disabled": "Disattivata", + "Delete": "Elimina regola" + }, + "CashFlow": { + "Title": "Flusso di cassa", + "Heading": "Flusso di cassa previsto", + "Hint": "Disponibilità di oggi e movimenti attesi da scadenze, distinte, ordini, registrazioni ricorrenti e imposte. Lo scaduto cade nel primo periodo.", + "Days": "Orizzonte", + "DaysText": "{0} giorni", + "Period": "Periodo", + "Weeks": "Settimane", + "Months": "Mesi", + "Periods": "Andamento", + "Balance": "Saldo", + "Chart": "Grafico", + "Accounts": "Banche e cassa oggi", + "Movements": "Movimenti previsti", + "NoMovements": "Nessun movimento previsto.", + "Source": "Origine", + "Today": "Disponibilità oggi", + "TotalIn": "Entrate previste", + "TotalOut": "Uscite previste", + "End": "Saldo finale", + "Lowest": "Punto più basso" + }, + "Enums": { + "OpenItemStatus": { + "Open": "Aperta", + "Partial": "Parziale", + "Closed": "Chiusa", + "Unpaid": "Insoluta", + "InRemittance": "In distinta" + }, + "ScheduleView": { + "Open": "Aperte", + "Overdue": "Scadute", + "Unpaid": "Insolute", + "InRemittance": "In distinta", + "Disputed": "Contestate", + "Closed": "Chiuse", + "All": "Tutte" + }, + "PaymentOrigin": { + "Manual": "Manuale", + "Remittance": "Distinta", + "BankStatement": "Estratto conto" + }, + "RemittanceKind": { + "Riba": "RiBa (CBI)", + "SddCore": "SDD Core", + "SddB2b": "SDD B2B", + "SepaCreditTransfer": "Bonifici SEPA" + }, + "RemittanceStatus": { + "Draft": "Bozza", + "Generated": "File generato", + "Presented": "Presentata", + "Closed": "Chiusa" + }, + "RemittanceLineStatus": { + "Included": "In distinta", + "Paid": "Pagato", + "Unpaid": "Insoluto" + }, + "SddScheme": { + "Core": "Core (privati)", + "B2b": "B2B (imprese)" + }, + "StatementLineStatus": { + "ToMatch": "Da abbinare", + "Suggested": "Suggerito", + "Matched": "Abbinato", + "Ignored": "Ignorato" + }, + "StatementMatchKind": { + "None": "Nessuno", + "OpenItems": "Partite", + "Payment": "Movimento registrato", + "TaxPayment": "F24", + "Rule": "Regola", + "RemittanceCredit": "Accredito distinta", + "Unpaid": "Insoluto", + "Entry": "Registrazione" + }, + "StatementFormat": { + "Csv": "CSV", + "Camt053": "CAMT.053", + "Cbi": "CBI" + }, + "BankRuleDirection": { + "Any": "Entrate e uscite", + "In": "Entrate", + "Out": "Uscite" + }, + "DunningChannel": { + "None": "Nessuno", + "Email": "e-mail", + "Pec": "PEC", + "Letter": "Lettera PDF" + }, + "DunningAction": { + "None": "—", + "NotifyAgent": "Avvisa l'agente", + "BlockCustomer": "Blocca il cliente" + }, + "DunningLetterStatus": { + "Queued": "In coda", + "Sent": "Inviato", + "Failed": "Non inviato" + }, + "CashFlowSource": { + "Receivables": "Incassi da clienti", + "Payables": "Pagamenti a fornitori", + "SaleOrders": "Ordini clienti", + "PurchaseOrders": "Ordini fornitori", + "Recurring": "Ricorrenti", + "Taxes": "Imposte" + } + } + }, + "treasury": { + "not-found": "L'elemento non esiste più.", + "account-missing": "Manca il conto contabile: controlla il piano dei conti e le causali.", + "money-account-missing": "Manca il conto della banca o della cassa: indica il conto contabile della banca.", + "iban-invalid": "L'IBAN non è valido.", + "payment": { + "party-required": "Indica il cliente o il fornitore.", + "items-required": "Scegli almeno una partita.", + "amount-required": "Indica un importo diverso da zero.", + "item-party": "Le partite devono essere della stessa controparte.", + "over-settled": "L'importo supera il residuo della partita.", + "unbalanced": "Il movimento non quadra con le partite.", + "from-remittance": "Il movimento nasce da una distinta: annullalo dalla distinta." + }, + "item": { + "in-remittance": "La partita è in una distinta." + }, + "remittance": { + "empty": "La distinta non ha effetti.", + "status": "La distinta non è nello stato giusto per questa operazione.", + "bank": "La banca di presentazione non ha i dati richiesti (IBAN, SIA, CUC o identificativo creditore).", + "iban": "IBAN o ABI/CAB mancanti", + "mandate": "Mandato SDD mancante o revocato", + "item": "La partita non è disponibile.", + "format": "Il pacchetto fiscale non sa scrivere questo formato." + }, + "mandate": { + "duplicate": "Esiste già un mandato con questo riferimento.", + "reference": "Il riferimento del mandato è obbligatorio (massimo 35 caratteri).", + "used": "Il mandato è già stato usato in una distinta: revocalo invece di eliminarlo." + }, + "statement": { + "format": "Formato dell'estratto conto non riconosciuto (CAMT.053, CBI o CSV).", + "empty": "L'estratto conto non contiene movimenti.", + "account": "L'estratto conto è di un altro conto." + }, + "match": { + "done": "Il movimento è già riconciliato.", + "amount": "L'importo non corrisponde." + }, + "rule": { + "pattern": "Scrivi il testo da cercare." + }, + "dunning": { + "recipient": "Nessun indirizzo e-mail o PEC: preparata la lettera PDF.", + "level": "Livello di sollecito non valido." + } + } +} diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 097ecda..28153da 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -74,10 +74,11 @@ public static class MenuCatalog ("Shell.Menu.Ledger.Parties", "partitari"), ("Shell.Menu.Ledger.VatRegisters", "registri-iva"), ("Shell.Menu.Ledger.VatSettlement", "liquidazione-iva"), ("Shell.Menu.Ledger.Withholdings", "ritenute"), ("Shell.Menu.Ledger.StampDuty", "bollo"), ("Shell.Menu.Ledger.Statements", "bilancio")), - Area("Shell.Menu.Finance", "coins", "/scadenzario", ModuleCodes.Finance, "finance.schedule.read", "M9", - ("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Dunning", "solleciti"), - ("Shell.Menu.Finance.Reconciliation", "riconciliazione")), - Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M8", + 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")), + Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M9", ("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"), ("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento")), Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10", diff --git a/src/Khaemhat.Web/Tables/TableScreens.cs b/src/Khaemhat.Web/Tables/TableScreens.cs index 8db0429..9bda8e7 100644 --- a/src/Khaemhat.Web/Tables/TableScreens.cs +++ b/src/Khaemhat.Web/Tables/TableScreens.cs @@ -178,6 +178,7 @@ public static class TableScreens new(nameof(BankAccount.SiaCode), TableFieldKind.Code) { Span = 4, MaxLength = 5 }, new(nameof(BankAccount.CucCode), TableFieldKind.Code) { Span = 4, MaxLength = 8 }, new(nameof(BankAccount.AccountCode), TableFieldKind.Code) { Span = 4 }, + new(nameof(BankAccount.CreditorId), TableFieldKind.Code) { Span = 8, MaxLength = 35 }, new(nameof(BankAccount.IsDefault), TableFieldKind.Bool) { Span = 12, InGrid = true, Width = "90px" }, ], }, diff --git a/src/Khaemhat.Web/Treasury/TreasuryScreens.cs b/src/Khaemhat.Web/Treasury/TreasuryScreens.cs new file mode 100644 index 0000000..af4a522 --- /dev/null +++ b/src/Khaemhat.Web/Treasury/TreasuryScreens.cs @@ -0,0 +1,144 @@ +using System.Globalization; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Web.Ledger; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Treasury; + +/// What the screens of the schedule and the treasury share (SPEC §11.8, mockups 053-057): addresses, texts and tones. +public static class TreasuryScreens +{ + /// The address of the area. + public const string BasePath = "/scadenzario"; + + /// The text of the channels of a reminder level: they are flags, so "e-mail + PEC". + /// The texts. + /// The channels. + /// The text. + public static string ChannelText(ITexts texts, DunningChannel channel) + { + ArgumentNullException.ThrowIfNull(texts); + var parts = Enum.GetValues().Where(c => c != DunningChannel.None && channel.HasFlag(c)).Select(c => texts[EnumKey(c)]).ToList(); + return parts.Count == 0 ? texts[EnumKey(DunningChannel.None)] : string.Join(" + ", parts); + } + + /// The channels with one of them switched on or off. + /// The channels. + /// The channel to switch. + /// Whether it is on. + /// The channels. + public static DunningChannel Switch(DunningChannel channel, DunningChannel flag, bool on) => on ? channel | flag : channel & ~flag; + + /// The key of the text of an enum value. + /// The value. + /// The key. + public static string EnumKey(Enum value) + { + ArgumentNullException.ThrowIfNull(value); + return "Treasury.Enums." + value.GetType().Name + "." + value; + } + + /// The choices of an enum. + /// The enum. + /// The texts. + /// The choices in declaration order. + public static IReadOnlyList> Choices(ITexts texts) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v, texts[EnumKey(v)]))]; + } + + /// The text of the errors of a refused operation. + /// The texts. + /// The refusal. + /// The messages. + public static string Errors(ITexts texts, ValidationFailedException exception) => LedgerScreens.Errors(texts, exception); + + /// The tone of the state of an item; an open item past due is an error. + /// The item. + /// Today. + /// The tone. + public static KhTone ToneOf(OpenItem item, DateOnly today) + { + ArgumentNullException.ThrowIfNull(item); + return item.Status switch + { + OpenItemStatus.Closed => KhTone.Ok, + OpenItemStatus.Unpaid => KhTone.Error, + OpenItemStatus.InRemittance => KhTone.Info, + OpenItemStatus.Partial => KhTone.Warning, + _ when item.DueDate < today => KhTone.Error, + _ when item.DueDate <= today.AddDays(7) => KhTone.Warning, + _ => KhTone.Neutral, + }; + } + + /// The text of the state of an item: overdue and due soon are told apart from open. + /// The texts. + /// The item. + /// Today. + /// The text. + public static string StatusText(ITexts texts, OpenItem item, DateOnly today) + { + ArgumentNullException.ThrowIfNull(texts); + ArgumentNullException.ThrowIfNull(item); + var text = item.Status == OpenItemStatus.Open && item.DueDate < today ? texts["Treasury.Schedule.Overdue"] + : item.Status == OpenItemStatus.Open && item.DueDate <= today.AddDays(7) ? texts["Treasury.Schedule.DueSoon"] + : texts[EnumKey(item.Status)]; + return item.Disputed ? text + " · " + texts["Treasury.Schedule.Disputed"] : text; + } + + /// The tone of the state of a remittance. + /// The state. + /// The tone. + public static KhTone ToneOf(RemittanceStatus status) => status switch + { + RemittanceStatus.Draft => KhTone.Warning, + RemittanceStatus.Generated => KhTone.Info, + RemittanceStatus.Presented => KhTone.Accent, + _ => KhTone.Ok, + }; + + /// The tone of the state of a movement of the bank. + /// The state. + /// The tone. + public static KhTone ToneOf(StatementLineStatus status) => status switch + { + StatementLineStatus.Matched => KhTone.Ok, + StatementLineStatus.Suggested => KhTone.Info, + StatementLineStatus.Ignored => KhTone.Neutral, + _ => KhTone.Warning, + }; + + /// A number of a remittance as the screens show it. + /// The remittance. + /// The text, year/number. + public static string Number(Remittance remittance) + { + ArgumentNullException.ThrowIfNull(remittance); + return remittance.Year.ToString(CultureInfo.InvariantCulture) + "/" + remittance.Number.ToString("000", CultureInfo.InvariantCulture); + } + + /// An IBAN shortened for a grid: country, check digits and the last four characters. + /// The IBAN. + /// The short text. + public static string ShortIban(string? iban) => + string.IsNullOrEmpty(iban) || iban.Length < 10 ? iban ?? string.Empty : iban[..4] + "…" + iban[^4..]; + + /// The choices of the bank accounts. + /// The bank accounts. + /// The choices, code and name. + public static IReadOnlyList> BankChoices(IEnumerable banks) => + [.. (banks ?? []).Select(b => new KhOption(b.Id, b.Code + " · " + (b.BankName ?? b.Description)))]; + + /// The choices of the payment methods. + /// The payment methods. + /// The choices, description and code of the e-invoice. + public static IReadOnlyList> MethodChoices(IEnumerable methods) => + [.. (methods ?? []).Select(m => new KhOption(m.Id, m.Description + " (" + m.EInvoiceCode + ")"))]; +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 53c7d36..5c1d41d 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -436,3 +436,24 @@ 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); } } + +/* 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; } +.kh-remit { display: grid; grid-template-columns: minmax(280px, 1fr) minmax(0, 3fr); gap: 12px; align-items: start; } +.kh-remit .kh-panel .btn.primary, .kh-remit .panel .btn.primary { margin-top: 12px; width: 100%; justify-content: center; } +.kh-subhead { margin: 14px 0 6px; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; color: var(--kh-text-2); } +.grid .chkcol { width: 32px; text-align: center; } +.grid tr.warn td { background: var(--kh-warn-soft); } +.grid tr.clickable { cursor: pointer; } +.grid td.neg, .grid td .neg { color: var(--kh-err); } +.grid td.pos { color: var(--kh-ok); } +.btn.ok { color: var(--kh-ok); border-color: var(--kh-ok); } +/* The strip clips its overflow, so in the column of the page it would shrink to nothing on long pages. */ +.strip { flex-shrink: 0; } +.grid td .ib { display: inline-grid; vertical-align: middle; } +.grid td.kh-acts { overflow: visible; max-width: none; white-space: nowrap; text-align: right; } +.grid td.kh-w260 { max-width: 260px; } +.kh-cfbarcol { width: 28%; } +.kh-cfbar { display: block; height: 8px; border-radius: 4px; background: var(--kh-accent); min-width: 2px; } +.kh-cfbar.neg { background: var(--kh-err); } +@media (max-width: 1100px) { .kh-remit { grid-template-columns: minmax(0, 1fr); } } diff --git a/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj b/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj index b07fb57..bd9f648 100644 --- a/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj +++ b/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj @@ -8,4 +8,9 @@ + + + + + diff --git a/tests/Khaemhat.Core.Tests/Treasury/Camt053ReaderTests.cs b/tests/Khaemhat.Core.Tests/Treasury/Camt053ReaderTests.cs new file mode 100644 index 0000000..19b8c0a --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/Camt053ReaderTests.cs @@ -0,0 +1,185 @@ +using System.Text; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Core.Tests.Treasury; + +/// ISO 20022 camt.053 statements (issue #71), read whatever the version of the namespace. +[TestClass] +public sealed class Camt053ReaderTests +{ + private const string Sample = """ + + + + STMT-12026-11-01T06:00:00 + + 2026-10 + 2026-11-01T06:00:00 + 2026-10-01T00:00:002026-10-31T23:59:59 + IT60X0542811101000000123456EUR + + OPBD + 1000.00CRDT
2026-09-30
+
+ + CLBD + 1950.50CRDT
2026-10-31
+
+ + 1220.00CRDTBOOK +
2026-10-05
2026-10-06
+ CRO-0001 + PMNTRCDTESCT + + E2E-AAA + + Cliente Uno S.p.A. + IT63A0200801600000101234567 + + Saldo FT 2026/388e FT 2026/390 + +
+ + 30.50CRDTBOOK + 2026-10-10T10:15:00+02:00 + 48 + E2E-BBB + Bonifico da + Cliente Due + + + 300.00DBITBOOK +
2026-10-20
2026-10-20
+ + + Officine Balbo + Fornitore Tre + DE89 3704 0044 0532 0130 00 + + Pagamento fattura 77 + +
+ + 9.99DBITPDNG +
2026-10-31
+
+
+
+
+ """; + + // The 2009 version: plain status, parties without Pty, PRCD as opening, no period. + private const string Version02 = """ + + + + OLD2026-11-01T06:00:00 + + 1 + IT60X0542811101000000123456 + PRCD50.00DBIT
2026-10-31
+ CLBD150.00CRDT
2026-11-03
+ + 200.00CRDTBOOK +
2026-11-02
+ Cliente Vecchio + Accredito +
+ + 1.00CRDTBOOK +
2026-11-03
+
+
+
+
+ """; + + [TestMethod] + public void Read_TwoCreditsAndADebit_WithBalancesAndPeriod() + { + var statement = Read(Sample); + + Assert.AreEqual(StatementFormat.Camt053, statement.Format); + Assert.AreEqual("IT60X0542811101000000123456", statement.AccountIban); + Assert.AreEqual("EUR", statement.Currency); + Assert.AreEqual(1000m, statement.OpeningBalance); + Assert.AreEqual(1950.50m, statement.ClosingBalance); + Assert.AreEqual(new DateOnly(2026, 10, 1), statement.FromDate); + Assert.AreEqual(new DateOnly(2026, 10, 31), statement.ToDate); + Assert.HasCount(3, statement.Movements); + Assert.AreEqual(statement.ClosingBalance, statement.OpeningBalance + statement.Movements.Sum(m => m.Amount)); + + var first = statement.Movements[0]; + Assert.AreEqual(new DateOnly(2026, 10, 5), first.BookingDate); + Assert.AreEqual(new DateOnly(2026, 10, 6), first.ValueDate); + Assert.AreEqual(1220m, first.Amount); + Assert.AreEqual("CRO-0001", first.Reference); + Assert.AreEqual("PMNT/RCDT/ESCT", first.BankCode); + Assert.AreEqual("Saldo FT 2026/388 e FT 2026/390", first.Description); + Assert.AreEqual("Cliente Uno S.p.A.", first.CounterpartyName); + Assert.AreEqual("IT63A0200801600000101234567", first.CounterpartyIban); + + var second = statement.Movements[1]; + Assert.AreEqual(new DateOnly(2026, 10, 10), second.BookingDate); + Assert.IsNull(second.ValueDate); + Assert.AreEqual("E2E-BBB", second.Reference); + Assert.AreEqual("48", second.BankCode); + Assert.AreEqual("Bonifico da Cliente Due", second.Description); + + var debit = statement.Movements[2]; + Assert.AreEqual(-300m, debit.Amount); + Assert.AreEqual("Fornitore Tre", debit.CounterpartyName); + Assert.AreEqual("DE89370400440532013000", debit.CounterpartyIban); + Assert.AreEqual("Pagamento fattura 77", debit.Description); + Assert.IsNull(debit.Reference); + } + + [TestMethod] + public void Read_Version02_UsesThePreviousClosingAndTheBookingDates() + { + var statement = Read(Version02); + + Assert.AreEqual(-50m, statement.OpeningBalance); + Assert.AreEqual(150m, statement.ClosingBalance); + Assert.AreEqual("EUR", statement.Currency); + Assert.AreEqual(new DateOnly(2026, 11, 2), statement.FromDate); + Assert.AreEqual(new DateOnly(2026, 11, 3), statement.ToDate); + Assert.HasCount(2, statement.Movements); + Assert.AreEqual("Cliente Vecchio", statement.Movements[0].CounterpartyName); + Assert.AreEqual("Accredito", statement.Movements[0].Description); + Assert.AreEqual(string.Empty, statement.Movements[1].Description); + } + + [TestMethod] + public void Recognizes_Camt053_ButNotOtherFiles() + { + Assert.IsTrue(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes(Sample))); + Assert.IsTrue(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes(Version02))); + Assert.IsFalse(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes("Data;Descrizione;Importo\n"))); + Assert.IsFalse(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes(""))); + } + + [TestMethod] + public void Read_RefusesBrokenOrForeignXml_AndDtds() + { + Assert.ThrowsExactly(() => Read("")); + Assert.ThrowsExactly(() => Read("")); + Assert.ThrowsExactly(() => Read("]>")); + Assert.ThrowsExactly(() => Read(Sample.Replace("30.50", "abc", StringComparison.Ordinal))); + } + + [TestMethod] + public void Read_TwoStatementsOfTwoAccounts_IsRefused() + { + var stmt = Sample[Sample.IndexOf("", StringComparison.Ordinal)..(Sample.IndexOf("", StringComparison.Ordinal) + 7)]; + var other = stmt.Replace("IT60X0542811101000000123456", "DE89370400440532013000", StringComparison.Ordinal); + + Assert.ThrowsExactly(() => Read(Sample.Replace("", "" + other, StringComparison.Ordinal))); + } + + private static StatementFile Read(string xml) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); + return Camt053Reader.Read(stream); + } +} diff --git a/tests/Khaemhat.Core.Tests/Treasury/CsvStatementReaderTests.cs b/tests/Khaemhat.Core.Tests/Treasury/CsvStatementReaderTests.cs new file mode 100644 index 0000000..cd0a1a6 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/CsvStatementReaderTests.cs @@ -0,0 +1,184 @@ +using System.Text; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Core.Tests.Treasury; + +/// CSV exports of home banking (issue #71): layouts, Italian numbers, encodings and the guess of the layout. +[TestClass] +public sealed class CsvStatementReaderTests +{ + private static readonly CsvStatementLayout SignedLayout = new(';', 1, 0, 1, 2, 3, null, null, 4); + private static readonly CsvStatementLayout TwoColumnLayout = new(';', 1, 0, 1, 2, null, 3, 4, null); + + [TestMethod] + public void Read_OneSignedColumn_WithItalianNumbersAndSigns() + { + const string csv = """ + Data contabile;Data valuta;Descrizione;Importo;CRO + 01/10/2026;02/10/2026;"Bonifico da ""Cliente Uno""; saldo";1.234,56;CRO1 + 03/10/2026;03/10/2026;Commissioni;-2,50; + + 05/10/2026;;Pagamento F24;1.000,00-; + 06/10/2026;06/10/2026;Storno;+10; + """; + + var statement = Read(csv, SignedLayout); + + Assert.AreEqual(StatementFormat.Csv, statement.Format); + Assert.HasCount(4, statement.Movements); + Assert.AreEqual(new DateOnly(2026, 10, 1), statement.FromDate); + Assert.AreEqual(new DateOnly(2026, 10, 6), statement.ToDate); + Assert.IsNull(statement.OpeningBalance); + + var first = statement.Movements[0]; + Assert.AreEqual(1234.56m, first.Amount); + Assert.AreEqual(new DateOnly(2026, 10, 2), first.ValueDate); + Assert.AreEqual("Bonifico da \"Cliente Uno\"; saldo", first.Description); + Assert.AreEqual("CRO1", first.Reference); + Assert.AreEqual(-2.50m, statement.Movements[1].Amount); + Assert.IsNull(statement.Movements[1].Reference); + Assert.AreEqual(-1000m, statement.Movements[2].Amount); + Assert.IsNull(statement.Movements[2].ValueDate); + Assert.AreEqual(10m, statement.Movements[3].Amount); + } + + [TestMethod] + public void Read_TwoColumns_GivesMoneyInAndOut() + { + const string csv = """ + Data;Valuta;Causale;Entrate;Uscite + 01/10/2026;01/10/2026;Accredito;500,00; + 02/10/2026;02/10/2026;Addebito SDD;;120,30 + 02/10/2026;02/10/2026;Addebito con segno;;-80,00 + Saldo finale;;;; + """; + + var statement = Read(csv, TwoColumnLayout); + + CollectionAssert.AreEqual(new[] { 500m, -120.30m, -80m }, statement.Movements.Select(m => m.Amount).ToArray()); + } + + [TestMethod] + public void Read_DecimalPoint_AndQuotedFieldsOnTwoLines() + { + var layout = new CsvStatementLayout(',', 1, 0, null, 1, 2, null, null, null, "yyyy-MM-dd", DecimalComma: false); + const string csv = "Booking date,Description,Amount\r\n2026-10-01,\"Transfer\r\nfrom ACME, Inc.\",\"1,234.50\"\r\n2026-10-02,Fee,-1.25\r\n"; + + var statement = Read(csv, layout); + + Assert.HasCount(2, statement.Movements); + Assert.AreEqual("Transfer from ACME, Inc.", statement.Movements[0].Description); + Assert.AreEqual(1234.50m, statement.Movements[0].Amount); + Assert.AreEqual(-1.25m, statement.Movements[1].Amount); + } + + [TestMethod] + public void Read_Utf8WithBom_AndWindows1252() + { + const string csv = "Data;Valuta;Descrizione;Importo;CRO\n01/10/2026;01/10/2026;Caffè € e più;-1,20;\n"; + var bom = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(csv)).ToArray(); + + var utf8 = CsvStatementReader.Read(new MemoryStream(bom), SignedLayout); + Assert.AreEqual("Caffè € e più", utf8.Movements.Single().Description); + + // Windows-1252: è = E8, ù = F9, € = 80 (not valid UTF-8). + var ansi = Encoding.Latin1.GetBytes("Data;Valuta;Descrizione;Importo;CRO\n01/10/2026;01/10/2026;Caffè X e più;-1,20;\n"); + ansi[Array.IndexOf(ansi, (byte)'X')] = 0x80; + var windows = CsvStatementReader.Read(new MemoryStream(ansi), SignedLayout); + Assert.AreEqual("Caffè € e più", windows.Movements.Single().Description); + } + + [TestMethod] + public void Read_BadRows_NameTheRow() + { + var badDate = Assert.ThrowsExactly(() => Read("h\n01/10/2026;;a;1,00;\n32/13/2026;;b;2,00;\n", SignedLayout)); + StringAssert.Contains(badDate.Message, "Row 3"); + + var badAmount = Assert.ThrowsExactly(() => Read("h\n01/10/2026;;a;uno;\n", SignedLayout)); + StringAssert.Contains(badAmount.Message, "Row 2"); + + var noAmount = Assert.ThrowsExactly(() => Read("h\n01/10/2026;;a;;\n", SignedLayout)); + StringAssert.Contains(noAmount.Message, "Row 2"); + + Assert.ThrowsExactly(() => Read("h\n", new CsvStatementLayout(';', 1, 0, null, 1, null, null, null, null))); + } + + [TestMethod] + public void Read_SkipsHeaderRowsAndRowsWithoutDateAndAmount() + { + var layout = SignedLayout with { HeaderRows = 3 }; + const string csv = "Banca X\nConto 123\nData;Valuta;Descrizione;Importo;CRO\n01/10/2026;;a;1,00;\nTotale;;;;\n;;;;\n"; + + Assert.HasCount(1, Read(csv, layout).Movements); + } + + [TestMethod] + public void ParseAmount_ReadsTheBankFormats() + { + Assert.AreEqual(-1234.56m, CsvStatementReader.ParseAmount("-1.234,56", decimalComma: true)); + Assert.AreEqual(-1234.56m, CsvStatementReader.ParseAmount("1.234,56-", decimalComma: true)); + Assert.AreEqual(12m, CsvStatementReader.ParseAmount("+12,00 €", decimalComma: true)); + Assert.AreEqual(-5m, CsvStatementReader.ParseAmount("(5,00)", decimalComma: true)); + Assert.AreEqual(1234.5m, CsvStatementReader.ParseAmount("EUR 1,234.50", decimalComma: false)); + Assert.IsNull(CsvStatementReader.ParseAmount(" ", decimalComma: true)); + Assert.ThrowsExactly(() => CsvStatementReader.ParseAmount("12a", decimalComma: true)); + } + + [TestMethod] + public void Detect_ItalianBankHeaders() + { + // One signed column, value date and reference. + var a = CsvStatementReader.Detect("Data contabile;Data valuta;Descrizione operazione;Importo (EUR);CRO")!; + Assert.AreEqual(new CsvStatementLayout(';', 1, 0, 1, 2, 3, null, null, 4), a); + + // Money in and out, accents and case. + var b = CsvStatementReader.Detect("\"DATA OPERAZIONE\";\"DATA VALUTA\";\"CAUSALE\";\"DESCRIZIONE\";\"ADDEBITI\";\"ACCREDITI\"")!; + Assert.AreEqual(0, b.DateColumn); + Assert.AreEqual(1, b.ValueDateColumn); + Assert.AreEqual(3, b.DescriptionColumn); + Assert.IsNull(b.AmountColumn); + Assert.AreEqual(5, b.CreditColumn); + Assert.AreEqual(4, b.DebitColumn); + Assert.IsTrue(b.DecimalComma); + + // Tabs, Dare/Avere, "Riferimento". + var c = CsvStatementReader.Detect("Data\tValuta\tDescrizione\tDare\tAvere\tRiferimento")!; + Assert.AreEqual('\t', c.Separator); + Assert.AreEqual(3, c.DebitColumn); + Assert.AreEqual(4, c.CreditColumn); + Assert.AreEqual(5, c.ReferenceColumn); + + // Accent-insensitive: "Entrate" and "Uscite" with "Descrizióne". + var d = CsvStatementReader.Detect("Data;Descrizióne;Entrate;Uscite")!; + Assert.AreEqual(1, d.DescriptionColumn); + Assert.AreEqual(2, d.CreditColumn); + Assert.IsNull(d.ValueDateColumn); + + // English export. + var e = CsvStatementReader.Detect("Booking date,Value date,Description,Amount,Reference")!; + Assert.AreEqual(',', e.Separator); + Assert.IsFalse(e.DecimalComma); + Assert.AreEqual(4, e.ReferenceColumn); + + Assert.IsNull(CsvStatementReader.Detect("Data;Importo")); + Assert.IsNull(CsvStatementReader.Detect("Nome;Cognome;Telefono")); + Assert.IsNull(CsvStatementReader.Detect("")); + } + + [TestMethod] + public void Detect_ThenRead_WorksEndToEnd() + { + const string csv = "Data operazione;Data valuta;Descrizione;Uscite;Entrate\n12/11/2026;12/11/2026;Bonifico;;1.500,00\n13/11/2026;13/11/2026;POS;12,40;\n"; + var layout = CsvStatementReader.Detect(csv[..csv.IndexOf('\n', StringComparison.Ordinal)])!; + + var statement = Read(csv, layout); + + CollectionAssert.AreEqual(new[] { 1500m, -12.40m }, statement.Movements.Select(m => m.Amount).ToArray()); + } + + private static StatementFile Read(string csv, CsvStatementLayout layout) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(csv)); + return CsvStatementReader.Read(stream, layout); + } +} diff --git a/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.001.001.09.xsd b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.001.001.09.xsd new file mode 100644 index 0000000..cfbb599 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.001.001.09.xsd @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.008.001.08.xsd b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.008.001.08.xsd new file mode 100644 index 0000000..71ca93b --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.008.001.08.xsd @@ -0,0 +1,385 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Khaemhat.Core.Tests/Treasury/SepaXmlWriterTests.cs b/tests/Khaemhat.Core.Tests/Treasury/SepaXmlWriterTests.cs new file mode 100644 index 0000000..e7d2a03 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/SepaXmlWriterTests.cs @@ -0,0 +1,338 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using System.Xml.Schema; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Core.Tests.Treasury; + +/// +/// SEPA credit transfers (pain.001.001.09) and direct debits (pain.008.001.08), issues #70 and #71: the +/// files validate against the schemas, totals and counts, the character set, the grouping of debits and the errors. +/// +[TestClass] +public sealed class SepaXmlWriterTests +{ + private const string CompanyIban = "IT60X0542811101000000123456"; + + private static readonly BankFileCompany Company = new( + "Officine Bàlbo S.r.l.", + "01234567890", + "Via Roma 1", + "10121", + "Torino", + "TO", + "IT", + CompanyIban, + "BPMOIT22XXX", + "A1B2C", + "ABC1234X", + "IT66ZZZA1B2C3D4E5F6G7H8"); + + [TestMethod] + public void CreditTransfer_ValidatesAgainstTheSchema_WithCountsAndTotals() + { + var file = SepaXmlWriter.CreditTransfer(Transfers()); + + Assert.AreEqual("SCT_DIST-2026-0042.xml", file.FileName); + Assert.AreEqual("application/xml", file.ContentType); + AssertValid(file.Content, "pain.001.001.09.xsd", SepaXmlWriter.CreditTransferNamespace); + + var doc = Load(file.Content); + XNamespace ns = SepaXmlWriter.CreditTransferNamespace; + var header = doc.Descendants(ns + "GrpHdr").Single(); + Assert.AreEqual("DIST-2026-0042", header.Element(ns + "MsgId")!.Value); + Assert.AreEqual("2026-11-13T09:30:00", header.Element(ns + "CreDtTm")!.Value); + Assert.AreEqual("3", header.Element(ns + "NbOfTxs")!.Value); + Assert.AreEqual("1601.25", header.Element(ns + "CtrlSum")!.Value); + var initiator = header.Element(ns + "InitgPty")!; + Assert.AreEqual("ABC1234X", initiator.Descendants(ns + "Othr").Single().Element(ns + "Id")!.Value); + Assert.AreEqual("CBI", initiator.Descendants(ns + "Issr").Single().Value); + + var payment = doc.Descendants(ns + "PmtInf").Single(); + Assert.AreEqual("TRF", payment.Element(ns + "PmtMtd")!.Value); + Assert.AreEqual("true", payment.Element(ns + "BtchBookg")!.Value); + Assert.AreEqual("3", payment.Element(ns + "NbOfTxs")!.Value); + Assert.AreEqual("1601.25", payment.Element(ns + "CtrlSum")!.Value); + Assert.AreEqual("SEPA", payment.Element(ns + "PmtTpInf")!.Descendants(ns + "Cd").Single().Value); + Assert.AreEqual("2026-11-16", payment.Element(ns + "ReqdExctnDt")!.Element(ns + "Dt")!.Value); + Assert.AreEqual(CompanyIban, payment.Element(ns + "DbtrAcct")!.Descendants(ns + "IBAN").Single().Value); + Assert.AreEqual("BPMOIT22XXX", payment.Element(ns + "DbtrAgt")!.Descendants(ns + "BICFI").Single().Value); + Assert.AreEqual("SLEV", payment.Element(ns + "ChrgBr")!.Value); + + var transactions = payment.Elements(ns + "CdtTrfTxInf").ToList(); + Assert.HasCount(3, transactions); + var first = transactions[0]; + Assert.AreEqual("E2E-1", first.Descendants(ns + "EndToEndId").Single().Value); + var amount = first.Descendants(ns + "InstdAmt").Single(); + Assert.AreEqual("1000.00", amount.Value); + Assert.AreEqual("EUR", amount.Attribute("Ccy")!.Value); + Assert.AreEqual("DEUTDEFFXXX", first.Element(ns + "CdtrAgt")!.Descendants(ns + "BICFI").Single().Value); + Assert.AreEqual("DE", first.Element(ns + "Cdtr")!.Descendants(ns + "Ctry").Single().Value); + Assert.AreEqual("Berlin", first.Element(ns + "Cdtr")!.Descendants(ns + "TwnNm").Single().Value); + Assert.AreEqual("FT 2026/000388 del 31/08/2026", first.Descendants(ns + "Ustrd").Single().Value); + + // A creditor without BIC has no agent; the amount is rounded to two decimals. + Assert.IsNull(transactions[1].Element(ns + "CdtrAgt")); + Assert.AreEqual("0.25", transactions[2].Descendants(ns + "InstdAmt").Single().Value); + } + + [TestMethod] + public void CreditTransfer_WithoutBicOrCuc_WritesNotProvided_AndNoInitiatorId() + { + var remittance = Transfers() with { Company = Company with { Bic = null, CucCode = null } }; + + var file = SepaXmlWriter.CreditTransfer(remittance); + + AssertValid(file.Content, "pain.001.001.09.xsd", SepaXmlWriter.CreditTransferNamespace); + var doc = Load(file.Content); + XNamespace ns = SepaXmlWriter.CreditTransferNamespace; + Assert.AreEqual("NOTPROVIDED", doc.Descendants(ns + "DbtrAgt").Single().Descendants(ns + "Id").Single().Value); + Assert.IsNull(doc.Descendants(ns + "InitgPty").Single().Element(ns + "Id")); + } + + [TestMethod] + public void Schemas_RejectAFileOutOfTheRules() + { + var transfer = Encoding.UTF8.GetString(SepaXmlWriter.CreditTransfer(Transfers()).Content); + var debit = Encoding.UTF8.GetString(SepaXmlWriter.DirectDebit(Debits(RemittanceKind.SddCore)).Content); + + string[] brokenTransfers = + [ + transfer.Replace("TRF", "DD", StringComparison.Ordinal), + transfer.Replace("IT60X", "it60x", StringComparison.Ordinal), + transfer.Replace(">1000.00<", ">1000.001234<", StringComparison.Ordinal), + transfer.Replace("SLEV", string.Empty, StringComparison.Ordinal).Replace("", "SLEV", StringComparison.Ordinal), + transfer.Replace("pain.001.001.09", "pain.001.001.03", StringComparison.Ordinal), + ]; + foreach (var broken in brokenTransfers) + { + Assert.IsNotEmpty(Validate(Encoding.UTF8.GetBytes(broken), "pain.001.001.09.xsd", SepaXmlWriter.CreditTransferNamespace)); + } + + Assert.IsNotEmpty(Validate( + Encoding.UTF8.GetBytes(debit.Replace("FRST", "FIRST", StringComparison.Ordinal)), + "pain.008.001.08.xsd", + SepaXmlWriter.DirectDebitNamespace)); + Assert.IsNotEmpty(Validate( + Encoding.UTF8.GetBytes(debit.Replace("MND-001", "" + new string('M', 36) + "", StringComparison.Ordinal)), + "pain.008.001.08.xsd", + SepaXmlWriter.DirectDebitNamespace)); + } + + [TestMethod] + public void CreditTransfer_IsUtf8WithoutBom() + { + var file = SepaXmlWriter.CreditTransfer(Transfers()); + + Assert.AreEqual((byte)'<', file.Content[0]); + StringAssert.StartsWith(Encoding.UTF8.GetString(file.Content), ""); + } + + [TestMethod] + public void Texts_AreReducedToTheSepaCharacterSet_AndCut() + { + Assert.AreEqual("Officine Balbo S.r.l.", SepaXmlWriter.Text("Officine Bàlbo S.r.l.", 70)); + Assert.AreEqual("Citta Perche Pero E E AEIOU", SepaXmlWriter.Text("Città Perché Però È É ÀÈÌÒÙ", 70)); + Assert.AreEqual("Rossi Figli - n 5 (ok)", SepaXmlWriter.Text("Rossi & Figli - n° 5 (ok)", 70)); + Assert.AreEqual("abc", SepaXmlWriter.Text(" abc€ ", 70)); + Assert.AreEqual(string.Empty, SepaXmlWriter.Text(null, 70)); + Assert.AreEqual("12345", SepaXmlWriter.Text("123456789", 5)); + + var item = Transfers().Items[0] with + { + CounterpartyName = "Società " + new string('x', 100), + Reference = new string('r', 200) + " & co", + EndToEndId = new string('e', 50), + }; + var doc = Load(SepaXmlWriter.CreditTransfer(Transfers() with { Items = [item] }).Content); + XNamespace ns = SepaXmlWriter.CreditTransferNamespace; + var name = doc.Descendants(ns + "Cdtr").Single().Element(ns + "Nm")!.Value; + Assert.AreEqual(70, name.Length); + StringAssert.StartsWith(name, "Societa x"); + Assert.AreEqual(140, doc.Descendants(ns + "Ustrd").Single().Value.Length); + Assert.AreEqual(35, doc.Descendants(ns + "EndToEndId").Single().Value.Length); + } + + [TestMethod] + public void DirectDebit_ValidatesAgainstTheSchema_AndGroupsBySequenceAndDate() + { + var file = SepaXmlWriter.DirectDebit(Debits(RemittanceKind.SddCore)); + + Assert.AreEqual("SDD_RID-7.xml", file.FileName); + AssertValid(file.Content, "pain.008.001.08.xsd", SepaXmlWriter.DirectDebitNamespace); + + var doc = Load(file.Content); + XNamespace ns = SepaXmlWriter.DirectDebitNamespace; + var header = doc.Descendants(ns + "GrpHdr").Single(); + Assert.AreEqual("4", header.Element(ns + "NbOfTxs")!.Value); + Assert.AreEqual("460.00", header.Element(ns + "CtrlSum")!.Value); + + var groups = doc.Descendants(ns + "PmtInf").ToList(); + Assert.HasCount(3, groups); + string Describe(XElement g) => string.Create( + CultureInfo.InvariantCulture, + $"{g.Element(ns + "ReqdColltnDt")!.Value} {g.Descendants(ns + "SeqTp").Single().Value} {g.Element(ns + "NbOfTxs")!.Value} {g.Element(ns + "CtrlSum")!.Value}"); + Assert.AreEqual("2026-12-01 FRST 1 100.00", Describe(groups[0])); + Assert.AreEqual("2026-12-01 RCUR 2 300.00", Describe(groups[1])); + Assert.AreEqual("2026-12-15 RCUR 1 60.00", Describe(groups[2])); + Assert.AreEqual("RID-7-1", groups[0].Element(ns + "PmtInfId")!.Value); + Assert.AreEqual("RID-7-3", groups[2].Element(ns + "PmtInfId")!.Value); + + var first = groups[0]; + Assert.AreEqual("DD", first.Element(ns + "PmtMtd")!.Value); + Assert.AreEqual("CORE", first.Descendants(ns + "LclInstrm").Single().Element(ns + "Cd")!.Value); + Assert.AreEqual("IT66ZZZA1B2C3D4E5F6G7H8", first.Element(ns + "CdtrSchmeId")!.Descendants(ns + "Id").Last().Value); + Assert.AreEqual("SEPA", first.Element(ns + "CdtrSchmeId")!.Descendants(ns + "Prtry").Single().Value); + Assert.AreEqual(CompanyIban, first.Element(ns + "CdtrAcct")!.Descendants(ns + "IBAN").Single().Value); + + var debit = first.Elements(ns + "DrctDbtTxInf").Single(); + Assert.AreEqual("100.00", debit.Element(ns + "InstdAmt")!.Value); + Assert.AreEqual("MND-001", debit.Descendants(ns + "MndtId").Single().Value); + Assert.AreEqual("2025-03-01", debit.Descendants(ns + "DtOfSgntr").Single().Value); + Assert.AreEqual("NOTPROVIDED", debit.Element(ns + "DbtrAgt")!.Descendants(ns + "Id").Single().Value); + Assert.AreEqual("IT63A0200801600000101234567", debit.Element(ns + "DbtrAcct")!.Descendants(ns + "IBAN").Single().Value); + } + + [TestMethod] + public void DirectDebit_B2b_WritesTheB2bInstrument() + { + var file = SepaXmlWriter.DirectDebit(Debits(RemittanceKind.SddB2b)); + + AssertValid(file.Content, "pain.008.001.08.xsd", SepaXmlWriter.DirectDebitNamespace); + XNamespace ns = SepaXmlWriter.DirectDebitNamespace; + Assert.IsTrue(Load(file.Content).Descendants(ns + "LclInstrm").All(l => l.Element(ns + "Cd")!.Value == "B2B")); + } + + [TestMethod] + public void DirectDebit_SequenceCodes_CoverEveryValue() + { + var debits = Debits(RemittanceKind.SddCore); + var items = new[] { SddSequence.First, SddSequence.Recurrent, SddSequence.Final, SddSequence.OneOff } + .Select((s, i) => debits.Items[0] with { Sequence = s, EndToEndId = "E" + i.ToString(CultureInfo.InvariantCulture) }) + .ToList(); + + var doc = Load(SepaXmlWriter.DirectDebit(debits with { Items = items }).Content); + + XNamespace ns = SepaXmlWriter.DirectDebitNamespace; + CollectionAssert.AreEqual(new[] { "FRST", "RCUR", "FNAL", "OOFF" }, doc.Descendants(ns + "SeqTp").Select(s => s.Value).ToArray()); + } + + [TestMethod] + public void Errors_AreBankFileExceptions() + { + var transfers = Transfers(); + var debits = Debits(RemittanceKind.SddCore); + var transfer = transfers.Items[0]; + var debit = debits.Items[0]; + + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = -5m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0.004m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "" } })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "IT61X0542811101000000123456" } })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = null }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = "DE89370400440532013001" }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Bic = "NOT A BIC" }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.SddCore })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.Riba })); + + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Company = Company with { CreditorId = null } })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateId = " " }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateDate = null }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Amount = 0m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Iban = "" }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Kind = RemittanceKind.SepaCreditTransfer })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Kind = RemittanceKind.Riba })); + } + + private static BankFileRemittance Transfers() => new( + RemittanceKind.SepaCreditTransfer, + "DIST-2026-0042", + new DateTime(2026, 11, 13, 9, 30, 0, DateTimeKind.Local), + new DateOnly(2026, 11, 16), + Company, + [ + new BankFileItem(1, "F001", "Müller GmbH", "DE123456789", "Hauptstraße 5", "10115", "Berlin", null, "DE", "DE89370400440532013000", "DEUTDEFF XXX", null, 1000m, new DateOnly(2026, 11, 16), "FT 2026/000388 del 31/08/2026", "E2E-1"), + new BankFileItem(2, "F002", "Fornitore Rossi & C.", "01234567897", null, null, null, null, "it", "IT68 X030 6909 6061 0000 0063 241", null, null, 601m, new DateOnly(2026, 11, 16), "Saldo fattura 12", "E2E-2"), + new BankFileItem(3, "F003", "Société Générale Client", null, "1 rue de la Paix", "75002", "Paris", null, "FR", "FR1420041010050500013M02606", null, null, 0.249m, new DateOnly(2026, 11, 16), "Arrotondamento", "E2E-3"), + ]); + + private static BankFileRemittance Debits(RemittanceKind kind) + { + BankFileItem Debit(int n, decimal amount, DateOnly due, SddSequence sequence) => new( + n, + "C00" + n.ToString(CultureInfo.InvariantCulture), + "Cliente " + n.ToString(CultureInfo.InvariantCulture), + null, + "Via Po " + n.ToString(CultureInfo.InvariantCulture), + "20121", + "Milano", + "MI", + "IT", + "IT63A0200801600000101234567", + null, + null, + amount, + due, + "Canone dicembre", + "RID7-" + n.ToString(CultureInfo.InvariantCulture), + "MND-00" + n.ToString(CultureInfo.InvariantCulture), + new DateOnly(2025, 3, 1), + sequence); + + var first = new DateOnly(2026, 12, 1); + var second = new DateOnly(2026, 12, 15); + return new BankFileRemittance( + kind, + "RID-7", + new DateTime(2026, 11, 13, 10, 0, 0, DateTimeKind.Local), + first, + Company, + [ + Debit(1, 100m, first, SddSequence.First), + Debit(2, 120m, first, SddSequence.Recurrent), + Debit(3, 60m, second, SddSequence.Recurrent), + Debit(4, 180m, first, SddSequence.Recurrent), + ]); + } + + private static XDocument Load(byte[] content) + { + using var stream = new MemoryStream(content); + return XDocument.Load(stream); + } + + private static void AssertValid(byte[] content, string schemaFile, string ns) + { + var errors = Validate(content, schemaFile, ns); + Assert.IsEmpty(errors, string.Join(Environment.NewLine, errors)); + } + + // Warnings are reported too, so that an element the schema does not know (or a wrong namespace) is not skipped. + private static List Validate(byte[] content, string schemaFile, string ns) + { + var schemas = new XmlSchemaSet(); + schemas.Add(ns, Path.Combine(AppContext.BaseDirectory, "Treasury", "Schemas", schemaFile)); + var errors = new List(); + var settings = new XmlReaderSettings + { + ValidationType = ValidationType.Schema, + Schemas = schemas, + ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints, + }; + settings.ValidationEventHandler += (_, e) => errors.Add($"{e.Severity}: {e.Message} (line {e.Exception?.LineNumber})"); + using var stream = new MemoryStream(content); + using (var reader = XmlReader.Create(stream, settings)) + { + while (reader.Read()) + { + } + } + + return errors; + } +} diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 84bf94f..bc19b8c 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -84,6 +84,8 @@ public sealed class MappingTests "inventory_entries", "inventory_entry_lines", "item_balances", "stock_takes", "stock_take_lines", "gl_accounts", "vat_registers", "gl_journal_templates", "gl_journal_template_lines", "gl_entries", "gl_entry_lines", "gl_entry_vat", "gl_open_items", "gl_recurring_entries", "vat_settlements", "vat_settlement_lines", "tax_payments", "withholdings", "vat_register_prints", + "payments", "payment_lines", "remittances", "remittance_lines", "sdd_mandates", "bank_statements", "bank_statement_lines", + "bank_match_rules", "dunning_levels", "dunning_letters", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/CbiStatementReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/CbiStatementReaderTests.cs new file mode 100644 index 0000000..a162c4f --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/CbiStatementReaderTests.cs @@ -0,0 +1,147 @@ +using System.Text; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// The CBI current account statement (issue #71): balances, movements and their description lines. +[TestClass] +public sealed class CbiStatementReaderTests +{ + private static readonly CbiStatementReader Reader = new(); + + [TestMethod] + public void Read_SampleStatement_WithBalancesMovementsAndDescriptions() + { + var statement = Read(string.Join("\r\n", Sample())); + + Assert.AreEqual(StatementFormat.Cbi, Reader.Format); + Assert.AreEqual(StatementFormat.Cbi, statement.Format); + Assert.AreEqual("IT60X0542811101000000123456", statement.AccountIban); + Assert.AreEqual("EUR", statement.Currency); + Assert.AreEqual(1000m, statement.OpeningBalance); + Assert.AreEqual(2207.50m, statement.ClosingBalance); + Assert.AreEqual(new DateOnly(2026, 10, 31), statement.FromDate); + Assert.AreEqual(new DateOnly(2026, 11, 3), statement.ToDate); + Assert.HasCount(3, statement.Movements); + Assert.AreEqual(statement.ClosingBalance, statement.OpeningBalance + statement.Movements.Sum(m => m.Amount)); + + var first = statement.Movements[0]; + Assert.AreEqual(new DateOnly(2026, 11, 2), first.BookingDate); + Assert.AreEqual(new DateOnly(2026, 11, 3), first.ValueDate); + Assert.AreEqual(1220.50m, first.Amount); + Assert.AreEqual("48", first.BankCode); + Assert.AreEqual("CRO123456", first.Reference); + Assert.AreEqual("BONIFICO A VOSTRO FAVORE DA CLIENTE UNO SPA SALDO FT 388", first.Description); + + var second = statement.Movements[1]; + Assert.AreEqual(-12.50m, second.Amount); + Assert.AreEqual("COMMISSIONI", second.Description); + Assert.IsNull(second.Reference); + + // The amount with the comma as some banks write it. + Assert.AreEqual(-0.50m, statement.Movements[2].Amount); + } + + [TestMethod] + public void Read_LinesWithoutLeadingSpace_AndWithoutLineBreaks() + { + var trimmed = string.Join("\n", Sample().Select(l => l[1..])); + Assert.HasCount(3, Read(trimmed).Movements); + + var stream = string.Concat(Sample()); + var statement = Read(stream); + Assert.HasCount(3, statement.Movements); + Assert.AreEqual(2207.50m, statement.ClosingBalance); + } + + [TestMethod] + public void Recognizes_TheRhHeader_WithOrWithoutLeadingSpace() + { + var lines = Sample(); + Assert.IsTrue(Reader.Recognizes(Encoding.ASCII.GetBytes(string.Join("\r\n", lines)))); + Assert.IsTrue(Reader.Recognizes(Encoding.ASCII.GetBytes("\r\n" + string.Join("\r\n", lines.Select(l => l[1..]))))); + Assert.IsTrue(Reader.Recognizes(Encoding.ASCII.GetBytes(string.Concat(lines)))); + Assert.IsFalse(Reader.Recognizes(Encoding.ASCII.GetBytes(" RH short\r\n"))); + Assert.IsFalse(Reader.Recognizes(Encoding.ASCII.GetBytes("Data;Descrizione;Importo\r\n"))); + Assert.IsFalse(Reader.Recognizes(Encoding.ASCII.GetBytes(" IB" + new string(' ', 117)))); + } + + [TestMethod] + public void Read_Errors_AreBankFileExceptions() + { + var lines = Sample(); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", lines.Skip(1)))); + + var badSign = lines.ToArray(); + badSign[2] = Put(badSign[2], 26, "X"); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", badSign))); + + var badAmount = lines.ToArray(); + badAmount[2] = Put(badAmount[2], 27, "00000ABC0000000"); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", badAmount))); + + var badDate = lines.ToArray(); + badDate[2] = Put(badDate[2], 20, "321326"); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", badDate))); + + var orphan = lines.ToList(); + orphan.Insert(2, Record("63", (4, "0000001"), (11, "001"), (14, "ORFANA"))); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", orphan))); + } + + private static List Sample() => + [ + Record("RH", (4, "05428"), (9, "A1B2C"), (14, "041126"), (20, "ESTRATTO-2026-11"), (114, "E")), + Record( + "61", + (4, "0000001"), + (52, "X"), + (53, "05428"), + (58, "11101"), + (63, "000000123456"), + (75, "EUR"), + (78, "311026"), + (84, "C"), + (85, "000000000100000"), + (100, "IT"), + (102, "60")), + Record( + "62", + (4, "0000001"), + (11, "001"), + (14, "031126"), + (20, "021126"), + (26, "C"), + (27, "000000000122050"), + (42, "48"), + (44, "00"), + (62, "CRO123456"), + (87, "BONIFICO A VOSTRO FAVORE")), + Record("63", (4, "0000001"), (11, "001"), (14, "DA CLIENTE UNO SPA")), + Record("63", (4, "0000001"), (11, "001"), (14, "SALDO FT 388")), + Record("62", (4, "0000001"), (11, "002"), (14, "031126"), (20, "031126"), (26, "D"), (27, "000000000001250"), (42, "26"), (87, "COMMISSIONI")), + Record("62", (4, "0000001"), (11, "003"), (14, "031126"), (20, "031126"), (26, "D"), (27, " 0,50"), (42, "26"), (87, "BOLLO")), + Record("64", (4, "0000001"), (11, "EUR"), (14, "031126"), (20, "C"), (21, "000000000220750"), (36, "C"), (37, "000000000220750")), + Record("EF", (4, "05428"), (9, "A1B2C"), (14, "041126"), (20, "ESTRATTO-2026-11"), (46, "0000001"), (83, "0000009"), (114, "E")), + ]; + + private static string Record(string type, params (int Position, string Value)[] fields) + { + var line = " " + type + new string(' ', 117); + foreach (var (position, value) in fields) + { + line = Put(line, position, value); + } + + return line; + } + + private static string Put(string line, int position, string value) => + line[..(position - 1)] + value + line[(position - 1 + value.Length)..]; + + private static StatementFile Read(string text) + { + using var stream = new MemoryStream(Encoding.Latin1.GetBytes(text)); + return Reader.Read(stream); + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/LatePaymentRulesItTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/LatePaymentRulesItTests.cs new file mode 100644 index 0000000..0a1e4c2 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/LatePaymentRulesItTests.cs @@ -0,0 +1,28 @@ +namespace Khaemhat.Fiscal.Italy.Tests; + +/// The late payment interest of D.Lgs. 231/2002 (issue #72): the reference rate of the half-year plus eight points. +[TestClass] +public sealed class LatePaymentRulesItTests +{ + private static readonly LatePaymentRulesIt Rules = new(); + + [TestMethod] + [DataRow(2025, 3, 10, 11.15)] + [DataRow(2026, 1, 1, 10.15)] + [DataRow(2026, 6, 30, 10.15)] + [DataRow(2026, 7, 1, 10.40)] + [DataRow(2026, 12, 31, 10.40)] + public void RateOn_IsTheRateOfTheHalfYearPlusEightPoints(int year, int month, int day, double expected) => + Assert.AreEqual((decimal)expected, Rules.RateOn(new DateOnly(year, month, day))); + + [TestMethod] + public void AfterTheLastPublishedRate_TheLastRateApplies() => + Assert.AreEqual(Rules.RateOn(new DateOnly(2026, 12, 31)), Rules.RateOn(new DateOnly(2030, 1, 1))); + + [TestMethod] + public void TheCompensation_IsFortyEuros() + { + Assert.AreEqual(40m, Rules.RecoveryCompensation); + Assert.AreEqual("D.Lgs. 231/2002", Rules.LegalReference); + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/RibaCbiWriterTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/RibaCbiWriterTests.cs new file mode 100644 index 0000000..ecd2af6 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/RibaCbiWriterTests.cs @@ -0,0 +1,183 @@ +using System.Text; +using Khaemhat.Core.Treasury; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// Bank receipts in the CBI fixed-width layout (issue #70): record lengths, order, positions and totals. +[TestClass] +public sealed class RibaCbiWriterTests +{ + private static readonly RibaCbiWriter Writer = new(); + + private static readonly BankFileCompany Company = new( + "Officine Bàlbo S.r.l.", + "01234567890", + "Via Roma 1", + "10121", + "Torino", + "TO", + "IT", + "IT60X0542811101000000123456", + null, + "a1b2c", + null, + null); + + [TestMethod] + public void Supports_OnlyRiba() + { + Assert.IsTrue(Writer.Supports(RemittanceKind.Riba)); + Assert.IsFalse(Writer.Supports(RemittanceKind.SddCore)); + Assert.IsFalse(Writer.Supports(RemittanceKind.SepaCreditTransfer)); + } + + [TestMethod] + public void Write_EveryRecordIs120Characters_InTheCbiOrder() + { + var file = Writer.Write(Remittance()); + + Assert.AreEqual("RIBA_RB-2026-11.txt", file.FileName); + Assert.AreEqual("text/plain", file.ContentType); + var text = Encoding.ASCII.GetString(file.Content); + Assert.IsTrue(text.EndsWith("\r\n", StringComparison.Ordinal)); + Assert.IsTrue(file.Content.All(b => b < 128)); + var lines = Lines(file); + Assert.IsTrue(lines.All(l => l.Length == 120), string.Join("\n", lines.Where(l => l.Length != 120))); + CollectionAssert.AreEqual( + new[] { "IB", "14", "20", "30", "40", "50", "51", "70", "14", "20", "30", "40", "50", "51", "70", "EF" }, + lines.Select(l => l[1..3]).ToArray()); + Assert.IsTrue(lines.All(l => l[0] == ' ')); + } + + [TestMethod] + public void Write_HeaderAndReceipt_HaveTheValuesAtTheirPositions() + { + var lines = Lines(Writer.Write(Remittance())); + + var header = lines[0]; + Assert.AreEqual("A1B2C", At(header, 4, 8)); + Assert.AreEqual("05428", At(header, 9, 13)); + Assert.AreEqual("131126", At(header, 14, 19)); + Assert.AreEqual("RB-2026-11 ", At(header, 20, 39)); + Assert.AreEqual("E", At(header, 114, 114)); + + var receipt = lines[1]; + Assert.AreEqual("0000001", At(receipt, 4, 10)); + Assert.AreEqual("311226", At(receipt, 23, 28)); + Assert.AreEqual("30000", At(receipt, 29, 33)); + Assert.AreEqual("0000000122050", At(receipt, 34, 46)); + Assert.AreEqual("-", At(receipt, 47, 47)); + Assert.AreEqual("05428", At(receipt, 48, 52)); + Assert.AreEqual("11101", At(receipt, 53, 57)); + Assert.AreEqual("000000123456", At(receipt, 58, 69)); + Assert.AreEqual("02008", At(receipt, 70, 74)); + Assert.AreEqual("01600", At(receipt, 75, 79)); + Assert.AreEqual("A1B2C", At(receipt, 92, 96)); + Assert.AreEqual("4", At(receipt, 97, 97)); + Assert.AreEqual("C0001 ", At(receipt, 98, 113)); + Assert.AreEqual("E", At(receipt, 120, 120)); + + var creditor = lines[2]; + Assert.AreEqual("OFFICINE BALBO S.R.L. ", At(creditor, 11, 34)); + Assert.AreEqual("VIA ROMA 1", At(creditor, 35, 58).TrimEnd()); + Assert.AreEqual("10121 TORINO TO", At(creditor, 59, 82).TrimEnd()); + Assert.AreEqual("01234567890", At(creditor, 83, 106).TrimEnd()); + + var debtor = lines[3]; + Assert.AreEqual("CITTA DI MONDOVI SOCIETA COOPE", At(debtor, 11, 40)); + Assert.AreEqual("RATIVA", At(debtor, 41, 70).TrimEnd()); + Assert.AreEqual("RSSMRA80A01H501U", At(debtor, 71, 86)); + + var address = lines[4]; + Assert.AreEqual("PIAZZA MAGGIORE 3", At(address, 11, 40).TrimEnd()); + Assert.AreEqual("12084", At(address, 41, 45)); + Assert.AreEqual("MONDOVI", At(address, 46, 67).TrimEnd()); + Assert.AreEqual("CN", At(address, 69, 70)); + Assert.AreEqual("UNICREDIT AG. 2", At(address, 71, 120).TrimEnd()); + + var reference = lines[5]; + Assert.AreEqual("FT 2026/000388 DEL 31/08/2026", At(reference, 11, 50).TrimEnd()); + Assert.AreEqual("01234567890", At(reference, 101, 116).TrimEnd()); + + var number = lines[6]; + Assert.AreEqual("0000000007", At(number, 11, 20)); + Assert.AreEqual("OFFICINE BALBO S.R.L", At(number, 21, 40)); + + Assert.AreEqual("0000001", At(lines[7], 4, 10)); + Assert.AreEqual(string.Empty, At(lines[7], 11, 120).Trim()); + Assert.AreEqual("0000002", At(lines[8], 4, 10)); + } + + [TestMethod] + public void Write_Footer_CountsReceiptsRecordsAndTotal() + { + var footer = Lines(Writer.Write(Remittance()))[^1]; + + Assert.AreEqual("EF", At(footer, 2, 3)); + Assert.AreEqual("A1B2C", At(footer, 4, 8)); + Assert.AreEqual("05428", At(footer, 9, 13)); + Assert.AreEqual("131126", At(footer, 14, 19)); + Assert.AreEqual("RB-2026-11", At(footer, 20, 39).TrimEnd()); + Assert.AreEqual("0000002", At(footer, 46, 52)); + Assert.AreEqual("000000000132050", At(footer, 53, 67)); + Assert.AreEqual("000000000000000", At(footer, 68, 82)); + Assert.AreEqual("0000016", At(footer, 83, 89)); + Assert.AreEqual("E", At(footer, 114, 114)); + } + + [TestMethod] + public void Write_Errors_AreBankFileExceptions() + { + var remittance = Remittance(); + var item = remittance.Items[0]; + + Assert.ThrowsExactly(() => Writer.Write(remittance with { Company = Company with { SiaCode = null } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Company = Company with { SiaCode = "123" } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Company = Company with { Iban = "DE89370400440532013000" } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Company = Company with { Iban = "IT61X0542811101000000123456" } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Iban = null }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Iban = "DE89370400440532013000" }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Amount = 0m }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Amount = 100_000_000_000m }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Kind = RemittanceKind.SddCore })); + } + + [TestMethod] + public void Text_IsUpperCaseAsciiPaddedOrCut() + { + Assert.AreEqual("PERCHE CITTA ", RibaCbiWriter.Text("perché città", 14)); + Assert.AreEqual("ABC", RibaCbiWriter.Text("abcdef", 3)); + Assert.AreEqual("A B ", RibaCbiWriter.Text("a€b", 4)); + } + + [TestMethod] + public void Pack_ExposesTheRemittanceWriterAndTheStatementReader() + { + var pack = new ItalyFiscalPack(); + + Assert.IsTrue(pack.Require().Supports(RemittanceKind.Riba)); + Assert.AreEqual(StatementFormat.Cbi, pack.Require().Format); + } + + private static BankFileRemittance Remittance() => new( + RemittanceKind.Riba, + "RB-2026-11", + new DateTime(2026, 11, 13, 9, 0, 0, DateTimeKind.Local), + new DateOnly(2026, 11, 13), + Company, + [ + new BankFileItem( + 7, "C0001", "Città di Mondovì Società Cooperativa", "RSSMRA80A01H501U", "Piazza Maggiore 3", "12084", "Mondovì", "CN", "IT", + "IT63A0200801600000101234567", null, "UniCredit Ag. 2", 1220.50m, new DateOnly(2026, 12, 31), "FT 2026/000388 del 31/08/2026", "E1"), + new BankFileItem( + 8, "C0002", "Bianchi Snc", "01234567897", "Via Po 2", "20121", "Milano", "MI", "IT", + "IT11B0503401633000000012345", null, "Banco BPM", 100m, new DateOnly(2027, 1, 31), "FT 2026/000401", "E2"), + ]); + + private static string[] Lines(BankFile file) => + Encoding.ASCII.GetString(file.Content).Split("\r\n", StringSplitOptions.RemoveEmptyEntries); + + private static string At(string line, int from, int to) => line[(from - 1)..to]; +} diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index ff40898..e090f77 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -95,7 +95,7 @@ public sealed partial class LocalizationRulesTests keys.AddRange(UserPreferences.Accents.Select(a => "Pages.Profile.Accent." + a)); keys.AddRange(Enum.GetValues().Select(v => "Pages.Catalog.Windows.Toast." + v)); - Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList()); + Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k)))); } [TestMethod] @@ -115,7 +115,7 @@ public sealed partial class LocalizationRulesTests keys.AddRange(typeof(LedgerErrors).GetFields(BindingFlags.Public | BindingFlags.Static) .Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!)); - Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList()); + Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k)))); } [TestMethod] diff --git a/tests/Khaemhat.Web.Tests/Treasury/TreasuryTests.cs b/tests/Khaemhat.Web.Tests/Treasury/TreasuryTests.cs new file mode 100644 index 0000000..74e30a2 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Treasury/TreasuryTests.cs @@ -0,0 +1,245 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Ledger; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Application.Seeding; +using Khaemhat.Application.Treasury; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Treasury; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Treasury; + +/// +/// The schedule and the treasury on a real instance (issues #69-#72): the demo treasury seeded on top of the demo +/// ledger, a collection registered and cancelled, the RiBa remittance written to a file, the bank statement reconciled, +/// the reminders proposed and the cash flow forecast. After every flow the trial balance still balances. +/// +[TestClass] +public sealed class TreasuryTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task DemoTreasury_IsSeededOnce_AndKeepsTheLedgerBalanced() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var today = DateOnly.FromDateTime(DateTime.Now); + var payments = app.Services.GetRequiredService(); + var remittances = app.Services.GetRequiredService(); + var schedule = app.Services.GetRequiredService(); + + var collected = await payments.ListAsync(Root, company, PaymentDirection.Receipt, Year, Next); + var paid = await payments.ListAsync(Root, company, PaymentDirection.Disbursement, Year, Next); + TestContext.WriteLine($"Collections {collected.Count}, payments {paid.Count}"); + Assert.IsNotEmpty(collected); + Assert.IsNotEmpty(paid); + Assert.IsTrue(collected.All(p => p.EntryNumber is not null), "Every collection has its entry."); + + // A partial collection leaves a partial item; the RiBa back unpaid reopens its item. + var receivables = await schedule.ItemsAsync(Root, company, new ScheduleFilter(OpenItemDirection.Receivable, ScheduleView.All)); + Assert.IsTrue(receivables.Rows.Any(r => r.Item.Status == OpenItemStatus.Partial)); + var list = await remittances.ListAsync(Root, company, today.Year); + if (list.Any(r => r.Remittance.Status == RemittanceStatus.Closed)) + { + Assert.IsTrue(receivables.Rows.Any(r => r.Item.Status == OpenItemStatus.Unpaid && r.Item.UnpaidCount == 1)); + Assert.IsTrue(receivables.Rows.Any(r => r.Item.ParentId is not null && r.Item.Amount == DemoTreasurySeeder.UnpaidFees), "The fees of the unpaid effect are charged."); + } + + Assert.IsNotEmpty(await app.Services.GetRequiredService().ListAsync(Root, company)); + Assert.IsNotEmpty(await app.Services.GetRequiredService().HistoryAsync(Root, company)); + Assert.IsNotEmpty(await app.Services.GetRequiredService().RulesAsync(Root, company)); + await AssertBalancedAsync(app.Services, company); + + // Run again, nothing changes. + await app.Services.GetRequiredService().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true)); + Assert.HasCount(collected.Count, await payments.ListAsync(Root, company, PaymentDirection.Receipt, Year, Next)); + Assert.HasCount(list.Count, await remittances.ListAsync(Root, company, today.Year)); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task ACollection_SettlesTheItems_AndIsCancelled() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var payments = app.Services.GetRequiredService(); + var schedule = app.Services.GetRequiredService(); + var open = (await schedule.ItemsAsync(Root, company, new ScheduleFilter(OpenItemDirection.Receivable))).Rows + .First(r => r.Item.Status == OpenItemStatus.Open && r.Item.Residual > 10m).Item; + var day = DateOnly.FromDateTime(DateTime.Now); + + // More than the residual is refused. + await Assert.ThrowsExactlyAsync(() => payments.RegisterAsync(Root, company, new PaymentInput( + PaymentDirection.Receipt, open.PartyId, day, null, null, 0m, null, null, [new PaymentLineInput(open.Id, open.Residual + 1m)]))); + + // Half, then the rest: the item is partial, then closed. + var half = Math.Round(open.Residual / 2m, 2); + var first = await payments.RegisterAsync(Root, company, new PaymentInput( + PaymentDirection.Receipt, open.PartyId, day, null, null, 0m, "CRO TEST1", null, [new PaymentLineInput(open.Id, half)])); + Assert.AreEqual(OpenItemStatus.Partial, (await schedule.ItemAsync(Root, company, open.Id))!.Item.Status); + var second = await payments.RegisterAsync(Root, company, new PaymentInput( + PaymentDirection.Receipt, open.PartyId, day, null, null, 0m, "CRO TEST2", null, [new PaymentLineInput(open.Id, open.Residual - half)])); + var closed = (await schedule.ItemAsync(Root, company, open.Id))!.Item; + Assert.AreEqual(OpenItemStatus.Closed, closed.Status); + Assert.AreEqual(0m, closed.Residual); + Assert.IsNotNull(first.GlEntryId); + await AssertBalancedAsync(app.Services, company); + + // Cancelling both gives the item back as it was, and the entries go away. + await payments.CancelAsync(Root, company, second.Id); + await payments.CancelAsync(Root, company, first.Id); + var back = (await schedule.ItemAsync(Root, company, open.Id))!.Item; + Assert.AreEqual(OpenItemStatus.Open, back.Status); + Assert.AreEqual(open.Residual, back.Residual); + Assert.IsNull(await payments.GetAsync(Root, company, first.Id)); + await AssertBalancedAsync(app.Services, company); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task TheRibaRemittance_IsWrittenToAFile() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var remittances = app.Services.GetRequiredService(); + var today = DateOnly.FromDateTime(DateTime.Now); + var draft = (await remittances.ListAsync(Root, company, today.Year)).FirstOrDefault(r => r.Remittance.Status == RemittanceStatus.Draft); + if (draft is null) + { + Assert.Inconclusive("No RiBa due in the next weeks in the demo data of today."); + } + + var file = await remittances.FileAsync(Root, company, draft.Remittance.Id); + var text = Encoding.Latin1.GetString(file.Content); + var records = text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); + TestContext.WriteLine(file.FileName); + Assert.StartsWith(" IB", records[0]); + Assert.StartsWith(" EF", records[^1]); + Assert.IsTrue(records.All(r => r.Length == 120), "Every CBI record is 120 characters."); + Assert.AreEqual(RemittanceStatus.Generated, (await remittances.GetAsync(Root, company, draft.Remittance.Id))!.Value.Row.Remittance.Status); + + // Presented: the effects leave the customers for the bank, the entry balances. + await remittances.PresentAsync(Root, company, draft.Remittance.Id); + var presented = (await remittances.GetAsync(Root, company, draft.Remittance.Id))!.Value; + Assert.AreEqual(RemittanceStatus.Presented, presented.Row.Remittance.Status); + Assert.IsNotNull(presented.Row.Remittance.GlEntryId); + await AssertBalancedAsync(app.Services, company); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task TheBankStatement_IsReconciled() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var reconciliation = app.Services.GetRequiredService(); + var bank = await BankAsync(app.Services, company); + var lines = await reconciliation.LinesAsync(Root, company, bank, onlyOpen: true); + foreach (var l in lines) + { + TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{l.Line.BookingDate:dd/MM} {l.Line.Amount,10:0.00} {l.Line.Status} {l.Line.MatchKind} {l.Line.Confidence} {l.Line.Description}")); + } + + Assert.IsTrue(lines.Any(l => l.Line.MatchKind == StatementMatchKind.Rule && l.Line.Amount == -DemoTreasurySeeder.AccountFee)); + Assert.IsTrue(lines.Any(l => l.Line.Status == StatementLineStatus.ToMatch), "The movement nobody knows stays to match."); + + // The same file again adds nothing. + var again = await reconciliation.StatementsAsync(Root, company, bank); + Assert.HasCount(1, again); + + // Confirming the suggestions posts the fee and matches the rest; the unknown movement stays. + var confirmed = await reconciliation.ConfirmAllAsync(Root, company, bank); + Assert.IsGreaterThan(0, confirmed); + var left = await reconciliation.LinesAsync(Root, company, bank, onlyOpen: true); + Assert.IsTrue(left.All(l => l.Line.Status != StatementLineStatus.Matched)); + var unknown = left.First(l => l.Line.Status == StatementLineStatus.ToMatch); + await reconciliation.IgnoreAsync(Root, company, unknown.Line.Id); + var position = await reconciliation.PositionAsync(Root, company, bank); + TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"Book {position.BookBalance:0.00}, to match {position.ToMatch}")); + Assert.AreEqual(0, position.ToMatch); + Assert.IsGreaterThan(0m, position.BookBalance, "The demo bank starts with the capital paid in."); + await AssertBalancedAsync(app.Services, company); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Reminders_AndCashFlow_AreComputed() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var dunning = app.Services.GetRequiredService(); + Assert.HasCount(3, await dunning.LevelsAsync(Root, company)); + var proposal = await dunning.ProposalAsync(Root, company); + foreach (var p in proposal) + { + TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{p.PartyName}: {p.Items.Count} items {p.Overdue:0.00} level {p.Level?.Level} ({p.MaxDays} days)")); + } + + Assert.IsNotEmpty(proposal); + var pdf = await dunning.PreviewAsync(Root, company, proposal[0].PartyId); + Assert.StartsWith("%PDF", Encoding.ASCII.GetString(pdf.Content, 0, 4)); + + var forecast = await app.Services.GetRequiredService().ForecastAsync(Root, company); + Assert.IsNotEmpty(forecast.Accounts); + Assert.IsGreaterThanOrEqualTo(13, forecast.Periods.Count); + var last = forecast.Periods[^1]; + Assert.AreEqual(forecast.Opening + forecast.Periods.Sum(p => p.In - p.Out), last.Balance); + await app.StopAsync(); + } + } + + private static DateOnly Year => new(DateTime.Now.Year - 1, 1, 1); + + private static DateOnly Next => DateOnly.FromDateTime(DateTime.Now).AddYears(1); + + private static async Task BankAsync(IServiceProvider services, string company) + { + await using var uow = await services.GetRequiredService().CreateAsync(DatabaseScope.Company(company)); + return (await uow.Repository().FindAsync(Query.For().Where(b => b.Code == DemoTreasurySeeder.BankCode)))!.Id; + } + + private static async Task SeedAsync(IServiceProvider services, string company) + { + // The treasury is not in the trial: the tests use the code of every module (SPEC §8.3). + 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); + } + + private static async Task AssertBalancedAsync(IServiceProvider services, string company) + { + var today = DateOnly.FromDateTime(DateTime.Now); + var balance = await services.GetRequiredService().TrialBalanceAsync(Root, company, new DateOnly(today.Year, 1, 1), today.AddYears(1)); + Assert.IsTrue(balance.Balanced, $"Debit {balance.TotalDebit} credit {balance.TotalCredit}"); + } +}