M5 · Motore documenti e vendite (v0.5.0) #124
No files matched your search
@@ -23,10 +23,20 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
- Evasione riga per riga: copia e trasformazione dei documenti con le quantità residue, collegamenti registrati alla
|
||||
conferma e tolti all'annullamento, stato evaso/evaso in parte calcolato dalle righe, chiusura e riapertura del
|
||||
residuo. Servizio generico `DocumentService<THeader, TLine>` per famiglia e `DocumentCopyService`.
|
||||
- Totali dei documenti (#48, ADR 0033): importo di riga con sconti a cascata, spese e righe di sconto, sconto di
|
||||
piede sulle merci, prezzi IVA compresa scorporati per aliquota, castelletto IVA per codice con imposta sul totale del
|
||||
gruppo, esigibilità (immediata, differita, split payment), bollo sopra 77,47 euro di operazioni senza IVA (addebitato
|
||||
al cliente o no), cassa previdenza con la sua IVA, ritenuta d'acconto (anche sul 50% o 20% per gli agenti), ENASARCO,
|
||||
netto a pagare. Scadenze dalle condizioni di pagamento con fine mese, giorno fisso, mesi esclusi del cliente, IVA
|
||||
sulla prima rata e arrotondamento sull'ultima. Tabelle `document_tax_summaries` e `document_installments`,
|
||||
ricalcolate a ogni salvataggio.
|
||||
- Copia di più documenti della stessa controparte in uno solo (`MergeAsync`), con una riga di riferimento per ognuno:
|
||||
la base della fatturazione differita. Le note di credito e di debito ricordano la fattura che correggono.
|
||||
|
||||
### Changed
|
||||
- *Tipi documento*: nuovo campo obbligatorio **Genere** (i tipi di base lo ricevono dalla migrazione); *Numeratori*:
|
||||
nuovo campo **Data dell'ultimo numero**.
|
||||
- *Clienti*, condizioni di vendita: **mesi esclusi** (due mesi senza scadenze e il giorno del mese dopo in cui slittano).
|
||||
|
||||
## [0.4.0] - 2026-11-12
|
||||
|
||||
|
||||
@@ -991,6 +991,26 @@ Migrazioni applicate in ordine:
|
||||
|
||||
- indice unico `ux_discount_policies_code` su `code`
|
||||
|
||||
#### `document_installments`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `family` | String(40) | no | | |
|
||||
| `document_id` | Int64 | no | | |
|
||||
| `number` | Int32 | no | | |
|
||||
| `due_date` | Date | no | | |
|
||||
| `amount` | Decimal(19,6) | no | | |
|
||||
| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
|
||||
| `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_document_installments_document` su `family`, `document_id`
|
||||
- indice `ix_document_installments_due` su `due_date`
|
||||
|
||||
#### `document_links`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
@@ -1038,6 +1058,30 @@ Migrazioni applicate in ordine:
|
||||
|
||||
- indice unico `ux_document_numerators_code_year` su `code`, `year`
|
||||
|
||||
#### `document_tax_summaries`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `family` | String(40) | no | | |
|
||||
| `document_id` | Int64 | no | | |
|
||||
| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `rate` | Decimal(19,6) | no | | |
|
||||
| `nature` | String(10) | sì | | |
|
||||
| `exigibility` | String(40) | no | | |
|
||||
| `non_deductible_percent` | Decimal(19,6) | no | `0` | |
|
||||
| `legal_reference` | String(100) | sì | | |
|
||||
| `taxable` | Decimal(19,6) | no | | |
|
||||
| `tax` | Decimal(19,6) | no | | |
|
||||
| `non_deductible_tax` | Decimal(19,6) | no | `0` | |
|
||||
| `created_at` | DateTimeUtc | no | | |
|
||||
| `created_by` | String(100) | sì | | |
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
|
||||
- indice `ix_document_tax_summaries_document` su `family`, `document_id`
|
||||
|
||||
#### `document_types`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
@@ -1160,6 +1204,7 @@ Migrazioni applicate in ordine:
|
||||
| `fulfillment_closed` | Bool | no | `false` | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_line_id` | Int64 | sì | | |
|
||||
| `withholding_excluded` | Bool | no | `false` | |
|
||||
| `account_code` | String(20) | sì | | |
|
||||
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
|
||||
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
|
||||
@@ -1227,6 +1272,27 @@ Migrazioni applicate in ordine:
|
||||
| `withholding_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `social_security_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `net_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `prices_include_tax` | Bool | no | `false` | |
|
||||
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `exigibility` | String(40) | sì | | |
|
||||
| `split_payment` | Bool | no | `false` | |
|
||||
| `stamp_duty_charged` | Bool | no | `false` | |
|
||||
| `withholding_rate` | Decimal(19,6) | sì | | |
|
||||
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
|
||||
| `withholding_type` | String(4) | sì | | |
|
||||
| `withholding_reason` | String(2) | sì | | |
|
||||
| `social_security_fund` | String(4) | sì | | |
|
||||
| `social_security_rate` | Decimal(19,6) | sì | | |
|
||||
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `social_security_withheld` | Bool | no | `false` | |
|
||||
| `enasarco_rate` | Decimal(19,6) | sì | | |
|
||||
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `cig` | String(15) | sì | | |
|
||||
| `cup` | String(15) | sì | | |
|
||||
| `transport_by` | String(40) | sì | | |
|
||||
| `related_document_id` | Int64 | sì | | -> `inventory_documents` (Restrict) |
|
||||
| `related_number` | String(30) | sì | | |
|
||||
| `related_date` | Date | sì | | |
|
||||
| `notes` | Text | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | |
|
||||
| `vat_protocol` | Int64 | sì | | |
|
||||
@@ -1740,6 +1806,9 @@ Migrazioni applicate in ordine:
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
| `excluded_month1` | Int32 | sì | | |
|
||||
| `excluded_month2` | Int32 | sì | | |
|
||||
| `excluded_months_day` | Int32 | sì | | |
|
||||
|
||||
- indice unico `ux_party_sales_terms_party` su `party_id`
|
||||
|
||||
@@ -1867,6 +1936,7 @@ Migrazioni applicate in ordine:
|
||||
| `fulfillment_closed` | Bool | no | `false` | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_line_id` | Int64 | sì | | |
|
||||
| `withholding_excluded` | Bool | no | `false` | |
|
||||
| `account_code` | String(20) | sì | | |
|
||||
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
|
||||
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
|
||||
@@ -1934,6 +2004,27 @@ Migrazioni applicate in ordine:
|
||||
| `withholding_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `social_security_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `net_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `prices_include_tax` | Bool | no | `false` | |
|
||||
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `exigibility` | String(40) | sì | | |
|
||||
| `split_payment` | Bool | no | `false` | |
|
||||
| `stamp_duty_charged` | Bool | no | `false` | |
|
||||
| `withholding_rate` | Decimal(19,6) | sì | | |
|
||||
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
|
||||
| `withholding_type` | String(4) | sì | | |
|
||||
| `withholding_reason` | String(2) | sì | | |
|
||||
| `social_security_fund` | String(4) | sì | | |
|
||||
| `social_security_rate` | Decimal(19,6) | sì | | |
|
||||
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `social_security_withheld` | Bool | no | `false` | |
|
||||
| `enasarco_rate` | Decimal(19,6) | sì | | |
|
||||
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `cig` | String(15) | sì | | |
|
||||
| `cup` | String(15) | sì | | |
|
||||
| `transport_by` | String(40) | sì | | |
|
||||
| `related_document_id` | Int64 | sì | | -> `purchase_documents` (Restrict) |
|
||||
| `related_number` | String(30) | sì | | |
|
||||
| `related_date` | Date | sì | | |
|
||||
| `notes` | Text | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | |
|
||||
| `vat_protocol` | Int64 | sì | | |
|
||||
@@ -1976,6 +2067,7 @@ Migrazioni applicate in ordine:
|
||||
| `fulfillment_closed` | Bool | no | `false` | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_line_id` | Int64 | sì | | |
|
||||
| `withholding_excluded` | Bool | no | `false` | |
|
||||
| `account_code` | String(20) | sì | | |
|
||||
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
|
||||
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
|
||||
@@ -2043,6 +2135,27 @@ Migrazioni applicate in ordine:
|
||||
| `withholding_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `social_security_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `net_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `prices_include_tax` | Bool | no | `false` | |
|
||||
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `exigibility` | String(40) | sì | | |
|
||||
| `split_payment` | Bool | no | `false` | |
|
||||
| `stamp_duty_charged` | Bool | no | `false` | |
|
||||
| `withholding_rate` | Decimal(19,6) | sì | | |
|
||||
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
|
||||
| `withholding_type` | String(4) | sì | | |
|
||||
| `withholding_reason` | String(2) | sì | | |
|
||||
| `social_security_fund` | String(4) | sì | | |
|
||||
| `social_security_rate` | Decimal(19,6) | sì | | |
|
||||
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `social_security_withheld` | Bool | no | `false` | |
|
||||
| `enasarco_rate` | Decimal(19,6) | sì | | |
|
||||
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `cig` | String(15) | sì | | |
|
||||
| `cup` | String(15) | sì | | |
|
||||
| `transport_by` | String(40) | sì | | |
|
||||
| `related_document_id` | Int64 | sì | | -> `purchase_orders` (Restrict) |
|
||||
| `related_number` | String(30) | sì | | |
|
||||
| `related_date` | Date | sì | | |
|
||||
| `notes` | Text | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | |
|
||||
| `vat_protocol` | Int64 | sì | | |
|
||||
@@ -2118,6 +2231,7 @@ Migrazioni applicate in ordine:
|
||||
| `fulfillment_closed` | Bool | no | `false` | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_line_id` | Int64 | sì | | |
|
||||
| `withholding_excluded` | Bool | no | `false` | |
|
||||
| `account_code` | String(20) | sì | | |
|
||||
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
|
||||
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
|
||||
@@ -2185,6 +2299,27 @@ Migrazioni applicate in ordine:
|
||||
| `withholding_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `social_security_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `net_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `prices_include_tax` | Bool | no | `false` | |
|
||||
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `exigibility` | String(40) | sì | | |
|
||||
| `split_payment` | Bool | no | `false` | |
|
||||
| `stamp_duty_charged` | Bool | no | `false` | |
|
||||
| `withholding_rate` | Decimal(19,6) | sì | | |
|
||||
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
|
||||
| `withholding_type` | String(4) | sì | | |
|
||||
| `withholding_reason` | String(2) | sì | | |
|
||||
| `social_security_fund` | String(4) | sì | | |
|
||||
| `social_security_rate` | Decimal(19,6) | sì | | |
|
||||
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `social_security_withheld` | Bool | no | `false` | |
|
||||
| `enasarco_rate` | Decimal(19,6) | sì | | |
|
||||
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `cig` | String(15) | sì | | |
|
||||
| `cup` | String(15) | sì | | |
|
||||
| `transport_by` | String(40) | sì | | |
|
||||
| `related_document_id` | Int64 | sì | | -> `sale_documents` (Restrict) |
|
||||
| `related_number` | String(30) | sì | | |
|
||||
| `related_date` | Date | sì | | |
|
||||
| `notes` | Text | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | |
|
||||
| `vat_protocol` | Int64 | sì | | |
|
||||
@@ -2227,6 +2362,7 @@ Migrazioni applicate in ordine:
|
||||
| `fulfillment_closed` | Bool | no | `false` | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_line_id` | Int64 | sì | | |
|
||||
| `withholding_excluded` | Bool | no | `false` | |
|
||||
| `account_code` | String(20) | sì | | |
|
||||
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
|
||||
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
|
||||
@@ -2294,6 +2430,27 @@ Migrazioni applicate in ordine:
|
||||
| `withholding_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `social_security_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `net_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `prices_include_tax` | Bool | no | `false` | |
|
||||
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `exigibility` | String(40) | sì | | |
|
||||
| `split_payment` | Bool | no | `false` | |
|
||||
| `stamp_duty_charged` | Bool | no | `false` | |
|
||||
| `withholding_rate` | Decimal(19,6) | sì | | |
|
||||
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
|
||||
| `withholding_type` | String(4) | sì | | |
|
||||
| `withholding_reason` | String(2) | sì | | |
|
||||
| `social_security_fund` | String(4) | sì | | |
|
||||
| `social_security_rate` | Decimal(19,6) | sì | | |
|
||||
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `social_security_withheld` | Bool | no | `false` | |
|
||||
| `enasarco_rate` | Decimal(19,6) | sì | | |
|
||||
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `cig` | String(15) | sì | | |
|
||||
| `cup` | String(15) | sì | | |
|
||||
| `transport_by` | String(40) | sì | | |
|
||||
| `related_document_id` | Int64 | sì | | -> `sale_orders` (Restrict) |
|
||||
| `related_number` | String(30) | sì | | |
|
||||
| `related_date` | Date | sì | | |
|
||||
| `notes` | Text | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | |
|
||||
| `vat_protocol` | Int64 | sì | | |
|
||||
@@ -2336,6 +2493,7 @@ Migrazioni applicate in ordine:
|
||||
| `fulfillment_closed` | Bool | no | `false` | |
|
||||
| `source_family` | String(40) | sì | | |
|
||||
| `source_line_id` | Int64 | sì | | |
|
||||
| `withholding_excluded` | Bool | no | `false` | |
|
||||
| `account_code` | String(20) | sì | | |
|
||||
| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
|
||||
| `job_id` | Int64 | sì | | -> `jobs` (Restrict) |
|
||||
@@ -2403,6 +2561,27 @@ Migrazioni applicate in ordine:
|
||||
| `withholding_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `social_security_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `net_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `prices_include_tax` | Bool | no | `false` | |
|
||||
| `footer_discount_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `exigibility` | String(40) | sì | | |
|
||||
| `split_payment` | Bool | no | `false` | |
|
||||
| `stamp_duty_charged` | Bool | no | `false` | |
|
||||
| `withholding_rate` | Decimal(19,6) | sì | | |
|
||||
| `withholding_base_percent` | Decimal(19,6) | no | `100` | |
|
||||
| `withholding_type` | String(4) | sì | | |
|
||||
| `withholding_reason` | String(2) | sì | | |
|
||||
| `social_security_fund` | String(4) | sì | | |
|
||||
| `social_security_rate` | Decimal(19,6) | sì | | |
|
||||
| `social_security_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||
| `social_security_withheld` | Bool | no | `false` | |
|
||||
| `enasarco_rate` | Decimal(19,6) | sì | | |
|
||||
| `enasarco_amount` | Decimal(19,6) | no | `0` | |
|
||||
| `cig` | String(15) | sì | | |
|
||||
| `cup` | String(15) | sì | | |
|
||||
| `transport_by` | String(40) | sì | | |
|
||||
| `related_document_id` | Int64 | sì | | -> `sale_quotations` (Restrict) |
|
||||
| `related_number` | String(30) | sì | | |
|
||||
| `related_date` | Date | sì | | |
|
||||
| `notes` | Text | sì | | |
|
||||
| `gl_entry_id` | Int64 | sì | | |
|
||||
| `vat_protocol` | Int64 | sì | | |
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# ADR 0033 - Totali, castelletto IVA e scadenze dei documenti
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §11.3; milestone M5, issue #48
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.3 chiede un `DocumentTotalsCalculator` (imponibile di riga, sconti a cascata, castelletto per codice IVA,
|
||||
spese, sconto di piede, bollo, ritenuta, cassa previdenza, split payment, reverse charge, IVA per cassa) e un
|
||||
`InstallmentGenerator` (fine mese, giorno fisso, percentuali, IVA sulla prima rata, arrotondamento sull'ultima), con
|
||||
tabelle `_tax_summary` e `_installments` per ogni famiglia. Restavano aperti: dove si applica lo sconto di piede,
|
||||
come si gestiscono i prezzi IVA compresa, che cosa entra nella base della ritenuta e della cassa, dove si salvano
|
||||
castelletto e scadenze, quando si ricalcolano.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Calcolo puro.** `DocumentTotalsCalculator` e `InstallmentGenerator` sono funzioni senza database, provate con
|
||||
casi numerici di riferimento. L'arrotondamento e il bollo vengono da `ITaxEngine` del pacchetto paese.
|
||||
2. **Riga.** Importo = quantità × prezzo × (1 − s1)(1 − s2)…, al centesimo con metà lontano da zero. Spese e sconti
|
||||
senza quantità valgono una volta; le righe di sconto sono negative; le righe descrittive non contano.
|
||||
3. **Sconto di piede** (formula come `10+5`): si applica a ogni riga di merce, non alle spese, e solo nel castelletto.
|
||||
La riga conserva il suo importo, il documento registra quanto lo sconto ha tolto (`footer_discount_amount`).
|
||||
4. **Castelletto** per codice IVA, con l'imposta calcolata sul totale del gruppo (come `DatiRiepilogo`). Con i
|
||||
**prezzi IVA compresa** si somma il lordo del gruppo e si scorpora una volta sola. L'esigibilità è quella del
|
||||
codice IVA, del documento (IVA per cassa) o *S* con lo **split payment**. Il reverse charge non ha bisogno di
|
||||
regole: i codici N6.x hanno aliquota zero.
|
||||
5. **Cassa previdenza, ritenuta, ENASARCO.** La base è la somma delle righe non escluse
|
||||
(`withholding_excluded`, ad esempio le spese anticipate in nome del cliente), dopo lo sconto di piede. La cassa
|
||||
entra nel castelletto con l'IVA indicata o con quella della prima riga imponibile; la ritenuta si calcola sulla
|
||||
quota della base (100% per i professionisti, 50% o 20% per gli agenti), con la cassa se è soggetta. Ritenuta,
|
||||
ENASARCO e IVA in split payment si tolgono dal **netto a pagare**, non dal totale.
|
||||
6. **Bollo** sulle fatture e note di vendita quando gli importi senza IVA che lo richiedono superano la soglia del
|
||||
pacchetto paese (77,47 euro): è sempre indicato; entra nel totale solo se addebitato al cliente.
|
||||
7. **Scadenze** dal netto a pagare e dalle rate della condizione di pagamento; con *IVA sulla prima rata* l'IVA
|
||||
effettivamente incassata va tutta sulla prima. Fine mese e giorno fisso: con fine mese il giorno fisso è del mese
|
||||
successivo, senza fine mese è il primo giorno fisso non anteriore. I **mesi esclusi** stanno nelle condizioni di
|
||||
vendita del cliente e spostano la scadenza a un giorno del mese successivo (10 se non indicato). Le scadenze
|
||||
esistono per fatture, note, fatture fornitore e, come previsione, per preventivi, ordini e pro forma.
|
||||
8. **Due tabelle condivise invece di dodici.** Castelletto e scadenze stanno in `document_tax_summaries` e
|
||||
`document_installments` con la colonna `family`, come `document_links`: le righe non hanno vincoli verso una
|
||||
sola tabella e il codice resta unico per tutte le famiglie. Diverge dalla lettera di §11.3 (una coppia di tabelle
|
||||
per famiglia), non dalla sostanza.
|
||||
9. **Quando.** Il motore ricalcola a ogni salvataggio (bozze e righe di documenti ancora aperti) e riscrive
|
||||
castelletto e scadenze nella stessa transazione. Un documento emesso non cambia più, quindi i suoi totali restano
|
||||
quelli dell'emissione. Lo scadenzario vero (partite, incassi) arriva con M8 e parte da queste righe.
|
||||
10. **Revisioni dei preventivi.** Modificare un preventivo confermato aumenta il numero di revisione: il numero
|
||||
del documento resta lo stesso.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le maschere mostrano castelletto, totali e scadenze ricalcolati durante la modifica con lo stesso codice del
|
||||
salvataggio (anteprima senza scrittura).
|
||||
- Il file FatturaPA (M9) troverà lo sconto di piede da ripartire sulle righe e il castelletto già pronto.
|
||||
- Lo sconto cassa resta fuori: si gestirà con gli incassi (M8).
|
||||
@@ -0,0 +1,201 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>The totals of a stored document: its tax summary and installments, as written by the last save.</summary>
|
||||
/// <param name="Summary">The tax summary.</param>
|
||||
/// <param name="Installments">The installments.</param>
|
||||
public sealed record DocumentFigures(IReadOnlyList<DocumentTaxSummary> Summary, IReadOnlyList<DocumentInstallment> Installments)
|
||||
{
|
||||
/// <summary>No figures.</summary>
|
||||
public static DocumentFigures Empty { get; } = new([], []);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies <see cref="DocumentTotalsCalculator"/> and <see cref="InstallmentGenerator"/> to a document being saved:
|
||||
/// writes the line amounts and header totals, then replaces its tax summary and installments (issue #48).
|
||||
/// </summary>
|
||||
internal static class DocumentCalculation
|
||||
{
|
||||
/// <summary>Computes the totals of a document in place.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="engine">The country's tax engine.</param>
|
||||
/// <param name="behavior">The behaviour of the document.</param>
|
||||
/// <param name="record">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The tax summary and installments to write once the document has its id.</returns>
|
||||
public static async Task<DocumentFigures> ApplyAsync(IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = record.Header;
|
||||
var taxCodes = await TaxCodesAsync(uow, record, cancellationToken).ConfigureAwait(false);
|
||||
var options = new TotalsOptions
|
||||
{
|
||||
PricesIncludeTax = header.PricesIncludeTax,
|
||||
FooterDiscount = header.FooterDiscount,
|
||||
Exigibility = header.Exigibility,
|
||||
SplitPayment = header.SplitPayment,
|
||||
StampDutyApplies = behavior.Direction == DocumentDirection.Sale && behavior.Has(DocumentEffects.EInvoice),
|
||||
StampDutyCharged = header.StampDutyCharged,
|
||||
WithholdingRate = header.WithholdingRate,
|
||||
WithholdingBasePercent = header.WithholdingBasePercent <= 0m ? 100m : header.WithholdingBasePercent,
|
||||
SocialSecurityRate = header.SocialSecurityRate,
|
||||
SocialSecurityTax = header.SocialSecurityTaxCodeId is { } id && taxCodes.TryGetValue(id, out var own) ? own : null,
|
||||
SocialSecurityWithheld = header.SocialSecurityWithheld,
|
||||
EnasarcoRate = header.EnasarcoRate,
|
||||
};
|
||||
var lines = record.Lines
|
||||
.Select(l => new TotalsLine(l.Kind, l.Quantity, l.Price, l.DiscountFormula,
|
||||
l.TaxCodeId is { } t && taxCodes.TryGetValue(t, out var tax) ? tax : null, l.WithholdingExcluded))
|
||||
.ToList();
|
||||
var totals = DocumentTotalsCalculator.Compute(lines, options, engine);
|
||||
for (var i = 0; i < record.Lines.Count; i++)
|
||||
{
|
||||
record.Lines[i].TaxableAmount = totals.LineAmounts[i];
|
||||
}
|
||||
|
||||
header.TaxableAmount = totals.Taxable;
|
||||
header.TaxAmount = totals.Tax;
|
||||
header.TotalAmount = totals.Total;
|
||||
header.ExpensesAmount = totals.Expenses;
|
||||
header.FooterDiscountAmount = totals.FooterDiscountAmount;
|
||||
header.StampDuty = totals.StampDuty;
|
||||
header.WithholdingAmount = totals.Withholding;
|
||||
header.SocialSecurityAmount = totals.SocialSecurity;
|
||||
header.EnasarcoAmount = totals.Enasarco;
|
||||
header.NetAmount = totals.Net;
|
||||
|
||||
var summary = totals.Summary.Select(s => new DocumentTaxSummary
|
||||
{
|
||||
Family = record.Family,
|
||||
TaxCodeId = s.Tax.TaxCodeId,
|
||||
Rate = s.Tax.Rate,
|
||||
Nature = s.Tax.Nature,
|
||||
Exigibility = s.Tax.Exigibility,
|
||||
NonDeductiblePercent = s.Tax.NonDeductiblePercent,
|
||||
LegalReference = s.Tax.LegalReference,
|
||||
Taxable = s.Taxable,
|
||||
Tax = s.TaxAmount,
|
||||
NonDeductibleTax = s.NonDeductibleTax,
|
||||
}).ToList();
|
||||
|
||||
var installments = new List<DocumentInstallment>();
|
||||
if (behavior.Has(DocumentEffects.Installments) || behavior.Kind is DocumentKind.ProForma or DocumentKind.SalesOrder or DocumentKind.Quotation)
|
||||
{
|
||||
installments = await InstallmentsAsync(uow, engine, behavior, record, totals, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new DocumentFigures(summary, installments);
|
||||
}
|
||||
|
||||
/// <summary>Replaces the tax summary and installments of a document.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="figures">The new rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task WriteAsync(IUnitOfWork uow, DocumentFamily family, long documentId, DocumentFigures figures, CancellationToken cancellationToken)
|
||||
{
|
||||
var summaries = uow.Repository<DocumentTaxSummary, long>();
|
||||
var installments = uow.Repository<DocumentInstallment, long>();
|
||||
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
|
||||
foreach (var old in (await summaries.ListAsync(Query.For<DocumentTaxSummary>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
await summaries.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var old in (await installments.ListAsync(Query.For<DocumentInstallment>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
await installments.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var row in figures.Summary)
|
||||
{
|
||||
row.Id = 0;
|
||||
row.Family = family;
|
||||
row.DocumentId = documentId;
|
||||
await summaries.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var row in figures.Installments)
|
||||
{
|
||||
row.Id = 0;
|
||||
row.Family = family;
|
||||
row.DocumentId = documentId;
|
||||
await installments.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the tax summary and installments of a document.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public static async Task<DocumentFigures> ReadAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
|
||||
var summary = await uow.Repository<DocumentTaxSummary, long>()
|
||||
.ListAsync(Query.For<DocumentTaxSummary>().Where(where).OrderByDescending(s => s.Rate), cancellationToken).ConfigureAwait(false);
|
||||
var installments = await uow.Repository<DocumentInstallment, long>()
|
||||
.ListAsync(Query.For<DocumentInstallment>().Where(where).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false);
|
||||
return new DocumentFigures(summary.Items, installments.Items);
|
||||
}
|
||||
|
||||
private static async Task<Dictionary<long, TotalsTax>> TaxCodesAsync(IUnitOfWork uow, DocumentRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).ToHashSet();
|
||||
if (record.Header.SocialSecurityTaxCodeId is { } own)
|
||||
{
|
||||
ids.Add(own);
|
||||
}
|
||||
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var list = ids.ToList();
|
||||
var codes = await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(c => list.Contains(c.Id)), cancellationToken).ConfigureAwait(false);
|
||||
return codes.Items.ToDictionary(c => c.Id, c => new TotalsTax(c.Id, c.Rate, string.IsNullOrWhiteSpace(c.Nature) ? null : c.Nature,
|
||||
c.Exigibility, c.NonDeductiblePercent, c.LegalReference));
|
||||
}
|
||||
|
||||
private static async Task<List<DocumentInstallment>> InstallmentsAsync(
|
||||
IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, DocumentTotals totals, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = record.Header;
|
||||
PaymentTerm? term = null;
|
||||
IReadOnlyList<PaymentTermLine> termLines = [];
|
||||
if (header.PaymentTermId is { } termId)
|
||||
{
|
||||
term = await uow.Repository<PaymentTerm, long>().GetAsync(termId, cancellationToken).ConfigureAwait(false);
|
||||
termLines = (await uow.Repository<PaymentTermLine, long>()
|
||||
.ListAsync(Query.For<PaymentTermLine>().Where(l => l.PaymentTermId == termId).OrderBy(l => l.Number), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
ExcludedMonths? excluded = null;
|
||||
if (behavior.Direction == DocumentDirection.Sale && header.PartyId is { } partyId)
|
||||
{
|
||||
var terms = await uow.Repository<PartySalesTerms, long>()
|
||||
.FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == partyId), cancellationToken).ConfigureAwait(false);
|
||||
if (terms is { } t && (t.ExcludedMonth1 is not null || t.ExcludedMonth2 is not null))
|
||||
{
|
||||
excluded = new ExcludedMonths(t.ExcludedMonth1, t.ExcludedMonth2, t.ExcludedMonthsDay ?? 10);
|
||||
}
|
||||
}
|
||||
|
||||
var paidTax = totals.Tax - totals.SplitPaymentTax;
|
||||
var dues = InstallmentGenerator.Generate(
|
||||
header.DocumentDate, totals.Net, paidTax,
|
||||
[.. termLines.Select(l => new InstallmentRule(l.Days, l.EndOfMonth, l.FixedDay, l.Percent))],
|
||||
term?.VatOnFirstInstallment ?? false, excluded, engine.Round);
|
||||
var method = header.PaymentMethodId ?? term?.PaymentMethodId;
|
||||
return [.. dues.Select(d => new DocumentInstallment { Number = d.Number, DueDate = d.DueDate, Amount = d.Amount, PaymentMethodId = method })];
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Data;
|
||||
@@ -40,13 +41,44 @@ public sealed class DocumentCopyService
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new draft.</returns>
|
||||
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
|
||||
public async Task<DocumentRecord> CopyAsync(
|
||||
public Task<DocumentRecord> CopyAsync(
|
||||
Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
CancellationToken cancellationToken = default) =>
|
||||
MergeAsync(actor, companyCode, family, [id], targetTypeCode, null, lineIds, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Copies several documents of the same party into one new draft and saves it (deferred invoice from delivery
|
||||
/// notes, delivery note from several orders): the header comes from the first, each source adds a reference line
|
||||
/// and its lines.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who copies.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family of the sources.</param>
|
||||
/// <param name="ids">The sources, in order.</param>
|
||||
/// <param name="targetTypeCode">The type of the new document.</param>
|
||||
/// <param name="date">The date of the new document; today when empty.</param>
|
||||
/// <param name="lineIds">The lines to copy; all when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new draft.</returns>
|
||||
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
|
||||
public async Task<DocumentRecord> MergeAsync(
|
||||
Actor actor, string companyCode, DocumentFamily family, IReadOnlyList<long> ids, string targetTypeCode, DateOnly? date = null,
|
||||
IReadOnlyCollection<long>? lineIds = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var source = await _engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]);
|
||||
}
|
||||
|
||||
var sources = new List<DocumentRecord>();
|
||||
foreach (var id in ids)
|
||||
{
|
||||
sources.Add(await _engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(DocumentErrors.NotFound));
|
||||
}
|
||||
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
DocumentDefinition target;
|
||||
await using (var uow = await _engine.Factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
@@ -55,42 +87,69 @@ public sealed class DocumentCopyService
|
||||
}
|
||||
|
||||
await _permissions.DemandAsync(actor, target.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var sourceBehavior = DocumentBehaviors.Of(source.Header.Kind);
|
||||
DocumentStateMachine.Apply(sourceBehavior.Lifecycle, source.Header.Status, DocumentAction.Copy);
|
||||
if (sourceBehavior.Direction != target.Behavior.Direction)
|
||||
if (sources.Select(s => s.Header.PartyId).Distinct().Count() > 1)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.CopyDirection]);
|
||||
throw new ValidationFailedException([":" + DocumentErrors.CopyParties]);
|
||||
}
|
||||
|
||||
var fulfils = target.Behavior.Fulfils(source.Header.Kind);
|
||||
if (fulfils && (source.Header.Status is DocumentStatus.Draft or DocumentStatus.Closed or DocumentStatus.Cancelled))
|
||||
var copy = new DocumentRecord
|
||||
{
|
||||
throw new ValidationFailedException([":" + DocumentErrors.CopySourceNotOpen]);
|
||||
}
|
||||
|
||||
var copy = new DocumentRecord { Family = target.Family, Header = Header(source.Header, target, DateOnly.FromDateTime(_clock.GetLocalNow().DateTime)) };
|
||||
Family = target.Family,
|
||||
Header = Header(sources[0], target, date ?? DateOnly.FromDateTime(_clock.GetLocalNow().DateTime)),
|
||||
};
|
||||
var wanted = lineIds is { Count: > 0 } ? lineIds.ToHashSet() : null;
|
||||
foreach (var line in source.Lines.Where(l => wanted is null || wanted.Contains(l.Id)))
|
||||
var anyFulfils = false;
|
||||
foreach (var source in sources)
|
||||
{
|
||||
if (!target.Behavior.Lines.Contains(line.Kind))
|
||||
var sourceBehavior = DocumentBehaviors.Of(source.Header.Kind);
|
||||
DocumentStateMachine.Apply(sourceBehavior.Lifecycle, source.Header.Status, DocumentAction.Copy);
|
||||
if (sourceBehavior.Direction != target.Behavior.Direction)
|
||||
{
|
||||
continue;
|
||||
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.CopyDirection]);
|
||||
}
|
||||
|
||||
var quantity = line.Quantity;
|
||||
if (fulfils && DocumentLine.CarriesQuantity(line.Kind))
|
||||
var fulfils = target.Behavior.Fulfils(source.Header.Kind);
|
||||
anyFulfils |= fulfils;
|
||||
if (fulfils && (source.Header.Status is DocumentStatus.Draft or DocumentStatus.Closed or DocumentStatus.Cancelled))
|
||||
{
|
||||
quantity = line.Residual;
|
||||
if (quantity <= 0)
|
||||
throw new ValidationFailedException([":" + DocumentErrors.CopySourceNotOpen]);
|
||||
}
|
||||
|
||||
var lines = new List<DocumentLine>();
|
||||
foreach (var line in source.Lines.Where(l => wanted is null || wanted.Contains(l.Id)))
|
||||
{
|
||||
if (!target.Behavior.Lines.Contains(line.Kind))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var quantity = line.Quantity;
|
||||
if (fulfils && DocumentLine.CarriesQuantity(line.Kind))
|
||||
{
|
||||
quantity = line.Residual;
|
||||
if (quantity <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
lines.Add(Line(line, target.Family, quantity, fulfils ? source.Family : null));
|
||||
}
|
||||
|
||||
copy.Lines.Add(Line(line, target.Family, quantity, fulfils ? source.Family : null));
|
||||
if (sources.Count > 1 && lines.Count > 0 && source.Header.DocumentNumber is { } number
|
||||
&& target.Behavior.Lines.Contains(DocumentLineKind.Description))
|
||||
{
|
||||
var reference = DocumentStores.Of(target.Family).NewLine();
|
||||
reference.Kind = DocumentLineKind.Description;
|
||||
reference.Description = ReferenceLabel(source.Header.Kind) + " " + number + " del "
|
||||
+ source.Header.DocumentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
|
||||
copy.Lines.Add(reference);
|
||||
}
|
||||
|
||||
copy.Lines.AddRange(lines);
|
||||
}
|
||||
|
||||
if (fulfils && !copy.Lines.Any(l => l.SourceLineId is not null))
|
||||
if (anyFulfils && !copy.Lines.Any(l => l.SourceLineId is not null))
|
||||
{
|
||||
throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]);
|
||||
}
|
||||
@@ -98,8 +157,18 @@ public sealed class DocumentCopyService
|
||||
return await _engine.SaveAsync(actor, company, copy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static DocumentHeader Header(DocumentHeader source, DocumentDefinition target, DateOnly today)
|
||||
// The reference printed before the lines of each source (the documents are written in Italian).
|
||||
private static string ReferenceLabel(DocumentKind kind) => kind switch
|
||||
{
|
||||
DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote => "Rif. DDT n.",
|
||||
DocumentKind.SalesOrder or DocumentKind.PurchaseOrder => "Rif. ordine n.",
|
||||
DocumentKind.Quotation => "Rif. preventivo n.",
|
||||
_ => "Rif. documento n.",
|
||||
};
|
||||
|
||||
private static DocumentHeader Header(DocumentRecord record, DocumentDefinition target, DateOnly today)
|
||||
{
|
||||
var source = record.Header;
|
||||
var header = DocumentStores.Of(target.Family).NewHeader();
|
||||
header.DocumentTypeId = target.Type.Id;
|
||||
header.Kind = target.Kind;
|
||||
@@ -124,6 +193,33 @@ public sealed class DocumentCopyService
|
||||
header.DeliveryDate = source.DeliveryDate;
|
||||
header.FooterDiscount = source.FooterDiscount;
|
||||
header.Notes = source.Notes;
|
||||
header.ExternalReference = source.ExternalReference;
|
||||
header.ExternalDate = source.ExternalDate;
|
||||
header.PricesIncludeTax = source.PricesIncludeTax;
|
||||
header.Exigibility = source.Exigibility;
|
||||
header.SplitPayment = source.SplitPayment;
|
||||
header.StampDutyCharged = source.StampDutyCharged;
|
||||
header.WithholdingRate = source.WithholdingRate;
|
||||
header.WithholdingBasePercent = source.WithholdingBasePercent;
|
||||
header.WithholdingType = source.WithholdingType;
|
||||
header.WithholdingReason = source.WithholdingReason;
|
||||
header.SocialSecurityFund = source.SocialSecurityFund;
|
||||
header.SocialSecurityRate = source.SocialSecurityRate;
|
||||
header.SocialSecurityTaxCodeId = source.SocialSecurityTaxCodeId;
|
||||
header.SocialSecurityWithheld = source.SocialSecurityWithheld;
|
||||
header.EnasarcoRate = source.EnasarcoRate;
|
||||
header.Cig = source.Cig;
|
||||
header.Cup = source.Cup;
|
||||
header.TransportBy = source.TransportBy;
|
||||
if (target.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote or DocumentKind.PurchaseCreditNote
|
||||
&& DocumentBehaviors.Of(source.Kind).Lifecycle != DocumentLifecycle.Order && record.Family == target.Family)
|
||||
{
|
||||
// A note refers to the invoice it corrects (DatiFattureCollegate).
|
||||
header.RelatedDocumentId = source.Id;
|
||||
header.RelatedNumber = source.DocumentNumber;
|
||||
header.RelatedDate = source.DocumentDate;
|
||||
}
|
||||
|
||||
return header;
|
||||
}
|
||||
|
||||
@@ -148,6 +244,7 @@ public sealed class DocumentCopyService
|
||||
line.CostCenterId = source.CostCenterId;
|
||||
line.JobId = source.JobId;
|
||||
line.Notes = source.Notes;
|
||||
line.WithholdingExcluded = source.WithholdingExcluded;
|
||||
if (sourceFamily is not null && DocumentLine.CarriesQuantity(source.Kind))
|
||||
{
|
||||
line.SourceFamily = sourceFamily;
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>A document in a radar.</summary>
|
||||
/// <param name="Id">The document.</param>
|
||||
/// <param name="Family">The family.</param>
|
||||
/// <param name="Kind">The kind.</param>
|
||||
/// <param name="TypeCode">The code of the document type.</param>
|
||||
/// <param name="DocumentNumber">The number as printed; empty for drafts.</param>
|
||||
/// <param name="Date">The date.</param>
|
||||
/// <param name="PartyId">The party.</param>
|
||||
/// <param name="PartyCode">The code of the party.</param>
|
||||
/// <param name="PartyName">The name of the party.</param>
|
||||
/// <param name="Status">The state.</param>
|
||||
/// <param name="Taxable">The taxable amount.</param>
|
||||
/// <param name="Total">The total.</param>
|
||||
/// <param name="Net">The amount to pay.</param>
|
||||
/// <param name="Reference">The reference of the other side.</param>
|
||||
/// <param name="DeliveryDate">The delivery date.</param>
|
||||
/// <param name="ValidUntil">Until when a quotation is valid.</param>
|
||||
/// <param name="Revision">The revision of a quotation.</param>
|
||||
/// <param name="IsDemo">Demo data.</param>
|
||||
public sealed record DocumentRow(
|
||||
long Id, DocumentFamily Family, DocumentKind Kind, string TypeCode, string? DocumentNumber, DateOnly Date, long? PartyId, string? PartyCode,
|
||||
string? PartyName, DocumentStatus Status, decimal Taxable, decimal Total, decimal Net, string? Reference, DateOnly? DeliveryDate,
|
||||
DateOnly? ValidUntil, int Revision, bool IsDemo);
|
||||
|
||||
/// <summary>A document linked to another one.</summary>
|
||||
/// <param name="Family">The family.</param>
|
||||
/// <param name="Id">The document.</param>
|
||||
/// <param name="Kind">The kind.</param>
|
||||
/// <param name="DocumentNumber">The number.</param>
|
||||
/// <param name="Date">The date.</param>
|
||||
/// <param name="Status">The state.</param>
|
||||
/// <param name="Total">The total.</param>
|
||||
/// <param name="Direction">Where it stands: before (source), after (fulfils it) or corrected (note).</param>
|
||||
/// <param name="Quantity">The quantity fulfilled between the two.</param>
|
||||
public sealed record LinkedDocument(
|
||||
DocumentFamily Family, long Id, DocumentKind Kind, string? DocumentNumber, DateOnly Date, DocumentStatus Status, decimal Total,
|
||||
LinkDirection Direction, decimal Quantity);
|
||||
|
||||
/// <summary>How a linked document relates to the one shown.</summary>
|
||||
public enum LinkDirection
|
||||
{
|
||||
/// <summary>The document shown fulfils it (an order of a delivery note).</summary>
|
||||
Source = 0,
|
||||
|
||||
/// <summary>It fulfils the document shown (a delivery note of an order).</summary>
|
||||
Target = 1,
|
||||
|
||||
/// <summary>The invoice a note corrects, or a note that corrects the invoice shown.</summary>
|
||||
Related = 2,
|
||||
}
|
||||
|
||||
/// <summary>An open document with something left to fulfil, for the guided fulfilment and the deferred invoicing.</summary>
|
||||
/// <param name="Row">The document.</param>
|
||||
/// <param name="Lines">The lines with a residual.</param>
|
||||
public sealed record OpenDocument(DocumentRow Row, IReadOnlyList<DocumentLine> Lines);
|
||||
|
||||
/// <summary>
|
||||
/// What the document screens need besides the engine (SPEC §11.3-§11.4): radars, the values proposed by the party and
|
||||
/// by the item, totals computed while editing, the documents linked and the open documents to fulfil.
|
||||
/// </summary>
|
||||
public sealed class DocumentEditor
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
public DocumentEditor(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
}
|
||||
|
||||
/// <summary>A page of documents of some kinds of a family.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="kinds">The kinds; all of the family when empty.</param>
|
||||
/// <param name="query">The request; the search also looks at the code and name of the party.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<ListPage<DocumentRow>> ListAsync(
|
||||
Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection<DocumentKind> kinds, ListQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kinds);
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var wanted = kinds.Count > 0 ? kinds : DocumentBehaviors.KindsOf(family);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(wanted.First()).ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var conditions = new List<SqlFragment>
|
||||
{
|
||||
SqlFragment.Literal("kind IN (") + SqlFragment.Join(", ", wanted.Select(k => SqlFragment.Parameter(k.ToString()))) + SqlFragment.Literal(")"),
|
||||
};
|
||||
var list = query;
|
||||
if (!string.IsNullOrWhiteSpace(query.Search))
|
||||
{
|
||||
var pattern = "%" + query.Search.Trim().ToLowerInvariant() + "%";
|
||||
var parties = await uow.Repository<Party, long>().ListAsync(
|
||||
Query.For<Party>().Where(SqlFragment.Of($"(LOWER(name) LIKE {pattern} OR LOWER(code) LIKE {pattern})")).Take(500), cancellationToken).ConfigureAwait(false);
|
||||
var any = new List<SqlFragment>
|
||||
{
|
||||
SqlFragment.Of($"LOWER(document_number) LIKE {pattern}"),
|
||||
SqlFragment.Of($"LOWER(external_reference) LIKE {pattern}"),
|
||||
};
|
||||
if (parties.Items.Count > 0)
|
||||
{
|
||||
any.Add(SqlFragment.Literal("party_id IN (") + SqlFragment.Join(", ", parties.Items.Select(p => SqlFragment.Parameter(p.Id))) + SqlFragment.Literal(")"));
|
||||
}
|
||||
|
||||
conditions.Add(SqlFragment.Join(" OR ", any).Parenthesize());
|
||||
list = query with { Search = null };
|
||||
}
|
||||
|
||||
var page = await DocumentStores.Of(family).ListAsync(uow, list, conditions, cancellationToken).ConfigureAwait(false);
|
||||
return new ListPage<DocumentRow>(await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false), page.Total, page.Totals);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Proposes the values of a party on a draft (SPEC §11.3): destination, price list, payment, bank, agent, carrier,
|
||||
/// warehouse, currency, split payment, stamp duty, withholding and social security; the VAT code of the lines when
|
||||
/// the party has its own (declaration of intent, exemption).
|
||||
/// </summary>
|
||||
/// <param name="actor">Who edits.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The document, changed in place.</param>
|
||||
/// <param name="partyId">The party; none clears it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task ApplyPartyAsync(Actor actor, string companyCode, DocumentRecord record, long? partyId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var behavior = DocumentBehaviors.Of(record.Header.Kind);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var header = record.Header;
|
||||
header.PartyId = partyId;
|
||||
header.DestinationId = null;
|
||||
if (partyId is not { } id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var party = await uow.Repository<Party, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("party.not-found");
|
||||
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == id), cancellationToken).ConfigureAwait(false);
|
||||
header.CurrencyCode = party.CurrencyCode;
|
||||
header.SalespersonId = party.SalespersonId ?? header.SalespersonId;
|
||||
if (behavior.Direction == DocumentDirection.Sale)
|
||||
{
|
||||
var terms = await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == id), cancellationToken).ConfigureAwait(false);
|
||||
header.PriceListId = terms?.PriceListId;
|
||||
header.PaymentTermId = terms?.PaymentTermId ?? header.PaymentTermId;
|
||||
header.BankAccountId = terms?.CompanyBankAccountId ?? header.BankAccountId;
|
||||
header.CarrierId = terms?.CarrierId ?? header.CarrierId;
|
||||
header.ShippingTermId = terms?.ShippingTermId ?? header.ShippingTermId;
|
||||
header.WarehouseId = terms?.WarehouseId ?? header.WarehouseId;
|
||||
var addresses = await uow.Repository<PartyAddress, long>()
|
||||
.ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id && a.Kind == PartyAddressKind.Delivery), cancellationToken).ConfigureAwait(false);
|
||||
header.DestinationId = (addresses.Items.FirstOrDefault(a => a.IsDefault) ?? (addresses.Items.Count == 1 ? addresses.Items[0] : null))?.Id;
|
||||
if (header.BankAccountId is null)
|
||||
{
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
header.BankAccountId = profile?.DefaultBankAccountId;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var terms = await uow.Repository<PartyPurchaseTerms, long>().FindAsync(Query.For<PartyPurchaseTerms>().Where(t => t.PartyId == id), cancellationToken).ConfigureAwait(false);
|
||||
header.PaymentTermId = terms?.PaymentTermId ?? header.PaymentTermId;
|
||||
header.ShippingTermId = terms?.ShippingTermId ?? header.ShippingTermId;
|
||||
}
|
||||
|
||||
header.PaymentMethodId = header.PaymentTermId is { } termId
|
||||
? (await uow.Repository<PaymentTerm, long>().GetAsync(termId, cancellationToken).ConfigureAwait(false))?.PaymentMethodId
|
||||
: null;
|
||||
header.SplitPayment = fiscal?.SplitPayment ?? false;
|
||||
header.StampDutyCharged = fiscal?.StampDutyCharged ?? true;
|
||||
header.Exigibility = fiscal?.Exigibility?.Trim().ToUpperInvariant() switch
|
||||
{
|
||||
"D" => TaxExigibility.Deferred,
|
||||
"S" => TaxExigibility.SplitPayment,
|
||||
_ => null,
|
||||
};
|
||||
var withholding = fiscal is { Withholding: true } && behavior.Kind != DocumentKind.DeliveryNote;
|
||||
header.WithholdingRate = withholding ? fiscal!.WithholdingRate ?? 20m : null;
|
||||
header.WithholdingBasePercent = 100m;
|
||||
header.WithholdingType = withholding ? "RT01" : null;
|
||||
header.WithholdingReason = withholding ? fiscal!.WithholdingReason ?? "A" : null;
|
||||
header.SocialSecurityFund = string.IsNullOrWhiteSpace(fiscal?.PensionFund) ? null : fiscal.PensionFund;
|
||||
header.SocialSecurityRate = header.SocialSecurityFund is null ? null : fiscal!.PensionFundRate;
|
||||
header.SocialSecurityWithheld = header.SocialSecurityFund == "TC22";
|
||||
header.EnasarcoRate = behavior.Direction == DocumentDirection.Purchase && fiscal is { Enasarco: true } ? 8.5m : null;
|
||||
|
||||
if (PartyTaxCode(fiscal, header.DocumentDate) is { } taxCode)
|
||||
{
|
||||
foreach (var line in record.Lines.Where(l => l.Kind != DocumentLineKind.Description))
|
||||
{
|
||||
line.TaxCodeId = taxCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills a line from an item: description, unit, VAT, price and discounts (net price of the party, list, base list,
|
||||
/// item) and quantity one when empty.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who edits.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The document.</param>
|
||||
/// <param name="line">The line, changed in place.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FillLineAsync(Actor actor, string companyCode, DocumentRecord record, DocumentLine line, long itemId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
ArgumentNullException.ThrowIfNull(line);
|
||||
var behavior = DocumentBehaviors.Of(record.Header.Kind);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var item = await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
|
||||
line.Kind = DocumentLineKind.Item;
|
||||
line.ItemId = item.Id;
|
||||
line.Description = item.Description;
|
||||
line.UnitOfMeasureId = item.UnitOfMeasureId;
|
||||
if (line.Quantity == 0m)
|
||||
{
|
||||
line.Quantity = 1m;
|
||||
}
|
||||
|
||||
PartyFiscal? fiscal = null;
|
||||
if (record.Header.PartyId is { } partyId)
|
||||
{
|
||||
fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == partyId), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (behavior.Direction == DocumentDirection.Purchase)
|
||||
{
|
||||
line.TaxCodeId = PartyTaxCode(fiscal, record.Header.DocumentDate) ?? item.PurchaseTaxCodeId;
|
||||
var supplier = record.Header.PartyId is { } supplierId
|
||||
? await uow.Repository<ItemSupplier, long>().FindAsync(Query.For<ItemSupplier>().Where(s => s.ItemId == item.Id && s.PartyId == supplierId), cancellationToken).ConfigureAwait(false)
|
||||
: null;
|
||||
line.Price = supplier?.Price ?? item.LastCost ?? item.StandardCost ?? 0m;
|
||||
line.PriceSource = supplier?.Price is not null ? PriceSource.PartyNet : PriceSource.Item;
|
||||
line.DiscountFormula = null;
|
||||
return;
|
||||
}
|
||||
|
||||
line.TaxCodeId = PartyTaxCode(fiscal, record.Header.DocumentDate) ?? item.SalesTaxCodeId;
|
||||
var (price, discounts) = await PriceListService.QuoteAsync(uow, item.Id, record.Header.PartyId, record.Header.PriceListId, record.Header.DocumentDate, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
line.Price = price.Price ?? 0m;
|
||||
line.PriceSource = price.Source;
|
||||
line.DiscountFormula = discounts.Formula;
|
||||
if (price.VatIncluded && !record.Header.PricesIncludeTax && line.TaxCodeId is { } taxId
|
||||
&& await uow.Repository<TaxCode, long>().GetAsync(taxId, cancellationToken).ConfigureAwait(false) is { Rate: > 0m } tax)
|
||||
{
|
||||
// A list with VAT on a document without: the net price, to four decimals like the lists.
|
||||
line.Price = Math.Round(line.Price * 100m / (100m + tax.Rate), 4, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the totals of a document being edited, without saving: line amounts and header totals change in place.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who edits.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The tax summary and installments the save would write.</returns>
|
||||
public async Task<DocumentFigures> PreviewAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var behavior = DocumentBehaviors.Of(record.Header.Kind);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, behavior.ReadPermission, 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);
|
||||
return await DocumentCalculation.ApplyAsync(uow, pack.TaxEngine, behavior, record, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The documents linked to one: the ones it fulfils, the ones that fulfil it, the invoice a note corrects.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The linked documents.</returns>
|
||||
public async Task<IReadOnlyList<LinkedDocument>> LinksAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(record.Header.Kind).ReadPermission, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (record.Header.Id == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var family = record.Family.ToString();
|
||||
var id = record.Header.Id;
|
||||
var links = (await uow.Repository<DocumentLink, long>().ListAsync(
|
||||
Query.For<DocumentLink>().Where(SqlFragment.Of(
|
||||
$"((target_family = {family} AND target_document_id = {id}) OR (source_family = {family} AND source_document_id = {id}))")),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var wanted = new Dictionary<(DocumentFamily, long), (LinkDirection Direction, decimal Quantity)>();
|
||||
foreach (var link in links)
|
||||
{
|
||||
var (key, direction) = link.TargetFamily == record.Family && link.TargetDocumentId == id
|
||||
? ((link.SourceFamily, link.SourceDocumentId), LinkDirection.Source)
|
||||
: ((link.TargetFamily, link.TargetDocumentId), LinkDirection.Target);
|
||||
wanted[key] = (direction, wanted.GetValueOrDefault(key).Quantity + link.Quantity);
|
||||
}
|
||||
|
||||
if (record.Header.RelatedDocumentId is { } related)
|
||||
{
|
||||
wanted.TryAdd((record.Family, related), (LinkDirection.Related, 0m));
|
||||
}
|
||||
|
||||
var notes = await DocumentStores.Of(record.Family).ListAsync(uow, new ListQuery { Limit = 100 },
|
||||
[SqlFragment.Of($"related_document_id = {id}")], cancellationToken).ConfigureAwait(false);
|
||||
foreach (var note in notes.Items)
|
||||
{
|
||||
wanted.TryAdd((record.Family, note.Id), (LinkDirection.Related, 0m));
|
||||
}
|
||||
|
||||
var result = new List<LinkedDocument>();
|
||||
foreach (var group in wanted.GroupBy(w => w.Key.Item1))
|
||||
{
|
||||
var headers = await DocumentStores.Of(group.Key).ManyAsync(uow, [.. group.Select(g => g.Key.Item2)], cancellationToken).ConfigureAwait(false);
|
||||
foreach (var header in headers)
|
||||
{
|
||||
var (direction, quantity) = wanted[(group.Key, header.Id)];
|
||||
result.Add(new LinkedDocument(group.Key, header.Id, header.Kind, header.DocumentNumber, header.DocumentDate, header.Status, header.TotalAmount,
|
||||
direction, quantity));
|
||||
}
|
||||
}
|
||||
|
||||
return [.. result.OrderBy(r => r.Direction).ThenBy(r => r.Date).ThenBy(r => r.DocumentNumber, StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The confirmed documents of some kinds with something left to fulfil, for a party or for all, up to a date: what
|
||||
/// a new delivery note can take from the orders, or a deferred invoice from the delivery notes.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family of the sources.</param>
|
||||
/// <param name="kinds">The kinds of the sources.</param>
|
||||
/// <param name="partyId">The party; all when empty.</param>
|
||||
/// <param name="from">The first date; none when empty.</param>
|
||||
/// <param name="to">The last date; none when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents, by party and date.</returns>
|
||||
public async Task<IReadOnlyList<OpenDocument>> OpenAsync(
|
||||
Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection<DocumentKind> kinds, long? partyId, DateOnly? from, DateOnly? to,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kinds);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DocumentBehaviors.Of(kinds.First()).ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var conditions = new List<SqlFragment>
|
||||
{
|
||||
SqlFragment.Literal("kind IN (") + SqlFragment.Join(", ", kinds.Select(k => SqlFragment.Parameter(k.ToString()))) + SqlFragment.Literal(")"),
|
||||
SqlFragment.Of($"status IN ({nameof(DocumentStatus.Confirmed)}, {nameof(DocumentStatus.PartiallyFulfilled)})"),
|
||||
};
|
||||
if (partyId is { } party)
|
||||
{
|
||||
conditions.Add(SqlFragment.Of($"party_id = {party}"));
|
||||
}
|
||||
|
||||
if (from is { } first)
|
||||
{
|
||||
conditions.Add(SqlFragment.Of($"document_date >= {first}"));
|
||||
}
|
||||
|
||||
if (to is { } last)
|
||||
{
|
||||
conditions.Add(SqlFragment.Of($"document_date <= {last}"));
|
||||
}
|
||||
|
||||
var store = DocumentStores.Of(family);
|
||||
var page = await store.ListAsync(uow, new ListQuery { Limit = ListQuery.MaxLimit, Sort = [new ListSort("date"), new ListSort("number")] }, conditions, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var rows = await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false);
|
||||
var result = new List<OpenDocument>();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var lines = (await store.LinesAsync(uow, row.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.Residual > 0m).ToList();
|
||||
if (lines.Count > 0)
|
||||
{
|
||||
result.Add(new OpenDocument(row, lines));
|
||||
}
|
||||
}
|
||||
|
||||
return [.. result.OrderBy(r => r.Row.PartyName, StringComparer.CurrentCulture).ThenBy(r => r.Row.Date).ThenBy(r => r.Row.DocumentNumber, StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
private static long? PartyTaxCode(PartyFiscal? fiscal, DateOnly date) =>
|
||||
fiscal switch
|
||||
{
|
||||
{ IntentActive: true, IntentTaxCodeId: { } intent } when (fiscal.IntentFrom is null || fiscal.IntentFrom <= date) && (fiscal.IntentTo is null || fiscal.IntentTo >= date) => intent,
|
||||
{ TaxCodeId: { } own } => own,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static async Task<IReadOnlyList<DocumentRow>> RowsAsync(IUnitOfWork uow, DocumentFamily family, IReadOnlyList<DocumentHeader> headers, CancellationToken cancellationToken)
|
||||
{
|
||||
var partyIds = headers.Where(h => h.PartyId is not null).Select(h => h.PartyId!.Value).Distinct().ToList();
|
||||
var parties = partyIds.Count == 0
|
||||
? new Dictionary<long, Party>()
|
||||
: (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(p => p.Id);
|
||||
var typeIds = headers.Select(h => h.DocumentTypeId).Distinct().ToList();
|
||||
var types = typeIds.Count == 0
|
||||
? new Dictionary<long, DocumentType>()
|
||||
: (await uow.Repository<DocumentType, long>().ListAsync(Query.For<DocumentType>().Where(t => typeIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(t => t.Id);
|
||||
return
|
||||
[
|
||||
.. headers.Select(h =>
|
||||
{
|
||||
var party = h.PartyId is { } p ? parties.GetValueOrDefault(p) : null;
|
||||
return new DocumentRow(h.Id, family, h.Kind, types.GetValueOrDefault(h.DocumentTypeId)?.Code ?? string.Empty, h.DocumentNumber, h.DocumentDate, h.PartyId,
|
||||
party?.Code, party?.Name, h.Status, h.TaxableAmount, h.TotalAmount, h.NetAmount, h.ExternalReference, h.DeliveryDate, h.ValidUntil, h.Revision, h.IsDemo);
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,9 @@ public sealed class DocumentRecord
|
||||
|
||||
/// <summary>The lines, in order.</summary>
|
||||
public List<DocumentLine> Lines { get; init; } = [];
|
||||
|
||||
/// <summary>The tax summary and installments written by the last save.</summary>
|
||||
public DocumentFigures Figures { get; init; } = DocumentFigures.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The error codes of the document engine; the interface translates them (<c>Documents.json</c>).</summary>
|
||||
@@ -76,6 +79,12 @@ public static class DocumentErrors
|
||||
|
||||
/// <summary>A closed or cancelled document cannot be fulfilled.</summary>
|
||||
public const string CopySourceNotOpen = "document.copy.source-not-open";
|
||||
|
||||
/// <summary>Error: documents of different parties cannot go into one document.</summary>
|
||||
public const string CopyParties = "document.copy.parties";
|
||||
|
||||
/// <summary>Error: a discount formula that cannot be read.</summary>
|
||||
public const string LineDiscountInvalid = "document.line.discount-invalid";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -89,6 +98,7 @@ public sealed class DocumentEngine
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly FiscalYearService _fiscal;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the engine.</summary>
|
||||
@@ -96,9 +106,12 @@ public sealed class DocumentEngine
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
/// <param name="fiscal">The fiscal calendar (open periods).</param>
|
||||
/// <param name="packs">The fiscal pack of each company (tax rounding, stamp duty).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public DocumentEngine(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, TimeProvider clock)
|
||||
public DocumentEngine(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, CompanyFiscalContext packs, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
_packs = packs;
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
@@ -194,6 +207,7 @@ public sealed class DocumentEngine
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = Company(actor, companyCode);
|
||||
var store = DocumentStores.Of(record.Family);
|
||||
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
long id;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
@@ -221,7 +235,15 @@ public sealed class DocumentEngine
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
if (before is not null && definition.Kind == DocumentKind.Quotation && DocumentStateMachine.IsInForce(header.Status))
|
||||
{
|
||||
// A confirmed quotation that changes is a new revision of the same offer.
|
||||
header.Revision = before.Header.Revision + 1;
|
||||
}
|
||||
|
||||
var figures = await DocumentCalculation.ApplyAsync(uow, pack.TaxEngine, definition.Behavior, record, cancellationToken).ConfigureAwait(false);
|
||||
id = await WriteAsync(uow, store, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await DocumentCalculation.WriteAsync(uow, record.Family, id, figures, cancellationToken).ConfigureAwait(false);
|
||||
if (before is not null && DocumentStateMachine.IsInForce(header.Status))
|
||||
{
|
||||
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
@@ -435,7 +457,13 @@ public sealed class DocumentEngine
|
||||
return null;
|
||||
}
|
||||
|
||||
return new DocumentRecord { Family = family, Header = header, Lines = await store.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false) };
|
||||
return new DocumentRecord
|
||||
{
|
||||
Family = family,
|
||||
Header = header,
|
||||
Lines = await store.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false),
|
||||
Figures = await DocumentCalculation.ReadAsync(uow, family, id, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Checks a document against its definition; <paramref name="before"/> is the stored one.</summary>
|
||||
@@ -487,6 +515,11 @@ public sealed class DocumentEngine
|
||||
errors.Add(field + nameof(DocumentLine.Description) + ":" + DocumentErrors.LineDescriptionRequired);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(line.DiscountFormula) && !DiscountFormula.TryParse(line.DiscountFormula, out _))
|
||||
{
|
||||
errors.Add(field + nameof(DocumentLine.DiscountFormula) + ":" + DocumentErrors.LineDiscountInvalid);
|
||||
}
|
||||
|
||||
if (line.Kind == DocumentLineKind.Item && line.ItemId is null)
|
||||
{
|
||||
errors.Add(field + nameof(DocumentLine.ItemId) + ":" + DocumentErrors.LineItemRequired);
|
||||
@@ -710,6 +743,9 @@ public sealed class DocumentEngine
|
||||
header.Posted = stored.Posted;
|
||||
header.GlEntryId = stored.GlEntryId;
|
||||
header.InstallmentsGenerated = stored.InstallmentsGenerated;
|
||||
header.Printed = stored.Printed;
|
||||
header.Sent = stored.Sent;
|
||||
header.Revision = stored.Revision;
|
||||
header.IsDemo = stored.IsDemo;
|
||||
}
|
||||
|
||||
@@ -728,6 +764,9 @@ public sealed class DocumentEngine
|
||||
header.Posted = false;
|
||||
header.GlEntryId = null;
|
||||
header.InstallmentsGenerated = false;
|
||||
header.Printed = false;
|
||||
header.Sent = false;
|
||||
header.Revision = 0;
|
||||
}
|
||||
|
||||
private static string Company(Actor actor, string companyCode)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
@@ -101,6 +102,15 @@ internal interface IDocumentStore
|
||||
Task RecordAsync(
|
||||
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>A page of headers: the list request, plus the conditions the caller adds (kinds, search on parties).</summary>
|
||||
Task<ListPage<DocumentHeader>> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList<SqlFragment> conditions, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Headers by id.</summary>
|
||||
Task<IReadOnlyList<DocumentHeader>> ManyAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Lines by id.</summary>
|
||||
Task<IReadOnlyList<DocumentLine>> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The store of one family.</summary>
|
||||
@@ -168,6 +178,73 @@ internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, strin
|
||||
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
|
||||
CancellationToken cancellationToken) =>
|
||||
audit.RecordAsync(uow, action, id, (THeader?)before, (THeader?)after, userName, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ListPage<DocumentHeader>> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList<SqlFragment> conditions, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = Query.For<THeader>();
|
||||
foreach (var condition in conditions)
|
||||
{
|
||||
query = query.Where(condition);
|
||||
}
|
||||
|
||||
var fields = DocumentListFields<THeader>.Fields;
|
||||
var page = await uow.Repository<THeader, long>().ListAsync(fields.Apply(query, list), cancellationToken).ConfigureAwait(false);
|
||||
return new ListPage<DocumentHeader>([.. page.Items], page.TotalCount, new Dictionary<string, decimal>());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<DocumentHeader>> ManyAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var list = ids.ToList();
|
||||
var rows = await uow.Repository<THeader, long>().ListAsync(Query.For<THeader>().Where(h => list.Contains(h.Id)), cancellationToken).ConfigureAwait(false);
|
||||
return [.. rows.Items];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<DocumentLine>> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection<long> ids, CancellationToken cancellationToken)
|
||||
{
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var list = ids.ToList();
|
||||
var rows = await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(l => list.Contains(l.Id)), cancellationToken).ConfigureAwait(false);
|
||||
return [.. rows.Items];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The fields of the document radars (ADR 0032): the same for every family.</summary>
|
||||
/// <typeparam name="THeader">The header.</typeparam>
|
||||
internal static class DocumentListFields<THeader>
|
||||
where THeader : DocumentHeader
|
||||
{
|
||||
/// <summary>The fields.</summary>
|
||||
public static ListFields<THeader> Fields { get; } = new ListFields<THeader>()
|
||||
.Add("number", h => h.Number)
|
||||
.Add("documentNumber", h => h.DocumentNumber, searchable: true)
|
||||
.Add("date", h => h.DocumentDate)
|
||||
.Add("year", h => h.Year)
|
||||
.Add("kind", h => h.Kind)
|
||||
.Add("type", h => h.DocumentTypeId)
|
||||
.Add("status", h => h.Status)
|
||||
.Add("party", h => h.PartyId)
|
||||
.Add("reference", h => h.ExternalReference, searchable: true)
|
||||
.Add("salesperson", h => h.SalespersonId)
|
||||
.Add("taxable", h => h.TaxableAmount, total: true)
|
||||
.Add("tax", h => h.TaxAmount, total: true)
|
||||
.Add("total", h => h.TotalAmount, total: true)
|
||||
.Add("net", h => h.NetAmount, total: true)
|
||||
.Add("delivery", h => h.DeliveryDate)
|
||||
.Add("validUntil", h => h.ValidUntil)
|
||||
.Add("demo", h => h.IsDemo)
|
||||
.OrderByDefault(new ListSort("date", Descending: true), new ListSort("number", Descending: true));
|
||||
}
|
||||
|
||||
/// <summary>The stores of the six families.</summary>
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>The VAT of a line, from its tax code.</summary>
|
||||
/// <param name="TaxCodeId">The tax code.</param>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="Nature">The nature of operations without VAT.</param>
|
||||
/// <param name="Exigibility">When the VAT becomes due.</param>
|
||||
/// <param name="NonDeductiblePercent">The non-deductible share (purchases).</param>
|
||||
/// <param name="LegalReference">The law printed for operations without VAT.</param>
|
||||
public sealed record TotalsTax(
|
||||
long? TaxCodeId,
|
||||
decimal Rate,
|
||||
string? Nature = null,
|
||||
TaxExigibility Exigibility = TaxExigibility.Immediate,
|
||||
decimal NonDeductiblePercent = 0m,
|
||||
string? LegalReference = null);
|
||||
|
||||
/// <summary>A line as the calculator sees it.</summary>
|
||||
/// <param name="Kind">The kind of line.</param>
|
||||
/// <param name="Quantity">The quantity (expenses and discounts without quantity count as one).</param>
|
||||
/// <param name="Price">The unit price, with VAT when the document's prices include it.</param>
|
||||
/// <param name="DiscountFormula">The discounts, such as <c>10+5</c>.</param>
|
||||
/// <param name="Tax">The VAT; lines without it are left out of the summary.</param>
|
||||
/// <param name="WithholdingExcluded">The line is out of the withholding and of the social security contribution.</param>
|
||||
public sealed record TotalsLine(
|
||||
DocumentLineKind Kind,
|
||||
decimal Quantity,
|
||||
decimal Price,
|
||||
string? DiscountFormula,
|
||||
TotalsTax? Tax,
|
||||
bool WithholdingExcluded = false);
|
||||
|
||||
/// <summary>The settings of the document that change its totals.</summary>
|
||||
public sealed record TotalsOptions
|
||||
{
|
||||
/// <summary>The prices include VAT: the taxable amount is computed back from each VAT group.</summary>
|
||||
public bool PricesIncludeTax { get; init; }
|
||||
|
||||
/// <summary>The discount on the goods (not on expenses), such as <c>5</c> or <c>10+5</c>.</summary>
|
||||
public string? FooterDiscount { get; init; }
|
||||
|
||||
/// <summary>The exigibility of the whole document (cash basis, deferred), when not the one of the tax codes.</summary>
|
||||
public TaxExigibility? Exigibility { get; init; }
|
||||
|
||||
/// <summary>Split payment: the VAT is paid by the customer to the State.</summary>
|
||||
public bool SplitPayment { get; init; }
|
||||
|
||||
/// <summary>The document can carry the stamp duty (invoices and notes).</summary>
|
||||
public bool StampDutyApplies { get; init; }
|
||||
|
||||
/// <summary>The stamp duty is added to the total.</summary>
|
||||
public bool StampDutyCharged { get; init; }
|
||||
|
||||
/// <summary>The withholding rate, percent.</summary>
|
||||
public decimal? WithholdingRate { get; init; }
|
||||
|
||||
/// <summary>The share of the amount the withholding applies to, percent.</summary>
|
||||
public decimal WithholdingBasePercent { get; init; } = 100m;
|
||||
|
||||
/// <summary>The social security contribution rate, percent.</summary>
|
||||
public decimal? SocialSecurityRate { get; init; }
|
||||
|
||||
/// <summary>The VAT of the contribution; the one of the first taxed line when empty.</summary>
|
||||
public TotalsTax? SocialSecurityTax { get; init; }
|
||||
|
||||
/// <summary>The contribution is part of the withholding base.</summary>
|
||||
public bool SocialSecurityWithheld { get; init; }
|
||||
|
||||
/// <summary>The ENASARCO rate withheld, percent.</summary>
|
||||
public decimal? EnasarcoRate { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A line of the computed tax summary.</summary>
|
||||
/// <param name="Tax">The VAT of the group, with the exigibility of the document.</param>
|
||||
/// <param name="Taxable">The taxable amount.</param>
|
||||
/// <param name="TaxAmount">The VAT.</param>
|
||||
/// <param name="NonDeductibleTax">The non-deductible part of the VAT.</param>
|
||||
public sealed record TotalsSummaryLine(TotalsTax Tax, decimal Taxable, decimal TaxAmount, decimal NonDeductibleTax);
|
||||
|
||||
/// <summary>The totals of a document.</summary>
|
||||
/// <param name="LineAmounts">The amount of each line (quantity × price less its discounts), in the order given.</param>
|
||||
/// <param name="Summary">The tax summary, by rate (highest first).</param>
|
||||
/// <param name="Expenses">The total of the expense lines.</param>
|
||||
/// <param name="FooterDiscountAmount">What the footer discount took off.</param>
|
||||
/// <param name="SocialSecurity">The social security contribution.</param>
|
||||
/// <param name="Taxable">The taxable amount.</param>
|
||||
/// <param name="Tax">The VAT.</param>
|
||||
/// <param name="StampDuty">The stamp duty due (charged or not).</param>
|
||||
/// <param name="Total">The total of the document.</param>
|
||||
/// <param name="Withholding">The withholding tax.</param>
|
||||
/// <param name="Enasarco">The ENASARCO contribution withheld.</param>
|
||||
/// <param name="SplitPaymentTax">The VAT the customer pays to the State.</param>
|
||||
/// <param name="Net">The amount to pay.</param>
|
||||
public sealed record DocumentTotals(
|
||||
IReadOnlyList<decimal> LineAmounts,
|
||||
IReadOnlyList<TotalsSummaryLine> Summary,
|
||||
decimal Expenses,
|
||||
decimal FooterDiscountAmount,
|
||||
decimal SocialSecurity,
|
||||
decimal Taxable,
|
||||
decimal Tax,
|
||||
decimal StampDuty,
|
||||
decimal Total,
|
||||
decimal Withholding,
|
||||
decimal Enasarco,
|
||||
decimal SplitPaymentTax,
|
||||
decimal Net);
|
||||
|
||||
/// <summary>
|
||||
/// The totals of a document (SPEC §11.3, issue #48): line amount = quantity × price × (1 − d1)(1 − d2)… rounded to the
|
||||
/// cent; footer discount on the goods; tax summary per VAT code with the tax computed on the total of each group
|
||||
/// (FatturaPA <c>DatiRiepilogo</c>); social security contribution with its own VAT; stamp duty; withholding, ENASARCO
|
||||
/// and split payment taken off the amount to pay.
|
||||
/// </summary>
|
||||
public static class DocumentTotalsCalculator
|
||||
{
|
||||
/// <summary>Computes the totals.</summary>
|
||||
/// <param name="lines">The lines.</param>
|
||||
/// <param name="options">The settings of the document.</param>
|
||||
/// <param name="engine">The country's rounding and stamp duty rules.</param>
|
||||
/// <returns>The totals.</returns>
|
||||
public static DocumentTotals Compute(IReadOnlyList<TotalsLine> lines, TotalsOptions options, ITaxEngine engine)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(engine);
|
||||
var footer = Factor(options.FooterDiscount);
|
||||
var amounts = new decimal[lines.Count];
|
||||
var groups = new List<Group>();
|
||||
decimal beforeFooter = 0m, afterFooter = 0m, expenses = 0m, withholdingBase = 0m;
|
||||
TotalsTax? firstTax = null;
|
||||
for (var i = 0; i < lines.Count; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
if (line.Kind == DocumentLineKind.Description)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var quantity = line.Kind is DocumentLineKind.Expense or DocumentLineKind.Discount && line.Quantity == 0m ? 1m : line.Quantity;
|
||||
var raw = quantity * line.Price * Factor(line.DiscountFormula);
|
||||
if (line.Kind == DocumentLineKind.Discount)
|
||||
{
|
||||
raw = -Math.Abs(raw);
|
||||
}
|
||||
|
||||
amounts[i] = engine.Round(raw);
|
||||
var net = amounts[i];
|
||||
if (line.Kind == DocumentLineKind.Expense)
|
||||
{
|
||||
expenses += net;
|
||||
}
|
||||
else if (footer != 1m)
|
||||
{
|
||||
net = engine.Round(raw * footer);
|
||||
beforeFooter += amounts[i];
|
||||
afterFooter += net;
|
||||
}
|
||||
|
||||
if (!line.WithholdingExcluded)
|
||||
{
|
||||
withholdingBase += net;
|
||||
}
|
||||
|
||||
if (line.Tax is { } tax)
|
||||
{
|
||||
firstTax ??= tax.Rate > 0m ? tax : null;
|
||||
var group = GroupOf(groups, tax);
|
||||
if (options.PricesIncludeTax)
|
||||
{
|
||||
group.Gross += net;
|
||||
}
|
||||
else
|
||||
{
|
||||
group.Net += net;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var socialSecurity = 0m;
|
||||
if (options.SocialSecurityRate is > 0m and var rate)
|
||||
{
|
||||
socialSecurity = engine.Round(withholdingBase * rate / 100m);
|
||||
if ((options.SocialSecurityTax ?? firstTax ?? groups.FirstOrDefault()?.Tax) is { } tax)
|
||||
{
|
||||
GroupOf(groups, tax).Net += socialSecurity;
|
||||
}
|
||||
}
|
||||
|
||||
var summary = groups
|
||||
.Select(g => Summarize(g, options, engine))
|
||||
.OrderByDescending(s => s.Tax.Rate)
|
||||
.ThenBy(s => s.Tax.Nature, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
var taxable = summary.Sum(s => s.Taxable);
|
||||
var taxAmount = summary.Sum(s => s.TaxAmount);
|
||||
var stamp = 0m;
|
||||
if (options.StampDutyApplies)
|
||||
{
|
||||
stamp = engine.AssessStampDuty(summary.Select(s => new TaxSummaryLine(s.Tax.Rate, s.Tax.Nature, s.Tax.Exigibility,
|
||||
s.Tax.NonDeductiblePercent, s.Taxable, s.TaxAmount, s.NonDeductibleTax))).Amount;
|
||||
}
|
||||
|
||||
var total = taxable + taxAmount + (options.StampDutyCharged ? stamp : 0m);
|
||||
var withholding = options.WithholdingRate is > 0m and var withholdingRate
|
||||
? engine.Round((withholdingBase + (options.SocialSecurityWithheld ? socialSecurity : 0m)) * options.WithholdingBasePercent / 100m * withholdingRate / 100m)
|
||||
: 0m;
|
||||
var enasarco = options.EnasarcoRate is > 0m and var enasarcoRate ? engine.Round(withholdingBase * enasarcoRate / 100m) : 0m;
|
||||
var split = summary.Where(s => s.Tax.Exigibility == TaxExigibility.SplitPayment).Sum(s => s.TaxAmount);
|
||||
return new DocumentTotals(amounts, summary, expenses, beforeFooter - afterFooter, socialSecurity, taxable, taxAmount, stamp, total,
|
||||
withholding, enasarco, split, total - withholding - enasarco - split);
|
||||
}
|
||||
|
||||
/// <summary>The factor of a discount formula: 10+5 is 0.855; an empty or invalid formula is 1.</summary>
|
||||
/// <param name="formula">The formula.</param>
|
||||
/// <returns>The factor.</returns>
|
||||
public static decimal Factor(string? formula) =>
|
||||
DiscountFormula.TryParse(formula, out var steps) ? steps.Aggregate(1m, (left, step) => left * (1m - (step / 100m))) : 1m;
|
||||
|
||||
private static Group GroupOf(List<Group> groups, TotalsTax tax)
|
||||
{
|
||||
var group = groups.Find(g => g.Tax.TaxCodeId == tax.TaxCodeId && g.Tax.Rate == tax.Rate && g.Tax.Nature == tax.Nature);
|
||||
if (group is null)
|
||||
{
|
||||
group = new Group(tax);
|
||||
groups.Add(group);
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
private static TotalsSummaryLine Summarize(Group group, TotalsOptions options, ITaxEngine engine)
|
||||
{
|
||||
var tax = group.Tax;
|
||||
var exigibility = tax.Rate == 0m ? tax.Exigibility
|
||||
: options.SplitPayment ? TaxExigibility.SplitPayment
|
||||
: options.Exigibility ?? tax.Exigibility;
|
||||
var grossTaxable = group.Gross == 0m ? 0m : engine.Round(group.Gross * 100m / (100m + tax.Rate));
|
||||
var taxable = grossTaxable + group.Net;
|
||||
var amount = group.Gross - grossTaxable + engine.ComputeTax(group.Net, tax.Rate);
|
||||
return new TotalsSummaryLine(tax with { Exigibility = exigibility }, taxable, amount, engine.Round(amount * tax.NonDeductiblePercent / 100m));
|
||||
}
|
||||
|
||||
private sealed class Group(TotalsTax tax)
|
||||
{
|
||||
public TotalsTax Tax { get; } = tax;
|
||||
|
||||
public decimal Net { get; set; }
|
||||
|
||||
public decimal Gross { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>An installment of payment terms.</summary>
|
||||
/// <param name="Days">Days from the document date.</param>
|
||||
/// <param name="EndOfMonth">Move to the end of that month.</param>
|
||||
/// <param name="FixedDay">A fixed day: of the next month after the end-of-month move, else the next such day.</param>
|
||||
/// <param name="Percent">The share of the amount, percent.</param>
|
||||
public sealed record InstallmentRule(int Days, bool EndOfMonth, int? FixedDay, decimal Percent);
|
||||
|
||||
/// <summary>Months without due dates (mesi esclusi): a due date in them moves to a day of the next month.</summary>
|
||||
/// <param name="First">The first month (1-12).</param>
|
||||
/// <param name="Second">The second month.</param>
|
||||
/// <param name="Day">The day of the next month.</param>
|
||||
public sealed record ExcludedMonths(int? First, int? Second, int Day = 10)
|
||||
{
|
||||
/// <summary>Whether a month is excluded.</summary>
|
||||
/// <param name="month">The month.</param>
|
||||
/// <returns>Whether it is.</returns>
|
||||
public bool Contains(int month) => First == month || Second == month;
|
||||
}
|
||||
|
||||
/// <summary>A computed installment.</summary>
|
||||
/// <param name="Number">The order, from 1.</param>
|
||||
/// <param name="DueDate">The due date.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
public sealed record InstallmentDue(int Number, DateOnly DueDate, decimal Amount);
|
||||
|
||||
/// <summary>
|
||||
/// The installments of a document from its payment terms (SPEC §11.3, issue #48): days, end of month, fixed day,
|
||||
/// excluded months, percentages, all the VAT on the first installment; the rounding goes on the last one.
|
||||
/// </summary>
|
||||
public static class InstallmentGenerator
|
||||
{
|
||||
/// <summary>Computes the installments.</summary>
|
||||
/// <param name="date">The document date.</param>
|
||||
/// <param name="amount">The amount to pay.</param>
|
||||
/// <param name="tax">The VAT included in <paramref name="amount"/> (for <paramref name="vatOnFirst"/>).</param>
|
||||
/// <param name="rules">The installments of the terms; none means one installment on the document date.</param>
|
||||
/// <param name="vatOnFirst">All the VAT is paid with the first installment.</param>
|
||||
/// <param name="excluded">The months without due dates.</param>
|
||||
/// <param name="round">Rounding to the cent.</param>
|
||||
/// <returns>The installments, empty for a zero amount.</returns>
|
||||
public static IReadOnlyList<InstallmentDue> Generate(
|
||||
DateOnly date, decimal amount, decimal tax, IReadOnlyList<InstallmentRule> rules, bool vatOnFirst, ExcludedMonths? excluded, Func<decimal, decimal> round)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rules);
|
||||
ArgumentNullException.ThrowIfNull(round);
|
||||
if (amount == 0m)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
if (rules.Count == 0)
|
||||
{
|
||||
return [new InstallmentDue(1, Move(date, excluded), amount)];
|
||||
}
|
||||
|
||||
var share = vatOnFirst && rules.Count > 1 ? tax : 0m;
|
||||
var spread = amount - share;
|
||||
var percents = rules.Sum(r => r.Percent);
|
||||
var result = new List<InstallmentDue>(rules.Count);
|
||||
var assigned = 0m;
|
||||
for (var i = 0; i < rules.Count; i++)
|
||||
{
|
||||
var rule = rules[i];
|
||||
var part = i == rules.Count - 1
|
||||
? spread - assigned
|
||||
: round(spread * (percents == 0m ? 1m / rules.Count : rule.Percent / percents));
|
||||
assigned += part;
|
||||
result.Add(new InstallmentDue(i + 1, DueDate(date, rule, excluded), part + (i == 0 ? share : 0m)));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The due date of an installment.</summary>
|
||||
/// <param name="date">The document date.</param>
|
||||
/// <param name="rule">The installment.</param>
|
||||
/// <param name="excluded">The months without due dates.</param>
|
||||
/// <returns>The due date.</returns>
|
||||
public static DateOnly DueDate(DateOnly date, InstallmentRule rule, ExcludedMonths? excluded)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
var due = date.AddDays(rule.Days);
|
||||
if (rule.EndOfMonth)
|
||||
{
|
||||
due = new DateOnly(due.Year, due.Month, DateTime.DaysInMonth(due.Year, due.Month));
|
||||
}
|
||||
|
||||
if (rule.FixedDay is { } day and >= 1 and <= 31)
|
||||
{
|
||||
due = rule.EndOfMonth || due.Day > day ? Day(due.AddMonths(1), day) : Day(due, day);
|
||||
}
|
||||
|
||||
return Move(due, excluded);
|
||||
}
|
||||
|
||||
private static DateOnly Move(DateOnly due, ExcludedMonths? excluded)
|
||||
{
|
||||
for (var guard = 0; excluded is not null && excluded.Contains(due.Month) && guard < 12; guard++)
|
||||
{
|
||||
due = Day(due.AddMonths(1), excluded.Day);
|
||||
}
|
||||
|
||||
return due;
|
||||
}
|
||||
|
||||
private static DateOnly Day(DateOnly month, int day) =>
|
||||
new(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month)));
|
||||
}
|
||||
@@ -233,3 +233,16 @@ public enum DocumentLineKind
|
||||
/// <summary>A discount, premium or allowance.</summary>
|
||||
Discount = 4,
|
||||
}
|
||||
|
||||
/// <summary>Who carries the goods (delivery note: trasporto a cura del).</summary>
|
||||
public enum TransportResponsibility
|
||||
{
|
||||
/// <summary>The sender (mittente).</summary>
|
||||
Sender = 0,
|
||||
|
||||
/// <summary>The recipient (destinatario).</summary>
|
||||
Recipient = 1,
|
||||
|
||||
/// <summary>A carrier (vettore).</summary>
|
||||
Carrier = 2,
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Core.Documents;
|
||||
|
||||
@@ -150,6 +151,69 @@ public abstract class DocumentHeader : Entity<long>, IDemoMarkable
|
||||
/// <summary>The amount to pay.</summary>
|
||||
public decimal NetAmount { get; set; }
|
||||
|
||||
/// <summary>The prices of the lines include VAT: the taxable amount is computed back from them.</summary>
|
||||
public bool PricesIncludeTax { get; set; }
|
||||
|
||||
/// <summary>The amount taken off the lines by <see cref="FooterDiscount"/>.</summary>
|
||||
public decimal FooterDiscountAmount { get; set; }
|
||||
|
||||
/// <summary>When the VAT of the document becomes due, when not the one of its tax codes (split payment, cash basis).</summary>
|
||||
public TaxExigibility? Exigibility { get; set; }
|
||||
|
||||
/// <summary>Split payment: the public administration pays the VAT to the State, not to the company.</summary>
|
||||
public bool SplitPayment { get; set; }
|
||||
|
||||
/// <summary>The stamp duty is charged to the customer (added to the total).</summary>
|
||||
public bool StampDutyCharged { get; set; }
|
||||
|
||||
/// <summary>The withholding tax rate, percent; none when the document has no withholding.</summary>
|
||||
public decimal? WithholdingRate { get; set; }
|
||||
|
||||
/// <summary>The share of the amount the withholding is computed on, percent (100 for fees, 50 or 20 for agents).</summary>
|
||||
public decimal WithholdingBasePercent { get; set; } = 100m;
|
||||
|
||||
/// <summary>The withholding type of the e-invoice, such as <c>RT01</c>.</summary>
|
||||
public string? WithholdingType { get; set; }
|
||||
|
||||
/// <summary>The payment reason of the withholding (e-invoice), such as <c>A</c>.</summary>
|
||||
public string? WithholdingReason { get; set; }
|
||||
|
||||
/// <summary>The social security fund (cassa previdenza) of the e-invoice, such as <c>TC22</c>.</summary>
|
||||
public string? SocialSecurityFund { get; set; }
|
||||
|
||||
/// <summary>The contribution rate of the fund, percent.</summary>
|
||||
public decimal? SocialSecurityRate { get; set; }
|
||||
|
||||
/// <summary>The VAT code of the contribution; the one of the first line when empty.</summary>
|
||||
public long? SocialSecurityTaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The contribution is subject to the withholding tax (INPS 4%).</summary>
|
||||
public bool SocialSecurityWithheld { get; set; }
|
||||
|
||||
/// <summary>The ENASARCO rate withheld from the commissions of an agent, percent.</summary>
|
||||
public decimal? EnasarcoRate { get; set; }
|
||||
|
||||
/// <summary>The ENASARCO contribution withheld.</summary>
|
||||
public decimal EnasarcoAmount { get; set; }
|
||||
|
||||
/// <summary>The tender code (CIG) of a public contract.</summary>
|
||||
public string? Cig { get; set; }
|
||||
|
||||
/// <summary>The project code (CUP) of a public contract.</summary>
|
||||
public string? Cup { get; set; }
|
||||
|
||||
/// <summary>Who carries the goods (delivery notes, accompanying invoices).</summary>
|
||||
public TransportResponsibility? TransportBy { get; set; }
|
||||
|
||||
/// <summary>The document a credit or debit note corrects, in the same family.</summary>
|
||||
public long? RelatedDocumentId { get; set; }
|
||||
|
||||
/// <summary>The number of the corrected document, also for documents outside Khaemhat.</summary>
|
||||
public string? RelatedNumber { get; set; }
|
||||
|
||||
/// <summary>The date of the corrected document.</summary>
|
||||
public DateOnly? RelatedDate { get; set; }
|
||||
|
||||
/// <summary>The notes printed on the document.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
@@ -236,6 +300,9 @@ public abstract class DocumentLine : Entity<long>
|
||||
/// <summary>The line this one fulfils.</summary>
|
||||
public long? SourceLineId { get; set; }
|
||||
|
||||
/// <summary>The line is left out of the withholding tax and of the social security contribution (expenses paid on behalf).</summary>
|
||||
public bool WithholdingExcluded { get; set; }
|
||||
|
||||
/// <summary>The ledger account (M7).</summary>
|
||||
public string? AccountCode { get; set; }
|
||||
|
||||
@@ -327,3 +394,65 @@ public sealed class DocumentLink : Entity<long>
|
||||
/// <summary>The quantity fulfilled.</summary>
|
||||
public decimal Quantity { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A line of the tax summary of a document (castelletto IVA, <c>document_tax_summaries</c>): one per VAT code,
|
||||
/// written by the totals calculator each time the document is saved.
|
||||
/// </summary>
|
||||
public sealed class DocumentTaxSummary : Entity<long>
|
||||
{
|
||||
/// <summary>The family of the document.</summary>
|
||||
public DocumentFamily Family { get; set; }
|
||||
|
||||
/// <summary>The document.</summary>
|
||||
public long DocumentId { get; set; }
|
||||
|
||||
/// <summary>The VAT code.</summary>
|
||||
public long? TaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The rate in percent.</summary>
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
/// <summary>The nature of operations without VAT.</summary>
|
||||
public string? Nature { get; set; }
|
||||
|
||||
/// <summary>When the VAT becomes due.</summary>
|
||||
public TaxExigibility Exigibility { get; set; }
|
||||
|
||||
/// <summary>The non-deductible share, percent.</summary>
|
||||
public decimal NonDeductiblePercent { get; set; }
|
||||
|
||||
/// <summary>The law printed for operations without VAT.</summary>
|
||||
public string? LegalReference { get; set; }
|
||||
|
||||
/// <summary>The taxable amount.</summary>
|
||||
public decimal Taxable { get; set; }
|
||||
|
||||
/// <summary>The VAT.</summary>
|
||||
public decimal Tax { get; set; }
|
||||
|
||||
/// <summary>The non-deductible part of the VAT.</summary>
|
||||
public decimal NonDeductibleTax { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An installment of a document (<c>document_installments</c>), from its payment terms.</summary>
|
||||
public sealed class DocumentInstallment : Entity<long>
|
||||
{
|
||||
/// <summary>The family of the document.</summary>
|
||||
public DocumentFamily Family { get; set; }
|
||||
|
||||
/// <summary>The document.</summary>
|
||||
public long DocumentId { get; set; }
|
||||
|
||||
/// <summary>The order, from 1.</summary>
|
||||
public int Number { get; set; }
|
||||
|
||||
/// <summary>The due date.</summary>
|
||||
public DateOnly DueDate { get; set; }
|
||||
|
||||
/// <summary>The amount.</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>The payment method.</summary>
|
||||
public long? PaymentMethodId { get; set; }
|
||||
}
|
||||
@@ -339,6 +339,15 @@ public sealed class PartySalesTerms : Entity<long>
|
||||
/// <summary>The day of the month the deferred invoices are issued, if fixed.</summary>
|
||||
public int? InvoiceDay { get; set; }
|
||||
|
||||
/// <summary>A month without due dates (1-12), such as August: they move to the next month.</summary>
|
||||
public int? ExcludedMonth1 { get; set; }
|
||||
|
||||
/// <summary>A second month without due dates, such as December.</summary>
|
||||
public int? ExcludedMonth2 { get; set; }
|
||||
|
||||
/// <summary>The day of the next month a due date in an excluded month moves to (10 when empty).</summary>
|
||||
public int? ExcludedMonthsDay { get; set; }
|
||||
|
||||
/// <summary>How the documents are sent.</summary>
|
||||
public DocumentDelivery SendDocuments { get; set; }
|
||||
|
||||
|
||||
@@ -20,6 +20,12 @@ public abstract class DocumentHeaderMap<T> : EntityMap<T>
|
||||
Map(x => x.FooterDiscount).MaxLength(30);
|
||||
Map(x => x.ConfirmedBy).MaxLength(100);
|
||||
Map(x => x.CancelReason).MaxLength(200);
|
||||
Map(x => x.WithholdingType).MaxLength(4);
|
||||
Map(x => x.WithholdingReason).MaxLength(2);
|
||||
Map(x => x.SocialSecurityFund).MaxLength(4);
|
||||
Map(x => x.Cig).MaxLength(15);
|
||||
Map(x => x.Cup).MaxLength(15);
|
||||
Map(x => x.RelatedNumber).MaxLength(30);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,3 +87,22 @@ public sealed class DocumentLinkMap : EntityMap<DocumentLink>
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DocumentLinkMap() => ToTable("document_links");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DocumentTaxSummary"/> to <c>document_tax_summaries</c>.</summary>
|
||||
public sealed class DocumentTaxSummaryMap : EntityMap<DocumentTaxSummary>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DocumentTaxSummaryMap()
|
||||
{
|
||||
ToTable("document_tax_summaries");
|
||||
Map(x => x.Nature).MaxLength(10);
|
||||
Map(x => x.LegalReference).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DocumentInstallment"/> to <c>document_installments</c>.</summary>
|
||||
public sealed class DocumentInstallmentMap : EntityMap<DocumentInstallment>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DocumentInstallmentMap() => ToTable("document_installments");
|
||||
}
|
||||
@@ -5,7 +5,7 @@ namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// The document engine (SPEC §11.3, ADR 0032, issue #47): six families of headers with their lines, the fulfilment
|
||||
/// links, the kind of each document type and the date of the last number of each numerator.
|
||||
/// links, the tax summaries and installments (#48), the kind of each document type and the date of the last number of each numerator.
|
||||
/// </summary>
|
||||
[Migration(20261112_003, "create_documents")]
|
||||
public sealed class M20261112_003_CreateDocuments : IMigration
|
||||
@@ -30,6 +30,12 @@ public sealed class M20261112_003_CreateDocuments : IMigration
|
||||
}
|
||||
|
||||
schema.AlterTable("document_numerators", t => t.Date("last_date"));
|
||||
schema.AlterTable("party_sales_terms", t =>
|
||||
{
|
||||
t.Int32("excluded_month1");
|
||||
t.Int32("excluded_month2");
|
||||
t.Int32("excluded_months_day");
|
||||
});
|
||||
|
||||
Family(schema, "sale_quotations", "sale_quotation_lines");
|
||||
Family(schema, "sale_orders", "sale_order_lines");
|
||||
@@ -53,6 +59,40 @@ public sealed class M20261112_003_CreateDocuments : IMigration
|
||||
t.Index("ix_document_links_source_document", "source_family", "source_document_id");
|
||||
t.Index("ix_document_links_target", "target_family", "target_document_id");
|
||||
});
|
||||
|
||||
schema.CreateTable("document_tax_summaries", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("family", 40).NotNull();
|
||||
t.Int64("document_id").NotNull();
|
||||
t.Int64("tax_code_id");
|
||||
t.Decimal("rate").NotNull();
|
||||
t.String("nature", 10);
|
||||
t.String("exigibility", 40).NotNull();
|
||||
t.Decimal("non_deductible_percent").NotNull().Default(0m);
|
||||
t.String("legal_reference", 100);
|
||||
t.Decimal("taxable").NotNull();
|
||||
t.Decimal("tax").NotNull();
|
||||
t.Decimal("non_deductible_tax").NotNull().Default(0m);
|
||||
t.AuditColumns();
|
||||
t.Index("ix_document_tax_summaries_document", "family", "document_id");
|
||||
t.ForeignKey("fk_document_tax_summaries_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable("document_installments", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("family", 40).NotNull();
|
||||
t.Int64("document_id").NotNull();
|
||||
t.Int32("number").NotNull();
|
||||
t.Date("due_date").NotNull();
|
||||
t.Decimal("amount").NotNull();
|
||||
t.Int64("payment_method_id");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_document_installments_document", "family", "document_id");
|
||||
t.Index("ix_document_installments_due", "due_date");
|
||||
t.ForeignKey("fk_document_installments_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict);
|
||||
});
|
||||
}
|
||||
|
||||
private static void Family(ISchemaBuilder schema, string headers, string lines)
|
||||
@@ -107,6 +147,27 @@ public sealed class M20261112_003_CreateDocuments : IMigration
|
||||
t.Decimal("withholding_amount").NotNull().Default(0m);
|
||||
t.Decimal("social_security_amount").NotNull().Default(0m);
|
||||
t.Decimal("net_amount").NotNull().Default(0m);
|
||||
t.Bool("prices_include_tax").NotNull().Default(false);
|
||||
t.Decimal("footer_discount_amount").NotNull().Default(0m);
|
||||
t.String("exigibility", 40);
|
||||
t.Bool("split_payment").NotNull().Default(false);
|
||||
t.Bool("stamp_duty_charged").NotNull().Default(false);
|
||||
t.Decimal("withholding_rate");
|
||||
t.Decimal("withholding_base_percent").NotNull().Default(100m);
|
||||
t.String("withholding_type", 4);
|
||||
t.String("withholding_reason", 2);
|
||||
t.String("social_security_fund", 4);
|
||||
t.Decimal("social_security_rate");
|
||||
t.Int64("social_security_tax_code_id");
|
||||
t.Bool("social_security_withheld").NotNull().Default(false);
|
||||
t.Decimal("enasarco_rate");
|
||||
t.Decimal("enasarco_amount").NotNull().Default(0m);
|
||||
t.String("cig", 15);
|
||||
t.String("cup", 15);
|
||||
t.String("transport_by", 40);
|
||||
t.Int64("related_document_id");
|
||||
t.String("related_number", 30);
|
||||
t.Date("related_date");
|
||||
t.Text("notes");
|
||||
t.Int64("gl_entry_id");
|
||||
t.Int64("vat_protocol");
|
||||
@@ -135,6 +196,8 @@ public sealed class M20261112_003_CreateDocuments : IMigration
|
||||
t.ForeignKey("fk_" + headers + "_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_" + headers + "_carrier", "carrier_id", "carriers", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_" + headers + "_goods_appearance", "goods_appearance_id", "goods_appearances", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_" + headers + "_social_security_tax_code", "social_security_tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||
t.ForeignKey("fk_" + headers + "_related", "related_document_id", headers, ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
schema.CreateTable(lines, t =>
|
||||
@@ -158,6 +221,7 @@ public sealed class M20261112_003_CreateDocuments : IMigration
|
||||
t.Bool("fulfillment_closed").NotNull().Default(false);
|
||||
t.String("source_family", 40);
|
||||
t.Int64("source_line_id");
|
||||
t.Bool("withholding_excluded").NotNull().Default(false);
|
||||
t.String("account_code", 20);
|
||||
t.Int64("cost_center_id");
|
||||
t.Int64("job_id");
|
||||
|
||||
@@ -223,7 +223,9 @@ public sealed class ExpressionTranslator(IEntityMap map, ISqlDialect dialect)
|
||||
node = convert.Operand;
|
||||
}
|
||||
|
||||
return node is MemberExpression { Member: PropertyInfo property } member && member.Expression == entity
|
||||
// In generic code (T : DocumentHeader) the compiler casts the parameter to the base class before the member.
|
||||
return node is MemberExpression { Member: PropertyInfo property } member
|
||||
&& (member.Expression == entity || member.Expression is UnaryExpression { NodeType: ExpressionType.Convert, Operand: var operand } && operand == entity)
|
||||
? map.FindByProperty(property.Name) ?? throw new NotSupportedException($"{map.EntityType.Name}.{property.Name} is not mapped.")
|
||||
: null;
|
||||
}
|
||||
|
||||
@@ -151,6 +151,7 @@ internal static class KhaemhatServices
|
||||
// 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>();
|
||||
services.AddSingleton<Khaemhat.Application.Documents.DocumentEditor>();
|
||||
services.AddSingleton(typeof(Khaemhat.Application.Documents.DocumentService<,>));
|
||||
|
||||
// Guided import and export (ADR 0031): the entities in the order of the screen.
|
||||
|
||||
@@ -27,7 +27,8 @@
|
||||
"item-required": "Una riga articolo ha bisogno dell'articolo.",
|
||||
"below-fulfilled": "La quantità non può scendere sotto quella già evasa.",
|
||||
"fulfilled-removed": "Una riga già evasa da altri documenti non si può togliere.",
|
||||
"source-invalid": "La riga d'origine non esiste o non può essere evasa da questo documento."
|
||||
"source-invalid": "La riga d'origine non esiste o non può essere evasa da questo documento.",
|
||||
"discount-invalid": "Lo sconto si scrive come percentuali separate da +, ad esempio 10+5."
|
||||
},
|
||||
"cancel": {
|
||||
"reason-required": "Per annullare una fattura indica il motivo.",
|
||||
@@ -36,7 +37,8 @@
|
||||
"copy": {
|
||||
"direction": "Si trasforma solo in un documento della stessa direzione (vendita o acquisto).",
|
||||
"nothing-left": "Non c'è più nulla da evadere.",
|
||||
"source-not-open": "Il documento non è confermato o è chiuso o annullato: non si può evadere."
|
||||
"source-not-open": "Il documento non è confermato o è chiuso o annullato: non si può evadere.",
|
||||
"parties": "I documenti scelti sono di clienti o fornitori diversi: si uniscono solo documenti della stessa controparte."
|
||||
},
|
||||
"number": {
|
||||
"date-before-last": "La data è anteriore a quella dell'ultimo documento numerato: con questo numeratore non sono ammessi documenti fuori sequenza.",
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Italy;
|
||||
|
||||
namespace Khaemhat.Application.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Reference cases of the totals (SPEC §11.3, issue #48): cascaded discounts, footer discount, expenses, tax summary,
|
||||
/// stamp duty, social security and withholding, split payment, prices with VAT, rounding to the cent, installments.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class DocumentTotalsTests
|
||||
{
|
||||
private static readonly ItalianTaxEngine Engine = new();
|
||||
private static readonly TotalsTax Vat22 = new(1, 22m);
|
||||
private static readonly TotalsTax Exempt = new(2, 0m, "N4", LegalReference: "Esente art. 10 DPR 633/72");
|
||||
private static readonly TotalsTax Excluded = new(3, 0m, "N1", LegalReference: "Escluso art. 15 DPR 633/72");
|
||||
|
||||
private static TotalsLine Item(decimal quantity, decimal price, TotalsTax tax, string? discount = null) =>
|
||||
new(DocumentLineKind.Item, quantity, price, discount, tax);
|
||||
|
||||
[TestMethod]
|
||||
public void Invoice_with_discounts_expenses_and_exempt_lines_carries_the_stamp_duty()
|
||||
{
|
||||
var totals = DocumentTotalsCalculator.Compute(
|
||||
[
|
||||
Item(3m, 12.35m, Vat22, "10+5"),
|
||||
Item(1m, 100m, Vat22),
|
||||
new(DocumentLineKind.Description, 0m, 0m, null, null),
|
||||
new(DocumentLineKind.Expense, 0m, 10m, null, Vat22),
|
||||
Item(2m, 50m, Exempt),
|
||||
],
|
||||
new TotalsOptions { StampDutyApplies = true, StampDutyCharged = true },
|
||||
Engine);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 31.68m, 100m, 0m, 10m, 100m }, totals.LineAmounts.ToArray());
|
||||
Assert.HasCount(2, totals.Summary);
|
||||
Assert.AreEqual(141.68m, totals.Summary[0].Taxable);
|
||||
Assert.AreEqual(31.17m, totals.Summary[0].TaxAmount);
|
||||
Assert.AreEqual("N4", totals.Summary[1].Tax.Nature);
|
||||
Assert.AreEqual(100m, totals.Summary[1].Taxable);
|
||||
Assert.AreEqual(241.68m, totals.Taxable);
|
||||
Assert.AreEqual(31.17m, totals.Tax);
|
||||
Assert.AreEqual(10m, totals.Expenses);
|
||||
Assert.AreEqual(2m, totals.StampDuty);
|
||||
Assert.AreEqual(274.85m, totals.Total);
|
||||
Assert.AreEqual(274.85m, totals.Net);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Stamp_duty_not_charged_stays_out_of_the_total_and_below_the_threshold_is_not_due()
|
||||
{
|
||||
var notCharged = DocumentTotalsCalculator.Compute([Item(1m, 100m, Exempt)], new TotalsOptions { StampDutyApplies = true }, Engine);
|
||||
Assert.AreEqual(2m, notCharged.StampDuty);
|
||||
Assert.AreEqual(100m, notCharged.Total);
|
||||
|
||||
var below = DocumentTotalsCalculator.Compute([Item(1m, 77.47m, Exempt)], new TotalsOptions { StampDutyApplies = true, StampDutyCharged = true }, Engine);
|
||||
Assert.AreEqual(0m, below.StampDuty);
|
||||
Assert.AreEqual(77.47m, below.Total);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Footer_discount_applies_to_goods_and_not_to_expenses()
|
||||
{
|
||||
var totals = DocumentTotalsCalculator.Compute(
|
||||
[Item(3m, 12.35m, Vat22, "10+5"), Item(1m, 100m, Vat22), new(DocumentLineKind.Expense, 1m, 10m, null, Vat22)],
|
||||
new TotalsOptions { FooterDiscount = "5" },
|
||||
Engine);
|
||||
|
||||
Assert.AreEqual(31.68m, totals.LineAmounts[0], "the line keeps its own amount");
|
||||
Assert.AreEqual(6.59m, totals.FooterDiscountAmount);
|
||||
Assert.AreEqual(135.09m, totals.Taxable);
|
||||
Assert.AreEqual(29.72m, totals.Tax);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Fee_with_social_security_withheld_and_withholding_tax()
|
||||
{
|
||||
var totals = DocumentTotalsCalculator.Compute(
|
||||
[new(DocumentLineKind.Free, 1m, 1000m, null, Vat22), new(DocumentLineKind.Expense, 1m, 50m, null, Excluded, WithholdingExcluded: true)],
|
||||
new TotalsOptions { SocialSecurityRate = 4m, SocialSecurityWithheld = true, WithholdingRate = 20m },
|
||||
Engine);
|
||||
|
||||
Assert.AreEqual(40m, totals.SocialSecurity);
|
||||
Assert.AreEqual(1040m, totals.Summary[0].Taxable);
|
||||
Assert.AreEqual(228.80m, totals.Tax);
|
||||
Assert.AreEqual(1090m, totals.Taxable);
|
||||
Assert.AreEqual(1318.80m, totals.Total);
|
||||
Assert.AreEqual(208m, totals.Withholding);
|
||||
Assert.AreEqual(1110.80m, totals.Net);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Agent_commissions_withhold_on_half_and_enasarco()
|
||||
{
|
||||
var totals = DocumentTotalsCalculator.Compute(
|
||||
[new(DocumentLineKind.Free, 1m, 2000m, null, Vat22)],
|
||||
new TotalsOptions { WithholdingRate = 23m, WithholdingBasePercent = 50m, EnasarcoRate = 8.5m },
|
||||
Engine);
|
||||
|
||||
Assert.AreEqual(230m, totals.Withholding);
|
||||
Assert.AreEqual(170m, totals.Enasarco);
|
||||
Assert.AreEqual(2440m - 230m - 170m, totals.Net);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Split_payment_leaves_the_vat_out_of_the_amount_to_pay()
|
||||
{
|
||||
var totals = DocumentTotalsCalculator.Compute([Item(1m, 1000m, Vat22)], new TotalsOptions { SplitPayment = true }, Engine);
|
||||
|
||||
Assert.AreEqual(TaxExigibility.SplitPayment, totals.Summary[0].Tax.Exigibility);
|
||||
Assert.AreEqual(1220m, totals.Total);
|
||||
Assert.AreEqual(220m, totals.SplitPaymentTax);
|
||||
Assert.AreEqual(1000m, totals.Net);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Prices_with_vat_are_split_back_per_group_and_discount_lines_subtract()
|
||||
{
|
||||
var gross = DocumentTotalsCalculator.Compute([Item(1m, 122m, Vat22), Item(2m, 10.99m, Vat22)], new TotalsOptions { PricesIncludeTax = true }, Engine);
|
||||
Assert.AreEqual(118.02m, gross.Taxable);
|
||||
Assert.AreEqual(25.96m, gross.Tax);
|
||||
Assert.AreEqual(143.98m, gross.Total);
|
||||
|
||||
var discounted = DocumentTotalsCalculator.Compute([Item(1m, 100m, Vat22), new(DocumentLineKind.Discount, 0m, 10m, null, Vat22)], new TotalsOptions(), Engine);
|
||||
Assert.AreEqual(-10m, discounted.LineAmounts[1]);
|
||||
Assert.AreEqual(90m, discounted.Taxable);
|
||||
Assert.AreEqual(19.80m, discounted.Tax);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Halves_round_away_from_zero_on_lines_and_on_the_tax_of_the_group()
|
||||
{
|
||||
var totals = DocumentTotalsCalculator.Compute([Item(1m, 0.125m, Vat22), Item(1m, 2.125m, Vat22)], new TotalsOptions(), Engine);
|
||||
CollectionAssert.AreEqual(new[] { 0.13m, 2.13m }, totals.LineAmounts.ToArray());
|
||||
Assert.AreEqual(2.26m, totals.Taxable);
|
||||
Assert.AreEqual(0.50m, totals.Tax, "22% of 2.26 is 0.4972, rounded once on the group");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Installments_move_to_end_of_month_and_carry_the_vat_on_the_first()
|
||||
{
|
||||
var dues = InstallmentGenerator.Generate(new DateOnly(2026, 1, 15), 1220m, 220m,
|
||||
[new(30, true, null, 50m), new(60, true, null, 50m)], vatOnFirst: true, null, Engine.Round);
|
||||
|
||||
Assert.HasCount(2, dues);
|
||||
Assert.AreEqual(new DateOnly(2026, 2, 28), dues[0].DueDate);
|
||||
Assert.AreEqual(720m, dues[0].Amount);
|
||||
Assert.AreEqual(new DateOnly(2026, 3, 31), dues[1].DueDate);
|
||||
Assert.AreEqual(500m, dues[1].Amount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Installments_with_fixed_day_excluded_months_and_rounding_on_the_last()
|
||||
{
|
||||
Assert.AreEqual(new DateOnly(2026, 4, 10), InstallmentGenerator.DueDate(new DateOnly(2026, 1, 15), new(60, true, 10, 100m), null));
|
||||
Assert.AreEqual(new DateOnly(2026, 2, 5), InstallmentGenerator.DueDate(new DateOnly(2026, 1, 20), new(0, false, 5, 100m), null));
|
||||
Assert.AreEqual(new DateOnly(2026, 9, 10), InstallmentGenerator.DueDate(new DateOnly(2026, 7, 1), new(60, true, null, 100m), new ExcludedMonths(8, 12)));
|
||||
|
||||
var thirds = InstallmentGenerator.Generate(new DateOnly(2026, 1, 1), 100m, 0m,
|
||||
[new(30, false, null, 33.33m), new(60, false, null, 33.33m), new(90, false, null, 33.34m)], false, null, Engine.Round);
|
||||
CollectionAssert.AreEqual(new[] { 33.33m, 33.33m, 33.34m }, thirds.Select(d => d.Amount).ToArray());
|
||||
|
||||
var single = InstallmentGenerator.Generate(new DateOnly(2026, 8, 3), 50m, 0m, [], false, new ExcludedMonths(8, null, 15), Engine.Round);
|
||||
Assert.AreEqual(new DateOnly(2026, 9, 15), single[0].DueDate);
|
||||
Assert.IsEmpty(InstallmentGenerator.Generate(new DateOnly(2026, 1, 1), 0m, 0m, [], false, null, Engine.Round));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/Khaemhat.Application/Khaemhat.Application.csproj" />
|
||||
<ProjectReference Include="../../src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" />
|
||||
<ProjectReference Include="../../src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -80,7 +80,7 @@ public sealed class MappingTests
|
||||
"items", "item_uoms", "item_barcodes", "item_prices", "item_suppliers", "item_substitutes", "party_item_codes",
|
||||
"sale_quotations", "sale_quotation_lines", "sale_orders", "sale_order_lines", "sale_documents", "sale_document_lines",
|
||||
"purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines",
|
||||
"document_links",
|
||||
"document_links", "document_tax_summaries", "document_installments",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user