diff --git a/CHANGELOG.md b/CHANGELOG.md index d2df3f8..9f9b0e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. ## [Unreleased] +### Added +- Motore documenti (#47, ADR 0032): un solo motore per vendite, acquisti e magazzino. Ogni tipo documento ha un + **genere** (17: preventivo, ordine cliente, DDT, fatture immediate, accompagnatorie, differite e di acconto, note + di credito e di debito, parcella, pro forma, autofattura, ordine fornitore, DDT fornitore, fattura e nota di credito + fornitore, movimento di magazzino) che ne decide famiglia, ciclo di vita, effetti, righe ammesse, documenti evadibili + e permessi. Tabelle `sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`, `purchase_documents`, + `inventory_documents` con le righe e `document_links`. +- Stati e azioni ammesse per stato (`DocumentStateMachine`): ciclo *documento* (bozza, confermato, evaso in parte, + evaso, chiuso, annullato), *fattura* (bozza, emessa, XML generato, inviata, consegnata, scartata, non consegnata, + annullata) e *semplice*; fattura emessa immutabile, annullamento con motivo solo prima dell'invio allo SDI. +- Numerazione alla conferma dentro la transazione e sotto il lock del numeratore (advisory lock su PostgreSQL, lock di + scrittura su SQLite): nessun numero doppio, un rollback restituisce il numero, controllo della data fuori sequenza + sui numeratori senza buchi, numeratore dell'anno nuovo creato da solo, elenco dei numeri mancanti. +- 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`. + +### Changed +- *Tipi documento*: nuovo campo obbligatorio **Genere** (i tipi di base lo ricevono dalla migrazione); *Numeratori*: + nuovo campo **Data dell'ultimo numero**. + ## [0.4.0] - 2026-11-12 M4 — Tabelle, anagrafiche, articoli. Il pacchetto fiscale italiano, il profilo e le tabelle dell'azienda con i dati diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index 471e9b0..d60c272 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -729,6 +729,7 @@ Migrazioni applicate in ordine: - `core` 20261111015 `create_code_sequences` (M20261111_015_CreateCodeSequences) - `core` 20261112001 `create_parties` (M20261112_001_CreateParties) - `core` 20261112002 `create_items` (M20261112_002_CreateItems) +- `core` 20261112003 `create_documents` (M20261112_003_CreateDocuments) #### `attachments` @@ -990,6 +991,28 @@ Migrazioni applicate in ordine: - indice unico `ux_discount_policies_code` su `code` +#### `document_links` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `target_family` | String(40) | no | | | +| `target_document_id` | Int64 | no | | | +| `target_line_id` | Int64 | no | | | +| `source_family` | String(40) | no | | | +| `source_document_id` | Int64 | no | | | +| `source_line_id` | Int64 | no | | | +| `quantity` | Decimal(19,6) | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_document_links_source` su `source_family`, `source_line_id` +- indice `ix_document_links_source_document` su `source_family`, `source_document_id` +- indice `ix_document_links_target` su `target_family`, `target_document_id` + #### `document_numerators` | Colonna | Tipo | Null | Default | Note | @@ -1011,6 +1034,7 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `last_date` | Date | sì | | | - indice unico `ux_document_numerators_code_year` su `code`, `year` @@ -1035,6 +1059,7 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `document_kind` | String(40) | sì | | | - indice unico `ux_document_types_code` su `code` @@ -1112,6 +1137,115 @@ Migrazioni applicate in ordine: - indice unico `ux_goods_appearances_code` su `code` +#### `inventory_document_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_id` | Int64 | no | | -> `inventory_documents` (Cascade) | +| `line_number` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `item_id` | Int64 | sì | | -> `items` (Restrict) | +| `description` | String(1000) | no | | | +| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) | +| `quantity` | Decimal(19,6) | no | `0` | | +| `price` | Decimal(19,6) | no | `0` | | +| `price_source` | String(40) | no | | | +| `discount_formula` | String(30) | sì | | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `delivery_date` | Date | sì | | | +| `fulfilled_quantity` | Decimal(19,6) | no | `0` | | +| `fulfillment_closed` | Bool | no | `false` | | +| `source_family` | String(40) | sì | | | +| `source_line_id` | Int64 | sì | | | +| `account_code` | String(20) | sì | | | +| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) | +| `job_id` | Int64 | sì | | -> `jobs` (Restrict) | +| `notes` | Text | sì | | | +| `sort_order` | Int32 | 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_inventory_document_lines_document` su `document_id` +- indice `ix_inventory_document_lines_item` su `item_id` +- indice `ix_inventory_document_lines_source` su `source_family`, `source_line_id` + +#### `inventory_documents` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) | +| `kind` | String(40) | no | | | +| `status` | String(40) | no | | | +| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) | +| `section` | String(10) | sì | | | +| `number` | Int64 | sì | | | +| `document_number` | String(30) | sì | | | +| `document_date` | Date | no | | | +| `year` | Int32 | no | | | +| `party_id` | Int64 | sì | | -> `parties` (Restrict) | +| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) | +| `external_reference` | String(40) | sì | | | +| `external_date` | Date | sì | | | +| `currency_code` | String(3) | no | | | +| `exchange_rate` | Decimal(19,6) | no | `1` | | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) | +| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) | +| `packages` | Int32 | sì | | | +| `gross_weight` | Decimal(19,6) | sì | | | +| `net_weight` | Decimal(19,6) | sì | | | +| `transport_start` | DateTimeUtc | sì | | | +| `valid_until` | Date | sì | | | +| `delivery_date` | Date | sì | | | +| `revision` | Int32 | no | `0` | | +| `printed` | Bool | no | `false` | | +| `sent` | Bool | no | `false` | | +| `posted` | Bool | no | `false` | | +| `installments_generated` | Bool | no | `false` | | +| `xml_generated` | Bool | no | `false` | | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `tax_amount` | Decimal(19,6) | no | `0` | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `footer_discount` | String(30) | sì | | | +| `expenses_amount` | Decimal(19,6) | no | `0` | | +| `stamp_duty` | Decimal(19,6) | no | `0` | | +| `withholding_amount` | Decimal(19,6) | no | `0` | | +| `social_security_amount` | Decimal(19,6) | no | `0` | | +| `net_amount` | Decimal(19,6) | no | `0` | | +| `notes` | Text | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `vat_protocol` | Int64 | sì | | | +| `confirmed_at` | DateTimeUtc | sì | | | +| `confirmed_by` | String(100) | sì | | | +| `cancelled_at` | DateTimeUtc | sì | | | +| `cancel_reason` | String(200) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_inventory_documents_date` su `document_date` +- indice `ix_inventory_documents_party` su `party_id` +- indice `ix_inventory_documents_status` su `status` +- indice unico `ux_inventory_documents_number` su `numerator_id`, `number` + #### `inventory_reasons` | Colonna | Tipo | Null | Default | Note | @@ -1710,6 +1844,224 @@ Migrazioni applicate in ordine: - indice unico `ux_provinces_code` su `code` +#### `purchase_document_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_id` | Int64 | no | | -> `purchase_documents` (Cascade) | +| `line_number` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `item_id` | Int64 | sì | | -> `items` (Restrict) | +| `description` | String(1000) | no | | | +| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) | +| `quantity` | Decimal(19,6) | no | `0` | | +| `price` | Decimal(19,6) | no | `0` | | +| `price_source` | String(40) | no | | | +| `discount_formula` | String(30) | sì | | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `delivery_date` | Date | sì | | | +| `fulfilled_quantity` | Decimal(19,6) | no | `0` | | +| `fulfillment_closed` | Bool | no | `false` | | +| `source_family` | String(40) | sì | | | +| `source_line_id` | Int64 | sì | | | +| `account_code` | String(20) | sì | | | +| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) | +| `job_id` | Int64 | sì | | -> `jobs` (Restrict) | +| `notes` | Text | sì | | | +| `sort_order` | Int32 | 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_purchase_document_lines_document` su `document_id` +- indice `ix_purchase_document_lines_item` su `item_id` +- indice `ix_purchase_document_lines_source` su `source_family`, `source_line_id` + +#### `purchase_documents` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) | +| `kind` | String(40) | no | | | +| `status` | String(40) | no | | | +| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) | +| `section` | String(10) | sì | | | +| `number` | Int64 | sì | | | +| `document_number` | String(30) | sì | | | +| `document_date` | Date | no | | | +| `year` | Int32 | no | | | +| `party_id` | Int64 | sì | | -> `parties` (Restrict) | +| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) | +| `external_reference` | String(40) | sì | | | +| `external_date` | Date | sì | | | +| `currency_code` | String(3) | no | | | +| `exchange_rate` | Decimal(19,6) | no | `1` | | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) | +| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) | +| `packages` | Int32 | sì | | | +| `gross_weight` | Decimal(19,6) | sì | | | +| `net_weight` | Decimal(19,6) | sì | | | +| `transport_start` | DateTimeUtc | sì | | | +| `valid_until` | Date | sì | | | +| `delivery_date` | Date | sì | | | +| `revision` | Int32 | no | `0` | | +| `printed` | Bool | no | `false` | | +| `sent` | Bool | no | `false` | | +| `posted` | Bool | no | `false` | | +| `installments_generated` | Bool | no | `false` | | +| `xml_generated` | Bool | no | `false` | | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `tax_amount` | Decimal(19,6) | no | `0` | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `footer_discount` | String(30) | sì | | | +| `expenses_amount` | Decimal(19,6) | no | `0` | | +| `stamp_duty` | Decimal(19,6) | no | `0` | | +| `withholding_amount` | Decimal(19,6) | no | `0` | | +| `social_security_amount` | Decimal(19,6) | no | `0` | | +| `net_amount` | Decimal(19,6) | no | `0` | | +| `notes` | Text | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `vat_protocol` | Int64 | sì | | | +| `confirmed_at` | DateTimeUtc | sì | | | +| `confirmed_by` | String(100) | sì | | | +| `cancelled_at` | DateTimeUtc | sì | | | +| `cancel_reason` | String(200) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_purchase_documents_date` su `document_date` +- indice `ix_purchase_documents_party` su `party_id` +- indice `ix_purchase_documents_status` su `status` +- indice unico `ux_purchase_documents_number` su `numerator_id`, `number` + +#### `purchase_order_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_id` | Int64 | no | | -> `purchase_orders` (Cascade) | +| `line_number` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `item_id` | Int64 | sì | | -> `items` (Restrict) | +| `description` | String(1000) | no | | | +| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) | +| `quantity` | Decimal(19,6) | no | `0` | | +| `price` | Decimal(19,6) | no | `0` | | +| `price_source` | String(40) | no | | | +| `discount_formula` | String(30) | sì | | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `delivery_date` | Date | sì | | | +| `fulfilled_quantity` | Decimal(19,6) | no | `0` | | +| `fulfillment_closed` | Bool | no | `false` | | +| `source_family` | String(40) | sì | | | +| `source_line_id` | Int64 | sì | | | +| `account_code` | String(20) | sì | | | +| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) | +| `job_id` | Int64 | sì | | -> `jobs` (Restrict) | +| `notes` | Text | sì | | | +| `sort_order` | Int32 | 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_purchase_order_lines_document` su `document_id` +- indice `ix_purchase_order_lines_item` su `item_id` +- indice `ix_purchase_order_lines_source` su `source_family`, `source_line_id` + +#### `purchase_orders` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) | +| `kind` | String(40) | no | | | +| `status` | String(40) | no | | | +| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) | +| `section` | String(10) | sì | | | +| `number` | Int64 | sì | | | +| `document_number` | String(30) | sì | | | +| `document_date` | Date | no | | | +| `year` | Int32 | no | | | +| `party_id` | Int64 | sì | | -> `parties` (Restrict) | +| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) | +| `external_reference` | String(40) | sì | | | +| `external_date` | Date | sì | | | +| `currency_code` | String(3) | no | | | +| `exchange_rate` | Decimal(19,6) | no | `1` | | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) | +| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) | +| `packages` | Int32 | sì | | | +| `gross_weight` | Decimal(19,6) | sì | | | +| `net_weight` | Decimal(19,6) | sì | | | +| `transport_start` | DateTimeUtc | sì | | | +| `valid_until` | Date | sì | | | +| `delivery_date` | Date | sì | | | +| `revision` | Int32 | no | `0` | | +| `printed` | Bool | no | `false` | | +| `sent` | Bool | no | `false` | | +| `posted` | Bool | no | `false` | | +| `installments_generated` | Bool | no | `false` | | +| `xml_generated` | Bool | no | `false` | | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `tax_amount` | Decimal(19,6) | no | `0` | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `footer_discount` | String(30) | sì | | | +| `expenses_amount` | Decimal(19,6) | no | `0` | | +| `stamp_duty` | Decimal(19,6) | no | `0` | | +| `withholding_amount` | Decimal(19,6) | no | `0` | | +| `social_security_amount` | Decimal(19,6) | no | `0` | | +| `net_amount` | Decimal(19,6) | no | `0` | | +| `notes` | Text | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `vat_protocol` | Int64 | sì | | | +| `confirmed_at` | DateTimeUtc | sì | | | +| `confirmed_by` | String(100) | sì | | | +| `cancelled_at` | DateTimeUtc | sì | | | +| `cancel_reason` | String(200) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_purchase_orders_date` su `document_date` +- indice `ix_purchase_orders_party` su `party_id` +- indice `ix_purchase_orders_status` su `status` +- indice unico `ux_purchase_orders_number` su `numerator_id`, `number` + #### `role_permissions` | Colonna | Tipo | Null | Default | Note | @@ -1743,6 +2095,333 @@ Migrazioni applicate in ordine: - indice unico `ux_roles_code` su `code` +#### `sale_document_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_id` | Int64 | no | | -> `sale_documents` (Cascade) | +| `line_number` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `item_id` | Int64 | sì | | -> `items` (Restrict) | +| `description` | String(1000) | no | | | +| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) | +| `quantity` | Decimal(19,6) | no | `0` | | +| `price` | Decimal(19,6) | no | `0` | | +| `price_source` | String(40) | no | | | +| `discount_formula` | String(30) | sì | | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `delivery_date` | Date | sì | | | +| `fulfilled_quantity` | Decimal(19,6) | no | `0` | | +| `fulfillment_closed` | Bool | no | `false` | | +| `source_family` | String(40) | sì | | | +| `source_line_id` | Int64 | sì | | | +| `account_code` | String(20) | sì | | | +| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) | +| `job_id` | Int64 | sì | | -> `jobs` (Restrict) | +| `notes` | Text | sì | | | +| `sort_order` | Int32 | 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_sale_document_lines_document` su `document_id` +- indice `ix_sale_document_lines_item` su `item_id` +- indice `ix_sale_document_lines_source` su `source_family`, `source_line_id` + +#### `sale_documents` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) | +| `kind` | String(40) | no | | | +| `status` | String(40) | no | | | +| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) | +| `section` | String(10) | sì | | | +| `number` | Int64 | sì | | | +| `document_number` | String(30) | sì | | | +| `document_date` | Date | no | | | +| `year` | Int32 | no | | | +| `party_id` | Int64 | sì | | -> `parties` (Restrict) | +| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) | +| `external_reference` | String(40) | sì | | | +| `external_date` | Date | sì | | | +| `currency_code` | String(3) | no | | | +| `exchange_rate` | Decimal(19,6) | no | `1` | | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) | +| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) | +| `packages` | Int32 | sì | | | +| `gross_weight` | Decimal(19,6) | sì | | | +| `net_weight` | Decimal(19,6) | sì | | | +| `transport_start` | DateTimeUtc | sì | | | +| `valid_until` | Date | sì | | | +| `delivery_date` | Date | sì | | | +| `revision` | Int32 | no | `0` | | +| `printed` | Bool | no | `false` | | +| `sent` | Bool | no | `false` | | +| `posted` | Bool | no | `false` | | +| `installments_generated` | Bool | no | `false` | | +| `xml_generated` | Bool | no | `false` | | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `tax_amount` | Decimal(19,6) | no | `0` | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `footer_discount` | String(30) | sì | | | +| `expenses_amount` | Decimal(19,6) | no | `0` | | +| `stamp_duty` | Decimal(19,6) | no | `0` | | +| `withholding_amount` | Decimal(19,6) | no | `0` | | +| `social_security_amount` | Decimal(19,6) | no | `0` | | +| `net_amount` | Decimal(19,6) | no | `0` | | +| `notes` | Text | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `vat_protocol` | Int64 | sì | | | +| `confirmed_at` | DateTimeUtc | sì | | | +| `confirmed_by` | String(100) | sì | | | +| `cancelled_at` | DateTimeUtc | sì | | | +| `cancel_reason` | String(200) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_sale_documents_date` su `document_date` +- indice `ix_sale_documents_party` su `party_id` +- indice `ix_sale_documents_status` su `status` +- indice unico `ux_sale_documents_number` su `numerator_id`, `number` + +#### `sale_order_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_id` | Int64 | no | | -> `sale_orders` (Cascade) | +| `line_number` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `item_id` | Int64 | sì | | -> `items` (Restrict) | +| `description` | String(1000) | no | | | +| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) | +| `quantity` | Decimal(19,6) | no | `0` | | +| `price` | Decimal(19,6) | no | `0` | | +| `price_source` | String(40) | no | | | +| `discount_formula` | String(30) | sì | | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `delivery_date` | Date | sì | | | +| `fulfilled_quantity` | Decimal(19,6) | no | `0` | | +| `fulfillment_closed` | Bool | no | `false` | | +| `source_family` | String(40) | sì | | | +| `source_line_id` | Int64 | sì | | | +| `account_code` | String(20) | sì | | | +| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) | +| `job_id` | Int64 | sì | | -> `jobs` (Restrict) | +| `notes` | Text | sì | | | +| `sort_order` | Int32 | 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_sale_order_lines_document` su `document_id` +- indice `ix_sale_order_lines_item` su `item_id` +- indice `ix_sale_order_lines_source` su `source_family`, `source_line_id` + +#### `sale_orders` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) | +| `kind` | String(40) | no | | | +| `status` | String(40) | no | | | +| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) | +| `section` | String(10) | sì | | | +| `number` | Int64 | sì | | | +| `document_number` | String(30) | sì | | | +| `document_date` | Date | no | | | +| `year` | Int32 | no | | | +| `party_id` | Int64 | sì | | -> `parties` (Restrict) | +| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) | +| `external_reference` | String(40) | sì | | | +| `external_date` | Date | sì | | | +| `currency_code` | String(3) | no | | | +| `exchange_rate` | Decimal(19,6) | no | `1` | | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) | +| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) | +| `packages` | Int32 | sì | | | +| `gross_weight` | Decimal(19,6) | sì | | | +| `net_weight` | Decimal(19,6) | sì | | | +| `transport_start` | DateTimeUtc | sì | | | +| `valid_until` | Date | sì | | | +| `delivery_date` | Date | sì | | | +| `revision` | Int32 | no | `0` | | +| `printed` | Bool | no | `false` | | +| `sent` | Bool | no | `false` | | +| `posted` | Bool | no | `false` | | +| `installments_generated` | Bool | no | `false` | | +| `xml_generated` | Bool | no | `false` | | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `tax_amount` | Decimal(19,6) | no | `0` | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `footer_discount` | String(30) | sì | | | +| `expenses_amount` | Decimal(19,6) | no | `0` | | +| `stamp_duty` | Decimal(19,6) | no | `0` | | +| `withholding_amount` | Decimal(19,6) | no | `0` | | +| `social_security_amount` | Decimal(19,6) | no | `0` | | +| `net_amount` | Decimal(19,6) | no | `0` | | +| `notes` | Text | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `vat_protocol` | Int64 | sì | | | +| `confirmed_at` | DateTimeUtc | sì | | | +| `confirmed_by` | String(100) | sì | | | +| `cancelled_at` | DateTimeUtc | sì | | | +| `cancel_reason` | String(200) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_sale_orders_date` su `document_date` +- indice `ix_sale_orders_party` su `party_id` +- indice `ix_sale_orders_status` su `status` +- indice unico `ux_sale_orders_number` su `numerator_id`, `number` + +#### `sale_quotation_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_id` | Int64 | no | | -> `sale_quotations` (Cascade) | +| `line_number` | Int32 | no | | | +| `kind` | String(40) | no | | | +| `item_id` | Int64 | sì | | -> `items` (Restrict) | +| `description` | String(1000) | no | | | +| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) | +| `quantity` | Decimal(19,6) | no | `0` | | +| `price` | Decimal(19,6) | no | `0` | | +| `price_source` | String(40) | no | | | +| `discount_formula` | String(30) | sì | | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `delivery_date` | Date | sì | | | +| `fulfilled_quantity` | Decimal(19,6) | no | `0` | | +| `fulfillment_closed` | Bool | no | `false` | | +| `source_family` | String(40) | sì | | | +| `source_line_id` | Int64 | sì | | | +| `account_code` | String(20) | sì | | | +| `cost_center_id` | Int64 | sì | | -> `cost_centers` (Restrict) | +| `job_id` | Int64 | sì | | -> `jobs` (Restrict) | +| `notes` | Text | sì | | | +| `sort_order` | Int32 | 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_sale_quotation_lines_document` su `document_id` +- indice `ix_sale_quotation_lines_item` su `item_id` +- indice `ix_sale_quotation_lines_source` su `source_family`, `source_line_id` + +#### `sale_quotations` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `document_type_id` | Int64 | no | | -> `document_types` (Restrict) | +| `kind` | String(40) | no | | | +| `status` | String(40) | no | | | +| `numerator_id` | Int64 | sì | | -> `document_numerators` (Restrict) | +| `section` | String(10) | sì | | | +| `number` | Int64 | sì | | | +| `document_number` | String(30) | sì | | | +| `document_date` | Date | no | | | +| `year` | Int32 | no | | | +| `party_id` | Int64 | sì | | -> `parties` (Restrict) | +| `destination_id` | Int64 | sì | | -> `party_addresses` (Restrict) | +| `external_reference` | String(40) | sì | | | +| `external_date` | Date | sì | | | +| `currency_code` | String(3) | no | | | +| `exchange_rate` | Decimal(19,6) | no | `1` | | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) | +| `bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `transport_reason_id` | Int64 | sì | | -> `transport_reasons` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `goods_appearance_id` | Int64 | sì | | -> `goods_appearances` (Restrict) | +| `packages` | Int32 | sì | | | +| `gross_weight` | Decimal(19,6) | sì | | | +| `net_weight` | Decimal(19,6) | sì | | | +| `transport_start` | DateTimeUtc | sì | | | +| `valid_until` | Date | sì | | | +| `delivery_date` | Date | sì | | | +| `revision` | Int32 | no | `0` | | +| `printed` | Bool | no | `false` | | +| `sent` | Bool | no | `false` | | +| `posted` | Bool | no | `false` | | +| `installments_generated` | Bool | no | `false` | | +| `xml_generated` | Bool | no | `false` | | +| `taxable_amount` | Decimal(19,6) | no | `0` | | +| `tax_amount` | Decimal(19,6) | no | `0` | | +| `total_amount` | Decimal(19,6) | no | `0` | | +| `footer_discount` | String(30) | sì | | | +| `expenses_amount` | Decimal(19,6) | no | `0` | | +| `stamp_duty` | Decimal(19,6) | no | `0` | | +| `withholding_amount` | Decimal(19,6) | no | `0` | | +| `social_security_amount` | Decimal(19,6) | no | `0` | | +| `net_amount` | Decimal(19,6) | no | `0` | | +| `notes` | Text | sì | | | +| `gl_entry_id` | Int64 | sì | | | +| `vat_protocol` | Int64 | sì | | | +| `confirmed_at` | DateTimeUtc | sì | | | +| `confirmed_by` | String(100) | sì | | | +| `cancelled_at` | DateTimeUtc | sì | | | +| `cancel_reason` | String(200) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_sale_quotations_date` su `document_date` +- indice `ix_sale_quotations_party` su `party_id` +- indice `ix_sale_quotations_status` su `status` +- indice unico `ux_sale_quotations_number` su `numerator_id`, `number` + #### `salespeople` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/STATUS.md b/docs/STATUS.md index 63edb64..01e8517 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -5,7 +5,8 @@ **Ultimo aggiornamento:** 2026-11-12 **Milestone corrente:** M5 — Motore documenti e Vendite (issue #47-#54, nel progetto in *Da fare*). M4 chiusa: PR #121 in `main`, tag `v0.4.0`, immagine e release. -**Prossimo passo:** M5, a partire dal motore documenti (#47) e dal calcolo dei totali (#48). #35 (PNG ad alta +**Prossimo passo:** M5: il motore documenti (#47) è sul ramo `feat/47-motore-documenti` in attesa di revisione; +poi il calcolo dei totali (#48) e le maschere (#49-#51). #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile). Da recuperare: profilo dell'azienda demo (indirizzo, partita IVA) prima dei documenti di M5; misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della @@ -15,7 +16,7 @@ filtro predefinito nei radar. ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7. -- ADR 0001-0031. +- ADR 0001-0032. - Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice). - Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid). - Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`, @@ -59,6 +60,10 @@ filtro predefinito nei radar. aggiornamento massivo (ADR 0030); import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (ADR 0031); 21 anagrafiche e 120 articoli di esempio; screenshot reali nella wiki. Test: 631 verdi in locale, 21 di PostgreSQL saltati; immagine costruita in locale e avviata da zero con SQLite e dati di esempio. +- **M5 (in corso):** motore documenti (#47, ADR 0032): generi e definizioni dei tipi documento, sei famiglie di + tabelle con le righe e `document_links`, stati con azioni ammesse, numerazione atomica alla conferma (provata in + concorrenza su SQLite e su PostgreSQL 18 in locale), copia e trasformazione con evasione riga per riga. Test: 664 + verdi in locale, PostgreSQL compreso. - Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13) e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36, M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91, diff --git a/docs/adr/0032-motore-documenti.md b/docs/adr/0032-motore-documenti.md new file mode 100644 index 0000000..bb3dc82 --- /dev/null +++ b/docs/adr/0032-motore-documenti.md @@ -0,0 +1,65 @@ +# ADR 0032 - Motore documenti: comportamento per genere, tabelle per famiglia, numerazione alla conferma + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** SPEC §11.3; milestone M5, issue #47 + +## Contesto + +SPEC §11.3 vuole un solo motore per tutti i documenti (vendita, acquisto, magazzino), guidato da definizioni +dichiarative, con tabelle per famiglia (`sale_quotations`, `sale_orders`, `sale_documents`, `purchase_orders`, +`purchase_documents`, `inventory_documents`, ognuna con le righe), `document_links` per l'evasione, gli stati +`Draft → Confirmed → (PartiallyFulfilled | Fulfilled) → Closed`, `Cancelled` e per le fatture +`Draft → Issued → SdiGenerated → SdiSent → (SdiDelivered | SdiRejected | SdiNotDelivered)`, la numerazione alla +conferma con la data non anteriore all'ultimo numero del sezionale. Restavano aperti: dove sta il comportamento di un +tipo documento (la tabella `document_types` è modificabile dall'utente e il suo `kind` dice solo la famiglia di +numerazione), come si numera per anno quando il numeratore è per anno, quando nasce un legame di evasione, che cosa +fa la copia, quali tabelle servono già adesso. + +## Decisione + +1. **Genere e definizione.** Il comportamento sta in codice, per **genere** (`DocumentKind`: preventivo, ordine + cliente, DDT, fattura immediata, accompagnatoria, differita, di acconto, nota di credito, nota di debito, parcella, + pro forma, autofattura, ordine fornitore, DDT fornitore, fattura fornitore, nota di credito fornitore, movimento di + magazzino). `DocumentBehaviors` dà per ogni genere: famiglia (tabella), direzione, ciclo di vita, effetti + (magazzino, impegnato, ordinato, contabilità, scadenze, e-fattura), tipi di riga ammessi, generi da cui evade + (sorgenti) e permessi. La tabella `document_types` riceve la colonna `document_kind`: ogni tipo dell'utente + sceglie un genere e aggiunge numeratore, causale di magazzino, TD SDI, causale contabile, registro IVA, modello di + stampa. `DocumentDefinition` è l'unione dei due (tipo + comportamento) e si legge con `DocumentDefinitionService`. + I tipi seminati prendono il genere dalla migrazione e dal modello del pacchetto paese. +2. **Tre cicli di vita.** `DocumentStateMachine` conosce tre cicli: *ordine* (preventivi, ordini, DDT, pro forma: + bozza, confermato, evaso parzialmente, evaso, chiuso, annullato), *fattura* (fatture e autofatture di vendita: + bozza, emessa, XML generato, inviata, consegnata, scartata, non consegnata, annullata) e *semplice* (fatture + fornitore, movimenti: bozza, confermato, annullato). Per ogni stato dice le azioni ammesse; un'azione non ammessa + è rifiutata con `document.action.not-allowed`. Si modifica solo una bozza, oltre a ordini e preventivi confermati + non evasi; la fattura emessa è immutabile: si annulla con un motivo finché l'XML non è inviato (o se scartato), + altrimenti si fa una nota di credito. Gli stati di evasione non sono azioni: li calcola `FulfillmentCalculator`. +3. **Numerazione alla conferma.** `DocumentNumberingService` numera nella stessa transazione della conferma, sotto il + lock `numerator::` (advisory lock di transazione su PostgreSQL, lock di scrittura su SQLite): un + rollback restituisce il numero, quindi non nascono buchi. Il numeratore del tipo vale per il suo codice; per + l'anno della data si usa la riga (codice, anno) e, se manca, si crea copiando formato, prefisso e sezionale + dell'ultima. Sui numeratori **senza buchi** (fatture, autofatture, protocollo acquisti) la data non può + precedere l'ultima numerata (`document_numerators.last_date`) e la conferma chiede il periodo aperto quando il + genere ha effetto contabile. `FindGapsAsync` elenca i numeri mancanti di un numeratore. Un documento numerato non + si elimina: si annulla e il numero resta. +4. **Tabelle.** Sei testate e sei tabelle di righe con le stesse colonne (classi base `DocumentHeader` e + `DocumentLine`), più `document_links` (riga destinazione → riga sorgente, quantità). Le tabelle del castelletto IVA + e delle rate arrivano con il calcolo dei totali (#48), i campi di trasporto sono già nella testata. +5. **Evasione.** Una riga copiata da un documento evadibile tiene la riga d'origine (`source_family`, + `source_line_id`). Il legame in `document_links` nasce alla **conferma** del documento destinazione e sparisce al + suo annullamento; dopo ogni cambio `FulfillmentCalculator` ricalcola la quantità evasa delle righe sorgente e lo + stato del documento sorgente (confermato, evaso parzialmente, evaso). Le righe con saldo forzato contano come + evase; un documento chiuso o annullato non cambia stato. +6. **Copia.** `DocumentCopyService` crea una bozza da un documento esistente verso lo stesso tipo (duplicazione) o un + altro della stessa direzione (trasformazione). Se il genere destinazione evade il genere sorgente si copiano le + quantità residue e le righe tengono l'origine, altrimenti si copiano le quantità intere senza legame. +7. **Servizio generico.** `DocumentService` (uno per famiglia) espone crea, leggi, salva, conferma, + annulla, chiudi, riapri, elimina e copia; il lavoro su più famiglie (evasione, copia) passa da `DocumentEngine`, che + tratta testate e righe tramite le classi base. + +## Conseguenze + +- Un tipo documento nuovo dell'utente funziona senza codice se usa un genere esistente; un genere nuovo è codice. +- Gli effetti sono dichiarati ma si applicano con i moduli: magazzino in M6, contabilità in M7, scadenze in M8, + e-fattura in M8. Il calcolo dei totali e delle rate è #48, le maschere sono #49-#51. +- La numerazione concorrente è provata su SQLite e PostgreSQL (test dei dati, eseguiti su PostgreSQL 16 e 17 ai tag). diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md index 92d7be3..da6f66c 100644 --- a/docs/wiki/Tabelle-azienda.md +++ b/docs/wiki/Tabelle-azienda.md @@ -113,7 +113,7 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura | **Categorie controparte** | classificazione di clienti e fornitori | | **Listini** | intestazioni dei listini: valuta, IVA inclusa, validità, **Listino base** (uno solo, in partenza `BASE`), **Derivato da** con ricarico % e arrotondamento (i prezzi sono in [Articoli e listini](Articoli-e-listini)) | | **Politiche di sconto** | sconti in cascata con un codice, come formula (`10+5`), da richiamare nelle condizioni | -| **Tipi documento** | catalogo dei documenti con numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa | +| **Tipi documento** | catalogo dei documenti con **genere** (obbligatorio), numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa | | **Centri di costo** | per l'analisi dei costi e dei ricavi | | **Commesse** | progetti o cantieri a cui imputare costi e ricavi | @@ -156,7 +156,14 @@ clienti `OC-{year}-{number:D4}` (`OC-2026-0042`), autofatture `{number}/AF/{year Il numero è assegnato in modo atomico **alla conferma** del documento (da M5); per fatture, note di credito, protocollo acquisti e registrazioni contabili **non sono ammessi buchi** nella numerazione (opzione *Ammessi buchi di numerazione* -spenta). I numeratori sono per anno: il caricamento di base crea quelli dell'anno in corso. +spenta) e la data di un documento non può precedere la **data dell'ultimo numero** del numeratore. I numeratori sono +per anno: il caricamento di base crea quelli dell'anno in corso e il primo documento di un anno nuovo crea da solo il +numeratore di quell'anno, con le stesse regole e dal numero 1. + +Il **genere** di un tipo documento dice come si comportano i suoi documenti: famiglia, ciclo di vita, effetti, righe +ammesse e documenti che può evadere (vedi [Vendite](Vendite#il-motore-dei-documenti-in-sintesi)). I tipi di base hanno +già il genere; un tipo nuovo dell'azienda (ad esempio una seconda fattura immediata con un altro sezionale) sceglie uno +dei generi esistenti e funziona senza altre impostazioni. ## Preferenze e codici automatici diff --git a/docs/wiki/Vendite.md b/docs/wiki/Vendite.md index 8d6cd6c..dcbe9c8 100644 --- a/docs/wiki/Vendite.md +++ b/docs/wiki/Vendite.md @@ -1,6 +1,6 @@ # Vendite -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M5) +> **Stato:** bozza (motore documenti pronto, maschere in arrivo) · **Ultima revisione:** 2026-11-12 · **Versione software:** non ancora rilasciata (milestone M5) > **Modulo di licenza:** CORE (XML SDI con EINV, contabilizzazione con ACCT, partite con FIN) · **Permessi principali:** `sales.invoice.issue`, `sales.deliverynote.reopen`, famiglia `sales.*` · **Specifica:** SPEC §11.3, §11.4 Il modulo **Vendite** gestisce l'intero ciclo attivo: **preventivi**, **ordini clienti**, **DDT**, **fatture** @@ -14,14 +14,35 @@ Menu **Vendite** → *Preventivi*, *Ordini clienti*, *DDT*, *Fatture*, *Note di ## Il motore dei documenti in sintesi -Ogni tipo di documento è descritto da una definizione che stabilisce: numeratore e sezionale, causale di magazzino -(se il documento carica o scarica merce), **effetti** (impegno, scarico, partite, registrazione contabile), da quali +Ogni tipo di documento (tabella *Tipi documento*, vedi [Tabelle azienda](Tabelle-azienda)) ha un **genere** e +insieme formano la sua definizione: numeratore e sezionale, causale di magazzino (se il documento carica o scarica +merce), **effetti** (impegno, scarico, partite, registrazione contabile, fattura elettronica), righe ammesse, da quali documenti può essere **evaso** (ad esempio un DDT da un ordine), tipo documento SDI (TD), causale contabile, registro IVA e modello di stampa. +| Genere | Famiglia | Ciclo di vita | Evade | +|---|---|---|---| +| Preventivo | preventivi | documento | | +| Ordine cliente | ordini clienti | documento | preventivo | +| DDT di vendita | documenti di vendita | documento | ordine cliente | +| Fattura immediata, accompagnatoria, parcella | documenti di vendita | fattura | ordine cliente, pro forma | +| Fattura differita | documenti di vendita | fattura | DDT di vendita | +| Fattura di acconto | documenti di vendita | fattura | ordine cliente | +| Nota di credito, nota di debito | documenti di vendita | fattura | fatture | +| Pro forma | documenti di vendita | documento | ordine cliente | +| Autofattura o integrazione | documenti di vendita | fattura | fattura fornitore | +| Ordine fornitore | ordini fornitori | documento | | +| DDT fornitore | documenti di acquisto | documento | ordine fornitore | +| Fattura fornitore | documenti di acquisto | semplice | ordine fornitore, DDT fornitore | +| Nota di credito fornitore | documenti di acquisto | semplice | fattura fornitore | +| Movimento di magazzino | movimenti di magazzino | semplice | | + +I DDT non accettano righe di spesa o di sconto; i movimenti di magazzino solo articoli e righe descrittive. + I documenti sono **collegati riga per riga**: quando un DDT evade un ordine, ogni riga del DDT ricorda la riga d'ordine di origine e la quantità evasa. Così Khaemhat calcola i **residui**, permette di riaprirli e scrive nel file -XML della fattura i riferimenti all'ordine (*DatiOrdineAcquisto*) e ai DDT (*DatiDDT*). +XML della fattura i riferimenti all'ordine (*DatiOrdineAcquisto*) e ai DDT (*DatiDDT*). Il collegamento vale dalla +**conferma** del documento che evade: una bozza non toglie nulla al residuo, un documento annullato lo restituisce. ``` Preventivo ──trasforma──► Ordine cliente ──evadi──► DDT ──fattura differita──► Fattura TD24 @@ -214,14 +235,34 @@ La fattura differita va emessa entro il giorno 15 del mese successivo a quello d Altri badge indicano lo stato contabile (*Non contabilizzata*), del magazzino (*Scaricato*) o della fatturazione (*Da fatturare*). +Le fatture fornitore e i movimenti di magazzino hanno solo *Bozza*, *Confermato* e *Annullato*. + +Che cosa si può fare in ogni stato: + +- Si **modifica** una bozza; di ordini, preventivi, DDT e pro forma confermati si possono ancora cambiare le righe + finché non sono evasi del tutto, ma una quantità non scende sotto quella già evasa e una riga evasa non si toglie. + Numero, data di un documento numerato e tipo non cambiano più. +- Si **elimina** solo una bozza, che non ha mai avuto un numero. +- Si **annulla** un documento confermato non ancora evaso: il numero resta e le quantità che aveva evaso tornano ai + documenti d'origine. Una fattura si annulla **con un motivo** finché il file non è stato inviato allo SDI (o dopo + uno scarto); dopo, si fa una nota di credito. Non si annulla un documento che altri hanno già evaso. +- Si **chiude** il residuo di un documento evaso in parte (o anche del tutto); **Riapri** lo riporta allo stato che + dicono le sue righe. +- Si **duplica** o **trasforma** un documento in qualunque stato. + ## Numerazione -- Formato `{prefisso}/{anno}/{numero a 6 cifre}`, ad esempio `FT/2026/000418`, per **sezionale** (FT, NC, DDT…) e - anno, configurato nei numeratori (vedi [Tabelle azienda](Tabelle-azienda)). -- Il numero è assegnato **alla conferma**, in modo atomico: le bozze non consumano numeri. +- Il formato è quello del numeratore del tipo documento, per **sezionale** e anno (vedi + [Tabelle azienda](Tabelle-azienda#numeratori)): ad esempio `{number}/{year}` per fatture e note (`418/2026`), + `OC-{year}-{number:D4}` per gli ordini (`OC-2026-0042`). +- Il numero è assegnato **alla conferma**, in modo atomico: le bozze non consumano numeri, due conferme contemporanee + non ricevono mai lo stesso numero e una conferma non riuscita restituisce il numero. Fatture, note di credito e note + di debito condividono il numeratore delle fatture. - Per fatture e note di credito **non sono ammessi buchi** e la data non può essere anteriore a quella dell'ultimo - documento numerato nello stesso sezionale. -- La data deve cadere in un **periodo fiscale aperto** (vedi esercizi e periodi in [Tabelle azienda](Tabelle-azienda)). + documento numerato nello stesso numeratore. +- La data dei documenti con effetto contabile deve cadere in un **periodo fiscale aperto** (vedi esercizi e periodi in + [Tabelle azienda](Tabelle-azienda)). +- Con il primo documento di un anno nuovo la numerazione riparte da 1. ## Calcolo dei totali @@ -258,8 +299,10 @@ e-mail dell'azienda; il canale preferito è nelle condizioni del cliente. - **Collegamenti**: la scheda omonima mostra i documenti di origine e quelli generati (ordine → DDT → fattura) con le quantità; l'icona *Collegamenti* della toolbar apre lo stesso elenco. -- **Duplica** crea un nuovo documento in bozza con le stesse righe; la **trasformazione** cambia tipo mantenendo i - collegamenti (preventivo → ordine). +- **Duplica** crea un nuovo documento in bozza con le stesse righe e la data di oggi; la **trasformazione** crea un + documento di un altro tipo della stessa direzione (vendita o acquisto). Se il nuovo tipo evade il vecchio + (preventivo → ordine, ordine → DDT, DDT → fattura differita) le righe prendono solo le **quantità residue** e + restano collegate; le righe che il nuovo tipo non accetta (ad esempio le spese in un DDT) non si copiano. - **Corrispettivi**: le vendite al dettaglio si registrano a mano come corrispettivi giornalieri. ## Report diff --git a/src/Khaemhat.Application/Documents/DocumentCopyService.cs b/src/Khaemhat.Application/Documents/DocumentCopyService.cs new file mode 100644 index 0000000..dfe45f1 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentCopyService.cs @@ -0,0 +1,159 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Data; + +namespace Khaemhat.Application.Documents; + +/// +/// Makes a new draft from an existing document (SPEC §11.3, ADR 0032): a duplicate of the same type, or a +/// transformation to another type of the same direction. When the new kind fulfils the old one (order to delivery note, +/// delivery note to deferred invoice) the lines take what is left to fulfil and remember where they come from; the +/// link is recorded when the new document is confirmed. +/// +public sealed class DocumentCopyService +{ + private readonly DocumentEngine _engine; + private readonly PermissionService _permissions; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The engine. + /// The permissions. + /// The clock. + public DocumentCopyService(DocumentEngine engine, PermissionService permissions, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(clock); + _engine = engine; + _permissions = permissions; + _clock = clock; + } + + /// Copies a document into a new draft and saves it. + /// Who copies. + /// The company. + /// The family of the source. + /// The source. + /// The type of the new document, such as DDT. + /// The lines to copy; all when empty. + /// Cancellation. + /// The new draft. + /// The copy is not possible. + public async Task CopyAsync( + Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, 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); + var company = CompanyCodes.Normalize(companyCode); + DocumentDefinition target; + await using (var uow = await _engine.Factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + target = await DocumentDefinitionService.GetAsync(uow, targetTypeCode, cancellationToken).ConfigureAwait(false); + } + + 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) + { + throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.CopyDirection]); + } + + var fulfils = target.Behavior.Fulfils(source.Header.Kind); + if (fulfils && (source.Header.Status is DocumentStatus.Draft or DocumentStatus.Closed or DocumentStatus.Cancelled)) + { + throw new ValidationFailedException([":" + DocumentErrors.CopySourceNotOpen]); + } + + var copy = new DocumentRecord { Family = target.Family, Header = Header(source.Header, target, 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))) + { + 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; + } + } + + copy.Lines.Add(Line(line, target.Family, quantity, fulfils ? source.Family : null)); + } + + if (fulfils && !copy.Lines.Any(l => l.SourceLineId is not null)) + { + throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]); + } + + return await _engine.SaveAsync(actor, company, copy, cancellationToken).ConfigureAwait(false); + } + + private static DocumentHeader Header(DocumentHeader source, DocumentDefinition target, DateOnly today) + { + var header = DocumentStores.Of(target.Family).NewHeader(); + header.DocumentTypeId = target.Type.Id; + header.Kind = target.Kind; + header.Status = DocumentStatus.Draft; + header.DocumentDate = today; + header.Year = today.Year; + header.PartyId = source.PartyId; + header.DestinationId = source.DestinationId; + header.CurrencyCode = source.CurrencyCode; + header.ExchangeRate = source.ExchangeRate; + header.PriceListId = source.PriceListId; + header.PaymentTermId = source.PaymentTermId; + header.PaymentMethodId = source.PaymentMethodId; + header.BankAccountId = source.BankAccountId; + header.SalespersonId = source.SalespersonId; + header.WarehouseId = source.WarehouseId; + header.InventoryReasonId = target.Type.InventoryReasonId ?? source.InventoryReasonId; + header.TransportReasonId = source.TransportReasonId; + header.ShippingTermId = source.ShippingTermId; + header.CarrierId = source.CarrierId; + header.GoodsAppearanceId = source.GoodsAppearanceId; + header.DeliveryDate = source.DeliveryDate; + header.FooterDiscount = source.FooterDiscount; + header.Notes = source.Notes; + return header; + } + + private static DocumentLine Line(DocumentLine source, DocumentFamily family, decimal quantity, DocumentFamily? sourceFamily) + { + var line = DocumentStores.Of(family).NewLine(); + line.Kind = source.Kind; + line.ItemId = source.ItemId; + line.Description = source.Description; + line.UnitOfMeasureId = source.UnitOfMeasureId; + line.Quantity = quantity; + line.Price = source.Price; + line.PriceSource = source.PriceSource; + line.DiscountFormula = source.DiscountFormula; + line.TaxCodeId = source.TaxCodeId; + line.TaxableAmount = source.Quantity == 0 || quantity == source.Quantity + ? source.TaxableAmount + : Math.Round(source.TaxableAmount * quantity / source.Quantity, 2, MidpointRounding.AwayFromZero); + line.WarehouseId = source.WarehouseId; + line.DeliveryDate = source.DeliveryDate; + line.AccountCode = source.AccountCode; + line.CostCenterId = source.CostCenterId; + line.JobId = source.JobId; + line.Notes = source.Notes; + if (sourceFamily is not null && DocumentLine.CarriesQuantity(source.Kind)) + { + line.SourceFamily = sourceFamily; + line.SourceLineId = source.Id; + } + + return line; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentDefinition.cs b/src/Khaemhat.Application/Documents/DocumentDefinition.cs new file mode 100644 index 0000000..6f9cc87 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentDefinition.cs @@ -0,0 +1,97 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Documents; + +/// +/// A document type of the company with the behaviour of its kind (SPEC §11.3, ADR 0032): code, kind, direction, +/// numerator, warehouse reason, effects, sources for fulfilment, SDI type, journal template, VAT register, print +/// template. +/// +/// The row of document_types. +/// The behaviour of its kind. +public sealed record DocumentDefinition(DocumentType Type, DocumentBehavior Behavior) +{ + /// The code of the type. + public string Code => Type.Code; + + /// The kind. + public DocumentKind Kind => Behavior.Kind; + + /// The family (tables). + public DocumentFamily Family => Behavior.Family; + + /// The life cycle. + public DocumentLifecycle Lifecycle => Behavior.Lifecycle; + + /// The action that confirms the documents: issue for invoices, confirm for the others. + public DocumentAction ConfirmAction => Lifecycle == DocumentLifecycle.Invoice ? DocumentAction.Issue : DocumentAction.Confirm; +} + +/// Reads the definitions of the company's document types. +public static class DocumentDefinitionService +{ + /// Error: the document type does not exist. + public const string TypeMissing = "document.type.missing"; + + /// Error: the document type has no kind. + public const string TypeWithoutKind = "document.type.no-kind"; + + /// Error: the document type is disabled. + public const string TypeDisabled = "document.type.disabled"; + + /// The definition of a document type. + /// A company unit of work. + /// The type. + /// Cancellation. + /// The definition. + /// The type is missing or has no kind. + public static async Task GetAsync(IUnitOfWork uow, long typeId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var type = await uow.Repository().GetAsync(typeId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]); + return Of(type); + } + + /// The definition of a document type by code. + /// A company unit of work. + /// The code, such as FI. + /// Cancellation. + /// The definition. + /// The type is missing or has no kind. + public static async Task GetAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var normalized = (code ?? string.Empty).Trim().ToUpperInvariant(); + var type = await uow.Repository().FindAsync(Query.For().Where(t => t.Code == normalized), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]); + return Of(type); + } + + /// The definitions of every usable type (enabled, with a kind), by code. + /// A company unit of work. + /// Cancellation. + /// The definitions. + public static async Task> ListAsync(IUnitOfWork uow, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var types = await uow.Repository().ListAsync(Query.For().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false); + return [.. types.Items.Where(t => !t.Disabled && t.DocumentKind is not null).Select(Of)]; + } + + /// The definition of a type row. + /// The row. + /// The definition. + /// The type has no kind. + public static DocumentDefinition Of(DocumentType type) + { + ArgumentNullException.ThrowIfNull(type); + return type.DocumentKind is { } kind + ? new DocumentDefinition(type, DocumentBehaviors.Of(kind)) + : throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeWithoutKind]); + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs new file mode 100644 index 0000000..7f418ea --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -0,0 +1,746 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Documents; + +/// A document with its lines, whatever the family. +public sealed class DocumentRecord +{ + /// The family. + public DocumentFamily Family { get; init; } + + /// The header. + public required DocumentHeader Header { get; init; } + + /// The lines, in order. + public List Lines { get; init; } = []; +} + +/// The error codes of the document engine; the interface translates them (Documents.json). +public static class DocumentErrors +{ + /// The document does not exist. + public const string NotFound = "document.not-found"; + + /// A customer or supplier is needed. + public const string PartyRequired = "document.party.required"; + + /// The date is missing. + public const string DateRequired = "document.date.required"; + + /// The date of a numbered document cannot change. + public const string DateNumbered = "document.date.numbered"; + + /// The type belongs to another family of documents. + public const string TypeFamily = "document.type.family"; + + /// The type of a confirmed document cannot change. + public const string TypeLocked = "document.type.locked"; + + /// The document has no lines. + public const string LinesRequired = "document.lines.required"; + + /// The kind of line is not accepted by the document. + public const string LineKindNotAllowed = "document.line.kind-not-allowed"; + + /// A line without description. + public const string LineDescriptionRequired = "document.line.description-required"; + + /// An item line without item. + public const string LineItemRequired = "document.line.item-required"; + + /// A quantity below what later documents already fulfilled. + public const string LineBelowFulfilled = "document.line.below-fulfilled"; + + /// A line fulfilled by later documents cannot be removed. + public const string LineFulfilledRemoved = "document.line.fulfilled-removed"; + + /// The line to fulfil does not exist or belongs to a kind the document does not fulfil. + public const string LineSourceInvalid = "document.line.source-invalid"; + + /// A cancelled invoice needs a reason. + public const string CancelReasonRequired = "document.cancel.reason-required"; + + /// Later documents fulfil this one: cancel them first. + public const string CancelHasFollowers = "document.cancel.has-followers"; + + /// A copy changes direction (sale to purchase). + public const string CopyDirection = "document.copy.direction"; + + /// Nothing is left to fulfil. + public const string CopyNothingLeft = "document.copy.nothing-left"; + + /// A closed or cancelled document cannot be fulfilled. + public const string CopySourceNotOpen = "document.copy.source-not-open"; +} + +/// +/// The document engine (SPEC §11.3, ADR 0032): one implementation of create, save, confirm or issue, cancel, close, +/// reopen and delete for every family, with the numbering and the fulfilment links. The typed entry points are +/// and . +/// +public sealed class DocumentEngine +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly FiscalYearService _fiscal; + private readonly TimeProvider _clock; + + /// Creates the engine. + /// The units of work. + /// The permissions. + /// The history. + /// The fiscal calendar (open periods). + /// The clock. + public DocumentEngine(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _audit = audit; + _fiscal = fiscal; + _clock = clock; + } + + internal IUnitOfWorkFactory Factory => _factory; + + internal AuditTrail Audit => _audit; + + /// The definitions of the usable document types. + /// Who asks. + /// The company. + /// Cancellation. + /// The definitions the actor can see. + public async Task> DefinitionsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = Company(actor, companyCode); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var result = new List(); + foreach (var definition in await DocumentDefinitionService.ListAsync(uow, cancellationToken).ConfigureAwait(false)) + { + if ((await _permissions.CheckAsync(actor, definition.Behavior.ReadPermission, cancellationToken).ConfigureAwait(false)).Allowed) + { + result.Add(definition); + } + } + + return result; + } + + /// A new draft of a type, not saved: today's date and the defaults of the type. + /// Who creates. + /// The company. + /// The document type, such as FI. + /// Cancellation. + /// The draft. + public async Task NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default) + { + var company = Company(actor, companyCode); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var definition = await DocumentDefinitionService.GetAsync(uow, typeCode, cancellationToken).ConfigureAwait(false); + await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false); + var header = DocumentStores.Of(definition.Family).NewHeader(); + header.DocumentTypeId = definition.Type.Id; + header.Kind = definition.Kind; + header.Status = DocumentStatus.Draft; + header.DocumentDate = Today(); + header.Year = header.DocumentDate.Year; + header.InventoryReasonId = definition.Type.InventoryReasonId; + return new DocumentRecord { Family = definition.Family, Header = header }; + } + + /// Reads a document. + /// Who reads. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document, if any. + public async Task GetAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) + { + var company = Company(actor, companyCode); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false); + if (record is not null) + { + await _permissions.DemandAsync(actor, DocumentBehaviors.Of(record.Header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false); + } + + return record; + } + + /// + /// Saves a draft (or the lines of a confirmed order still open): the engine keeps the number, state and other fields + /// it owns, numbers the lines and recomputes the fulfilment of a confirmed order. + /// + /// Who saves. + /// The company. + /// The document. + /// Cancellation. + /// The document as saved. + /// The document breaks a rule. + /// The state does not admit changes. + public async Task SaveAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = Company(actor, companyCode); + var store = DocumentStores.Of(record.Family); + long id; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var header = record.Header; + var before = header.Id == 0 ? null : await LoadAsync(uow, record.Family, header.Id, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([":" + DocumentErrors.NotFound]); + var definition = await DocumentDefinitionService.GetAsync(uow, before?.Header.DocumentTypeId ?? header.DocumentTypeId, cancellationToken).ConfigureAwait(false); + await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false); + if (before is null) + { + header.Kind = definition.Kind; + header.Status = DocumentStatus.Draft; + Release(header); + } + else + { + DocumentStateMachine.Apply(definition.Lifecycle, before.Header.Status, DocumentAction.Edit); + Keep(header, before.Header); + } + + var errors = Check(definition, record, before); + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + id = await WriteAsync(uow, store, record, before, actor.UserName, cancellationToken).ConfigureAwait(false); + if (before is not null && DocumentStateMachine.IsInForce(header.Status)) + { + await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, record.Family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + } + + /// + /// Confirms a document, or issues an invoice: checks it, numbers it, records the fulfilment of the documents its + /// lines come from. + /// + /// Who confirms. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document as confirmed. + public async Task ConfirmAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) + { + var company = Company(actor, companyCode); + var store = DocumentStores.Of(family); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + // The open period is read outside the transaction (the calendar has its own cache and connection). + var draft = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + var definition = await DocumentDefinitionService.GetAsync(uow, draft.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false); + await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false); + DocumentStateMachine.Apply(definition.Lifecycle, draft.Header.Status, definition.ConfirmAction); + if (definition.Behavior.Has(DocumentEffects.Ledger)) + { + await _fiscal.DemandOpenAsync(company, draft.Header.DocumentDate, PeriodUse.Vat, cancellationToken).ConfigureAwait(false); + } + + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, definition.ConfirmAction); + var errors = Check(definition, record, record); + if (record.Lines.Count == 0) + { + errors.Add("Lines:" + DocumentErrors.LinesRequired); + } + + if (errors.Count > 0 || record.Header.DocumentDate != draft.Header.DocumentDate) + { + throw errors.Count > 0 ? new ValidationFailedException(errors) : new Core.Common.ConcurrencyException(); + } + + var header = record.Header; + var before = header.Clone(); + if (definition.Type.NumeratorId is { } numeratorId) + { + var number = await DocumentNumberingService.NextAsync(uow, numeratorId, header.DocumentDate, cancellationToken).ConfigureAwait(false); + header.NumeratorId = number.Numerator.Id; + header.Section = number.Numerator.Section; + header.Number = number.Number; + header.DocumentNumber = number.Text; + } + + header.Year = header.DocumentDate.Year; + header.Status = next; + header.ConfirmedAt = _clock.GetUtcNow().UtcDateTime; + header.ConfirmedBy = actor.UserName; + await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false); + await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false); + await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + } + + /// + /// Cancels a document: the number stays, the fulfilment it recorded is given back. An invoice needs a reason and is + /// cancelled only before its file reaches the exchange system (or after a rejection). + /// + /// Who cancels. + /// The company. + /// The family. + /// The document. + /// Why. + /// Cancellation. + /// The document as cancelled. + public Task CancelAsync(Actor actor, string companyCode, DocumentFamily family, long id, string? reason, CancellationToken cancellationToken = default) => + ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Cancel, async (uow, definition, record, ct) => + { + var text = reason?.Trim(); + if (definition.Lifecycle == DocumentLifecycle.Invoice && string.IsNullOrEmpty(text)) + { + throw new ValidationFailedException([nameof(DocumentHeader.CancelReason) + ":" + DocumentErrors.CancelReasonRequired]); + } + + if ((await LinksFromAsync(uow, family, id, ct).ConfigureAwait(false)).Count > 0) + { + throw new ValidationFailedException([":" + DocumentErrors.CancelHasFollowers]); + } + + record.Header.CancelReason = string.IsNullOrEmpty(text) ? null : text[..Math.Min(text.Length, 200)]; + record.Header.CancelledAt = _clock.GetUtcNow().UtcDateTime; + }, + (uow, record, user, ct) => UnlinkAsync(uow, family, id, user, ct), + cancellationToken); + + /// Closes what is left to fulfil of an order, quotation, delivery note or pro forma. + /// Who closes. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document as closed. + public Task CloseAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) => + ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Close, null, null, cancellationToken); + + /// Reopens a closed document: its state comes back from the fulfilment of its lines. + /// Who reopens. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The document as reopened. + public Task ReopenAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) => + ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Reopen, null, + (uow, record, user, ct) => RefreshFulfillmentAsync(uow, family, id, user, ct), cancellationToken); + + /// + /// Records a step of the electronic invoice (file generated, sent, delivered, rejected, not delivered); the module + /// of the electronic invoice (M8) calls it. + /// + /// Who records it. + /// The company. + /// The family. + /// The document. + /// The step. + /// Cancellation. + /// The document. + public Task RecordExchangeAsync(Actor actor, string companyCode, DocumentFamily family, long id, DocumentAction action, CancellationToken cancellationToken = default) + { + if (action is not (DocumentAction.GenerateXml or DocumentAction.Send or DocumentAction.MarkDelivered or DocumentAction.MarkRejected or DocumentAction.MarkNotDelivered)) + { + throw new ArgumentOutOfRangeException(nameof(action), action, "Not a step of the electronic invoice."); + } + + return ChangeStateAsync(actor, companyCode, family, id, action, (uow, definition, record, ct) => + { + if (action == DocumentAction.GenerateXml) + { + record.Header.XmlGenerated = true; + } + + return Task.CompletedTask; + }, null, cancellationToken); + } + + /// Deletes a draft. + /// Who deletes. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// A task. + public async Task DeleteAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) + { + var company = Company(actor, companyCode); + var store = DocumentStores.Of(family); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + var definition = DocumentBehaviors.Of(record.Header.Kind); + await _permissions.DemandAsync(actor, definition.DeletePermission, cancellationToken).ConfigureAwait(false); + DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, DocumentAction.Delete); + await store.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false); + await store.RecordAsync(_audit, uow, AuditAction.Delete, id, record.Header, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// The actions the state of a document admits for an actor. + /// Who asks. + /// The document. + /// Cancellation. + /// The actions. + public async Task> ActionsAsync(Actor actor, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var behavior = DocumentBehaviors.Of(record.Header.Kind); + var result = new List(); + foreach (var action in DocumentStateMachine.Actions(behavior.Lifecycle, record.Header.Status)) + { + var permission = action switch + { + DocumentAction.Edit or DocumentAction.Copy => behavior.WritePermission, + DocumentAction.Delete => behavior.DeletePermission, + _ => behavior.ConfirmPermission, + }; + if ((await _permissions.CheckAsync(actor, permission, cancellationToken).ConfigureAwait(false)).Allowed) + { + result.Add(action); + } + } + + return result; + } + + internal static async Task LoadAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) + { + var store = DocumentStores.Of(family); + if (await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) is not { } header) + { + return null; + } + + return new DocumentRecord { Family = family, Header = header, Lines = await store.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false) }; + } + + /// Checks a document against its definition; is the stored one. + internal static List Check(DocumentDefinition definition, DocumentRecord record, DocumentRecord? before) + { + var errors = new List(); + var header = record.Header; + if (definition.Family != record.Family) + { + errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily); + } + + if (before is not null && header.DocumentTypeId != before.Header.DocumentTypeId) + { + errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeLocked); + } + + if (definition.Type.Disabled && before is null) + { + errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentDefinitionService.TypeDisabled); + } + + if (definition.Behavior.NeedsParty && header.PartyId is null) + { + errors.Add(nameof(DocumentHeader.PartyId) + ":" + DocumentErrors.PartyRequired); + } + + if (header.DocumentDate == default) + { + errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateRequired); + } + else if (before?.Header.Number is not null && header.DocumentDate != before.Header.DocumentDate) + { + errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateNumbered); + } + + var stored = before?.Lines.ToDictionary(l => l.Id) ?? []; + for (var i = 0; i < record.Lines.Count; i++) + { + var line = record.Lines[i]; + var field = "Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "."; + if (!definition.Behavior.Lines.Contains(line.Kind)) + { + errors.Add(field + nameof(DocumentLine.Kind) + ":" + DocumentErrors.LineKindNotAllowed); + } + + if (string.IsNullOrWhiteSpace(line.Description)) + { + errors.Add(field + nameof(DocumentLine.Description) + ":" + DocumentErrors.LineDescriptionRequired); + } + + if (line.Kind == DocumentLineKind.Item && line.ItemId is null) + { + errors.Add(field + nameof(DocumentLine.ItemId) + ":" + DocumentErrors.LineItemRequired); + } + + if (line.Id != 0 && stored.TryGetValue(line.Id, out var old) && old.FulfilledQuantity > 0 && line.Quantity < old.FulfilledQuantity) + { + errors.Add(field + nameof(DocumentLine.Quantity) + ":" + DocumentErrors.LineBelowFulfilled); + } + } + + var kept = record.Lines.Where(l => l.Id != 0).Select(l => l.Id).ToHashSet(); + if (before is not null && before.Lines.Any(l => !kept.Contains(l.Id) && l.FulfilledQuantity > 0)) + { + errors.Add("Lines:" + DocumentErrors.LineFulfilledRemoved); + } + + return errors; + } + + /// Writes the header and replaces the lines of a draft or open document. + internal async Task WriteAsync(IUnitOfWork uow, IDocumentStore store, DocumentRecord record, DocumentRecord? before, string userName, CancellationToken cancellationToken) + { + var header = record.Header; + if (before is null) + { + header.Year = header.DocumentDate.Year; + await store.InsertAsync(uow, header, cancellationToken).ConfigureAwait(false); + await store.RecordAsync(_audit, uow, AuditAction.Insert, header.Id, null, header, userName, cancellationToken).ConfigureAwait(false); + } + else + { + if (header.Number is null) + { + header.Year = header.DocumentDate.Year; + } + + header.RowVersion = before.Header.RowVersion; + await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false); + await store.RecordAsync(_audit, uow, AuditAction.Update, header.Id, before.Header, header, userName, cancellationToken).ConfigureAwait(false); + } + + var id = header.Id; + var previous = before?.Lines.ToDictionary(l => l.Id) ?? []; + var kept = record.Lines.Where(l => l.Id != 0 && previous.ContainsKey(l.Id)).Select(l => l.Id).ToHashSet(); + foreach (var old in previous.Values.Where(l => !kept.Contains(l.Id))) + { + await store.DeleteLineAsync(uow, old.Id, cancellationToken).ConfigureAwait(false); + } + + for (var i = 0; i < record.Lines.Count; i++) + { + var line = record.Lines[i]; + line.DocumentId = id; + line.LineNumber = i + 1; + line.SortOrder = i + 1; + if (line.Id != 0 && previous.TryGetValue(line.Id, out var old)) + { + // The fulfilment is the engine's: what the links say, not what the screen sends. + line.FulfilledQuantity = old.FulfilledQuantity; + line.SourceFamily = old.SourceFamily; + line.SourceLineId = old.SourceLineId; + line.RowVersion = old.RowVersion; + await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false); + } + else + { + line.Id = 0; + line.FulfilledQuantity = 0; + if (line.SourceLineId is null || line.SourceFamily is null) + { + line.SourceLineId = null; + line.SourceFamily = null; + } + + await store.InsertLineAsync(uow, line, cancellationToken).ConfigureAwait(false); + } + } + + return id; + } + + private async Task ChangeStateAsync( + Actor actor, + string companyCode, + DocumentFamily family, + long id, + DocumentAction action, + Func? before, + Func? after, + CancellationToken cancellationToken) + { + var company = Company(actor, companyCode); + var store = DocumentStores.Of(family); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + var definition = await DocumentDefinitionService.GetAsync(uow, record.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false); + await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false); + var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, action); + var old = record.Header.Clone(); + if (before is not null) + { + await before(uow, definition, record, cancellationToken).ConfigureAwait(false); + } + + record.Header.Status = next; + await store.UpdateAsync(uow, record.Header, cancellationToken).ConfigureAwait(false); + await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, record.Header, actor.UserName, cancellationToken).ConfigureAwait(false); + if (after is not null) + { + await after(uow, record, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + } + + // Records the links of a confirmed document towards the lines it fulfils, then the fulfilment of those documents. + private async Task LinkAsync(IUnitOfWork uow, DocumentDefinition definition, DocumentRecord record, string userName, CancellationToken cancellationToken) + { + var links = uow.Repository(); + var touched = new HashSet<(DocumentFamily, long)>(); + foreach (var line in record.Lines.Where(l => l.SourceLineId is not null && l.SourceFamily is not null)) + { + var sourceFamily = line.SourceFamily!.Value; + var source = await DocumentStores.Of(sourceFamily).GetLineAsync(uow, line.SourceLineId!.Value, cancellationToken).ConfigureAwait(false); + var sourceHeader = source is null ? null : await DocumentStores.Of(sourceFamily).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false); + if (source is null || sourceHeader is null || !definition.Behavior.Fulfils(sourceHeader.Kind) || !DocumentStateMachine.IsInForce(sourceHeader.Status)) + { + throw new ValidationFailedException(["Lines." + (line.LineNumber - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) + ".SourceLineId:" + DocumentErrors.LineSourceInvalid]); + } + + await links.InsertAsync( + new DocumentLink + { + TargetFamily = record.Family, + TargetDocumentId = record.Header.Id, + TargetLineId = line.Id, + SourceFamily = sourceFamily, + SourceDocumentId = source.DocumentId, + SourceLineId = source.Id, + Quantity = line.Quantity, + }, + cancellationToken).ConfigureAwait(false); + touched.Add((sourceFamily, source.DocumentId)); + } + + foreach (var (family, documentId) in touched) + { + await RefreshFulfillmentAsync(uow, family, documentId, userName, cancellationToken).ConfigureAwait(false); + } + } + + // Removes the links of a cancelled document and gives the quantities back to the documents it fulfilled. + private async Task UnlinkAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken) + { + var links = uow.Repository(); + var mine = (await links.ListAsync(Query.For().Where(l => l.TargetFamily == family && l.TargetDocumentId == id), cancellationToken).ConfigureAwait(false)).Items; + foreach (var link in mine) + { + await links.DeleteAsync(link.Id, cancellationToken).ConfigureAwait(false); + } + + foreach (var source in mine.Select(l => (l.SourceFamily, l.SourceDocumentId)).Distinct()) + { + await RefreshFulfillmentAsync(uow, source.SourceFamily, source.SourceDocumentId, userName, cancellationToken).ConfigureAwait(false); + } + } + + private static async Task> LinksFromAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().Where(l => l.SourceFamily == family && l.SourceDocumentId == id), cancellationToken) + .ConfigureAwait(false)).Items; + + // The quantities fulfilled of each line from the links, then the state of the document from its lines. + private async Task RefreshFulfillmentAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken) + { + var store = DocumentStores.Of(family); + var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false); + if (record is null) + { + return; + } + + var links = await LinksFromAsync(uow, family, id, cancellationToken).ConfigureAwait(false); + foreach (var line in FulfillmentCalculator.Apply(record.Lines, links)) + { + await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false); + } + + var header = record.Header; + var lifecycle = DocumentBehaviors.Of(header.Kind).Lifecycle; + var status = DocumentStateMachine.AfterFulfillment(lifecycle, header.Status, FulfillmentCalculator.StateOf(record.Lines)); + if (status != header.Status) + { + var before = header.Clone(); + header.Status = status; + await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false); + await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, userName, cancellationToken).ConfigureAwait(false); + } + } + + // The fields the engine owns keep their stored value whatever the screen sends. + private static void Keep(DocumentHeader header, DocumentHeader stored) + { + header.Kind = stored.Kind; + header.Status = stored.Status; + header.NumeratorId = stored.NumeratorId; + header.Section = stored.Section; + header.Number = stored.Number; + header.DocumentNumber = stored.DocumentNumber; + header.Year = stored.Year; + header.ConfirmedAt = stored.ConfirmedAt; + header.ConfirmedBy = stored.ConfirmedBy; + header.CancelledAt = stored.CancelledAt; + header.CancelReason = stored.CancelReason; + header.XmlGenerated = stored.XmlGenerated; + header.Posted = stored.Posted; + header.GlEntryId = stored.GlEntryId; + header.InstallmentsGenerated = stored.InstallmentsGenerated; + header.IsDemo = stored.IsDemo; + } + + // A new draft has no number and no history of states. + private static void Release(DocumentHeader header) + { + header.Id = 0; + header.NumeratorId = null; + header.Number = null; + header.DocumentNumber = null; + header.ConfirmedAt = null; + header.ConfirmedBy = null; + header.CancelledAt = null; + header.CancelReason = null; + header.XmlGenerated = false; + header.Posted = false; + header.GlEntryId = null; + header.InstallmentsGenerated = false; + } + + private static string Company(Actor actor, string companyCode) + { + ArgumentNullException.ThrowIfNull(actor); + var company = CompanyCodes.Normalize(companyCode); + if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + return company; + } + + private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); +} diff --git a/src/Khaemhat.Application/Documents/DocumentNumberingService.cs b/src/Khaemhat.Application/Documents/DocumentNumberingService.cs new file mode 100644 index 0000000..97759e5 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentNumberingService.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Documents; + +/// A number given to a document. +/// The numerator row (code and year) that gave it, already updated. +/// The progressive number. +/// The number as printed. +public sealed record AssignedNumber(DocumentNumerator Numerator, long Number, string Text); + +/// +/// Numbers documents (SPEC §11.3, ADR 0032): inside the transaction that confirms the document, under the lock of the +/// numerator and year, so that two confirmations never get the same number and a rollback gives the number back. +/// +public static class DocumentNumberingService +{ + /// Error: on a numerator without gaps the date precedes the last document numbered. + public const string DateBeforeLast = "document.number.date-before-last"; + + /// Error: the numerator of the document type does not exist. + public const string NumeratorMissing = "document.number.numerator-missing"; + + /// Error: the numerator is disabled. + public const string NumeratorDisabled = "document.number.numerator-disabled"; + + /// Error: the formatted number is longer than the column. + public const string NumberTooLong = "document.number.too-long"; + + /// The longest number as printed. + public const int MaxLength = 30; + + /// The lock that serializes the numbering of a numerator in a year. + /// The numerator code. + /// The year. + /// The lock key. + public static string LockKey(string code, int year) => "numerator:" + code + ":" + year.ToString(CultureInfo.InvariantCulture); + + /// + /// Gives the next number of a numerator for a date. The numerator row of the document type names the code; the + /// number comes from the row of the same code for the year of the date, created from the latest one when missing. + /// + /// A company unit of work inside a transaction. + /// The numerator of the document type. + /// The date of the document. + /// Cancellation. + /// The number. + /// The numerator is missing or disabled, or the date is out of sequence. + public static async Task NextAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var numerators = uow.Repository(); + var template = await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([NumeratorMissing]); + await uow.AcquireLockAsync(LockKey(template.Code, date.Year), cancellationToken).ConfigureAwait(false); + + // Read again under the lock: another transaction may have numbered (or created the year) meanwhile. + var numerator = await ForYearAsync(uow, template, date.Year, cancellationToken).ConfigureAwait(false); + if (numerator.Disabled) + { + throw new ValidationFailedException([NumeratorDisabled]); + } + + if (!numerator.GapsAllowed && numerator.LastDate is { } last && date < last) + { + throw new ValidationFailedException([DateBeforeLast]); + } + + var number = numerator.LastNumber + 1; + var text = DocumentNumberFormat.Apply(numerator.Format, number, numerator.Year, numerator.Prefix, numerator.Section); + if (text.Length > MaxLength) + { + throw new ValidationFailedException([NumberTooLong]); + } + + numerator.LastNumber = number; + if (numerator.LastDate is null || date > numerator.LastDate) + { + numerator.LastDate = date; + } + + await numerators.UpdateAsync(numerator, cancellationToken).ConfigureAwait(false); + return new AssignedNumber(numerator, number, text); + } + + /// What the next number would be, without giving it (the preview of a draft). + /// A company unit of work. + /// The numerator of the document type. + /// The date. + /// Cancellation. + /// The number as printed, or when the numerator is missing. + public static async Task PreviewAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var numerators = uow.Repository(); + if (await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false) is not { } template) + { + return null; + } + + var row = template.Year == date.Year + ? template + : await numerators.FindAsync(Query.For().Where(n => n.Code == template.Code && n.Year == date.Year), cancellationToken).ConfigureAwait(false); + var source = row ?? template; + return DocumentNumberFormat.Apply(source.Format, (row?.LastNumber ?? 0) + 1, date.Year, source.Prefix, source.Section); + } + + /// + /// The numbers missing between 1 and the last number given, over every family of documents: on a numerator without + /// gaps the list must be empty. + /// + /// A company unit of work. + /// The numerator row (code and year). + /// Cancellation. + /// The missing numbers, in order. + public static async Task> FindGapsAsync(IUnitOfWork uow, long numeratorId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var numerator = await uow.Repository().GetAsync(numeratorId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([NumeratorMissing]); + var used = new HashSet(); + foreach (var store in DocumentStores.All) + { + var sql = SqlFragment.Literal("SELECT number FROM " + store.HeaderTable + " WHERE ") + SqlFragment.Of($"numerator_id = {numeratorId} AND number IS NOT NULL"); + used.UnionWith(await uow.QueryAsync(sql, cancellationToken).ConfigureAwait(false)); + } + + var missing = new List(); + for (var n = 1L; n <= numerator.LastNumber; n++) + { + if (!used.Contains(n)) + { + missing.Add(n); + } + } + + return missing; + } + + private static async Task ForYearAsync(IUnitOfWork uow, DocumentNumerator template, int year, CancellationToken cancellationToken) + { + var numerators = uow.Repository(); + var code = template.Code; + if (await numerators.FindAsync(Query.For().Where(n => n.Code == code && n.Year == year), cancellationToken).ConfigureAwait(false) is { } row) + { + return row; + } + + // A new year: the same rules as the latest year of the code, starting from one. + var found = (await numerators.ListAsync(Query.For().Where(n => n.Code == code).OrderByDescending(n => n.Year).Take(1), cancellationToken) + .ConfigureAwait(false)).Items; + var latest = found.Count > 0 ? found[0] : template; + var created = new DocumentNumerator + { + Code = latest.Code, + Description = latest.Description, + Kind = latest.Kind, + Section = latest.Section, + Year = year, + Prefix = latest.Prefix, + Format = latest.Format, + GapsAllowed = latest.GapsAllowed, + Disabled = latest.Disabled, + }; + await numerators.InsertAsync(created, cancellationToken).ConfigureAwait(false); + return created; + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentService.cs b/src/Khaemhat.Application/Documents/DocumentService.cs new file mode 100644 index 0000000..3937ed7 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentService.cs @@ -0,0 +1,149 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; + +namespace Khaemhat.Application.Documents; + +/// A document of one family, with its lines. +/// The header. +/// The line. +public sealed class DocumentRecord + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() +{ + /// The header. + public THeader Header { get; set; } = new(); + + /// The lines, in order. + public List Lines { get; set; } = []; +} + +/// +/// The document engine for one family (SPEC §11.3): create, read, save, confirm or issue, cancel, close, reopen, +/// delete and copy, with the types of that family. The screens of quotations, orders, invoices use one each. +/// +/// The header. +/// The line. +public sealed class DocumentService + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() +{ + private readonly DocumentEngine _engine; + private readonly DocumentCopyService _copies; + + /// Creates the service. + /// The engine. + /// The copies. + public DocumentService(DocumentEngine engine, DocumentCopyService copies) + { + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(copies); + _engine = engine; + _copies = copies; + } + + /// The family. + public DocumentFamily Family => FamilyOfHeader; + + private static readonly DocumentFamily FamilyOfHeader = DocumentStores.FamilyOf(); + + /// A new draft of a type of this family, not saved. + /// Who creates. + /// The company. + /// The document type. + /// Cancellation. + /// The draft. + public async Task> NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default) + { + var record = await _engine.NewAsync(actor, companyCode, typeCode, cancellationToken).ConfigureAwait(false); + if (record.Family != Family) + { + throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily]); + } + + return Typed(record); + } + + /// Reads a document. + /// Who reads. + /// The company. + /// The document. + /// Cancellation. + /// The document, if any. + public async Task?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + await _engine.GetAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false) is { } record ? Typed(record) : null; + + /// Saves a draft, or an order still open. + /// Who saves. + /// The company. + /// The document. + /// Cancellation. + /// The document as saved. + public async Task> SaveAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var saved = await _engine.SaveAsync(actor, companyCode, new DocumentRecord { Family = Family, Header = record.Header, Lines = [.. record.Lines] }, cancellationToken) + .ConfigureAwait(false); + return Typed(saved); + } + + /// Confirms a document, or issues an invoice. + /// Who confirms. + /// The company. + /// The document. + /// Cancellation. + /// The document. + public async Task> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + Typed(await _engine.ConfirmAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false)); + + /// Cancels a document. + /// Who cancels. + /// The company. + /// The document. + /// Why (required for invoices). + /// Cancellation. + /// The document. + public async Task> CancelAsync(Actor actor, string companyCode, long id, string? reason, CancellationToken cancellationToken = default) => + Typed(await _engine.CancelAsync(actor, companyCode, Family, id, reason, cancellationToken).ConfigureAwait(false)); + + /// Closes what is left to fulfil. + /// Who closes. + /// The company. + /// The document. + /// Cancellation. + /// The document. + public async Task> CloseAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + Typed(await _engine.CloseAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false)); + + /// Reopens a closed document. + /// Who reopens. + /// The company. + /// The document. + /// Cancellation. + /// The document. + public async Task> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + Typed(await _engine.ReopenAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false)); + + /// Deletes a draft. + /// Who deletes. + /// The company. + /// The document. + /// Cancellation. + /// A task. + public Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) => + _engine.DeleteAsync(actor, companyCode, Family, id, cancellationToken); + + /// Copies a document of this family into a new draft of any type of the same direction. + /// Who copies. + /// The company. + /// The source. + /// The type of the new document. + /// The lines to copy; all when empty. + /// Cancellation. + /// The new draft, in its own family. + public Task CopyAsync( + Actor actor, string companyCode, long id, string targetTypeCode, IReadOnlyCollection? lineIds = null, CancellationToken cancellationToken = default) => + _copies.CopyAsync(actor, companyCode, Family, id, targetTypeCode, lineIds, cancellationToken); + + private static DocumentRecord Typed(DocumentRecord record) => + new() { Header = (THeader)record.Header, Lines = [.. record.Lines.Cast()] }; +} diff --git a/src/Khaemhat.Application/Documents/DocumentStores.cs b/src/Khaemhat.Application/Documents/DocumentStores.cs new file mode 100644 index 0000000..bc96935 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentStores.cs @@ -0,0 +1,203 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Core.Documents; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Documents; + +/// +/// Reads and writes the headers and lines of one family through the base classes, so that the engine can follow +/// fulfilment links and copies from one family to another (ADR 0032). +/// +internal interface IDocumentStore +{ + /// The family. + DocumentFamily Family { get; } + + /// The header table. + string HeaderTable { get; } + + /// A new header of the family. + /// The header. + DocumentHeader NewHeader(); + + /// A new line of the family. + /// The line. + DocumentLine NewLine(); + + /// Reads a header. + /// The unit of work. + /// The document. + /// Cancellation. + /// The header, if any. + Task GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Reads the lines of a document in their order. + /// The unit of work. + /// The document. + /// Cancellation. + /// The lines. + Task> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken); + + /// Reads a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// The line, if any. + Task GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Inserts a header. + /// The unit of work. + /// The header. + /// Cancellation. + /// A task. + Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken); + + /// Updates a header. + /// The unit of work. + /// The header. + /// Cancellation. + /// A task. + Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken); + + /// Deletes a header and, by cascade, its lines. + /// The unit of work. + /// The document. + /// Cancellation. + /// A task. + Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Inserts a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// A task. + Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken); + + /// Updates a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// A task. + Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken); + + /// Deletes a line. + /// The unit of work. + /// The line. + /// Cancellation. + /// A task. + Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken); + + /// Writes a change of a header in the history, under the name of its class. + /// The history. + /// The unit of work. + /// What happened. + /// The document. + /// The header before. + /// The header after. + /// Who did it. + /// Cancellation. + /// A task. + Task RecordAsync( + AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName, + CancellationToken cancellationToken); +} + +/// The store of one family. +/// The header. +/// The line. +internal sealed class DocumentStore(DocumentFamily family, string headerTable) : IDocumentStore + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() +{ + /// + public DocumentFamily Family => family; + + /// + public string HeaderTable => headerTable; + + /// + public DocumentHeader NewHeader() => new THeader(); + + /// + public DocumentLine NewLine() => new TLine(); + + /// + public async Task GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + + /// + public async Task> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken) + { + // A SQL condition: the expression of a generic parameter may reach the base property through a conversion. + var rows = await uow.Repository().ListAsync(Query.For().Where(SqlFragment.Of($"document_id = {documentId}")), cancellationToken) + .ConfigureAwait(false); + return [.. rows.Items.OrderBy(l => l.SortOrder).ThenBy(l => l.LineNumber).ThenBy(l => l.Id).Cast()]; + } + + /// + public async Task GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + + /// + public async Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) => + header.Id = await uow.Repository().InsertAsync((THeader)header, cancellationToken).ConfigureAwait(false); + + /// + public Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) => + uow.Repository().UpdateAsync((THeader)header, cancellationToken); + + /// + public Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + uow.Repository().DeleteAsync(id, cancellationToken); + + /// + public async Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) => + line.Id = await uow.Repository().InsertAsync((TLine)line, cancellationToken).ConfigureAwait(false); + + /// + public Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) => + uow.Repository().UpdateAsync((TLine)line, cancellationToken); + + /// + public Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => + uow.Repository().DeleteAsync(id, cancellationToken); + + /// + public Task RecordAsync( + 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); +} + +/// The stores of the six families. +internal static class DocumentStores +{ + private static readonly Dictionary ByFamily = new IDocumentStore[] + { + new DocumentStore(DocumentFamily.SaleQuotation, "sale_quotations"), + new DocumentStore(DocumentFamily.SaleOrder, "sale_orders"), + new DocumentStore(DocumentFamily.SaleDocument, "sale_documents"), + new DocumentStore(DocumentFamily.PurchaseOrder, "purchase_orders"), + new DocumentStore(DocumentFamily.PurchaseDocument, "purchase_documents"), + new DocumentStore(DocumentFamily.InventoryDocument, "inventory_documents"), + }.ToDictionary(s => s.Family); + + /// Every store. + public static IEnumerable All => ByFamily.Values; + + /// The store of a family. + /// The family. + /// The store. + public static IDocumentStore Of(DocumentFamily family) => ByFamily[family]; + + /// The family of a header class. + /// The header. + /// The family. + public static DocumentFamily FamilyOf() + where THeader : DocumentHeader, new() + { + var type = typeof(THeader); + return All.Single(s => s.NewHeader().GetType() == type).Family; + } +} diff --git a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs index 4564270..a1636df 100644 --- a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs +++ b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs @@ -123,6 +123,7 @@ public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder Code = d.Code, Description = d.Description, Kind = d.Kind, + DocumentKind = d.DocumentKind, NumeratorId = d.NumeratorCode is { } n && numerators.TryGetValue(n, out var numerator) ? numerator.Id : null, InventoryReasonId = d.InventoryReasonCode is { } r && reasons.TryGetValue(r, out var reason) ? reason.Id : null, EInvoiceType = d.EInvoiceType, diff --git a/src/Khaemhat.Application/Tables/TableCatalog.cs b/src/Khaemhat.Application/Tables/TableCatalog.cs index b50a8fe..50000ec 100644 --- a/src/Khaemhat.Application/Tables/TableCatalog.cs +++ b/src/Khaemhat.Application/Tables/TableCatalog.cs @@ -66,6 +66,9 @@ public sealed partial class TableCatalog /// Error: another price list is already the base one. public const string BaseDuplicate = "tables.price-list.base-duplicate"; + /// A document type without a kind. + public const string DocumentKindRequired = "tables.document-type.kind-required"; + /// The maximum depth of item categories. public const int MaxCategoryLevel = 3; @@ -303,6 +306,11 @@ public sealed partial class TableCatalog .Field("einvoice", x => x.EInvoiceType) .Rule(async (x, c, ct) => { + if (x.DocumentKind is null) + { + c.Error(nameof(DocumentType.DocumentKind), DocumentKindRequired); + } + if (!string.IsNullOrWhiteSpace(x.EInvoiceType)) { x.EInvoiceType = x.EInvoiceType.Trim().ToUpperInvariant(); diff --git a/src/Khaemhat.Core/Documents/DocumentBehaviors.cs b/src/Khaemhat.Core/Documents/DocumentBehaviors.cs new file mode 100644 index 0000000..e9f4e47 --- /dev/null +++ b/src/Khaemhat.Core/Documents/DocumentBehaviors.cs @@ -0,0 +1,113 @@ +namespace Khaemhat.Core.Documents; + +/// How the documents of a kind behave (ADR 0032). +/// The kind. +/// The tables that hold them. +/// Customer, supplier or internal. +/// The states they go through. +/// What confirming them does. +/// The line kinds they accept. +/// The kinds whose lines they fulfil (order to delivery note, delivery note to invoice...). +/// The permission to see them. +/// The permission to create and change drafts. +/// The permission to confirm or issue, cancel, close and reopen. +/// The permission to delete drafts. +public sealed record DocumentBehavior( + DocumentKind Kind, + DocumentFamily Family, + DocumentDirection Direction, + DocumentLifecycle Lifecycle, + DocumentEffects Effects, + IReadOnlyList Lines, + IReadOnlyList Sources, + string ReadPermission, + string WritePermission, + string ConfirmPermission, + string DeletePermission) +{ + /// Whether the documents need a customer or supplier. + public bool NeedsParty => Direction != DocumentDirection.Internal; + + /// Whether the documents have the given effect. + /// The effect. + /// Whether they have it. + public bool Has(DocumentEffects effect) => (Effects & effect) == effect; + + /// Whether the documents fulfil the lines of documents of another kind. + /// The kind of the source. + /// Whether a copy from it creates fulfilment links. + public bool Fulfils(DocumentKind source) => Sources.Contains(source); +} + +/// The behaviour of every . +public static class DocumentBehaviors +{ + private static readonly DocumentLineKind[] Commercial = + [DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description, DocumentLineKind.Expense, DocumentLineKind.Discount]; + + private static readonly DocumentLineKind[] Goods = [DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description]; + + private static readonly DocumentLineKind[] Stock = [DocumentLineKind.Item, DocumentLineKind.Description]; + + private static readonly DocumentKind[] SaleInvoices = + [ + DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, + DocumentKind.Fee, + ]; + + private static readonly Dictionary ByKind = Build().ToDictionary(b => b.Kind); + + /// Every behaviour, in the order of . + public static IReadOnlyList All { get; } = [.. ByKind.Values.OrderBy(b => b.Kind)]; + + /// The behaviour of a kind. + /// The kind. + /// The behaviour. + public static DocumentBehavior Of(DocumentKind kind) => + ByKind.TryGetValue(kind, out var behavior) ? behavior : throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown document kind."); + + /// The kinds kept in a family. + /// The family. + /// The kinds. + public static IReadOnlyList KindsOf(DocumentFamily family) => [.. All.Where(b => b.Family == family).Select(b => b.Kind)]; + + private static IEnumerable Build() + { + const DocumentEffects Invoice = DocumentEffects.Ledger | DocumentEffects.Installments | DocumentEffects.EInvoice; + var quote = Permissions("sales.quote"); + var order = Permissions("sales.order"); + var delivery = Permissions("sales.delivery"); + var invoice = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.issue", "sales.invoice.delete"); + var proForma = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.write", "sales.invoice.delete"); + var purchaseOrder = Permissions("purchases.order"); + var purchaseInvoice = Permissions("purchases.invoice"); + var entry = new Perms("inventory.entry.read", "inventory.entry.write", "inventory.entry.post", "inventory.entry.write"); + + yield return Make(DocumentKind.Quotation, DocumentFamily.SaleQuotation, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [], quote); + yield return Make(DocumentKind.SalesOrder, DocumentFamily.SaleOrder, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Commitment, Commercial, [DocumentKind.Quotation], order); + yield return Make(DocumentKind.DeliveryNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.SalesOrder], delivery); + yield return Make(DocumentKind.ImmediateInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice); + yield return Make(DocumentKind.AccompanyingInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice | DocumentEffects.Inventory, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice); + yield return Make(DocumentKind.DeferredInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.DeliveryNote], invoice); + yield return Make(DocumentKind.DownPaymentInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder], invoice); + yield return Make(DocumentKind.CreditNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice); + yield return Make(DocumentKind.DebitNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice); + yield return Make(DocumentKind.Fee, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice); + yield return Make(DocumentKind.ProForma, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [DocumentKind.SalesOrder], proForma); + yield return Make(DocumentKind.SelfInvoice, DocumentFamily.SaleDocument, DocumentDirection.Purchase, DocumentLifecycle.Invoice, DocumentEffects.Ledger | DocumentEffects.EInvoice, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice); + yield return Make(DocumentKind.PurchaseOrder, DocumentFamily.PurchaseOrder, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Ordered, Commercial, [], purchaseOrder); + yield return Make(DocumentKind.PurchaseDeliveryNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.PurchaseOrder], entry); + yield return Make(DocumentKind.PurchaseInvoice, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseOrder, DocumentKind.PurchaseDeliveryNote], purchaseInvoice); + yield return Make(DocumentKind.PurchaseCreditNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice); + yield return Make(DocumentKind.InventoryEntry, DocumentFamily.InventoryDocument, DocumentDirection.Internal, DocumentLifecycle.Simple, DocumentEffects.Inventory, Stock, [], entry); + } + + private static Perms Permissions(string area) => new(area + ".read", area + ".write", area + ".write", area + ".write"); + + private static DocumentBehavior Make( + DocumentKind kind, DocumentFamily family, DocumentDirection direction, DocumentLifecycle lifecycle, DocumentEffects effects, + DocumentLineKind[] lines, DocumentKind[] sources, Perms perms) => + new(kind, family, direction, lifecycle, effects, lines, sources, perms.Read, perms.Write, perms.Confirm, perms.Delete); + + private sealed record Perms(string Read, string Write, string Confirm, string Delete); +} diff --git a/src/Khaemhat.Core/Documents/DocumentKinds.cs b/src/Khaemhat.Core/Documents/DocumentKinds.cs new file mode 100644 index 0000000..08eba25 --- /dev/null +++ b/src/Khaemhat.Core/Documents/DocumentKinds.cs @@ -0,0 +1,235 @@ +namespace Khaemhat.Core.Documents; + +/// The family of a document: the pair of tables that holds it (SPEC §11.3). +public enum DocumentFamily +{ + /// Quotations (sale_quotations). + SaleQuotation = 0, + + /// Customer orders (sale_orders). + SaleOrder = 1, + + /// Delivery notes, invoices, credit and debit notes, pro forma, fees, self-invoices (sale_documents). + SaleDocument = 2, + + /// Supplier orders (purchase_orders). + PurchaseOrder = 3, + + /// Supplier delivery notes, invoices and credit notes (purchase_documents). + PurchaseDocument = 4, + + /// Warehouse entries (inventory_documents). + InventoryDocument = 5, +} + +/// Who the document is with. +public enum DocumentDirection +{ + /// A customer: the company sells. + Sale = 0, + + /// A supplier: the company buys. + Purchase = 1, + + /// Nobody: an internal document. + Internal = 2, +} + +/// +/// What a document is, which decides how it behaves (ADR 0032). A document type of the company chooses a kind and adds +/// its numerator, reasons and templates. +/// +public enum DocumentKind +{ + /// A quotation to a customer. + Quotation = 0, + + /// A customer order. + SalesOrder = 1, + + /// A delivery note (DDT) to a customer. + DeliveryNote = 2, + + /// An immediate invoice. + ImmediateInvoice = 3, + + /// An accompanying invoice: an invoice that is also the delivery note. + AccompanyingInvoice = 4, + + /// A deferred invoice of one or more delivery notes. + DeferredInvoice = 5, + + /// A down payment invoice. + DownPaymentInvoice = 6, + + /// A credit note to a customer. + CreditNote = 7, + + /// A debit note to a customer. + DebitNote = 8, + + /// A professional fee invoice (parcella). + Fee = 9, + + /// A pro forma invoice, without fiscal effects. + ProForma = 10, + + /// A self-invoice or integration of a purchase (reverse charge, purchases from abroad). + SelfInvoice = 11, + + /// An order to a supplier. + PurchaseOrder = 12, + + /// A delivery note of a supplier (goods received). + PurchaseDeliveryNote = 13, + + /// An invoice of a supplier. + PurchaseInvoice = 14, + + /// A credit note of a supplier. + PurchaseCreditNote = 15, + + /// A warehouse entry: loads, unloads, transfers. + InventoryEntry = 16, +} + +/// The life cycle a document follows (ADR 0032). +public enum DocumentLifecycle +{ + /// Draft, confirmed, partially fulfilled, fulfilled, closed, cancelled: quotations, orders, delivery notes, pro forma. + Order = 0, + + /// Draft, issued, then the states of the exchange system: sale invoices and self-invoices. + Invoice = 1, + + /// Draft, confirmed, cancelled: supplier invoices, warehouse entries. + Simple = 2, +} + +/// The state of a document (SPEC §11.3). +public enum DocumentStatus +{ + /// Being written: no number, no effects. + Draft = 0, + + /// Confirmed: numbered, effects applied. + Confirmed = 1, + + /// Some lines fulfilled by later documents. + PartiallyFulfilled = 2, + + /// Every line fulfilled. + Fulfilled = 3, + + /// Closed by hand: what is left will not be fulfilled. + Closed = 4, + + /// Cancelled: the number stays, the effects are removed. + Cancelled = 5, + + /// An invoice issued: numbered and no longer changeable. + Issued = 6, + + /// The electronic invoice file has been generated. + SdiGenerated = 7, + + /// The electronic invoice has been sent to the exchange system. + SdiSent = 8, + + /// The exchange system delivered the invoice. + SdiDelivered = 9, + + /// The exchange system rejected the invoice. + SdiRejected = 10, + + /// The exchange system could not deliver the invoice (made available to the customer). + SdiNotDelivered = 11, +} + +/// What a user or a procedure can do with a document; the state machine says when. +public enum DocumentAction +{ + /// Change the header or the lines. + Edit = 0, + + /// Delete a draft that was never numbered. + Delete = 1, + + /// Confirm: number and apply the effects (orders, delivery notes, simple documents). + Confirm = 2, + + /// Issue an invoice: number it and make it unchangeable. + Issue = 3, + + /// Cancel: keep the number, remove the effects. + Cancel = 4, + + /// Close what is left to fulfil. + Close = 5, + + /// Reopen a closed document. + Reopen = 6, + + /// Make a new draft from the document (duplicate or transform). + Copy = 7, + + /// Record that the electronic invoice file was generated. + GenerateXml = 8, + + /// Record that the electronic invoice was sent. + Send = 9, + + /// Record the delivery receipt. + MarkDelivered = 10, + + /// Record the rejection. + MarkRejected = 11, + + /// Record that the invoice could not be delivered. + MarkNotDelivered = 12, +} + +/// What confirming a document does to the rest of the company's data (applied by the modules: M6, M7, M8). +[Flags] +public enum DocumentEffects +{ + /// No effect. + None = 0, + + /// Moves stock (load or unload by the warehouse reason). + Inventory = 1, + + /// Commits stock to customers (orders). + Commitment = 2, + + /// Records quantities ordered from suppliers. + Ordered = 4, + + /// Posts to the general ledger and the VAT registers. + Ledger = 8, + + /// Generates the installments of the payment schedule. + Installments = 16, + + /// Produces an electronic invoice. + EInvoice = 32, +} + +/// The kind of a document line. +public enum DocumentLineKind +{ + /// An item of the catalogue, with quantity and price. + Item = 0, + + /// A line with quantity and price but no item. + Free = 1, + + /// Text only. + Description = 2, + + /// An ancillary expense (transport, collection). + Expense = 3, + + /// A discount, premium or allowance. + Discount = 4, +} diff --git a/src/Khaemhat.Core/Documents/DocumentStateMachine.cs b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs new file mode 100644 index 0000000..69b5b60 --- /dev/null +++ b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs @@ -0,0 +1,157 @@ +namespace Khaemhat.Core.Documents; + +/// +/// The states of the three life cycles and the actions each state admits (SPEC §11.3, ADR 0032). The fulfilment states +/// are not reached by actions: computes them. +/// +public static class DocumentStateMachine +{ + private static readonly Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary> Rules = Build(); + + /// The states a life cycle uses, in order. + /// The life cycle. + /// The states. + public static IReadOnlyList States(DocumentLifecycle lifecycle) => + [.. Rules.Keys.Where(k => k.Item1 == lifecycle).Select(k => k.Item2).OrderBy(s => s)]; + + /// The actions a state admits. + /// The life cycle. + /// The state. + /// The actions, in the order of . + public static IReadOnlyList Actions(DocumentLifecycle lifecycle, DocumentStatus status) => + Rules.TryGetValue((lifecycle, status), out var actions) ? [.. actions.Keys.OrderBy(a => a)] : []; + + /// Whether a state admits an action. + /// The life cycle. + /// The state. + /// The action. + /// Whether it is admitted. + public static bool Allows(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) => + Rules.TryGetValue((lifecycle, status), out var actions) && actions.ContainsKey(action); + + /// The state after an action. + /// The life cycle. + /// The state. + /// The action. + /// The new state (the same one for actions that do not move it, such as edit and copy). + /// The state does not admit the action. + public static DocumentStatus Apply(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) => + Rules.TryGetValue((lifecycle, status), out var actions) && actions.TryGetValue(action, out var next) + ? next + : throw new InvalidDocumentActionException(lifecycle, status, action); + + /// Whether the header and lines can change in a state. + /// The life cycle. + /// The state. + /// Whether they can. + public static bool IsEditable(DocumentLifecycle lifecycle, DocumentStatus status) => Allows(lifecycle, status, DocumentAction.Edit); + + /// Whether a document in this state counts: confirmed or issued, and not cancelled. + /// The state. + /// Whether its effects and links are in force. + public static bool IsInForce(DocumentStatus status) => status is not (DocumentStatus.Draft or DocumentStatus.Cancelled); + + /// + /// The state of a document after its lines were fulfilled: only confirmed, partially fulfilled and fulfilled + /// documents of the order life cycle move; the others keep their state. + /// + /// The life cycle. + /// The state. + /// What the lines say. + /// The new state. + public static DocumentStatus AfterFulfillment(DocumentLifecycle lifecycle, DocumentStatus status, FulfillmentState fulfillment) => + lifecycle == DocumentLifecycle.Order && status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled or DocumentStatus.Fulfilled + ? fulfillment switch + { + FulfillmentState.Fulfilled => DocumentStatus.Fulfilled, + FulfillmentState.Partial => DocumentStatus.PartiallyFulfilled, + _ => DocumentStatus.Confirmed, + } + : status; + + private static Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary> Build() + { + var rules = new Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary>(); + + void Add(DocumentLifecycle lifecycle, DocumentStatus status, params (DocumentAction Action, DocumentStatus? Next)[] actions) => + rules[(lifecycle, status)] = actions.ToDictionary(a => a.Action, a => a.Next ?? status); + + const DocumentAction Copy = DocumentAction.Copy; + const DocumentAction Edit = DocumentAction.Edit; + + // Orders, quotations, delivery notes, pro forma: changeable until something is fulfilled. + Add(DocumentLifecycle.Order, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Confirm, DocumentStatus.Confirmed), (Copy, null)); + Add(DocumentLifecycle.Order, DocumentStatus.Confirmed, (Edit, null), (Copy, null), (DocumentAction.Cancel, DocumentStatus.Cancelled), (DocumentAction.Close, DocumentStatus.Closed)); + Add(DocumentLifecycle.Order, DocumentStatus.PartiallyFulfilled, (Edit, null), (Copy, null), (DocumentAction.Close, DocumentStatus.Closed)); + Add(DocumentLifecycle.Order, DocumentStatus.Fulfilled, (Copy, null), (DocumentAction.Close, DocumentStatus.Closed)); + Add(DocumentLifecycle.Order, DocumentStatus.Closed, (Copy, null), (DocumentAction.Reopen, DocumentStatus.Confirmed)); + Add(DocumentLifecycle.Order, DocumentStatus.Cancelled, (Copy, null)); + + // Invoices: unchangeable once issued; cancelled (with a reason) only while the file has not reached the + // exchange system or after a rejection, otherwise a credit note. + Add(DocumentLifecycle.Invoice, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Issue, DocumentStatus.Issued), (Copy, null)); + Add(DocumentLifecycle.Invoice, DocumentStatus.Issued, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled)); + Add(DocumentLifecycle.Invoice, DocumentStatus.SdiGenerated, (Copy, null), (DocumentAction.GenerateXml, null), (DocumentAction.Send, DocumentStatus.SdiSent), (DocumentAction.Cancel, DocumentStatus.Cancelled)); + Add(DocumentLifecycle.Invoice, DocumentStatus.SdiSent, (Copy, null), (DocumentAction.MarkDelivered, DocumentStatus.SdiDelivered), + (DocumentAction.MarkRejected, DocumentStatus.SdiRejected), (DocumentAction.MarkNotDelivered, DocumentStatus.SdiNotDelivered)); + Add(DocumentLifecycle.Invoice, DocumentStatus.SdiRejected, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled)); + Add(DocumentLifecycle.Invoice, DocumentStatus.SdiDelivered, (Copy, null)); + Add(DocumentLifecycle.Invoice, DocumentStatus.SdiNotDelivered, (Copy, null)); + Add(DocumentLifecycle.Invoice, DocumentStatus.Cancelled, (Copy, null)); + + // Supplier invoices and warehouse entries. + Add(DocumentLifecycle.Simple, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Confirm, DocumentStatus.Confirmed), (Copy, null)); + Add(DocumentLifecycle.Simple, DocumentStatus.Confirmed, (Copy, null), (DocumentAction.Cancel, DocumentStatus.Cancelled)); + Add(DocumentLifecycle.Simple, DocumentStatus.Cancelled, (Copy, null)); + return rules; + } +} + +/// An action the state of the document does not admit. +public sealed class InvalidDocumentActionException : InvalidOperationException +{ + /// The error code for the interface. + public const string Code = "document.action.not-allowed"; + + /// Creates the exception. + public InvalidDocumentActionException() + : base(Code) + { + } + + /// Creates the exception. + /// The message. + public InvalidDocumentActionException(string message) + : base(message) + { + } + + /// Creates the exception. + /// The message. + /// The cause. + public InvalidDocumentActionException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// Creates the exception. + /// The life cycle. + /// The state. + /// The refused action. + public InvalidDocumentActionException(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) + : base($"A {lifecycle} document in state {status} does not admit {action}.") + { + Lifecycle = lifecycle; + Status = status; + Action = action; + } + + /// The life cycle. + public DocumentLifecycle Lifecycle { get; } + + /// The state. + public DocumentStatus Status { get; } + + /// The refused action. + public DocumentAction Action { get; } +} diff --git a/src/Khaemhat.Core/Documents/Documents.cs b/src/Khaemhat.Core/Documents/Documents.cs new file mode 100644 index 0000000..2f05e01 --- /dev/null +++ b/src/Khaemhat.Core/Documents/Documents.cs @@ -0,0 +1,329 @@ +using Khaemhat.Core.Entities; +using Khaemhat.Core.Items; + +namespace Khaemhat.Core.Documents; + +/// +/// The header of a document (SPEC §11.3): the same columns in the six families of tables. The totals are written by the +/// totals calculator (#48); the flags by printing, sending, posting and the electronic invoice. +/// +public abstract class DocumentHeader : Entity, IDemoMarkable +{ + /// The document type of the company. + public long DocumentTypeId { get; set; } + + /// The kind, copied from the type when the document is created. + public DocumentKind Kind { get; set; } + + /// The state. + public DocumentStatus Status { get; set; } + + /// The numerator row (code and year) that gave the number. + public long? NumeratorId { get; set; } + + /// The section (sezionale) of the numerator. + public string? Section { get; set; } + + /// The progressive number; empty until confirmation. + public long? Number { get; set; } + + /// The number as printed, such as 12/2026. + public string? DocumentNumber { get; set; } + + /// The date of the document. + public DateOnly DocumentDate { get; set; } + + /// The year of the numbering. + public int Year { get; set; } + + /// The customer or supplier. + public long? PartyId { get; set; } + + /// The destination (an address of the party). + public long? DestinationId { get; set; } + + /// The reference of the other side: customer order number, supplier invoice or delivery note number. + public string? ExternalReference { get; set; } + + /// The date of the reference. + public DateOnly? ExternalDate { get; set; } + + /// The currency. + public string CurrencyCode { get; set; } = "EUR"; + + /// The exchange rate to euro. + public decimal ExchangeRate { get; set; } = 1m; + + /// The price list. + public long? PriceListId { get; set; } + + /// The payment terms. + public long? PaymentTermId { get; set; } + + /// The payment method. + public long? PaymentMethodId { get; set; } + + /// The bank account of the company that collects or pays. + public long? BankAccountId { get; set; } + + /// The agent. + public long? SalespersonId { get; set; } + + /// The warehouse. + public long? WarehouseId { get; set; } + + /// The warehouse reason. + public long? InventoryReasonId { get; set; } + + /// The reason of the transport. + public long? TransportReasonId { get; set; } + + /// The shipping terms (porto). + public long? ShippingTermId { get; set; } + + /// The carrier. + public long? CarrierId { get; set; } + + /// The appearance of the goods. + public long? GoodsAppearanceId { get; set; } + + /// The number of packages. + public int? Packages { get; set; } + + /// The gross weight in kg. + public decimal? GrossWeight { get; set; } + + /// The net weight in kg. + public decimal? NetWeight { get; set; } + + /// When the transport starts. + public DateTime? TransportStart { get; set; } + + /// Until when a quotation is valid. + public DateOnly? ValidUntil { get; set; } + + /// The delivery date requested or promised. + public DateOnly? DeliveryDate { get; set; } + + /// The revision of a quotation. + public int Revision { get; set; } + + /// Printed at least once. + public bool Printed { get; set; } + + /// Sent by e-mail at least once. + public bool Sent { get; set; } + + /// Posted to the ledger. + public bool Posted { get; set; } + + /// Installments generated in the payment schedule. + public bool InstallmentsGenerated { get; set; } + + /// Electronic invoice file generated. + public bool XmlGenerated { get; set; } + + /// The taxable amount. + public decimal TaxableAmount { get; set; } + + /// The tax. + public decimal TaxAmount { get; set; } + + /// The total of the document. + public decimal TotalAmount { get; set; } + + /// The discount on the total (percent formula, such as 5 or 10+5). + public string? FooterDiscount { get; set; } + + /// The ancillary expenses. + public decimal ExpensesAmount { get; set; } + + /// The stamp duty. + public decimal StampDuty { get; set; } + + /// The withholding tax. + public decimal WithholdingAmount { get; set; } + + /// The social security contribution (cassa previdenza). + public decimal SocialSecurityAmount { get; set; } + + /// The amount to pay. + public decimal NetAmount { get; set; } + + /// The notes printed on the document. + public string? Notes { get; set; } + + /// The ledger entry, once posted (M7). + public long? GlEntryId { get; set; } + + /// The VAT protocol of a supplier invoice. + public long? VatProtocol { get; set; } + + /// When the document was confirmed or issued. + public DateTime? ConfirmedAt { get; set; } + + /// Who confirmed or issued it. + public string? ConfirmedBy { get; set; } + + /// When it was cancelled. + public DateTime? CancelledAt { get; set; } + + /// Why it was cancelled. + public string? CancelReason { get; set; } + + /// + public bool IsDemo { get; set; } + + /// A shallow copy of the same class (the state before a change, for the history). + /// The copy. + public DocumentHeader Clone() => (DocumentHeader)MemberwiseClone(); +} + +/// A line of a document (SPEC §11.3). +public abstract class DocumentLine : Entity +{ + /// The document. + public long DocumentId { get; set; } + + /// The progressive number of the line (1, 2...), the one printed and sent. + public int LineNumber { get; set; } + + /// The kind of line. + public DocumentLineKind Kind { get; set; } + + /// The item. + public long? ItemId { get; set; } + + /// The description. + public string Description { get; set; } = string.Empty; + + /// The unit of measure. + public long? UnitOfMeasureId { get; set; } + + /// The quantity. + public decimal Quantity { get; set; } + + /// The unit price. + public decimal Price { get; set; } + + /// Where the price comes from. + public PriceSource PriceSource { get; set; } + + /// The discounts, such as 10+5. + public string? DiscountFormula { get; set; } + + /// The VAT code. + public long? TaxCodeId { get; set; } + + /// The taxable amount of the line. + public decimal TaxableAmount { get; set; } + + /// The warehouse of the line, when different from the header. + public long? WarehouseId { get; set; } + + /// The delivery date of the line. + public DateOnly? DeliveryDate { get; set; } + + /// How much later documents fulfilled. + public decimal FulfilledQuantity { get; set; } + + /// The rest will not be fulfilled (line closed by hand). + public bool FulfillmentClosed { get; set; } + + /// The family of the line this one was copied from to fulfil it. + public DocumentFamily? SourceFamily { get; set; } + + /// The line this one fulfils. + public long? SourceLineId { get; set; } + + /// The ledger account (M7). + public string? AccountCode { get; set; } + + /// The cost centre. + public long? CostCenterId { get; set; } + + /// The job (commessa). + public long? JobId { get; set; } + + /// Notes of the line. + public string? Notes { get; set; } + + /// The order on screen and in print. + public int SortOrder { get; set; } + + /// What is left to fulfil: zero for closed lines and lines without quantity. + public decimal Residual => FulfillmentClosed || !CarriesQuantity(Kind) ? 0m : Math.Max(0m, Quantity - FulfilledQuantity); + + /// A shallow copy of the same class. + /// The copy. + public DocumentLine Clone() => (DocumentLine)MemberwiseClone(); + + /// Whether lines of a kind carry a quantity that later documents can fulfil. + /// The kind. + /// Whether they do. + public static bool CarriesQuantity(DocumentLineKind kind) => kind is DocumentLineKind.Item or DocumentLineKind.Free; +} + +/// A quotation (sale_quotations). +public sealed class SaleQuotation : DocumentHeader; + +/// A line of a quotation. +public sealed class SaleQuotationLine : DocumentLine; + +/// A customer order (sale_orders). +public sealed class SaleOrder : DocumentHeader; + +/// A line of a customer order. +public sealed class SaleOrderLine : DocumentLine; + +/// A delivery note, invoice, credit or debit note, pro forma, fee or self-invoice (sale_documents). +public sealed class SaleDocument : DocumentHeader; + +/// A line of a sale document. +public sealed class SaleDocumentLine : DocumentLine; + +/// A supplier order (purchase_orders). +public sealed class PurchaseOrder : DocumentHeader; + +/// A line of a supplier order. +public sealed class PurchaseOrderLine : DocumentLine; + +/// A supplier delivery note, invoice or credit note (purchase_documents). +public sealed class PurchaseDocument : DocumentHeader; + +/// A line of a purchase document. +public sealed class PurchaseDocumentLine : DocumentLine; + +/// A warehouse entry (inventory_documents). +public sealed class InventoryDocument : DocumentHeader; + +/// A line of a warehouse entry. +public sealed class InventoryDocumentLine : DocumentLine; + +/// +/// A fulfilment link (document_links): a line of a confirmed document fulfils a quantity of a line of an earlier +/// one (order to delivery note, delivery note to deferred invoice, supplier delivery note to supplier invoice). +/// +public sealed class DocumentLink : Entity +{ + /// The family of the fulfilling document. + public DocumentFamily TargetFamily { get; set; } + + /// The fulfilling document. + public long TargetDocumentId { get; set; } + + /// The fulfilling line. + public long TargetLineId { get; set; } + + /// The family of the fulfilled document. + public DocumentFamily SourceFamily { get; set; } + + /// The fulfilled document. + public long SourceDocumentId { get; set; } + + /// The fulfilled line. + public long SourceLineId { get; set; } + + /// The quantity fulfilled. + public decimal Quantity { get; set; } +} diff --git a/src/Khaemhat.Core/Documents/FulfillmentCalculator.cs b/src/Khaemhat.Core/Documents/FulfillmentCalculator.cs new file mode 100644 index 0000000..53f878b --- /dev/null +++ b/src/Khaemhat.Core/Documents/FulfillmentCalculator.cs @@ -0,0 +1,61 @@ +namespace Khaemhat.Core.Documents; + +/// What the lines of a document say about its fulfilment. +public enum FulfillmentState +{ + /// Nothing fulfilled. + None = 0, + + /// Something fulfilled, something left. + Partial = 1, + + /// Every line fulfilled or closed. + Fulfilled = 2, +} + +/// Line-by-line fulfilment (SPEC §11.3, ADR 0032): quantities from the links, state of the document from the lines. +public static class FulfillmentCalculator +{ + /// Writes on each line the quantity fulfilled by the links that point to it. + /// The lines of the fulfilled document. + /// The links in force (of confirmed documents) towards those lines. + /// The lines whose quantity changed. + public static IReadOnlyList Apply(IEnumerable lines, IEnumerable links) + { + ArgumentNullException.ThrowIfNull(lines); + ArgumentNullException.ThrowIfNull(links); + var byLine = links.GroupBy(l => l.SourceLineId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity)); + var changed = new List(); + foreach (var line in lines) + { + var fulfilled = byLine.GetValueOrDefault(line.Id); + if (line.FulfilledQuantity != fulfilled) + { + line.FulfilledQuantity = fulfilled; + changed.Add(line); + } + } + + return changed; + } + + /// The fulfilment of a document from its lines; lines without quantity do not count. + /// The lines. + /// The state. + public static FulfillmentState StateOf(IEnumerable lines) + { + ArgumentNullException.ThrowIfNull(lines); + var counted = lines.Where(l => DocumentLine.CarriesQuantity(l.Kind) && l.Quantity > 0).ToList(); + if (counted.Count == 0) + { + return FulfillmentState.None; + } + + if (counted.All(l => l.Residual == 0)) + { + return FulfillmentState.Fulfilled; + } + + return counted.Any(l => l.FulfilledQuantity > 0 || l.FulfillmentClosed) ? FulfillmentState.Partial : FulfillmentState.None; + } +} diff --git a/src/Khaemhat.Core/Tables/BaseTables.cs b/src/Khaemhat.Core/Tables/BaseTables.cs index 77326c5..e5ca6fa 100644 --- a/src/Khaemhat.Core/Tables/BaseTables.cs +++ b/src/Khaemhat.Core/Tables/BaseTables.cs @@ -408,6 +408,9 @@ public sealed class DocumentNumerator : CodedEntity /// Whether gaps are allowed (never for invoices, credit notes and final entries). public bool GapsAllowed { get; set; } + + /// The date of the last document numbered: without gaps, no later document may have an earlier date. + public DateOnly? LastDate { get; set; } } /// A type of document: the links between a document and its numerator, warehouse reason and SDI type. @@ -416,6 +419,9 @@ public sealed class DocumentType : CodedEntity /// The family of document. public NumeratorKind Kind { get; set; } + /// What the documents of this type are, which decides how they behave (ADR 0032); empty for types not yet usable. + public Documents.DocumentKind? DocumentKind { get; set; } + /// The numerator. public long? NumeratorId { get; set; } diff --git a/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs b/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs new file mode 100644 index 0000000..f06835a --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/DocumentMaps.cs @@ -0,0 +1,83 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// The columns shared by the six document headers (ADR 0032). +/// The header. +public abstract class DocumentHeaderMap : EntityMap + where T : DocumentHeader, new() +{ + /// Creates the map. + /// The table of the family. + protected DocumentHeaderMap(string table) + { + ToTable(table); + Map(x => x.Section).MaxLength(10); + Map(x => x.DocumentNumber).MaxLength(30); + Map(x => x.ExternalReference).MaxLength(40); + Map(x => x.CurrencyCode).MaxLength(3); + Map(x => x.FooterDiscount).MaxLength(30); + Map(x => x.ConfirmedBy).MaxLength(100); + Map(x => x.CancelReason).MaxLength(200); + } +} + +/// The columns shared by the six tables of lines. +/// The line. +public abstract class DocumentLineMap : EntityMap + where T : DocumentLine, new() +{ + /// Creates the map. + /// The table of the lines. + protected DocumentLineMap(string table) + { + ToTable(table); + Map(x => x.Description).MaxLength(1000); + Map(x => x.DiscountFormula).MaxLength(30); + Map(x => x.AccountCode).MaxLength(20); + } +} + +/// Map of to sale_quotations. +public sealed class SaleQuotationMap() : DocumentHeaderMap("sale_quotations"); + +/// Map of to sale_quotation_lines. +public sealed class SaleQuotationLineMap() : DocumentLineMap("sale_quotation_lines"); + +/// Map of to sale_orders. +public sealed class SaleOrderMap() : DocumentHeaderMap("sale_orders"); + +/// Map of to sale_order_lines. +public sealed class SaleOrderLineMap() : DocumentLineMap("sale_order_lines"); + +/// Map of to sale_documents. +public sealed class SaleDocumentMap() : DocumentHeaderMap("sale_documents"); + +/// Map of to sale_document_lines. +public sealed class SaleDocumentLineMap() : DocumentLineMap("sale_document_lines"); + +/// Map of to purchase_orders. +public sealed class PurchaseOrderMap() : DocumentHeaderMap("purchase_orders"); + +/// Map of to purchase_order_lines. +public sealed class PurchaseOrderLineMap() : DocumentLineMap("purchase_order_lines"); + +/// Map of to purchase_documents. +public sealed class PurchaseDocumentMap() : DocumentHeaderMap("purchase_documents"); + +/// Map of to purchase_document_lines. +public sealed class PurchaseDocumentLineMap() : DocumentLineMap("purchase_document_lines"); + +/// Map of to inventory_documents. +public sealed class InventoryDocumentMap() : DocumentHeaderMap("inventory_documents"); + +/// Map of to inventory_document_lines. +public sealed class InventoryDocumentLineMap() : DocumentLineMap("inventory_document_lines"); + +/// Map of to document_links. +public sealed class DocumentLinkMap : EntityMap +{ + /// Creates the map. + public DocumentLinkMap() => ToTable("document_links"); +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs new file mode 100644 index 0000000..9960faa --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_003_CreateDocuments.cs @@ -0,0 +1,179 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +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. +/// +[Migration(20261112_003, "create_documents")] +public sealed class M20261112_003_CreateDocuments : IMigration +{ + // The kinds of the document types seeded by M20261111_014 (ItalianBaseTables): the code decides the behaviour. + private static readonly (string Code, string Kind)[] SeededKinds = + [ + ("PRE", "Quotation"), ("OC", "SalesOrder"), ("DDT", "DeliveryNote"), ("FI", "ImmediateInvoice"), ("FA", "AccompanyingInvoice"), + ("FD", "DeferredInvoice"), ("FACC", "DownPaymentInvoice"), ("NC", "CreditNote"), ("ND", "DebitNote"), ("PAR", "Fee"), ("PF", "ProForma"), + ("AF16", "SelfInvoice"), ("AF17", "SelfInvoice"), ("AF18", "SelfInvoice"), ("AF19", "SelfInvoice"), ("OF", "PurchaseOrder"), + ("DDTF", "PurchaseDeliveryNote"), ("FF", "PurchaseInvoice"), ("NCF", "PurchaseCreditNote"), ("MM", "InventoryEntry"), + ]; + + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.AlterTable("document_types", t => t.String("document_kind", 40)); + foreach (var (code, kind) in SeededKinds) + { + schema.Sql(_ => "UPDATE document_types SET document_kind = '" + kind + "' WHERE code = '" + code + "'"); + } + + schema.AlterTable("document_numerators", t => t.Date("last_date")); + + Family(schema, "sale_quotations", "sale_quotation_lines"); + Family(schema, "sale_orders", "sale_order_lines"); + Family(schema, "sale_documents", "sale_document_lines"); + Family(schema, "purchase_orders", "purchase_order_lines"); + Family(schema, "purchase_documents", "purchase_document_lines"); + Family(schema, "inventory_documents", "inventory_document_lines"); + + schema.CreateTable("document_links", t => + { + t.Id(); + t.String("target_family", 40).NotNull(); + t.Int64("target_document_id").NotNull(); + t.Int64("target_line_id").NotNull(); + t.String("source_family", 40).NotNull(); + t.Int64("source_document_id").NotNull(); + t.Int64("source_line_id").NotNull(); + t.Decimal("quantity").NotNull(); + t.AuditColumns(); + t.Index("ix_document_links_source", "source_family", "source_line_id"); + t.Index("ix_document_links_source_document", "source_family", "source_document_id"); + t.Index("ix_document_links_target", "target_family", "target_document_id"); + }); + } + + private static void Family(ISchemaBuilder schema, string headers, string lines) + { + schema.CreateTable(headers, t => + { + t.Id(); + t.Int64("document_type_id").NotNull(); + t.String("kind", 40).NotNull(); + t.String("status", 40).NotNull(); + t.Int64("numerator_id"); + t.String("section", 10); + t.Int64("number"); + t.String("document_number", 30); + t.Date("document_date").NotNull(); + t.Int32("year").NotNull(); + t.Int64("party_id"); + t.Int64("destination_id"); + t.String("external_reference", 40); + t.Date("external_date"); + t.String("currency_code", 3).NotNull(); + t.Decimal("exchange_rate").NotNull().Default(1m); + t.Int64("price_list_id"); + t.Int64("payment_term_id"); + t.Int64("payment_method_id"); + t.Int64("bank_account_id"); + t.Int64("salesperson_id"); + t.Int64("warehouse_id"); + t.Int64("inventory_reason_id"); + t.Int64("transport_reason_id"); + t.Int64("shipping_term_id"); + t.Int64("carrier_id"); + t.Int64("goods_appearance_id"); + t.Int32("packages"); + t.Decimal("gross_weight"); + t.Decimal("net_weight"); + t.DateTimeUtc("transport_start"); + t.Date("valid_until"); + t.Date("delivery_date"); + t.Int32("revision").NotNull().Default(0); + t.Bool("printed").NotNull().Default(false); + t.Bool("sent").NotNull().Default(false); + t.Bool("posted").NotNull().Default(false); + t.Bool("installments_generated").NotNull().Default(false); + t.Bool("xml_generated").NotNull().Default(false); + t.Decimal("taxable_amount").NotNull().Default(0m); + t.Decimal("tax_amount").NotNull().Default(0m); + t.Decimal("total_amount").NotNull().Default(0m); + t.String("footer_discount", 30); + t.Decimal("expenses_amount").NotNull().Default(0m); + t.Decimal("stamp_duty").NotNull().Default(0m); + t.Decimal("withholding_amount").NotNull().Default(0m); + t.Decimal("social_security_amount").NotNull().Default(0m); + t.Decimal("net_amount").NotNull().Default(0m); + t.Text("notes"); + t.Int64("gl_entry_id"); + t.Int64("vat_protocol"); + t.DateTimeUtc("confirmed_at"); + t.String("confirmed_by", 100); + t.DateTimeUtc("cancelled_at"); + t.String("cancel_reason", 200); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_" + headers + "_number", "numerator_id", "number"); + t.Index("ix_" + headers + "_date", "document_date"); + t.Index("ix_" + headers + "_party", "party_id"); + t.Index("ix_" + headers + "_status", "status"); + t.ForeignKey("fk_" + headers + "_type", "document_type_id", "document_types", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_numerator", "numerator_id", "document_numerators", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_party", "party_id", "parties", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_destination", "destination_id", "party_addresses", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_bank_account", "bank_account_id", "bank_accounts", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_inventory_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict); + t.ForeignKey("fk_" + headers + "_transport_reason", "transport_reason_id", "transport_reasons", ReferentialAction.Restrict); + 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); + }); + + schema.CreateTable(lines, t => + { + t.Id(); + t.Int64("document_id").NotNull(); + t.Int32("line_number").NotNull(); + t.String("kind", 40).NotNull(); + t.Int64("item_id"); + t.String("description", 1000).NotNull(); + t.Int64("unit_of_measure_id"); + t.Decimal("quantity").NotNull().Default(0m); + t.Decimal("price").NotNull().Default(0m); + t.String("price_source", 40).NotNull(); + t.String("discount_formula", 30); + t.Int64("tax_code_id"); + t.Decimal("taxable_amount").NotNull().Default(0m); + t.Int64("warehouse_id"); + t.Date("delivery_date"); + t.Decimal("fulfilled_quantity").NotNull().Default(0m); + t.Bool("fulfillment_closed").NotNull().Default(false); + t.String("source_family", 40); + t.Int64("source_line_id"); + t.String("account_code", 20); + t.Int64("cost_center_id"); + t.Int64("job_id"); + t.Text("notes"); + t.Int32("sort_order").NotNull().Default(0); + t.AuditColumns(); + t.Index("ix_" + lines + "_document", "document_id"); + t.Index("ix_" + lines + "_item", "item_id"); + t.Index("ix_" + lines + "_source", "source_family", "source_line_id"); + t.ForeignKey("fk_" + lines + "_document", "document_id", headers, ReferentialAction.Cascade); + t.ForeignKey("fk_" + lines + "_item", "item_id", "items", ReferentialAction.Restrict); + t.ForeignKey("fk_" + lines + "_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict); + t.ForeignKey("fk_" + lines + "_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict); + t.ForeignKey("fk_" + lines + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + t.ForeignKey("fk_" + lines + "_cost_center", "cost_center_id", "cost_centers", ReferentialAction.Restrict); + t.ForeignKey("fk_" + lines + "_job", "job_id", "jobs", ReferentialAction.Restrict); + }); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs index 2f5cbc2..727d475 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Features.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -221,8 +221,10 @@ public sealed record PaymentTermTemplate(string Code, string Description, string /// The numerator of the base data (FAT, DDT...), if the document is numbered by the company. /// The warehouse reason of the base data (SCA, CAR...), if the document moves goods. /// The type of the e-invoice format, if the document is sent electronically. +/// What the documents are, which decides how they behave (ADR 0032). public sealed record DocumentTypeTemplate( - string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType); + string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType, + Khaemhat.Core.Documents.DocumentKind DocumentKind); /// /// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes diff --git a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs index 1b7b629..e015538 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs @@ -1,3 +1,4 @@ +using Khaemhat.Core.Documents; using Khaemhat.Core.Tables; using Khaemhat.Fiscal.Abstractions; @@ -46,25 +47,25 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate /// public IReadOnlyList DocumentTypes { get; } = [ - new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null), - new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null), - new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null), - new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01"), - new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01"), - new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24"), - new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02"), - new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04"), - new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05"), - new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06"), - new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null), - new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16"), - new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17"), - new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18"), - new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19"), - new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null), - new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null), - new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null), - new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null), - new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null), + new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null, DocumentKind.Quotation), + new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null, DocumentKind.SalesOrder), + new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null, DocumentKind.DeliveryNote), + new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01", DocumentKind.ImmediateInvoice), + new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.AccompanyingInvoice), + new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24", DocumentKind.DeferredInvoice), + new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02", DocumentKind.DownPaymentInvoice), + new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04", DocumentKind.CreditNote), + new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05", DocumentKind.DebitNote), + new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06", DocumentKind.Fee), + new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null, DocumentKind.ProForma), + new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16", DocumentKind.SelfInvoice), + new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17", DocumentKind.SelfInvoice), + new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18", DocumentKind.SelfInvoice), + new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19", DocumentKind.SelfInvoice), + new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null, DocumentKind.PurchaseOrder), + new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null, DocumentKind.PurchaseDeliveryNote), + new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseInvoice), + new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseCreditNote), + new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null, DocumentKind.InventoryEntry), ]; } diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 3a0fe9d..69d0bc0 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -148,6 +148,11 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); + // The document engine (ADR 0032): one engine, the copies, a typed service per family. + 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. services.AddSingleton(sp => ActivatorUtilities.CreateInstance( sp, Khaemhat.Core.Parties.PartyKind.Customer)); diff --git a/src/Khaemhat.Web/Resources/it-IT/Documents.json b/src/Khaemhat.Web/Resources/it-IT/Documents.json new file mode 100644 index 0000000..bea31ea --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Documents.json @@ -0,0 +1,48 @@ +{ + "document": { + "not-found": "Il documento non esiste più.", + "action": { + "not-allowed": "Nello stato attuale del documento questa operazione non è ammessa." + }, + "type": { + "missing": "Il tipo documento non esiste.", + "no-kind": "Il tipo documento non ha un genere: sceglilo in Tabelle azienda, Tipi documento.", + "disabled": "Il tipo documento è disattivato.", + "family": "Questo tipo documento appartiene a un'altra famiglia di documenti.", + "locked": "Il tipo di un documento già salvato non si può cambiare." + }, + "party": { + "required": "Indica il cliente o il fornitore." + }, + "date": { + "required": "Indica la data del documento.", + "numbered": "La data di un documento numerato non si può cambiare." + }, + "lines": { + "required": "Il documento non ha righe." + }, + "line": { + "kind-not-allowed": "Questo tipo di riga non è ammesso in questo documento.", + "description-required": "Ogni riga ha bisogno di una descrizione.", + "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." + }, + "cancel": { + "reason-required": "Per annullare una fattura indica il motivo.", + "has-followers": "Altri documenti evadono questo: annulla prima quelli." + }, + "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." + }, + "number": { + "date-before-last": "La data è anteriore a quella dell'ultimo documento numerato: con questo numeratore non sono ammessi documenti fuori sequenza.", + "numerator-missing": "Il numeratore del tipo documento non esiste.", + "numerator-disabled": "Il numeratore del tipo documento è disattivato.", + "too-long": "Il numero formattato supera i 30 caratteri: accorcia il formato del numeratore." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Tables.json b/src/Khaemhat.Web/Resources/it-IT/Tables.json index ae12783..127f764 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Tables.json +++ b/src/Khaemhat.Web/Resources/it-IT/Tables.json @@ -255,6 +255,7 @@ "IsDefault": "Predefinito", "Symbol": "Simbolo", "Decimals": "Decimali", + "DocumentKind": "Genere", "NumeratorId": "Numeratore", "InventoryReasonId": "Causale di magazzino", "EInvoiceType": "Tipo TD", @@ -266,6 +267,7 @@ "Prefix": "Prefisso", "Format": "Formato", "LastNumber": "Ultimo numero", + "LastDate": "Data dell'ultimo numero", "GapsAllowed": "Ammessi buchi di numerazione", "CurrencyCode": "Valuta", "VatIncluded": "IVA inclusa", @@ -353,6 +355,25 @@ "Journal": "Prima nota", "Other": "Altro" }, + "DocumentKind": { + "Quotation": "Preventivo", + "SalesOrder": "Ordine cliente", + "DeliveryNote": "DDT di vendita", + "ImmediateInvoice": "Fattura immediata", + "AccompanyingInvoice": "Fattura accompagnatoria", + "DeferredInvoice": "Fattura differita", + "DownPaymentInvoice": "Fattura di acconto", + "CreditNote": "Nota di credito", + "DebitNote": "Nota di debito", + "Fee": "Parcella", + "ProForma": "Pro forma", + "SelfInvoice": "Autofattura o integrazione", + "PurchaseOrder": "Ordine fornitore", + "PurchaseDeliveryNote": "DDT fornitore", + "PurchaseInvoice": "Fattura fornitore", + "PurchaseCreditNote": "Nota di credito fornitore", + "InventoryEntry": "Movimento di magazzino" + }, "StockEffect": { "None": "Nessuno", "Load": "Carico", @@ -446,6 +467,9 @@ "numerator": { "format": "Il formato deve contenere il segnaposto del numero e solo segnaposto noti (anno, prefisso, sezionale)." }, + "document-type": { + "kind-required": "Scegli il genere: dice come si comportano i documenti di questo tipo." + }, "year": { "range": "Anno fuori intervallo." }, diff --git a/src/Khaemhat.Web/Tables/TableScreens.cs b/src/Khaemhat.Web/Tables/TableScreens.cs index 48dcb0c..8db0429 100644 --- a/src/Khaemhat.Web/Tables/TableScreens.cs +++ b/src/Khaemhat.Web/Tables/TableScreens.cs @@ -194,6 +194,7 @@ public static class TableScreens Fields = [ new(nameof(DocumentType.Kind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "170px" }, + new(nameof(DocumentType.DocumentKind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "190px" }, new(nameof(DocumentType.NumeratorId), TableFieldKind.Lookup) { Lookup = typeof(DocumentNumerator), InGrid = true, Width = "120px" }, new(nameof(DocumentType.InventoryReasonId), TableFieldKind.Lookup) { Lookup = typeof(InventoryReason) }, new(nameof(DocumentType.EInvoiceType), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.DocumentTypes), InGrid = true, Width = "90px" }, @@ -212,7 +213,8 @@ public static class TableScreens new(nameof(DocumentNumerator.Prefix), TableFieldKind.Code) { MaxLength = 10, Span = 4 }, new(nameof(DocumentNumerator.Format)) { Required = true, Span = 8, InGrid = true, Width = "180px" }, new(nameof(DocumentNumerator.LastNumber), TableFieldKind.Number) { Min = 0, InGrid = true, Width = "100px", Span = 4 }, - new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 8 }, + new(nameof(DocumentNumerator.LastDate), TableFieldKind.Date) { Span = 4 }, + new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 4 }, ], }, new("listini", "price-lists", typeof(PriceList), "tag", TableGroup.Sales) diff --git a/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs new file mode 100644 index 0000000..9d14106 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs @@ -0,0 +1,121 @@ +using Khaemhat.Core.Documents; + +namespace Khaemhat.Core.Tests.Documents; + +/// The declarative rules of the document engine (issue #47): behaviours, states, fulfilment. +[TestClass] +public sealed class DocumentRulesTests +{ + [TestMethod] + public void EveryKind_HasABehaviour_AndFulfilsOnlyKindsOfTheSameDirection() + { + Assert.HasCount(Enum.GetValues().Length, DocumentBehaviors.All); + foreach (var behavior in DocumentBehaviors.All) + { + Assert.IsNotEmpty(behavior.Lines, behavior.Kind.ToString()); + foreach (var source in behavior.Sources) + { + Assert.AreEqual(behavior.Direction, DocumentBehaviors.Of(source).Direction, $"{behavior.Kind} fulfils {source}"); + } + + // Invoices are the only documents that reach the exchange system. + Assert.AreEqual(behavior.Lifecycle == DocumentLifecycle.Invoice, behavior.Has(DocumentEffects.EInvoice), behavior.Kind.ToString()); + } + + Assert.AreEqual(DocumentFamily.SaleDocument, DocumentBehaviors.Of(DocumentKind.DeliveryNote).Family); + Assert.IsTrue(DocumentBehaviors.Of(DocumentKind.DeferredInvoice).Fulfils(DocumentKind.DeliveryNote)); + Assert.IsFalse(DocumentBehaviors.Of(DocumentKind.DeferredInvoice).Fulfils(DocumentKind.SalesOrder)); + Assert.IsTrue(DocumentBehaviors.Of(DocumentKind.Quotation).NeedsParty); + Assert.IsFalse(DocumentBehaviors.Of(DocumentKind.InventoryEntry).NeedsParty); + CollectionAssert.AreEquivalent( + new[] { DocumentKind.DeliveryNote, DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, + DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.Fee, DocumentKind.ProForma, DocumentKind.SelfInvoice }, + DocumentBehaviors.KindsOf(DocumentFamily.SaleDocument).ToArray()); + } + + [TestMethod] + public void OrderLifecycle_MovesThroughItsStates_AndRefusesTheRest() + { + const DocumentLifecycle Order = DocumentLifecycle.Order; + Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Confirm)); + Assert.AreEqual(DocumentStatus.Closed, DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Close)); + Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.Apply(Order, DocumentStatus.Closed, DocumentAction.Reopen)); + Assert.AreEqual(DocumentStatus.Cancelled, DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Cancel)); + Assert.IsTrue(DocumentStateMachine.IsEditable(Order, DocumentStatus.PartiallyFulfilled)); + Assert.IsFalse(DocumentStateMachine.IsEditable(Order, DocumentStatus.Fulfilled)); + + var refused = Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Cancel)); + Assert.AreEqual(DocumentAction.Cancel, refused.Action); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Delete)); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Issue)); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.Cancelled, DocumentAction.Reopen)); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(Order, DocumentStatus.Issued, DocumentAction.Copy), "Not a state of the cycle."); + } + + [TestMethod] + public void InvoiceLifecycle_IsUnchangeableOnceIssued_AndCancelledOnlyBeforeTheExchangeSystemHasIt() + { + const DocumentLifecycle Invoice = DocumentLifecycle.Invoice; + var status = DocumentStatus.Draft; + foreach (var action in new[] { DocumentAction.Issue, DocumentAction.GenerateXml, DocumentAction.Send, DocumentAction.MarkDelivered }) + { + status = DocumentStateMachine.Apply(Invoice, status, action); + } + + Assert.AreEqual(DocumentStatus.SdiDelivered, status); + CollectionAssert.AreEqual(new[] { DocumentAction.Copy }, DocumentStateMachine.Actions(Invoice, DocumentStatus.SdiDelivered).ToArray()); + foreach (var issued in DocumentStateMachine.States(Invoice).Where(s => s != DocumentStatus.Draft)) + { + Assert.IsFalse(DocumentStateMachine.IsEditable(Invoice, issued), issued.ToString()); + Assert.IsFalse(DocumentStateMachine.Allows(Invoice, issued, DocumentAction.Delete), issued.ToString()); + } + + Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiGenerated, DocumentAction.Cancel)); + Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiRejected, DocumentAction.Cancel)); + Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiSent, DocumentAction.Cancel)); + Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.Draft, DocumentAction.Confirm), "Invoices are issued, not confirmed."); + Assert.AreEqual(DocumentStatus.SdiGenerated, DocumentStateMachine.Apply(Invoice, DocumentStatus.SdiRejected, DocumentAction.GenerateXml)); + } + + [TestMethod] + public void SimpleLifecycle_HasDraftConfirmedCancelled() + { + CollectionAssert.AreEqual( + new[] { DocumentStatus.Draft, DocumentStatus.Confirmed, DocumentStatus.Cancelled }, DocumentStateMachine.States(DocumentLifecycle.Simple).ToArray()); + Assert.ThrowsExactly(() => DocumentStateMachine.Apply(DocumentLifecycle.Simple, DocumentStatus.Confirmed, DocumentAction.Close)); + } + + [TestMethod] + public void Fulfilment_SumsTheLinks_AndClosedLinesCountAsFulfilled() + { + var lines = new List + { + new SaleOrderLine { Id = 1, Kind = DocumentLineKind.Item, Quantity = 10m }, + new SaleOrderLine { Id = 2, Kind = DocumentLineKind.Free, Quantity = 4m }, + new SaleOrderLine { Id = 3, Kind = DocumentLineKind.Description }, + new SaleOrderLine { Id = 4, Kind = DocumentLineKind.Expense, Quantity = 1m }, + }; + Assert.AreEqual(FulfillmentState.None, FulfillmentCalculator.StateOf(lines)); + + var changed = FulfillmentCalculator.Apply(lines, [Link(1, 6m), Link(1, 1m)]); + Assert.HasCount(1, changed); + Assert.AreEqual(7m, lines[0].FulfilledQuantity); + Assert.AreEqual(3m, lines[0].Residual); + Assert.AreEqual(0m, lines[3].Residual, "Expenses are not fulfilled."); + Assert.AreEqual(FulfillmentState.Partial, FulfillmentCalculator.StateOf(lines)); + + FulfillmentCalculator.Apply(lines, [Link(1, 12m), Link(2, 1m)]); + Assert.AreEqual(0m, lines[0].Residual, "More than ordered leaves nothing to fulfil."); + Assert.AreEqual(FulfillmentState.Partial, FulfillmentCalculator.StateOf(lines)); + lines[1].FulfillmentClosed = true; + Assert.AreEqual(FulfillmentState.Fulfilled, FulfillmentCalculator.StateOf(lines)); + + Assert.AreEqual(DocumentStatus.Fulfilled, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.Confirmed, FulfillmentState.Fulfilled)); + Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.PartiallyFulfilled, FulfillmentState.None)); + Assert.AreEqual(DocumentStatus.Closed, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.Closed, FulfillmentState.Fulfilled)); + Assert.AreEqual(DocumentStatus.Issued, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Invoice, DocumentStatus.Issued, FulfillmentState.Fulfilled)); + } + + private static DocumentLink Link(long sourceLine, decimal quantity) => + new() { SourceFamily = DocumentFamily.SaleOrder, SourceLineId = sourceLine, Quantity = quantity }; +} diff --git a/tests/Khaemhat.Data.Tests/DocumentNumberingTests.cs b/tests/Khaemhat.Data.Tests/DocumentNumberingTests.cs new file mode 100644 index 0000000..f0efbde --- /dev/null +++ b/tests/Khaemhat.Data.Tests/DocumentNumberingTests.cs @@ -0,0 +1,92 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Querying; +using Khaemhat.Data.Tests.Support; + +namespace Khaemhat.Data.Tests; + +/// Document numbering on both engines (issue #47): concurrent confirmations never share a number. +[TestClass] +public sealed class DocumentNumberingTests +{ + private static readonly DateOnly Day = new(2026, 11, 12); + + [TestMethod] + [DataRow(TestDatabase.Sqlite)] + [DataRow(TestDatabase.Postgres)] + public async Task ConcurrentConfirmations_GetEveryNumberOnce_AndRollbacksGiveTheNumberBack(string engine) + { + await using var db = await TestDatabase.CreateAsync(engine); + var id = await NumeratorAsync(db); + const int Workers = 24; + + var results = await Task.WhenAll(Enumerable.Range(0, Workers).Select(i => Task.Run(async () => + { + await using var uow = await db.OpenAsync(); + await uow.BeginAsync(); + var number = await DocumentNumberingService.NextAsync(uow, id, Day); + await Task.Yield(); + if (i % 4 == 0) + { + await uow.RollbackAsync(); + return (long?)null; + } + + await uow.CommitAsync(); + return number.Number; + }))); + + var given = results.OfType().Order().ToArray(); + CollectionAssert.AreEqual(Enumerable.Range(1, given.Length).Select(n => (long)n).ToArray(), given, "Each number once, none skipped."); + await using var check = await db.OpenAsync(); + var numerator = await check.Repository().GetAsync(id); + Assert.AreEqual((long)given.Length, numerator!.LastNumber); + Assert.AreEqual(Day, numerator.LastDate); + } + + [TestMethod] + [DataRow(TestDatabase.Sqlite)] + [DataRow(TestDatabase.Postgres)] + public async Task Numbering_RefusesDatesBeforeTheLast_AndStartsANewYearFromOne(string engine) + { + await using var db = await TestDatabase.CreateAsync(engine); + var id = await NumeratorAsync(db); + await using var uow = await db.OpenAsync(); + + await uow.BeginAsync(); + var first = await DocumentNumberingService.NextAsync(uow, id, Day); + Assert.AreEqual("FV-2026/0001", first.Text); + var refused = await Assert.ThrowsExactlyAsync(() => DocumentNumberingService.NextAsync(uow, id, Day.AddDays(-1))); + Assert.AreEqual(DocumentNumberingService.DateBeforeLast, refused.Errors.Single()); + Assert.AreEqual("FV-2027/0001", await DocumentNumberingService.PreviewAsync(uow, id, new DateOnly(2027, 1, 2))); + + // The first document of a new year creates the numerator of that year with the same rules. + var next = await DocumentNumberingService.NextAsync(uow, id, new DateOnly(2027, 1, 2)); + Assert.AreEqual(1L, next.Number); + Assert.AreEqual("FV-2027/0001", next.Text); + Assert.AreNotEqual(id, next.Numerator.Id); + Assert.AreEqual(2, (await uow.Repository().ListAsync(Query.For().Where(n => n.Code == "FAT"))).Items.Count); + Assert.AreEqual(2L, (await DocumentNumberingService.NextAsync(uow, id, Day.AddDays(1))).Number, "2026 goes on by itself."); + await uow.CommitAsync(); + + // No document carries the number given in 2027: the check lists it as missing. + CollectionAssert.AreEqual(new long[] { 1 }, (await DocumentNumberingService.FindGapsAsync(uow, next.Numerator.Id)).ToArray()); + } + + private static async Task NumeratorAsync(TestDatabase db) + { + await new MigrationRunner(db.Context).RunAsync(db.Target, MigrationCatalog.ForCompany()); + await using var setup = await db.OpenAsync(); + return await setup.Repository().InsertAsync(new DocumentNumerator + { + Code = "FAT", + Description = "Fatture", + Kind = NumeratorKind.SalesInvoice, + Year = 2026, + Prefix = "FV", + Format = "{prefix}-{year}/{number:D4}", + }); + } +} diff --git a/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj b/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj index d595a2e..f65bb54 100644 --- a/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj +++ b/tests/Khaemhat.Data.Tests/Khaemhat.Data.Tests.csproj @@ -9,6 +9,8 @@ + + diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index c5b635d..4f13e6e 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -78,6 +78,9 @@ public sealed class MappingTests "discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences", "parties", "party_addresses", "party_contacts", "party_bank_accounts", "party_sales_terms", "party_purchase_terms", "party_fiscal", "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", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs new file mode 100644 index 0000000..ffc102a --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs @@ -0,0 +1,226 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Documents; + +/// The document engine on a real instance (issue #47): definitions, numbering, states, copies and fulfilment. +[TestClass] +public sealed class DocumentEngineTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task OrderToDeliveryNotesToDeferredInvoice_FollowsTheFulfilmentLineByLine() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var orders = app.Services.GetRequiredService>(); + var sales = app.Services.GetRequiredService>(); + var copies = app.Services.GetRequiredService(); + var customer = await CustomerAsync(app, company); + var year = DateTime.Now.Year; + + var order = await orders.NewAsync(Root, company, "OC"); + Assert.AreEqual(DocumentKind.SalesOrder, order.Header.Kind); + order.Header.PartyId = customer; + order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Valvola a sfera 1/2\"", Quantity = 10m, Price = 5m }); + order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Raccordo a T", Quantity = 4m, Price = 2m }); + order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Description, Description = "Consegna in cantiere" }); + order = await orders.SaveAsync(Root, company, order); + Assert.AreEqual(DocumentStatus.Draft, order.Header.Status); + Assert.IsNull(order.Header.Number, "Numbered at confirmation."); + CollectionAssert.AreEqual(new[] { 1, 2, 3 }, order.Lines.Select(l => l.LineNumber).ToArray()); + + order = await orders.ConfirmAsync(Root, company, order.Header.Id); + Assert.AreEqual(DocumentStatus.Confirmed, order.Header.Status); + Assert.AreEqual($"OC-{year}-0001", order.Header.DocumentNumber); + Assert.AreEqual(Root.UserName, order.Header.ConfirmedBy); + + // First delivery: part of the first line only. + var first = Typed(await copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT")); + Assert.AreEqual(DocumentKind.DeliveryNote, first.Header.Kind); + Assert.HasCount(3, first.Lines); + Assert.AreEqual(order.Lines[0].Id, first.Lines[0].SourceLineId); + Assert.IsNull(first.Lines[2].SourceLineId, "Descriptions are copied without a link."); + first.Lines[0].Quantity = 6m; + first.Lines.RemoveAt(1); + first = await sales.SaveAsync(Root, company, first); + Assert.AreEqual(DocumentStatus.Confirmed, (await orders.GetAsync(Root, company, order.Header.Id))!.Header.Status, "A draft fulfils nothing."); + + first = await sales.ConfirmAsync(Root, company, first.Header.Id); + Assert.AreEqual($"1/{year}", first.Header.DocumentNumber); + order = (await orders.GetAsync(Root, company, order.Header.Id))!; + Assert.AreEqual(DocumentStatus.PartiallyFulfilled, order.Header.Status); + Assert.AreEqual(6m, order.Lines[0].FulfilledQuantity); + Assert.AreEqual(4m, order.Lines[0].Residual); + + // The order can still change, but not below what was delivered. + order.Lines[0].Quantity = 5m; + var below = await Assert.ThrowsExactlyAsync(() => orders.SaveAsync(Root, company, order)); + Assert.AreEqual("Lines.0.Quantity:" + DocumentErrors.LineBelowFulfilled, below.Errors.Single()); + await Assert.ThrowsExactlyAsync(() => orders.CancelAsync(Root, company, order.Header.Id, null)); + + // Second delivery: the rest. + var second = await copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT"); + CollectionAssert.AreEqual(new[] { 4m, 4m, 0m }, second.Lines.Select(l => l.Quantity).ToArray()); + await sales.ConfirmAsync(Root, company, second.Header.Id); + Assert.AreEqual(DocumentStatus.Fulfilled, (await orders.GetAsync(Root, company, order.Header.Id))!.Header.Status); + await Assert.ThrowsExactlyAsync(() => copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT")); + + // Cancelling a delivery gives its quantities back. + var cancelled = await sales.CancelAsync(Root, company, second.Header.Id, null); + Assert.AreEqual(DocumentStatus.Cancelled, cancelled.Header.Status); + Assert.AreEqual($"2/{year}", cancelled.Header.DocumentNumber, "The number stays."); + order = (await orders.GetAsync(Root, company, order.Header.Id))!; + Assert.AreEqual(DocumentStatus.PartiallyFulfilled, order.Header.Status); + Assert.AreEqual(0m, order.Lines[1].FulfilledQuantity); + + // Closing the rest, then reopening, comes back to what the lines say. + Assert.AreEqual(DocumentStatus.Closed, (await orders.CloseAsync(Root, company, order.Header.Id)).Header.Status); + await Assert.ThrowsExactlyAsync(() => copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT")); + Assert.AreEqual(DocumentStatus.PartiallyFulfilled, (await orders.ReopenAsync(Root, company, order.Header.Id)).Header.Status); + + // The deferred invoice fulfils the delivery note; once issued it is unchangeable. + var invoice = Typed(await copies.CopyAsync(Root, company, DocumentFamily.SaleDocument, first.Header.Id, "FD")); + invoice = await sales.ConfirmAsync(Root, company, invoice.Header.Id); + Assert.AreEqual(DocumentStatus.Issued, invoice.Header.Status); + Assert.AreEqual($"1/{year}", invoice.Header.DocumentNumber, "Invoices have their own numerator."); + Assert.AreEqual(DocumentStatus.Fulfilled, (await sales.GetAsync(Root, company, first.Header.Id))!.Header.Status); + invoice.Header.Notes = "Changed"; + await Assert.ThrowsExactlyAsync(() => sales.SaveAsync(Root, company, invoice)); + await Assert.ThrowsExactlyAsync(() => sales.DeleteAsync(Root, company, invoice.Header.Id)); + await Assert.ThrowsExactlyAsync(() => sales.CancelAsync(Root, company, first.Header.Id, null), "Fulfilled by the invoice."); + + var reason = await Assert.ThrowsExactlyAsync(() => sales.CancelAsync(Root, company, invoice.Header.Id, " ")); + Assert.AreEqual("CancelReason:" + DocumentErrors.CancelReasonRequired, reason.Errors.Single()); + invoice = await sales.CancelAsync(Root, company, invoice.Header.Id, "Emessa per errore"); + Assert.AreEqual("Emessa per errore", invoice.Header.CancelReason); + Assert.AreEqual(DocumentStatus.Confirmed, (await sales.GetAsync(Root, company, first.Header.Id))!.Header.Status); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Invoices_AreCheckedAndNumberedWithoutGapsInDateOrder_AndDraftsAreDeleted() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var sales = app.Services.GetRequiredService>(); + var customer = await CustomerAsync(app, company); + var year = DateTime.Now.Year; + + var definitions = await engine.DefinitionsAsync(Root, company); + Assert.HasCount(20, definitions, "Every seeded type has its kind."); + Assert.AreEqual(DocumentKind.DeferredInvoice, definitions.Single(d => d.Code == "FD").Kind); + Assert.AreEqual(DocumentAction.Issue, definitions.Single(d => d.Code == "FI").ConfirmAction); + await Assert.ThrowsExactlyAsync(() => sales.NewAsync(Root, company, "OC"), "An order is not a sale document."); + + var draft = await sales.NewAsync(Root, company, "FI"); + draft.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, Description = "Senza articolo", Quantity = 1m }); + draft.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = " ", Quantity = 1m }); + var refused = await Assert.ThrowsExactlyAsync(() => sales.SaveAsync(Root, company, draft)); + CollectionAssert.AreEquivalent( + new[] { "PartyId:" + DocumentErrors.PartyRequired, "Lines.0.ItemId:" + DocumentErrors.LineItemRequired, "Lines.1.Description:" + DocumentErrors.LineDescriptionRequired }, + refused.Errors.ToArray()); + + var delivery = await sales.NewAsync(Root, company, "DDT"); + delivery.Header.PartyId = customer; + delivery.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Expense, Description = "Trasporto", Quantity = 1m }); + var expense = await Assert.ThrowsExactlyAsync(() => sales.SaveAsync(Root, company, delivery)); + Assert.AreEqual("Lines.0.Kind:" + DocumentErrors.LineKindNotAllowed, expense.Errors.Single()); + + var later = await InvoiceAsync(sales, company, customer, new DateOnly(year, 3, 10)); + var earlier = await InvoiceAsync(sales, company, customer, new DateOnly(year, 3, 9)); + var empty = await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, new DateOnly(year, 3, 11), lines: false)); + var noLines = await Assert.ThrowsExactlyAsync(() => sales.ConfirmAsync(Root, company, empty.Header.Id)); + Assert.AreEqual("Lines:" + DocumentErrors.LinesRequired, noLines.Errors.Single()); + + Assert.AreEqual($"1/{year}", (await sales.ConfirmAsync(Root, company, later.Header.Id)).Header.DocumentNumber); + var outOfOrder = await Assert.ThrowsExactlyAsync(() => sales.ConfirmAsync(Root, company, earlier.Header.Id)); + Assert.AreEqual(DocumentNumberingService.DateBeforeLast, outOfOrder.Errors.Single()); + Assert.AreEqual(DocumentStatus.Draft, (await sales.GetAsync(Root, company, earlier.Header.Id))!.Header.Status, "Nothing changed."); + + earlier.Header.DocumentDate = new DateOnly(year, 3, 12); + earlier = await sales.SaveAsync(Root, company, earlier); + var issued = await sales.ConfirmAsync(Root, company, earlier.Header.Id); + Assert.AreEqual(2L, issued.Header.Number); + + var factory = app.Services.GetRequiredService(); + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company))) + { + Assert.IsEmpty(await DocumentNumberingService.FindGapsAsync(uow, issued.Header.NumeratorId!.Value)); + } + + var actions = await engine.ActionsAsync(Root, new DocumentRecord { Family = DocumentFamily.SaleDocument, Header = issued.Header }); + CollectionAssert.AreEquivalent(new[] { DocumentAction.Copy, DocumentAction.GenerateXml, DocumentAction.Cancel }, actions.ToArray()); + + await sales.DeleteAsync(Root, company, empty.Header.Id); + Assert.IsNull(await sales.GetAsync(Root, company, empty.Header.Id)); + + // A type of the company needs a kind to be used. + var tables = app.Services.GetRequiredService(); + var noKind = await Assert.ThrowsExactlyAsync(() => + tables.SaveAsync(Root, company, new DocumentType { Code = "FX", Description = "Fattura speciale", Kind = NumeratorKind.SalesInvoice })); + Assert.IsTrue(noKind.Errors.Any(e => e.EndsWith(TableCatalog.DocumentKindRequired, StringComparison.Ordinal)), string.Join(", ", noKind.Errors)); + await app.StopAsync(); + } + } + + [TestMethod] + public void EveryErrorCodeAndKind_HasAnItalianText() + { + var keys = new[] { typeof(DocumentErrors), typeof(DocumentNumberingService), typeof(DocumentDefinitionService) } + .SelectMany(t => t.GetFields()) + .Where(f => f.IsLiteral && f.FieldType == typeof(string)) + .Select(f => (string)f.GetRawConstantValue()!) + .Append(InvalidDocumentActionException.Code) + .Append(TableCatalog.DocumentKindRequired) + .Concat(Enum.GetValues().Select(k => Khaemhat.Web.Tables.TableScreens.EnumKey(k))) + .ToList(); + var missing = keys.Where(k => !Shell.ShellTests.Texts.Contains(k)).ToList(); + Assert.IsEmpty(missing, string.Join(", ", missing)); + } + + private static async Task> NewInvoiceAsync( + DocumentService sales, string company, long customer, DateOnly date, bool lines = true) + { + var invoice = await sales.NewAsync(Root, company, "FI"); + invoice.Header.PartyId = customer; + invoice.Header.DocumentDate = date; + if (lines) + { + invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Assistenza tecnica", Quantity = 2m, Price = 40m }); + } + + return invoice; + } + + private static async Task> InvoiceAsync( + DocumentService sales, string company, long customer, DateOnly date) => + await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, date)); + + private static DocumentRecord Typed(DocumentRecord record) => + new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast()] }; + + private static async Task CustomerAsync(WebApplication app, string company) + { + var parties = app.Services.GetRequiredService(); + var record = await parties.NewAsync(Root, company, PartyKind.Customer); + record.Party.Name = "Rossi Impianti S.r.l."; + record.Party.VatNumber = "01234567897"; + return (await parties.SaveAsync(Root, company, record)).Party.Id; + } +}