feat: document engine with kinds, states, atomic numbering and fulfilment (#47)
One engine for sales, purchases and warehouse documents (ADR 0032). Each document type now carries a kind that decides its family of tables, life cycle, effects, accepted lines, the kinds it fulfils and its permissions, so company-defined types work without code. - Six families of header and line tables plus document_links; document_types gets document_kind (seeded types filled by the migration and the Italian template), document_numerators gets last_date. - DocumentStateMachine with the order, invoice and simple life cycles and the actions each state admits; issued invoices are immutable and are cancelled with a reason only before the file reaches the exchange system. - DocumentNumberingService numbers at confirmation inside the transaction under the numerator lock (advisory lock on PostgreSQL, write lock on SQLite): no duplicates, a rollback gives the number back, out-of-sequence dates refused on gap-free numerators, the new year's numerator created on first use, gap report. - DocumentEngine, the generic DocumentService<THeader, TLine> and DocumentCopyService: save, confirm or issue, cancel, close, reopen, delete, duplicate and transform; links are recorded at confirmation and removed at cancellation, and FulfillmentCalculator recomputes quantities and states. - Tests: rules in Core, concurrent numbering on SQLite and PostgreSQL (data tests, run on PostgreSQL 18 locally), order to delivery notes to deferred invoice on a real instance. Wiki (Vendite, Tabelle azienda), CHANGELOG, STATUS, DATA-MODEL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fa9304834a
commit
ddd2273f7e
33 files changed
+4081
-37
No files matched your search
@@ -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<THeader, TLine>` 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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+7
-2
@@ -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,
|
||||
|
||||
@@ -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:<codice>:<anno>` (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<THeader, TLine>` (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).
|
||||
@@ -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
|
||||
|
||||
|
||||
+54
-11
@@ -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
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Data;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class DocumentCopyService
|
||||
{
|
||||
private readonly DocumentEngine _engine;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="engine">The engine.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public DocumentCopyService(DocumentEngine engine, PermissionService permissions, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(engine);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_engine = engine;
|
||||
_permissions = permissions;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>Copies a document into a new draft and saves it.</summary>
|
||||
/// <param name="actor">Who copies.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family of the source.</param>
|
||||
/// <param name="id">The source.</param>
|
||||
/// <param name="targetTypeCode">The type of the new document, such as <c>DDT</c>.</param>
|
||||
/// <param name="lineIds">The lines to copy; all when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new draft.</returns>
|
||||
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
|
||||
public async Task<DocumentRecord> CopyAsync(
|
||||
Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var source = await _engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="Type">The row of <c>document_types</c>.</param>
|
||||
/// <param name="Behavior">The behaviour of its kind.</param>
|
||||
public sealed record DocumentDefinition(DocumentType Type, DocumentBehavior Behavior)
|
||||
{
|
||||
/// <summary>The code of the type.</summary>
|
||||
public string Code => Type.Code;
|
||||
|
||||
/// <summary>The kind.</summary>
|
||||
public DocumentKind Kind => Behavior.Kind;
|
||||
|
||||
/// <summary>The family (tables).</summary>
|
||||
public DocumentFamily Family => Behavior.Family;
|
||||
|
||||
/// <summary>The life cycle.</summary>
|
||||
public DocumentLifecycle Lifecycle => Behavior.Lifecycle;
|
||||
|
||||
/// <summary>The action that confirms the documents: issue for invoices, confirm for the others.</summary>
|
||||
public DocumentAction ConfirmAction => Lifecycle == DocumentLifecycle.Invoice ? DocumentAction.Issue : DocumentAction.Confirm;
|
||||
}
|
||||
|
||||
/// <summary>Reads the definitions of the company's document types.</summary>
|
||||
public static class DocumentDefinitionService
|
||||
{
|
||||
/// <summary>Error: the document type does not exist.</summary>
|
||||
public const string TypeMissing = "document.type.missing";
|
||||
|
||||
/// <summary>Error: the document type has no kind.</summary>
|
||||
public const string TypeWithoutKind = "document.type.no-kind";
|
||||
|
||||
/// <summary>Error: the document type is disabled.</summary>
|
||||
public const string TypeDisabled = "document.type.disabled";
|
||||
|
||||
/// <summary>The definition of a document type.</summary>
|
||||
/// <param name="uow">A company unit of work.</param>
|
||||
/// <param name="typeId">The type.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The definition.</returns>
|
||||
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
|
||||
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, long typeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var type = await uow.Repository<DocumentType, long>().GetAsync(typeId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
|
||||
return Of(type);
|
||||
}
|
||||
|
||||
/// <summary>The definition of a document type by code.</summary>
|
||||
/// <param name="uow">A company unit of work.</param>
|
||||
/// <param name="code">The code, such as <c>FI</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The definition.</returns>
|
||||
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
|
||||
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var normalized = (code ?? string.Empty).Trim().ToUpperInvariant();
|
||||
var type = await uow.Repository<DocumentType, long>().FindAsync(Query.For<DocumentType>().Where(t => t.Code == normalized), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
|
||||
return Of(type);
|
||||
}
|
||||
|
||||
/// <summary>The definitions of every usable type (enabled, with a kind), by code.</summary>
|
||||
/// <param name="uow">A company unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The definitions.</returns>
|
||||
public static async Task<IReadOnlyList<DocumentDefinition>> ListAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var types = await uow.Repository<DocumentType, long>().ListAsync(Query.For<DocumentType>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false);
|
||||
return [.. types.Items.Where(t => !t.Disabled && t.DocumentKind is not null).Select(Of)];
|
||||
}
|
||||
|
||||
/// <summary>The definition of a type row.</summary>
|
||||
/// <param name="type">The row.</param>
|
||||
/// <returns>The definition.</returns>
|
||||
/// <exception cref="ValidationFailedException">The type has no kind.</exception>
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A document with its lines, whatever the family.</summary>
|
||||
public sealed class DocumentRecord
|
||||
{
|
||||
/// <summary>The family.</summary>
|
||||
public DocumentFamily Family { get; init; }
|
||||
|
||||
/// <summary>The header.</summary>
|
||||
public required DocumentHeader Header { get; init; }
|
||||
|
||||
/// <summary>The lines, in order.</summary>
|
||||
public List<DocumentLine> Lines { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>The error codes of the document engine; the interface translates them (<c>Documents.json</c>).</summary>
|
||||
public static class DocumentErrors
|
||||
{
|
||||
/// <summary>The document does not exist.</summary>
|
||||
public const string NotFound = "document.not-found";
|
||||
|
||||
/// <summary>A customer or supplier is needed.</summary>
|
||||
public const string PartyRequired = "document.party.required";
|
||||
|
||||
/// <summary>The date is missing.</summary>
|
||||
public const string DateRequired = "document.date.required";
|
||||
|
||||
/// <summary>The date of a numbered document cannot change.</summary>
|
||||
public const string DateNumbered = "document.date.numbered";
|
||||
|
||||
/// <summary>The type belongs to another family of documents.</summary>
|
||||
public const string TypeFamily = "document.type.family";
|
||||
|
||||
/// <summary>The type of a confirmed document cannot change.</summary>
|
||||
public const string TypeLocked = "document.type.locked";
|
||||
|
||||
/// <summary>The document has no lines.</summary>
|
||||
public const string LinesRequired = "document.lines.required";
|
||||
|
||||
/// <summary>The kind of line is not accepted by the document.</summary>
|
||||
public const string LineKindNotAllowed = "document.line.kind-not-allowed";
|
||||
|
||||
/// <summary>A line without description.</summary>
|
||||
public const string LineDescriptionRequired = "document.line.description-required";
|
||||
|
||||
/// <summary>An item line without item.</summary>
|
||||
public const string LineItemRequired = "document.line.item-required";
|
||||
|
||||
/// <summary>A quantity below what later documents already fulfilled.</summary>
|
||||
public const string LineBelowFulfilled = "document.line.below-fulfilled";
|
||||
|
||||
/// <summary>A line fulfilled by later documents cannot be removed.</summary>
|
||||
public const string LineFulfilledRemoved = "document.line.fulfilled-removed";
|
||||
|
||||
/// <summary>The line to fulfil does not exist or belongs to a kind the document does not fulfil.</summary>
|
||||
public const string LineSourceInvalid = "document.line.source-invalid";
|
||||
|
||||
/// <summary>A cancelled invoice needs a reason.</summary>
|
||||
public const string CancelReasonRequired = "document.cancel.reason-required";
|
||||
|
||||
/// <summary>Later documents fulfil this one: cancel them first.</summary>
|
||||
public const string CancelHasFollowers = "document.cancel.has-followers";
|
||||
|
||||
/// <summary>A copy changes direction (sale to purchase).</summary>
|
||||
public const string CopyDirection = "document.copy.direction";
|
||||
|
||||
/// <summary>Nothing is left to fulfil.</summary>
|
||||
public const string CopyNothingLeft = "document.copy.nothing-left";
|
||||
|
||||
/// <summary>A closed or cancelled document cannot be fulfilled.</summary>
|
||||
public const string CopySourceNotOpen = "document.copy.source-not-open";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="DocumentService{THeader, TLine}"/> and <see cref="DocumentCopyService"/>.
|
||||
/// </summary>
|
||||
public sealed class DocumentEngine
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly FiscalYearService _fiscal;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the engine.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
/// <param name="fiscal">The fiscal calendar (open periods).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
|
||||
/// <summary>The definitions of the usable document types.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The definitions the actor can see.</returns>
|
||||
public async Task<IReadOnlyList<DocumentDefinition>> 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<DocumentDefinition>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A new draft of a type, not saved: today's date and the defaults of the type.</summary>
|
||||
/// <param name="actor">Who creates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="typeCode">The document type, such as <c>FI</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The draft.</returns>
|
||||
public async Task<DocumentRecord> 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 };
|
||||
}
|
||||
|
||||
/// <summary>Reads a document.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document, if any.</returns>
|
||||
public async Task<DocumentRecord?> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document as saved.</returns>
|
||||
/// <exception cref="ValidationFailedException">The document breaks a rule.</exception>
|
||||
/// <exception cref="InvalidDocumentActionException">The state does not admit changes.</exception>
|
||||
public async Task<DocumentRecord> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirms a document, or issues an invoice: checks it, numbers it, records the fulfilment of the documents its
|
||||
/// lines come from.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who confirms.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document as confirmed.</returns>
|
||||
public async Task<DocumentRecord> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="actor">Who cancels.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="reason">Why.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document as cancelled.</returns>
|
||||
public Task<DocumentRecord> 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);
|
||||
|
||||
/// <summary>Closes what is left to fulfil of an order, quotation, delivery note or pro forma.</summary>
|
||||
/// <param name="actor">Who closes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document as closed.</returns>
|
||||
public Task<DocumentRecord> CloseAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
|
||||
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Close, null, null, cancellationToken);
|
||||
|
||||
/// <summary>Reopens a closed document: its state comes back from the fulfilment of its lines.</summary>
|
||||
/// <param name="actor">Who reopens.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document as reopened.</returns>
|
||||
public Task<DocumentRecord> 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);
|
||||
|
||||
/// <summary>
|
||||
/// Records a step of the electronic invoice (file generated, sent, delivered, rejected, not delivered); the module
|
||||
/// of the electronic invoice (M8) calls it.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who records it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="action">The step.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document.</returns>
|
||||
public Task<DocumentRecord> 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);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a draft.</summary>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The actions the state of a document admits for an actor.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="record">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The actions.</returns>
|
||||
public async Task<IReadOnlyList<DocumentAction>> ActionsAsync(Actor actor, DocumentRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var behavior = DocumentBehaviors.Of(record.Header.Kind);
|
||||
var result = new List<DocumentAction>();
|
||||
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<DocumentRecord?> 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) };
|
||||
}
|
||||
|
||||
/// <summary>Checks a document against its definition; <paramref name="before"/> is the stored one.</summary>
|
||||
internal static List<string> Check(DocumentDefinition definition, DocumentRecord record, DocumentRecord? before)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Writes the header and replaces the lines of a draft or open document.</summary>
|
||||
internal async Task<long> 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<DocumentRecord> ChangeStateAsync(
|
||||
Actor actor,
|
||||
string companyCode,
|
||||
DocumentFamily family,
|
||||
long id,
|
||||
DocumentAction action,
|
||||
Func<IUnitOfWork, DocumentDefinition, DocumentRecord, CancellationToken, Task>? before,
|
||||
Func<IUnitOfWork, DocumentRecord, string, CancellationToken, Task>? 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<DocumentLink, long>();
|
||||
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<DocumentLink, long>();
|
||||
var mine = (await links.ListAsync(Query.For<DocumentLink>().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<IReadOnlyList<DocumentLink>> LinksFromAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<DocumentLink, long>().ListAsync(Query.For<DocumentLink>().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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A number given to a document.</summary>
|
||||
/// <param name="Numerator">The numerator row (code and year) that gave it, already updated.</param>
|
||||
/// <param name="Number">The progressive number.</param>
|
||||
/// <param name="Text">The number as printed.</param>
|
||||
public sealed record AssignedNumber(DocumentNumerator Numerator, long Number, string Text);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class DocumentNumberingService
|
||||
{
|
||||
/// <summary>Error: on a numerator without gaps the date precedes the last document numbered.</summary>
|
||||
public const string DateBeforeLast = "document.number.date-before-last";
|
||||
|
||||
/// <summary>Error: the numerator of the document type does not exist.</summary>
|
||||
public const string NumeratorMissing = "document.number.numerator-missing";
|
||||
|
||||
/// <summary>Error: the numerator is disabled.</summary>
|
||||
public const string NumeratorDisabled = "document.number.numerator-disabled";
|
||||
|
||||
/// <summary>Error: the formatted number is longer than the column.</summary>
|
||||
public const string NumberTooLong = "document.number.too-long";
|
||||
|
||||
/// <summary>The longest number as printed.</summary>
|
||||
public const int MaxLength = 30;
|
||||
|
||||
/// <summary>The lock that serializes the numbering of a numerator in a year.</summary>
|
||||
/// <param name="code">The numerator code.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <returns>The lock key.</returns>
|
||||
public static string LockKey(string code, int year) => "numerator:" + code + ":" + year.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="uow">A company unit of work inside a transaction.</param>
|
||||
/// <param name="numeratorId">The numerator of the document type.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The number.</returns>
|
||||
/// <exception cref="ValidationFailedException">The numerator is missing or disabled, or the date is out of sequence.</exception>
|
||||
public static async Task<AssignedNumber> NextAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var numerators = uow.Repository<DocumentNumerator, long>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>What the next number would be, without giving it (the preview of a draft).</summary>
|
||||
/// <param name="uow">A company unit of work.</param>
|
||||
/// <param name="numeratorId">The numerator of the document type.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The number as printed, or <see langword="null"/> when the numerator is missing.</returns>
|
||||
public static async Task<string?> PreviewAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var numerators = uow.Repository<DocumentNumerator, long>();
|
||||
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<DocumentNumerator>().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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="uow">A company unit of work.</param>
|
||||
/// <param name="numeratorId">The numerator row (code and year).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The missing numbers, in order.</returns>
|
||||
public static async Task<IReadOnlyList<long>> FindGapsAsync(IUnitOfWork uow, long numeratorId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var numerator = await uow.Repository<DocumentNumerator, long>().GetAsync(numeratorId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException([NumeratorMissing]);
|
||||
var used = new HashSet<long>();
|
||||
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<long>(sql, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
var missing = new List<long>();
|
||||
for (var n = 1L; n <= numerator.LastNumber; n++)
|
||||
{
|
||||
if (!used.Contains(n))
|
||||
{
|
||||
missing.Add(n);
|
||||
}
|
||||
}
|
||||
|
||||
return missing;
|
||||
}
|
||||
|
||||
private static async Task<DocumentNumerator> ForYearAsync(IUnitOfWork uow, DocumentNumerator template, int year, CancellationToken cancellationToken)
|
||||
{
|
||||
var numerators = uow.Repository<DocumentNumerator, long>();
|
||||
var code = template.Code;
|
||||
if (await numerators.FindAsync(Query.For<DocumentNumerator>().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<DocumentNumerator>().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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Documents;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>A document of one family, with its lines.</summary>
|
||||
/// <typeparam name="THeader">The header.</typeparam>
|
||||
/// <typeparam name="TLine">The line.</typeparam>
|
||||
public sealed class DocumentRecord<THeader, TLine>
|
||||
where THeader : DocumentHeader, new()
|
||||
where TLine : DocumentLine, new()
|
||||
{
|
||||
/// <summary>The header.</summary>
|
||||
public THeader Header { get; set; } = new();
|
||||
|
||||
/// <summary>The lines, in order.</summary>
|
||||
public List<TLine> Lines { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <typeparam name="THeader">The header.</typeparam>
|
||||
/// <typeparam name="TLine">The line.</typeparam>
|
||||
public sealed class DocumentService<THeader, TLine>
|
||||
where THeader : DocumentHeader, new()
|
||||
where TLine : DocumentLine, new()
|
||||
{
|
||||
private readonly DocumentEngine _engine;
|
||||
private readonly DocumentCopyService _copies;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="engine">The engine.</param>
|
||||
/// <param name="copies">The copies.</param>
|
||||
public DocumentService(DocumentEngine engine, DocumentCopyService copies)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(engine);
|
||||
ArgumentNullException.ThrowIfNull(copies);
|
||||
_engine = engine;
|
||||
_copies = copies;
|
||||
}
|
||||
|
||||
/// <summary>The family.</summary>
|
||||
public DocumentFamily Family => FamilyOfHeader;
|
||||
|
||||
private static readonly DocumentFamily FamilyOfHeader = DocumentStores.FamilyOf<THeader>();
|
||||
|
||||
/// <summary>A new draft of a type of this family, not saved.</summary>
|
||||
/// <param name="actor">Who creates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="typeCode">The document type.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The draft.</returns>
|
||||
public async Task<DocumentRecord<THeader, TLine>> 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);
|
||||
}
|
||||
|
||||
/// <summary>Reads a document.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document, if any.</returns>
|
||||
public async Task<DocumentRecord<THeader, TLine>?> 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;
|
||||
|
||||
/// <summary>Saves a draft, or an order still open.</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document as saved.</returns>
|
||||
public async Task<DocumentRecord<THeader, TLine>> SaveAsync(Actor actor, string companyCode, DocumentRecord<THeader, TLine> 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);
|
||||
}
|
||||
|
||||
/// <summary>Confirms a document, or issues an invoice.</summary>
|
||||
/// <param name="actor">Who confirms.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document.</returns>
|
||||
public async Task<DocumentRecord<THeader, TLine>> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
|
||||
Typed(await _engine.ConfirmAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Cancels a document.</summary>
|
||||
/// <param name="actor">Who cancels.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="reason">Why (required for invoices).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document.</returns>
|
||||
public async Task<DocumentRecord<THeader, TLine>> CancelAsync(Actor actor, string companyCode, long id, string? reason, CancellationToken cancellationToken = default) =>
|
||||
Typed(await _engine.CancelAsync(actor, companyCode, Family, id, reason, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Closes what is left to fulfil.</summary>
|
||||
/// <param name="actor">Who closes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document.</returns>
|
||||
public async Task<DocumentRecord<THeader, TLine>> CloseAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
|
||||
Typed(await _engine.CloseAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Reopens a closed document.</summary>
|
||||
/// <param name="actor">Who reopens.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The document.</returns>
|
||||
public async Task<DocumentRecord<THeader, TLine>> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
|
||||
Typed(await _engine.ReopenAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Deletes a draft.</summary>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
|
||||
_engine.DeleteAsync(actor, companyCode, Family, id, cancellationToken);
|
||||
|
||||
/// <summary>Copies a document of this family into a new draft of any type of the same direction.</summary>
|
||||
/// <param name="actor">Who copies.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The source.</param>
|
||||
/// <param name="targetTypeCode">The type of the new document.</param>
|
||||
/// <param name="lineIds">The lines to copy; all when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new draft, in its own family.</returns>
|
||||
public Task<DocumentRecord> CopyAsync(
|
||||
Actor actor, string companyCode, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null, CancellationToken cancellationToken = default) =>
|
||||
_copies.CopyAsync(actor, companyCode, Family, id, targetTypeCode, lineIds, cancellationToken);
|
||||
|
||||
private static DocumentRecord<THeader, TLine> Typed(DocumentRecord record) =>
|
||||
new() { Header = (THeader)record.Header, Lines = [.. record.Lines.Cast<TLine>()] };
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
internal interface IDocumentStore
|
||||
{
|
||||
/// <summary>The family.</summary>
|
||||
DocumentFamily Family { get; }
|
||||
|
||||
/// <summary>The header table.</summary>
|
||||
string HeaderTable { get; }
|
||||
|
||||
/// <summary>A new header of the family.</summary>
|
||||
/// <returns>The header.</returns>
|
||||
DocumentHeader NewHeader();
|
||||
|
||||
/// <summary>A new line of the family.</summary>
|
||||
/// <returns>The line.</returns>
|
||||
DocumentLine NewLine();
|
||||
|
||||
/// <summary>Reads a header.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The header, if any.</returns>
|
||||
Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads the lines of a document in their order.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lines.</returns>
|
||||
Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads a line.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="id">The line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The line, if any.</returns>
|
||||
Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Inserts a header.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="header">The header.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Updates a header.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="header">The header.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Deletes a header and, by cascade, its lines.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Inserts a line.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="line">The line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Updates a line.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="line">The line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Deletes a line.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="id">The line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Writes a change of a header in the history, under the name of its class.</summary>
|
||||
/// <param name="audit">The history.</param>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="action">What happened.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="before">The header before.</param>
|
||||
/// <param name="after">The header after.</param>
|
||||
/// <param name="userName">Who did it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task RecordAsync(
|
||||
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The store of one family.</summary>
|
||||
/// <typeparam name="THeader">The header.</typeparam>
|
||||
/// <typeparam name="TLine">The line.</typeparam>
|
||||
internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, string headerTable) : IDocumentStore
|
||||
where THeader : DocumentHeader, new()
|
||||
where TLine : DocumentLine, new()
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public DocumentFamily Family => family;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string HeaderTable => headerTable;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DocumentHeader NewHeader() => new THeader();
|
||||
|
||||
/// <inheritdoc />
|
||||
public DocumentLine NewLine() => new TLine();
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<THeader, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<DocumentLine>> 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<TLine, long>().ListAsync(Query.For<TLine>().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<DocumentLine>()];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<TLine, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
|
||||
header.Id = await uow.Repository<THeader, long>().InsertAsync((THeader)header, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
|
||||
uow.Repository<THeader, long>().UpdateAsync((THeader)header, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
|
||||
uow.Repository<THeader, long>().DeleteAsync(id, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
|
||||
line.Id = await uow.Repository<TLine, long>().InsertAsync((TLine)line, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
|
||||
uow.Repository<TLine, long>().UpdateAsync((TLine)line, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
|
||||
uow.Repository<TLine, long>().DeleteAsync(id, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The stores of the six families.</summary>
|
||||
internal static class DocumentStores
|
||||
{
|
||||
private static readonly Dictionary<DocumentFamily, IDocumentStore> ByFamily = new IDocumentStore[]
|
||||
{
|
||||
new DocumentStore<SaleQuotation, SaleQuotationLine>(DocumentFamily.SaleQuotation, "sale_quotations"),
|
||||
new DocumentStore<SaleOrder, SaleOrderLine>(DocumentFamily.SaleOrder, "sale_orders"),
|
||||
new DocumentStore<SaleDocument, SaleDocumentLine>(DocumentFamily.SaleDocument, "sale_documents"),
|
||||
new DocumentStore<PurchaseOrder, PurchaseOrderLine>(DocumentFamily.PurchaseOrder, "purchase_orders"),
|
||||
new DocumentStore<PurchaseDocument, PurchaseDocumentLine>(DocumentFamily.PurchaseDocument, "purchase_documents"),
|
||||
new DocumentStore<InventoryDocument, InventoryDocumentLine>(DocumentFamily.InventoryDocument, "inventory_documents"),
|
||||
}.ToDictionary(s => s.Family);
|
||||
|
||||
/// <summary>Every store.</summary>
|
||||
public static IEnumerable<IDocumentStore> All => ByFamily.Values;
|
||||
|
||||
/// <summary>The store of a family.</summary>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <returns>The store.</returns>
|
||||
public static IDocumentStore Of(DocumentFamily family) => ByFamily[family];
|
||||
|
||||
/// <summary>The family of a header class.</summary>
|
||||
/// <typeparam name="THeader">The header.</typeparam>
|
||||
/// <returns>The family.</returns>
|
||||
public static DocumentFamily FamilyOf<THeader>()
|
||||
where THeader : DocumentHeader, new()
|
||||
{
|
||||
var type = typeof(THeader);
|
||||
return All.Single(s => s.NewHeader().GetType() == type).Family;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -66,6 +66,9 @@ public sealed partial class TableCatalog
|
||||
/// <summary>Error: another price list is already the base one.</summary>
|
||||
public const string BaseDuplicate = "tables.price-list.base-duplicate";
|
||||
|
||||
/// <summary>A document type without a kind.</summary>
|
||||
public const string DocumentKindRequired = "tables.document-type.kind-required";
|
||||
|
||||
/// <summary>The maximum depth of item categories.</summary>
|
||||
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();
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
namespace Khaemhat.Core.Documents;
|
||||
|
||||
/// <summary>How the documents of a kind behave (ADR 0032).</summary>
|
||||
/// <param name="Kind">The kind.</param>
|
||||
/// <param name="Family">The tables that hold them.</param>
|
||||
/// <param name="Direction">Customer, supplier or internal.</param>
|
||||
/// <param name="Lifecycle">The states they go through.</param>
|
||||
/// <param name="Effects">What confirming them does.</param>
|
||||
/// <param name="Lines">The line kinds they accept.</param>
|
||||
/// <param name="Sources">The kinds whose lines they fulfil (order to delivery note, delivery note to invoice...).</param>
|
||||
/// <param name="ReadPermission">The permission to see them.</param>
|
||||
/// <param name="WritePermission">The permission to create and change drafts.</param>
|
||||
/// <param name="ConfirmPermission">The permission to confirm or issue, cancel, close and reopen.</param>
|
||||
/// <param name="DeletePermission">The permission to delete drafts.</param>
|
||||
public sealed record DocumentBehavior(
|
||||
DocumentKind Kind,
|
||||
DocumentFamily Family,
|
||||
DocumentDirection Direction,
|
||||
DocumentLifecycle Lifecycle,
|
||||
DocumentEffects Effects,
|
||||
IReadOnlyList<DocumentLineKind> Lines,
|
||||
IReadOnlyList<DocumentKind> Sources,
|
||||
string ReadPermission,
|
||||
string WritePermission,
|
||||
string ConfirmPermission,
|
||||
string DeletePermission)
|
||||
{
|
||||
/// <summary>Whether the documents need a customer or supplier.</summary>
|
||||
public bool NeedsParty => Direction != DocumentDirection.Internal;
|
||||
|
||||
/// <summary>Whether the documents have the given effect.</summary>
|
||||
/// <param name="effect">The effect.</param>
|
||||
/// <returns>Whether they have it.</returns>
|
||||
public bool Has(DocumentEffects effect) => (Effects & effect) == effect;
|
||||
|
||||
/// <summary>Whether the documents fulfil the lines of documents of another kind.</summary>
|
||||
/// <param name="source">The kind of the source.</param>
|
||||
/// <returns>Whether a copy from it creates fulfilment links.</returns>
|
||||
public bool Fulfils(DocumentKind source) => Sources.Contains(source);
|
||||
}
|
||||
|
||||
/// <summary>The behaviour of every <see cref="DocumentKind"/>.</summary>
|
||||
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<DocumentKind, DocumentBehavior> ByKind = Build().ToDictionary(b => b.Kind);
|
||||
|
||||
/// <summary>Every behaviour, in the order of <see cref="DocumentKind"/>.</summary>
|
||||
public static IReadOnlyList<DocumentBehavior> All { get; } = [.. ByKind.Values.OrderBy(b => b.Kind)];
|
||||
|
||||
/// <summary>The behaviour of a kind.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>The behaviour.</returns>
|
||||
public static DocumentBehavior Of(DocumentKind kind) =>
|
||||
ByKind.TryGetValue(kind, out var behavior) ? behavior : throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown document kind.");
|
||||
|
||||
/// <summary>The kinds kept in a family.</summary>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <returns>The kinds.</returns>
|
||||
public static IReadOnlyList<DocumentKind> KindsOf(DocumentFamily family) => [.. All.Where(b => b.Family == family).Select(b => b.Kind)];
|
||||
|
||||
private static IEnumerable<DocumentBehavior> 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);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
namespace Khaemhat.Core.Documents;
|
||||
|
||||
/// <summary>The family of a document: the pair of tables that holds it (SPEC §11.3).</summary>
|
||||
public enum DocumentFamily
|
||||
{
|
||||
/// <summary>Quotations (<c>sale_quotations</c>).</summary>
|
||||
SaleQuotation = 0,
|
||||
|
||||
/// <summary>Customer orders (<c>sale_orders</c>).</summary>
|
||||
SaleOrder = 1,
|
||||
|
||||
/// <summary>Delivery notes, invoices, credit and debit notes, pro forma, fees, self-invoices (<c>sale_documents</c>).</summary>
|
||||
SaleDocument = 2,
|
||||
|
||||
/// <summary>Supplier orders (<c>purchase_orders</c>).</summary>
|
||||
PurchaseOrder = 3,
|
||||
|
||||
/// <summary>Supplier delivery notes, invoices and credit notes (<c>purchase_documents</c>).</summary>
|
||||
PurchaseDocument = 4,
|
||||
|
||||
/// <summary>Warehouse entries (<c>inventory_documents</c>).</summary>
|
||||
InventoryDocument = 5,
|
||||
}
|
||||
|
||||
/// <summary>Who the document is with.</summary>
|
||||
public enum DocumentDirection
|
||||
{
|
||||
/// <summary>A customer: the company sells.</summary>
|
||||
Sale = 0,
|
||||
|
||||
/// <summary>A supplier: the company buys.</summary>
|
||||
Purchase = 1,
|
||||
|
||||
/// <summary>Nobody: an internal document.</summary>
|
||||
Internal = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public enum DocumentKind
|
||||
{
|
||||
/// <summary>A quotation to a customer.</summary>
|
||||
Quotation = 0,
|
||||
|
||||
/// <summary>A customer order.</summary>
|
||||
SalesOrder = 1,
|
||||
|
||||
/// <summary>A delivery note (DDT) to a customer.</summary>
|
||||
DeliveryNote = 2,
|
||||
|
||||
/// <summary>An immediate invoice.</summary>
|
||||
ImmediateInvoice = 3,
|
||||
|
||||
/// <summary>An accompanying invoice: an invoice that is also the delivery note.</summary>
|
||||
AccompanyingInvoice = 4,
|
||||
|
||||
/// <summary>A deferred invoice of one or more delivery notes.</summary>
|
||||
DeferredInvoice = 5,
|
||||
|
||||
/// <summary>A down payment invoice.</summary>
|
||||
DownPaymentInvoice = 6,
|
||||
|
||||
/// <summary>A credit note to a customer.</summary>
|
||||
CreditNote = 7,
|
||||
|
||||
/// <summary>A debit note to a customer.</summary>
|
||||
DebitNote = 8,
|
||||
|
||||
/// <summary>A professional fee invoice (parcella).</summary>
|
||||
Fee = 9,
|
||||
|
||||
/// <summary>A pro forma invoice, without fiscal effects.</summary>
|
||||
ProForma = 10,
|
||||
|
||||
/// <summary>A self-invoice or integration of a purchase (reverse charge, purchases from abroad).</summary>
|
||||
SelfInvoice = 11,
|
||||
|
||||
/// <summary>An order to a supplier.</summary>
|
||||
PurchaseOrder = 12,
|
||||
|
||||
/// <summary>A delivery note of a supplier (goods received).</summary>
|
||||
PurchaseDeliveryNote = 13,
|
||||
|
||||
/// <summary>An invoice of a supplier.</summary>
|
||||
PurchaseInvoice = 14,
|
||||
|
||||
/// <summary>A credit note of a supplier.</summary>
|
||||
PurchaseCreditNote = 15,
|
||||
|
||||
/// <summary>A warehouse entry: loads, unloads, transfers.</summary>
|
||||
InventoryEntry = 16,
|
||||
}
|
||||
|
||||
/// <summary>The life cycle a document follows (ADR 0032).</summary>
|
||||
public enum DocumentLifecycle
|
||||
{
|
||||
/// <summary>Draft, confirmed, partially fulfilled, fulfilled, closed, cancelled: quotations, orders, delivery notes, pro forma.</summary>
|
||||
Order = 0,
|
||||
|
||||
/// <summary>Draft, issued, then the states of the exchange system: sale invoices and self-invoices.</summary>
|
||||
Invoice = 1,
|
||||
|
||||
/// <summary>Draft, confirmed, cancelled: supplier invoices, warehouse entries.</summary>
|
||||
Simple = 2,
|
||||
}
|
||||
|
||||
/// <summary>The state of a document (SPEC §11.3).</summary>
|
||||
public enum DocumentStatus
|
||||
{
|
||||
/// <summary>Being written: no number, no effects.</summary>
|
||||
Draft = 0,
|
||||
|
||||
/// <summary>Confirmed: numbered, effects applied.</summary>
|
||||
Confirmed = 1,
|
||||
|
||||
/// <summary>Some lines fulfilled by later documents.</summary>
|
||||
PartiallyFulfilled = 2,
|
||||
|
||||
/// <summary>Every line fulfilled.</summary>
|
||||
Fulfilled = 3,
|
||||
|
||||
/// <summary>Closed by hand: what is left will not be fulfilled.</summary>
|
||||
Closed = 4,
|
||||
|
||||
/// <summary>Cancelled: the number stays, the effects are removed.</summary>
|
||||
Cancelled = 5,
|
||||
|
||||
/// <summary>An invoice issued: numbered and no longer changeable.</summary>
|
||||
Issued = 6,
|
||||
|
||||
/// <summary>The electronic invoice file has been generated.</summary>
|
||||
SdiGenerated = 7,
|
||||
|
||||
/// <summary>The electronic invoice has been sent to the exchange system.</summary>
|
||||
SdiSent = 8,
|
||||
|
||||
/// <summary>The exchange system delivered the invoice.</summary>
|
||||
SdiDelivered = 9,
|
||||
|
||||
/// <summary>The exchange system rejected the invoice.</summary>
|
||||
SdiRejected = 10,
|
||||
|
||||
/// <summary>The exchange system could not deliver the invoice (made available to the customer).</summary>
|
||||
SdiNotDelivered = 11,
|
||||
}
|
||||
|
||||
/// <summary>What a user or a procedure can do with a document; the state machine says when.</summary>
|
||||
public enum DocumentAction
|
||||
{
|
||||
/// <summary>Change the header or the lines.</summary>
|
||||
Edit = 0,
|
||||
|
||||
/// <summary>Delete a draft that was never numbered.</summary>
|
||||
Delete = 1,
|
||||
|
||||
/// <summary>Confirm: number and apply the effects (orders, delivery notes, simple documents).</summary>
|
||||
Confirm = 2,
|
||||
|
||||
/// <summary>Issue an invoice: number it and make it unchangeable.</summary>
|
||||
Issue = 3,
|
||||
|
||||
/// <summary>Cancel: keep the number, remove the effects.</summary>
|
||||
Cancel = 4,
|
||||
|
||||
/// <summary>Close what is left to fulfil.</summary>
|
||||
Close = 5,
|
||||
|
||||
/// <summary>Reopen a closed document.</summary>
|
||||
Reopen = 6,
|
||||
|
||||
/// <summary>Make a new draft from the document (duplicate or transform).</summary>
|
||||
Copy = 7,
|
||||
|
||||
/// <summary>Record that the electronic invoice file was generated.</summary>
|
||||
GenerateXml = 8,
|
||||
|
||||
/// <summary>Record that the electronic invoice was sent.</summary>
|
||||
Send = 9,
|
||||
|
||||
/// <summary>Record the delivery receipt.</summary>
|
||||
MarkDelivered = 10,
|
||||
|
||||
/// <summary>Record the rejection.</summary>
|
||||
MarkRejected = 11,
|
||||
|
||||
/// <summary>Record that the invoice could not be delivered.</summary>
|
||||
MarkNotDelivered = 12,
|
||||
}
|
||||
|
||||
/// <summary>What confirming a document does to the rest of the company's data (applied by the modules: M6, M7, M8).</summary>
|
||||
[Flags]
|
||||
public enum DocumentEffects
|
||||
{
|
||||
/// <summary>No effect.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>Moves stock (load or unload by the warehouse reason).</summary>
|
||||
Inventory = 1,
|
||||
|
||||
/// <summary>Commits stock to customers (orders).</summary>
|
||||
Commitment = 2,
|
||||
|
||||
/// <summary>Records quantities ordered from suppliers.</summary>
|
||||
Ordered = 4,
|
||||
|
||||
/// <summary>Posts to the general ledger and the VAT registers.</summary>
|
||||
Ledger = 8,
|
||||
|
||||
/// <summary>Generates the installments of the payment schedule.</summary>
|
||||
Installments = 16,
|
||||
|
||||
/// <summary>Produces an electronic invoice.</summary>
|
||||
EInvoice = 32,
|
||||
}
|
||||
|
||||
/// <summary>The kind of a document line.</summary>
|
||||
public enum DocumentLineKind
|
||||
{
|
||||
/// <summary>An item of the catalogue, with quantity and price.</summary>
|
||||
Item = 0,
|
||||
|
||||
/// <summary>A line with quantity and price but no item.</summary>
|
||||
Free = 1,
|
||||
|
||||
/// <summary>Text only.</summary>
|
||||
Description = 2,
|
||||
|
||||
/// <summary>An ancillary expense (transport, collection).</summary>
|
||||
Expense = 3,
|
||||
|
||||
/// <summary>A discount, premium or allowance.</summary>
|
||||
Discount = 4,
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
namespace Khaemhat.Core.Documents;
|
||||
|
||||
/// <summary>
|
||||
/// 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: <see cref="FulfillmentCalculator"/> computes them.
|
||||
/// </summary>
|
||||
public static class DocumentStateMachine
|
||||
{
|
||||
private static readonly Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>> Rules = Build();
|
||||
|
||||
/// <summary>The states a life cycle uses, in order.</summary>
|
||||
/// <param name="lifecycle">The life cycle.</param>
|
||||
/// <returns>The states.</returns>
|
||||
public static IReadOnlyList<DocumentStatus> States(DocumentLifecycle lifecycle) =>
|
||||
[.. Rules.Keys.Where(k => k.Item1 == lifecycle).Select(k => k.Item2).OrderBy(s => s)];
|
||||
|
||||
/// <summary>The actions a state admits.</summary>
|
||||
/// <param name="lifecycle">The life cycle.</param>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns>The actions, in the order of <see cref="DocumentAction"/>.</returns>
|
||||
public static IReadOnlyList<DocumentAction> Actions(DocumentLifecycle lifecycle, DocumentStatus status) =>
|
||||
Rules.TryGetValue((lifecycle, status), out var actions) ? [.. actions.Keys.OrderBy(a => a)] : [];
|
||||
|
||||
/// <summary>Whether a state admits an action.</summary>
|
||||
/// <param name="lifecycle">The life cycle.</param>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <param name="action">The action.</param>
|
||||
/// <returns>Whether it is admitted.</returns>
|
||||
public static bool Allows(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) =>
|
||||
Rules.TryGetValue((lifecycle, status), out var actions) && actions.ContainsKey(action);
|
||||
|
||||
/// <summary>The state after an action.</summary>
|
||||
/// <param name="lifecycle">The life cycle.</param>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <param name="action">The action.</param>
|
||||
/// <returns>The new state (the same one for actions that do not move it, such as edit and copy).</returns>
|
||||
/// <exception cref="InvalidDocumentActionException">The state does not admit the action.</exception>
|
||||
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);
|
||||
|
||||
/// <summary>Whether the header and lines can change in a state.</summary>
|
||||
/// <param name="lifecycle">The life cycle.</param>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns>Whether they can.</returns>
|
||||
public static bool IsEditable(DocumentLifecycle lifecycle, DocumentStatus status) => Allows(lifecycle, status, DocumentAction.Edit);
|
||||
|
||||
/// <summary>Whether a document in this state counts: confirmed or issued, and not cancelled.</summary>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns>Whether its effects and links are in force.</returns>
|
||||
public static bool IsInForce(DocumentStatus status) => status is not (DocumentStatus.Draft or DocumentStatus.Cancelled);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="lifecycle">The life cycle.</param>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <param name="fulfillment">What the lines say.</param>
|
||||
/// <returns>The new state.</returns>
|
||||
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<DocumentAction, DocumentStatus>> Build()
|
||||
{
|
||||
var rules = new Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An action the state of the document does not admit.</summary>
|
||||
public sealed class InvalidDocumentActionException : InvalidOperationException
|
||||
{
|
||||
/// <summary>The error code for the interface.</summary>
|
||||
public const string Code = "document.action.not-allowed";
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public InvalidDocumentActionException()
|
||||
: base(Code)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public InvalidDocumentActionException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public InvalidDocumentActionException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="lifecycle">The life cycle.</param>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <param name="action">The refused action.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The life cycle.</summary>
|
||||
public DocumentLifecycle Lifecycle { get; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public DocumentStatus Status { get; }
|
||||
|
||||
/// <summary>The refused action.</summary>
|
||||
public DocumentAction Action { get; }
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Items;
|
||||
|
||||
namespace Khaemhat.Core.Documents;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public abstract class DocumentHeader : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The document type of the company.</summary>
|
||||
public long DocumentTypeId { get; set; }
|
||||
|
||||
/// <summary>The kind, copied from the type when the document is created.</summary>
|
||||
public DocumentKind Kind { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public DocumentStatus Status { get; set; }
|
||||
|
||||
/// <summary>The numerator row (code and year) that gave the number.</summary>
|
||||
public long? NumeratorId { get; set; }
|
||||
|
||||
/// <summary>The section (sezionale) of the numerator.</summary>
|
||||
public string? Section { get; set; }
|
||||
|
||||
/// <summary>The progressive number; empty until confirmation.</summary>
|
||||
public long? Number { get; set; }
|
||||
|
||||
/// <summary>The number as printed, such as <c>12/2026</c>.</summary>
|
||||
public string? DocumentNumber { get; set; }
|
||||
|
||||
/// <summary>The date of the document.</summary>
|
||||
public DateOnly DocumentDate { get; set; }
|
||||
|
||||
/// <summary>The year of the numbering.</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The customer or supplier.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The destination (an address of the party).</summary>
|
||||
public long? DestinationId { get; set; }
|
||||
|
||||
/// <summary>The reference of the other side: customer order number, supplier invoice or delivery note number.</summary>
|
||||
public string? ExternalReference { get; set; }
|
||||
|
||||
/// <summary>The date of the reference.</summary>
|
||||
public DateOnly? ExternalDate { get; set; }
|
||||
|
||||
/// <summary>The currency.</summary>
|
||||
public string CurrencyCode { get; set; } = "EUR";
|
||||
|
||||
/// <summary>The exchange rate to euro.</summary>
|
||||
public decimal ExchangeRate { get; set; } = 1m;
|
||||
|
||||
/// <summary>The price list.</summary>
|
||||
public long? PriceListId { get; set; }
|
||||
|
||||
/// <summary>The payment terms.</summary>
|
||||
public long? PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>The payment method.</summary>
|
||||
public long? PaymentMethodId { get; set; }
|
||||
|
||||
/// <summary>The bank account of the company that collects or pays.</summary>
|
||||
public long? BankAccountId { get; set; }
|
||||
|
||||
/// <summary>The agent.</summary>
|
||||
public long? SalespersonId { get; set; }
|
||||
|
||||
/// <summary>The warehouse.</summary>
|
||||
public long? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The warehouse reason.</summary>
|
||||
public long? InventoryReasonId { get; set; }
|
||||
|
||||
/// <summary>The reason of the transport.</summary>
|
||||
public long? TransportReasonId { get; set; }
|
||||
|
||||
/// <summary>The shipping terms (porto).</summary>
|
||||
public long? ShippingTermId { get; set; }
|
||||
|
||||
/// <summary>The carrier.</summary>
|
||||
public long? CarrierId { get; set; }
|
||||
|
||||
/// <summary>The appearance of the goods.</summary>
|
||||
public long? GoodsAppearanceId { get; set; }
|
||||
|
||||
/// <summary>The number of packages.</summary>
|
||||
public int? Packages { get; set; }
|
||||
|
||||
/// <summary>The gross weight in kg.</summary>
|
||||
public decimal? GrossWeight { get; set; }
|
||||
|
||||
/// <summary>The net weight in kg.</summary>
|
||||
public decimal? NetWeight { get; set; }
|
||||
|
||||
/// <summary>When the transport starts.</summary>
|
||||
public DateTime? TransportStart { get; set; }
|
||||
|
||||
/// <summary>Until when a quotation is valid.</summary>
|
||||
public DateOnly? ValidUntil { get; set; }
|
||||
|
||||
/// <summary>The delivery date requested or promised.</summary>
|
||||
public DateOnly? DeliveryDate { get; set; }
|
||||
|
||||
/// <summary>The revision of a quotation.</summary>
|
||||
public int Revision { get; set; }
|
||||
|
||||
/// <summary>Printed at least once.</summary>
|
||||
public bool Printed { get; set; }
|
||||
|
||||
/// <summary>Sent by e-mail at least once.</summary>
|
||||
public bool Sent { get; set; }
|
||||
|
||||
/// <summary>Posted to the ledger.</summary>
|
||||
public bool Posted { get; set; }
|
||||
|
||||
/// <summary>Installments generated in the payment schedule.</summary>
|
||||
public bool InstallmentsGenerated { get; set; }
|
||||
|
||||
/// <summary>Electronic invoice file generated.</summary>
|
||||
public bool XmlGenerated { get; set; }
|
||||
|
||||
/// <summary>The taxable amount.</summary>
|
||||
public decimal TaxableAmount { get; set; }
|
||||
|
||||
/// <summary>The tax.</summary>
|
||||
public decimal TaxAmount { get; set; }
|
||||
|
||||
/// <summary>The total of the document.</summary>
|
||||
public decimal TotalAmount { get; set; }
|
||||
|
||||
/// <summary>The discount on the total (percent formula, such as <c>5</c> or <c>10+5</c>).</summary>
|
||||
public string? FooterDiscount { get; set; }
|
||||
|
||||
/// <summary>The ancillary expenses.</summary>
|
||||
public decimal ExpensesAmount { get; set; }
|
||||
|
||||
/// <summary>The stamp duty.</summary>
|
||||
public decimal StampDuty { get; set; }
|
||||
|
||||
/// <summary>The withholding tax.</summary>
|
||||
public decimal WithholdingAmount { get; set; }
|
||||
|
||||
/// <summary>The social security contribution (cassa previdenza).</summary>
|
||||
public decimal SocialSecurityAmount { get; set; }
|
||||
|
||||
/// <summary>The amount to pay.</summary>
|
||||
public decimal NetAmount { get; set; }
|
||||
|
||||
/// <summary>The notes printed on the document.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>The ledger entry, once posted (M7).</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <summary>The VAT protocol of a supplier invoice.</summary>
|
||||
public long? VatProtocol { get; set; }
|
||||
|
||||
/// <summary>When the document was confirmed or issued.</summary>
|
||||
public DateTime? ConfirmedAt { get; set; }
|
||||
|
||||
/// <summary>Who confirmed or issued it.</summary>
|
||||
public string? ConfirmedBy { get; set; }
|
||||
|
||||
/// <summary>When it was cancelled.</summary>
|
||||
public DateTime? CancelledAt { get; set; }
|
||||
|
||||
/// <summary>Why it was cancelled.</summary>
|
||||
public string? CancelReason { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
|
||||
/// <summary>A shallow copy of the same class (the state before a change, for the history).</summary>
|
||||
/// <returns>The copy.</returns>
|
||||
public DocumentHeader Clone() => (DocumentHeader)MemberwiseClone();
|
||||
}
|
||||
|
||||
/// <summary>A line of a document (SPEC §11.3).</summary>
|
||||
public abstract class DocumentLine : Entity<long>
|
||||
{
|
||||
/// <summary>The document.</summary>
|
||||
public long DocumentId { get; set; }
|
||||
|
||||
/// <summary>The progressive number of the line (1, 2...), the one printed and sent.</summary>
|
||||
public int LineNumber { get; set; }
|
||||
|
||||
/// <summary>The kind of line.</summary>
|
||||
public DocumentLineKind Kind { get; set; }
|
||||
|
||||
/// <summary>The item.</summary>
|
||||
public long? ItemId { get; set; }
|
||||
|
||||
/// <summary>The description.</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The unit of measure.</summary>
|
||||
public long? UnitOfMeasureId { get; set; }
|
||||
|
||||
/// <summary>The quantity.</summary>
|
||||
public decimal Quantity { get; set; }
|
||||
|
||||
/// <summary>The unit price.</summary>
|
||||
public decimal Price { get; set; }
|
||||
|
||||
/// <summary>Where the price comes from.</summary>
|
||||
public PriceSource PriceSource { get; set; }
|
||||
|
||||
/// <summary>The discounts, such as <c>10+5</c>.</summary>
|
||||
public string? DiscountFormula { get; set; }
|
||||
|
||||
/// <summary>The VAT code.</summary>
|
||||
public long? TaxCodeId { get; set; }
|
||||
|
||||
/// <summary>The taxable amount of the line.</summary>
|
||||
public decimal TaxableAmount { get; set; }
|
||||
|
||||
/// <summary>The warehouse of the line, when different from the header.</summary>
|
||||
public long? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The delivery date of the line.</summary>
|
||||
public DateOnly? DeliveryDate { get; set; }
|
||||
|
||||
/// <summary>How much later documents fulfilled.</summary>
|
||||
public decimal FulfilledQuantity { get; set; }
|
||||
|
||||
/// <summary>The rest will not be fulfilled (line closed by hand).</summary>
|
||||
public bool FulfillmentClosed { get; set; }
|
||||
|
||||
/// <summary>The family of the line this one was copied from to fulfil it.</summary>
|
||||
public DocumentFamily? SourceFamily { get; set; }
|
||||
|
||||
/// <summary>The line this one fulfils.</summary>
|
||||
public long? SourceLineId { get; set; }
|
||||
|
||||
/// <summary>The ledger account (M7).</summary>
|
||||
public string? AccountCode { get; set; }
|
||||
|
||||
/// <summary>The cost centre.</summary>
|
||||
public long? CostCenterId { get; set; }
|
||||
|
||||
/// <summary>The job (commessa).</summary>
|
||||
public long? JobId { get; set; }
|
||||
|
||||
/// <summary>Notes of the line.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>The order on screen and in print.</summary>
|
||||
public int SortOrder { get; set; }
|
||||
|
||||
/// <summary>What is left to fulfil: zero for closed lines and lines without quantity.</summary>
|
||||
public decimal Residual => FulfillmentClosed || !CarriesQuantity(Kind) ? 0m : Math.Max(0m, Quantity - FulfilledQuantity);
|
||||
|
||||
/// <summary>A shallow copy of the same class.</summary>
|
||||
/// <returns>The copy.</returns>
|
||||
public DocumentLine Clone() => (DocumentLine)MemberwiseClone();
|
||||
|
||||
/// <summary>Whether lines of a kind carry a quantity that later documents can fulfil.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Whether they do.</returns>
|
||||
public static bool CarriesQuantity(DocumentLineKind kind) => kind is DocumentLineKind.Item or DocumentLineKind.Free;
|
||||
}
|
||||
|
||||
/// <summary>A quotation (<c>sale_quotations</c>).</summary>
|
||||
public sealed class SaleQuotation : DocumentHeader;
|
||||
|
||||
/// <summary>A line of a quotation.</summary>
|
||||
public sealed class SaleQuotationLine : DocumentLine;
|
||||
|
||||
/// <summary>A customer order (<c>sale_orders</c>).</summary>
|
||||
public sealed class SaleOrder : DocumentHeader;
|
||||
|
||||
/// <summary>A line of a customer order.</summary>
|
||||
public sealed class SaleOrderLine : DocumentLine;
|
||||
|
||||
/// <summary>A delivery note, invoice, credit or debit note, pro forma, fee or self-invoice (<c>sale_documents</c>).</summary>
|
||||
public sealed class SaleDocument : DocumentHeader;
|
||||
|
||||
/// <summary>A line of a sale document.</summary>
|
||||
public sealed class SaleDocumentLine : DocumentLine;
|
||||
|
||||
/// <summary>A supplier order (<c>purchase_orders</c>).</summary>
|
||||
public sealed class PurchaseOrder : DocumentHeader;
|
||||
|
||||
/// <summary>A line of a supplier order.</summary>
|
||||
public sealed class PurchaseOrderLine : DocumentLine;
|
||||
|
||||
/// <summary>A supplier delivery note, invoice or credit note (<c>purchase_documents</c>).</summary>
|
||||
public sealed class PurchaseDocument : DocumentHeader;
|
||||
|
||||
/// <summary>A line of a purchase document.</summary>
|
||||
public sealed class PurchaseDocumentLine : DocumentLine;
|
||||
|
||||
/// <summary>A warehouse entry (<c>inventory_documents</c>).</summary>
|
||||
public sealed class InventoryDocument : DocumentHeader;
|
||||
|
||||
/// <summary>A line of a warehouse entry.</summary>
|
||||
public sealed class InventoryDocumentLine : DocumentLine;
|
||||
|
||||
/// <summary>
|
||||
/// A fulfilment link (<c>document_links</c>): 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).
|
||||
/// </summary>
|
||||
public sealed class DocumentLink : Entity<long>
|
||||
{
|
||||
/// <summary>The family of the fulfilling document.</summary>
|
||||
public DocumentFamily TargetFamily { get; set; }
|
||||
|
||||
/// <summary>The fulfilling document.</summary>
|
||||
public long TargetDocumentId { get; set; }
|
||||
|
||||
/// <summary>The fulfilling line.</summary>
|
||||
public long TargetLineId { get; set; }
|
||||
|
||||
/// <summary>The family of the fulfilled document.</summary>
|
||||
public DocumentFamily SourceFamily { get; set; }
|
||||
|
||||
/// <summary>The fulfilled document.</summary>
|
||||
public long SourceDocumentId { get; set; }
|
||||
|
||||
/// <summary>The fulfilled line.</summary>
|
||||
public long SourceLineId { get; set; }
|
||||
|
||||
/// <summary>The quantity fulfilled.</summary>
|
||||
public decimal Quantity { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
namespace Khaemhat.Core.Documents;
|
||||
|
||||
/// <summary>What the lines of a document say about its fulfilment.</summary>
|
||||
public enum FulfillmentState
|
||||
{
|
||||
/// <summary>Nothing fulfilled.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>Something fulfilled, something left.</summary>
|
||||
Partial = 1,
|
||||
|
||||
/// <summary>Every line fulfilled or closed.</summary>
|
||||
Fulfilled = 2,
|
||||
}
|
||||
|
||||
/// <summary>Line-by-line fulfilment (SPEC §11.3, ADR 0032): quantities from the links, state of the document from the lines.</summary>
|
||||
public static class FulfillmentCalculator
|
||||
{
|
||||
/// <summary>Writes on each line the quantity fulfilled by the links that point to it.</summary>
|
||||
/// <param name="lines">The lines of the fulfilled document.</param>
|
||||
/// <param name="links">The links in force (of confirmed documents) towards those lines.</param>
|
||||
/// <returns>The lines whose quantity changed.</returns>
|
||||
public static IReadOnlyList<DocumentLine> Apply(IEnumerable<DocumentLine> lines, IEnumerable<DocumentLink> 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<DocumentLine>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var fulfilled = byLine.GetValueOrDefault(line.Id);
|
||||
if (line.FulfilledQuantity != fulfilled)
|
||||
{
|
||||
line.FulfilledQuantity = fulfilled;
|
||||
changed.Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>The fulfilment of a document from its lines; lines without quantity do not count.</summary>
|
||||
/// <param name="lines">The lines.</param>
|
||||
/// <returns>The state.</returns>
|
||||
public static FulfillmentState StateOf(IEnumerable<DocumentLine> 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;
|
||||
}
|
||||
}
|
||||
@@ -408,6 +408,9 @@ public sealed class DocumentNumerator : CodedEntity
|
||||
|
||||
/// <summary>Whether gaps are allowed (never for invoices, credit notes and final entries).</summary>
|
||||
public bool GapsAllowed { get; set; }
|
||||
|
||||
/// <summary>The date of the last document numbered: without gaps, no later document may have an earlier date.</summary>
|
||||
public DateOnly? LastDate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A type of document: the links between a document and its numerator, warehouse reason and SDI type.</summary>
|
||||
@@ -416,6 +419,9 @@ public sealed class DocumentType : CodedEntity
|
||||
/// <summary>The family of document.</summary>
|
||||
public NumeratorKind Kind { get; set; }
|
||||
|
||||
/// <summary>What the documents of this type are, which decides how they behave (ADR 0032); empty for types not yet usable.</summary>
|
||||
public Documents.DocumentKind? DocumentKind { get; set; }
|
||||
|
||||
/// <summary>The numerator.</summary>
|
||||
public long? NumeratorId { get; set; }
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>The columns shared by the six document headers (ADR 0032).</summary>
|
||||
/// <typeparam name="T">The header.</typeparam>
|
||||
public abstract class DocumentHeaderMap<T> : EntityMap<T>
|
||||
where T : DocumentHeader, new()
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
/// <param name="table">The table of the family.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The columns shared by the six tables of lines.</summary>
|
||||
/// <typeparam name="T">The line.</typeparam>
|
||||
public abstract class DocumentLineMap<T> : EntityMap<T>
|
||||
where T : DocumentLine, new()
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
/// <param name="table">The table of the lines.</param>
|
||||
protected DocumentLineMap(string table)
|
||||
{
|
||||
ToTable(table);
|
||||
Map(x => x.Description).MaxLength(1000);
|
||||
Map(x => x.DiscountFormula).MaxLength(30);
|
||||
Map(x => x.AccountCode).MaxLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="SaleQuotation"/> to <c>sale_quotations</c>.</summary>
|
||||
public sealed class SaleQuotationMap() : DocumentHeaderMap<SaleQuotation>("sale_quotations");
|
||||
|
||||
/// <summary>Map of <see cref="SaleQuotationLine"/> to <c>sale_quotation_lines</c>.</summary>
|
||||
public sealed class SaleQuotationLineMap() : DocumentLineMap<SaleQuotationLine>("sale_quotation_lines");
|
||||
|
||||
/// <summary>Map of <see cref="SaleOrder"/> to <c>sale_orders</c>.</summary>
|
||||
public sealed class SaleOrderMap() : DocumentHeaderMap<SaleOrder>("sale_orders");
|
||||
|
||||
/// <summary>Map of <see cref="SaleOrderLine"/> to <c>sale_order_lines</c>.</summary>
|
||||
public sealed class SaleOrderLineMap() : DocumentLineMap<SaleOrderLine>("sale_order_lines");
|
||||
|
||||
/// <summary>Map of <see cref="SaleDocument"/> to <c>sale_documents</c>.</summary>
|
||||
public sealed class SaleDocumentMap() : DocumentHeaderMap<SaleDocument>("sale_documents");
|
||||
|
||||
/// <summary>Map of <see cref="SaleDocumentLine"/> to <c>sale_document_lines</c>.</summary>
|
||||
public sealed class SaleDocumentLineMap() : DocumentLineMap<SaleDocumentLine>("sale_document_lines");
|
||||
|
||||
/// <summary>Map of <see cref="PurchaseOrder"/> to <c>purchase_orders</c>.</summary>
|
||||
public sealed class PurchaseOrderMap() : DocumentHeaderMap<PurchaseOrder>("purchase_orders");
|
||||
|
||||
/// <summary>Map of <see cref="PurchaseOrderLine"/> to <c>purchase_order_lines</c>.</summary>
|
||||
public sealed class PurchaseOrderLineMap() : DocumentLineMap<PurchaseOrderLine>("purchase_order_lines");
|
||||
|
||||
/// <summary>Map of <see cref="PurchaseDocument"/> to <c>purchase_documents</c>.</summary>
|
||||
public sealed class PurchaseDocumentMap() : DocumentHeaderMap<PurchaseDocument>("purchase_documents");
|
||||
|
||||
/// <summary>Map of <see cref="PurchaseDocumentLine"/> to <c>purchase_document_lines</c>.</summary>
|
||||
public sealed class PurchaseDocumentLineMap() : DocumentLineMap<PurchaseDocumentLine>("purchase_document_lines");
|
||||
|
||||
/// <summary>Map of <see cref="InventoryDocument"/> to <c>inventory_documents</c>.</summary>
|
||||
public sealed class InventoryDocumentMap() : DocumentHeaderMap<InventoryDocument>("inventory_documents");
|
||||
|
||||
/// <summary>Map of <see cref="InventoryDocumentLine"/> to <c>inventory_document_lines</c>.</summary>
|
||||
public sealed class InventoryDocumentLineMap() : DocumentLineMap<InventoryDocumentLine>("inventory_document_lines");
|
||||
|
||||
/// <summary>Map of <see cref="DocumentLink"/> to <c>document_links</c>.</summary>
|
||||
public sealed class DocumentLinkMap : EntityMap<DocumentLink>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DocumentLinkMap() => ToTable("document_links");
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// The document engine (SPEC §11.3, ADR 0032, issue #47): six families of headers with their lines, the fulfilment
|
||||
/// links, the kind of each document type and the date of the last number of each numerator.
|
||||
/// </summary>
|
||||
[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"),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -221,8 +221,10 @@ public sealed record PaymentTermTemplate(string Code, string Description, string
|
||||
/// <param name="NumeratorCode">The numerator of the base data (<c>FAT</c>, <c>DDT</c>...), if the document is numbered by the company.</param>
|
||||
/// <param name="InventoryReasonCode">The warehouse reason of the base data (<c>SCA</c>, <c>CAR</c>...), if the document moves goods.</param>
|
||||
/// <param name="EInvoiceType">The type of the e-invoice format, if the document is sent electronically.</param>
|
||||
/// <param name="DocumentKind">What the documents are, which decides how they behave (ADR 0032).</param>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes
|
||||
|
||||
@@ -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
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<DocumentTypeTemplate> 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),
|
||||
];
|
||||
}
|
||||
@@ -148,6 +148,11 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
|
||||
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
|
||||
|
||||
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
|
||||
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
|
||||
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
|
||||
services.AddSingleton(typeof(Khaemhat.Application.Documents.DocumentService<,>));
|
||||
|
||||
// Guided import and export (ADR 0031): the entities in the order of the screen.
|
||||
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget>(sp => ActivatorUtilities.CreateInstance<Khaemhat.Application.ImportExport.PartiesImportTarget>(
|
||||
sp, Khaemhat.Core.Parties.PartyKind.Customer));
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
},
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Documents;
|
||||
|
||||
/// <summary>The declarative rules of the document engine (issue #47): behaviours, states, fulfilment.</summary>
|
||||
[TestClass]
|
||||
public sealed class DocumentRulesTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void EveryKind_HasABehaviour_AndFulfilsOnlyKindsOfTheSameDirection()
|
||||
{
|
||||
Assert.HasCount(Enum.GetValues<DocumentKind>().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<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Cancel));
|
||||
Assert.AreEqual(DocumentAction.Cancel, refused.Action);
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Delete));
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Issue));
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Cancelled, DocumentAction.Reopen));
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => 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<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(DocumentLifecycle.Simple, DocumentStatus.Confirmed, DocumentAction.Close));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Fulfilment_SumsTheLinks_AndClosedLinesCountAsFulfilled()
|
||||
{
|
||||
var lines = new List<DocumentLine>
|
||||
{
|
||||
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 };
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Document numbering on both engines (issue #47): concurrent confirmations never share a number.</summary>
|
||||
[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<long>().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<DocumentNumerator, long>().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<ValidationFailedException>(() => 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<DocumentNumerator, long>().ListAsync(Query.For<DocumentNumerator>().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<long> NumeratorAsync(TestDatabase db)
|
||||
{
|
||||
await new MigrationRunner(db.Context).RunAsync(db.Target, MigrationCatalog.ForCompany());
|
||||
await using var setup = await db.OpenAsync();
|
||||
return await setup.Repository<DocumentNumerator, long>().InsertAsync(new DocumentNumerator
|
||||
{
|
||||
Code = "FAT",
|
||||
Description = "Fatture",
|
||||
Kind = NumeratorKind.SalesInvoice,
|
||||
Year = 2026,
|
||||
Prefix = "FV",
|
||||
Format = "{prefix}-{year}/{number:D4}",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@
|
||||
<ProjectReference Include="../../src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" />
|
||||
<ProjectReference Include="../../src/Khaemhat.Data.PostgreSql/Khaemhat.Data.PostgreSql.csproj" />
|
||||
<ProjectReference Include="../../src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj" />
|
||||
<!-- The document numbering (issue #47) runs against both engines here, the only tests the tag CI runs on PostgreSQL. -->
|
||||
<ProjectReference Include="../../src/Khaemhat.Application/Khaemhat.Application.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>The document engine on a real instance (issue #47): definitions, numbering, states, copies and fulfilment.</summary>
|
||||
[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<DocumentService<SaleOrder, SaleOrderLine>>();
|
||||
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
|
||||
var copies = app.Services.GetRequiredService<DocumentCopyService>();
|
||||
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<ValidationFailedException>(() => orders.SaveAsync(Root, company, order));
|
||||
Assert.AreEqual("Lines.0.Quantity:" + DocumentErrors.LineBelowFulfilled, below.Errors.Single());
|
||||
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => 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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<InvalidDocumentActionException>(() => sales.SaveAsync(Root, company, invoice));
|
||||
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.DeleteAsync(Root, company, invoice.Header.Id));
|
||||
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.CancelAsync(Root, company, first.Header.Id, null), "Fulfilled by the invoice.");
|
||||
|
||||
var reason = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => 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<DocumentEngine>();
|
||||
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
|
||||
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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<IUnitOfWorkFactory>();
|
||||
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<TableService>();
|
||||
var noKind = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
|
||||
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<DocumentKind>().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<DocumentRecord<SaleDocument, SaleDocumentLine>> NewInvoiceAsync(
|
||||
DocumentService<SaleDocument, SaleDocumentLine> 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<DocumentRecord<SaleDocument, SaleDocumentLine>> InvoiceAsync(
|
||||
DocumentService<SaleDocument, SaleDocumentLine> sales, string company, long customer, DateOnly date) =>
|
||||
await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, date));
|
||||
|
||||
private static DocumentRecord<SaleDocument, SaleDocumentLine> Typed(DocumentRecord record) =>
|
||||
new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast<SaleDocumentLine>()] };
|
||||
|
||||
private static async Task<long> CustomerAsync(WebApplication app, string company)
|
||||
{
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user