diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f9b0e5..162eeef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` 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 diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index d60c272..d60d59f 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -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ì | | | diff --git a/docs/adr/0033-totali-e-scadenze-dei-documenti.md b/docs/adr/0033-totali-e-scadenze-dei-documenti.md new file mode 100644 index 0000000..6eb78f4 --- /dev/null +++ b/docs/adr/0033-totali-e-scadenze-dei-documenti.md @@ -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). diff --git a/src/Khaemhat.Application/Documents/DocumentCalculation.cs b/src/Khaemhat.Application/Documents/DocumentCalculation.cs new file mode 100644 index 0000000..3f301ab --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentCalculation.cs @@ -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; + +/// The totals of a stored document: its tax summary and installments, as written by the last save. +/// The tax summary. +/// The installments. +public sealed record DocumentFigures(IReadOnlyList Summary, IReadOnlyList Installments) +{ + /// No figures. + public static DocumentFigures Empty { get; } = new([], []); +} + +/// +/// Applies and to a document being saved: +/// writes the line amounts and header totals, then replaces its tax summary and installments (issue #48). +/// +internal static class DocumentCalculation +{ + /// Computes the totals of a document in place. + /// The unit of work. + /// The country's tax engine. + /// The behaviour of the document. + /// The document. + /// Cancellation. + /// The tax summary and installments to write once the document has its id. + public static async Task 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(); + 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); + } + + /// Replaces the tax summary and installments of a document. + /// The unit of work. + /// The family. + /// The document. + /// The new rows. + /// Cancellation. + /// A task. + public static async Task WriteAsync(IUnitOfWork uow, DocumentFamily family, long documentId, DocumentFigures figures, CancellationToken cancellationToken) + { + var summaries = uow.Repository(); + var installments = uow.Repository(); + var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}"); + foreach (var old in (await summaries.ListAsync(Query.For().Where(where), cancellationToken).ConfigureAwait(false)).Items) + { + await summaries.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + } + + foreach (var old in (await installments.ListAsync(Query.For().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); + } + } + + /// Reads the tax summary and installments of a document. + /// The unit of work. + /// The family. + /// The document. + /// Cancellation. + /// The rows. + public static async Task 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() + .ListAsync(Query.For().Where(where).OrderByDescending(s => s.Rate), cancellationToken).ConfigureAwait(false); + var installments = await uow.Repository() + .ListAsync(Query.For().Where(where).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false); + return new DocumentFigures(summary.Items, installments.Items); + } + + private static async Task> 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().ListAsync(Query.For().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> InstallmentsAsync( + IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, DocumentTotals totals, CancellationToken cancellationToken) + { + var header = record.Header; + PaymentTerm? term = null; + IReadOnlyList termLines = []; + if (header.PaymentTermId is { } termId) + { + term = await uow.Repository().GetAsync(termId, cancellationToken).ConfigureAwait(false); + termLines = (await uow.Repository() + .ListAsync(Query.For().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() + .FindAsync(Query.For().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 })]; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentCopyService.cs b/src/Khaemhat.Application/Documents/DocumentCopyService.cs index dfe45f1..392e166 100644 --- a/src/Khaemhat.Application/Documents/DocumentCopyService.cs +++ b/src/Khaemhat.Application/Documents/DocumentCopyService.cs @@ -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 /// Cancellation. /// The new draft. /// The copy is not possible. - public async Task CopyAsync( + public Task CopyAsync( Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, IReadOnlyCollection? lineIds = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) => + MergeAsync(actor, companyCode, family, [id], targetTypeCode, null, lineIds, cancellationToken); + + /// + /// 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. + /// + /// Who copies. + /// The company. + /// The family of the sources. + /// The sources, in order. + /// The type of the new document. + /// The date of the new document; today when empty. + /// The lines to copy; all when empty. + /// Cancellation. + /// The new draft. + /// The copy is not possible. + public async Task MergeAsync( + Actor actor, string companyCode, DocumentFamily family, IReadOnlyList ids, string targetTypeCode, DateOnly? date = null, + IReadOnlyCollection? 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(); + 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(); + 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; diff --git a/src/Khaemhat.Application/Documents/DocumentEditor.cs b/src/Khaemhat.Application/Documents/DocumentEditor.cs new file mode 100644 index 0000000..d011826 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentEditor.cs @@ -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; + +/// A document in a radar. +/// The document. +/// The family. +/// The kind. +/// The code of the document type. +/// The number as printed; empty for drafts. +/// The date. +/// The party. +/// The code of the party. +/// The name of the party. +/// The state. +/// The taxable amount. +/// The total. +/// The amount to pay. +/// The reference of the other side. +/// The delivery date. +/// Until when a quotation is valid. +/// The revision of a quotation. +/// Demo data. +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); + +/// A document linked to another one. +/// The family. +/// The document. +/// The kind. +/// The number. +/// The date. +/// The state. +/// The total. +/// Where it stands: before (source), after (fulfils it) or corrected (note). +/// The quantity fulfilled between the two. +public sealed record LinkedDocument( + DocumentFamily Family, long Id, DocumentKind Kind, string? DocumentNumber, DateOnly Date, DocumentStatus Status, decimal Total, + LinkDirection Direction, decimal Quantity); + +/// How a linked document relates to the one shown. +public enum LinkDirection +{ + /// The document shown fulfils it (an order of a delivery note). + Source = 0, + + /// It fulfils the document shown (a delivery note of an order). + Target = 1, + + /// The invoice a note corrects, or a note that corrects the invoice shown. + Related = 2, +} + +/// An open document with something left to fulfil, for the guided fulfilment and the deferred invoicing. +/// The document. +/// The lines with a residual. +public sealed record OpenDocument(DocumentRow Row, IReadOnlyList Lines); + +/// +/// 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. +/// +public sealed class DocumentEditor +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal packs. + public DocumentEditor(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + _factory = factory; + _permissions = permissions; + _packs = packs; + } + + /// A page of documents of some kinds of a family. + /// Who reads. + /// The company. + /// The family. + /// The kinds; all of the family when empty. + /// The request; the search also looks at the code and name of the party. + /// Cancellation. + /// The page. + public async Task> ListAsync( + Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection 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.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().ListAsync( + Query.For().Where(SqlFragment.Of($"(LOWER(name) LIKE {pattern} OR LOWER(code) LIKE {pattern})")).Take(500), cancellationToken).ConfigureAwait(false); + var any = new List + { + 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(await RowsAsync(uow, family, page.Items, cancellationToken).ConfigureAwait(false), page.Total, page.Totals); + } + + /// + /// 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). + /// + /// Who edits. + /// The company. + /// The document, changed in place. + /// The party; none clears it. + /// Cancellation. + /// A task. + 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("party.not-found"); + var fiscal = await uow.Repository().FindAsync(Query.For().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().FindAsync(Query.For().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() + .ListAsync(Query.For().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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + header.BankAccountId = profile?.DefaultBankAccountId; + } + } + else + { + var terms = await uow.Repository().FindAsync(Query.For().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().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; + } + } + } + + /// + /// 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. + /// + /// Who edits. + /// The company. + /// The document. + /// The line, changed in place. + /// The item. + /// Cancellation. + /// A task. + 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().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().FindAsync(Query.For().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().FindAsync(Query.For().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().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); + } + } + + /// + /// Computes the totals of a document being edited, without saving: line amounts and header totals change in place. + /// + /// Who edits. + /// The company. + /// The document. + /// Cancellation. + /// The tax summary and installments the save would write. + public async Task 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); + } + + /// The documents linked to one: the ones it fulfils, the ones that fulfil it, the invoice a note corrects. + /// Who reads. + /// The company. + /// The document. + /// Cancellation. + /// The linked documents. + public async Task> 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().ListAsync( + Query.For().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(); + 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)]; + } + + /// + /// 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. + /// + /// Who reads. + /// The company. + /// The family of the sources. + /// The kinds of the sources. + /// The party; all when empty. + /// The first date; none when empty. + /// The last date; none when empty. + /// Cancellation. + /// The documents, by party and date. + public async Task> OpenAsync( + Actor actor, string companyCode, DocumentFamily family, IReadOnlyCollection 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.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(); + 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> RowsAsync(IUnitOfWork uow, DocumentFamily family, IReadOnlyList 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() + : (await uow.Repository().ListAsync(Query.For().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() + : (await uow.Repository().ListAsync(Query.For().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); + }), + ]; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index 7f418ea..6ec090d 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -18,6 +18,9 @@ public sealed class DocumentRecord /// The lines, in order. public List Lines { get; init; } = []; + + /// The tax summary and installments written by the last save. + public DocumentFigures Figures { get; init; } = DocumentFigures.Empty; } /// The error codes of the document engine; the interface translates them (Documents.json). @@ -76,6 +79,12 @@ public static class DocumentErrors /// A closed or cancelled document cannot be fulfilled. public const string CopySourceNotOpen = "document.copy.source-not-open"; + + /// Error: documents of different parties cannot go into one document. + public const string CopyParties = "document.copy.parties"; + + /// Error: a discount formula that cannot be read. + public const string LineDiscountInvalid = "document.line.discount-invalid"; } /// @@ -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; /// Creates the engine. @@ -96,9 +106,12 @@ public sealed class DocumentEngine /// The permissions. /// The history. /// The fiscal calendar (open periods). + /// The fiscal pack of each company (tax rounding, stamp duty). /// The clock. - 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), + }; } /// Checks a document against its definition; is the stored one. @@ -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) diff --git a/src/Khaemhat.Application/Documents/DocumentStores.cs b/src/Khaemhat.Application/Documents/DocumentStores.cs index bc96935..aa55ea5 100644 --- a/src/Khaemhat.Application/Documents/DocumentStores.cs +++ b/src/Khaemhat.Application/Documents/DocumentStores.cs @@ -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); + + /// A page of headers: the list request, plus the conditions the caller adds (kinds, search on parties). + Task> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList conditions, CancellationToken cancellationToken); + + /// Headers by id. + Task> ManyAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken); + + /// Lines by id. + Task> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken); } /// The store of one family. @@ -168,6 +178,73 @@ internal sealed class DocumentStore(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); + + /// + public async Task> ListAsync(IUnitOfWork uow, ListQuery list, IReadOnlyList conditions, CancellationToken cancellationToken) + { + var query = Query.For(); + foreach (var condition in conditions) + { + query = query.Where(condition); + } + + var fields = DocumentListFields.Fields; + var page = await uow.Repository().ListAsync(fields.Apply(query, list), cancellationToken).ConfigureAwait(false); + return new ListPage([.. page.Items], page.TotalCount, new Dictionary()); + } + + /// + public async Task> ManyAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken) + { + if (ids.Count == 0) + { + return []; + } + + var list = ids.ToList(); + var rows = await uow.Repository().ListAsync(Query.For().Where(h => list.Contains(h.Id)), cancellationToken).ConfigureAwait(false); + return [.. rows.Items]; + } + + /// + public async Task> LinesByIdAsync(IUnitOfWork uow, IReadOnlyCollection ids, CancellationToken cancellationToken) + { + if (ids.Count == 0) + { + return []; + } + + var list = ids.ToList(); + var rows = await uow.Repository().ListAsync(Query.For().Where(l => list.Contains(l.Id)), cancellationToken).ConfigureAwait(false); + return [.. rows.Items]; + } +} + +/// The fields of the document radars (ADR 0032): the same for every family. +/// The header. +internal static class DocumentListFields + where THeader : DocumentHeader +{ + /// The fields. + public static ListFields Fields { get; } = new ListFields() + .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)); } /// The stores of the six families. diff --git a/src/Khaemhat.Application/Documents/DocumentTotalsCalculator.cs b/src/Khaemhat.Application/Documents/DocumentTotalsCalculator.cs new file mode 100644 index 0000000..a6d82f1 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentTotalsCalculator.cs @@ -0,0 +1,257 @@ +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Documents; + +/// The VAT of a line, from its tax code. +/// The tax code. +/// The rate in percent. +/// The nature of operations without VAT. +/// When the VAT becomes due. +/// The non-deductible share (purchases). +/// The law printed for operations without VAT. +public sealed record TotalsTax( + long? TaxCodeId, + decimal Rate, + string? Nature = null, + TaxExigibility Exigibility = TaxExigibility.Immediate, + decimal NonDeductiblePercent = 0m, + string? LegalReference = null); + +/// A line as the calculator sees it. +/// The kind of line. +/// The quantity (expenses and discounts without quantity count as one). +/// The unit price, with VAT when the document's prices include it. +/// The discounts, such as 10+5. +/// The VAT; lines without it are left out of the summary. +/// The line is out of the withholding and of the social security contribution. +public sealed record TotalsLine( + DocumentLineKind Kind, + decimal Quantity, + decimal Price, + string? DiscountFormula, + TotalsTax? Tax, + bool WithholdingExcluded = false); + +/// The settings of the document that change its totals. +public sealed record TotalsOptions +{ + /// The prices include VAT: the taxable amount is computed back from each VAT group. + public bool PricesIncludeTax { get; init; } + + /// The discount on the goods (not on expenses), such as 5 or 10+5. + public string? FooterDiscount { get; init; } + + /// The exigibility of the whole document (cash basis, deferred), when not the one of the tax codes. + public TaxExigibility? Exigibility { get; init; } + + /// Split payment: the VAT is paid by the customer to the State. + public bool SplitPayment { get; init; } + + /// The document can carry the stamp duty (invoices and notes). + public bool StampDutyApplies { get; init; } + + /// The stamp duty is added to the total. + public bool StampDutyCharged { get; init; } + + /// The withholding rate, percent. + public decimal? WithholdingRate { get; init; } + + /// The share of the amount the withholding applies to, percent. + public decimal WithholdingBasePercent { get; init; } = 100m; + + /// The social security contribution rate, percent. + public decimal? SocialSecurityRate { get; init; } + + /// The VAT of the contribution; the one of the first taxed line when empty. + public TotalsTax? SocialSecurityTax { get; init; } + + /// The contribution is part of the withholding base. + public bool SocialSecurityWithheld { get; init; } + + /// The ENASARCO rate withheld, percent. + public decimal? EnasarcoRate { get; init; } +} + +/// A line of the computed tax summary. +/// The VAT of the group, with the exigibility of the document. +/// The taxable amount. +/// The VAT. +/// The non-deductible part of the VAT. +public sealed record TotalsSummaryLine(TotalsTax Tax, decimal Taxable, decimal TaxAmount, decimal NonDeductibleTax); + +/// The totals of a document. +/// The amount of each line (quantity × price less its discounts), in the order given. +/// The tax summary, by rate (highest first). +/// The total of the expense lines. +/// What the footer discount took off. +/// The social security contribution. +/// The taxable amount. +/// The VAT. +/// The stamp duty due (charged or not). +/// The total of the document. +/// The withholding tax. +/// The ENASARCO contribution withheld. +/// The VAT the customer pays to the State. +/// The amount to pay. +public sealed record DocumentTotals( + IReadOnlyList LineAmounts, + IReadOnlyList Summary, + decimal Expenses, + decimal FooterDiscountAmount, + decimal SocialSecurity, + decimal Taxable, + decimal Tax, + decimal StampDuty, + decimal Total, + decimal Withholding, + decimal Enasarco, + decimal SplitPaymentTax, + decimal Net); + +/// +/// 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 DatiRiepilogo); social security contribution with its own VAT; stamp duty; withholding, ENASARCO +/// and split payment taken off the amount to pay. +/// +public static class DocumentTotalsCalculator +{ + /// Computes the totals. + /// The lines. + /// The settings of the document. + /// The country's rounding and stamp duty rules. + /// The totals. + public static DocumentTotals Compute(IReadOnlyList 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(); + 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); + } + + /// The factor of a discount formula: 10+5 is 0.855; an empty or invalid formula is 1. + /// The formula. + /// The factor. + 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 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; } + } +} diff --git a/src/Khaemhat.Application/Documents/InstallmentGenerator.cs b/src/Khaemhat.Application/Documents/InstallmentGenerator.cs new file mode 100644 index 0000000..2789c77 --- /dev/null +++ b/src/Khaemhat.Application/Documents/InstallmentGenerator.cs @@ -0,0 +1,110 @@ +namespace Khaemhat.Application.Documents; + +/// An installment of payment terms. +/// Days from the document date. +/// Move to the end of that month. +/// A fixed day: of the next month after the end-of-month move, else the next such day. +/// The share of the amount, percent. +public sealed record InstallmentRule(int Days, bool EndOfMonth, int? FixedDay, decimal Percent); + +/// Months without due dates (mesi esclusi): a due date in them moves to a day of the next month. +/// The first month (1-12). +/// The second month. +/// The day of the next month. +public sealed record ExcludedMonths(int? First, int? Second, int Day = 10) +{ + /// Whether a month is excluded. + /// The month. + /// Whether it is. + public bool Contains(int month) => First == month || Second == month; +} + +/// A computed installment. +/// The order, from 1. +/// The due date. +/// The amount. +public sealed record InstallmentDue(int Number, DateOnly DueDate, decimal Amount); + +/// +/// 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. +/// +public static class InstallmentGenerator +{ + /// Computes the installments. + /// The document date. + /// The amount to pay. + /// The VAT included in (for ). + /// The installments of the terms; none means one installment on the document date. + /// All the VAT is paid with the first installment. + /// The months without due dates. + /// Rounding to the cent. + /// The installments, empty for a zero amount. + public static IReadOnlyList Generate( + DateOnly date, decimal amount, decimal tax, IReadOnlyList rules, bool vatOnFirst, ExcludedMonths? excluded, Func 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(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; + } + + /// The due date of an installment. + /// The document date. + /// The installment. + /// The months without due dates. + /// The due date. + 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))); +} diff --git a/src/Khaemhat.Core/Documents/DocumentKinds.cs b/src/Khaemhat.Core/Documents/DocumentKinds.cs index 08eba25..1ebff92 100644 --- a/src/Khaemhat.Core/Documents/DocumentKinds.cs +++ b/src/Khaemhat.Core/Documents/DocumentKinds.cs @@ -233,3 +233,16 @@ public enum DocumentLineKind /// A discount, premium or allowance. Discount = 4, } + +/// Who carries the goods (delivery note: trasporto a cura del). +public enum TransportResponsibility +{ + /// The sender (mittente). + Sender = 0, + + /// The recipient (destinatario). + Recipient = 1, + + /// A carrier (vettore). + Carrier = 2, +} diff --git a/src/Khaemhat.Core/Documents/Documents.cs b/src/Khaemhat.Core/Documents/Documents.cs index 2f05e01..cf8cbc9 100644 --- a/src/Khaemhat.Core/Documents/Documents.cs +++ b/src/Khaemhat.Core/Documents/Documents.cs @@ -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, IDemoMarkable /// The amount to pay. public decimal NetAmount { get; set; } + /// The prices of the lines include VAT: the taxable amount is computed back from them. + public bool PricesIncludeTax { get; set; } + + /// The amount taken off the lines by . + public decimal FooterDiscountAmount { get; set; } + + /// When the VAT of the document becomes due, when not the one of its tax codes (split payment, cash basis). + public TaxExigibility? Exigibility { get; set; } + + /// Split payment: the public administration pays the VAT to the State, not to the company. + public bool SplitPayment { get; set; } + + /// The stamp duty is charged to the customer (added to the total). + public bool StampDutyCharged { get; set; } + + /// The withholding tax rate, percent; none when the document has no withholding. + public decimal? WithholdingRate { get; set; } + + /// The share of the amount the withholding is computed on, percent (100 for fees, 50 or 20 for agents). + public decimal WithholdingBasePercent { get; set; } = 100m; + + /// The withholding type of the e-invoice, such as RT01. + public string? WithholdingType { get; set; } + + /// The payment reason of the withholding (e-invoice), such as A. + public string? WithholdingReason { get; set; } + + /// The social security fund (cassa previdenza) of the e-invoice, such as TC22. + public string? SocialSecurityFund { get; set; } + + /// The contribution rate of the fund, percent. + public decimal? SocialSecurityRate { get; set; } + + /// The VAT code of the contribution; the one of the first line when empty. + public long? SocialSecurityTaxCodeId { get; set; } + + /// The contribution is subject to the withholding tax (INPS 4%). + public bool SocialSecurityWithheld { get; set; } + + /// The ENASARCO rate withheld from the commissions of an agent, percent. + public decimal? EnasarcoRate { get; set; } + + /// The ENASARCO contribution withheld. + public decimal EnasarcoAmount { get; set; } + + /// The tender code (CIG) of a public contract. + public string? Cig { get; set; } + + /// The project code (CUP) of a public contract. + public string? Cup { get; set; } + + /// Who carries the goods (delivery notes, accompanying invoices). + public TransportResponsibility? TransportBy { get; set; } + + /// The document a credit or debit note corrects, in the same family. + public long? RelatedDocumentId { get; set; } + + /// The number of the corrected document, also for documents outside Khaemhat. + public string? RelatedNumber { get; set; } + + /// The date of the corrected document. + public DateOnly? RelatedDate { get; set; } + /// The notes printed on the document. public string? Notes { get; set; } @@ -236,6 +300,9 @@ public abstract class DocumentLine : Entity /// The line this one fulfils. public long? SourceLineId { get; set; } + /// The line is left out of the withholding tax and of the social security contribution (expenses paid on behalf). + public bool WithholdingExcluded { get; set; } + /// The ledger account (M7). public string? AccountCode { get; set; } @@ -327,3 +394,65 @@ public sealed class DocumentLink : Entity /// The quantity fulfilled. public decimal Quantity { get; set; } } + +/// +/// A line of the tax summary of a document (castelletto IVA, document_tax_summaries): one per VAT code, +/// written by the totals calculator each time the document is saved. +/// +public sealed class DocumentTaxSummary : Entity +{ + /// The family of the document. + public DocumentFamily Family { get; set; } + + /// The document. + public long DocumentId { get; set; } + + /// The VAT code. + public long? TaxCodeId { get; set; } + + /// The rate in percent. + public decimal Rate { get; set; } + + /// The nature of operations without VAT. + public string? Nature { get; set; } + + /// When the VAT becomes due. + public TaxExigibility Exigibility { get; set; } + + /// The non-deductible share, percent. + public decimal NonDeductiblePercent { get; set; } + + /// The law printed for operations without VAT. + public string? LegalReference { get; set; } + + /// The taxable amount. + public decimal Taxable { get; set; } + + /// The VAT. + public decimal Tax { get; set; } + + /// The non-deductible part of the VAT. + public decimal NonDeductibleTax { get; set; } +} + +/// An installment of a document (document_installments), from its payment terms. +public sealed class DocumentInstallment : Entity +{ + /// The family of the document. + public DocumentFamily Family { get; set; } + + /// The document. + public long DocumentId { get; set; } + + /// The order, from 1. + public int Number { get; set; } + + /// The due date. + public DateOnly DueDate { get; set; } + + /// The amount. + public decimal Amount { get; set; } + + /// The payment method. + public long? PaymentMethodId { get; set; } +} diff --git a/src/Khaemhat.Core/Parties/Parties.cs b/src/Khaemhat.Core/Parties/Parties.cs index 63a7e82..6177c45 100644 --- a/src/Khaemhat.Core/Parties/Parties.cs +++ b/src/Khaemhat.Core/Parties/Parties.cs @@ -339,6 +339,15 @@ public sealed class PartySalesTerms : Entity /// The day of the month the deferred invoices are issued, if fixed. public int? InvoiceDay { get; set; } + /// A month without due dates (1-12), such as August: they move to the next month. + public int? ExcludedMonth1 { get; set; } + + /// A second month without due dates, such as December. + public int? ExcludedMonth2 { get; set; } + + /// The day of the next month a due date in an excluded month moves to (10 when empty). + public int? ExcludedMonthsDay { get; set; } + /// How the documents are sent. public DocumentDelivery SendDocuments { get; set; } diff --git a/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs b/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs index f06835a..29bf09b 100644 --- a/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs @@ -20,6 +20,12 @@ public abstract class DocumentHeaderMap : EntityMap 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 /// Creates the map. public DocumentLinkMap() => ToTable("document_links"); } + +/// Map of to document_tax_summaries. +public sealed class DocumentTaxSummaryMap : EntityMap +{ + /// Creates the map. + public DocumentTaxSummaryMap() + { + ToTable("document_tax_summaries"); + Map(x => x.Nature).MaxLength(10); + Map(x => x.LegalReference).MaxLength(100); + } +} + +/// Map of to document_installments. +public sealed class DocumentInstallmentMap : EntityMap +{ + /// Creates the map. + public DocumentInstallmentMap() => ToTable("document_installments"); +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs index 9960faa..78da870 100644 --- a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs @@ -5,7 +5,7 @@ namespace Khaemhat.Data.CompanyDatabase.Migrations; /// /// 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. /// [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"); diff --git a/src/Khaemhat.Data/Querying/ExpressionTranslator.cs b/src/Khaemhat.Data/Querying/ExpressionTranslator.cs index 0f2368b..cb21d3c 100644 --- a/src/Khaemhat.Data/Querying/ExpressionTranslator.cs +++ b/src/Khaemhat.Data/Querying/ExpressionTranslator.cs @@ -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; } diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 69d0bc0..448f38a 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -151,6 +151,7 @@ internal static class KhaemhatServices // The document engine (ADR 0032): one engine, the copies, a typed service per family. services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(typeof(Khaemhat.Application.Documents.DocumentService<,>)); // Guided import and export (ADR 0031): the entities in the order of the screen. diff --git a/src/Khaemhat.Web/Resources/it-IT/Documents.json b/src/Khaemhat.Web/Resources/it-IT/Documents.json index bea31ea..5506e0f 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Documents.json +++ b/src/Khaemhat.Web/Resources/it-IT/Documents.json @@ -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.", diff --git a/tests/Khaemhat.Application.Tests/DocumentTotalsTests.cs b/tests/Khaemhat.Application.Tests/DocumentTotalsTests.cs new file mode 100644 index 0000000..075326e --- /dev/null +++ b/tests/Khaemhat.Application.Tests/DocumentTotalsTests.cs @@ -0,0 +1,169 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Italy; + +namespace Khaemhat.Application.Tests; + +/// +/// 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. +/// +[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)); + } +} diff --git a/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj b/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj index 56cd603..8c3f051 100644 --- a/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj +++ b/tests/Khaemhat.Application.Tests/Khaemhat.Application.Tests.csproj @@ -7,6 +7,7 @@ + diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 4f13e6e..69cc632 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -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()); }