Compare commits

...
9 Commits
Author SHA1 Message Date
Alby96 0debd82983 Merge M8 · Scadenzario e tesoreria (v0.8.0) (#127)
Wiki / Publish the wiki (push) Successful in 7s
Release / Image and release (push) Successful in 2m43s
CI / PostgreSQL 16 integration (push) Successful in 1m39s
CI / Build and test (SQLite) (push) Successful in 3m47s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 4s
CI / PostgreSQL 17 integration (push) Successful in 1m29s
Closes #69 #70 #71 #72 #73
2026-11-13 10:09:45 +01:00
Alby96andClaude Opus 5.5 f38b5894ce docs: close M8 with treasury wiki, screenshots and screen fixes (#69 #70 #71 #72 #73)
CI / Build and test (SQLite) (pull_request) Successful in 3m51s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m22s
Rewrite the Scadenzario wiki page from the real screens and services, add
ADR 0038, the 0.8.0 changelog, STATUS, MODULES and the regenerated data
model, and update the pages that still pointed to M8.

The browser check found a few screen defects, fixed here: reminder
channels are flags, so they show as "e-mail + PEC" and are edited with
check boxes; icon buttons in grids stay on one row; the summary strip no
longer collapses on long pages; the customers/suppliers switch uses the
right style; the cash flow bars scale between the lowest and highest
balance. The late payment rate of the second half of 2026 is 2.40 (MEF,
GU 163 of 16 July 2026), now covered by tests, and the mapping test
knows the ten treasury tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:59:57 +01:00
Alby96andClaude Opus 5.5 aef0a0d233 feat: schedule and treasury screens (#69 #70 #71 #72)
The pages of the Scadenzario area follow mockups 053-057: open items with aging,
the collection and payment dialog, collections and payments of a period,
remittances (new, file, presentation, credit, unpaid), SDD mandates, reminders
with levels and history, bank reconciliation with rules, and the cash flow
forecast. The dashboard shows the items due among the deadlines and the overdue
receivables among the things to do. Texts are in Treasury.json; the menu lists
the new pages and no longer marks the area as coming.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:36:33 +01:00
Alby96andClaude Opus 5.5 4014373797 feat: demo treasury and integration tests for the schedule (#69 #70 #71 #72)
The demo company gets a bank account with the capital paid in, collections and
supplier payments (one customer pays only half), a RiBa remittance presented,
credited and with one effect back unpaid, a draft remittance for the next weeks,
a direct debit mandate, a CSV statement to reconcile with a rule for the bank
fees, and a first reminder already sent. The seeder runs only when FIN is
licensed and only once.

The tests run the demo on a real instance: collections registered and cancelled,
the CBI file written, the statement reconciled, reminders and cash flow, with the
trial balance checked after every flow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:17:29 +01:00
Alby96andClaude Opus 5.5 5bbc2120a1 feat: remittances, SDD mandates, bank reconciliation, dunning and cash flow services (#70 #71 #72)
Remittances draft the items due, write the RiBa CBI or SEPA pain.001/pain.008
file, present them (bills account and advance, or supplier payments), credit
them and record unpaid effects with their fees. The reconciliation imports
CSV, CBI and CAMT.053 statements without duplicates and proposes matches with
open items, payments, F24, remittances and saved rules. Reminders follow three
levels with late interest, e-mail/PEC/letter and customer block, also from a
scheduled task; the cash flow forecasts 90 days by week.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:06:04 +01:00
Alby96andClaude Opus 5.5 562bf98092 feat: schedule and payments services; posting keeps settled open items (#69)
The schedule lists the open items with aging, disputes and statement of
account; a collection or payment settles items with allowances, exchange
differences and fees, writes its INC/PAG entry and makes the withholding of a
fully paid invoice due. Reposting a document now updates its items by
installment and refuses to drop what was already collected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:53:21 +01:00
Alby96andClaude Opus 5.5 5fbbe4d3a4 feat: SEPA, RiBa and bank statement file formats for treasury (#70 #71)
Remittances need files the banks accept and statements need readers for
reconciliation, without external libraries:

- SepaXmlWriter writes pain.001.001.09 credit transfers and pain.008.001.08
  direct debits (one PmtInf per sequence and collection date), reducing texts
  to the SEPA Latin set and refusing what a bank would reject.
- Camt053Reader reads any camt.053.001.xx by local names; CsvStatementReader
  reads home banking exports (UTF-8 or Windows-1252, Italian or English
  numbers) and guesses the layout from the header row.
- The Italian pack gains RibaCbiWriter (CBI Ricevute bancarie, 120-character
  records IB/14/20/30/40/50/51/70/EF) and CbiStatementReader (RH/61-64/EF).
- Tests validate the SEPA files against hand-written subsets of the ISO 20022
  schemas, to be replaced by the official XSDs when available.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:51:09 +01:00
Alby96andClaude Opus 5.5 b12dc79317 feat: treasury data model, rules and migration (#69 #70 #71 #72)
Open items gain their schedule state; payments, remittances, mandates, bank
statements, match rules and dunning get their tables. Pure rules for aging,
allocation, payment posting, late interest, bank matching, dunning levels and
cash flow periods. The Italian pack adds the treasury accounts, templates and
the late payment rates of D.Lgs. 231/2002.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:42:48 +01:00
Alby96andClaude Opus 5.5 88a0c8ce9c feat: bank file contracts for remittances and statements (#70 #71)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:32:59 +01:00
101 changed files with 14609 additions and 248 deletions

No files matched your search

+51
View File
@@ -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,
+276
View File
@@ -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 |
+6 -6
View File
@@ -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
+14 -6
View File
@@ -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,
+70
View File
@@ -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).
+1 -1
View File
@@ -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
+2 -1
View File
@@ -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
+1
View File
@@ -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,
+6 -5
View File
@@ -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
+4 -1
View File
@@ -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
+17 -1
View File
@@ -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.
+3 -3
View File
@@ -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
+34 -8
View File
@@ -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)
+1 -1
View File
@@ -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)
+5 -4
View File
@@ -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
+1 -1
View File
@@ -30,7 +30,7 @@ volume `/data/files/<azienda>`; 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) |
+1 -1
View File
@@ -13,7 +13,7 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo
quando verrà deciso esplicitamente.
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0), 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 |
|---|---|---|---|
+252 -105
View File
@@ -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)
+1 -1
View File
@@ -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… |
+2 -2
View File
@@ -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'è.
Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

@@ -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;
@@ -502,7 +502,10 @@ public sealed class JournalEntryService
cancellationToken).ConfigureAwait(false);
entry.ReversedById = reversal.Id;
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0"), cancellationToken).ConfigureAwait(false);
// 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;
}
+62 -17
View File
@@ -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<OpenItem, long>();
foreach (var (number, due, amount, method) in rows)
var current = (await repository.ListAsync(
Query.For<OpenItem>().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);
}
}
@@ -115,12 +115,25 @@ internal static class LedgerStore
/// <summary>Removes an entry with its lines, VAT lines and open items.</summary>
public static async Task DeleteAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await 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<GlEntry, long>().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>Refuses when an open item of the entry was collected, paid or put in a remittance (ADR 0038).</summary>
public static async Task EnsureUnpaidAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
var touched = await uow.QuerySingleAsync<long?>(
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]);
}
}
/// <summary>The lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryLine>> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryLine, long>().ListAsync(Query.For<GlEntryLine>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
+86 -70
View File
@@ -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<TaxPayment, long>();
var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture);
var year = paidOn.Year;
var payment = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year
&& t.ReferencePeriod == period && t.PaidOn == null),
cancellationToken).ConfigureAwait(false);
if (payment is null)
{
payment = new TaxPayment
{
DueDate = due,
PaymentCode = code,
ReferenceYear = year,
ReferencePeriod = period,
Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!,
Amount = withholding.Amount,
Source = TaxPaymentSource.Withholding,
IsDemo = withholding.IsDemo,
};
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
payment.Amount += withholding.Amount;
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
withholding.TaxPaymentId = payment.Id;
}
await ApplyInvoicePaidAsync(uow, withholding, paidOn, settlementRules, withholdingRules, cancellationToken).ConfigureAwait(false);
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -491,35 +451,7 @@ public sealed class TaxService
}
var before = Copy(withholding);
if (withholding.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
payment.Amount -= withholding.Amount;
if (payment.Amount == 0m)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
}
if (withholding.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
withholding.InvoicePaidOn = null;
withholding.GlEntryId = null;
withholding.TaxPaymentId = null;
withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered;
await UndoInvoicePaidAsync(uow, withholding, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -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.
/// <summary>Takes back the payment of the invoice of a withholding: its F24 share and its entry. The caller writes the withholding.</summary>
internal static async Task UndoInvoicePaidAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string? userName, CancellationToken cancellationToken)
{
if (withholding.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
payment.Amount -= withholding.Amount;
if (payment.Amount == 0m)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
}
if (withholding.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, 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;
}
/// <summary>
/// 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.
/// </summary>
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<TaxPayment, long>();
var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture);
var year = paidOn.Year;
var payment = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year
&& t.ReferencePeriod == period && t.PaidOn == null),
cancellationToken).ConfigureAwait(false);
if (payment is null)
{
payment = new TaxPayment
{
DueDate = due,
PaymentCode = code,
ReferenceYear = year,
ReferencePeriod = period,
Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!,
Amount = withholding.Amount,
Source = TaxPaymentSource.Withholding,
IsDemo = withholding.IsDemo,
};
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
payment.Amount += withholding.Amount;
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
withholding.TaxPaymentId = payment.Id;
}
}
private static async Task<GlEntry?> PostWithholdingAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string templateCode, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
@@ -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;
/// <summary>
/// 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.
/// </summary>
/// <param name="payments">Collections and payments.</param>
/// <param name="remittances">The remittances.</param>
/// <param name="mandates">The mandates.</param>
/// <param name="reconciliation">The bank statements.</param>
/// <param name="factory">Reads and writes the company.</param>
/// <param name="licenses">Whether the treasury is licensed.</param>
/// <param name="clock">Today.</param>
public sealed class DemoTreasurySeeder(
PaymentService payments, RemittanceService remittances, MandateService mandates, BankReconciliationService reconciliation, IUnitOfWorkFactory factory,
ILicenseGate licenses, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The code of the demo bank account.</summary>
public const string BankCode = "BPD";
/// <summary>The capital paid into the bank on the first day of the year.</summary>
public const decimal OpeningBalance = 25000m;
/// <summary>The account of the capital paid in by the shareholders.</summary>
public const string CapitalAccount = "10.01.004";
/// <summary>The fees of the unpaid effect.</summary>
public const decimal UnpaidFees = 6.50m;
/// <summary>The monthly fee of the bank account, matched by a saved rule.</summary>
public const decimal AccountFee = 12.50m;
private static readonly Actor Seed = Actor.System;
/// <inheritdoc />
public int Order => 50;
/// <summary>An Italian IBAN with its check digits computed from ABI, CAB and account.</summary>
/// <param name="cin">The CIN letter.</param>
/// <param name="abi">The ABI code.</param>
/// <param name="cab">The CAB code.</param>
/// <param name="account">The account number (12 characters).</param>
/// <returns>The IBAN.</returns>
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;
}
/// <inheritdoc />
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<GlAccount, long>().CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0
|| await uow.Repository<Payment, long>().CountAsync(Query.For<Payment>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<Remittance, long>().CountAsync(Query.For<Remittance>(), 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<long> BankAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var banks = uow.Repository<BankAccount, long>();
var bank = await banks.FindAsync(Query.For<BankAccount>().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<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
if (profile is not null && profile.DefaultBankAccountId is null)
{
profile.DefaultBankAccountId = bank.Id;
await uow.Repository<CompanyProfile, long>().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<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), 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<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<PartyBankAccount, long>();
if (await accounts.CountAsync(Query.For<PartyBankAccount>().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<OpenItem> items;
Dictionary<long, PaymentMethod> 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<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), 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<Party, long>().FindAsync(Query.For<Party>().Where(p => p.Name == "Idrotermica Piemonte S.r.l."), cancellationToken).ConfigureAwait(false);
if (party is null)
{
return;
}
var account = await uow.Repository<PartyBankAccount, long>().FindAsync(Query.For<PartyBankAccount>().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<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<Party, long>().GetAsync(open.PartyId, cancellationToken).ConfigureAwait(false))?.Name;
paid = await uow.Repository<Payment, long>().FindAsync(
Query.For<Payment>().Where(p => p.Direction == PaymentDirection.Disbursement).OrderByDescending(p => p.PaymentDate), cancellationToken).ConfigureAwait(false);
feeAccount = (await uow.Repository<GlAccount, long>().FindAsync(Query.For<GlAccount>().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<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<DunningLetter, long>().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<OpenItem, long>().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>The result of an import of a bank statement.</summary>
/// <param name="Statement">The statement.</param>
/// <param name="Added">The new movements.</param>
/// <param name="Duplicates">The movements already imported and skipped.</param>
/// <param name="Suggested">The movements with a proposal.</param>
public sealed record StatementImport(BankStatement Statement, int Added, int Duplicates, int Suggested);
/// <summary>A movement with the name of its party.</summary>
/// <param name="Line">The movement.</param>
/// <param name="PartyName">The customer or supplier of the match.</param>
public sealed record StatementLineRow(BankStatementLine Line, string? PartyName);
/// <summary>The position of a bank account: the ledger against the bank.</summary>
/// <param name="BankAccountId">The bank account.</param>
/// <param name="BookBalance">The balance of its ledger account to the day.</param>
/// <param name="BankBalance">The closing balance of its last statement.</param>
/// <param name="BankBalanceDate">The day of that balance.</param>
/// <param name="ToMatch">Movements still to reconcile.</param>
/// <param name="ToMatchAmount">Their sum.</param>
public sealed record BankPosition(long BankAccountId, decimal BookBalance, decimal? BankBalance, DateOnly? BankBalanceDate, int ToMatch, decimal ToMatchAmount);
/// <summary>A saved rule being written.</summary>
/// <param name="Id">The rule, or <see langword="null"/>.</param>
/// <param name="Name">The name.</param>
/// <param name="Pattern">The text looked for in the description.</param>
/// <param name="Direction">Money in, out or both.</param>
/// <param name="AccountId">The account posted against the bank.</param>
/// <param name="EntryDescription">The description of the entry.</param>
/// <param name="Disabled">Not used.</param>
public sealed record BankRuleInput(long? Id, string Name, string Pattern, BankRuleDirection Direction, long AccountId, string? EntryDescription, bool Disabled);
/// <summary>
/// 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.
/// </summary>
public sealed class BankReconciliationService
{
/// <summary>The confidence from which the proposals are confirmed together.</summary>
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;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public 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;
}
/// <summary>The fingerprint of a movement: the same movement imported twice has the same one.</summary>
/// <param name="bankAccountId">The bank account.</param>
/// <param name="movement">The movement.</param>
/// <param name="occurrence">How many equal movements came before it in the same file.</param>
/// <returns>64 hexadecimal characters.</returns>
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();
}
/// <summary>Reads a bank file of any supported format.</summary>
/// <param name="content">The file.</param>
/// <param name="pack">The fiscal pack (its readers, such as CBI).</param>
/// <returns>The statement.</returns>
/// <exception cref="ValidationFailedException">The format is not recognized or the file cannot be read.</exception>
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<IBankStatementReader>() 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]);
}
/// <summary>The statements imported for a bank account.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="bankAccountId">The bank account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The statements, latest first.</returns>
public async Task<IReadOnlyList<BankStatement>> 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<BankStatement, long>().ListAsync(
Query.For<BankStatement>().Where(s => s.BankAccountId == bankAccountId).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Imports a bank file: the movements already imported are skipped, the new ones get their proposals.</summary>
/// <param name="actor">Who imports it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="bankAccountId">The bank account.</param>
/// <param name="fileName">The name of the file.</param>
/// <param name="content">The file.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was imported.</returns>
public async Task<StatementImport> 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<BankAccount, long>().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<BankStatement, long>().InsertAsync(statement, cancellationToken).ConfigureAwait(false);
var lines = uow.Repository<BankStatementLine, long>();
var seen = new Dictionary<string, int>(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<BankStatementLine>().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<BankStatement, long>().UpdateAsync(statement, cancellationToken).ConfigureAwait(false);
var suggested = await SuggestAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<BankStatement>(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);
}
/// <summary>The movements of a bank account.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="bankAccountId">The bank account.</param>
/// <param name="onlyOpen">Only those to reconcile (to match or suggested).</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movements, by date.</returns>
public async Task<IReadOnlyList<StatementLineRow>> 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<BankStatementLine>().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<BankStatementLine, long>().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))];
}
/// <summary>The position of a bank account.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="bankAccountId">The bank account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The position.</returns>
public async Task<BankPosition> 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<BankAccount, long>().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<decimal?>(
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<BankStatement, long>().FindAsync(
Query.For<BankStatement>().Where(s => s.BankAccountId == bankAccountId && s.ClosingBalance != null).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false);
var open = (await uow.Repository<BankStatementLine, long>().ListAsync(
Query.For<BankStatementLine>().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));
}
/// <summary>Computes the proposals again for the movements to reconcile.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="bankAccountId">The bank account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movements with a proposal.</returns>
public async Task<int> 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;
}
/// <summary>Confirms the proposal of a movement.</summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The movement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movement.</returns>
public async Task<BankStatementLine> 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;
}
/// <summary>Confirms every proposal at or above the threshold.</summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="bankAccountId">The bank account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many movements were reconciled.</returns>
public async Task<int> 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<BankStatementLine, long>().ListAsync(
Query.For<BankStatementLine>().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<string>(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;
}
/// <summary>Reconciles a movement with open items chosen by hand: a collection or payment is recorded.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The movement.</param>
/// <param name="openItemIds">The items, oldest first.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movement.</returns>
public async Task<BankStatementLine> MatchItemsAsync(Actor actor, string companyCode, long lineId, IReadOnlyList<long> 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;
}
/// <summary>Reconciles a movement with a collection or payment already recorded.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The movement.</param>
/// <param name="paymentId">The payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movement.</returns>
public async Task<BankStatementLine> 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;
}
/// <summary>Posts a movement on an account against the bank, and may save a rule for the next ones.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The movement.</param>
/// <param name="accountId">The account.</param>
/// <param name="description">The description of the entry.</param>
/// <param name="rulePattern">The text of a rule to save, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The movement.</returns>
public async Task<BankStatementLine> 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<GlAccount, long>().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<BankMatchRule, long>().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<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return line;
}
/// <summary>Leaves a movement out of the reconciliation (a transfer between own accounts already posted).</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The movement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The movement.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<BankStatementLine, long>().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<Payment, long>().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<BankStatementLine, long>().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<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The saved rules.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rules, by name.</returns>
public async Task<IReadOnlyList<BankMatchRule>> 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<BankMatchRule, long>().ListAsync(Query.For<BankMatchRule>().OrderBy(r => r.Name), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Writes a rule.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The rule.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rule.</returns>
public async Task<BankMatchRule> 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<BankMatchRule, long>();
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;
}
/// <summary>Deletes a rule.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The rule.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<BankMatchRule, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Gives the movements to reconcile of a bank account their best proposal.</summary>
internal static async Task<int> SuggestAsync(IUnitOfWork uow, long bankAccountId, CancellationToken cancellationToken)
{
var lines = (await uow.Repository<BankStatementLine, long>().ListAsync(
Query.For<BankStatementLine>().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<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id);
var rules = (await uow.Repository<BankMatchRule, long>().ListAsync(Query.For<BankMatchRule>().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<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
return count;
}
private static async Task<List<MatchCandidate>> CandidatesAsync(IUnitOfWork uow, long bankAccountId, DateOnly since, CancellationToken cancellationToken)
{
var result = new List<MatchCandidate>();
var items = (await uow.Repository<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<Payment, long>().ListAsync(
Query.For<Payment>().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<long, List<string>>();
foreach (var chunk in partyIds.Chunk(500))
{
var list = chunk.ToList();
foreach (var account in (await uow.Repository<PartyBankAccount, long>().ListAsync(Query.For<PartyBankAccount>().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<string> Names(long partyId) => parties.GetValueOrDefault(partyId) is { } p ? [p.Name, .. p.FiscalName is { } f ? new[] { f } : []] : [];
IReadOnlyList<string> 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<long>(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<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().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<Remittance, long>().ListAsync(
Query.For<Remittance>().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<OpenItem, long>();
var items = new List<OpenItem>();
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<Payment, long>().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<Payment, long>().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<Remittance, long>().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<RemittanceLine, long>().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<BankMatchRule, long>().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<BankMatchRule, long>().UpdateAsync(rule, cancellationToken).ConfigureAwait(false);
break;
}
default:
throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]);
}
Matched(line, line.MatchKind, userName);
await uow.Repository<BankStatementLine, long>().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<ILedgerTemplate>(), cancellationToken).ConfigureAwait(false);
var amount = Math.Abs(line.Amount);
var text = LedgerStore.Trim(description, 200)!;
IReadOnlyList<PaymentPostedLine> 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<BankStatementLine> OpenLineAsync(IUnitOfWork uow, long lineId, CancellationToken cancellationToken)
{
var line = await uow.Repository<BankStatementLine, long>().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;
}
}
@@ -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;
/// <summary>The balance of a bank or cash account in the ledger.</summary>
/// <param name="BankAccountId">The bank account, or <see langword="null"/> for the cash.</param>
/// <param name="Name">Its name.</param>
/// <param name="Balance">Its ledger balance today.</param>
public sealed record CashAccountBalance(long? BankAccountId, string Name, decimal Balance);
/// <summary>The cash flow forecast.</summary>
/// <param name="From">The first day.</param>
/// <param name="Days">How many days.</param>
/// <param name="Accounts">The banks and the cash with their balance.</param>
/// <param name="Opening">The money today.</param>
/// <param name="Periods">The periods with what comes in, goes out and the balance after.</param>
/// <param name="Movements">The movements forecast, by date.</param>
/// <param name="Sources">The sources included.</param>
public sealed record CashFlowForecast(
DateOnly From, int Days, IReadOnlyList<CashAccountBalance> Accounts, decimal Opening, IReadOnlyList<CashFlowPeriod> Periods, IReadOnlyList<CashFlowMovement> Movements,
IReadOnlySet<CashFlowSource> Sources);
/// <summary>
/// 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.
/// </summary>
public sealed class CashFlowService
{
/// <summary>The days after the delivery when an order is expected to be paid.</summary>
public const int OrderPaymentDays = 30;
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="clock">The clock.</param>
public CashFlowService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_clock = clock;
}
/// <summary>The forecast.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="days">How many days ahead (30 to 365).</param>
/// <param name="sources">The sources to include, or <see langword="null"/> for all.</param>
/// <param name="periodDays">The length of a period (7 for weeks, 30 for months).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The forecast.</returns>
public async Task<CashFlowForecast> ForecastAsync(
Actor actor, string companyCode, int days = 90, IReadOnlySet<CashFlowSource>? 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<CashFlowSource>().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<CashFlowMovement>();
var parties = new Dictionary<long, string>();
if (include.Contains(CashFlowSource.Receivables) || include.Contains(CashFlowSource.Payables))
{
var items = (await uow.Repository<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<Remittance, long>().ListAsync(
Query.For<Remittance>().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<SaleOrder, SaleOrderLine>(uow, 1m, CashFlowSource.SaleOrders, until, cancellationToken).ConfigureAwait(false));
}
if (include.Contains(CashFlowSource.PurchaseOrders))
{
movements.AddRange(await OrdersAsync<PurchaseOrder, PurchaseOrderLine>(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<TaxPayment, long>().ListAsync(
Query.For<TaxPayment>().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<IReadOnlyList<CashAccountBalance>> BalancesAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken)
{
var result = new List<CashAccountBalance>();
var draft = nameof(GlEntryStatus.Draft);
var banks = (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>().OrderBy(b => b.Code), cancellationToken).ConfigureAwait(false)).Items;
var seen = new HashSet<long>();
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<decimal?>(
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<decimal?>(
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<IReadOnlyList<CashFlowMovement>> OrdersAsync<THeader, TLine>(
IUnitOfWork uow, decimal sign, CashFlowSource source, DateOnly until, CancellationToken cancellationToken)
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
var orders = (await uow.Repository<THeader, long>().ListAsync(
Query.For<THeader>().Where(o => o.Status == DocumentStatus.Confirmed || o.Status == DocumentStatus.PartiallyFulfilled), cancellationToken).ConfigureAwait(false)).Items;
var result = new List<CashFlowMovement>();
foreach (var chunk in orders.Chunk(200))
{
var ids = chunk.Select(o => o.Id).ToList();
var lines = (await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().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<IReadOnlyList<CashFlowMovement>> RecurringAsync(IUnitOfWork uow, DateOnly today, DateOnly until, CancellationToken cancellationToken)
{
var recurring = (await uow.Repository<RecurringEntry, long>().ListAsync(Query.For<RecurringEntry>().Where(r => !r.Disabled), cancellationToken).ConfigureAwait(false)).Items;
if (recurring.Count == 0)
{
return [];
}
var moneyAccounts = new HashSet<long>();
foreach (var bank in (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>(), 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<GlAccount, long>().ListAsync(Query.For<GlAccount>().Where(a => a.Type == AccountType.Cash || a.Type == AccountType.Bank), cancellationToken).ConfigureAwait(false)).Items)
{
moneyAccounts.Add(account.Id);
}
var result = new List<CashFlowMovement>();
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;
}
}
@@ -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;
/// <summary>A customer to remind, with the level due and its overdue items.</summary>
/// <param name="PartyId">The customer.</param>
/// <param name="PartyCode">Its code.</param>
/// <param name="PartyName">Its name.</param>
/// <param name="Email">Its e-mail.</param>
/// <param name="Pec">Its PEC.</param>
/// <param name="Level">The level due, or <see langword="null"/> when none is due yet.</param>
/// <param name="CurrentLevel">The highest level already sent for its items.</param>
/// <param name="Items">The overdue items.</param>
/// <param name="Overdue">Their residual.</param>
/// <param name="Interest">The late payment interest to the day.</param>
/// <param name="MaxDays">The days past due of the oldest item.</param>
/// <param name="LastSent">The last reminder.</param>
/// <param name="Blocked">The customer is blocked.</param>
public sealed record DunningProposal(
long PartyId, string? PartyCode, string PartyName, string? Email, string? Pec, DunningLevel? Level, int CurrentLevel, IReadOnlyList<ScheduleRow> Items,
decimal Overdue, decimal Interest, int MaxDays, DateOnly? LastSent, bool Blocked);
/// <summary>A reminder sent, with the name of its customer.</summary>
/// <param name="Letter">The reminder.</param>
/// <param name="PartyName">The customer.</param>
public sealed record DunningLetterRow(DunningLetter Letter, string PartyName);
/// <summary>What a run of reminders did.</summary>
/// <param name="Sent">Reminders queued by e-mail or PEC.</param>
/// <param name="Letters">Reminders to print (letter channel).</param>
/// <param name="Skipped">Customers left out, with the reason code.</param>
/// <param name="Pdf">The letters to print, one file, when any.</param>
public sealed record DunningRun(int Sent, int Letters, IReadOnlyList<(string Party, string Reason)> Skipped, LedgerFile? Pdf);
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="mail">The outgoing mail.</param>
/// <param name="clock">The clock.</param>
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;
}
/// <summary>The levels given to a company that has none (mockup 056).</summary>
/// <returns>Three levels: 7, 20 and 45 days after the due date.</returns>
public static IReadOnlyList<DunningLevel> 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}",
},
];
/// <summary>The levels, created with the defaults when the company has none.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The levels in order.</returns>
public async Task<IReadOnlyList<DunningLevel>> 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);
}
/// <summary>Writes a level.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="level">The level (its <c>Level</c> number identifies it).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The level.</returns>
public async Task<DunningLevel> 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<DunningLevel, long>();
var number = level.Level;
var existing = await repository.FindAsync(Query.For<DunningLevel>().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;
}
/// <summary>The customers with overdue items and the level due for each.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The proposals, the most overdue first.</returns>
public async Task<IReadOnlyList<DunningProposal>> 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<ILatePaymentRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ProposalsAsync(uow, rules, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false);
}
/// <summary>The reminders sent.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">One customer.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reminders, latest first (at most 500).</returns>
public async Task<IReadOnlyList<DunningLetterRow>> 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<DunningLetter>();
if (partyId is { } party)
{
query = query.Where(l => l.PartyId == party);
}
var letters = (await uow.Repository<DunningLetter, long>().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))];
}
/// <summary>The letter of the level due for a customer, as a PDF, without sending it.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">The customer.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> 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<ILatePaymentRules>();
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<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var party = await uow.Repository<Party, long>().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);
}
/// <summary>Sends the reminders of the level due to customers.</summary>
/// <param name="actor">Who sends them.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyIds">The customers.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was done.</returns>
public async Task<DunningRun> SendAsync(Actor actor, string companyCode, IReadOnlyList<long> 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);
}
/// <summary>Sends the automatic levels of a company (the scheduled task).</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was done.</returns>
public Task<DunningRun> 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<IReadOnlyList<DunningLevel>> EnsureLevelsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var repository = uow.Repository<DunningLevel, long>();
var levels = (await repository.ListAsync(Query.For<DunningLevel>().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<IReadOnlyList<DunningProposal>> 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<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<PartySalesTerms, long>().ListAsync(Query.For<PartySalesTerms>().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<DunningProposal>();
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<DunningRun> RunAsync(string company, HashSet<long>? partyIds, bool automaticOnly, string? userName, CancellationToken cancellationToken)
{
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<ILatePaymentRules>();
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<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var skipped = new List<(string, string)>();
var printed = new List<byte[]>();
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<Party, long>().GetAsync(proposal.PartyId, cancellationToken).ConfigureAwait(false);
var recipients = new List<string>();
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<string>();
if (level.Action == DunningAction.NotifyAgent && party?.SalespersonId is { } agentId
&& await uow.Repository<Salesperson, long>().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<DunningLetter, long>().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<OpenItem, long>().UpdateAsync(row.Item, cancellationToken).ConfigureAwait(false);
}
if (level.Action == DunningAction.BlockCustomer)
{
var terms = uow.Repository<PartySalesTerms, long>();
var partyId = proposal.PartyId;
var current = await terms.FindAsync(Query.For<PartySalesTerms>().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<byte[]> 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<byte[]> LettersAsync(
IUnitOfWork uow, CompanyProfile? profile, IReadOnlyList<DunningProposal> 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<Party, long>().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;
}
}
}
/// <summary>Sends the automatic reminders of every company (job <c>finance.dunning</c>, SPEC §11.8).</summary>
/// <param name="companies">The companies.</param>
/// <param name="service">The reminders.</param>
/// <param name="license">The licence.</param>
public sealed class DunningJob(ICompanyRegistry companies, DunningService service, ILicenseGate license) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "finance.dunning";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> 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.");
}
}
@@ -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;
/// <summary>A mandate being written.</summary>
/// <param name="Id">The mandate, or <see langword="null"/> for a new one.</param>
/// <param name="PartyId">The debtor.</param>
/// <param name="Reference">The unique mandate reference (UMR).</param>
/// <param name="SignatureDate">The day it was signed.</param>
/// <param name="Scheme">Core or B2B.</param>
/// <param name="Iban">The account of the debtor.</param>
/// <param name="Bic">The BIC.</param>
/// <param name="OneOff">For one collection only.</param>
/// <param name="Notes">Notes.</param>
public sealed record MandateInput(long? Id, long PartyId, string Reference, DateOnly SignatureDate, SddScheme Scheme, string Iban, string? Bic, bool OneOff, string? Notes);
/// <summary>A mandate with the name of its debtor.</summary>
/// <param name="Mandate">The mandate.</param>
/// <param name="PartyCode">The code of the debtor.</param>
/// <param name="PartyName">The name of the debtor.</param>
public sealed record MandateRow(SddMandate Mandate, string? PartyCode, string PartyName);
/// <summary>The SEPA direct debit mandates of the customers (SPEC §11.8, mockup 055, ADR 0038).</summary>
public sealed class MandateService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="audit">The history.</param>
public MandateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_permissions = permissions;
_audit = audit;
}
/// <summary>The mandates, of a party or all.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">One party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The mandates, by party and date.</returns>
public async Task<IReadOnlyList<MandateRow>> 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<SddMandate>();
if (partyId is { } party)
{
query = query.Where(m => m.PartyId == party);
}
var mandates = (await uow.Repository<SddMandate, long>().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)];
}
/// <summary>Writes a mandate.</summary>
/// <param name="actor">Who writes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The mandate.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The mandate.</returns>
public async Task<SddMandate> 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<string>();
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<SddMandate, long>();
var same = await repository.FindAsync(Query.For<SddMandate>().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<SddMandate>(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;
}
/// <summary>Revokes a mandate or takes the revocation back.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The mandate.</param>
/// <param name="revoked">Revoked or not.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<SddMandate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
var before = Copy(mandate);
mandate.Revoked = revoked;
await uow.Repository<SddMandate, long>().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);
}
/// <summary>Deletes a mandate never used in a remittance.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The mandate.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, 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<SddMandate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
if (await uow.Repository<RemittanceLine, long>().CountAsync(Query.For<RemittanceLine>().Where(l => l.MandateId == id), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["Id:" + TreasuryErrors.MandateUsed]);
}
await uow.Repository<SddMandate, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<SddMandate>(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,
};
}
@@ -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;
/// <summary>A line of a collection or payment being recorded.</summary>
/// <param name="OpenItemId">The item.</param>
/// <param name="Amount">The money for the item.</param>
/// <param name="Allowance">The allowance (abbuono) that closes it.</param>
/// <param name="ExchangeDifference">The exchange difference.</param>
public sealed record PaymentLineInput(long OpenItemId, decimal Amount, decimal Allowance = 0m, decimal ExchangeDifference = 0m);
/// <summary>A collection or payment being recorded (mockup 054).</summary>
/// <param name="Direction">Collection or payment.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Date">The day of the money.</param>
/// <param name="PaymentMethodId">The method.</param>
/// <param name="BankAccountId">The bank of the company; none with a cash method means the cash.</param>
/// <param name="Fees">The bank fees.</param>
/// <param name="Reference">The reference (CRO, cheque number).</param>
/// <param name="Notes">Notes.</param>
/// <param name="Lines">The items settled.</param>
public sealed record PaymentInput(
PaymentDirection Direction, long PartyId, DateOnly Date, long? PaymentMethodId, long? BankAccountId, decimal Fees, string? Reference, string? Notes,
IReadOnlyList<PaymentLineInput> Lines);
/// <summary>A collection or payment with what the grid shows.</summary>
/// <param name="Payment">The payment.</param>
/// <param name="PartyName">The party.</param>
/// <param name="Bank">The bank (code).</param>
/// <param name="EntryNumber">The number of its entry.</param>
/// <param name="Documents">The documents it settled.</param>
public sealed record PaymentRow(Payment Payment, string PartyName, string? Bank, string? EntryNumber, string Documents);
/// <summary>
/// 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.
/// </summary>
public sealed class PaymentService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public 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;
}
/// <summary>The collections or payments of a period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="direction">Collections or payments.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="partyId">One party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, latest first.</returns>
public async Task<IReadOnlyList<PaymentRow>> 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<Payment>().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<Payment, long>().ListAsync(query.OrderByDescending(p => p.PaymentDate).OrderByDescending(p => p.Id), cancellationToken).ConfigureAwait(false)).Items;
return await RowsAsync(uow, payments, cancellationToken).ConfigureAwait(false);
}
/// <summary>A payment with its lines and their items.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The payment, its lines and the items, or <see langword="null"/>.</returns>
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<Payment, long>().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<OpenItem, long>().ListAsync(Query.For<OpenItem>().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)))]);
}
/// <summary>Records a collection or payment and its entry.</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The payment.</returns>
public async Task<Payment> 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<Payment>(uow, AuditAction.Insert, payment.Id, null, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>Cancels a collection or payment: its entry is deleted (or reversed when final) and its items reopen.</summary>
/// <param name="actor">Who cancels it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<Payment, long>().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<Payment>(uow, AuditAction.Delete, payment.Id, payment, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Records a payment inside a transaction (manual, remittances, bank statements).</summary>
internal static async Task<Payment> RegisterAsync(
IUnitOfWork uow, IFiscalPack pack, PaymentInput input, PaymentOrigin origin, long? remittanceId, long? statementLineId, CancellationToken cancellationToken)
{
var errors = new List<string>();
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<OpenItem, long>();
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<PaymentMethod, long>().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<ILedgerTemplate>();
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<PaymentPostedLine> 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<Payment, long>().InsertAsync(payment, cancellationToken).ConfigureAwait(false);
var lineRepository = uow.Repository<PaymentLine, long>();
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;
}
/// <summary>Cancels a payment inside a transaction.</summary>
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<OpenItem, long>();
var reopened = new List<OpenItem>();
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<Withholding, long>().ListAsync(
Query.For<Withholding>().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<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
}
}
await uow.Repository<Payment, long>().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<BankStatementLine, long>().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<BankStatementLine, long>().UpdateAsync(statementLine, cancellationToken).ConfigureAwait(false);
}
}
internal static async Task<IReadOnlyList<PaymentLine>> LinesAsync(IUnitOfWork uow, long paymentId, CancellationToken cancellationToken) =>
(await uow.Repository<PaymentLine, long>().ListAsync(Query.For<PaymentLine>().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<OpenItem> items, DateOnly date, CancellationToken cancellationToken)
{
var settlementRules = pack.GetFeature<IVatSettlementRules>();
if (settlementRules is null)
{
return;
}
var withholdingRules = pack.GetFeature<IWithholdingRules>();
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<OpenItem, long>().CountAsync(
Query.For<OpenItem>().Where(o => o.SourceFamily == family && o.SourceDocumentId == documentId && !o.Closed), cancellationToken).ConfigureAwait(false);
if (open > 0)
{
continue;
}
var withholdings = (await uow.Repository<Withholding, long>().ListAsync(
Query.For<Withholding>().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<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
}
}
}
private static async Task<IReadOnlyList<PaymentRow>> RowsAsync(IUnitOfWork uow, IReadOnlyList<Payment> 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<BankAccount, long>().ListAsync(Query.For<BankAccount>(), 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<long, string?>();
foreach (var chunk in entryIds.Chunk(500))
{
var list = chunk.ToList();
foreach (var entry in (await uow.Repository<GlEntry, long>().ListAsync(Query.For<GlEntry>().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<long, List<string>>();
foreach (var chunk in ids.Chunk(500))
{
var list = chunk.ToList();
var lines = (await uow.Repository<PaymentLine, long>().ListAsync(Query.For<PaymentLine>().Where(l => list.Contains(l.PaymentId)), cancellationToken).ConfigureAwait(false)).Items;
var itemIds = lines.Select(l => l.OpenItemId).Distinct().ToList();
var items = (await uow.Repository<OpenItem, long>().ListAsync(Query.For<OpenItem>().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) ?? [])))];
}
}
@@ -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;
/// <summary>An item that can go in a remittance, with what is missing for the file.</summary>
/// <param name="Row">The item.</param>
/// <param name="Iban">The IBAN of the customer or supplier (of the mandate for direct debits).</param>
/// <param name="Mandate">The mandate of a direct debit.</param>
/// <param name="Problems">The error codes that keep it out of the file.</param>
public sealed record RemittanceCandidate(ScheduleRow Row, string? Iban, SddMandate? Mandate, IReadOnlyList<string> Problems)
{
/// <summary>Ready for the file.</summary>
public bool Ready => Problems.Count == 0;
}
/// <summary>A new remittance.</summary>
/// <param name="Kind">RiBa, direct debits or credit transfers.</param>
/// <param name="BankAccountId">The bank of the company.</param>
/// <param name="PresentationDate">The day it goes to the bank.</param>
/// <param name="DueUntil">The last due date of its items.</param>
/// <param name="Advance">Advanced subject to collection (salvo buon fine).</param>
/// <param name="Notes">Notes.</param>
/// <param name="OpenItemIds">The items.</param>
public sealed record RemittanceInput(RemittanceKind Kind, long BankAccountId, DateOnly PresentationDate, DateOnly DueUntil, bool Advance, string? Notes, IReadOnlyList<long> OpenItemIds);
/// <summary>A remittance with its bank.</summary>
/// <param name="Remittance">The remittance.</param>
/// <param name="Bank">The bank (code and name).</param>
public sealed record RemittanceRow(Remittance Remittance, string Bank);
/// <summary>A line of a remittance with its item and party.</summary>
/// <param name="Line">The line.</param>
/// <param name="Item">The item.</param>
/// <param name="PartyName">The party.</param>
/// <param name="Mandate">The reference of the mandate.</param>
public sealed record RemittanceLineRow(RemittanceLine Line, OpenItem? Item, string PartyName, string? Mandate);
/// <summary>
/// The remittances (distinte, SPEC §11.8, mockup 055, ADR 0038): RiBa in the CBI file of the pack, SEPA direct
/// debits (<c>pain.008</c>) with their mandates, SEPA credit transfers to suppliers (<c>pain.001</c>). 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.
/// </summary>
public sealed class RemittanceService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public 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;
}
/// <summary>The direction of the items of a kind of remittance.</summary>
/// <param name="kind">The kind.</param>
/// <returns>Payables for credit transfers, receivables otherwise.</returns>
public static OpenItemDirection DirectionOf(RemittanceKind kind) =>
kind == RemittanceKind.SepaCreditTransfer ? OpenItemDirection.Payable : OpenItemDirection.Receivable;
/// <summary>The remittances of a year.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="year">The year.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The remittances, latest first.</returns>
public async Task<IReadOnlyList<RemittanceRow>> 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<Remittance, long>().ListAsync(
Query.For<Remittance>().Where(r => r.Year == year).OrderByDescending(r => r.Number), cancellationToken).ConfigureAwait(false)).Items;
var banks = (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>(), 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))];
}
/// <summary>A remittance with its lines.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The remittance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The remittance and its lines, or <see langword="null"/>.</returns>
public async Task<(RemittanceRow Row, IReadOnlyList<RemittanceLineRow> 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<Remittance, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } remittance)
{
return null;
}
var bank = await uow.Repository<BankAccount, long>().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<OpenItem, long>().ListAsync(Query.For<OpenItem>().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<SddMandate, long>().ListAsync(Query.For<SddMandate>(), 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))]);
}
/// <summary>The items that can go in a remittance of a kind, due up to a day.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="kind">The kind.</param>
/// <param name="dueUntil">The last due date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The candidates, by due date.</returns>
public async Task<IReadOnlyList<RemittanceCandidate>> 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<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id);
var kinds = pack.GetFeature<IRemittanceMethods>();
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))];
}
/// <summary>Drafts a remittance with items; they are reserved for it.</summary>
/// <param name="actor">Who drafts it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The remittance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The remittance.</returns>
public async Task<Remittance> 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<BankAccount, long>().GetAsync(input.BankAccountId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
var year = input.PresentationDate.Year;
var number = (int)((await uow.QuerySingleAsync<long?>(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<Remittance, long>().InsertAsync(remittance, cancellationToken).ConfigureAwait(false);
var itemRepository = uow.Repository<OpenItem, long>();
var direction = DirectionOf(input.Kind);
var items = new List<OpenItem>();
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<RemittanceLine, long>();
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<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<Remittance>(uow, AuditAction.Insert, remittance.Id, null, remittance, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return remittance;
}
/// <summary>Takes a line out of a remittance not presented.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<RemittanceLine, long>().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<RemittanceLine, long>().DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false);
remittance.ItemCount--;
remittance.TotalAmount -= line.Amount;
remittance.Status = RemittanceStatus.Draft;
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Deletes a remittance not presented; its items are free again.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The remittance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, 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<Remittance, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<Remittance>(uow, AuditAction.Delete, id, remittance, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Writes the file of a remittance for the bank (CBI for RiBa, XML for SEPA).</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The remittance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> 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<Remittance, long>().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<BankAccount, long>().GetAsync(remittance.BankAccountId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
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<OpenItem, long>().ListAsync(Query.For<OpenItem>().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id);
var fileItems = new List<BankFileItem>();
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<IRemittanceFileWriter>() 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<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new LedgerFile(file.FileName, file.ContentType, file.Content);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The remittance.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The remittance.</returns>
public async Task<Remittance> 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<OpenItem, long>();
var lineRepository = uow.Repository<RemittanceLine, long>();
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<ILedgerTemplate>();
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<PaymentPostedLine>();
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<Remittance, long>().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;
}
/// <summary>Records the credit at maturity of a presented remittance: the effects not unpaid are collected.</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The remittance.</param>
/// <param name="creditedOn">The day of the credit.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The remittance.</returns>
public async Task<Remittance> 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<Remittance, long>().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<Remittance, long>().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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="lineId">The line of the remittance.</param>
/// <param name="date">The day the bank returned it.</param>
/// <param name="fees">The fees charged by the bank, debited to the customer.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line.</returns>
public async Task<RemittanceLine> 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<RemittanceLine, long>().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
var remittance = await uow.Repository<Remittance, long>().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;
}
/// <summary>Credits a presented remittance inside a transaction (also from the bank reconciliation).</summary>
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<ILedgerTemplate>();
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<OpenItem, long>();
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<RemittanceLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
remittance.Status = RemittanceStatus.Closed;
remittance.CreditedOn = creditedOn;
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
}
/// <summary>Records an unpaid effect inside a transaction (also from the bank reconciliation).</summary>
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<Remittance, long>().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<OpenItem, long>().GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
var ledger = pack.GetFeature<ILedgerTemplate>();
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<PaymentPostedLine> { 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<OpenItem, long>().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
if (fees > 0m)
{
await uow.Repository<OpenItem, long>().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<RemittanceLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
}
internal static async Task<IReadOnlyList<RemittanceLine>> LinesAsync(IUnitOfWork uow, long remittanceId, CancellationToken cancellationToken) =>
(await uow.Repository<RemittanceLine, long>().ListAsync(Query.For<RemittanceLine>().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<string>();
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<PartyBanks> PartyBanksAsync(IUnitOfWork uow, IEnumerable<long> partyIds, CancellationToken cancellationToken)
{
var ids = partyIds.Distinct().ToList();
var accounts = new Dictionary<long, PartyBankAccount>();
var mandates = new List<SddMandate>();
foreach (var chunk in ids.Chunk(500))
{
var list = chunk.ToList();
foreach (var account in (await uow.Repository<PartyBankAccount, long>().ListAsync(
Query.For<PartyBankAccount>().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<SddMandate, long>().ListAsync(Query.For<SddMandate>().Where(m => list.Contains(m.PartyId)), cancellationToken).ConfigureAwait(false)).Items);
}
return new PartyBanks(accounts, mandates);
}
private static async Task<Remittance> EditableAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
var remittance = await uow.Repository<Remittance, long>().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<OpenItem, long>().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<OpenItem, long>().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
}
private static async Task MarkMandatesAsync(IUnitOfWork uow, IReadOnlyList<RemittanceLine> lines, CancellationToken cancellationToken)
{
foreach (var group in lines.Where(l => l.MandateId is not null).GroupBy(l => l.MandateId!.Value))
{
if (await uow.Repository<SddMandate, long>().GetAsync(group.Key, cancellationToken).ConfigureAwait(false) is { } mandate)
{
mandate.LastCollectionDate = group.Max(l => l.DueDate);
await uow.Repository<SddMandate, long>().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<long, PartyBankAccount> Accounts, List<SddMandate> Mandates);
}
@@ -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;
/// <summary>The payment methods and the bank accounts of the company.</summary>
/// <param name="Methods">The payment methods in use.</param>
/// <param name="Banks">The bank accounts in use.</param>
public sealed record TreasuryChoices(IReadOnlyList<PaymentMethod> Methods, IReadOnlyList<BankAccount> Banks);
/// <summary>Which items the schedule shows.</summary>
public enum ScheduleView
{
/// <summary>Not closed: open, partial, unpaid, in remittance.</summary>
Open = 0,
/// <summary>Not closed and past due.</summary>
Overdue = 1,
/// <summary>Returned effects not collected again.</summary>
Unpaid = 2,
/// <summary>In a remittance not credited yet.</summary>
InRemittance = 3,
/// <summary>Disputed by the customer or the company.</summary>
Disputed = 4,
/// <summary>Closed.</summary>
Closed = 5,
/// <summary>Everything.</summary>
All = 6,
}
/// <summary>The filter of the schedule.</summary>
/// <param name="Direction">Receivables or payables.</param>
/// <param name="View">Which items.</param>
/// <param name="PartyId">One customer or supplier.</param>
/// <param name="From">Due from this day.</param>
/// <param name="To">Due up to this day.</param>
/// <param name="PaymentMethodId">One payment method.</param>
/// <param name="Search">Part of the party name or of the document number.</param>
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);
/// <summary>An item of the schedule with what the grid shows.</summary>
/// <param name="Item">The item.</param>
/// <param name="PartyCode">The code of the party.</param>
/// <param name="PartyName">The name of the party.</param>
/// <param name="Method">The payment method (code).</param>
/// <param name="MethodDescription">The payment method (description).</param>
/// <param name="DaysOverdue">Days past due (negative when not due).</param>
/// <param name="Remittance">The number of the remittance that holds it.</param>
public sealed record ScheduleRow(OpenItem Item, string? PartyCode, string PartyName, string? Method, string? MethodDescription, int DaysOverdue, string? Remittance);
/// <summary>The schedule: the rows of the filter and the aging of what is open.</summary>
/// <param name="Rows">The rows, by due date.</param>
/// <param name="Aging">The residual by age of the open items of the filter.</param>
/// <param name="Residual">The residual of the rows.</param>
/// <param name="Overdue">The overdue residual of the rows.</param>
/// <param name="DueIn30Days">The residual due in the next 30 days.</param>
public sealed record ScheduleResult(IReadOnlyList<ScheduleRow> Rows, AgingBuckets Aging, decimal Residual, decimal Overdue, decimal DueIn30Days);
/// <summary>A change of an item by hand.</summary>
/// <param name="DueDate">The due date.</param>
/// <param name="PaymentMethodId">The payment method.</param>
/// <param name="BankAccountId">The bank of the company it is collected on.</param>
/// <param name="Disputed">Disputed: left out of reminders and remittances.</param>
/// <param name="Notes">Notes.</param>
public sealed record OpenItemChange(DateOnly DueDate, long? PaymentMethodId, long? BankAccountId, bool Disputed, string? Notes);
/// <summary>The statement of account of a party.</summary>
/// <param name="Party">The party.</param>
/// <param name="Direction">Receivables or payables.</param>
/// <param name="Day">The day of the statement.</param>
/// <param name="Items">The items not closed, by due date.</param>
/// <param name="Payments">The collections or payments of the last twelve months.</param>
/// <param name="Residual">What is left.</param>
/// <param name="Overdue">What is past due.</param>
/// <param name="Interest">The late payment interest to the day, when the pack has the rules.</param>
public sealed record PartyStatement(Party Party, OpenItemDirection Direction, DateOnly Day, IReadOnlyList<ScheduleRow> Items, IReadOnlyList<Payment> Payments, decimal Residual, decimal Overdue, decimal Interest);
/// <summary>
/// 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.
/// </summary>
public sealed class ScheduleService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public 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;
}
/// <summary>The items of a filter with the aging.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The schedule.</returns>
public async Task<ScheduleResult> 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);
}
/// <summary>An item with its row.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The row, or <see langword="null"/>.</returns>
public async Task<ScheduleRow?> 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<OpenItem, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item)
{
return null;
}
return (await RowsAsync(uow, [item], TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false))[0];
}
/// <summary>Changes due date, method, bank, dispute and notes of an item.</summary>
/// <param name="actor">Who changes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The item.</param>
/// <param name="change">The change.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The item.</returns>
public async Task<OpenItem> 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<OpenItem, long>();
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;
}
/// <summary>The statement of account of a party (estratto conto).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">The party.</param>
/// <param name="direction">Receivables or payables.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The statement.</returns>
public async Task<PartyStatement> 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<Fiscal.Abstractions.ILatePaymentRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var party = await uow.Repository<Party, long>().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<Payment, long>().ListAsync(
Query.For<Payment>().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);
}
/// <summary>The rows of a filter as a CSV file.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> 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());
}
/// <summary>The items due in the next days, for the dashboard (receivables and payables).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="days">How many days ahead.</param>
/// <param name="take">How many rows at most.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, by due date, overdue first.</returns>
public async Task<IReadOnlyList<ScheduleRow>> 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<OpenItem, long>().ListAsync(
Query.For<OpenItem>().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);
}
/// <summary>The payment methods and the bank accounts in use, for the choices of the treasury screens.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The choices, by code.</returns>
public async Task<TreasuryChoices> 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<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>().Where(m => !m.Disabled).OrderBy(m => m.Code), cancellationToken).ConfigureAwait(false)).Items;
var banks = (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>().Where(b => !b.Disabled).OrderBy(b => b.Code), cancellationToken).ConfigureAwait(false)).Items;
return new TreasuryChoices(methods, banks);
}
internal static async Task<ScheduleResult> LoadAsync(IUnitOfWork uow, ScheduleFilter filter, DateOnly today, CancellationToken cancellationToken)
{
var direction = filter.Direction;
var query = Query.For<OpenItem>().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<OpenItem, long>().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<IReadOnlyList<ScheduleRow>> RowsAsync(IUnitOfWork uow, IReadOnlyList<OpenItem> items, DateOnly today, CancellationToken cancellationToken)
{
var parties = await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false);
var methods = (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), 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<Remittance, long>().ListAsync(Query.For<Remittance>().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,
};
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
/// <param name="schedule">The schedule.</param>
/// <param name="permissions">The permissions, licence included.</param>
/// <param name="texts">The texts.</param>
public sealed class TreasuryFeedSource(ScheduleService schedule, PermissionService permissions, ITexts texts) : IDeadlineSource, ITodoSource
{
/// <summary>The text key of the area.</summary>
public const string Area = "Dashboard.Areas.Treasury";
/// <summary>The most deadlines of the schedule on the dashboard.</summary>
public const int MaxDeadlines = 12;
private const string Href = "/scadenzario/scadenze";
/// <inheritdoc />
public async Task<IReadOnlyList<FeedItem>> 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"),
};
})];
}
/// <inheritdoc />
public async Task<IReadOnlyList<FeedItem>> 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<bool> AllowedAsync(FeedContext context, CancellationToken cancellationToken) =>
context.Actor.CompanyCode is not null && (await permissions.CheckAsync(context.Actor, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false)).Allowed;
}
@@ -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;
/// <summary>The permissions of the schedule and the treasury (module FIN, <see cref="Modules.BuiltInModules"/>).</summary>
public static class TreasuryPermissions
{
/// <summary>See the schedule, the remittances, the reminders and the cash flow.</summary>
public const string ScheduleRead = "finance.schedule.read";
/// <summary>Change due dates, disputes, remittances, mandates and reminders.</summary>
public const string ScheduleWrite = "finance.schedule.write";
/// <summary>See collections and payments.</summary>
public const string PaymentRead = "finance.payment.read";
/// <summary>Record collections and payments.</summary>
public const string PaymentWrite = "finance.payment.write";
/// <summary>Import bank statements and reconcile them.</summary>
public const string BankReconcile = "finance.bank.reconcile";
}
/// <summary>
/// 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.
/// </summary>
internal static class TreasuryStore
{
/// <summary>The day of the company clock.</summary>
public static DateOnly Today(TimeProvider clock) => DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
/// <summary>A bank account of the company, or the preferred one.</summary>
public static async Task<BankAccount?> BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken)
{
var banks = uow.Repository<BankAccount, long>();
if (id is { } bankId)
{
return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
}
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
if (profile?.DefaultBankAccountId is { } defaultId && await banks.GetAsync(defaultId, cancellationToken).ConfigureAwait(false) is { } preferred)
{
return preferred;
}
return await banks.FindAsync(Query.For<BankAccount>().Where(b => b.IsDefault), cancellationToken).ConfigureAwait(false)
?? await banks.FindAsync(Query.For<BankAccount>().OrderBy(b => b.Id), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// 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).
/// </summary>
public static async Task<long?> RoleAccountAsync(
IUnitOfWork uow, IReadOnlyList<JournalTemplateLine>? 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;
}
/// <summary>The account the money moves on: the ledger account of the bank, or cash for a method without bank.</summary>
public static async Task<long> MoneyAccountAsync(
IUnitOfWork uow, BankAccount? bank, bool cash, IReadOnlyList<JournalTemplateLine>? 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]);
}
/// <summary>Writes a posted entry of the treasury from its lines.</summary>
public static async Task<GlEntry> PostAsync(
IUnitOfWork uow, string templateCode, DateOnly date, string description, long? partyId, IReadOnlyList<PaymentPostedLine> 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);
}
/// <summary>Takes back an entry of the treasury: deleted while posted, reversed when final.</summary>
public static async Task UndoEntryAsync(IUnitOfWork uow, long? entryId, DateOnly date, string? userName, CancellationToken cancellationToken)
{
if (entryId is not { } id || await uow.Repository<GlEntry, long>().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);
}
}
/// <summary>Moves what an item has settled and gives it its state.</summary>
public static void Settle(OpenItem item, decimal delta)
{
item.PaidAmount += delta;
item.Status = OpenItemStates.Of(item);
item.Closed = item.Status == OpenItemStatus.Closed;
}
/// <summary>The names and codes of parties.</summary>
public static async Task<Dictionary<long, Party>> PartiesAsync(IUnitOfWork uow, IEnumerable<long> ids, CancellationToken cancellationToken)
{
var set = ids.Distinct().ToList();
if (set.Count == 0)
{
return [];
}
var result = new Dictionary<long, Party>();
foreach (var chunk in set.Chunk(500))
{
var list = chunk.ToList();
foreach (var party in (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items)
{
result[party.Id] = party;
}
}
return result;
}
/// <summary>The description of an item in entries and files.</summary>
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)!;
}
@@ -122,6 +122,9 @@ public static class LedgerErrors
/// <summary>The account of the bank is missing.</summary>
public const string BankAccountMissing = "ledger.bank.account-missing";
/// <summary>An open item already collected, paid or in a remittance cannot go below what was settled or go away.</summary>
public const string OpenItemPaid = "ledger.open-item.paid";
/// <summary>The final print of a VAT register must follow the last one.</summary>
public const string PrintOrder = "vat.register.print-order";
}
+55
View File
@@ -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
/// <summary>VAT of split payment, due by the public customer.</summary>
SplitPaymentVat = 15,
/// <summary>Allowances received and rounding in favour (abbuoni attivi).</summary>
AllowanceIncome = 16,
/// <summary>Bank fees and charges.</summary>
BankCharges = 17,
/// <summary>Effects and direct debits presented for collection (effetti all'incasso).</summary>
BillsForCollection = 18,
/// <summary>Advances of the bank on effects presented subject to collection (banche c/anticipi).</summary>
BankAdvances = 19,
/// <summary>Exchange gains.</summary>
ExchangeGain = 20,
/// <summary>Exchange losses.</summary>
ExchangeLoss = 21,
/// <summary>Late payment interest charged to customers.</summary>
LateInterest = 22,
}
/// <summary>A line of a journal template (<c>gl_journal_template_lines</c>).</summary>
@@ -239,6 +261,9 @@ public enum GlEntrySource
/// <summary>The payment of an invoice with a withholding.</summary>
Withholding = 6,
/// <summary>A collection, a payment or a remittance of the schedule (M8).</summary>
Treasury = 7,
}
/// <summary>
@@ -476,8 +501,38 @@ public sealed class OpenItem : Entity<long>, IDemoMarkable
/// <summary>Fully settled.</summary>
public bool Closed { get; set; }
/// <summary>The state in the schedule (M8).</summary>
public OpenItemStatus Status { get; set; }
/// <summary>Contested by the customer or with the supplier: left out of reminders and remittances.</summary>
public bool Disputed { get; set; }
/// <summary>The bank account of the company that collects or pays it (from the document).</summary>
public long? BankAccountId { get; set; }
/// <summary>The remittance it is in.</summary>
public long? RemittanceId { get; set; }
/// <summary>The times it came back unpaid.</summary>
public int UnpaidCount { get; set; }
/// <summary>The item it was split from: the bank fees of an unpaid effect.</summary>
public long? ParentId { get; set; }
/// <summary>The level of the last reminder.</summary>
public int DunningLevel { get; set; }
/// <summary>The day of the last reminder.</summary>
public DateOnly? LastDunningDate { get; set; }
/// <summary>Notes (the reason of a dispute).</summary>
public string? Notes { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
/// <summary>What is left to collect or pay.</summary>
public decimal Residual => Amount - PaidAmount;
}
/// <summary>How often a recurring entry repeats.</summary>
+3
View File
@@ -207,6 +207,9 @@ public sealed class BankAccount : CodedEntity
/// <summary>The ledger account (M7).</summary>
public string? AccountCode { get; set; }
/// <summary>The SEPA creditor identifier for direct debits (M8).</summary>
public string? CreditorId { get; set; }
/// <summary>The account proposed on documents.</summary>
public bool IsDefault { get; set; }
}
+232
View File
@@ -0,0 +1,232 @@
namespace Khaemhat.Core.Treasury;
/// <summary>What a remittance (distinta) carries to the bank.</summary>
public enum RemittanceKind
{
/// <summary>Italian bank receipts (ricevute bancarie), CBI fixed-width file.</summary>
Riba = 0,
/// <summary>SEPA direct debit, core scheme (consumers and companies), ISO 20022 <c>pain.008</c>.</summary>
SddCore = 1,
/// <summary>SEPA direct debit, business-to-business scheme, ISO 20022 <c>pain.008</c>.</summary>
SddB2b = 2,
/// <summary>SEPA credit transfers to suppliers, ISO 20022 <c>pain.001</c>.</summary>
SepaCreditTransfer = 3,
}
/// <summary>The sequence of a direct debit under its mandate.</summary>
public enum SddSequence
{
/// <summary>The first debit of a recurrent mandate (<c>FRST</c>).</summary>
First = 0,
/// <summary>A following debit (<c>RCUR</c>).</summary>
Recurrent = 1,
/// <summary>The last debit (<c>FNAL</c>).</summary>
Final = 2,
/// <summary>A one-off mandate (<c>OOFF</c>).</summary>
OneOff = 3,
}
/// <summary>
/// The company in a bank file: the creditor of receipts and direct debits, the debtor of credit transfers.
/// </summary>
/// <param name="Name">The company name.</param>
/// <param name="TaxCode">The VAT number or tax code.</param>
/// <param name="Address">The street and number.</param>
/// <param name="PostalCode">The postal code.</param>
/// <param name="City">The town.</param>
/// <param name="Province">The province, two letters.</param>
/// <param name="CountryCode">The country, ISO 3166 alpha-2.</param>
/// <param name="Iban">The IBAN of the company account, compact.</param>
/// <param name="Bic">The BIC of the company bank, if known.</param>
/// <param name="SiaCode">The SIA code of the company (RiBa sender), five characters.</param>
/// <param name="CucCode">The CBI CUC code (initiating party of SEPA files in Italy).</param>
/// <param name="CreditorId">The SEPA creditor identifier of direct debits, such as <c>IT66ZZZA1B2C3D4E5F6G7H8</c>.</param>
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);
/// <summary>One effect, debit or transfer of a remittance.</summary>
/// <param name="Number">The progressive number in the file, from 1.</param>
/// <param name="CounterpartyCode">The code of the customer or supplier in the company (RiBa debtor code).</param>
/// <param name="CounterpartyName">The customer (debtor) or supplier (creditor).</param>
/// <param name="CounterpartyTaxCode">Its VAT number or tax code.</param>
/// <param name="Address">Its street and number.</param>
/// <param name="PostalCode">Its postal code.</param>
/// <param name="City">Its town.</param>
/// <param name="Province">Its province.</param>
/// <param name="CountryCode">Its country.</param>
/// <param name="Iban">Its IBAN, compact (for RiBa only ABI and CAB are used).</param>
/// <param name="Bic">Its BIC, if known.</param>
/// <param name="BankName">Its bank, for the RiBa description.</param>
/// <param name="Amount">The amount, positive, in euro.</param>
/// <param name="DueDate">The due date (RiBa), the collection date (SDD) or the execution date (transfers).</param>
/// <param name="Reference">The remittance information: the invoices paid, such as <c>FT 2026/000388 del 31/08/2026</c>.</param>
/// <param name="EndToEndId">The end-to-end identifier, unique in the company, at most 35 characters.</param>
/// <param name="MandateId">The direct debit mandate reference (UMR).</param>
/// <param name="MandateDate">The date the mandate was signed.</param>
/// <param name="Sequence">The sequence of the direct debit.</param>
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);
/// <summary>A remittance as the bank file writers read it.</summary>
/// <param name="Kind">What it carries.</param>
/// <param name="MessageId">The unique identifier of the file (also the RiBa support name), at most 35 characters.</param>
/// <param name="CreatedAt">When the file is created, local time.</param>
/// <param name="ExecutionDate">The presentation date (RiBa), or the requested execution date of transfers.</param>
/// <param name="Company">The company and its account.</param>
/// <param name="Items">The effects, debits or transfers.</param>
public sealed record BankFileRemittance(
RemittanceKind Kind,
string MessageId,
DateTime CreatedAt,
DateOnly ExecutionDate,
BankFileCompany Company,
IReadOnlyList<BankFileItem> Items)
{
/// <summary>The total of the items.</summary>
public decimal Total => Items.Sum(i => i.Amount);
}
/// <summary>A file written for the bank.</summary>
/// <param name="FileName">The proposed name.</param>
/// <param name="ContentType">The media type.</param>
/// <param name="Content">The bytes.</param>
public sealed record BankFile(string FileName, string ContentType, byte[] Content);
/// <summary>The formats of a bank statement.</summary>
public enum StatementFormat
{
/// <summary>A CSV export of the home banking, with a layout.</summary>
Csv = 0,
/// <summary>ISO 20022 <c>camt.053</c> (bank to customer statement).</summary>
Camt053 = 1,
/// <summary>The Italian CBI statement (rendicontazione movimenti, records RH, 61-64, EF).</summary>
Cbi = 2,
}
/// <summary>A movement of a bank statement.</summary>
/// <param name="BookingDate">The booking date.</param>
/// <param name="ValueDate">The value date.</param>
/// <param name="Amount">The amount: positive for money in, negative for money out.</param>
/// <param name="Description">The description of the movement, on one line.</param>
/// <param name="Reference">The bank reference (CRO, TRN, end-to-end id), if any.</param>
/// <param name="CounterpartyName">The other party, if the file says it.</param>
/// <param name="CounterpartyIban">Its IBAN, if the file says it.</param>
/// <param name="BankCode">The bank transaction code (CBI causale, ISO domain/family), if any.</param>
public sealed record StatementMovement(
DateOnly BookingDate,
DateOnly? ValueDate,
decimal Amount,
string Description,
string? Reference = null,
string? CounterpartyName = null,
string? CounterpartyIban = null,
string? BankCode = null);
/// <summary>A bank statement read from a file.</summary>
/// <param name="Format">The format.</param>
/// <param name="AccountIban">The IBAN of the account, if the file says it.</param>
/// <param name="Currency">The currency, if the file says it.</param>
/// <param name="FromDate">The first day.</param>
/// <param name="ToDate">The last day.</param>
/// <param name="OpeningBalance">The opening balance, if the file says it.</param>
/// <param name="ClosingBalance">The closing balance, if the file says it.</param>
/// <param name="Movements">The movements, in the order of the file.</param>
public sealed record StatementFile(
StatementFormat Format,
string? AccountIban,
string? Currency,
DateOnly? FromDate,
DateOnly? ToDate,
decimal? OpeningBalance,
decimal? ClosingBalance,
IReadOnlyList<StatementMovement> Movements);
/// <summary>
/// The columns of a CSV statement. Column indexes are zero-based. The amount is either one signed column
/// (<see cref="AmountColumn"/>) or two columns of money in and money out (<see cref="CreditColumn"/>,
/// <see cref="DebitColumn"/>, both read as positive numbers).
/// </summary>
/// <param name="Separator">The field separator.</param>
/// <param name="HeaderRows">The rows to skip before the movements.</param>
/// <param name="DateColumn">The booking date.</param>
/// <param name="ValueDateColumn">The value date.</param>
/// <param name="DescriptionColumn">The description.</param>
/// <param name="AmountColumn">A signed amount.</param>
/// <param name="CreditColumn">Money in.</param>
/// <param name="DebitColumn">Money out.</param>
/// <param name="ReferenceColumn">The bank reference.</param>
/// <param name="DateFormat">The date format, such as <c>dd/MM/yyyy</c>.</param>
/// <param name="DecimalComma">Numbers are written <c>1.234,56</c> (otherwise <c>1,234.56</c>).</param>
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);
/// <summary>A bank file that cannot be read or written.</summary>
public sealed class BankFileException : Exception
{
/// <summary>Creates the exception.</summary>
public BankFileException()
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What is wrong, with the line or element (logged; the screens show a generic text).</param>
public BankFileException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What is wrong.</param>
/// <param name="innerException">The cause.</param>
public BankFileException(string message, Exception innerException)
: base(message, innerException)
{
}
}
+270
View File
@@ -0,0 +1,270 @@
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace Khaemhat.Core.Treasury;
/// <summary>
/// Reads ISO 20022 bank to customer statements (<c>camt.053.001.xx</c>, any version): the elements are found by their
/// local names, so the version of the namespace does not matter.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>account: <c>Stmt/Acct/Id/IBAN</c> and <c>Stmt/Acct/Ccy</c> (or the currency of the first amount);</item>
/// <item>balances: <c>OPBD</c> (or <c>PRCD</c>) as opening, <c>CLBD</c> as closing, negative when <c>CdtDbtInd</c> is <c>DBIT</c>;</item>
/// <item>period: <c>FrToDt</c>, otherwise the first and last booking dates;</item>
/// <item>each <c>Ntry</c>: amount signed by <c>CdtDbtInd</c>, <c>BookgDt</c>, <c>ValDt</c>, <c>AcctSvcrRef</c> or the
/// end-to-end id as reference, <c>BkTxCd</c> as bank code (<c>Domn/Fmly/SubFmly</c> or the proprietary code), the
/// description from <c>AddtlNtryInf</c> or the unstructured remittance information, the counterparty from
/// <c>RltdPties</c> (the debtor of a credit, the creditor of a debit);</item>
/// <item>entries with status <c>PDNG</c> or <c>INFO</c> are not booked and are skipped.</item>
/// </list>
/// When a file has several <c>Stmt</c> of the same account their entries are read in order; balances come from the first
/// opening and the last closing.
/// </remarks>
public static class Camt053Reader
{
/// <summary>Whether the start of a file looks like a <c>camt.053</c> statement.</summary>
/// <param name="head">The first bytes of the file.</param>
/// <returns><see langword="true"/> when the head is XML naming <c>camt.053</c> or <c>BkToCstmrStmt</c>.</returns>
public static bool Recognizes(ReadOnlySpan<byte> 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));
}
/// <summary>Reads a statement.</summary>
/// <param name="content">The file.</param>
/// <returns>The statement.</returns>
/// <exception cref="BankFileException">The file is not a readable <c>camt.053</c> statement.</exception>
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<StatementMovement>();
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<string>()
.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<string>());
}
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<XElement> 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));
}
@@ -0,0 +1,400 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Core.Treasury;
/// <summary>
/// Reads the CSV exports of home banking with a <see cref="CsvStatementLayout"/>, and guesses the layout from the header
/// row of the common Italian and English exports.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>The file is UTF-8 (with or without BOM); when it is not valid UTF-8 it is read as Windows-1252.</item>
/// <item>Fields may be quoted, with doubled quotes inside; quoted fields may span lines.</item>
/// <item>Empty rows and the <see cref="CsvStatementLayout.HeaderRows"/> 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.</item>
/// <item>Numbers may carry a leading or trailing sign and the currency (<c>€</c>, <c>EUR</c>); the debit column is read as
/// money out whatever its sign.</item>
/// </list>
/// </remarks>
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"];
/// <summary>Reads a statement.</summary>
/// <param name="content">The file.</param>
/// <param name="layout">Its columns.</param>
/// <returns>The statement: no account, currency or balances, the period from the booking dates.</returns>
/// <exception cref="BankFileException">A row cannot be read; the message names it.</exception>
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<StatementMovement>();
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);
}
/// <summary>
/// Guesses the layout from the header row: the separator (<c>;</c>, tab or <c>,</c>) 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 <c>dd/MM/yyyy</c> (the reader also tries the other common day-first formats).
/// </summary>
/// <param name="headerLine">The first row of the file.</param>
/// <returns>The layout with one header row, or <see langword="null"/> when a date, a description or an amount column is missing.</returns>
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);
}
/// <summary>Reads a number as the bank writes it.</summary>
/// <param name="text">The text, such as <c>-1.234,56</c>, <c>1.234,56-</c>, <c>+12,00 €</c>.</param>
/// <param name="decimalComma">Whether the decimal separator is the comma.</param>
/// <returns>The number, or <see langword="null"/> for an empty field.</returns>
/// <exception cref="FormatException">The text is not a number.</exception>
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<string>();
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<string> 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));
}
+515
View File
@@ -0,0 +1,515 @@
using System.Globalization;
using System.Text;
using System.Xml;
using Khaemhat.Core.Validation;
namespace Khaemhat.Core.Treasury;
/// <summary>
/// Writes SEPA remittances as ISO 20022 customer initiation messages, within the subset of the EPC rulebooks (2023):
/// credit transfers to suppliers as <c>pain.001.001.09</c> and direct debits as <c>pain.008.001.08</c>.
/// </summary>
/// <remarks>
/// <para>
/// Every text is reduced to the SEPA Latin character set (<c>a-z A-Z 0-9 / - ? : ( ) . , ' +</c> 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.
/// </para>
/// <para>
/// When the company has a CBI CUC code it goes in <c>GrpHdr/InitgPty/Id/OrgId/Othr</c> with issuer <c>CBI</c>, as
/// Italian banks require. A bank without a known BIC is written as <c>FinInstnId/Othr/Id</c> <c>NOTPROVIDED</c>.
/// </para>
/// </remarks>
public static class SepaXmlWriter
{
/// <summary>The namespace of credit transfer initiations.</summary>
public const string CreditTransferNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.09";
/// <summary>The namespace of direct debit initiations.</summary>
public const string DirectDebitNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.008.001.08";
/// <summary>The media type of the files.</summary>
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";
/// <summary>Writes a remittance of SEPA credit transfers (<c>pain.001.001.09</c>).</summary>
/// <param name="remittance">The remittance, of kind <see cref="RemittanceKind.SepaCreditTransfer"/>.</param>
/// <returns>The file <c>SCT_&lt;MsgId&gt;.xml</c>.</returns>
/// <exception cref="BankFileException">The remittance cannot be written as SEPA credit transfers.</exception>
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);
}
/// <summary>
/// Writes a remittance of SEPA direct debits (<c>pain.008.001.08</c>), with one payment information block for each
/// sequence and collection date.
/// </summary>
/// <param name="remittance">The remittance, of kind <see cref="RemittanceKind.SddCore"/> or <see cref="RemittanceKind.SddB2b"/>.</param>
/// <returns>The file <c>SDD_&lt;MsgId&gt;.xml</c>.</returns>
/// <exception cref="BankFileException">The remittance cannot be written as SEPA direct debits.</exception>
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);
}
/// <summary>
/// A text in the SEPA Latin character set: accents removed, other characters replaced by spaces, spaces collapsed,
/// cut to a length.
/// </summary>
/// <param name="value">The text.</param>
/// <param name="maxLength">The maximum length.</param>
/// <returns>The text, possibly empty.</returns>
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<XmlWriter> 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<Item> 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);
}
+631
View File
@@ -0,0 +1,631 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Treasury;
/// <summary>The state of an open item (SPEC §11.8, mockup 053).</summary>
public enum OpenItemStatus
{
/// <summary>Nothing collected or paid.</summary>
Open = 0,
/// <summary>Collected or paid in part.</summary>
Partial = 1,
/// <summary>Settled.</summary>
Closed = 2,
/// <summary>Returned unpaid by the bank (insoluto): open again, with the bank fees in an item of their own.</summary>
Unpaid = 3,
/// <summary>In a remittance presented to the bank: the customer is settled, the effect is not collected yet.</summary>
InRemittance = 4,
}
/// <summary>Whether money comes in or goes out.</summary>
public enum PaymentDirection
{
/// <summary>A collection from a customer (incasso).</summary>
Receipt = 0,
/// <summary>A payment to a supplier (pagamento).</summary>
Disbursement = 1,
}
/// <summary>Where a collection or payment comes from.</summary>
public enum PaymentOrigin
{
/// <summary>Recorded in the dialog of the schedule.</summary>
Manual = 0,
/// <summary>The presentation of a remittance (effects, direct debits, transfers).</summary>
Remittance = 1,
/// <summary>A movement of the bank statement matched in the reconciliation.</summary>
BankStatement = 2,
}
/// <summary>
/// A collection or payment (SPEC §11.8, mockup 054, <c>payments</c>): 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 (<c>INC</c>, <c>PAG</c>, or <c>DIST</c> 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.
/// </summary>
public sealed class Payment : Entity<long>, IDemoMarkable
{
/// <summary>In or out.</summary>
public PaymentDirection Direction { get; set; }
/// <summary>The customer or supplier.</summary>
public long PartyId { get; set; }
/// <summary>The day of the collection or payment.</summary>
public DateOnly PaymentDate { get; set; }
/// <summary>The payment method.</summary>
public long? PaymentMethodId { get; set; }
/// <summary>The bank account of the company, when the money goes through a bank.</summary>
public long? BankAccountId { get; set; }
/// <summary>The ledger account of the money (bank, cash, effects for collection).</summary>
public long? AccountId { get; set; }
/// <summary>The money moved (sum of the cash part of the lines), without fees.</summary>
public decimal Amount { get; set; }
/// <summary>The allowances of the lines (positive: granted to the customer, or received from the supplier).</summary>
public decimal AllowanceAmount { get; set; }
/// <summary>The exchange differences of the lines (positive: a loss on collections, a gain on payments).</summary>
public decimal ExchangeDifference { get; set; }
/// <summary>The bank fees, a cost on the same account.</summary>
public decimal Fees { get; set; }
/// <summary>The bank reference (CRO, TRN, cheque number).</summary>
public string? Reference { get; set; }
/// <summary>The journal template of the entry.</summary>
public string? TemplateCode { get; set; }
/// <summary>Notes.</summary>
public string? Notes { get; set; }
/// <summary>Where it comes from.</summary>
public PaymentOrigin Origin { get; set; }
/// <summary>The remittance, when it comes from one.</summary>
public long? RemittanceId { get; set; }
/// <summary>The statement movement it was matched with.</summary>
public long? StatementLineId { get; set; }
/// <summary>The entry.</summary>
public long? GlEntryId { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>The part of a payment that settles one open item (<c>payment_lines</c>).</summary>
public sealed class PaymentLine : Entity<long>
{
/// <summary>The payment.</summary>
public long PaymentId { get; set; }
/// <summary>The open item.</summary>
public long OpenItemId { get; set; }
/// <summary>The money of this item (negative for a credit note set off).</summary>
public decimal Amount { get; set; }
/// <summary>The allowance on this item.</summary>
public decimal Allowance { get; set; }
/// <summary>The exchange difference on this item.</summary>
public decimal ExchangeDifference { get; set; }
/// <summary>What the line settles: money, allowance and exchange difference.</summary>
public decimal Settled => Amount + Allowance + ExchangeDifference;
}
/// <summary>The state of a remittance (mockup 055).</summary>
public enum RemittanceStatus
{
/// <summary>Being prepared: effects can be added and removed.</summary>
Draft = 0,
/// <summary>The file was written: it can still be written again, or the remittance posted.</summary>
Generated = 1,
/// <summary>Posted: the customers are settled (effects) or the suppliers paid (transfers).</summary>
Presented = 2,
/// <summary>Credited by the bank after the due dates: every effect collected or returned unpaid.</summary>
Closed = 3,
}
/// <summary>
/// A remittance (distinta, SPEC §11.8, mockup 055, <c>remittances</c>): RiBa effects or SEPA direct debits presented
/// to a bank, or SEPA credit transfers to suppliers, numbered per year.
/// </summary>
public sealed class Remittance : Entity<long>, IDemoMarkable
{
/// <summary>The year of the number.</summary>
public int Year { get; set; }
/// <summary>The number in the year.</summary>
public int Number { get; set; }
/// <summary>What it carries.</summary>
public RemittanceKind Kind { get; set; }
/// <summary>The bank of the company that receives it.</summary>
public long BankAccountId { get; set; }
/// <summary>The day it is presented (or the transfers executed).</summary>
public DateOnly PresentationDate { get; set; }
/// <summary>The last due date taken.</summary>
public DateOnly DueUntil { get; set; }
/// <summary>Presented subject to collection with an advance (salvo buon fine): the bank credits it at once.</summary>
public bool Advance { get; set; }
/// <summary>The state.</summary>
public RemittanceStatus Status { get; set; }
/// <summary>The total of the effects.</summary>
public decimal TotalAmount { get; set; }
/// <summary>The number of effects.</summary>
public int ItemCount { get; set; }
/// <summary>The unique identifier written in the file.</summary>
public string? MessageId { get; set; }
/// <summary>The attachment with the last file written.</summary>
public long? AttachmentId { get; set; }
/// <summary>The name of the last file written.</summary>
public string? FileName { get; set; }
/// <summary>The entry of the presentation (effects to the bank, or the advance).</summary>
public long? GlEntryId { get; set; }
/// <summary>The day the bank credited the effects.</summary>
public DateOnly? CreditedOn { get; set; }
/// <summary>The entry of the credit.</summary>
public long? CreditEntryId { get; set; }
/// <summary>Notes.</summary>
public string? Notes { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
/// <summary>The number as shown, such as <c>2026/018</c>.</summary>
public string DisplayNumber => $"{Year}/{Number:000}";
}
/// <summary>The state of an effect of a remittance.</summary>
public enum RemittanceLineStatus
{
/// <summary>In the remittance.</summary>
Included = 0,
/// <summary>Collected (or the transfer executed).</summary>
Paid = 1,
/// <summary>Returned unpaid.</summary>
Unpaid = 2,
}
/// <summary>An effect, debit or transfer of a remittance (<c>remittance_lines</c>).</summary>
public sealed class RemittanceLine : Entity<long>
{
/// <summary>The remittance.</summary>
public long RemittanceId { get; set; }
/// <summary>The open item.</summary>
public long OpenItemId { get; set; }
/// <summary>The customer or supplier.</summary>
public long PartyId { get; set; }
/// <summary>The amount.</summary>
public decimal Amount { get; set; }
/// <summary>The due date.</summary>
public DateOnly DueDate { get; set; }
/// <summary>The IBAN of the customer or supplier, as it was when the effect was added.</summary>
public string? Iban { get; set; }
/// <summary>The direct debit mandate.</summary>
public long? MandateId { get; set; }
/// <summary>The end-to-end identifier written in the file.</summary>
public string? EndToEndId { get; set; }
/// <summary>The state.</summary>
public RemittanceLineStatus Status { get; set; }
/// <summary>The day it was returned unpaid.</summary>
public DateOnly? UnpaidOn { get; set; }
/// <summary>The bank fees of the unpaid effect, charged to the customer.</summary>
public decimal UnpaidFees { get; set; }
/// <summary>The entry of the unpaid effect.</summary>
public long? UnpaidEntryId { get; set; }
/// <summary>The payment that settled the item when the remittance was posted.</summary>
public long? PaymentId { get; set; }
}
/// <summary>The scheme of a direct debit mandate.</summary>
public enum SddScheme
{
/// <summary>Core: consumers and companies; the debtor can ask a refund for eight weeks.</summary>
Core = 0,
/// <summary>Business to business: companies only, no refund, the debtor's bank must know the mandate.</summary>
B2b = 1,
}
/// <summary>A SEPA direct debit mandate signed by a customer (<c>sdd_mandates</c>).</summary>
public sealed class SddMandate : Entity<long>, IDemoMarkable
{
/// <summary>The customer.</summary>
public long PartyId { get; set; }
/// <summary>The unique mandate reference (UMR), at most 35 characters.</summary>
public string Reference { get; set; } = string.Empty;
/// <summary>The day it was signed.</summary>
public DateOnly SignatureDate { get; set; }
/// <summary>Core or B2B.</summary>
public SddScheme Scheme { get; set; }
/// <summary>The account debited, compact.</summary>
public string Iban { get; set; } = string.Empty;
/// <summary>The BIC of the debtor's bank.</summary>
public string? Bic { get; set; }
/// <summary>A one-off mandate (a single debit).</summary>
public bool OneOff { get; set; }
/// <summary>The day of the last collection: none means the next one is the first.</summary>
public DateOnly? LastCollectionDate { get; set; }
/// <summary>Revoked by the customer: no more debits.</summary>
public bool Revoked { get; set; }
/// <summary>Notes.</summary>
public string? Notes { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>A bank statement imported (<c>bank_statements</c>, mockup 057).</summary>
public sealed class BankStatement : Entity<long>, IDemoMarkable
{
/// <summary>The bank account of the company.</summary>
public long BankAccountId { get; set; }
/// <summary>The format of the file.</summary>
public StatementFormat Format { get; set; }
/// <summary>The name of the file.</summary>
public string? FileName { get; set; }
/// <summary>The first day.</summary>
public DateOnly FromDate { get; set; }
/// <summary>The last day.</summary>
public DateOnly ToDate { get; set; }
/// <summary>The opening balance, if the file says it.</summary>
public decimal? OpeningBalance { get; set; }
/// <summary>The closing balance, if the file says it.</summary>
public decimal? ClosingBalance { get; set; }
/// <summary>The movements imported (the ones already imported before are skipped).</summary>
public int MovementCount { get; set; }
/// <summary>The file, kept as an attachment.</summary>
public long? AttachmentId { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>The state of a movement in the reconciliation (mockup 057).</summary>
public enum StatementLineStatus
{
/// <summary>Nothing found: to match by hand.</summary>
ToMatch = 0,
/// <summary>A match is proposed, with its confidence.</summary>
Suggested = 1,
/// <summary>Matched and recorded.</summary>
Matched = 2,
/// <summary>Left out on purpose (already recorded in another way).</summary>
Ignored = 3,
}
/// <summary>What a movement is matched with.</summary>
public enum StatementMatchKind
{
/// <summary>Nothing.</summary>
None = 0,
/// <summary>Open items of one customer or supplier: a collection or payment is recorded.</summary>
OpenItems = 1,
/// <summary>A collection or payment already recorded.</summary>
Payment = 2,
/// <summary>The F24 of a due date: its payment is recorded.</summary>
TaxPayment = 3,
/// <summary>A saved rule: an entry on its account is recorded.</summary>
Rule = 4,
/// <summary>The credit of a remittance.</summary>
RemittanceCredit = 5,
/// <summary>An effect returned unpaid.</summary>
Unpaid = 6,
/// <summary>An entry of the ledger on the bank account already recorded.</summary>
Entry = 7,
}
/// <summary>A movement of a bank statement (<c>bank_statement_lines</c>).</summary>
public sealed class BankStatementLine : Entity<long>, IDemoMarkable
{
/// <summary>The statement.</summary>
public long StatementId { get; set; }
/// <summary>The bank account of the company.</summary>
public long BankAccountId { get; set; }
/// <summary>The booking date.</summary>
public DateOnly BookingDate { get; set; }
/// <summary>The value date.</summary>
public DateOnly? ValueDate { get; set; }
/// <summary>Positive for money in, negative for money out.</summary>
public decimal Amount { get; set; }
/// <summary>The description of the bank.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The bank reference.</summary>
public string? Reference { get; set; }
/// <summary>The other party, if known.</summary>
public string? CounterpartyName { get; set; }
/// <summary>Its IBAN, if known.</summary>
public string? CounterpartyIban { get; set; }
/// <summary>The bank transaction code.</summary>
public string? BankCode { get; set; }
/// <summary>A hash of date, amount, description and reference: the same movement is never imported twice.</summary>
public string Fingerprint { get; set; } = string.Empty;
/// <summary>The state.</summary>
public StatementLineStatus Status { get; set; }
/// <summary>What it is (or would be) matched with.</summary>
public StatementMatchKind MatchKind { get; set; }
/// <summary>The confidence of the proposal, 0-100.</summary>
public int Confidence { get; set; }
/// <summary>The proposal, as shown.</summary>
public string? Proposal { get; set; }
/// <summary>The ids the proposal points to (open items, payment, remittance line...), comma separated.</summary>
public string? Targets { get; set; }
/// <summary>The party of the proposal.</summary>
public long? PartyId { get; set; }
/// <summary>The rule of the proposal.</summary>
public long? RuleId { get; set; }
/// <summary>The collection or payment recorded or matched.</summary>
public long? PaymentId { get; set; }
/// <summary>The entry recorded or matched.</summary>
public long? GlEntryId { get; set; }
/// <summary>When it was matched.</summary>
public DateTime? MatchedAt { get; set; }
/// <summary>Who matched it.</summary>
public string? MatchedBy { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>Which movements a rule applies to.</summary>
public enum BankRuleDirection
{
/// <summary>Money in and out.</summary>
Any = 0,
/// <summary>Money in.</summary>
In = 1,
/// <summary>Money out.</summary>
Out = 2,
}
/// <summary>
/// A rule of the reconciliation (<c>bank_match_rules</c>): the movements whose description contains a text are
/// recorded on an account, such as bank fees on <c>21.03.011</c>.
/// </summary>
public sealed class BankMatchRule : Entity<long>, IDemoMarkable
{
/// <summary>The name.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>The text looked for in the description, case and accents ignored.</summary>
public string Pattern { get; set; } = string.Empty;
/// <summary>Money in, out or both.</summary>
public BankRuleDirection Direction { get; set; }
/// <summary>The account the movement goes to (the other side is the bank).</summary>
public long AccountId { get; set; }
/// <summary>The journal template of the entry.</summary>
public string? TemplateCode { get; set; }
/// <summary>The description of the entry; empty for the description of the movement.</summary>
public string? EntryDescription { get; set; }
/// <summary>Not applied.</summary>
public bool Disabled { get; set; }
/// <summary>How many movements it recorded.</summary>
public int Uses { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>How a reminder is sent.</summary>
[Flags]
public enum DunningChannel
{
/// <summary>Not sent: printed only.</summary>
None = 0,
/// <summary>E-mail.</summary>
Email = 1,
/// <summary>Certified e-mail (PEC).</summary>
Pec = 2,
/// <summary>A PDF letter, kept as an attachment of the customer.</summary>
Letter = 4,
}
/// <summary>What happens when a reminder of a level is sent.</summary>
public enum DunningAction
{
/// <summary>Nothing else.</summary>
None = 0,
/// <summary>The agent of the customer is notified.</summary>
NotifyAgent = 1,
/// <summary>The customer is blocked (orders and deliveries) and the administration notified.</summary>
BlockCustomer = 2,
}
/// <summary>A level of the reminders (<c>dunning_levels</c>, mockup 056).</summary>
public sealed class DunningLevel : Entity<long>
{
/// <summary>The level, from 1.</summary>
public int Level { get; set; }
/// <summary>Days after the due date.</summary>
public int DaysAfterDue { get; set; }
/// <summary>The name of the template, such as <c>Promemoria cortese</c>.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>The subject, with fields such as <c>{{Cliente}}</c>.</summary>
public string Subject { get; set; } = string.Empty;
/// <summary>The text, with fields such as <c>{{Elenco}}</c> and <c>{{Totale}}</c>.</summary>
public string Body { get; set; } = string.Empty;
/// <summary>How it is sent.</summary>
public DunningChannel Channel { get; set; }
/// <summary>Late payment interest is computed and written.</summary>
public bool ChargeInterest { get; set; }
/// <summary>What else happens.</summary>
public DunningAction Action { get; set; }
/// <summary>Sent by the scheduled task without asking (e-mail and PEC only).</summary>
public bool Automatic { get; set; }
}
/// <summary>The state of a reminder.</summary>
public enum DunningLetterStatus
{
/// <summary>Waiting in the mail queue.</summary>
Queued = 0,
/// <summary>Sent (or printed).</summary>
Sent = 1,
/// <summary>Not sent.</summary>
Failed = 2,
}
/// <summary>A reminder sent to a customer (<c>dunning_letters</c>): the log of the reminders.</summary>
public sealed class DunningLetter : Entity<long>, IDemoMarkable
{
/// <summary>The customer.</summary>
public long PartyId { get; set; }
/// <summary>The level.</summary>
public int Level { get; set; }
/// <summary>The day.</summary>
public DateOnly SentOn { get; set; }
/// <summary>How it was sent.</summary>
public DunningChannel Channel { get; set; }
/// <summary>The addresses.</summary>
public string? Recipients { get; set; }
/// <summary>The subject.</summary>
public string Subject { get; set; } = string.Empty;
/// <summary>The open items reminded.</summary>
public int ItemCount { get; set; }
/// <summary>The overdue amount.</summary>
public decimal OverdueAmount { get; set; }
/// <summary>The late payment interest written.</summary>
public decimal Interest { get; set; }
/// <summary>The state.</summary>
public DunningLetterStatus Status { get; set; }
/// <summary>The PDF letter.</summary>
public long? AttachmentId { get; set; }
/// <summary>The message in the mail queue.</summary>
public long? MailId { get; set; }
/// <summary>Who sent it (empty for the scheduled task).</summary>
public string? SentBy { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
@@ -0,0 +1,95 @@
namespace Khaemhat.Core.Treasury;
/// <summary>The error codes of the schedule and the treasury; the interface translates them (<c>Treasury.json</c>).</summary>
public static class TreasuryErrors
{
/// <summary>The record does not exist.</summary>
public const string NotFound = "treasury.not-found";
/// <summary>A collection or payment without customer or supplier.</summary>
public const string PartyRequired = "treasury.payment.party-required";
/// <summary>A collection or payment without items.</summary>
public const string ItemsRequired = "treasury.payment.items-required";
/// <summary>A collection or payment without amount.</summary>
public const string AmountRequired = "treasury.payment.amount-required";
/// <summary>The items belong to another party or the other direction.</summary>
public const string ItemParty = "treasury.payment.item-party";
/// <summary>An item would be settled for more than what is left.</summary>
public const string OverSettled = "treasury.payment.over-settled";
/// <summary>An item is in a remittance: it is settled by the remittance.</summary>
public const string InRemittance = "treasury.item.in-remittance";
/// <summary>The lines do not add up to the amount.</summary>
public const string Unbalanced = "treasury.payment.unbalanced";
/// <summary>An allowance, exchange difference or fee has no account.</summary>
public const string AccountMissing = "treasury.account-missing";
/// <summary>No bank or cash account to move the money.</summary>
public const string MoneyAccountMissing = "treasury.money-account-missing";
/// <summary>A collection made by a remittance or a bank statement is cancelled there.</summary>
public const string FromRemittance = "treasury.payment.from-remittance";
/// <summary>The remittance has no items.</summary>
public const string RemittanceEmpty = "treasury.remittance.empty";
/// <summary>The remittance is not in the state the operation needs.</summary>
public const string RemittanceStatus = "treasury.remittance.status";
/// <summary>The bank of the remittance has no IBAN, SIA or creditor identifier for the file.</summary>
public const string RemittanceBank = "treasury.remittance.bank";
/// <summary>An item has no bank coordinates (IBAN, or ABI and CAB for RiBa).</summary>
public const string RemittanceIban = "treasury.remittance.iban";
/// <summary>A direct debit item has no valid mandate.</summary>
public const string RemittanceMandate = "treasury.remittance.mandate";
/// <summary>The item cannot go in this kind of remittance.</summary>
public const string RemittanceItem = "treasury.remittance.item";
/// <summary>The file format is not available.</summary>
public const string RemittanceFormat = "treasury.remittance.format";
/// <summary>Another mandate has the reference.</summary>
public const string MandateDuplicate = "treasury.mandate.duplicate";
/// <summary>The mandate has no reference.</summary>
public const string MandateReference = "treasury.mandate.reference";
/// <summary>The IBAN is not valid.</summary>
public const string IbanInvalid = "treasury.iban-invalid";
/// <summary>The mandate is used by remittances.</summary>
public const string MandateUsed = "treasury.mandate.used";
/// <summary>The bank file is not recognized.</summary>
public const string StatementFormat = "treasury.statement.format";
/// <summary>The bank file has no movements.</summary>
public const string StatementEmpty = "treasury.statement.empty";
/// <summary>The bank file belongs to another bank account.</summary>
public const string StatementAccount = "treasury.statement.account";
/// <summary>The movement is already matched or ignored.</summary>
public const string MatchDone = "treasury.match.done";
/// <summary>The chosen items or payments do not add up to the movement.</summary>
public const string MatchAmount = "treasury.match.amount";
/// <summary>A rule without pattern or account.</summary>
public const string RulePattern = "treasury.rule.pattern";
/// <summary>The customer has no address for the reminder on the chosen channel.</summary>
public const string DunningRecipient = "treasury.dunning.recipient";
/// <summary>A level of reminders without name, subject or days.</summary>
public const string DunningLevel = "treasury.dunning.level";
}
+716
View File
@@ -0,0 +1,716 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Core.Treasury;
/// <summary>The residual of the open items by age (mockup 053).</summary>
/// <param name="NotDue">Not due yet.</param>
/// <param name="Days1To30">Overdue by 1 to 30 days.</param>
/// <param name="Days31To60">Overdue by 31 to 60 days.</param>
/// <param name="Days61To90">Overdue by 61 to 90 days.</param>
/// <param name="Over90">Overdue by more than 90 days.</param>
/// <param name="CountNotDue">Items not due.</param>
/// <param name="Count1To30">Items overdue by 1 to 30 days.</param>
/// <param name="Count31To60">Items overdue by 31 to 60 days.</param>
/// <param name="Count61To90">Items overdue by 61 to 90 days.</param>
/// <param name="CountOver90">Items overdue by more than 90 days.</param>
public sealed record AgingBuckets(
decimal NotDue,
decimal Days1To30,
decimal Days31To60,
decimal Days61To90,
decimal Over90,
int CountNotDue,
int Count1To30,
int Count31To60,
int Count61To90,
int CountOver90)
{
/// <summary>Everything open.</summary>
public decimal Total => NotDue + Overdue;
/// <summary>Everything overdue.</summary>
public decimal Overdue => Days1To30 + Days31To60 + Days61To90 + Over90;
}
/// <summary>The age of open items (SPEC §11.8, <c>AgingCalculator</c>).</summary>
public static class AgingCalculator
{
/// <summary>Days past the due date: negative while it is not due.</summary>
/// <param name="dueDate">The due date.</param>
/// <param name="today">Today.</param>
/// <returns>The days.</returns>
public static int DaysOverdue(DateOnly dueDate, DateOnly today) => today.DayNumber - dueDate.DayNumber;
/// <summary>Splits the residuals by age.</summary>
/// <param name="items">The due date and residual of each item.</param>
/// <param name="today">Today.</param>
/// <returns>The buckets.</returns>
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]);
}
}
/// <summary>Spreads a collection or payment over open items.</summary>
public static class PaymentAllocator
{
/// <summary>
/// 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.
/// </summary>
/// <param name="residuals">The residual of each item, in order.</param>
/// <param name="amount">The money.</param>
/// <returns>What each item takes; what is left over is not given to anyone.</returns>
public static IReadOnlyList<decimal> Allocate(IReadOnlyList<decimal> 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;
}
}
/// <summary>The accounts of the entry of a collection or payment.</summary>
/// <param name="Money">The bank, cash or effects account the money moves on.</param>
/// <param name="AllowanceExpense">Allowances granted (abbuoni passivi).</param>
/// <param name="AllowanceIncome">Allowances received (abbuoni attivi).</param>
/// <param name="ExchangeLoss">Exchange losses.</param>
/// <param name="ExchangeGain">Exchange gains.</param>
/// <param name="BankCharges">Bank fees.</param>
public sealed record PaymentPostingAccounts(long Money, long? AllowanceExpense, long? AllowanceIncome, long? ExchangeLoss, long? ExchangeGain, long? BankCharges);
/// <summary>A line of a collection or payment as the entry reads it.</summary>
/// <param name="ControlAccountId">The customers or suppliers account of the item.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="OpenItemId">The item.</param>
/// <param name="Description">The description (the document).</param>
/// <param name="Amount">The money.</param>
/// <param name="Allowance">The allowance.</param>
/// <param name="ExchangeDifference">The exchange difference.</param>
public sealed record PaymentPostingLine(long ControlAccountId, long PartyId, long OpenItemId, string? Description, decimal Amount, decimal Allowance, decimal ExchangeDifference);
/// <summary>A line of the entry written for a collection or payment.</summary>
/// <param name="AccountId">The account.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="OpenItemId">The item it settles.</param>
/// <param name="Description">The description.</param>
/// <param name="Debit">Dare.</param>
/// <param name="Credit">Avere.</param>
public sealed record PaymentPostedLine(long AccountId, long? PartyId, long? OpenItemId, string? Description, decimal Debit, decimal Credit);
/// <summary>The missing account of a collection or payment.</summary>
public sealed class PaymentAccountMissingException : InvalidOperationException
{
/// <summary>Creates the exception.</summary>
public PaymentAccountMissingException()
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The role of the missing account.</param>
public PaymentAccountMissingException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The role.</param>
/// <param name="innerException">The cause.</param>
public PaymentAccountMissingException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// 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.
/// </summary>
public static class PaymentPosting
{
/// <summary>Builds the lines.</summary>
/// <param name="direction">Collection or payment.</param>
/// <param name="accounts">The accounts.</param>
/// <param name="lines">The items settled.</param>
/// <param name="fees">The bank fees.</param>
/// <param name="description">The description of the money line.</param>
/// <returns>The lines, balanced.</returns>
/// <exception cref="PaymentAccountMissingException">An allowance, exchange difference or fee has no account.</exception>
public static IReadOnlyList<PaymentPostedLine> Build(
PaymentDirection direction, PaymentPostingAccounts accounts, IReadOnlyList<PaymentPostingLine> lines, decimal fees, string? description)
{
ArgumentNullException.ThrowIfNull(accounts);
ArgumentNullException.ThrowIfNull(lines);
var result = new List<PaymentPostedLine>();
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;
}
}
/// <summary>Late payment interest (SPEC §11.8, D.Lgs. 231/2002 in Italy).</summary>
public static class LateInterestCalculator
{
/// <summary>
/// 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.
/// </summary>
/// <param name="residual">The amount overdue.</param>
/// <param name="dueDate">The due date.</param>
/// <param name="until">The last day counted.</param>
/// <param name="rateOn">The yearly rate in percent of a day.</param>
/// <returns>The interest; zero when not overdue.</returns>
public static decimal Interest(decimal residual, DateOnly dueDate, DateOnly until, Func<DateOnly, decimal> 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);
}
}
/// <summary>A possible match of a bank movement, built by the reconciliation from the open data of the company.</summary>
/// <param name="Kind">What it is.</param>
/// <param name="Targets">The ids it points to, comma separated.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Amount">The movement it expects: positive money in, negative money out.</param>
/// <param name="Date">The date it expects (due date, payment date).</param>
/// <param name="Label">The proposal as shown, such as <c>Incasso FT/2026/000388</c>.</param>
/// <param name="Keys">Document numbers and references that may appear in the description.</param>
/// <param name="Names">Names of the party that may appear.</param>
/// <param name="Ibans">IBANs of the party.</param>
/// <param name="Keywords">Words that must appear for the candidate to count (such as <c>INSOLUT</c>, <c>F24</c>); empty for none.</param>
/// <param name="AmountTolerance">How much more the movement may be (bank fees of an unpaid effect).</param>
public sealed record MatchCandidate(
StatementMatchKind Kind,
string? Targets,
long? PartyId,
decimal Amount,
DateOnly Date,
string Label,
IReadOnlyList<string> Keys,
IReadOnlyList<string> Names,
IReadOnlyList<string> Ibans,
IReadOnlyList<string> Keywords,
decimal AmountTolerance = 0m);
/// <summary>A saved rule as the matcher reads it.</summary>
/// <param name="Id">The rule.</param>
/// <param name="Pattern">The text looked for.</param>
/// <param name="Direction">Money in, out or both.</param>
/// <param name="Label">The proposal, such as <c>Regola 'COMMISSIONI' → 21.03.011 Spese bancarie</c>.</param>
public sealed record MatchRule(long Id, string Pattern, BankRuleDirection Direction, string Label);
/// <summary>The best match of a movement.</summary>
/// <param name="Kind">What it is.</param>
/// <param name="Targets">The ids.</param>
/// <param name="PartyId">The party.</param>
/// <param name="RuleId">The rule.</param>
/// <param name="Confidence">0-100.</param>
/// <param name="Label">As shown.</param>
public sealed record MatchProposal(StatementMatchKind Kind, string? Targets, long? PartyId, long? RuleId, int Confidence, string Label);
/// <summary>
/// Proposes what a bank movement is (SPEC §11.8, mockup 057, <c>BankMatcher</c>): 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.
/// </summary>
public static class BankMatcher
{
/// <summary>The words before a document number in bank descriptions.</summary>
private static readonly HashSet<string> NumberPrefixes = new(StringComparer.Ordinal)
{
"FT", "FATT", "FATTURA", "FATTURE", "FAT", "FA", "N", "NR", "NUM", "DOC", "RIF", "FAT.", "INV", "INVOICE",
};
/// <summary>The best proposal for a movement, or <see langword="null"/> when nothing fits.</summary>
/// <param name="movement">The movement.</param>
/// <param name="candidates">The candidates.</param>
/// <param name="rules">The rules.</param>
/// <returns>The proposal.</returns>
public static MatchProposal? Best(StatementMovement movement, IEnumerable<MatchCandidate> candidates, IEnumerable<MatchRule> 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;
}
/// <summary>The score of a candidate, 0 when it does not fit.</summary>
/// <param name="movement">The movement.</param>
/// <param name="candidate">The candidate.</param>
/// <returns>0-100.</returns>
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));
}
/// <summary>Upper case, no accents, only letters and digits separated by single spaces.</summary>
/// <param name="text">The text.</param>
/// <returns>The normalised text.</returns>
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();
}
/// <summary>
/// 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.
/// </summary>
/// <param name="items">The id and residual of the items, oldest first.</param>
/// <param name="amount">The amount.</param>
/// <returns>The ids, or an empty list.</returns>
public static IReadOnlyList<long> 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);
}
/// <summary>An open item as the reminders read it.</summary>
/// <param name="OpenItemId">The item.</param>
/// <param name="DueDate">The due date.</param>
/// <param name="Residual">What is left.</param>
/// <param name="Level">The level of its last reminder.</param>
/// <param name="LastDunningDate">The day of its last reminder.</param>
/// <param name="Disputed">Contested.</param>
public sealed record DunningItem(long OpenItemId, DateOnly DueDate, decimal Residual, int Level, DateOnly? LastDunningDate, bool Disputed);
/// <summary>A level as the reminders read it.</summary>
/// <param name="Level">The level.</param>
/// <param name="DaysAfterDue">Days after the due date.</param>
public sealed record DunningStep(int Level, int DaysAfterDue);
/// <summary>Which reminder a customer gets next (SPEC §11.8, mockup 056, <c>DunningRules</c>).</summary>
public static class DunningRules
{
/// <summary>Days between two reminders to the same customer.</summary>
public const int MinDaysBetween = 7;
/// <summary>
/// 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.
/// </summary>
/// <param name="items">The open items of the customer.</param>
/// <param name="levels">The levels.</param>
/// <param name="today">Today.</param>
/// <returns>The level, or <see langword="null"/>.</returns>
public static int? NextLevel(IReadOnlyList<DunningItem> items, IReadOnlyList<DunningStep> 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;
}
}
/// <summary>What a forecast movement comes from.</summary>
public enum CashFlowSource
{
/// <summary>Open items of customers.</summary>
Receivables = 0,
/// <summary>Open items of suppliers.</summary>
Payables = 1,
/// <summary>Customer orders not invoiced.</summary>
SaleOrders = 2,
/// <summary>Supplier orders not invoiced.</summary>
PurchaseOrders = 3,
/// <summary>Recurring entries on bank or cash.</summary>
Recurring = 4,
/// <summary>Taxes to pay (F24).</summary>
Taxes = 5,
}
/// <summary>A forecast movement.</summary>
/// <param name="Date">When it is expected.</param>
/// <param name="Amount">Positive in, negative out.</param>
/// <param name="Source">Where it comes from.</param>
/// <param name="Label">What it is.</param>
public sealed record CashFlowMovement(DateOnly Date, decimal Amount, CashFlowSource Source, string Label);
/// <summary>A period of the forecast.</summary>
/// <param name="From">The first day.</param>
/// <param name="To">The last day.</param>
/// <param name="In">Money in.</param>
/// <param name="Out">Money out (positive).</param>
/// <param name="Balance">The balance at the end of the period.</param>
public sealed record CashFlowPeriod(DateOnly From, DateOnly To, decimal In, decimal Out, decimal Balance);
/// <summary>The cash flow forecast (SPEC §11.8, <c>CashFlowForecastService</c>): the balance period by period.</summary>
public static class CashFlowForecaster
{
/// <summary>Spreads the movements over periods; the overdue ones count in the first period.</summary>
/// <param name="opening">The money today on bank and cash.</param>
/// <param name="movements">The movements.</param>
/// <param name="from">The first day.</param>
/// <param name="days">How many days.</param>
/// <param name="periodDays">The days of a period.</param>
/// <returns>The periods.</returns>
public static IReadOnlyList<CashFlowPeriod> Periods(decimal opening, IEnumerable<CashFlowMovement> 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<CashFlowPeriod>();
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;
}
}
/// <summary>The state of an open item in the schedule from its amounts (ADR 0038).</summary>
public static class OpenItemStates
{
/// <summary>The state an item has after a change of its amounts.</summary>
/// <param name="item">The item.</param>
/// <returns>In remittance while a remittance holds it; closed when nothing is left; partial when something was settled; unpaid after a returned effect; open otherwise.</returns>
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;
}
}
@@ -99,6 +99,7 @@ public sealed class OpenItemMap : EntityMap<OpenItem>
{
ToTable("gl_open_items");
Map(x => x.DocumentNumber).MaxLength(30);
Map(x => x.Notes).MaxLength(200);
}
}
@@ -0,0 +1,252 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>
/// 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.
/// </summary>
[Migration(20261113_003, "create_treasury")]
public sealed class M20261113_003_CreateTreasury : IMigration
{
/// <inheritdoc />
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);
});
}
}
@@ -208,6 +208,7 @@ public sealed class BankAccountMap : EntityMap<BankAccount>
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);
}
}
@@ -0,0 +1,134 @@
using Khaemhat.Core.Treasury;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.CompanyDatabase;
/// <summary>Map of <see cref="Payment"/> to <c>payments</c>.</summary>
public sealed class PaymentMap : EntityMap<Payment>
{
/// <summary>Creates the map.</summary>
public PaymentMap()
{
ToTable("payments");
Map(x => x.Reference).MaxLength(60);
Map(x => x.TemplateCode).MaxLength(10);
Map(x => x.Notes).MaxLength(500);
}
}
/// <summary>Map of <see cref="PaymentLine"/> to <c>payment_lines</c>.</summary>
public sealed class PaymentLineMap : EntityMap<PaymentLine>
{
/// <summary>Creates the map.</summary>
public PaymentLineMap() => ToTable("payment_lines");
}
/// <summary>Map of <see cref="Remittance"/> to <c>remittances</c>.</summary>
public sealed class RemittanceMap : EntityMap<Remittance>
{
/// <summary>Creates the map.</summary>
public RemittanceMap()
{
ToTable("remittances");
Map(x => x.MessageId).MaxLength(35);
Map(x => x.FileName).MaxLength(100);
Map(x => x.Notes).MaxLength(500);
}
}
/// <summary>Map of <see cref="RemittanceLine"/> to <c>remittance_lines</c>.</summary>
public sealed class RemittanceLineMap : EntityMap<RemittanceLine>
{
/// <summary>Creates the map.</summary>
public RemittanceLineMap()
{
ToTable("remittance_lines");
Map(x => x.Iban).MaxLength(34);
Map(x => x.EndToEndId).MaxLength(35);
}
}
/// <summary>Map of <see cref="SddMandate"/> to <c>sdd_mandates</c>.</summary>
public sealed class SddMandateMap : EntityMap<SddMandate>
{
/// <summary>Creates the map.</summary>
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);
}
}
/// <summary>Map of <see cref="BankStatement"/> to <c>bank_statements</c>.</summary>
public sealed class BankStatementMap : EntityMap<BankStatement>
{
/// <summary>Creates the map.</summary>
public BankStatementMap()
{
ToTable("bank_statements");
Map(x => x.FileName).MaxLength(200);
}
}
/// <summary>Map of <see cref="BankStatementLine"/> to <c>bank_statement_lines</c>.</summary>
public sealed class BankStatementLineMap : EntityMap<BankStatementLine>
{
/// <summary>Creates the map.</summary>
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);
}
}
/// <summary>Map of <see cref="BankMatchRule"/> to <c>bank_match_rules</c>.</summary>
public sealed class BankMatchRuleMap : EntityMap<BankMatchRule>
{
/// <summary>Creates the map.</summary>
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);
}
}
/// <summary>Map of <see cref="DunningLevel"/> to <c>dunning_levels</c>.</summary>
public sealed class DunningLevelMap : EntityMap<DunningLevel>
{
/// <summary>Creates the map.</summary>
public DunningLevelMap()
{
ToTable("dunning_levels");
Map(x => x.Name).MaxLength(100);
Map(x => x.Subject).MaxLength(200);
Map(x => x.Channel).MaxLength(60);
}
}
/// <summary>Map of <see cref="DunningLetter"/> to <c>dunning_letters</c>.</summary>
public sealed class DunningLetterMap : EntityMap<DunningLetter>
{
/// <summary>Creates the map.</summary>
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);
}
}
@@ -0,0 +1,67 @@
using Khaemhat.Core.Treasury;
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>
/// 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 <c>Khaemhat.Core.Treasury.SepaXmlWriter</c> for every
/// country.
/// </summary>
public interface IRemittanceFileWriter
{
/// <summary>Whether this writer writes a kind of remittance.</summary>
/// <param name="kind">The kind.</param>
/// <returns><see langword="true"/> when <see cref="Write"/> accepts it.</returns>
bool Supports(RemittanceKind kind);
/// <summary>Writes the file.</summary>
/// <param name="remittance">The remittance.</param>
/// <returns>The file.</returns>
/// <exception cref="BankFileException">A value cannot be written in the format.</exception>
BankFile Write(BankFileRemittance remittance);
}
/// <summary>
/// Reads the national bank statement format of the country (Italy: CBI). CSV and <c>camt.053</c> are read by
/// <c>Khaemhat.Core.Treasury</c> for every country.
/// </summary>
public interface IBankStatementReader
{
/// <summary>The format read.</summary>
StatementFormat Format { get; }
/// <summary>Whether the start of a file looks like this format.</summary>
/// <param name="head">The first bytes of the file (up to 4 KB).</param>
/// <returns><see langword="true"/> when <see cref="Read"/> should be tried.</returns>
bool Recognizes(ReadOnlySpan<byte> head);
/// <summary>Reads a statement.</summary>
/// <param name="content">The file.</param>
/// <returns>The statement.</returns>
/// <exception cref="BankFileException">The file is not in the format.</exception>
StatementFile Read(Stream content);
}
/// <summary>Late payment interest between companies (Italy: D.Lgs. 231/2002).</summary>
public interface ILatePaymentRules
{
/// <summary>The yearly rate, in percent, that applies to the days of a half-year.</summary>
/// <param name="day">A day.</param>
/// <returns>The reference rate of the half-year plus the margin.</returns>
decimal RateOn(DateOnly day);
/// <summary>The law the interest comes from, for the letters (Italy: <c>D.Lgs. 231/2002</c>).</summary>
string LegalReference { get; }
/// <summary>The fixed compensation for recovery costs, per invoice (Italy: 40 euro, art. 6).</summary>
decimal RecoveryCompensation { get; }
}
/// <summary>Which remittance collects or pays the items of a payment method, by the code of the method in the pack.</summary>
public interface IRemittanceMethods
{
/// <summary>The kind of remittance of a method.</summary>
/// <param name="methodCode">The code of the method in the e-invoice (for Italy the <c>MPxx</c> codes).</param>
/// <returns>The kind, or <see langword="null"/> when the method does not go in remittances.</returns>
RemittanceKind? KindOf(string? methodCode);
}
@@ -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;
/// <summary>
/// Reads the CBI current account statement (rendicontazione movimenti di conto corrente, flow <c>RH</c>): records of
/// 120 characters, the <c>RH</c> header, the opening balance <c>61</c>, each movement <c>62</c> with its description
/// lines <c>63</c>, the closing balance <c>64</c> and the <c>EF</c> footer.
/// </summary>
/// <remarks>
/// 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>C</c> (credit, money in) and <c>D</c> (debit, money out); dates are <c>DDMMYY</c>.
/// <list type="table">
/// <listheader><term>Record</term><description>Positions read</description></listheader>
/// <item><term>RH</term><description>4-8 sender ABI; 9-13 receiver SIA; 14-19 creation date; 20-39 support name.</description></item>
/// <item><term>61</term><description>4-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.</description></item>
/// <item><term>62</term><description>4-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.</description></item>
/// <item><term>63</term><description>4-10 progressive; 11-13 movement number; 14-120 more description, appended to the
/// movement before.</description></item>
/// <item><term>64</term><description>4-10 progressive; 11-13 currency; 14-19 date of the closing balance; 20 sign; 21-35
/// closing (book) balance.</description></item>
/// <item><term>EF</term><description>end of the flow; nothing is read.</description></item>
/// </list>
/// 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.
/// </remarks>
public sealed class CbiStatementReader : IBankStatementReader
{
private const int RecordLength = 120;
/// <inheritdoc />
public StatementFormat Format => StatementFormat.Cbi;
/// <inheritdoc />
public bool Recognizes(ReadOnlySpan<byte> 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);
}
/// <inheritdoc />
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<Movement>();
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);
}
@@ -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;;;;
1 codice descrizione natura tipo voce_cee partitario iva
206 28.01.002 Interessi passivi su mutui C C.17
207 28.01.003 Interessi sulla liquidazione IVA trimestrale C C.17
208 28.01.004 Oneri finanziari diversi C C.17
209 28.01.005 Perdite su cambi C C.17-bis
210 29 Imposte sul reddito C 20
211 29.01 Imposte sul reddito dell'esercizio C 20
212 29.01.001 IRES dell'esercizio C 20
232 32.01 Proventi finanziari R C.16
233 32.01.001 Interessi attivi bancari R C.16
234 32.01.002 Altri proventi finanziari R C.16
235 32.01.003 Utili su cambi R C.17-bis
236 32.01.004 Interessi di mora attivi R C.16
237 90 Conti di apertura e chiusura O
238 90.01 Conti di apertura e chiusura O
239 90.01.001 Stato patrimoniale di apertura O
@@ -60,6 +60,27 @@ public sealed class ItalianLedgerTemplate : ILedgerTemplate
/// <summary>The interest of quarterly VAT payers.</summary>
public const string VatInterest = "28.01.003";
/// <summary>Allowances received.</summary>
public const string AllowanceIncome = "31.01.004";
/// <summary>Bank fees.</summary>
public const string BankCharges = "21.03.011";
/// <summary>Effects and direct debits presented for collection.</summary>
public const string BillsForCollection = "05.02.001";
/// <summary>Advances of the bank on effects.</summary>
public const string BankAdvances = "13.01.001";
/// <summary>Exchange gains.</summary>
public const string ExchangeGain = "32.01.003";
/// <summary>Exchange losses.</summary>
public const string ExchangeLoss = "28.01.005";
/// <summary>Late payment interest charged to customers.</summary>
public const string LateInterest = "32.01.004";
private readonly Lazy<IReadOnlyList<AccountTemplate>> _accounts = new(ReadAccounts);
/// <inheritdoc />
@@ -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,
[
@@ -15,6 +15,8 @@ public sealed class ItalyFiscalPack : FiscalPackBase
public ItalyFiscalPack()
{
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
AddFeature<ILatePaymentRules>(new LatePaymentRulesIt());
AddFeature<IRemittanceMethods>(new RemittanceMethodsIt());
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
@@ -27,6 +29,8 @@ public sealed class ItalyFiscalPack : FiscalPackBase
AddFeature<ILedgerTemplate>(new ItalianLedgerTemplate());
AddFeature<IVatSettlementRules>(new VatSettlementRulesIt());
AddFeature<IPeriodicVatReturnWriter>(new LipeWriter());
AddFeature<IRemittanceFileWriter>(new RibaCbiWriter());
AddFeature<IBankStatementReader>(new CbiStatementReader());
// ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026).
AddFeature<IBankDirectory>(new ItalianBankDirectory([]));
@@ -0,0 +1,56 @@
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// 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.
/// </summary>
public sealed class LatePaymentRulesIt : ILatePaymentRules
{
/// <summary>The points added to the reference rate.</summary>
public const decimal Margin = 8m;
/// <summary>The ECB main refinancing rate on the first day of each half-year, in percent.</summary>
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),
];
/// <inheritdoc />
public string LegalReference => "D.Lgs. 231/2002";
/// <inheritdoc />
public decimal RecoveryCompensation => 40m;
/// <summary>The reference rate of the half-year of a day, without the margin.</summary>
/// <param name="day">A day.</param>
/// <returns>The rate in percent.</returns>
public static decimal ReferenceRateOn(DateOnly day)
{
var rate = ReferenceRates[0].Rate;
foreach (var (from, value) in ReferenceRates)
{
if (from <= day)
{
rate = value;
}
}
return rate;
}
/// <inheritdoc />
public decimal RateOn(DateOnly day) => ReferenceRateOn(day) + Margin;
}
@@ -0,0 +1,21 @@
using Khaemhat.Core.Treasury;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// The Italian payment methods (codes <c>MPxx</c> 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).
/// </summary>
public sealed class RemittanceMethodsIt : IRemittanceMethods
{
/// <inheritdoc />
public RemittanceKind? KindOf(string? methodCode) => methodCode switch
{
"MP12" => RemittanceKind.Riba,
"MP19" or "MP20" => RemittanceKind.SddCore,
"MP21" => RemittanceKind.SddB2b,
"MP05" => RemittanceKind.SepaCreditTransfer,
_ => null,
};
}
+253
View File
@@ -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;
/// <summary>
/// Writes a remittance of bank receipts (ricevute bancarie) in the CBI fixed-width layout "Ricevute bancarie": records
/// of 120 characters separated by CRLF, the <c>IB</c> header, for each receipt the records <c>14</c>, <c>20</c>,
/// <c>30</c>, <c>40</c>, <c>50</c>, <c>51</c>, <c>70</c>, and the <c>EF</c> footer. Texts are upper case ASCII (accents
/// dropped) padded with spaces, numbers are zero padded, dates are <c>DDMMYY</c> and amounts are in cents.
/// </summary>
/// <remarks>
/// 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.
/// <list type="table">
/// <listheader><term>Record</term><description>Positions</description></listheader>
/// <item><term>IB</term><description>4-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 <c>E</c>.</description></item>
/// <item><term>14</term><description>4-10 progressive; 23-28 due date; 29-33 causale <c>30000</c>; 34-46 amount in cents;
/// 47 sign <c>-</c>; 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 <c>4</c>; 98-113 debtor code; 120 currency <c>E</c>.</description></item>
/// <item><term>20</term><description>4-10 progressive; 11-34 creditor name; 35-58 street; 59-82 postal code, town and
/// province; 83-106 VAT number or tax code.</description></item>
/// <item><term>30</term><description>4-10 progressive; 11-40 and 41-70 debtor name; 71-86 debtor tax code.</description></item>
/// <item><term>40</term><description>4-10 progressive; 11-40 debtor street; 41-45 postal code; 46-67 town; 69-70 province;
/// 71-120 debtor bank and branch.</description></item>
/// <item><term>50</term><description>4-10 progressive; 11-50 and 51-90 reference (the invoices paid); 101-116 creditor
/// tax code.</description></item>
/// <item><term>51</term><description>4-10 progressive; 11-20 receipt number; 21-40 creditor name.</description></item>
/// <item><term>70</term><description>4-10 progressive (closing record of the receipt).</description></item>
/// <item><term>EF</term><description>4-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 <c>E</c>.</description></item>
/// </list>
/// </remarks>
public sealed class RibaCbiWriter : IRemittanceFileWriter
{
/// <summary>The length of every record.</summary>
public const int RecordLength = 120;
/// <summary>The media type of the file.</summary>
public const string ContentType = "text/plain";
private const long MaximumItemCents = 9_999_999_999_999L;
private const long MaximumTotalCents = 999_999_999_999_999L;
/// <inheritdoc />
public bool Supports(RemittanceKind kind) => kind == RemittanceKind.Riba;
/// <inheritdoc />
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<string>();
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));
}
/// <summary>
/// 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.
/// </summary>
/// <param name="value">The text.</param>
/// <param name="length">The length of the field.</param>
/// <returns>The field, exactly <paramref name="length"/> characters.</returns>
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);
}
}
@@ -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. *@
<KhPageTitle Text="@T["Treasury.CashFlow.Title"]" Icon="chart" />
<FinanceGuard Permission="@TreasuryPermissions.ScheduleRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@TreasuryScreens.BasePath">@T["Shell.Menu.Finance"]</a> / @T["Treasury.CashFlow.Title"]</div>
<h1>@T["Treasury.CashFlow.Heading"]</h1>
<div class="sub">@T["Treasury.CashFlow.Hint"]</div>
</div>
</div>
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhSelect TValue="int" Label="@T["Treasury.CashFlow.Days"]" Name="cfdays" Options="DayChoices" Value="_days" ValueChanged="SetDaysAsync" />
<KhSelect TValue="int" Label="@T["Treasury.CashFlow.Period"]" Name="cfperiod" Options="PeriodChoices" Value="_period" ValueChanged="SetPeriodAsync" />
@foreach (var source in Enum.GetValues<CashFlowSource>())
{
<label class="chk">
<input type="checkbox" checked="@_sources.Contains(source)" @onchange="e => ToggleAsync(source, e.Value is true)" />
@T[TreasuryScreens.EnumKey(source)]
</label>
}
</div>
</KhPanel>
@if (_forecast is { } f)
{
var lowest = f.Periods.Count == 0 ? f.Opening : Math.Min(f.Opening, f.Periods.Min(p => p.Balance));
<KhStrip Items="Stats(f, lowest)" Label="@T["Treasury.CashFlow.Title"]" />
<div class="kh-ledger-two">
<KhPanel Title="@T["Treasury.CashFlow.Periods"]" Icon="chart" Tight="true">
<table class="grid" aria-label="@T["Treasury.CashFlow.Periods"]">
<thead>
<tr>
<th scope="col">@T["Treasury.CashFlow.Period"]</th>
<th scope="col" class="num">@T["Treasury.Reconciliation.In"]</th>
<th scope="col" class="num">@T["Treasury.Reconciliation.Out"]</th>
<th scope="col" class="num">@T["Treasury.CashFlow.Balance"]</th>
<th scope="col" class="kh-cfbarcol"><span class="sr-only">@T["Treasury.CashFlow.Chart"]</span></th>
</tr>
</thead>
<tbody>
@foreach (var p in f.Periods)
{
var width = BarWidth(f, p.Balance);
<tr>
<td>@T.Date(p.From) – @T.Date(p.To)</td>
<td class="num pos">@(p.In != 0m ? T.Money(p.In) : null)</td>
<td class="num neg">@(p.Out != 0m ? T.Money(p.Out) : null)</td>
<td class="num @(p.Balance < 0m ? "neg" : null)"><b>@T.Money(p.Balance)</b></td>
<td class="kh-cfbarcol"><span class="kh-cfbar @(p.Balance < 0m ? "neg" : null)" style="width:@(width)%"></span></td>
</tr>
}
</tbody>
</table>
</KhPanel>
<KhPanel Title="@T["Treasury.CashFlow.Accounts"]" Icon="building" Tight="true">
<table class="grid" aria-label="@T["Treasury.CashFlow.Accounts"]">
<tbody>
@foreach (var a in f.Accounts)
{
<tr>
<td>@a.Name</td>
<td class="num">@T.Money(a.Balance)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td><b>@T["Treasury.Fields.Total"]</b></td>
<td class="num"><b>@T.Money(f.Opening)</b></td>
</tr>
</tfoot>
</table>
</KhPanel>
</div>
<KhPanel Title="@T["Treasury.CashFlow.Movements"]" Icon="list" Tight="true">
@if (f.Movements.Count == 0)
{
<p class="kh-wempty">@T["Treasury.CashFlow.NoMovements"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Treasury.CashFlow.Movements"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Date"]</th>
<th scope="col">@T["Treasury.CashFlow.Source"]</th>
<th scope="col">@T["Treasury.Reconciliation.Description"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Amount"]</th>
</tr>
</thead>
<tbody>
@foreach (var m in f.Movements)
{
<tr>
<td>@T.Date(m.Date)</td>
<td>@T[TreasuryScreens.EnumKey(m.Source)]</td>
<td>@m.Label</td>
<td class="num @(m.Amount < 0m ? "neg" : "pos")">@T.Money(m.Amount)</td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
}
</FinanceGuard>
@code {
private int _days = 90;
private int _period = 7;
private readonly HashSet<CashFlowSource> _sources = [.. Enum.GetValues<CashFlowSource>()];
private CashFlowForecast? _forecast;
private IReadOnlyList<KhOption<int>> DayChoices =>
[.. new[] { 30, 60, 90, 180, 365 }.Select(d => new KhOption<int>(d, T.Format("Treasury.CashFlow.DaysText", d)))];
private IReadOnlyList<KhOption<int>> PeriodChoices =>
[
new(7, T["Treasury.CashFlow.Weeks"]),
new(30, T["Treasury.CashFlow.Months"]),
];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (FinanceGuard.Allowed(Session, TreasuryPermissions.ScheduleRead))
{
await LoadAsync();
}
}
/// <summary>
/// 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.
/// </summary>
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<KhStat> 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();
}
}
@@ -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. *@
<KhPageTitle Text="@T["Treasury.Dunning.Title"]" Icon="mail" />
<FinanceGuard Permission="@TreasuryPermissions.ScheduleRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@TreasuryScreens.BasePath">@T["Shell.Menu.Finance"]</a> / @T["Treasury.Dunning.Title"]</div>
<h1>@T["Treasury.Dunning.Heading"]</h1>
</div>
<div class="grow"></div>
@if (CanWrite)
{
<div class="toolbar">
<button type="button" class="btn" disabled="@(_busy || _included.Count == 0)" @onclick="PreviewAsync"><KhIcon Name="eye" /> @T["Treasury.Dunning.Preview"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _included.Count == 0)" @onclick="SendAsync"><KhIcon Name="send" /> @T.Format("Treasury.Dunning.Send", _included.Count)</button>
</div>
}
</div>
<KhStrip Items="Stats" Label="@T["Treasury.Dunning.Title"]" />
<KhTabs Items="Tabs" Active="@_tab" ActiveChanged="SetTabAsync" Label="@T["Treasury.Dunning.Title"]" />
@if (_tab == "proposal")
{
<KhPanel Title="@T["Treasury.Dunning.Proposal"]" Tight="true">
<Actions><span class="muted sm">@T["Treasury.Dunning.Rule"]</span></Actions>
<ChildContent>
@if (_proposal.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Dunning.Nothing"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Treasury.Dunning.Proposal"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Customer"]</th>
<th scope="col" class="num">@T["Treasury.Dunning.Items"]</th>
<th scope="col" class="num">@T["Treasury.Schedule.Overdue"]</th>
<th scope="col" class="num">@T["Treasury.Dunning.MaxDays"]</th>
<th scope="col">@T["Treasury.Dunning.LastSent"]</th>
<th scope="col">@T["Treasury.Dunning.NextLevel"]</th>
<th scope="col">@T["Treasury.Dunning.Channel"]</th>
<th scope="col" class="num">@T["Treasury.Statement.Interest"]</th>
<th scope="col">@T["Treasury.Dunning.Include"]</th>
</tr>
</thead>
<tbody>
@foreach (var p in _proposal)
{
<tr>
<td><b>@p.PartyName</b> @(p.Blocked ? T["Treasury.Dunning.Blocked"] : null)</td>
<td class="num">@p.Items.Count</td>
<td class="num">@T.Money(p.Overdue)</td>
<td class="num">@p.MaxDays</td>
<td>@(p.LastSent is { } last ? p.CurrentLevel + " · " + T.Date(last) : "—")</td>
<td>
@if (p.Level is { } level)
{
<KhBadge Tone="@(level.Level >= 2 ? KhTone.Warning : KhTone.Info)">@T.Format("Treasury.Dunning.Level", level.Level)</KhBadge>
}
else
{
<KhBadge Tone="KhTone.Neutral">@T["Treasury.Dunning.Waiting"]</KhBadge>
}
</td>
<td>@(p.Level is { } l ? TreasuryScreens.ChannelText(T, l.Channel) : "—") <span class="muted sm">@(p.Pec ?? p.Email)</span></td>
<td class="num">@T.Money(p.Interest)</td>
<td>
@if (p.Level is not null)
{
var on = _included.Contains(p.PartyId);
<button type="button" role="switch" class="kh-switch" aria-checked="@(on ? "true" : "false")" aria-label="@(T["Treasury.Dunning.Include"] + " " + p.PartyName)"
@onclick="() => Toggle(p.PartyId, !on)">
<span class="switch @(on ? "on" : null)" aria-hidden="true"></span>
</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
</KhPanel>
<KhPanel Title="@T["Treasury.Dunning.Levels"]" Tight="true">
<table class="grid" aria-label="@T["Treasury.Dunning.Levels"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Dunning.LevelColumn"]</th>
<th scope="col" class="num">@T["Treasury.Dunning.After"]</th>
<th scope="col">@T["Treasury.Dunning.Template"]</th>
<th scope="col">@T["Treasury.Dunning.Channel"]</th>
<th scope="col">@T["Treasury.Statement.Interest"]</th>
<th scope="col">@T["Treasury.Dunning.Action"]</th>
<th scope="col">@T["Treasury.Dunning.Automatic"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var level in _levels)
{
<tr>
<td>@level.Level</td>
<td class="num">@level.DaysAfterDue</td>
<td>@level.Name</td>
<td>@TreasuryScreens.ChannelText(T, level.Channel)</td>
<td>@T[level.ChargeInterest ? "Treasury.Dunning.InterestYes" : "Treasury.Dunning.InterestNo"]</td>
<td>@T[TreasuryScreens.EnumKey(level.Action)]</td>
<td>@T[level.Automatic ? "Common.Yes" : "Common.No"]</td>
<td class="kh-acts">
@if (CanWrite)
{
<KhIconButton Icon="edit" Text="@T["Treasury.Dunning.EditLevel"]" OnClick="() => OpenLevel(level)" />
}
</td>
</tr>
}
</tbody>
</table>
<div class="filters"><span class="muted sm">@T["Treasury.Dunning.Placeholders"]</span></div>
</KhPanel>
}
else
{
<KhPanel Tight="true">
@if (_history.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Dunning.NoHistory"]</p>
}
else
{
<table class="grid" aria-label="@T["Treasury.Dunning.History"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Date"]</th>
<th scope="col">@T["Treasury.Fields.Customer"]</th>
<th scope="col">@T["Treasury.Dunning.LevelColumn"]</th>
<th scope="col">@T["Treasury.Dunning.Channel"]</th>
<th scope="col">@T["Treasury.Dunning.Recipients"]</th>
<th scope="col" class="num">@T["Treasury.Dunning.Items"]</th>
<th scope="col" class="num">@T["Treasury.Schedule.Overdue"]</th>
<th scope="col" class="num">@T["Treasury.Statement.Interest"]</th>
<th scope="col">@T["Treasury.Fields.Status"]</th>
<th scope="col">@T["Treasury.Dunning.SentBy"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in _history)
{
var l = row.Letter;
<tr>
<td>@T.Date(l.SentOn)</td>
<td>@row.PartyName</td>
<td>@l.Level</td>
<td>@TreasuryScreens.ChannelText(T, l.Channel)</td>
<td class="sm">@l.Recipients</td>
<td class="num">@l.ItemCount</td>
<td class="num">@T.Money(l.OverdueAmount)</td>
<td class="num">@LedgerScreens.AmountText(T, l.Interest)</td>
<td><KhBadge Tone="@(l.Status == DunningLetterStatus.Failed ? KhTone.Error : l.Status == DunningLetterStatus.Sent ? KhTone.Ok : KhTone.Info)">@T[TreasuryScreens.EnumKey(l.Status)]</KhBadge></td>
<td>@l.SentBy</td>
</tr>
}
</tbody>
</table>
}
</KhPanel>
}
<KhDialog Open="_level is not null" Title="@T["Treasury.Dunning.EditLevel"]" Icon="edit" Size="lg" OnClose="() => _level = null">
<ChildContent>
@if (_level is { } level)
{
<div class="form plain">
<KhTextBox Label="@T["Treasury.Dunning.Template"]" Name="lname" @bind-Value="level.Name" MaxLength="60" Span="8" Required="true" />
<KhNumberBox Label="@T["Treasury.Dunning.After"]" Name="ldays" Value="level.DaysAfterDue" ValueChanged="v => level.DaysAfterDue = (int)(v ?? 0)" Decimals="0" Min="1" Span="4" />
<KhSelect TValue="DunningAction" Label="@T["Treasury.Dunning.Action"]" Name="laction" Options="Actions" @bind-Value="level.Action" Span="6" />
<KhCheck Label="@T[TreasuryScreens.EnumKey(DunningChannel.Email)]" Name="lemail" Value="level.Channel.HasFlag(DunningChannel.Email)" ValueChanged="v => level.Channel = TreasuryScreens.Switch(level.Channel, DunningChannel.Email, v)" Span="2" />
<KhCheck Label="@T[TreasuryScreens.EnumKey(DunningChannel.Pec)]" Name="lpec" Value="level.Channel.HasFlag(DunningChannel.Pec)" ValueChanged="v => level.Channel = TreasuryScreens.Switch(level.Channel, DunningChannel.Pec, v)" Span="2" />
<KhCheck Label="@T[TreasuryScreens.EnumKey(DunningChannel.Letter)]" Name="lletter" Value="level.Channel.HasFlag(DunningChannel.Letter)" ValueChanged="v => level.Channel = TreasuryScreens.Switch(level.Channel, DunningChannel.Letter, v)" Span="2" />
<KhCheck Label="@T["Treasury.Dunning.ChargeInterest"]" Name="linterest" @bind-Value="level.ChargeInterest" Span="6" />
<KhCheck Label="@T["Treasury.Dunning.Automatic"]" Name="lauto" @bind-Value="level.Automatic" Span="6" />
<KhTextBox Label="@T["Treasury.Dunning.Subject"]" Name="lsubject" @bind-Value="level.Subject" MaxLength="200" Span="12" Required="true" />
<KhTextArea Label="@T["Treasury.Dunning.Body"]" Name="lbody" @bind-Value="level.Body" Rows="10" Span="12" />
</div>
<p class="muted sm">@T["Treasury.Dunning.Placeholders"]</p>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _level = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveLevelAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
</FinanceGuard>
@code {
private string _tab = "proposal";
private IReadOnlyList<DunningProposal> _proposal = [];
private IReadOnlyList<DunningLevel> _levels = [];
private IReadOnlyList<DunningLetterRow> _history = [];
private readonly HashSet<long> _included = [];
private DunningLevel? _level;
private bool _busy;
private bool CanWrite => Session.Permissions.Allows(TreasuryPermissions.ScheduleWrite);
private IReadOnlyList<KhTabItem> 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<KhOption<DunningAction>> Actions => TreasuryScreens.Choices<DunningAction>(T);
private IReadOnlyList<KhStat> 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"]),
];
}
}
/// <inheritdoc />
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<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -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)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message">
<KhIcon Name="building" Class="lg" />
<h1>@T["Treasury.NoCompany"]</h1>
</div>
}
else if (!Session.Licenses.IsModuleActive(ModuleCodes.Finance))
{
<div class="kh-message">
<KhIcon Name="key" Class="lg" />
<h1>@T["Treasury.NoModule.Title"]</h1>
<p class="lead">@T["Treasury.NoModule.Lead"]</p>
</div>
}
else if (!Session.Permissions.Allows(Permission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
<a class="btn" href="./">@T["Common.BackHome"]</a>
</div>
}
else
{
@ChildContent
}
@code {
private bool _loaded;
/// <summary>The permission the page needs.</summary>
[Parameter, EditorRequired]
public string Permission { get; set; } = string.Empty;
/// <summary>The page.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>Whether the page may load its data: company, licence and permission.</summary>
/// <param name="session">The session.</param>
/// <param name="permission">The permission.</param>
/// <returns>True when it may.</returns>
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);
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_loaded = true;
}
}
@@ -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. *@
<KhPageTitle Text="@T["Treasury.Mandates.Title"]" Icon="file-check" />
<FinanceGuard Permission="@TreasuryPermissions.ScheduleRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@TreasuryScreens.BasePath">@T["Shell.Menu.Finance"]</a> / @T["Treasury.Mandates.Title"]</div>
<h1>@T["Treasury.Mandates.Heading"]</h1>
<div class="sub">@T["Treasury.Mandates.Hint"]</div>
</div>
<div class="grow"></div>
@if (CanWrite)
{
<div class="toolbar">
<button type="button" class="btn primary" @onclick="() => OpenEdit(null)"><KhIcon Name="plus" /> @T["Treasury.Mandates.New"]</button>
</div>
}
</div>
<KhPanel Tight="true">
@if (_rows.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Mandates.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Treasury.Mandates.Title"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Customer"]</th>
<th scope="col">@T["Treasury.Mandates.Reference"]</th>
<th scope="col">@T["Treasury.Mandates.Signed"]</th>
<th scope="col">@T["Treasury.Mandates.Scheme"]</th>
<th scope="col">@T["Treasury.Fields.Iban"]</th>
<th scope="col">@T["Treasury.Mandates.LastCollection"]</th>
<th scope="col">@T["Treasury.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in _rows)
{
var m = row.Mandate;
<tr>
<td><b>@row.PartyName</b> <span class="muted sm">@row.PartyCode</span></td>
<td class="code">@m.Reference</td>
<td>@T.Date(m.SignatureDate)</td>
<td>@T[TreasuryScreens.EnumKey(m.Scheme)] @(m.OneOff ? "· " + T["Treasury.Mandates.OneOff"] : null)</td>
<td class="code">@m.Iban</td>
<td>@(m.LastCollectionDate is { } last ? T.Date(last) : T["Treasury.Mandates.First"])</td>
<td><KhBadge Tone="@(m.Revoked ? KhTone.Error : KhTone.Ok)">@T[m.Revoked ? "Treasury.Mandates.Revoked" : "Treasury.Mandates.Active"]</KhBadge></td>
<td class="kh-acts">
@if (CanWrite)
{
<KhIconButton Icon="edit" Text="@T["Treasury.Mandates.Edit"]" OnClick="() => OpenEdit(row)" />
<KhIconButton Icon="@(m.Revoked ? "undo" : "slash")" Text="@T[m.Revoked ? "Treasury.Mandates.Restore" : "Treasury.Mandates.Revoke"]" Disabled="_busy" OnClick="() => RevokeAsync(row)" />
<KhIconButton Icon="trash" Text="@T["Treasury.Mandates.Delete"]" Danger="true" Disabled="_busy" OnClick="() => DeleteAsync(row)" />
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
<KhDialog Open="_editOpen" Title="@T[_editId is null ? "Treasury.Mandates.New" : "Treasury.Mandates.Edit"]" Icon="file-check" OnClose="() => _editOpen = false">
<ChildContent>
<div class="form plain">
<KhHotlink TItem="PartyRow" Label="@T["Treasury.Fields.Customer"]" Name="mparty" @bind-Value="_party" Span="12" Required="true"
Search="SearchPartiesAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" />
<KhTextBox Label="@T["Treasury.Mandates.Reference"]" Name="mref" @bind-Value="_reference" MaxLength="35" Mono="true" Span="6" Required="true" />
<KhDateBox Label="@T["Treasury.Mandates.Signed"]" Name="msigned" @bind-Value="_signed" Span="6" Required="true" />
<KhSelect TValue="SddScheme" Label="@T["Treasury.Mandates.Scheme"]" Name="mscheme" Options="Schemes" @bind-Value="_scheme" Span="6" />
<KhCheck Label="@T["Treasury.Mandates.OneOff"]" Name="moneoff" @bind-Value="_oneOff" Span="6" />
<KhTextBox Label="@T["Treasury.Fields.Iban"]" Name="miban" @bind-Value="_iban" MaxLength="34" Mono="true" Span="8" Required="true" />
<KhTextBox Label="@T["Treasury.Fields.Bic"]" Name="mbic" @bind-Value="_bic" MaxLength="11" Mono="true" Span="4" />
<KhTextBox Label="@T["Treasury.Fields.Notes"]" Name="mnotes" @bind-Value="_notes" MaxLength="200" Span="12" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _editOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _party is null || _signed is null)" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
</FinanceGuard>
@code {
private IReadOnlyList<MandateRow> _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<KhOption<SddScheme>> Schemes => TreasuryScreens.Choices<SddScheme>(T);
/// <inheritdoc />
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<IReadOnlyList<PartyRow>> 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<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -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. *@
<KhDialog Open="Open" Title="@T[Receipt ? "Treasury.Payment.NewReceipt" : "Treasury.Payment.NewPayment"]" Icon="euro" Size="lg" OnClose="CloseAsync">
<ChildContent>
<div class="form plain">
<KhTextBox Label="@T[Receipt ? "Treasury.Fields.Customer" : "Treasury.Fields.Supplier"]" Name="payparty" Value="@PartyName" ReadOnly="true" Span="6" />
<KhDateBox Label="@T["Treasury.Fields.Date"]" Name="paydate" @bind-Value="_date" Required="true" Span="3" />
<KhTextBox Label="@T["Treasury.Fields.Amount"]" Name="payamount" Value="@T.Money(Total)" ReadOnly="true" Span="3" />
<KhSelect TValue="long?" Label="@T["Treasury.Fields.Method"]" Name="paymethod" Options="Methods" Empty="—" @bind-Value="_methodId" Span="4" />
<KhSelect TValue="long?" Label="@T["Treasury.Fields.Bank"]" Name="paybank" Options="Banks" Empty="@T["Treasury.Payment.Cash"]" @bind-Value="_bankId" Span="4" />
<KhTextBox Label="@T["Treasury.Fields.Reference"]" Name="payref" @bind-Value="_reference" MaxLength="60" Span="4" />
<KhNumberBox Label="@T["Treasury.Fields.Fees"]" Name="payfees" @bind-Value="_fees" Decimals="2" Min="0" Span="4" />
<KhTextBox Label="@T["Treasury.Fields.Notes"]" Name="paynotes" @bind-Value="_notes" MaxLength="200" Span="8" />
</div>
<h3 class="kh-subhead">@T["Treasury.Payment.Items"]</h3>
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Treasury.Payment.Items"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Document"]</th>
<th scope="col">@T["Treasury.Fields.Installment"]</th>
<th scope="col">@T["Treasury.Fields.DueDate"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Residual"]</th>
<th scope="col" class="num">@T[Receipt ? "Treasury.Payment.Collected" : "Treasury.Payment.Paid"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Allowance"]</th>
<th scope="col" class="num">@T["Treasury.Payment.ResidualAfter"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in _lines)
{
var item = line.Row.Item;
<tr>
<td class="code">@item.DocumentNumber</td>
<td>@item.Installment</td>
<td>@T.Date(item.DueDate)</td>
<td class="num">@T.Money(item.Residual)</td>
<td class="num"><input class="in num" aria-label="@(T["Treasury.Payment.Collected"] + " " + item.DocumentNumber)" value="@LedgerScreens.AmountText(T, line.Amount)" @onchange="e => line.Amount = LedgerScreens.ParseAmount(T, e.Value?.ToString())" style="width:120px" /></td>
<td class="num"><input class="in num" aria-label="@(T["Treasury.Fields.Allowance"] + " " + item.DocumentNumber)" value="@LedgerScreens.AmountText(T, line.Allowance)" @onchange="e => line.Allowance = LedgerScreens.ParseAmount(T, e.Value?.ToString())" style="width:100px" /></td>
<td class="num">@T.Money(item.Residual - line.Amount - line.Allowance)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="3"><b>@T["Treasury.Fields.Total"]</b></td>
<td class="num"><b>@T.Money(_lines.Sum(l => l.Row.Item.Residual))</b></td>
<td class="num"><b>@T.Money(Total)</b></td>
<td class="num"><b>@T.Money(_lines.Sum(l => l.Allowance))</b></td>
<td class="num"><b>@T.Money(_lines.Sum(l => l.Row.Item.Residual - l.Amount - l.Allowance))</b></td>
</tr>
</tfoot>
</table>
</div>
<div class="callout info">
<KhIcon Name="info" />
<span>@T.Format(Receipt ? "Treasury.Payment.EntryReceipt" : "Treasury.Payment.EntryPayment", T.Money(Total), T.Money(_lines.Sum(l => l.Allowance)))</span>
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="CloseAsync"><KhIcon Name="x" /> @T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _date is null || Total == 0m && _lines.Sum(l => l.Allowance) == 0m)" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Treasury.Payment.Save"]</button>
</Footer>
</KhDialog>
@code {
private List<Line> _lines = [];
private DateOnly? _date;
private long? _methodId;
private long? _bankId;
private string? _reference;
private decimal? _fees;
private string? _notes;
private bool _busy;
private IReadOnlyList<ScheduleRow>? _shown;
/// <summary>Whether the dialog is open.</summary>
[Parameter]
public bool Open { get; set; }
/// <summary>The items to settle, all of one party and one direction.</summary>
[Parameter]
public IReadOnlyList<ScheduleRow> Rows { get; set; } = [];
/// <summary>The payment methods and the banks.</summary>
[Parameter]
public TreasuryChoices? Choices { get; set; }
/// <summary>Closed without saving.</summary>
[Parameter]
public EventCallback OnClose { get; set; }
/// <summary>Saved.</summary>
[Parameter]
public EventCallback<Payment> 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<KhOption<long?>> Methods => TreasuryScreens.MethodChoices(Choices?.Methods ?? []);
private IReadOnlyList<KhOption<long?>> Banks => TreasuryScreens.BankChoices(Choices?.Banks ?? []);
/// <inheritdoc />
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; }
}
}
@@ -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. *@
<KhPageTitle Text="@T[Title]" Icon="euro" />
<FinanceGuard Permission="@TreasuryPermissions.PaymentRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@TreasuryScreens.BasePath">@T["Shell.Menu.Finance"]</a> / @T[Title]</div>
<h1>@T[Title]</h1>
<div class="sub">@T[Receipts ? "Treasury.Payments.ReceiptsHint" : "Treasury.Payments.PaymentsHint"]</div>
</div>
<div class="grow"></div>
<div class="toolbar">
<a class="btn primary" href="@(TreasuryScreens.BasePath + "/scadenze" + (Receipts ? string.Empty : "?vista=fornitori"))">
<KhIcon Name="plus" /> @T[Receipts ? "Treasury.Payment.NewReceipt" : "Treasury.Payment.NewPayment"]
</a>
</div>
</div>
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["Treasury.Fields.From"]" Name="from" Value="_from" ValueChanged="SetFromAsync" />
<KhDateBox Label="@T["Treasury.Fields.To"]" Name="to" Value="_to" ValueChanged="SetToAsync" />
<span class="grow"></span>
<span class="muted sm">@T.Format("Treasury.Payments.Total", _rows.Count, T.Money(_rows.Sum(r => r.Payment.Amount)))</span>
</div>
@if (_rows.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Payments.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T[Title]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Date"]</th>
<th scope="col">@T[Receipts ? "Treasury.Fields.Customer" : "Treasury.Fields.Supplier"]</th>
<th scope="col">@T["Treasury.Payments.Documents"]</th>
<th scope="col">@T["Treasury.Fields.Reference"]</th>
<th scope="col">@T["Treasury.Fields.Bank"]</th>
<th scope="col">@T["Treasury.Payments.Origin"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Amount"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Allowance"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Fees"]</th>
<th scope="col">@T["Treasury.Payments.Entry"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in _rows)
{
var p = row.Payment;
<tr>
<td>@T.Date(p.PaymentDate)</td>
<td><b>@row.PartyName</b></td>
<td class="code">@row.Documents</td>
<td>@p.Reference</td>
<td>@(row.Bank ?? T["Treasury.Payment.Cash"])</td>
<td>@T[TreasuryScreens.EnumKey(p.Origin)]</td>
<td class="num"><b>@T.Money(p.Amount)</b></td>
<td class="num">@LedgerScreens.AmountText(T, p.AllowanceAmount)</td>
<td class="num">@LedgerScreens.AmountText(T, p.Fees)</td>
<td class="code">
@if (p.GlEntryId is { } entry)
{
<a href="@LedgerScreens.EntryUrl(entry)">@row.EntryNumber</a>
}
</td>
<td class="kh-acts">
@if (CanWrite && p.Origin != PaymentOrigin.Remittance)
{
<KhIconButton Icon="undo" Text="@T["Treasury.Payments.Cancel"]" Disabled="_busy" OnClick="() => CancelAsync(row)" />
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
</KhPanel>
</FinanceGuard>
@code {
private IReadOnlyList<PaymentRow> _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);
/// <inheritdoc />
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;
}
}
}
@@ -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. *@
<KhPageTitle Text="@T["Treasury.Reconciliation.Title"]" Icon="link" />
<FinanceGuard Permission="@TreasuryPermissions.BankReconcile">
<div class="phead">
<div>
<div class="crumbs"><a href="@TreasuryScreens.BasePath">@T["Shell.Menu.Finance"]</a> / @T["Treasury.Reconciliation.Title"]</div>
<h1>@T["Treasury.Reconciliation.Title"]</h1>
</div>
</div>
<KhStrip Items="Stats" Label="@T["Treasury.Reconciliation.Title"]" />
<div class="filters kh-ledger-filters">
<KhSelect TValue="long?" Label="@T["Treasury.Fields.Bank"]" Name="rbank" Options="Banks" Value="_bankId" ValueChanged="SetBankAsync" />
<label class="btn primary kh-filebtn">
<KhIcon Name="upload" /> @T["Treasury.Reconciliation.Import"]
<InputFile OnChange="ImportAsync" accept=".xml,.txt,.csv,.cbi,.sta" disabled="@(_busy || _bankId is null)" />
</label>
<button type="button" class="btn" disabled="@(_busy || _bankId is null)" @onclick="RefreshAsync"><KhIcon Name="zap" /> @T["Treasury.Reconciliation.Auto"]</button>
<button type="button" class="btn ok" disabled="@(_busy || _bankId is null)" @onclick="ConfirmAllAsync"><KhIcon Name="check" /> @T["Treasury.Reconciliation.ConfirmAll"]</button>
<span class="grow"></span>
<KhSelect TValue="string" Label="@T["Treasury.Fields.Status"]" Name="rshow" Options="Shows" Value="_show" ValueChanged="SetShowAsync" />
</div>
<KhTabs Items="Tabs" Active="@_tab" ActiveChanged="t => _tab = t" Label="@T["Treasury.Reconciliation.Title"]" />
@if (_tab == "lines")
{
<KhPanel Tight="true">
@if (_lines.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Reconciliation.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Treasury.Reconciliation.Lines"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Date"]</th>
<th scope="col">@T["Treasury.Reconciliation.Description"]</th>
<th scope="col" class="num">@T["Treasury.Reconciliation.In"]</th>
<th scope="col" class="num">@T["Treasury.Reconciliation.Out"]</th>
<th scope="col">@T["Treasury.Fields.Status"]</th>
<th scope="col">@T["Treasury.Reconciliation.Proposal"]</th>
<th scope="col" class="num">@T["Treasury.Reconciliation.Confidence"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in _lines)
{
var l = row.Line;
<tr>
<td>@T.Date(l.BookingDate)</td>
<td class="kh-w260" title="@l.Description">@l.Description <span class="muted sm">@row.PartyName</span></td>
<td class="num">@(l.Amount > 0m ? T.Money(l.Amount) : null)</td>
<td class="num">@(l.Amount < 0m ? T.Money(-l.Amount) : null)</td>
<td><KhBadge Tone="TreasuryScreens.ToneOf(l.Status)">@T[TreasuryScreens.EnumKey(l.Status)]</KhBadge></td>
<td class="kh-w260" title="@l.Proposal">
@if (l.MatchKind != StatementMatchKind.None)
{
<span class="muted sm">@T[TreasuryScreens.EnumKey(l.MatchKind)] · </span>
}
@l.Proposal
@if (l.GlEntryId is { } entry)
{
<a class="sm" href="@LedgerScreens.EntryUrl(entry)"> @T["Treasury.Payments.Entry"]</a>
}
</td>
<td class="num">@(l.Confidence > 0 ? l.Confidence + "%" : "—")</td>
<td class="kh-acts">
@if (l.Status == StatementLineStatus.Suggested)
{
<KhIconButton Icon="check" Text="@T["Treasury.Reconciliation.Confirm"]" Primary="true" Disabled="_busy" OnClick="() => ConfirmAsync(l)" />
}
@if (l.Status is StatementLineStatus.ToMatch or StatementLineStatus.Suggested)
{
<KhIconButton Icon="list" Text="@T["Treasury.Reconciliation.MatchItems"]" Disabled="_busy" OnClick="() => OpenItemsAsync(row)" />
<KhIconButton Icon="euro" Text="@T["Treasury.Reconciliation.MatchPayment"]" Disabled="_busy" OnClick="() => OpenPaymentsAsync(row)" />
<KhIconButton Icon="book" Text="@T["Treasury.Reconciliation.Post"]" Disabled="_busy" OnClick="() => OpenPostAsync(row)" />
<KhIconButton Icon="slash" Text="@T["Treasury.Reconciliation.Ignore"]" Disabled="_busy" OnClick="() => IgnoreAsync(l)" />
}
else
{
<KhIconButton Icon="undo" Text="@T["Treasury.Reconciliation.Reset"]" Disabled="_busy" OnClick="() => ResetAsync(l)" />
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T["Treasury.Reconciliation.Footer"]</span></div>
</KhPanel>
}
else if (_tab == "rules")
{
<KhPanel Tight="true">
<Actions>
<button type="button" class="btn sm" @onclick="() => OpenRuleAsync(null)"><KhIcon Name="plus" /> @T["Treasury.Rules.New"]</button>
</Actions>
<ChildContent>
@if (_rules.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Rules.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Treasury.Rules.Title"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Rules.Name"]</th>
<th scope="col">@T["Treasury.Rules.Pattern"]</th>
<th scope="col">@T["Treasury.Rules.Direction"]</th>
<th scope="col">@T["Treasury.Rules.Account"]</th>
<th scope="col" class="num">@T["Treasury.Rules.Uses"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var rule in _rules)
{
<tr class="@(rule.Disabled ? "muted" : null)">
<td>@rule.Name</td>
<td class="code">@rule.Pattern</td>
<td>@T[TreasuryScreens.EnumKey(rule.Direction)]</td>
<td>@AccountText(rule.AccountId)</td>
<td class="num">@rule.Uses</td>
<td class="kh-acts">
<KhIconButton Icon="edit" Text="@T["Treasury.Rules.Edit"]" OnClick="() => OpenRuleAsync(rule)" />
<KhIconButton Icon="trash" Text="@T["Treasury.Rules.Delete"]" Danger="true" Disabled="_busy" OnClick="() => DeleteRuleAsync(rule)" />
</td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
</KhPanel>
}
else
{
<KhPanel Tight="true">
@if (_statements.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Reconciliation.NoStatements"]</p>
}
else
{
<table class="grid" aria-label="@T["Treasury.Reconciliation.Statements"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Reconciliation.File"]</th>
<th scope="col">@T["Treasury.Reconciliation.Format"]</th>
<th scope="col">@T["Treasury.Fields.From"]</th>
<th scope="col">@T["Treasury.Fields.To"]</th>
<th scope="col" class="num">@T["Treasury.Reconciliation.Movements"]</th>
<th scope="col" class="num">@T["Treasury.Reconciliation.Closing"]</th>
</tr>
</thead>
<tbody>
@foreach (var st in _statements)
{
<tr>
<td>@st.FileName</td>
<td>@T[TreasuryScreens.EnumKey(st.Format)]</td>
<td>@T.Date(st.FromDate)</td>
<td>@T.Date(st.ToDate)</td>
<td class="num">@st.MovementCount</td>
<td class="num">@(st.ClosingBalance is { } c ? T.Money(c) : "—")</td>
</tr>
}
</tbody>
</table>
}
</KhPanel>
}
<KhDialog Open="_itemsFor is not null" Title="@T["Treasury.Reconciliation.MatchItems"]" Icon="list" Size="lg" OnClose="() => _itemsFor = null">
<ChildContent>
@if (_itemsFor is { } target)
{
<p>@target.Line.Description · <b>@T.Money(target.Line.Amount)</b></p>
<input type="search" class="in kh-searchbox" placeholder="@T["Treasury.Schedule.Search"]" aria-label="@T["Treasury.Schedule.Search"]" @onchange="SearchItemsAsync" />
<table class="grid" aria-label="@T["Treasury.Payment.Items"]">
<tbody>
@foreach (var row in _items)
{
<tr class="@(_chosen.Contains(row.Item.Id) ? "sel" : null)">
<td class="chkcol"><input type="checkbox" aria-label="@(T["Treasury.Select"] + " " + row.Item.DocumentNumber)" checked="@_chosen.Contains(row.Item.Id)" @onchange="e => ToggleItem(row.Item.Id, e.Value is true)" /></td>
<td>@row.PartyName</td>
<td class="code">@row.Item.DocumentNumber</td>
<td>@T.Date(row.Item.DueDate)</td>
<td class="num">@T.Money(row.Item.Residual)</td>
</tr>
}
</tbody>
</table>
<p class="muted sm">@T.Format("Treasury.Reconciliation.Chosen", T.Money(_items.Where(r => _chosen.Contains(r.Item.Id)).Sum(r => r.Item.Residual)))</p>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _itemsFor = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _chosen.Count == 0)" @onclick="MatchItemsAsync"><KhIcon Name="check" /> @T["Treasury.Reconciliation.Match"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_paymentsFor is not null" Title="@T["Treasury.Reconciliation.MatchPayment"]" Icon="euro" OnClose="() => _paymentsFor = null">
<ChildContent>
@if (_paymentsFor is { } target)
{
<p>@target.Line.Description · <b>@T.Money(target.Line.Amount)</b></p>
@if (_payments.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Payments.None"]</p>
}
<table class="grid" aria-label="@T["Treasury.Reconciliation.MatchPayment"]">
<tbody>
@foreach (var p in _payments)
{
<tr>
<td>@T.Date(p.Payment.PaymentDate)</td>
<td>@p.PartyName</td>
<td>@p.Payment.Reference</td>
<td class="num">@T.Money(p.Payment.Amount + p.Payment.Fees)</td>
<td class="num"><button type="button" class="btn sm" disabled="@_busy" @onclick="() => MatchPaymentAsync(p.Payment.Id)">@T["Treasury.Reconciliation.Match"]</button></td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _paymentsFor = null">@T["Common.Close"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_postFor is not null" Title="@T["Treasury.Reconciliation.Post"]" Icon="book" OnClose="() => _postFor = null">
<ChildContent>
@if (_postFor is { } target)
{
<p>@target.Line.Description · <b>@T.Money(target.Line.Amount)</b></p>
<div class="form plain">
<KhSelect TValue="long?" Label="@T["Treasury.Rules.Account"]" Name="paccount" Options="Accounts" Empty="—" @bind-Value="_postAccount" Span="12" Required="true" />
<KhTextBox Label="@T["Treasury.Reconciliation.EntryDescription"]" Name="pdesc" @bind-Value="_postDescription" MaxLength="200" Span="12" />
<KhTextBox Label="@T["Treasury.Reconciliation.SaveRule"]" Name="prule" @bind-Value="_postRule" MaxLength="60" Hint="@T["Treasury.Reconciliation.SaveRuleHint"]" Span="12" />
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _postFor = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _postAccount is null)" @onclick="PostAsync"><KhIcon Name="check" /> @T["Treasury.Reconciliation.Post"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_ruleOpen" Title="@T["Treasury.Rules.Edit"]" Icon="zap" OnClose="() => _ruleOpen = false">
<ChildContent>
<div class="form plain">
<KhTextBox Label="@T["Treasury.Rules.Name"]" Name="rname" @bind-Value="_ruleName" MaxLength="60" Span="12" Required="true" />
<KhTextBox Label="@T["Treasury.Rules.Pattern"]" Name="rpattern" @bind-Value="_rulePattern" MaxLength="100" Mono="true" Hint="@T["Treasury.Rules.PatternHint"]" Span="8" Required="true" />
<KhSelect TValue="BankRuleDirection" Label="@T["Treasury.Rules.Direction"]" Name="rdir" Options="Directions" @bind-Value="_ruleDirection" Span="4" />
<KhSelect TValue="long?" Label="@T["Treasury.Rules.Account"]" Name="racc" Options="Accounts" Empty="—" @bind-Value="_ruleAccount" Span="12" Required="true" />
<KhTextBox Label="@T["Treasury.Reconciliation.EntryDescription"]" Name="rdesc" @bind-Value="_ruleDescription" MaxLength="200" Span="12" />
<KhCheck Label="@T["Treasury.Rules.Disabled"]" Name="rdis" @bind-Value="_ruleDisabled" Span="12" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _ruleOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _ruleAccount is null)" @onclick="SaveRuleAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
</FinanceGuard>
@code {
private string _tab = "lines";
private string _show = "open";
private long? _bankId;
private TreasuryChoices? _choices;
private BankPosition? _position;
private IReadOnlyList<StatementLineRow> _lines = [];
private IReadOnlyList<BankStatement> _statements = [];
private IReadOnlyList<BankMatchRule> _rules = [];
private IReadOnlyList<GlAccount> _accounts = [];
private bool _busy;
private StatementLineRow? _itemsFor;
private IReadOnlyList<ScheduleRow> _items = [];
private readonly HashSet<long> _chosen = [];
private StatementLineRow? _paymentsFor;
private IReadOnlyList<PaymentRow> _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<KhOption<long?>> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []);
private IReadOnlyList<KhOption<string>> Shows =>
[
new("open", T["Treasury.Reconciliation.ShowOpen"]),
new("all", T["Treasury.All"]),
];
private IReadOnlyList<KhOption<BankRuleDirection>> Directions => TreasuryScreens.Choices<BankRuleDirection>(T);
private IReadOnlyList<KhOption<long?>> Accounts => [.. _accounts.Where(a => a.Postable && !a.Disabled).Select(a => new KhOption<long?>(a.Id, a.Code + " " + a.Description))];
private IReadOnlyList<KhTabItem> 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<KhStat> 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))),
];
}
}
/// <inheritdoc />
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<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -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. *@
<KhPageTitle Text="@T["Treasury.Remittances.Title"]" Icon="layers" />
<FinanceGuard Permission="@TreasuryPermissions.ScheduleRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@TreasuryScreens.BasePath">@T["Shell.Menu.Finance"]</a> / @T["Treasury.Remittances.Title"]</div>
<h1>@T["Treasury.Remittances.Heading"]</h1>
<div class="sub">@T["Treasury.Remittances.Hint"]</div>
</div>
</div>
<KhTabs Items="Tabs" Active="@_tab" ActiveChanged="SetTabAsync" Label="@T["Treasury.Remittances.Title"]" />
@if (_tab == "new")
{
<div class="kh-remit">
<KhPanel Title="@T["Treasury.Remittances.New"]" Icon="plus">
<div class="form plain">
<KhSelect TValue="RemittanceKind" Label="@T["Treasury.Remittances.Kind"]" Name="kind" Options="Kinds" Value="_kind" ValueChanged="SetKindAsync" Span="12" />
<KhSelect TValue="long?" Label="@T["Treasury.Remittances.Bank"]" Name="bank" Options="Banks" @bind-Value="_bankId" Span="12" />
<KhDateBox Label="@T["Treasury.Remittances.PresentationDate"]" Name="presented" @bind-Value="_presentation" Span="6" Required="true" />
<KhDateBox Label="@T["Treasury.Remittances.DueUntil"]" Name="dueuntil" Value="_dueUntil" ValueChanged="SetDueUntilAsync" Span="6" Required="true" />
<KhTextBox Label="@T["Treasury.Fields.Total"]" Name="rtotal" Value="@T.Money(SelectedTotal)" ReadOnly="true" Span="6" />
<KhTextBox Label="@T["Treasury.Remittances.Effects"]" Name="rcount" Value="@_chosen.Count.ToString(T.Culture)" ReadOnly="true" Span="6" />
@if (_kind != RemittanceKind.SepaCreditTransfer)
{
<KhCheck Label="@T["Treasury.Remittances.Advance"]" Name="advance" @bind-Value="_advance" Span="12" />
}
<KhTextBox Label="@T["Treasury.Fields.Notes"]" Name="rnotes" @bind-Value="_notes" MaxLength="200" Span="12" />
</div>
<KhVSteps Items="Steps" Current="@(_chosen.Count > 0 ? 1 : 0)" Label="@T["Treasury.Remittances.New"]" />
@if (CanWrite)
{
<button type="button" class="btn primary" disabled="@(_busy || _chosen.Count == 0 || _bankId is null || _presentation is null)" @onclick="CreateAsync">
<KhIcon Name="check" /> @T["Treasury.Remittances.Create"]
</button>
}
</KhPanel>
<KhPanel Tight="true">
@if (_candidates.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Remittances.NoCandidates"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Treasury.Remittances.Candidates"]">
<thead>
<tr>
<th scope="col" class="chkcol"><span class="sr-only">@T["Treasury.Select"]</span></th>
<th scope="col">@T[_kind == RemittanceKind.SepaCreditTransfer ? "Treasury.Fields.Supplier" : "Treasury.Fields.Customer"]</th>
<th scope="col">@T["Treasury.Fields.Document"]</th>
<th scope="col">@T["Treasury.Fields.Installment"]</th>
<th scope="col">@T["Treasury.Fields.DueDate"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Amount"]</th>
<th scope="col">@T["Treasury.Remittances.PartyBank"]</th>
<th scope="col">@T["Treasury.Remittances.Check"]</th>
</tr>
</thead>
<tbody>
@foreach (var c in _candidates)
{
var item = c.Row.Item;
var late = item.DueDate < Today;
<tr class="@(!c.Ready ? "warn" : _chosen.Contains(item.Id) ? "sel" : null)">
<td class="chkcol">
<input type="checkbox" aria-label="@(T["Treasury.Select"] + " " + item.DocumentNumber)" disabled="@(!c.Ready)" checked="@_chosen.Contains(item.Id)"
@onchange="e => Toggle(item.Id, e.Value is true)" />
</td>
<td><b>@c.Row.PartyName</b></td>
<td class="code">@item.DocumentNumber</td>
<td>@item.Installment</td>
<td>@T.Date(item.DueDate)</td>
<td class="num">@T.Money(item.Residual)</td>
<td>@TreasuryScreens.ShortIban(c.Iban) @(c.Mandate is { } m ? "· " + m.Reference : null)</td>
<td>
@if (!c.Ready)
{
<KhBadge Tone="KhTone.Error">@string.Join(", ", c.Problems.Select(p => T[p]))</KhBadge>
}
else if (late)
{
<KhBadge Tone="KhTone.Warning">@T["Treasury.Remittances.Late"]</KhBadge>
}
else
{
<KhBadge Tone="KhTone.Ok">@T["Treasury.Remittances.Ok"]</KhBadge>
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T["Treasury.Remittances.Footer"]</span></div>
</KhPanel>
</div>
}
else
{
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhSelect TValue="int" Label="@T["Treasury.Fields.Year"]" Name="ryear" Options="Years" Value="_year" ValueChanged="SetYearAsync" />
</div>
@if (_list.Count == 0)
{
<p class="kh-wempty">@T["Treasury.Remittances.None"]</p>
}
else
{
<table class="grid" aria-label="@T["Treasury.Remittances.History"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Number"]</th>
<th scope="col">@T["Treasury.Remittances.Kind"]</th>
<th scope="col">@T["Treasury.Fields.Bank"]</th>
<th scope="col">@T["Treasury.Remittances.PresentationDate"]</th>
<th scope="col" class="num">@T["Treasury.Remittances.Effects"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Total"]</th>
<th scope="col">@T["Treasury.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in _list)
{
var r = row.Remittance;
<tr class="@(_open?.Row.Remittance.Id == r.Id ? "sel" : null) clickable" @onclick="() => OpenAsync(r.Id)">
<td class="code"><a href="javascript:void(0)">@TreasuryScreens.Number(r)</a></td>
<td>@T[TreasuryScreens.EnumKey(r.Kind)] @(r.Advance ? "· " + T["Treasury.Remittances.AdvanceShort"] : null)</td>
<td>@row.Bank</td>
<td>@T.Date(r.PresentationDate)</td>
<td class="num">@r.ItemCount</td>
<td class="num">@T.Money(r.TotalAmount)</td>
<td><KhBadge Tone="TreasuryScreens.ToneOf(r.Status)">@T[TreasuryScreens.EnumKey(r.Status)]</KhBadge></td>
</tr>
}
</tbody>
</table>
}
</KhPanel>
@if (_open is { } open)
{
var rem = open.Row.Remittance;
<KhPanel Title="@T.Format("Treasury.Remittances.Detail", T[TreasuryScreens.EnumKey(rem.Kind)], TreasuryScreens.Number(rem))" Icon="layers" Tight="true">
<Actions>
@if (CanWrite)
{
@if (rem.Status is RemittanceStatus.Draft or RemittanceStatus.Generated)
{
<button type="button" class="btn sm primary" disabled="@_busy" @onclick="FileAsync"><KhIcon Name="download" /> @T[rem.Kind == RemittanceKind.Riba ? "Treasury.Remittances.FileCbi" : "Treasury.Remittances.FileXml"]</button>
<button type="button" class="btn sm" disabled="@(_busy || rem.Status != RemittanceStatus.Generated)" @onclick="PresentAsync"><KhIcon Name="send" /> @T["Treasury.Remittances.Present"]</button>
<button type="button" class="btn sm" disabled="@_busy" @onclick="DeleteAsync"><KhIcon Name="trash" /> @T["Treasury.Remittances.Delete"]</button>
}
@if (rem.Status == RemittanceStatus.Presented)
{
<button type="button" class="btn sm primary" disabled="@_busy" @onclick="() => OpenCredit(rem)"><KhIcon Name="check" /> @T["Treasury.Remittances.Credit"]</button>
}
}
</Actions>
<ChildContent>
<table class="grid" aria-label="@T["Treasury.Remittances.Lines"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Party"]</th>
<th scope="col">@T["Treasury.Fields.Document"]</th>
<th scope="col">@T["Treasury.Fields.DueDate"]</th>
<th scope="col">@T["Treasury.Fields.Iban"]</th>
<th scope="col">@T["Treasury.Remittances.EndToEnd"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Amount"]</th>
<th scope="col">@T["Treasury.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var line in open.Lines)
{
var l = line.Line;
<tr>
<td>@line.PartyName</td>
<td class="code">@line.Item?.DocumentNumber</td>
<td>@T.Date(l.DueDate)</td>
<td>@TreasuryScreens.ShortIban(l.Iban) @(line.Mandate is { } m ? "· " + m : null)</td>
<td class="code">@l.EndToEndId</td>
<td class="num">@T.Money(l.Amount)</td>
<td>
<KhBadge Tone="@(l.Status == RemittanceLineStatus.Unpaid ? KhTone.Error : l.Status == RemittanceLineStatus.Paid ? KhTone.Ok : KhTone.Neutral)">@T[TreasuryScreens.EnumKey(l.Status)]</KhBadge>
@if (l.UnpaidOn is { } u)
{
<span class="muted sm"> @T.Date(u) · @T.Money(l.UnpaidFees)</span>
}
</td>
<td class="kh-acts">
@if (CanWrite && rem.Status is RemittanceStatus.Draft or RemittanceStatus.Generated)
{
<KhIconButton Icon="x" Text="@T["Treasury.Remittances.RemoveLine"]" Disabled="_busy" OnClick="() => RemoveLineAsync(l)" />
}
else if (CanWrite && rem.Kind != RemittanceKind.SepaCreditTransfer && rem.Status is RemittanceStatus.Presented or RemittanceStatus.Closed && l.Status != RemittanceLineStatus.Unpaid)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="() => OpenUnpaid(l)"><KhIcon Name="alert" /> @T["Treasury.Remittances.Unpaid"]</button>
}
</td>
</tr>
}
</tbody>
</table>
<div class="filters">
<span class="muted sm">
@(rem.FileName is { } file ? T.Format("Treasury.Remittances.FileName", file) : null)
@(rem.CreditedOn is { } credited ? " · " + T.Format("Treasury.Remittances.CreditedOn", T.Date(credited)) : null)
</span>
@if (rem.GlEntryId is { } entry)
{
<a class="btn sm" href="@LedgerScreens.EntryUrl(entry)"><KhIcon Name="book" /> @T["Treasury.Remittances.Entry"]</a>
}
@if (rem.CreditEntryId is { } credit)
{
<a class="btn sm" href="@LedgerScreens.EntryUrl(credit)"><KhIcon Name="book" /> @T["Treasury.Remittances.CreditEntry"]</a>
}
</div>
</ChildContent>
</KhPanel>
}
}
<KhDialog Open="_creditOpen" Title="@T["Treasury.Remittances.Credit"]" Icon="check" OnClose="() => _creditOpen = false">
<ChildContent>
<p>@T["Treasury.Remittances.CreditText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Treasury.Remittances.CreditedOnLabel"]" Name="credited" @bind-Value="_creditOn" Required="true" Span="6" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _creditOpen = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _creditOn is null)" @onclick="CreditAsync"><KhIcon Name="check" /> @T["Treasury.Remittances.Credit"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_unpaid is not null" Title="@T["Treasury.Remittances.Unpaid"]" Icon="alert" OnClose="() => _unpaid = null">
<ChildContent>
<p>@T["Treasury.Remittances.UnpaidText"]</p>
<div class="form plain">
<KhDateBox Label="@T["Treasury.Fields.Date"]" Name="unpaidon" @bind-Value="_unpaidOn" Required="true" Span="6" />
<KhNumberBox Label="@T["Treasury.Fields.Fees"]" Name="unpaidfees" @bind-Value="_unpaidFees" Decimals="2" Min="0" Span="6" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _unpaid = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary danger" disabled="@(_busy || _unpaidOn is null)" @onclick="UnpaidAsync"><KhIcon Name="alert" /> @T["Treasury.Remittances.Unpaid"]</button>
</Footer>
</KhDialog>
</FinanceGuard>
@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<RemittanceCandidate> _candidates = [];
private readonly HashSet<long> _chosen = [];
private TreasuryChoices? _choices;
private int _year;
private IReadOnlyList<RemittanceRow> _list = [];
private (RemittanceRow Row, IReadOnlyList<RemittanceLineRow> 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<KhTabItem> Tabs =>
[
new("new", "plus", T["Treasury.Remittances.New"]),
new("history", "list", T["Treasury.Remittances.History"]),
];
private IReadOnlyList<KhOption<RemittanceKind>> Kinds => TreasuryScreens.Choices<RemittanceKind>(T);
private IReadOnlyList<KhOption<long?>> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []);
private IReadOnlyList<KhOption<int>> Years => [.. Enumerable.Range(Today.Year - 3, 5).Select(y => new KhOption<int>(y, y.ToString(System.Globalization.CultureInfo.InvariantCulture)))];
private IReadOnlyList<KhStep> 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"]),
];
/// <inheritdoc />
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<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -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. *@
<KhPageTitle Text="@T["Treasury.Schedule.Title"]" Icon="coins" />
<FinanceGuard Permission="@TreasuryPermissions.ScheduleRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@TreasuryScreens.BasePath">@T["Shell.Menu.Finance"]</a> / @T["Treasury.Schedule.Title"]</div>
<h1>@T["Treasury.Schedule.Heading"]</h1>
<div class="sub">@T["Treasury.Schedule.Hint"]</div>
</div>
<div class="grow"></div>
@if (_result is { } r)
{
<KhBadge Tone="KhTone.Info">@T.Format("Treasury.Schedule.OpenTotal", T.Money(r.Residual))</KhBadge>
<KhBadge Tone="KhTone.Error">@T.Format("Treasury.Schedule.OverdueTotal", T.Money(r.Overdue))</KhBadge>
}
</div>
@if (_result is { } result)
{
<div class="kh-aging">
<KhTile Title="@T["Treasury.Aging.NotDue"]" Value="@T.Money(result.Aging.NotDue)" Tone="KhTone.Ok"><Detail>@T.Format("Treasury.Aging.Count", result.Aging.CountNotDue)</Detail></KhTile>
<KhTile Title="@T["Treasury.Aging.Days1To30"]" Value="@T.Money(result.Aging.Days1To30)" Tone="KhTone.Warning"><Detail>@T.Format("Treasury.Aging.Count", result.Aging.Count1To30)</Detail></KhTile>
<KhTile Title="@T["Treasury.Aging.Days31To60"]" Value="@T.Money(result.Aging.Days31To60)" Tone="KhTone.Warning"><Detail>@T.Format("Treasury.Aging.Count", result.Aging.Count31To60)</Detail></KhTile>
<KhTile Title="@T["Treasury.Aging.Days61To90"]" Value="@T.Money(result.Aging.Days61To90)" Tone="KhTone.Error"><Detail>@T.Format("Treasury.Aging.Count", result.Aging.Count61To90)</Detail></KhTile>
<KhTile Title="@T["Treasury.Aging.Over90"]" Value="@T.Money(result.Aging.Over90)" Tone="KhTone.Error"><Detail>@T.Format("Treasury.Aging.Count", result.Aging.CountOver90)</Detail></KhTile>
</div>
}
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<input type="search" class="in kh-searchbox" placeholder="@T["Treasury.Schedule.Search"]" aria-label="@T["Treasury.Schedule.Search"]" value="@_search"
@onchange="SearchAsync" />
<KhSelect TValue="ScheduleView" Label="@T["Treasury.Schedule.View"]" Name="view" Options="Views" Value="_view" ValueChanged="SetViewAsync" />
<KhSelect TValue="long?" Label="@T["Treasury.Fields.Method"]" Name="method" Options="Methods" Empty="@T["Treasury.All"]" Value="_methodId" ValueChanged="SetMethodAsync" />
<span class="grow"></span>
<div class="kh-seg" role="group" aria-label="@T["Treasury.Schedule.Direction"]">
<button type="button" class="@(_direction == OpenItemDirection.Receivable ? "on" : null)" @onclick="() => SetDirectionAsync(OpenItemDirection.Receivable)">@T["Treasury.Schedule.Customers"]</button>
<button type="button" class="@(_direction == OpenItemDirection.Payable ? "on" : null)" @onclick="() => SetDirectionAsync(OpenItemDirection.Payable)">@T["Treasury.Schedule.Suppliers"]</button>
</div>
<button type="button" class="btn" disabled="@_busy" @onclick="ExportAsync"><KhIcon Name="download" /> @T["Treasury.Export"]</button>
</div>
<div class="filters">
@if (CanPay)
{
<button type="button" class="btn primary" disabled="@(!OnePartySelected)" @onclick="OpenPayment">
<KhIcon Name="euro" /> @T[_direction == OpenItemDirection.Receivable ? "Treasury.Payment.NewReceipt" : "Treasury.Payment.NewPayment"]
</button>
}
<button type="button" class="btn" disabled="@(!OnePartySelected)" @onclick="StatementAsync"><KhIcon Name="file" /> @T["Treasury.Statement.Open"]</button>
<span class="muted sm">@T["Treasury.Schedule.SelectHint"]</span>
</div>
@if (_result is not { Rows.Count: > 0 } rows)
{
<p class="kh-wempty">@T["Treasury.Schedule.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["Treasury.Schedule.Title"]">
<thead>
<tr>
<th scope="col" class="chkcol"><span class="sr-only">@T["Treasury.Select"]</span></th>
<th scope="col">@T[_direction == OpenItemDirection.Receivable ? "Treasury.Fields.Customer" : "Treasury.Fields.Supplier"]</th>
<th scope="col">@T["Treasury.Fields.Document"]</th>
<th scope="col">@T["Treasury.Fields.Installment"]</th>
<th scope="col">@T["Treasury.Fields.DueDate"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Days"]</th>
<th scope="col">@T["Treasury.Fields.Method"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Amount"]</th>
<th scope="col" class="num">@T[_direction == OpenItemDirection.Receivable ? "Treasury.Payment.Collected" : "Treasury.Payment.Paid"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Residual"]</th>
<th scope="col">@T["Treasury.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in rows.Rows)
{
var item = row.Item;
var selectable = !item.Closed && item.Status != OpenItemStatus.InRemittance;
<tr class="@(_selected.Contains(item.Id) ? "sel" : null)">
<td class="chkcol">
@if (selectable)
{
<input type="checkbox" aria-label="@(T["Treasury.Select"] + " " + item.DocumentNumber)" checked="@_selected.Contains(item.Id)" @onchange="e => Toggle(item.Id, e.Value is true)" />
}
</td>
<td><b>@row.PartyName</b></td>
<td class="code">
@if (item.EntryId > 0)
{
<a href="@LedgerScreens.EntryUrl(item.EntryId)">@item.DocumentNumber</a>
}
else
{
@item.DocumentNumber
}
</td>
<td>@item.Installment</td>
<td>@T.Date(item.DueDate)</td>
<td class="num @(row.DaysOverdue > 0 && !item.Closed ? "neg" : null)">@(item.Closed ? null : row.DaysOverdue.ToString(T.Culture))</td>
<td>@(row.MethodDescription ?? row.Method)</td>
<td class="num">@T.Money(item.Amount)</td>
<td class="num">@T.Money(item.PaidAmount)</td>
<td class="num"><b>@T.Money(item.Residual)</b></td>
<td>
<KhBadge Tone="TreasuryScreens.ToneOf(item, Today)">@TreasuryScreens.StatusText(T, item, Today)</KhBadge>
@if (row.Remittance is { } remittance)
{
<span class="muted sm"> @remittance</span>
}
</td>
<td class="kh-acts">
@if (CanWrite && !item.Closed)
{
<KhIconButton Icon="edit" Text="@T["Treasury.Schedule.Edit"]" OnClick="() => OpenEdit(row)" />
}
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="filters">
<span class="muted sm">@T.Format("Treasury.Schedule.Footer", rows.Rows.Count, _selected.Count, T.Money(SelectedRows.Sum(r => r.Item.Residual)))</span>
</div>
}
</KhPanel>
<PaymentDialog Open="_paymentOpen" Rows="_paymentRows" Choices="_choices" OnClose="() => _paymentOpen = false" OnSaved="PaidAsync" />
<KhDialog Open="_edit is not null" Title="@T["Treasury.Schedule.Edit"]" Icon="edit" OnClose="() => _edit = null">
<ChildContent>
@if (_edit is { } edit)
{
<p>@T.Format("Treasury.Schedule.EditText", edit.Item.DocumentNumber ?? string.Empty, edit.Item.Installment, edit.PartyName)</p>
<div class="form plain">
<KhDateBox Label="@T["Treasury.Fields.DueDate"]" Name="editdue" @bind-Value="_editDue" Required="true" Span="6" />
<KhSelect TValue="long?" Label="@T["Treasury.Fields.Method"]" Name="editmethod" Options="Methods" Empty="—" @bind-Value="_editMethod" Span="6" />
<KhSelect TValue="long?" Label="@T["Treasury.Fields.Bank"]" Name="editbank" Options="Banks" Empty="—" @bind-Value="_editBank" Span="6" />
<KhCheck Label="@T["Treasury.Schedule.Disputed"]" Name="editdisputed" @bind-Value="_editDisputed" Span="6" />
<KhTextArea Label="@T["Treasury.Fields.Notes"]" Name="editnotes" @bind-Value="_editNotes" MaxLength="200" Rows="2" Span="12" />
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _edit = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || _editDue is null)" @onclick="SaveEditAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_statement is not null" Title="@T["Treasury.Statement.Title"]" Icon="file" Size="lg" OnClose="() => _statement = null">
<ChildContent>
@if (_statement is { } st)
{
<p><b>@st.Party.Name</b> · @T.Format("Treasury.Statement.At", T.Date(st.Day))</p>
<div class="kh-aging">
<KhTile Title="@T["Treasury.Fields.Residual"]" Value="@T.Money(st.Residual)" />
<KhTile Title="@T["Treasury.Schedule.Overdue"]" Value="@T.Money(st.Overdue)" Tone="KhTone.Error" />
<KhTile Title="@T["Treasury.Statement.Interest"]" Value="@T.Money(st.Interest)" Tone="KhTone.Warning" />
</div>
<table class="grid" aria-label="@T["Treasury.Statement.Title"]">
<thead>
<tr>
<th scope="col">@T["Treasury.Fields.Document"]</th>
<th scope="col">@T["Treasury.Fields.DueDate"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Amount"]</th>
<th scope="col" class="num">@T["Treasury.Fields.Residual"]</th>
<th scope="col">@T["Treasury.Fields.Status"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in st.Items)
{
<tr>
<td class="code">@row.Item.DocumentNumber @(row.Item.Installment > 1 ? "· " + row.Item.Installment : null)</td>
<td>@T.Date(row.Item.DueDate)</td>
<td class="num">@T.Money(row.Item.Amount)</td>
<td class="num">@T.Money(row.Item.Residual)</td>
<td><KhBadge Tone="TreasuryScreens.ToneOf(row.Item, st.Day)">@TreasuryScreens.StatusText(T, row.Item, st.Day)</KhBadge></td>
</tr>
}
</tbody>
</table>
@if (st.Payments.Count > 0)
{
<h3 class="kh-subhead">@T["Treasury.Statement.Payments"]</h3>
<table class="grid" aria-label="@T["Treasury.Statement.Payments"]">
<tbody>
@foreach (var p in st.Payments)
{
<tr>
<td>@T.Date(p.PaymentDate)</td>
<td>@p.Reference</td>
<td class="num">@T.Money(p.Amount)</td>
</tr>
}
</tbody>
</table>
}
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _statement = null">@T["Common.Close"]</button>
</Footer>
</KhDialog>
</FinanceGuard>
@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<long> _selected = [];
private bool _busy;
private bool _paymentOpen;
private IReadOnlyList<ScheduleRow> _paymentRows = [];
private ScheduleRow? _edit;
private DateOnly? _editDue;
private long? _editMethod;
private long? _editBank;
private bool _editDisputed;
private string? _editNotes;
private PartyStatement? _statement;
/// <summary>The direction asked by the address (?fornitori).</summary>
[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<ScheduleRow> 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<KhOption<ScheduleView>> Views => TreasuryScreens.Choices<ScheduleView>(T);
private IReadOnlyList<KhOption<long?>> Methods => TreasuryScreens.MethodChoices(_choices?.Methods ?? []);
private IReadOnlyList<KhOption<long?>> Banks => TreasuryScreens.BankChoices(_choices?.Banks ?? []);
/// <inheritdoc />
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<Actor, string, Task> action)
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_busy = true;
try
{
await action(actor, company);
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, T["Treasury.NotDone"], TreasuryScreens.Errors(T, ex));
}
finally
{
_busy = false;
}
}
}
@@ -164,6 +164,16 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Ledger.RecurringEntryService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.Ledger.RecurringEntriesJob>();
// The schedule and the treasury (ADR 0038): collections, remittances, reconciliation, reminders, cash flow.
services.AddSingleton<Khaemhat.Application.Treasury.ScheduleService>();
services.AddSingleton<Khaemhat.Application.Treasury.PaymentService>();
services.AddSingleton<Khaemhat.Application.Treasury.RemittanceService>();
services.AddSingleton<Khaemhat.Application.Treasury.MandateService>();
services.AddSingleton<Khaemhat.Application.Treasury.BankReconciliationService>();
services.AddSingleton<Khaemhat.Application.Treasury.DunningService>();
services.AddSingleton<Khaemhat.Application.Treasury.CashFlowService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.Treasury.DunningJob>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
@@ -199,6 +209,8 @@ internal static class KhaemhatServices
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoPurchasesSeeder>());
services.AddSingleton<DemoLedgerSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoLedgerSeeder>());
services.AddSingleton<DemoTreasurySeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoTreasurySeeder>());
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
@@ -232,6 +244,9 @@ internal static class KhaemhatServices
services.AddSingleton<JobRunFeedSource>();
services.AddSingleton<ITodoSource>(sp => sp.GetRequiredService<JobRunFeedSource>());
services.AddSingleton<IDoneSource>(sp => sp.GetRequiredService<JobRunFeedSource>());
services.AddSingleton<Khaemhat.Application.Treasury.TreasuryFeedSource>();
services.AddSingleton<ITodoSource>(sp => sp.GetRequiredService<Khaemhat.Application.Treasury.TreasuryFeedSource>());
services.AddSingleton<IDeadlineSource>(sp => sp.GetRequiredService<Khaemhat.Application.Treasury.TreasuryFeedSource>());
services.AddSingleton<SystemStatusService>();
services.AddSingleton<TodoAggregator>();
services.AddSingleton<DoneAggregator>();
+1
View File
@@ -134,6 +134,7 @@ public static class SeedCommand
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoLedgerSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService<DemoTreasurySeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
@@ -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": {
+13 -2
View File
@@ -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": {
+7 -3
View File
@@ -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",
@@ -252,6 +252,7 @@
"SiaCode": "Codice SIA",
"CucCode": "Codice CUC",
"AccountCode": "Conto contabile",
"CreditorId": "Identificativo creditore SEPA",
"IsDefault": "Predefinito",
"Symbol": "Simbolo",
"Decimals": "Decimali",
@@ -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."
}
}
}
+5 -4
View File
@@ -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",
+1
View File
@@ -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" },
],
},
@@ -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;
/// <summary>What the screens of the schedule and the treasury share (SPEC §11.8, mockups 053-057): addresses, texts and tones.</summary>
public static class TreasuryScreens
{
/// <summary>The address of the area.</summary>
public const string BasePath = "/scadenzario";
/// <summary>The text of the channels of a reminder level: they are flags, so "e-mail + PEC".</summary>
/// <param name="texts">The texts.</param>
/// <param name="channel">The channels.</param>
/// <returns>The text.</returns>
public static string ChannelText(ITexts texts, DunningChannel channel)
{
ArgumentNullException.ThrowIfNull(texts);
var parts = Enum.GetValues<DunningChannel>().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);
}
/// <summary>The channels with one of them switched on or off.</summary>
/// <param name="channel">The channels.</param>
/// <param name="flag">The channel to switch.</param>
/// <param name="on">Whether it is on.</param>
/// <returns>The channels.</returns>
public static DunningChannel Switch(DunningChannel channel, DunningChannel flag, bool on) => on ? channel | flag : channel & ~flag;
/// <summary>The key of the text of an enum value.</summary>
/// <param name="value">The value.</param>
/// <returns>The key.</returns>
public static string EnumKey(Enum value)
{
ArgumentNullException.ThrowIfNull(value);
return "Treasury.Enums." + value.GetType().Name + "." + value;
}
/// <summary>The choices of an enum.</summary>
/// <typeparam name="TEnum">The enum.</typeparam>
/// <param name="texts">The texts.</param>
/// <returns>The choices in declaration order.</returns>
public static IReadOnlyList<KhOption<TEnum>> Choices<TEnum>(ITexts texts)
where TEnum : struct, Enum
{
ArgumentNullException.ThrowIfNull(texts);
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<TEnum>(v, texts[EnumKey(v)]))];
}
/// <summary>The text of the errors of a refused operation.</summary>
/// <param name="texts">The texts.</param>
/// <param name="exception">The refusal.</param>
/// <returns>The messages.</returns>
public static string Errors(ITexts texts, ValidationFailedException exception) => LedgerScreens.Errors(texts, exception);
/// <summary>The tone of the state of an item; an open item past due is an error.</summary>
/// <param name="item">The item.</param>
/// <param name="today">Today.</param>
/// <returns>The tone.</returns>
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,
};
}
/// <summary>The text of the state of an item: overdue and due soon are told apart from open.</summary>
/// <param name="texts">The texts.</param>
/// <param name="item">The item.</param>
/// <param name="today">Today.</param>
/// <returns>The text.</returns>
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;
}
/// <summary>The tone of the state of a remittance.</summary>
/// <param name="status">The state.</param>
/// <returns>The tone.</returns>
public static KhTone ToneOf(RemittanceStatus status) => status switch
{
RemittanceStatus.Draft => KhTone.Warning,
RemittanceStatus.Generated => KhTone.Info,
RemittanceStatus.Presented => KhTone.Accent,
_ => KhTone.Ok,
};
/// <summary>The tone of the state of a movement of the bank.</summary>
/// <param name="status">The state.</param>
/// <returns>The tone.</returns>
public static KhTone ToneOf(StatementLineStatus status) => status switch
{
StatementLineStatus.Matched => KhTone.Ok,
StatementLineStatus.Suggested => KhTone.Info,
StatementLineStatus.Ignored => KhTone.Neutral,
_ => KhTone.Warning,
};
/// <summary>A number of a remittance as the screens show it.</summary>
/// <param name="remittance">The remittance.</param>
/// <returns>The text, year/number.</returns>
public static string Number(Remittance remittance)
{
ArgumentNullException.ThrowIfNull(remittance);
return remittance.Year.ToString(CultureInfo.InvariantCulture) + "/" + remittance.Number.ToString("000", CultureInfo.InvariantCulture);
}
/// <summary>An IBAN shortened for a grid: country, check digits and the last four characters.</summary>
/// <param name="iban">The IBAN.</param>
/// <returns>The short text.</returns>
public static string ShortIban(string? iban) =>
string.IsNullOrEmpty(iban) || iban.Length < 10 ? iban ?? string.Empty : iban[..4] + "…" + iban[^4..];
/// <summary>The choices of the bank accounts.</summary>
/// <param name="banks">The bank accounts.</param>
/// <returns>The choices, code and name.</returns>
public static IReadOnlyList<KhOption<long?>> BankChoices(IEnumerable<BankAccount> banks) =>
[.. (banks ?? []).Select(b => new KhOption<long?>(b.Id, b.Code + " · " + (b.BankName ?? b.Description)))];
/// <summary>The choices of the payment methods.</summary>
/// <param name="methods">The payment methods.</param>
/// <returns>The choices, description and code of the e-invoice.</returns>
public static IReadOnlyList<KhOption<long?>> MethodChoices(IEnumerable<PaymentMethod> methods) =>
[.. (methods ?? []).Select(m => new KhOption<long?>(m.Id, m.Description + " (" + m.EInvoiceCode + ")"))];
}
+21
View File
@@ -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); } }
@@ -8,4 +8,9 @@
<ProjectReference Include="../../src/Khaemhat.Core/Khaemhat.Core.csproj" />
</ItemGroup>
<!-- Hand-written subsets of the ISO 20022 schemas the SEPA files are validated against (no download). -->
<ItemGroup>
<None Include="Treasury\Schemas\*.xsd" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -0,0 +1,185 @@
using System.Text;
using Khaemhat.Core.Treasury;
namespace Khaemhat.Core.Tests.Treasury;
/// <summary>ISO 20022 <c>camt.053</c> statements (issue #71), read whatever the version of the namespace.</summary>
[TestClass]
public sealed class Camt053ReaderTests
{
private const string Sample = """
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08">
<BkToCstmrStmt>
<GrpHdr><MsgId>STMT-1</MsgId><CreDtTm>2026-11-01T06:00:00</CreDtTm></GrpHdr>
<Stmt>
<Id>2026-10</Id>
<CreDtTm>2026-11-01T06:00:00</CreDtTm>
<FrToDt><FrDtTm>2026-10-01T00:00:00</FrDtTm><ToDtTm>2026-10-31T23:59:59</ToDtTm></FrToDt>
<Acct><Id><IBAN>IT60X0542811101000000123456</IBAN></Id><Ccy>EUR</Ccy></Acct>
<Bal>
<Tp><CdOrPrtry><Cd>OPBD</Cd></CdOrPrtry></Tp>
<Amt Ccy="EUR">1000.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-09-30</Dt></Dt>
</Bal>
<Bal>
<Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp>
<Amt Ccy="EUR">1950.50</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-10-31</Dt></Dt>
</Bal>
<Ntry>
<Amt Ccy="EUR">1220.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
<BookgDt><Dt>2026-10-05</Dt></BookgDt><ValDt><Dt>2026-10-06</Dt></ValDt>
<AcctSvcrRef>CRO-0001</AcctSvcrRef>
<BkTxCd><Domn><Cd>PMNT</Cd><Fmly><Cd>RCDT</Cd><SubFmlyCd>ESCT</SubFmlyCd></Fmly></Domn></BkTxCd>
<NtryDtls><TxDtls>
<Refs><EndToEndId>E2E-AAA</EndToEndId></Refs>
<RltdPties>
<Dbtr><Pty><Nm>Cliente Uno S.p.A.</Nm></Pty></Dbtr>
<DbtrAcct><Id><IBAN>IT63A0200801600000101234567</IBAN></Id></DbtrAcct>
</RltdPties>
<RmtInf><Ustrd>Saldo FT 2026/388</Ustrd><Ustrd>e FT 2026/390</Ustrd></RmtInf>
</TxDtls></NtryDtls>
</Ntry>
<Ntry>
<Amt Ccy="EUR">30.50</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
<BookgDt><DtTm>2026-10-10T10:15:00+02:00</DtTm></BookgDt>
<BkTxCd><Prtry><Cd>48</Cd></Prtry></BkTxCd>
<NtryDtls><TxDtls><Refs><EndToEndId>E2E-BBB</EndToEndId></Refs></TxDtls></NtryDtls>
<AddtlNtryInf>Bonifico da
Cliente Due</AddtlNtryInf>
</Ntry>
<Ntry>
<Amt Ccy="EUR">300.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
<BookgDt><Dt>2026-10-20</Dt></BookgDt><ValDt><Dt>2026-10-20</Dt></ValDt>
<NtryDtls><TxDtls>
<RltdPties>
<Dbtr><Pty><Nm>Officine Balbo</Nm></Pty></Dbtr>
<Cdtr><Pty><Nm>Fornitore Tre</Nm></Pty></Cdtr>
<CdtrAcct><Id><IBAN>DE89 3704 0044 0532 0130 00</IBAN></Id></CdtrAcct>
</RltdPties>
<RmtInf><Ustrd>Pagamento fattura 77</Ustrd></RmtInf>
</TxDtls></NtryDtls>
</Ntry>
<Ntry>
<Amt Ccy="EUR">9.99</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>PDNG</Cd></Sts>
<BookgDt><Dt>2026-10-31</Dt></BookgDt>
</Ntry>
</Stmt>
</BkToCstmrStmt>
</Document>
""";
// The 2009 version: plain status, parties without Pty, PRCD as opening, no period.
private const string Version02 = """
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02">
<BkToCstmrStmt>
<GrpHdr><MsgId>OLD</MsgId><CreDtTm>2026-11-01T06:00:00</CreDtTm></GrpHdr>
<Stmt>
<Id>1</Id>
<Acct><Id><IBAN>IT60X0542811101000000123456</IBAN></Id></Acct>
<Bal><Tp><CdOrPrtry><Cd>PRCD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">50.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Dt><Dt>2026-10-31</Dt></Dt></Bal>
<Bal><Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">150.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-11-03</Dt></Dt></Bal>
<Ntry>
<Amt Ccy="EUR">200.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts>BOOK</Sts>
<BookgDt><Dt>2026-11-02</Dt></BookgDt>
<NtryDtls><TxDtls><RltdPties><Dbtr><Nm>Cliente Vecchio</Nm></Dbtr></RltdPties></TxDtls></NtryDtls>
<AddtlNtryInf>Accredito</AddtlNtryInf>
</Ntry>
<Ntry>
<Amt Ccy="EUR">1.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts>BOOK</Sts>
<BookgDt><Dt>2026-11-03</Dt></BookgDt>
</Ntry>
</Stmt>
</BkToCstmrStmt>
</Document>
""";
[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("<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.09\"/>")));
}
[TestMethod]
public void Read_RefusesBrokenOrForeignXml_AndDtds()
{
Assert.ThrowsExactly<BankFileException>(() => Read("<Document><BkToCstmrStmt>"));
Assert.ThrowsExactly<BankFileException>(() => Read("<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.09\"><CstmrCdtTrfInitn/></Document>"));
Assert.ThrowsExactly<BankFileException>(() => Read("<?xml version=\"1.0\"?><!DOCTYPE d [<!ENTITY x \"y\">]><Document><BkToCstmrStmt><Stmt/></BkToCstmrStmt></Document>"));
Assert.ThrowsExactly<BankFileException>(() => Read(Sample.Replace("<Amt Ccy=\"EUR\">30.50</Amt>", "<Amt Ccy=\"EUR\">abc</Amt>", StringComparison.Ordinal)));
}
[TestMethod]
public void Read_TwoStatementsOfTwoAccounts_IsRefused()
{
var stmt = Sample[Sample.IndexOf("<Stmt>", StringComparison.Ordinal)..(Sample.IndexOf("</Stmt>", StringComparison.Ordinal) + 7)];
var other = stmt.Replace("IT60X0542811101000000123456", "DE89370400440532013000", StringComparison.Ordinal);
Assert.ThrowsExactly<BankFileException>(() => Read(Sample.Replace("</Stmt>", "</Stmt>" + other, StringComparison.Ordinal)));
}
private static StatementFile Read(string xml)
{
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
return Camt053Reader.Read(stream);
}
}
@@ -0,0 +1,184 @@
using System.Text;
using Khaemhat.Core.Treasury;
namespace Khaemhat.Core.Tests.Treasury;
/// <summary>CSV exports of home banking (issue #71): layouts, Italian numbers, encodings and the guess of the layout.</summary>
[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<BankFileException>(() => 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<BankFileException>(() => Read("h\n01/10/2026;;a;uno;\n", SignedLayout));
StringAssert.Contains(badAmount.Message, "Row 2");
var noAmount = Assert.ThrowsExactly<BankFileException>(() => Read("h\n01/10/2026;;a;;\n", SignedLayout));
StringAssert.Contains(noAmount.Message, "Row 2");
Assert.ThrowsExactly<BankFileException>(() => 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<FormatException>(() => 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);
}
}
@@ -0,0 +1,368 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
pain.001.001.09 (CustomerCreditTransferInitiationV09) - HAND-WRITTEN SUBSET.
This is not the official ISO 20022 schema: it reproduces, from the published message definition, the elements,
their order, types and facets for the part Khaemhat writes (SepaXmlWriter.CreditTransfer), with the official type
names and target namespace. Elements Khaemhat never writes are left out. Replace this file with the official
pain.001.001.09.xsd when it is available in the repository; the tests must keep passing against it.
-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"
targetNamespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"
elementFormDefault="qualified">
<xs:element name="Document" type="Document" />
<xs:complexType name="Document">
<xs:sequence>
<xs:element name="CstmrCdtTrfInitn" type="CustomerCreditTransferInitiationV09" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="CustomerCreditTransferInitiationV09">
<xs:sequence>
<xs:element name="GrpHdr" type="GroupHeader85" />
<xs:element name="PmtInf" type="PaymentInstruction30" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GroupHeader85">
<xs:sequence>
<xs:element name="MsgId" type="Max35Text" />
<xs:element name="CreDtTm" type="ISODateTime" />
<xs:element name="NbOfTxs" type="Max15NumericText" />
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
<xs:element name="InitgPty" type="PartyIdentification135" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PaymentInstruction30">
<xs:sequence>
<xs:element name="PmtInfId" type="Max35Text" />
<xs:element name="PmtMtd" type="PaymentMethod3Code" />
<xs:element name="BtchBookg" type="BatchBookingIndicator" minOccurs="0" />
<xs:element name="NbOfTxs" type="Max15NumericText" minOccurs="0" />
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
<xs:element name="PmtTpInf" type="PaymentTypeInformation26" minOccurs="0" />
<xs:element name="ReqdExctnDt" type="DateAndDateTime2Choice" />
<xs:element name="Dbtr" type="PartyIdentification135" />
<xs:element name="DbtrAcct" type="CashAccount38" />
<xs:element name="DbtrAgt" type="BranchAndFinancialInstitutionIdentification6" />
<xs:element name="ChrgBr" type="ChargeBearerType1Code" minOccurs="0" />
<xs:element name="CdtTrfTxInf" type="CreditTransferTransaction34" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PaymentTypeInformation26">
<xs:sequence>
<xs:element name="SvcLvl" type="ServiceLevel8Choice" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="LclInstrm" type="LocalInstrument2Choice" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="CreditTransferTransaction34">
<xs:sequence>
<xs:element name="PmtId" type="PaymentIdentification6" />
<xs:element name="Amt" type="AmountType4Choice" />
<xs:element name="CdtrAgt" type="BranchAndFinancialInstitutionIdentification6" minOccurs="0" />
<xs:element name="Cdtr" type="PartyIdentification135" minOccurs="0" />
<xs:element name="CdtrAcct" type="CashAccount38" minOccurs="0" />
<xs:element name="RmtInf" type="RemittanceInformation16" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PaymentIdentification6">
<xs:sequence>
<xs:element name="InstrId" type="Max35Text" minOccurs="0" />
<xs:element name="EndToEndId" type="Max35Text" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="AmountType4Choice">
<xs:choice>
<xs:element name="InstdAmt" type="ActiveOrHistoricCurrencyAndAmount" />
</xs:choice>
</xs:complexType>
<xs:complexType name="DateAndDateTime2Choice">
<xs:choice>
<xs:element name="Dt" type="ISODate" />
<xs:element name="DtTm" type="ISODateTime" />
</xs:choice>
</xs:complexType>
<xs:complexType name="PartyIdentification135">
<xs:sequence>
<xs:element name="Nm" type="Max140Text" minOccurs="0" />
<xs:element name="PstlAdr" type="PostalAddress24" minOccurs="0" />
<xs:element name="Id" type="Party38Choice" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PostalAddress24">
<xs:sequence>
<xs:element name="StrtNm" type="Max70Text" minOccurs="0" />
<xs:element name="BldgNb" type="Max16Text" minOccurs="0" />
<xs:element name="PstCd" type="Max16Text" minOccurs="0" />
<xs:element name="TwnNm" type="Max35Text" minOccurs="0" />
<xs:element name="CtrySubDvsn" type="Max35Text" minOccurs="0" />
<xs:element name="Ctry" type="CountryCode" minOccurs="0" />
<xs:element name="AdrLine" type="Max70Text" minOccurs="0" maxOccurs="7" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="Party38Choice">
<xs:choice>
<xs:element name="OrgId" type="OrganisationIdentification29" />
<xs:element name="PrvtId" type="PersonIdentification13" />
</xs:choice>
</xs:complexType>
<xs:complexType name="OrganisationIdentification29">
<xs:sequence>
<xs:element name="AnyBIC" type="AnyBICDec2014Identifier" minOccurs="0" />
<xs:element name="LEI" type="LEIIdentifier" minOccurs="0" />
<xs:element name="Othr" type="GenericOrganisationIdentification1" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GenericOrganisationIdentification1">
<xs:sequence>
<xs:element name="Id" type="Max35Text" />
<xs:element name="SchmeNm" type="OrganisationIdentificationSchemeName1Choice" minOccurs="0" />
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="OrganisationIdentificationSchemeName1Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalOrganisationIdentification1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="PersonIdentification13">
<xs:sequence>
<xs:element name="Othr" type="GenericPersonIdentification1" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GenericPersonIdentification1">
<xs:sequence>
<xs:element name="Id" type="Max35Text" />
<xs:element name="SchmeNm" type="PersonIdentificationSchemeName1Choice" minOccurs="0" />
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PersonIdentificationSchemeName1Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalPersonIdentification1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="CashAccount38">
<xs:sequence>
<xs:element name="Id" type="AccountIdentification4Choice" />
<xs:element name="Ccy" type="ActiveOrHistoricCurrencyCode" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="AccountIdentification4Choice">
<xs:choice>
<xs:element name="IBAN" type="IBAN2007Identifier" />
</xs:choice>
</xs:complexType>
<xs:complexType name="BranchAndFinancialInstitutionIdentification6">
<xs:sequence>
<xs:element name="FinInstnId" type="FinancialInstitutionIdentification18" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="FinancialInstitutionIdentification18">
<xs:sequence>
<xs:element name="BICFI" type="BICFIDec2014Identifier" minOccurs="0" />
<xs:element name="Othr" type="GenericFinancialIdentification1" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GenericFinancialIdentification1">
<xs:sequence>
<xs:element name="Id" type="Max35Text" />
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ServiceLevel8Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalServiceLevel1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="LocalInstrument2Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalLocalInstrument1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="RemittanceInformation16">
<xs:sequence>
<xs:element name="Ustrd" type="Max140Text" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ActiveOrHistoricCurrencyAndAmount">
<xs:simpleContent>
<xs:extension base="ActiveOrHistoricCurrencyAndAmount_SimpleType">
<xs:attribute name="Ccy" type="ActiveOrHistoricCurrencyCode" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:simpleType name="ActiveOrHistoricCurrencyAndAmount_SimpleType">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="5" />
<xs:totalDigits value="18" />
<xs:minInclusive value="0" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ActiveOrHistoricCurrencyCode">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{3,3}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="DecimalNumber">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="17" />
<xs:totalDigits value="18" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max15NumericText">
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]{1,15}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="BatchBookingIndicator">
<xs:restriction base="xs:boolean" />
</xs:simpleType>
<xs:simpleType name="PaymentMethod3Code">
<xs:restriction base="xs:string">
<xs:enumeration value="CHK" />
<xs:enumeration value="TRF" />
<xs:enumeration value="TRA" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ChargeBearerType1Code">
<xs:restriction base="xs:string">
<xs:enumeration value="DEBT" />
<xs:enumeration value="CRED" />
<xs:enumeration value="SHAR" />
<xs:enumeration value="SLEV" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="IBAN2007Identifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{2,2}[0-9]{2,2}[a-zA-Z0-9]{1,30}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="BICFIDec2014Identifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AnyBICDec2014Identifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="LEIIdentifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z0-9]{18,18}[0-9]{2,2}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="CountryCode">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{2,2}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ISODate">
<xs:restriction base="xs:date" />
</xs:simpleType>
<xs:simpleType name="ISODateTime">
<xs:restriction base="xs:dateTime" />
</xs:simpleType>
<xs:simpleType name="ExternalServiceLevel1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="4" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ExternalLocalInstrument1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="35" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ExternalOrganisationIdentification1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="4" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ExternalPersonIdentification1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="4" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max16Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="16" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max35Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="35" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max70Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="70" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max140Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="140" />
</xs:restriction>
</xs:simpleType>
</xs:schema>
@@ -0,0 +1,385 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
pain.008.001.08 (CustomerDirectDebitInitiationV08) - HAND-WRITTEN SUBSET.
This is not the official ISO 20022 schema: it reproduces, from the published message definition, the elements,
their order, types and facets for the part Khaemhat writes (SepaXmlWriter.DirectDebit), with the official type
names and target namespace. Elements Khaemhat never writes are left out. Replace this file with the official
pain.008.001.08.xsd when it is available in the repository; the tests must keep passing against it.
-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.08"
targetNamespace="urn:iso:std:iso:20022:tech:xsd:pain.008.001.08"
elementFormDefault="qualified">
<xs:element name="Document" type="Document" />
<xs:complexType name="Document">
<xs:sequence>
<xs:element name="CstmrDrctDbtInitn" type="CustomerDirectDebitInitiationV08" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="CustomerDirectDebitInitiationV08">
<xs:sequence>
<xs:element name="GrpHdr" type="GroupHeader83" />
<xs:element name="PmtInf" type="PaymentInstruction29" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GroupHeader83">
<xs:sequence>
<xs:element name="MsgId" type="Max35Text" />
<xs:element name="CreDtTm" type="ISODateTime" />
<xs:element name="NbOfTxs" type="Max15NumericText" />
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
<xs:element name="InitgPty" type="PartyIdentification135" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PaymentInstruction29">
<xs:sequence>
<xs:element name="PmtInfId" type="Max35Text" />
<xs:element name="PmtMtd" type="PaymentMethod2Code" />
<xs:element name="BtchBookg" type="BatchBookingIndicator" minOccurs="0" />
<xs:element name="NbOfTxs" type="Max15NumericText" minOccurs="0" />
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
<xs:element name="PmtTpInf" type="PaymentTypeInformation29" minOccurs="0" />
<xs:element name="ReqdColltnDt" type="ISODate" />
<xs:element name="Cdtr" type="PartyIdentification135" />
<xs:element name="CdtrAcct" type="CashAccount38" />
<xs:element name="CdtrAgt" type="BranchAndFinancialInstitutionIdentification6" />
<xs:element name="ChrgBr" type="ChargeBearerType1Code" minOccurs="0" />
<xs:element name="CdtrSchmeId" type="PartyIdentification135" minOccurs="0" />
<xs:element name="DrctDbtTxInf" type="DirectDebitTransactionInformation23" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PaymentTypeInformation29">
<xs:sequence>
<xs:element name="SvcLvl" type="ServiceLevel8Choice" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="LclInstrm" type="LocalInstrument2Choice" minOccurs="0" />
<xs:element name="SeqTp" type="SequenceType3Code" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="DirectDebitTransactionInformation23">
<xs:sequence>
<xs:element name="PmtId" type="PaymentIdentification6" />
<xs:element name="InstdAmt" type="ActiveOrHistoricCurrencyAndAmount" />
<xs:element name="DrctDbtTx" type="DirectDebitTransaction10" minOccurs="0" />
<xs:element name="DbtrAgt" type="BranchAndFinancialInstitutionIdentification6" />
<xs:element name="Dbtr" type="PartyIdentification135" />
<xs:element name="DbtrAcct" type="CashAccount38" />
<xs:element name="RmtInf" type="RemittanceInformation16" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="DirectDebitTransaction10">
<xs:sequence>
<xs:element name="MndtRltdInf" type="MandateRelatedInformation14" minOccurs="0" />
<xs:element name="CdtrSchmeId" type="PartyIdentification135" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="MandateRelatedInformation14">
<xs:sequence>
<xs:element name="MndtId" type="Max35Text" minOccurs="0" />
<xs:element name="DtOfSgntr" type="ISODate" minOccurs="0" />
<xs:element name="AmdmntInd" type="TrueFalseIndicator" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PaymentIdentification6">
<xs:sequence>
<xs:element name="InstrId" type="Max35Text" minOccurs="0" />
<xs:element name="EndToEndId" type="Max35Text" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PartyIdentification135">
<xs:sequence>
<xs:element name="Nm" type="Max140Text" minOccurs="0" />
<xs:element name="PstlAdr" type="PostalAddress24" minOccurs="0" />
<xs:element name="Id" type="Party38Choice" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PostalAddress24">
<xs:sequence>
<xs:element name="StrtNm" type="Max70Text" minOccurs="0" />
<xs:element name="BldgNb" type="Max16Text" minOccurs="0" />
<xs:element name="PstCd" type="Max16Text" minOccurs="0" />
<xs:element name="TwnNm" type="Max35Text" minOccurs="0" />
<xs:element name="CtrySubDvsn" type="Max35Text" minOccurs="0" />
<xs:element name="Ctry" type="CountryCode" minOccurs="0" />
<xs:element name="AdrLine" type="Max70Text" minOccurs="0" maxOccurs="7" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="Party38Choice">
<xs:choice>
<xs:element name="OrgId" type="OrganisationIdentification29" />
<xs:element name="PrvtId" type="PersonIdentification13" />
</xs:choice>
</xs:complexType>
<xs:complexType name="OrganisationIdentification29">
<xs:sequence>
<xs:element name="AnyBIC" type="AnyBICDec2014Identifier" minOccurs="0" />
<xs:element name="LEI" type="LEIIdentifier" minOccurs="0" />
<xs:element name="Othr" type="GenericOrganisationIdentification1" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GenericOrganisationIdentification1">
<xs:sequence>
<xs:element name="Id" type="Max35Text" />
<xs:element name="SchmeNm" type="OrganisationIdentificationSchemeName1Choice" minOccurs="0" />
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="OrganisationIdentificationSchemeName1Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalOrganisationIdentification1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="PersonIdentification13">
<xs:sequence>
<xs:element name="Othr" type="GenericPersonIdentification1" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GenericPersonIdentification1">
<xs:sequence>
<xs:element name="Id" type="Max35Text" />
<xs:element name="SchmeNm" type="PersonIdentificationSchemeName1Choice" minOccurs="0" />
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="PersonIdentificationSchemeName1Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalPersonIdentification1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="CashAccount38">
<xs:sequence>
<xs:element name="Id" type="AccountIdentification4Choice" />
<xs:element name="Ccy" type="ActiveOrHistoricCurrencyCode" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="AccountIdentification4Choice">
<xs:choice>
<xs:element name="IBAN" type="IBAN2007Identifier" />
</xs:choice>
</xs:complexType>
<xs:complexType name="BranchAndFinancialInstitutionIdentification6">
<xs:sequence>
<xs:element name="FinInstnId" type="FinancialInstitutionIdentification18" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="FinancialInstitutionIdentification18">
<xs:sequence>
<xs:element name="BICFI" type="BICFIDec2014Identifier" minOccurs="0" />
<xs:element name="Othr" type="GenericFinancialIdentification1" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="GenericFinancialIdentification1">
<xs:sequence>
<xs:element name="Id" type="Max35Text" />
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ServiceLevel8Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalServiceLevel1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="LocalInstrument2Choice">
<xs:choice>
<xs:element name="Cd" type="ExternalLocalInstrument1Code" />
<xs:element name="Prtry" type="Max35Text" />
</xs:choice>
</xs:complexType>
<xs:complexType name="RemittanceInformation16">
<xs:sequence>
<xs:element name="Ustrd" type="Max140Text" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ActiveOrHistoricCurrencyAndAmount">
<xs:simpleContent>
<xs:extension base="ActiveOrHistoricCurrencyAndAmount_SimpleType">
<xs:attribute name="Ccy" type="ActiveOrHistoricCurrencyCode" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:simpleType name="ActiveOrHistoricCurrencyAndAmount_SimpleType">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="5" />
<xs:totalDigits value="18" />
<xs:minInclusive value="0" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ActiveOrHistoricCurrencyCode">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{3,3}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="DecimalNumber">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="17" />
<xs:totalDigits value="18" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max15NumericText">
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]{1,15}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="BatchBookingIndicator">
<xs:restriction base="xs:boolean" />
</xs:simpleType>
<xs:simpleType name="ChargeBearerType1Code">
<xs:restriction base="xs:string">
<xs:enumeration value="DEBT" />
<xs:enumeration value="CRED" />
<xs:enumeration value="SHAR" />
<xs:enumeration value="SLEV" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="IBAN2007Identifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{2,2}[0-9]{2,2}[a-zA-Z0-9]{1,30}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="BICFIDec2014Identifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AnyBICDec2014Identifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="LEIIdentifier">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z0-9]{18,18}[0-9]{2,2}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="CountryCode">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{2,2}" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ISODate">
<xs:restriction base="xs:date" />
</xs:simpleType>
<xs:simpleType name="ISODateTime">
<xs:restriction base="xs:dateTime" />
</xs:simpleType>
<xs:simpleType name="ExternalServiceLevel1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="4" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ExternalLocalInstrument1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="35" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ExternalOrganisationIdentification1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="4" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ExternalPersonIdentification1Code">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="4" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max16Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="16" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max35Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="35" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max70Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="70" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="Max140Text">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="140" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PaymentMethod2Code">
<xs:restriction base="xs:string">
<xs:enumeration value="DD" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="SequenceType3Code">
<xs:restriction base="xs:string">
<xs:enumeration value="FRST" />
<xs:enumeration value="RCUR" />
<xs:enumeration value="FNAL" />
<xs:enumeration value="OOFF" />
<xs:enumeration value="RPRE" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="TrueFalseIndicator">
<xs:restriction base="xs:boolean" />
</xs:simpleType>
</xs:schema>
@@ -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;
/// <summary>
/// SEPA credit transfers (<c>pain.001.001.09</c>) and direct debits (<c>pain.008.001.08</c>), issues #70 and #71: the
/// files validate against the schemas, totals and counts, the character set, the grouping of debits and the errors.
/// </summary>
[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("<PmtMtd>TRF</PmtMtd>", "<PmtMtd>DD</PmtMtd>", StringComparison.Ordinal),
transfer.Replace("<IBAN>IT60X", "<IBAN>it60x", StringComparison.Ordinal),
transfer.Replace(">1000.00<", ">1000.001234<", StringComparison.Ordinal),
transfer.Replace("<ChrgBr>SLEV</ChrgBr>", string.Empty, StringComparison.Ordinal).Replace("<BtchBookg>", "<ChrgBr>SLEV</ChrgBr><BtchBookg>", 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("<SeqTp>FRST</SeqTp>", "<SeqTp>FIRST</SeqTp>", StringComparison.Ordinal)),
"pain.008.001.08.xsd",
SepaXmlWriter.DirectDebitNamespace));
Assert.IsNotEmpty(Validate(
Encoding.UTF8.GetBytes(debit.Replace("<MndtId>MND-001</MndtId>", "<MndtId>" + new string('M', 36) + "</MndtId>", 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), "<?xml version=\"1.0\" encoding=\"utf-8\"?>");
}
[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<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0m }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = -5m }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0.004m }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "" } }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "IT61X0542811101000000123456" } }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = null }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = "DE89370400440532013001" }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Bic = "NOT A BIC" }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.SddCore }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.Riba }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Company = Company with { CreditorId = null } }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateId = " " }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateDate = null }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Amount = 0m }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Iban = "" }] }));
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Kind = RemittanceKind.SepaCreditTransfer }));
Assert.ThrowsExactly<BankFileException>(() => 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<string> 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<string>();
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;
}
}
@@ -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());
}
@@ -0,0 +1,147 @@
using System.Text;
using Khaemhat.Core.Treasury;
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>The CBI current account statement (issue #71): balances, movements and their description lines.</summary>
[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<BankFileException>(() => Read(string.Join("\r\n", lines.Skip(1))));
var badSign = lines.ToArray();
badSign[2] = Put(badSign[2], 26, "X");
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", badSign)));
var badAmount = lines.ToArray();
badAmount[2] = Put(badAmount[2], 27, "00000ABC0000000");
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", badAmount)));
var badDate = lines.ToArray();
badDate[2] = Put(badDate[2], 20, "321326");
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", badDate)));
var orphan = lines.ToList();
orphan.Insert(2, Record("63", (4, "0000001"), (11, "001"), (14, "ORFANA")));
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", orphan)));
}
private static List<string> 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);
}
}
@@ -0,0 +1,28 @@
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>The late payment interest of D.Lgs. 231/2002 (issue #72): the reference rate of the half-year plus eight points.</summary>
[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);
}
}
@@ -0,0 +1,183 @@
using System.Text;
using Khaemhat.Core.Treasury;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>Bank receipts in the CBI fixed-width layout (issue #70): record lengths, order, positions and totals.</summary>
[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<BankFileException>(() => Writer.Write(remittance with { Company = Company with { SiaCode = null } }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Company = Company with { SiaCode = "123" } }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Company = Company with { Iban = "DE89370400440532013000" } }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Company = Company with { Iban = "IT61X0542811101000000123456" } }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Iban = null }] }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Iban = "DE89370400440532013000" }] }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Amount = 0m }] }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Amount = 100_000_000_000m }] }));
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [] }));
Assert.ThrowsExactly<BankFileException>(() => 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<IRemittanceFileWriter>().Supports(RemittanceKind.Riba));
Assert.AreEqual(StatementFormat.Cbi, pack.Require<IBankStatementReader>().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];
}
@@ -95,7 +95,7 @@ public sealed partial class LocalizationRulesTests
keys.AddRange(UserPreferences.Accents.Select(a => "Pages.Profile.Accent." + a));
keys.AddRange(Enum.GetValues<ToastKind>().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]
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more