diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md
index eaf4f5d..b457e27 100644
--- a/docs/DATA-MODEL.md
+++ b/docs/DATA-MODEL.md
@@ -721,6 +721,11 @@ Migrazioni applicate in ordine:
- `core` 20261111007 `create_attachments` (M20261111_007_CreateAttachments)
- `core` 20261111008 `create_company_settings` (M20261111_008_CreateCompanySettings)
- `core` 20261111009 `create_notification_reads` (M20261111_009_CreateNotificationReads)
+- `core` 20261111010 `create_company_profile` (M20261111_010_CreateCompanyProfile)
+- `core` 20261111011 `create_geography_and_currencies` (M20261111_011_CreateGeographyAndCurrencies)
+- `core` 20261111012 `create_tax_and_payment_tables` (M20261111_012_CreateTaxAndPaymentTables)
+- `core` 20261111013 `create_logistics_tables` (M20261111_013_CreateLogisticsTables)
+- `core` 20261111014 `create_catalog_tables` (M20261111_014_CreateCatalogTables)
#### `attachments`
@@ -767,6 +772,98 @@ Migrazioni applicate in ordine:
- indice `ix_audit_log_at` su `at`
- indice `ix_audit_log_entity_entity_id` su `entity`, `entity_id`
+#### `bank_accounts`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `bank_name` | String(100) | sì | | |
+| `iban` | String(34) | sì | | |
+| `bic` | String(11) | sì | | |
+| `sia_code` | String(5) | sì | | |
+| `cuc_code` | String(8) | sì | | |
+| `account_code` | String(20) | sì | | |
+| `is_default` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_bank_accounts_code` su `code`
+
+#### `carriers`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `vat_number` | String(28) | sì | | |
+| `address` | String(200) | sì | | |
+| `city` | String(100) | sì | | |
+| `phone` | String(30) | sì | | |
+| `email` | String(254) | sì | | |
+| `register_number` | String(30) | sì | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_carriers_code` su `code`
+
+#### `company_profile`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `legal_name` | String(200) | no | | |
+| `fiscal_name` | String(200) | sì | | |
+| `vat_number` | String(28) | sì | | |
+| `tax_code` | String(16) | sì | | |
+| `rea_office` | String(2) | sì | | |
+| `rea_number` | String(20) | sì | | |
+| `share_capital` | Decimal(19,6) | sì | | |
+| `shareholders` | String(2) | sì | | |
+| `liquidation_status` | String(2) | sì | | |
+| `address` | String(200) | sì | | |
+| `street_number` | String(8) | sì | | |
+| `postal_code` | String(10) | sì | | |
+| `city` | String(100) | sì | | |
+| `province_code` | String(2) | sì | | |
+| `address_country` | String(2) | sì | | |
+| `phone` | String(30) | sì | | |
+| `email` | String(254) | sì | | |
+| `pec` | String(254) | sì | | |
+| `website` | String(200) | sì | | |
+| `tax_regime` | String(4) | no | | |
+| `recipient_code` | String(7) | sì | | |
+| `logo_attachment_id` | Int64 | sì | | |
+| `default_bank_account_id` | Int64 | sì | | |
+| `currency_code` | String(3) | no | | |
+| `country` | String(2) | no | | |
+| `vat_periodicity` | String(40) | no | | |
+| `pro_rata_percent` | Decimal(19,6) | no | | |
+| `cash_vat` | Bool | no | `false` | |
+| `fiscal_year_start_month` | Int32 | no | | |
+| `transmitter_country` | String(2) | sì | | |
+| `transmitter_id` | String(28) | sì | | |
+| `intermediary_name` | String(200) | sì | | |
+| `intermediary_tax_code` | String(16) | sì | | |
+| `footer_notes` | Text | sì | | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
#### `company_settings`
| Colonna | Tipo | Null | Default | Note |
@@ -782,6 +879,304 @@ Migrazioni applicate in ordine:
- indice unico `ux_company_settings_key` su `key`
+#### `cost_centers`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(20) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `parent_id` | Int64 | sì | | -> `cost_centers` (Restrict) |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_cost_centers_code` su `code`
+
+#### `countries`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(2) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `iso3` | String(3) | sì | | |
+| `eu_member` | Bool | no | `false` | |
+| `vat_prefix` | String(2) | sì | | |
+| `currency_code` | String(3) | sì | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_countries_code` su `code`
+
+#### `currencies`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(3) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `symbol` | String(5) | sì | | |
+| `decimals` | Int32 | no | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_currencies_code` su `code`
+
+#### `delivery_terms`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_delivery_terms_code` su `code`
+
+#### `discount_policies`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `formula` | String(60) | no | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_discount_policies_code` su `code`
+
+#### `document_numerators`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `kind` | String(40) | no | | |
+| `section` | String(10) | sì | | |
+| `year` | Int32 | no | | |
+| `prefix` | String(10) | sì | | |
+| `format` | String(60) | no | | |
+| `last_number` | Int64 | no | | |
+| `gaps_allowed` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_document_numerators_code_year` su `code`, `year`
+
+#### `document_types`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `kind` | String(40) | no | | |
+| `numerator_id` | Int64 | sì | | |
+| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) |
+| `e_invoice_type` | String(4) | sì | | |
+| `journal_template_code` | String(10) | sì | | |
+| `vat_register_code` | String(10) | sì | | |
+| `print_template` | String(60) | sì | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_document_types_code` su `code`
+
+#### `exchange_rates`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `currency_code` | String(3) | no | | |
+| `rate_date` | Date | no | | |
+| `rate` | Decimal(19,6) | no | | |
+| `source` | String(10) | 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 unico `ux_exchange_rates_currency_code_rate_date` su `currency_code`, `rate_date`
+
+#### `fiscal_periods`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `fiscal_year_id` | Int64 | no | | -> `fiscal_years` (Cascade) |
+| `number` | Int32 | no | | |
+| `start_date` | Date | no | | |
+| `end_date` | Date | no | | |
+| `status` | String(40) | 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_fiscal_periods_start_date` su `start_date`
+- indice unico `ux_fiscal_periods_fiscal_year_id_number` su `fiscal_year_id`, `number`
+
+#### `fiscal_years`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `start_date` | Date | no | | |
+| `end_date` | Date | no | | |
+| `status` | String(40) | no | | |
+| `journal_first_page` | Int32 | no | | |
+| `last_final_entry_number` | Int64 | no | | |
+| `last_final_entry_date` | Date | sì | | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_fiscal_years_code` su `code`
+- indice unico `ux_fiscal_years_start_date` su `start_date`
+
+#### `goods_appearances`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_goods_appearances_code` su `code`
+
+#### `inventory_reasons`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `effect` | String(40) | no | | |
+| `affects_value` | Bool | no | `false` | |
+| `is_transfer` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_inventory_reasons_code` su `code`
+
+#### `item_categories`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(20) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `parent_id` | Int64 | sì | | -> `item_categories` (Restrict) |
+| `level` | Int32 | no | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_item_categories_code` su `code`
+
+#### `jobs`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(20) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `party_id` | Int64 | sì | | |
+| `start_date` | Date | sì | | |
+| `end_date` | Date | sì | | |
+| `status` | String(40) | no | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_jobs_code` su `code`
+
+#### `municipalities`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(4) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `province_code` | String(2) | no | | |
+| `region` | String(60) | sì | | |
+| `istat_code` | String(6) | sì | | |
+| `postal_codes` | String(400) | 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_municipalities_description` su `description`
+- indice `ix_municipalities_province_code` su `province_code`
+- indice unico `ux_municipalities_code` su `code`
+
#### `notification_reads`
| Colonna | Tipo | Null | Default | Note |
@@ -818,6 +1213,123 @@ Migrazioni applicate in ordine:
- indice `ix_notifications_recipient_user_id` su `recipient_user_id`
+#### `party_categories`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_party_categories_code` su `code`
+
+#### `payment_methods`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `e_invoice_code` | String(4) | no | | |
+| `needs_bank` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_payment_methods_code` su `code`
+
+#### `payment_term_lines`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `payment_term_id` | Int64 | no | | -> `payment_terms` (Cascade) |
+| `number` | Int32 | no | | |
+| `days` | Int32 | no | | |
+| `end_of_month` | Bool | no | `false` | |
+| `fixed_day` | Int32 | sì | | |
+| `percent` | 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 unico `ux_payment_term_lines_payment_term_id_number` su `payment_term_id`, `number`
+
+#### `payment_terms`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) |
+| `condition` | String(4) | no | | |
+| `vat_on_first_installment` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_payment_terms_code` su `code`
+
+#### `price_lists`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `currency_code` | String(3) | no | | |
+| `vat_included` | Bool | no | `false` | |
+| `valid_from` | Date | sì | | |
+| `valid_to` | Date | sì | | |
+| `base_price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
+| `markup_percent` | Decimal(19,6) | no | | |
+| `rounding_step` | Decimal(19,6) | no | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_price_lists_code` su `code`
+
+#### `provinces`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(2) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `region` | String(60) | sì | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_provinces_code` su `code`
+
#### `role_permissions`
| Colonna | Tipo | Null | Default | Note |
@@ -851,6 +1363,27 @@ Migrazioni applicate in ordine:
- indice unico `ux_roles_code` su `code`
+#### `salespeople`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `email` | String(254) | sì | | |
+| `phone` | String(30) | sì | | |
+| `commission_percent` | Decimal(19,6) | no | | |
+| `enasarco` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_salespeople_code` su `code`
+
#### `schema_version`
| Colonna | Tipo | Null | Default | Note |
@@ -863,6 +1396,103 @@ Migrazioni applicate in ordine:
Chiave primaria: `module`, `version`.
+#### `shipping_terms`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_shipping_terms_code` su `code`
+
+#### `tax_codes`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `rate` | Decimal(19,6) | no | | |
+| `nature` | String(5) | sì | | |
+| `kind` | String(40) | no | | |
+| `exigibility` | String(40) | no | | |
+| `non_deductible_percent` | Decimal(19,6) | no | | |
+| `legal_reference` | String(200) | sì | | |
+| `valid_from` | Date | sì | | |
+| `valid_to` | Date | sì | | |
+| `sales_account_code` | String(20) | sì | | |
+| `purchase_account_code` | String(20) | sì | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_tax_codes_code` su `code`
+
+#### `transport_means`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_transport_means_code` su `code`
+
+#### `transport_reasons`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_transport_reasons_code` su `code`
+
+#### `units_of_measure`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `decimals` | Int32 | no | | |
+| `e_invoice_code` | String(10) | sì | | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_units_of_measure_code` su `code`
+
#### `user_permission_overrides`
| Colonna | Tipo | Null | Default | Note |
@@ -972,4 +1602,25 @@ Chiave primaria: `module`, `version`.
- indice unico `ux_users_user_name` su `user_name`
+#### `warehouses`
+
+| Colonna | Tipo | Null | Default | Note |
+|---|---|---|---|---|
+| `id` | Int64 | no | | chiave primaria, identity |
+| `code` | String(10) | no | | |
+| `description` | String(100) | no | | |
+| `disabled` | Bool | no | `false` | |
+| `address` | String(200) | sì | | |
+| `city` | String(100) | sì | | |
+| `province_code` | String(2) | sì | | |
+| `is_default` | Bool | no | `false` | |
+| `is_demo` | Bool | no | `false` | |
+| `created_at` | DateTimeUtc | no | | |
+| `created_by` | String(100) | sì | | |
+| `updated_at` | DateTimeUtc | sì | | |
+| `updated_by` | String(100) | sì | | |
+| `row_version` | Int64 | no | `1` | |
+
+- indice unico `ux_warehouses_code` su `code`
+
diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs
index dd428a0..ab6a824 100644
--- a/src/Khaemhat.Application/Jobs/JobScheduler.cs
+++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs
@@ -39,7 +39,8 @@ public interface IScheduledJob
/// The job type.
/// When it runs.
/// Its timeout.
-public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600);
+/// Whether it calls services outside the instance (the tests run it with a stub).
+public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600, bool UsesNetwork = false);
///
/// The scheduler (SPEC §9.4; mockup 083): reads sys_scheduled_tasks, runs the due ones with a lock in
@@ -49,13 +50,14 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
///
public sealed class JobScheduler
{
- /// The system tasks (M2, attachments trash from M3).
+ /// The system tasks (M2, attachments trash from M3, ECB rates from M4).
public static readonly IReadOnlyList SystemTasks =
[
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120),
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
+ new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
];
private readonly IUnitOfWorkFactory _factory;
diff --git a/src/Khaemhat.Application/Khaemhat.Application.csproj b/src/Khaemhat.Application/Khaemhat.Application.csproj
index c5adc45..060cc02 100644
--- a/src/Khaemhat.Application/Khaemhat.Application.csproj
+++ b/src/Khaemhat.Application/Khaemhat.Application.csproj
@@ -9,6 +9,11 @@
+
+
+
+
+
diff --git a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs
new file mode 100644
index 0000000..34f8252
--- /dev/null
+++ b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs
@@ -0,0 +1,246 @@
+using Khaemhat.Application.Modules;
+using Khaemhat.Application.Tables;
+using Khaemhat.Core.Tables;
+using Khaemhat.Data.Querying;
+using Khaemhat.Fiscal.Abstractions;
+using Khaemhat.Infrastructure.Files;
+
+namespace Khaemhat.Application.Seeding;
+
+///
+/// The base tables of SPEC §14 available from M4: countries, currencies, units, VAT codes (from the fiscal pack),
+/// payment methods and terms and document types (from the pack's ), transport tables,
+/// warehouse reasons, the main warehouse, categories, the base price list, the numerators and the fiscal year of the
+/// current year. Provinces, municipalities and banks come from datasets loaded separately (ADR 0026).
+///
+/// Creates the current fiscal year.
+public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
+{
+ /// The currencies of the ECB reference rates, plus the euro: code, name, symbol, decimals.
+ public static readonly IReadOnlyList<(string Code, string Name, string Symbol, int Decimals)> Currencies =
+ [
+ ("EUR", "Euro", "€", 2), ("USD", "Dollaro statunitense", "$", 2), ("GBP", "Sterlina britannica", "£", 2), ("CHF", "Franco svizzero", "CHF", 2),
+ ("JPY", "Yen giapponese", "¥", 0), ("CZK", "Corona ceca", "Kč", 2), ("DKK", "Corona danese", "kr", 2), ("HUF", "Fiorino ungherese", "Ft", 2),
+ ("PLN", "Zloty polacco", "zł", 2), ("RON", "Leu rumeno", "lei", 2), ("SEK", "Corona svedese", "kr", 2), ("ISK", "Corona islandese", "kr", 0),
+ ("NOK", "Corona norvegese", "kr", 2), ("TRY", "Lira turca", "₺", 2), ("AUD", "Dollaro australiano", "A$", 2), ("BRL", "Real brasiliano", "R$", 2),
+ ("CAD", "Dollaro canadese", "C$", 2), ("CNY", "Renminbi cinese", "¥", 2), ("HKD", "Dollaro di Hong Kong", "HK$", 2), ("IDR", "Rupia indonesiana", "Rp", 2),
+ ("ILS", "Nuovo siclo israeliano", "₪", 2), ("INR", "Rupia indiana", "₹", 2), ("KRW", "Won sudcoreano", "₩", 0), ("MXN", "Peso messicano", "Mex$", 2),
+ ("MYR", "Ringgit malese", "RM", 2), ("NZD", "Dollaro neozelandese", "NZ$", 2), ("PHP", "Peso filippino", "₱", 2), ("SGD", "Dollaro di Singapore", "S$", 2),
+ ("THB", "Baht thailandese", "฿", 2), ("ZAR", "Rand sudafricano", "R", 2),
+ ];
+
+ /// The numerators of the base data: code, description, family, section, format, gaps allowed.
+ public static readonly IReadOnlyList<(string Code, string Description, NumeratorKind Kind, string? Section, string Format, bool Gaps)> Numerators =
+ [
+ ("PRE", "Preventivi", NumeratorKind.Quotation, null, "PRE-{year}-{number:D4}", true),
+ ("ORD", "Ordini clienti", NumeratorKind.SalesOrder, null, "OC-{year}-{number:D4}", true),
+ ("DDT", "Documenti di trasporto", NumeratorKind.DeliveryNote, null, "{number}/{year}", true),
+ ("FAT", "Fatture e note di credito", NumeratorKind.SalesInvoice, null, "{number}/{year}", false),
+ ("AUT", "Autofatture e integrazioni", NumeratorKind.SalesInvoice, "AF", "{number}/AF/{year}", false),
+ ("PRF", "Pro forma", NumeratorKind.Other, null, "PF-{year}-{number:D4}", true),
+ ("ORF", "Ordini fornitori", NumeratorKind.PurchaseOrder, null, "OF-{year}-{number:D4}", true),
+ ("PRA", "Protocollo acquisti", NumeratorKind.PurchaseInvoice, null, "{number}", false),
+ ("MAG", "Movimenti di magazzino", NumeratorKind.Inventory, null, "MM-{year}-{number:D5}", true),
+ ("PN", "Registrazioni contabili", NumeratorKind.Journal, null, "{number}", false),
+ ];
+
+ ///
+ public string ModuleCode => ModuleCodes.Core;
+
+ ///
+ public SeedKind Kind => SeedKind.Base;
+
+ ///
+ public int Order => 0;
+
+ ///
+ public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ await context.EnsureAsync("countries", ReadCountries(), cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("currencies", Currencies.Select(c => new Currency { Code = c.Code, Description = c.Name, Symbol = c.Symbol, Decimals = c.Decimals }), cancellationToken)
+ .ConfigureAwait(false);
+ await context.EnsureAsync("units_of_measure", Units(), cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("tax_codes", TaxCodes(context.Pack), cancellationToken).ConfigureAwait(false);
+
+ var reasons = await context.EnsureAsync("inventory_reasons", InventoryReasons(), cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("warehouses", [new Warehouse { Code = "SEDE", Description = "Magazzino sede", IsDefault = true }], cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("shipping_terms", Coded(("FRANCO", "Porto franco"), ("ASSEGNATO", "Porto assegnato"), ("ADDEBITO", "Franco con addebito in fattura")), cancellationToken)
+ .ConfigureAwait(false);
+ await context.EnsureAsync("transport_means", Coded(("MITT", "Mittente"), ("DEST", "Destinatario"), ("VETT", "Vettore")), cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync(
+ "goods_appearances",
+ Coded(("CARTONI", "Cartoni"), ("SCATOLE", "Scatole"), ("BANCALI", "Bancali"), ("COLLI", "Colli"), ("BUSTE", "Buste"), ("SFUSO", "Sfuso"), ("VISTA", "A vista")),
+ cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("delivery_terms", Incoterms(), cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync(
+ "transport_reasons",
+ Coded(
+ ("VEN", "Vendita"), ("CV", "Conto visione"), ("CD", "Conto deposito"), ("CL", "Conto lavorazione"), ("RES", "Reso"), ("RIP", "Riparazione"),
+ ("OMA", "Omaggio"), ("TRA", "Trasferimento tra depositi")),
+ cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("item_categories", [new ItemCategory { Code = "GEN", Description = "Generica" }], cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("party_categories", Coded(("GEN", "Generica")), cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base" }], cancellationToken).ConfigureAwait(false);
+
+ var year = context.Today.Year;
+ var numerators = new Dictionary(StringComparer.Ordinal);
+ foreach (var n in Numerators)
+ {
+ numerators[n.Code] = await context.EnsureOneAsync(
+ "document_numerators",
+ x => x.Code == n.Code && x.Year == year,
+ new DocumentNumerator { Code = n.Code, Description = n.Description, Kind = n.Kind, Section = n.Section, Year = year, Format = n.Format, GapsAllowed = n.Gaps },
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ if (context.Pack.GetFeature() is { } template)
+ {
+ await SeedPaymentsAsync(context, template, cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync(
+ "document_types",
+ template.DocumentTypes.Select(d => new DocumentType
+ {
+ Code = d.Code,
+ Description = d.Description,
+ Kind = d.Kind,
+ 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,
+ }),
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ var calendar = await context.UnitOfWork.Repository()
+ .CountAsync(Query.For().Where(y => y.StartDate <= context.Today && y.EndDate >= context.Today), cancellationToken).ConfigureAwait(false);
+ if (calendar == 0 && await context.UnitOfWork.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0)
+ {
+ await years.CreateAsync(context.UnitOfWork, context.Today, "system", cancellationToken).ConfigureAwait(false);
+ context.Count("fiscal_years");
+ }
+ }
+
+ /// The countries of the embedded list (ISO 3166-1, Italian names, EU members, currency).
+ /// The rows.
+ public static IReadOnlyList ReadCountries()
+ {
+ using var stream = typeof(BaseTablesSeeder).Assembly.GetManifestResourceStream("Khaemhat.Application.Seeding.Data.countries.csv")
+ ?? throw new InvalidOperationException("The country list is missing from the assembly.");
+ using var reader = new StreamReader(stream);
+ var lines = CsvReader.Parse(reader.ReadToEnd(), ';');
+ return
+ [
+ .. lines.Skip(1).Select(l => new Country
+ {
+ Code = l[0],
+ Iso3 = l[1].Length == 0 ? null : l[1],
+ Description = l[2],
+ EuMember = l[3] == "1",
+ CurrencyCode = l[4].Length == 0 ? null : l[4],
+
+ // Greece uses EL in VAT numbers and VIES.
+ VatPrefix = l[0] == "GR" ? "EL" : null,
+ }),
+ ];
+ }
+
+ private static async Task SeedPaymentsAsync(SeedContext context, IBaseTablesTemplate template, CancellationToken cancellationToken)
+ {
+ var methods = await context.EnsureAsync(
+ "payment_methods",
+ template.PaymentMethods.Select(m => new PaymentMethod { Code = m.Code, Description = m.Description, EInvoiceCode = m.EInvoiceCode, NeedsBank = m.NeedsBank }),
+ cancellationToken).ConfigureAwait(false);
+ var existing = (await context.UnitOfWork.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items
+ .Select(t => t.Code)
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var lines = context.UnitOfWork.Repository();
+ foreach (var t in template.PaymentTerms.Where(t => !existing.Contains(t.Code)))
+ {
+ var terms = await context.EnsureOneAsync(
+ "payment_terms",
+ x => x.Code == t.Code,
+ new PaymentTerm
+ {
+ Code = t.Code,
+ Description = t.Description,
+ Condition = t.Condition,
+ PaymentMethodId = methods.TryGetValue(t.PaymentMethodCode, out var method) ? method.Id : null,
+ },
+ cancellationToken).ConfigureAwait(false);
+ var number = 1;
+ foreach (var i in t.Installments)
+ {
+ await lines.InsertAsync(new PaymentTermLine { PaymentTermId = terms.Id, Number = number++, Days = i.Days, EndOfMonth = i.EndOfMonth, Percent = i.Percent }, cancellationToken)
+ .ConfigureAwait(false);
+ }
+ }
+ }
+
+ private static IEnumerable TaxCodes(IFiscalPack pack) =>
+ pack.TaxCodes.BaseCodes.Select(c => new TaxCode
+ {
+ Code = c.Code,
+ Description = c.Description,
+ Rate = c.Rate,
+ Nature = c.Nature,
+ Exigibility = c.Exigibility,
+ NonDeductiblePercent = c.NonDeductiblePercent,
+ LegalReference = c.LegalReference,
+ Kind = pack.TaxCodes.KindOf(c.Rate, c.Nature),
+ });
+
+ private static IEnumerable Units() =>
+ [
+ new() { Code = "NR", Description = "Numero", Decimals = 0 },
+ new() { Code = "PZ", Description = "Pezzi", Decimals = 0 },
+ new() { Code = "CF", Description = "Confezioni", Decimals = 0 },
+ new() { Code = "CT", Description = "Cartoni", Decimals = 0 },
+ new() { Code = "PAL", Description = "Pallet", Decimals = 0 },
+ new() { Code = "KG", Description = "Chilogrammi", Decimals = 3 },
+ new() { Code = "G", Description = "Grammi", Decimals = 0 },
+ new() { Code = "T", Description = "Tonnellate", Decimals = 3 },
+ new() { Code = "L", Description = "Litri", Decimals = 3 },
+ new() { Code = "M", Description = "Metri", Decimals = 3 },
+ new() { Code = "M2", Description = "Metri quadrati", Decimals = 3 },
+ new() { Code = "M3", Description = "Metri cubi", Decimals = 3 },
+ new() { Code = "KM", Description = "Chilometri", Decimals = 2 },
+ new() { Code = "KWH", Description = "Kilowattora", Decimals = 3 },
+ new() { Code = "ORE", Description = "Ore", Decimals = 2 },
+ new() { Code = "GG", Description = "Giorni", Decimals = 2 },
+ new() { Code = "MESI", Description = "Mesi", Decimals = 0 },
+ new() { Code = "SERV", Description = "Servizio", Decimals = 0 },
+ ];
+
+ private static IEnumerable InventoryReasons() =>
+ [
+ new() { Code = "CAR", Description = "Carico da acquisto", Effect = StockEffect.Load },
+ new() { Code = "SCA", Description = "Scarico per vendita", Effect = StockEffect.Unload },
+ new() { Code = "RESC", Description = "Reso da cliente", Effect = StockEffect.Load },
+ new() { Code = "RESF", Description = "Reso a fornitore", Effect = StockEffect.Unload },
+ new() { Code = "TRA", Description = "Trasferimento tra depositi", Effect = StockEffect.None, AffectsValue = false, IsTransfer = true },
+ new() { Code = "INVP", Description = "Rettifica inventariale in aumento", Effect = StockEffect.Load },
+ new() { Code = "INVN", Description = "Rettifica inventariale in diminuzione", Effect = StockEffect.Unload },
+ new() { Code = "CVU", Description = "Uscita in conto visione", Effect = StockEffect.Unload, AffectsValue = false },
+ new() { Code = "CVR", Description = "Rientro da conto visione", Effect = StockEffect.Load, AffectsValue = false },
+ new() { Code = "OMA", Description = "Omaggio", Effect = StockEffect.Unload },
+ new() { Code = "AUTO", Description = "Autoconsumo", Effect = StockEffect.Unload },
+ new() { Code = "APE", Description = "Esistenza iniziale", Effect = StockEffect.Load },
+ ];
+
+ private static IEnumerable Incoterms() => Coded(
+ ("EXW", "Franco fabbrica (Ex Works)"),
+ ("FCA", "Franco vettore (Free Carrier)"),
+ ("CPT", "Trasporto pagato fino a (Carriage Paid To)"),
+ ("CIP", "Trasporto e assicurazione pagati fino a (Carriage and Insurance Paid To)"),
+ ("DAP", "Reso al luogo di destinazione (Delivered at Place)"),
+ ("DPU", "Reso al luogo di destinazione scaricato (Delivered at Place Unloaded)"),
+ ("DDP", "Reso sdoganato (Delivered Duty Paid)"),
+ ("FAS", "Franco lungo bordo (Free Alongside Ship)"),
+ ("FOB", "Franco a bordo (Free On Board)"),
+ ("CFR", "Costo e nolo (Cost and Freight)"),
+ ("CIF", "Costo, assicurazione e nolo (Cost, Insurance and Freight)"));
+
+ private static IEnumerable Coded(params (string Code, string Description)[] rows)
+ where T : CodedEntity, new() =>
+ rows.Select(r => new T { Code = r.Code, Description = r.Description });
+}
diff --git a/src/Khaemhat.Application/Seeding/Data/countries.csv b/src/Khaemhat.Application/Seeding/Data/countries.csv
new file mode 100644
index 0000000..69f4342
--- /dev/null
+++ b/src/Khaemhat.Application/Seeding/Data/countries.csv
@@ -0,0 +1,252 @@
+code;iso3;name;eu;currency
+AD;AND;Andorra;0;EUR
+AE;ARE;Emirati Arabi Uniti;0;AED
+AF;AFG;Afghanistan;0;AFN
+AG;ATG;Antigua e Barbuda;0;XCD
+AI;AIA;Anguilla;0;XCD
+AL;ALB;Albania;0;ALL
+AM;ARM;Armenia;0;AMD
+AO;AGO;Angola;0;AOA
+AQ;ATA;Antartide;0;
+AR;ARG;Argentina;0;ARS
+AS;ASM;Samoa americane;0;USD
+AT;AUT;Austria;1;EUR
+AU;AUS;Australia;0;AUD
+AW;ABW;Aruba;0;AWG
+AX;ALA;Isole Åland;0;EUR
+AZ;AZE;Azerbaigian;0;AZN
+BA;BIH;Bosnia ed Erzegovina;0;BAM
+BB;BRB;Barbados;0;BBD
+BD;BGD;Bangladesh;0;BDT
+BE;BEL;Belgio;1;EUR
+BF;BFA;Burkina Faso;0;XOF
+BG;BGR;Bulgaria;1;EUR
+BH;BHR;Bahrein;0;BHD
+BI;BDI;Burundi;0;BIF
+BJ;BEN;Benin;0;XOF
+BL;BLM;Saint-Barthélemy;0;EUR
+BM;BMU;Bermuda;0;BMD
+BN;BRN;Brunei;0;BND
+BO;BOL;Bolivia;0;BOB
+BQ;BES;Caraibi olandesi;0;USD
+BR;BRA;Brasile;0;BRL
+BS;BHS;Bahamas;0;BSD
+BT;BTN;Bhutan;0;BTN
+BV;BVT;Isola Bouvet;0;NOK
+BW;BWA;Botswana;0;BWP
+BY;BLR;Bielorussia;0;BYN
+BZ;BLZ;Belize;0;BZD
+CA;CAN;Canada;0;CAD
+CC;CCK;Isole Cocos (Keeling);0;AUD
+CD;COD;Repubblica Democratica del Congo;0;CDF
+CF;CAF;Repubblica Centrafricana;0;XAF
+CG;COG;Repubblica del Congo;0;XAF
+CH;CHE;Svizzera;0;CHF
+CI;CIV;Costa d'Avorio;0;XOF
+CK;COK;Isole Cook;0;NZD
+CL;CHL;Cile;0;CLP
+CM;CMR;Camerun;0;XAF
+CN;CHN;Cina;0;CNY
+CO;COL;Colombia;0;COP
+CR;CRI;Costa Rica;0;CRC
+CU;CUB;Cuba;0;CUP
+CV;CPV;Capo Verde;0;CVE
+CW;CUW;Curaçao;0;XCG
+CX;CXR;Isola di Natale;0;AUD
+CY;CYP;Cipro;1;EUR
+CZ;CZE;Cechia;1;CZK
+DE;DEU;Germania;1;EUR
+DJ;DJI;Gibuti;0;DJF
+DK;DNK;Danimarca;1;DKK
+DM;DMA;Dominica;0;XCD
+DO;DOM;Repubblica Dominicana;0;DOP
+DZ;DZA;Algeria;0;DZD
+EC;ECU;Ecuador;0;USD
+EE;EST;Estonia;1;EUR
+EG;EGY;Egitto;0;EGP
+EH;ESH;Sahara Occidentale;0;MAD
+ER;ERI;Eritrea;0;ERN
+ES;ESP;Spagna;1;EUR
+ET;ETH;Etiopia;0;ETB
+FI;FIN;Finlandia;1;EUR
+FJ;FJI;Figi;0;FJD
+FK;FLK;Isole Falkland;0;FKP
+FM;FSM;Micronesia;0;USD
+FO;FRO;Isole Fær Øer;0;DKK
+FR;FRA;Francia;1;EUR
+GA;GAB;Gabon;0;XAF
+GB;GBR;Regno Unito;0;GBP
+GD;GRD;Grenada;0;XCD
+GE;GEO;Georgia;0;GEL
+GF;GUF;Guyana francese;0;EUR
+GG;GGY;Guernsey;0;GBP
+GH;GHA;Ghana;0;GHS
+GI;GIB;Gibilterra;0;GIP
+GL;GRL;Groenlandia;0;DKK
+GM;GMB;Gambia;0;GMD
+GN;GIN;Guinea;0;GNF
+GP;GLP;Guadalupa;0;EUR
+GQ;GNQ;Guinea Equatoriale;0;XAF
+GR;GRC;Grecia;1;EUR
+GS;SGS;Georgia del Sud e isole Sandwich australi;0;GBP
+GT;GTM;Guatemala;0;GTQ
+GU;GUM;Guam;0;USD
+GW;GNB;Guinea-Bissau;0;XOF
+GY;GUY;Guyana;0;GYD
+HK;HKG;Hong Kong;0;HKD
+HM;HMD;Isole Heard e McDonald;0;AUD
+HN;HND;Honduras;0;HNL
+HR;HRV;Croazia;1;EUR
+HT;HTI;Haiti;0;HTG
+HU;HUN;Ungheria;1;HUF
+ID;IDN;Indonesia;0;IDR
+IE;IRL;Irlanda;1;EUR
+IL;ISR;Israele;0;ILS
+IM;IMN;Isola di Man;0;GBP
+IN;IND;India;0;INR
+IO;IOT;Territorio britannico dell'Oceano Indiano;0;USD
+IQ;IRQ;Iraq;0;IQD
+IR;IRN;Iran;0;IRR
+IS;ISL;Islanda;0;ISK
+IT;ITA;Italia;1;EUR
+JE;JEY;Jersey;0;GBP
+JM;JAM;Giamaica;0;JMD
+JO;JOR;Giordania;0;JOD
+JP;JPN;Giappone;0;JPY
+KE;KEN;Kenya;0;KES
+KG;KGZ;Kirghizistan;0;KGS
+KH;KHM;Cambogia;0;KHR
+KI;KIR;Kiribati;0;AUD
+KM;COM;Comore;0;KMF
+KN;KNA;Saint Kitts e Nevis;0;XCD
+KP;PRK;Corea del Nord;0;KPW
+KR;KOR;Corea del Sud;0;KRW
+KW;KWT;Kuwait;0;KWD
+KY;CYM;Isole Cayman;0;KYD
+KZ;KAZ;Kazakistan;0;KZT
+LA;LAO;Laos;0;LAK
+LB;LBN;Libano;0;LBP
+LC;LCA;Santa Lucia;0;XCD
+LI;LIE;Liechtenstein;0;CHF
+LK;LKA;Sri Lanka;0;LKR
+LR;LBR;Liberia;0;LRD
+LS;LSO;Lesotho;0;LSL
+LT;LTU;Lituania;1;EUR
+LU;LUX;Lussemburgo;1;EUR
+LV;LVA;Lettonia;1;EUR
+LY;LBY;Libia;0;LYD
+MA;MAR;Marocco;0;MAD
+MC;MCO;Monaco;0;EUR
+MD;MDA;Moldavia;0;MDL
+ME;MNE;Montenegro;0;EUR
+MF;MAF;Saint-Martin;0;EUR
+MG;MDG;Madagascar;0;MGA
+MH;MHL;Isole Marshall;0;USD
+MK;MKD;Macedonia del Nord;0;MKD
+ML;MLI;Mali;0;XOF
+MM;MMR;Myanmar;0;MMK
+MN;MNG;Mongolia;0;MNT
+MO;MAC;Macao;0;MOP
+MP;MNP;Isole Marianne Settentrionali;0;USD
+MQ;MTQ;Martinica;0;EUR
+MR;MRT;Mauritania;0;MRU
+MS;MSR;Montserrat;0;XCD
+MT;MLT;Malta;1;EUR
+MU;MUS;Mauritius;0;MUR
+MV;MDV;Maldive;0;MVR
+MW;MWI;Malawi;0;MWK
+MX;MEX;Messico;0;MXN
+MY;MYS;Malaysia;0;MYR
+MZ;MOZ;Mozambico;0;MZN
+NA;NAM;Namibia;0;NAD
+NC;NCL;Nuova Caledonia;0;XPF
+NE;NER;Niger;0;XOF
+NF;NFK;Isola Norfolk;0;AUD
+NG;NGA;Nigeria;0;NGN
+NI;NIC;Nicaragua;0;NIO
+NL;NLD;Paesi Bassi;1;EUR
+NO;NOR;Norvegia;0;NOK
+NP;NPL;Nepal;0;NPR
+NR;NRU;Nauru;0;AUD
+NU;NIU;Niue;0;NZD
+NZ;NZL;Nuova Zelanda;0;NZD
+OM;OMN;Oman;0;OMR
+PA;PAN;Panama;0;PAB
+PE;PER;Perù;0;PEN
+PF;PYF;Polinesia francese;0;XPF
+PG;PNG;Papua Nuova Guinea;0;PGK
+PH;PHL;Filippine;0;PHP
+PK;PAK;Pakistan;0;PKR
+PL;POL;Polonia;1;PLN
+PM;SPM;Saint-Pierre e Miquelon;0;EUR
+PN;PCN;Isole Pitcairn;0;NZD
+PR;PRI;Porto Rico;0;USD
+PS;PSE;Palestina;0;ILS
+PT;PRT;Portogallo;1;EUR
+PW;PLW;Palau;0;USD
+PY;PRY;Paraguay;0;PYG
+QA;QAT;Qatar;0;QAR
+RE;REU;Riunione;0;EUR
+RO;ROU;Romania;1;RON
+RS;SRB;Serbia;0;RSD
+RU;RUS;Russia;0;RUB
+RW;RWA;Ruanda;0;RWF
+SA;SAU;Arabia Saudita;0;SAR
+SB;SLB;Isole Salomone;0;SBD
+SC;SYC;Seychelles;0;SCR
+SD;SDN;Sudan;0;SDG
+SE;SWE;Svezia;1;SEK
+SG;SGP;Singapore;0;SGD
+SH;SHN;Sant'Elena, Ascensione e Tristan da Cunha;0;SHP
+SI;SVN;Slovenia;1;EUR
+SJ;SJM;Svalbard e Jan Mayen;0;NOK
+SK;SVK;Slovacchia;1;EUR
+SL;SLE;Sierra Leone;0;SLE
+SM;SMR;San Marino;0;EUR
+SN;SEN;Senegal;0;XOF
+SO;SOM;Somalia;0;SOS
+SR;SUR;Suriname;0;SRD
+SS;SSD;Sudan del Sud;0;SSP
+ST;STP;São Tomé e Príncipe;0;STN
+SV;SLV;El Salvador;0;USD
+SX;SXM;Sint Maarten;0;XCG
+SY;SYR;Siria;0;SYP
+SZ;SWZ;Eswatini;0;SZL
+TC;TCA;Isole Turks e Caicos;0;USD
+TD;TCD;Ciad;0;XAF
+TF;ATF;Terre australi e antartiche francesi;0;EUR
+TG;TGO;Togo;0;XOF
+TH;THA;Thailandia;0;THB
+TJ;TJK;Tagikistan;0;TJS
+TK;TKL;Tokelau;0;NZD
+TL;TLS;Timor Est;0;USD
+TM;TKM;Turkmenistan;0;TMT
+TN;TUN;Tunisia;0;TND
+TO;TON;Tonga;0;TOP
+TR;TUR;Turchia;0;TRY
+TT;TTO;Trinidad e Tobago;0;TTD
+TV;TUV;Tuvalu;0;AUD
+TW;TWN;Taiwan;0;TWD
+TZ;TZA;Tanzania;0;TZS
+UA;UKR;Ucraina;0;UAH
+UG;UGA;Uganda;0;UGX
+UM;UMI;Isole minori esterne degli Stati Uniti;0;USD
+US;USA;Stati Uniti;0;USD
+UY;URY;Uruguay;0;UYU
+UZ;UZB;Uzbekistan;0;UZS
+VA;VAT;Città del Vaticano;0;EUR
+VC;VCT;Saint Vincent e Grenadine;0;XCD
+VE;VEN;Venezuela;0;VES
+VG;VGB;Isole Vergini britanniche;0;USD
+VI;VIR;Isole Vergini americane;0;USD
+VN;VNM;Vietnam;0;VND
+VU;VUT;Vanuatu;0;VUV
+WF;WLF;Wallis e Futuna;0;XPF
+WS;WSM;Samoa;0;WST
+XI;;Irlanda del Nord (IVA);1;GBP
+XK;XKX;Kosovo;0;EUR
+YE;YEM;Yemen;0;YER
+YT;MYT;Mayotte;0;EUR
+ZA;ZAF;Sudafrica;0;ZAR
+ZM;ZMB;Zambia;0;ZMW
+ZW;ZWE;Zimbabwe;0;ZWG
diff --git a/src/Khaemhat.Application/Seeding/Seeding.cs b/src/Khaemhat.Application/Seeding/Seeding.cs
new file mode 100644
index 0000000..661a8bb
--- /dev/null
+++ b/src/Khaemhat.Application/Seeding/Seeding.cs
@@ -0,0 +1,287 @@
+using Khaemhat.Application.Instance;
+using Khaemhat.Application.Security;
+using Khaemhat.Application.Tables;
+using Khaemhat.Core.Entities;
+using Khaemhat.Core.Instance;
+using Khaemhat.Core.Tables;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+using Khaemhat.Fiscal.Abstractions;
+using Microsoft.Extensions.Logging;
+
+namespace Khaemhat.Application.Seeding;
+
+/// The kind of data a seeder loads (SPEC §14).
+public enum SeedKind
+{
+ /// The base tables every company needs.
+ Base = 0,
+
+ /// The fictitious demo company.
+ Demo = 1,
+}
+
+/// A source of base or demo data (SPEC §14). Seeders are idempotent: they add what is missing and change nothing else.
+public interface ISeeder
+{
+ /// The licence module whose tables it fills (CORE, ACCT...).
+ string ModuleCode { get; }
+
+ /// Base or demo.
+ SeedKind Kind { get; }
+
+ /// The order among seeders of the same kind (lower first).
+ int Order { get; }
+
+ /// Loads the data.
+ /// The company, its unit of work and fiscal pack.
+ /// Cancellation.
+ /// A task.
+ Task RunAsync(SeedContext context, CancellationToken cancellationToken);
+}
+
+/// What a seeder works with, and the counts of what it added.
+public sealed class SeedContext
+{
+ private readonly Dictionary _added = new(StringComparer.Ordinal);
+
+ /// Creates the context.
+ /// The company.
+ /// The company unit of work, committed by the runner.
+ /// The fiscal pack of the company.
+ /// Today, for the current year.
+ public SeedContext(string companyCode, IUnitOfWork unitOfWork, IFiscalPack pack, DateOnly today)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
+ ArgumentNullException.ThrowIfNull(unitOfWork);
+ ArgumentNullException.ThrowIfNull(pack);
+ CompanyCode = companyCode;
+ UnitOfWork = unitOfWork;
+ Pack = pack;
+ Today = today;
+ }
+
+ /// The company.
+ public string CompanyCode { get; }
+
+ /// The company unit of work.
+ public IUnitOfWork UnitOfWork { get; }
+
+ /// The fiscal pack.
+ public IFiscalPack Pack { get; }
+
+ /// Today.
+ public DateOnly Today { get; }
+
+ /// Rows added, by table.
+ public IReadOnlyDictionary Added => _added;
+
+ /// Adds the rows whose code is missing; existing rows are left as the users made them.
+ /// The entity.
+ /// The table, for the counts.
+ /// The rows.
+ /// Cancellation.
+ /// Every row of the seed as stored (the existing one when the code was there).
+ public async Task> EnsureAsync(string table, IEnumerable rows, CancellationToken cancellationToken)
+ where T : CodedEntity, new()
+ {
+ ArgumentNullException.ThrowIfNull(rows);
+ var repository = UnitOfWork.Repository();
+ var existing = (await repository.ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items
+ .GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
+ var result = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var row in rows)
+ {
+ if (existing.TryGetValue(row.Code, out var found))
+ {
+ result[row.Code] = found;
+ continue;
+ }
+
+ row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
+ existing[row.Code] = row;
+ result[row.Code] = row;
+ Count(table);
+ }
+
+ return result;
+ }
+
+ /// Adds one row when nothing matches a condition.
+ /// The entity.
+ /// The table, for the counts.
+ /// Finds the row.
+ /// The row to add.
+ /// Cancellation.
+ /// The stored row.
+ public async Task EnsureOneAsync(string table, System.Linq.Expressions.Expression> match, T row, CancellationToken cancellationToken)
+ where T : class, IEntity, new()
+ {
+ ArgumentNullException.ThrowIfNull(row);
+ var repository = UnitOfWork.Repository();
+ var found = await repository.FindAsync(Query.For().Where(match), cancellationToken).ConfigureAwait(false);
+ if (found is not null)
+ {
+ return found;
+ }
+
+ row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
+ Count(table);
+ return row;
+ }
+
+ /// Counts a row added by hand.
+ /// The table.
+ public void Count(string table) => _added[table] = _added.GetValueOrDefault(table) + 1;
+}
+
+/// The outcome of a seed run.
+/// The data version now recorded, such as IT 2026.2.
+/// Rows added, by table.
+public sealed record SeedReport(string DataVersion, IReadOnlyDictionary Added)
+{
+ /// Total rows added.
+ public int Total => Added.Values.Sum();
+}
+
+///
+/// Runs the seeders of a kind on a company in one unit of work and records the data version in the company setting
+/// (SPEC §14). At company creation and at every start it runs the base seeders when
+/// KHAEMHAT_SEED_BASE is on; the button Aggiorna tabelle di base and scripts/seed.sh --base run
+/// them on demand. Being idempotent, running again only adds what a newer data version brings.
+///
+public sealed partial class SeedRunner : ICompanySeeder
+{
+ /// The company setting with the version of the base data.
+ public const string VersionSetting = "seed.base.version";
+
+ private readonly IReadOnlyList _seeders;
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly CompanyFiscalContext _fiscal;
+ private readonly PermissionService _permissions;
+ private readonly TableService _tables;
+ private readonly FiscalYearService _years;
+ private readonly TimeProvider _clock;
+ private readonly ILogger _logger;
+
+ /// Creates the runner.
+ /// The seeders.
+ /// Opens the company databases.
+ /// The fiscal pack of each company.
+ /// Checks permissions (the button).
+ /// The tables (cache invalidation).
+ /// The fiscal years (cache invalidation).
+ /// The clock.
+ /// The log.
+ public SeedRunner(
+ IEnumerable seeders, IUnitOfWorkFactory factory, CompanyFiscalContext fiscal, PermissionService permissions, TableService tables,
+ FiscalYearService years, TimeProvider clock, ILogger logger)
+ {
+ ArgumentNullException.ThrowIfNull(seeders);
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(fiscal);
+ ArgumentNullException.ThrowIfNull(permissions);
+ ArgumentNullException.ThrowIfNull(tables);
+ ArgumentNullException.ThrowIfNull(years);
+ ArgumentNullException.ThrowIfNull(clock);
+ ArgumentNullException.ThrowIfNull(logger);
+ _seeders = [.. seeders.OrderBy(s => s.Kind).ThenBy(s => s.Order)];
+ _factory = factory;
+ _fiscal = fiscal;
+ _permissions = permissions;
+ _tables = tables;
+ _years = years;
+ _clock = clock;
+ _logger = logger;
+ }
+
+ ///
+ public int Order => 10;
+
+ ///
+ public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ if (context.Base)
+ {
+ await RunAsync(companyCode, SeedKind.Base, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ /// The button Aggiorna tabelle di base: runs the base seeders for a company.
+ /// Who asks: needs company.settings.write.
+ /// The company.
+ /// Cancellation.
+ /// What was added.
+ public async Task UpdateBaseAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
+ {
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
+ return await RunAsync(company, SeedKind.Base, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// The data version recorded in a company, or before the first run.
+ /// The company.
+ /// Cancellation.
+ /// The version.
+ public async Task VersionAsync(string companyCode, CancellationToken cancellationToken = default)
+ {
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
+ var setting = await uow.Repository().FindAsync(Query.For().Where(s => s.Key == VersionSetting), cancellationToken).ConfigureAwait(false);
+ return setting?.Value;
+ }
+
+ /// Runs every seeder of a kind on a company.
+ /// The company.
+ /// Base or demo.
+ /// Cancellation.
+ /// What was added.
+ public async Task RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default)
+ {
+ var company = CompanyCodes.Normalize(companyCode);
+ var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
+ var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
+ SeedContext context;
+ await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
+ {
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ context = new SeedContext(company, uow, pack, today);
+ foreach (var seeder in _seeders.Where(s => s.Kind == kind))
+ {
+ await seeder.RunAsync(context, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (kind == SeedKind.Base)
+ {
+ await WriteVersionAsync(uow, pack.DataVersion, cancellationToken).ConfigureAwait(false);
+ }
+
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ await _tables.InvalidateAllAsync(company, cancellationToken).ConfigureAwait(false);
+ await _years.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
+ await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
+ var report = new SeedReport(pack.DataVersion, context.Added);
+ LogSeeded(_logger, kind, company, pack.DataVersion, report.Total);
+ return report;
+ }
+
+ private static async Task WriteVersionAsync(IUnitOfWork uow, string version, CancellationToken cancellationToken)
+ {
+ var settings = uow.Repository();
+ var setting = await settings.FindAsync(Query.For().Where(s => s.Key == VersionSetting), cancellationToken).ConfigureAwait(false);
+ if (setting is null)
+ {
+ await settings.InsertAsync(new CompanySetting { Key = VersionSetting, Value = version }, cancellationToken).ConfigureAwait(false);
+ }
+ else if (setting.Value != version)
+ {
+ setting.Value = version;
+ await settings.UpdateAsync(setting, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ [LoggerMessage(Level = LogLevel.Information, Message = "Dati {Kind} dell'azienda {Company} (versione {Version}): {Added} righe aggiunte.")]
+ private static partial void LogSeeded(ILogger logger, SeedKind kind, string company, string version, int added);
+}
diff --git a/src/Khaemhat.Application/Tables/CompanyFiscalContext.cs b/src/Khaemhat.Application/Tables/CompanyFiscalContext.cs
new file mode 100644
index 0000000..49e1fd0
--- /dev/null
+++ b/src/Khaemhat.Application/Tables/CompanyFiscalContext.cs
@@ -0,0 +1,72 @@
+using Khaemhat.Application.Configuration;
+using Khaemhat.Core.Caching;
+using Khaemhat.Core.Tables;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+using Khaemhat.Fiscal.Abstractions;
+
+namespace Khaemhat.Application.Tables;
+
+///
+/// The fiscal pack of each company: the one of company_profile.country, or of KHAEMHAT_COUNTRY while the
+/// profile is missing (ADR 0025). The country is cached per company.
+///
+public sealed class CompanyFiscalContext
+{
+ private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly FiscalPackCatalog _packs;
+ private readonly ICacheProvider _cache;
+ private readonly string _defaultCountry;
+
+ /// Creates the context.
+ /// Opens the company databases.
+ /// The fiscal packs.
+ /// The cache.
+ /// The instance options (KHAEMHAT_COUNTRY).
+ public CompanyFiscalContext(IUnitOfWorkFactory factory, FiscalPackCatalog packs, ICacheProvider cache, KhaemhatOptions options)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(packs);
+ ArgumentNullException.ThrowIfNull(cache);
+ ArgumentNullException.ThrowIfNull(options);
+ _factory = factory;
+ _packs = packs;
+ _cache = cache;
+ _defaultCountry = options.Country;
+ }
+
+ /// The country given to new companies.
+ public string DefaultCountry => _defaultCountry;
+
+ /// The pack of the instance's default country.
+ public IFiscalPack DefaultPack => _packs.ForCountry(_defaultCountry);
+
+ /// The fiscal pack of a company.
+ /// The company.
+ /// Cancellation.
+ /// The pack.
+ public async Task PackOfAsync(string companyCode, CancellationToken cancellationToken = default)
+ {
+ var company = CompanyCodes.Normalize(companyCode);
+ var country = await _cache.GetOrCreateAsync(
+ CacheKeys.For(company, "fiscal", "country"),
+ async ct =>
+ {
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
+ var profile = await uow.Repository().FindAsync(Query.For(), ct).ConfigureAwait(false);
+ return profile?.Country ?? _defaultCountry;
+ },
+ CacheTime,
+ cancellationToken).ConfigureAwait(false);
+ return _packs.TryForCountry(country, out var pack) ? pack : DefaultPack;
+ }
+
+ /// Forgets the cached country of a company (after the profile changes).
+ /// The company.
+ /// Cancellation.
+ /// A task.
+ public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
+ _cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "fiscal"), cancellationToken);
+}
diff --git a/src/Khaemhat.Application/Tables/CompanyProfileService.cs b/src/Khaemhat.Application/Tables/CompanyProfileService.cs
new file mode 100644
index 0000000..35dad98
--- /dev/null
+++ b/src/Khaemhat.Application/Tables/CompanyProfileService.cs
@@ -0,0 +1,273 @@
+using System.Text.RegularExpressions;
+using Khaemhat.Application.Audit;
+using Khaemhat.Application.Security;
+using Khaemhat.Core.Tables;
+using Khaemhat.Core.Tax;
+using Khaemhat.Core.Validation;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+using Khaemhat.Fiscal.Abstractions;
+
+namespace Khaemhat.Application.Tables;
+
+///
+/// The company profile (SPEC §11.1, mockup 075): one row per company, created on the first save. The country chooses
+/// the fiscal pack; changing it is refused once documents exist (from M5).
+///
+public sealed partial class CompanyProfileService
+{
+ /// Error: the name is missing.
+ public const string NameRequired = "profile.name.required";
+
+ /// Error: no fiscal pack for the country.
+ public const string CountryUnknown = "profile.country.unknown";
+
+ /// Error: the month is outside 1-12.
+ public const string MonthRange = "profile.month.range";
+
+ /// Error: a code that must be two letters.
+ public const string TwoLettersRequired = "profile.two-letters";
+
+ /// Error: the tax code is not valid.
+ public const string TaxCodeInvalid = "profile.tax-code.invalid";
+
+ /// Error: the recipient code is not seven characters.
+ public const string RecipientCodeInvalid = "profile.recipient-code.invalid";
+
+ /// Error: a value outside the list (SU/SM, LS/LN).
+ public const string ValueInvalid = "profile.value.invalid";
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly AuditTrail _audit;
+ private readonly CompanyFiscalContext _fiscal;
+ private readonly FiscalPackCatalog _packs;
+
+ /// Creates the service.
+ /// Opens the company databases.
+ /// Checks permissions.
+ /// Writes the history.
+ /// The fiscal pack of each company.
+ /// The installed fiscal packs.
+ public CompanyProfileService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, FiscalPackCatalog packs)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(permissions);
+ ArgumentNullException.ThrowIfNull(audit);
+ ArgumentNullException.ThrowIfNull(fiscal);
+ ArgumentNullException.ThrowIfNull(packs);
+ _factory = factory;
+ _permissions = permissions;
+ _audit = audit;
+ _fiscal = fiscal;
+ _packs = packs;
+ }
+
+ /// The profile, or a new one with the defaults of the instance when the company has none yet.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The profile ( 0 when new).
+ public async Task GetAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
+ {
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ return await LoadAsync(uow, cancellationToken).ConfigureAwait(false) ?? NewProfile(company);
+ }
+
+ /// Checks a profile without saving it.
+ /// The profile (normalized in place).
+ /// Errors and warnings by field.
+ public IReadOnlyList Validate(CompanyProfile profile)
+ {
+ ArgumentNullException.ThrowIfNull(profile);
+ var problems = new List();
+ profile.LegalName = profile.LegalName.Trim();
+ profile.Country = profile.Country.Trim().ToUpperInvariant();
+ if (profile.LegalName.Length == 0)
+ {
+ problems.Add(new(nameof(CompanyProfile.LegalName), NameRequired));
+ }
+
+ if (!_packs.TryForCountry(profile.Country, out var pack))
+ {
+ problems.Add(new(nameof(CompanyProfile.Country), CountryUnknown));
+ pack = _fiscal.DefaultPack;
+ }
+
+ if (pack.GetFeature() is { } rules)
+ {
+ if (!string.IsNullOrWhiteSpace(profile.VatNumber))
+ {
+ profile.VatNumber = rules.NormalizeVatNumber(profile.VatNumber);
+ if (!rules.IsValidVatNumber(profile.VatNumber))
+ {
+ problems.Add(new(nameof(CompanyProfile.VatNumber), TableCatalog.VatNumberInvalid));
+ }
+ }
+
+ if (!string.IsNullOrWhiteSpace(profile.TaxCode))
+ {
+ profile.TaxCode = profile.TaxCode.Trim().ToUpperInvariant();
+ if (!rules.IsValidTaxCode(profile.TaxCode))
+ {
+ problems.Add(new(nameof(CompanyProfile.TaxCode), TaxCodeInvalid));
+ }
+ }
+ }
+
+ if (pack.GetFeature() is { } format && format.TaxRegimes.Find(profile.TaxRegime) is not { Obsolete: false })
+ {
+ problems.Add(new(nameof(CompanyProfile.TaxRegime), TableCatalog.NotInCodeList));
+ }
+
+ if (!string.IsNullOrWhiteSpace(profile.RecipientCode))
+ {
+ profile.RecipientCode = profile.RecipientCode.Trim().ToUpperInvariant();
+ if (!RecipientCode().IsMatch(profile.RecipientCode))
+ {
+ problems.Add(new(nameof(CompanyProfile.RecipientCode), RecipientCodeInvalid));
+ }
+ }
+
+ CheckTwoLetters(profile.ProvinceCode, nameof(CompanyProfile.ProvinceCode), problems, v => profile.ProvinceCode = v);
+ CheckTwoLetters(profile.ReaOffice, nameof(CompanyProfile.ReaOffice), problems, v => profile.ReaOffice = v);
+ CheckTwoLetters(profile.AddressCountry, nameof(CompanyProfile.AddressCountry), problems, v => profile.AddressCountry = v);
+ CheckTwoLetters(profile.TransmitterCountry, nameof(CompanyProfile.TransmitterCountry), problems, v => profile.TransmitterCountry = v);
+ if (profile.Shareholders is { Length: > 0 } shareholders && shareholders is not ("SU" or "SM"))
+ {
+ problems.Add(new(nameof(CompanyProfile.Shareholders), ValueInvalid));
+ }
+
+ if (profile.LiquidationStatus is { Length: > 0 } liquidation && liquidation is not ("LS" or "LN"))
+ {
+ problems.Add(new(nameof(CompanyProfile.LiquidationStatus), ValueInvalid));
+ }
+
+ foreach (var (value, field) in new[] { (profile.Email, nameof(CompanyProfile.Email)), (profile.Pec, nameof(CompanyProfile.Pec)) })
+ {
+ if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value))
+ {
+ problems.Add(new(field, TableCatalog.EmailInvalid));
+ }
+ }
+
+ if (profile.ProRataPercent is < 0 or > 100)
+ {
+ problems.Add(new(nameof(CompanyProfile.ProRataPercent), TableCatalog.PercentRange));
+ }
+
+ if (profile.FiscalYearStartMonth is < 1 or > 12)
+ {
+ problems.Add(new(nameof(CompanyProfile.FiscalYearStartMonth), MonthRange));
+ }
+
+ profile.CurrencyCode = profile.CurrencyCode.Trim().ToUpperInvariant();
+ if (profile.CurrencyCode.Length != 3)
+ {
+ problems.Add(new(nameof(CompanyProfile.CurrencyCode), TableCatalog.CodePattern));
+ }
+
+ return problems;
+ }
+
+ /// Saves the profile (inserted the first time).
+ /// Who saves.
+ /// The company.
+ /// The profile.
+ /// Cancellation.
+ /// The saved profile.
+ /// A rule failed (Field:code).
+ public async Task SaveAsync(Actor actor, string companyCode, CompanyProfile profile, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(profile);
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
+ var errors = Validate(profile).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
+ if (errors.Count > 0)
+ {
+ throw new ValidationFailedException(errors);
+ }
+
+ await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
+ {
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ var repository = uow.Repository();
+ var before = await LoadAsync(uow, cancellationToken).ConfigureAwait(false);
+ if (before is null)
+ {
+ profile.Id = await repository.InsertAsync(profile, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Insert, profile.Id, null, profile, actor.UserName, cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ profile.Id = before.Id;
+ await repository.UpdateAsync(profile, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Update, profile.Id, before, profile, actor.UserName, cancellationToken).ConfigureAwait(false);
+ }
+
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
+ return profile;
+ }
+
+ /// A new profile with the defaults of the instance (country from KHAEMHAT_COUNTRY).
+ /// The name proposed.
+ /// The profile.
+ public CompanyProfile NewProfile(string companyName) => new()
+ {
+ LegalName = companyName,
+ Country = _fiscal.DefaultCountry.ToUpperInvariant(),
+ AddressCountry = _fiscal.DefaultCountry.ToUpperInvariant(),
+ CurrencyCode = "EUR",
+ VatPeriodicity = VatPeriodicity.Monthly,
+ LiquidationStatus = "LN",
+ };
+
+ internal static Task LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
+ uow.Repository().FindAsync(Query.For().OrderBy(x => x.Id), cancellationToken);
+
+ private static void CheckTwoLetters(string? value, string field, List problems, Action set)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ set(null);
+ return;
+ }
+
+ var upper = value.Trim().ToUpperInvariant();
+ set(upper);
+ if (upper.Length != 2 || !upper.All(char.IsAsciiLetterUpper))
+ {
+ problems.Add(new(field, TwoLettersRequired));
+ }
+ }
+
+ [GeneratedRegex("^[A-Z0-9]{6,7}$", RegexOptions.CultureInvariant)]
+ private static partial Regex RecipientCode();
+}
+
+/// The common access check of the company services.
+internal static class CompanyGuard
+{
+ /// Checks that the actor works in the company and has the permission.
+ /// The permission service.
+ /// Who acts.
+ /// The company.
+ /// The permission.
+ /// Cancellation.
+ /// The normalized company code.
+ public static async Task DemandAsync(PermissionService permissions, Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
+ {
+ 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.");
+ }
+
+ await permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
+ return company;
+ }
+}
diff --git a/src/Khaemhat.Application/Tables/ExchangeRates.cs b/src/Khaemhat.Application/Tables/ExchangeRates.cs
new file mode 100644
index 0000000..cad1654
--- /dev/null
+++ b/src/Khaemhat.Application/Tables/ExchangeRates.cs
@@ -0,0 +1,208 @@
+using System.Globalization;
+using Khaemhat.Application.Audit;
+using Khaemhat.Application.Jobs;
+using Khaemhat.Application.Querying;
+using Khaemhat.Application.Security;
+using Khaemhat.Core.Instance;
+using Khaemhat.Core.Tables;
+using Khaemhat.Data;
+using Khaemhat.Data.Companies;
+using Khaemhat.Data.Querying;
+using Khaemhat.Infrastructure.Http;
+
+namespace Khaemhat.Application.Tables;
+
+///
+/// The exchange rates of a company (SPEC §11.1): the ECB reference rates loaded by for the
+/// currencies of the table, and rates typed by hand. The rate of a day is the last one on or before it.
+///
+public sealed class ExchangeRateService
+{
+ /// The source of the ECB rates.
+ public const string EcbSource = "ECB";
+
+ /// The source of the rates typed by hand.
+ public const string ManualSource = "MANUAL";
+
+ /// Error: the rate is not positive.
+ public const string RateInvalid = "tables.exchange-rate.invalid";
+
+ /// The fields of the grid.
+ public static readonly ListFields Fields = new ListFields()
+ .Add("currency", x => x.CurrencyCode, searchable: true)
+ .Add("date", x => x.RateDate)
+ .Add("rate", x => x.Rate)
+ .Add("source", x => x.Source)
+ .OrderByDefault(new ListSort("date", Descending: true), new ListSort("currency"));
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly AuditTrail _audit;
+
+ /// Creates the service.
+ /// Opens the company databases.
+ /// Checks permissions.
+ /// Writes the history.
+ public ExchangeRateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(permissions);
+ ArgumentNullException.ThrowIfNull(audit);
+ _factory = factory;
+ _permissions = permissions;
+ _audit = audit;
+ }
+
+ /// A page of rates.
+ /// Who reads.
+ /// The company.
+ /// The request.
+ /// Cancellation.
+ /// The page.
+ public async Task> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(query);
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ var repository = uow.Repository();
+ var filtered = Fields.Apply(Query.For(), query);
+ var page = await repository.ListAsync(filtered, cancellationToken).ConfigureAwait(false);
+ return new ListPage(page.Items, page.TotalCount, new Dictionary());
+ }
+
+ /// The rate of a currency on a day: the last one on or before it; 1 for the euro.
+ /// The company.
+ /// The currency.
+ /// The day.
+ /// Cancellation.
+ /// The rate, or when none is known.
+ public async Task RateOnAsync(string companyCode, string currency, DateOnly date, CancellationToken cancellationToken = default)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(currency);
+ var code = currency.Trim().ToUpperInvariant();
+ if (code == "EUR")
+ {
+ return new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = 1m, Source = EcbSource };
+ }
+
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
+ return await uow.Repository()
+ .FindAsync(Query.For().Where(x => x.CurrencyCode == code && x.RateDate <= date).OrderByDescending(x => x.RateDate), cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ /// Saves a rate typed by hand (replacing the one of the same day).
+ /// Who saves.
+ /// The company.
+ /// The currency.
+ /// The day.
+ /// Units of the currency for one euro.
+ /// Cancellation.
+ /// The rate.
+ /// The rate is not positive or the currency is not in the table.
+ public async Task SetManualAsync(Actor actor, string companyCode, string currency, DateOnly date, decimal rate, CancellationToken cancellationToken = default)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(currency);
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
+ var code = currency.Trim().ToUpperInvariant();
+ if (rate <= 0)
+ {
+ throw new ValidationFailedException([nameof(ExchangeRate.Rate) + ":" + RateInvalid]);
+ }
+
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ if (await uow.Repository().CountAsync(Query.For().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) == 0)
+ {
+ throw new ValidationFailedException([nameof(ExchangeRate.CurrencyCode) + ":" + TableCatalog.ReferenceMissing]);
+ }
+
+ var saved = await UpsertAsync(uow, new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = rate, Source = ManualSource }, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return saved;
+ }
+
+ /// Stores ECB rates for the currencies of a company's table (manual rates of the same day are kept).
+ /// The company.
+ /// The ECB rates.
+ /// Cancellation.
+ /// How many rates were added or changed.
+ public async Task StoreEcbAsync(string companyCode, IReadOnlyList rates, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(rates);
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ var currencies = (await uow.Repository().ListAsync(Query.For().Where(x => !x.Disabled), cancellationToken).ConfigureAwait(false)).Items
+ .Select(c => c.Code)
+ .ToHashSet(StringComparer.Ordinal);
+ var changed = 0;
+ foreach (var rate in rates.Where(r => currencies.Contains(r.Currency)))
+ {
+ var existing = await FindAsync(uow, rate.Currency, rate.Date, cancellationToken).ConfigureAwait(false);
+ if (existing is { Source: ManualSource } || existing?.Rate == rate.Rate)
+ {
+ continue;
+ }
+
+ await UpsertAsync(uow, new ExchangeRate { CurrencyCode = rate.Currency, RateDate = rate.Date, Rate = rate.Rate, Source = EcbSource }, "system", cancellationToken)
+ .ConfigureAwait(false);
+ changed++;
+ }
+
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return changed;
+ }
+
+ private static Task FindAsync(IUnitOfWork uow, string currency, DateOnly date, CancellationToken cancellationToken) =>
+ uow.Repository().FindAsync(Query.For().Where(x => x.CurrencyCode == currency && x.RateDate == date), cancellationToken);
+
+ private async Task UpsertAsync(IUnitOfWork uow, ExchangeRate rate, string userName, CancellationToken cancellationToken)
+ {
+ var repository = uow.Repository();
+ var existing = await FindAsync(uow, rate.CurrencyCode, rate.RateDate, cancellationToken).ConfigureAwait(false);
+ if (existing is null)
+ {
+ rate.Id = await repository.InsertAsync(rate, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Insert, rate.Id, null, rate, userName, cancellationToken).ConfigureAwait(false);
+ return rate;
+ }
+
+ var before = new ExchangeRate { Id = existing.Id, CurrencyCode = existing.CurrencyCode, RateDate = existing.RateDate, Rate = existing.Rate, Source = existing.Source };
+ existing.Rate = rate.Rate;
+ existing.Source = rate.Source;
+ await repository.UpdateAsync(existing, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Update, existing.Id, before, existing, userName, cancellationToken).ConfigureAwait(false);
+ return existing;
+ }
+}
+
+/// Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days.
+/// The ECB client.
+/// The exchange rates.
+/// The companies.
+public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies) : IScheduledJob
+{
+ /// The job type.
+ public const string JobType = "tables.ecb-rates";
+
+ ///
+ public string Type => JobType;
+
+ ///
+ public async Task RunAsync(JobContext context, CancellationToken cancellationToken)
+ {
+ // The 90-day file also fills the days missed while the instance was stopped.
+ var downloaded = await client.GetAsync(last90Days: true, cancellationToken).ConfigureAwait(false);
+ var changed = 0;
+ foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
+ {
+ if (company.Status is CompanyStatus.Active)
+ {
+ changed += await rates.StoreEcbAsync(company.Code, downloaded, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ var last = downloaded.Max(r => r.Date);
+ return string.Create(CultureInfo.InvariantCulture, $"Cambi BCE del {last:dd/MM/yyyy}: {changed} valori aggiornati.");
+ }
+}
diff --git a/src/Khaemhat.Application/Tables/FiscalYearService.cs b/src/Khaemhat.Application/Tables/FiscalYearService.cs
new file mode 100644
index 0000000..30ba46f
--- /dev/null
+++ b/src/Khaemhat.Application/Tables/FiscalYearService.cs
@@ -0,0 +1,321 @@
+using System.Globalization;
+using Khaemhat.Application.Audit;
+using Khaemhat.Application.Security;
+using Khaemhat.Core.Caching;
+using Khaemhat.Core.Tables;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+
+namespace Khaemhat.Application.Tables;
+
+/// A fiscal year with its months, as mockup 052 shows it.
+/// The year.
+/// The months, in order.
+public sealed record FiscalYearView(FiscalYear Year, IReadOnlyList Periods);
+
+/// What a date may receive.
+public enum PeriodUse
+{
+ /// A document or entry without VAT (warehouse, quotations, orders).
+ NoVat = 0,
+
+ /// A document or entry with VAT: refused once the VAT of the period is settled.
+ Vat = 1,
+}
+
+/// Why a date is refused (or ).
+public enum PeriodState
+{
+ /// The date is in an open period.
+ Open = 0,
+
+ /// No fiscal year contains the date.
+ NoYear = 1,
+
+ /// The year is closed or being closed.
+ YearClosed = 2,
+
+ /// The month is locked.
+ Locked = 3,
+
+ /// The VAT of the month was settled (only for ).
+ Settled = 4,
+}
+
+///
+/// Fiscal years and their months (SPEC §11.1, mockup 052): creation of the next year with its twelve months, lock and
+/// unlock of months, and the check that a date can receive documents and entries (), used by
+/// every service that writes dated records. Years and months are cached per company.
+///
+public sealed class FiscalYearService
+{
+ /// Error: the date of the new year overlaps an existing year.
+ public const string Overlap = "fiscal.year.overlap";
+
+ /// Error: the year is closed: its months cannot change.
+ public const string YearClosedError = "fiscal.year.closed";
+
+ /// Error: the month cannot become open again because the VAT is settled (reopened with the settlement, M7).
+ public const string SettledError = "fiscal.period.settled";
+
+ /// The error code thrown by , followed by the .
+ public const string DateRefused = "fiscal.date.";
+
+ private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly AuditTrail _audit;
+ private readonly ICacheProvider _cache;
+
+ /// Creates the service.
+ /// Opens the company databases.
+ /// Checks permissions.
+ /// Writes the history.
+ /// The cache.
+ public FiscalYearService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(permissions);
+ ArgumentNullException.ThrowIfNull(audit);
+ ArgumentNullException.ThrowIfNull(cache);
+ _factory = factory;
+ _permissions = permissions;
+ _audit = audit;
+ _cache = cache;
+ }
+
+ /// The years, newest first, with their months.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The years.
+ public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
+ {
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
+ return [.. (await CalendarAsync(company, cancellationToken).ConfigureAwait(false)).OrderByDescending(y => y.Year.StartDate)];
+ }
+
+ ///
+ /// Creates a year with its months: after the last year, or the one containing when there are
+ /// none (starting in the month of the profile).
+ ///
+ /// Who creates.
+ /// The company.
+ /// A day of the first year, when the company has none.
+ /// Cancellation.
+ /// The new year.
+ public async Task CreateNextAsync(Actor actor, string companyCode, DateOnly day, CancellationToken cancellationToken = default)
+ {
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
+ FiscalYearView created;
+ await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
+ {
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ created = await CreateAsync(uow, day, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ await InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
+ return created;
+ }
+
+ /// Locks or unlocks a month (unlocking a settled month is refused).
+ /// Who changes it.
+ /// The company.
+ /// The month.
+ /// Lock or unlock.
+ /// Cancellation.
+ /// The month.
+ /// The year is closed, or the month is settled.
+ public async Task SetLockedAsync(Actor actor, string companyCode, long periodId, bool locked, CancellationToken cancellationToken = default)
+ {
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
+ FiscalPeriod period;
+ await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
+ {
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ var periods = uow.Repository();
+ period = await periods.GetAsync(periodId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TableService.NotFound);
+ var year = await uow.Repository().GetAsync(period.FiscalYearId, cancellationToken).ConfigureAwait(false)
+ ?? throw new KeyNotFoundException(TableService.NotFound);
+ if (year.Status != FiscalYearStatus.Open)
+ {
+ throw new ValidationFailedException([YearClosedError]);
+ }
+
+ if (period.Status == FiscalPeriodStatus.Settled && !locked)
+ {
+ throw new ValidationFailedException([SettledError]);
+ }
+
+ var target = locked ? FiscalPeriodStatus.Locked : FiscalPeriodStatus.Open;
+ if (period.Status != target)
+ {
+ var before = Copy(period);
+ period.Status = target;
+ await periods.UpdateAsync(period, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Update, period.Id, before, period, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ await InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
+ return period;
+ }
+
+ /// Whether a date can receive a document or entry.
+ /// The company.
+ /// The date.
+ /// With or without VAT.
+ /// Cancellation.
+ /// The state of the date.
+ public async Task CheckAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default)
+ {
+ var calendar = await CalendarAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false);
+ return StateOf(calendar, date, use);
+ }
+
+ /// Throws when a date cannot receive a document or entry.
+ /// The company.
+ /// The date.
+ /// With or without VAT.
+ /// Cancellation.
+ /// A task.
+ /// The date is refused: fiscal.date.locked and similar.
+ public async Task DemandOpenAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default)
+ {
+ var state = await CheckAsync(companyCode, date, use, cancellationToken).ConfigureAwait(false);
+ if (state != PeriodState.Open)
+ {
+ throw new ValidationFailedException([ErrorOf(state)]);
+ }
+ }
+
+ /// The error code of a refused date, such as fiscal.date.locked.
+ /// The state.
+ /// The code.
+ public static string ErrorOf(PeriodState state) => state switch
+ {
+ PeriodState.NoYear => DateRefused + "no-year",
+ PeriodState.YearClosed => DateRefused + "year-closed",
+ PeriodState.Locked => DateRefused + "locked",
+ PeriodState.Settled => DateRefused + "settled",
+ _ => DateRefused + "open",
+ };
+
+ /// The state of a date in a calendar.
+ /// The years with their months.
+ /// The date.
+ /// With or without VAT.
+ /// The state.
+ public static PeriodState StateOf(IEnumerable calendar, DateOnly date, PeriodUse use)
+ {
+ ArgumentNullException.ThrowIfNull(calendar);
+ var year = calendar.FirstOrDefault(y => y.Year.StartDate <= date && date <= y.Year.EndDate);
+ if (year is null)
+ {
+ return PeriodState.NoYear;
+ }
+
+ if (year.Year.Status != FiscalYearStatus.Open)
+ {
+ return PeriodState.YearClosed;
+ }
+
+ var period = year.Periods.FirstOrDefault(p => p.StartDate <= date && date <= p.EndDate);
+ return period?.Status switch
+ {
+ FiscalPeriodStatus.Locked => PeriodState.Locked,
+ FiscalPeriodStatus.Settled when use == PeriodUse.Vat => PeriodState.Settled,
+ _ => PeriodState.Open,
+ };
+ }
+
+ ///
+ /// Creates a year with its months inside a unit of work (the seeder uses it for the current year): after the last
+ /// year, or the one containing when there are none.
+ ///
+ /// The company unit of work.
+ /// A day of the first year.
+ /// Who creates.
+ /// Cancellation.
+ /// The new year.
+ internal async Task CreateAsync(IUnitOfWork uow, DateOnly day, string userName, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(uow);
+ var years = uow.Repository();
+ var last = await years.FindAsync(Query.For().OrderByDescending(x => x.StartDate), cancellationToken).ConfigureAwait(false);
+ DateOnly start;
+ if (last is not null)
+ {
+ start = last.EndDate.AddDays(1);
+ }
+ else
+ {
+ var profile = await CompanyProfileService.LoadAsync(uow, cancellationToken).ConfigureAwait(false);
+ var month = profile?.FiscalYearStartMonth ?? 1;
+ start = new DateOnly(day.Month >= month ? day.Year : day.Year - 1, month, 1);
+ }
+
+ var end = start.AddYears(1).AddDays(-1);
+ if (await years.CountAsync(Query.For().Where(x => x.StartDate <= end && x.EndDate >= start), cancellationToken).ConfigureAwait(false) > 0)
+ {
+ throw new ValidationFailedException([Overlap]);
+ }
+
+ var year = new FiscalYear
+ {
+ Code = start.Year == end.Year
+ ? start.Year.ToString(CultureInfo.InvariantCulture)
+ : string.Create(CultureInfo.InvariantCulture, $"{start.Year}/{end.Year % 100:00}"),
+ StartDate = start,
+ EndDate = end,
+ };
+ year.Id = await years.InsertAsync(year, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Insert, year.Id, null, year, userName, cancellationToken).ConfigureAwait(false);
+
+ var periods = new List();
+ var repository = uow.Repository();
+ for (var i = 0; i < 12; i++)
+ {
+ var first = start.AddMonths(i);
+ var period = new FiscalPeriod { FiscalYearId = year.Id, Number = i + 1, StartDate = first, EndDate = first.AddMonths(1).AddDays(-1) };
+ period.Id = await repository.InsertAsync(period, cancellationToken).ConfigureAwait(false);
+ periods.Add(period);
+ }
+
+ return new FiscalYearView(year, periods);
+ }
+
+ /// Forgets the cached calendar of a company.
+ /// The company.
+ /// Cancellation.
+ /// A task.
+ public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
+ _cache.PublishInvalidationAsync(CacheKeys.For(CompanyCodes.Normalize(companyCode), "fiscal", "calendar"), cancellationToken);
+
+ private static FiscalPeriod Copy(FiscalPeriod period) => new()
+ {
+ Id = period.Id,
+ FiscalYearId = period.FiscalYearId,
+ Number = period.Number,
+ StartDate = period.StartDate,
+ EndDate = period.EndDate,
+ Status = period.Status,
+ RowVersion = period.RowVersion,
+ };
+
+ private async Task> CalendarAsync(string company, CancellationToken cancellationToken) =>
+ await _cache.GetOrCreateAsync>(
+ CacheKeys.For(company, "fiscal", "calendar"),
+ async ct =>
+ {
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
+ var years = (await uow.Repository().ListAsync(Query.For().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items;
+ var periods = (await uow.Repository().ListAsync(Query.For().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items;
+ return [.. years.Select(y => new FiscalYearView(y, [.. periods.Where(p => p.FiscalYearId == y.Id)]))];
+ },
+ CacheTime,
+ cancellationToken).ConfigureAwait(false);
+}
diff --git a/src/Khaemhat.Application/Tables/TableCatalog.cs b/src/Khaemhat.Application/Tables/TableCatalog.cs
new file mode 100644
index 0000000..bf004c4
--- /dev/null
+++ b/src/Khaemhat.Application/Tables/TableCatalog.cs
@@ -0,0 +1,511 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Khaemhat.Core.Tables;
+using Khaemhat.Core.Validation;
+using Khaemhat.Fiscal.Abstractions;
+
+namespace Khaemhat.Application.Tables;
+
+///
+/// The company tables of SPEC §11.1 handled by , each with its rules. Keys are in English
+/// (tax-codes); the interface gives them Italian addresses and names through the resources.
+///
+public sealed partial class TableCatalog
+{
+ /// Error: a percentage outside 0-100.
+ public const string PercentRange = "tables.percent.range";
+
+ /// Error: the end of validity is before the start.
+ public const string ValidityOrder = "tables.validity.order";
+
+ /// Error: the code does not follow the pattern of the table.
+ public const string CodePattern = "tables.code.pattern";
+
+ /// Error: a value not in the fiscal pack's code list.
+ public const string NotInCodeList = "tables.code-list.unknown";
+
+ /// Warning: a value that the code list marks obsolete.
+ public const string ObsoleteInCodeList = "tables.code-list.obsolete";
+
+ /// Error: decimals outside the allowed range.
+ public const string DecimalsRange = "tables.decimals.range";
+
+ /// Error: the IBAN is not valid.
+ public const string IbanInvalid = "tables.iban.invalid";
+
+ /// Error: the BIC is not valid.
+ public const string BicInvalid = "tables.bic.invalid";
+
+ /// Error: the e-mail address is not valid.
+ public const string EmailInvalid = "tables.email.invalid";
+
+ /// Error: the VAT number is not valid.
+ public const string VatNumberInvalid = "tables.vat-number.invalid";
+
+ /// Error: the parent does not exist, is the row itself or is too deep.
+ public const string ParentInvalid = "tables.parent.invalid";
+
+ /// Error: a referenced row does not exist.
+ public const string ReferenceMissing = "tables.reference.missing";
+
+ /// Error: the discount formula cannot be read.
+ public const string FormulaInvalid = "tables.discount.formula";
+
+ /// Error: the numerator format has no {number}.
+ public const string FormatInvalid = "tables.numerator.format";
+
+ /// Error: the year is outside 2000-2100.
+ public const string YearRange = "tables.year.range";
+
+ /// Error: the last number is negative.
+ public const string NumberRange = "tables.number.range";
+
+ /// Error: a transfer reason must not change quantities by itself.
+ public const string TransferEffect = "tables.inventory-reason.transfer";
+
+ /// The maximum depth of item categories.
+ public const int MaxCategoryLevel = 3;
+
+ private readonly Dictionary _byType = [];
+ private readonly Dictionary _byKey = new(StringComparer.Ordinal);
+
+ /// Creates the catalog.
+ public TableCatalog()
+ {
+ Add(new TableDefinition("countries", "countries") { CodeLength = 2 }
+ .Field("eu", x => x.EuMember)
+ .Rule((x, c) => Pattern(x.Code, TwoLetters(), c))
+ .Rule((x, c) =>
+ {
+ if (x.VatPrefix is { Length: > 0 } && !TwoLetters().IsMatch(x.VatPrefix))
+ {
+ c.Error(nameof(Country.VatPrefix), CodePattern);
+ }
+ }));
+ Add(new TableDefinition("provinces", "provinces") { CodeLength = 2 }
+ .Field("region", x => x.Region, searchable: true)
+ .Rule((x, c) => Pattern(x.Code, TwoLetters(), c)));
+ Add(new TableDefinition("municipalities", "municipalities") { CodeLength = 4 }
+ .Field("province", x => x.ProvinceCode, searchable: true)
+ .Field("postal-codes", x => x.PostalCodes, searchable: true)
+ .Rule((x, c) => Pattern(x.Code, CadastralCode(), c))
+ .Rule((x, c) =>
+ {
+ x.ProvinceCode = x.ProvinceCode.Trim().ToUpperInvariant();
+ if (!TwoLetters().IsMatch(x.ProvinceCode))
+ {
+ c.Error(nameof(Municipality.ProvinceCode), CodePattern);
+ }
+ }));
+ Add(new TableDefinition("currencies", "currencies") { CodeLength = 3 }
+ .Rule((x, c) => Pattern(x.Code, ThreeLetters(), c))
+ .Rule((x, c) => Decimals(x.Decimals, 0, 4, nameof(Currency.Decimals), c)));
+ Add(new TableDefinition("units", "units_of_measure")
+ .Rule((x, c) => Decimals(x.Decimals, 0, 6, nameof(UnitOfMeasure.Decimals), c)));
+ Add(new TableDefinition("tax-codes", "tax_codes")
+ {
+ Complete = (x, pack) =>
+ {
+ x.Nature = string.IsNullOrWhiteSpace(x.Nature) ? null : x.Nature.Trim().ToUpperInvariant();
+ x.Kind = pack.TaxCodes.KindOf(x.Rate, x.Nature);
+ },
+ }
+ .Field("rate", x => x.Rate)
+ .Field("nature", x => x.Nature, searchable: true)
+ .Field("kind", x => x.Kind)
+ .Rule((x, c) =>
+ {
+ var definition = new TaxCodeDefinition(x.Code, x.Description, x.Rate, x.Nature, x.Exigibility, x.NonDeductiblePercent, x.LegalReference);
+ foreach (var problem in c.Pack.TaxCodes.Validate(definition))
+ {
+ if (problem.Severity == FiscalProblemSeverity.Error)
+ {
+ c.Error(problem.Field, problem.Code);
+ }
+ else
+ {
+ c.Warning(problem.Field, problem.Code);
+ }
+ }
+
+ Validity(x.ValidFrom, x.ValidTo, nameof(TaxCode.ValidTo), c);
+ }));
+ Add(new TableDefinition("payment-methods", "payment_methods")
+ .Field("einvoice", x => x.EInvoiceCode)
+ .Rule((x, c) => InCodeList(x.EInvoiceCode, c.Pack.GetFeature()?.PaymentMethods, nameof(PaymentMethod.EInvoiceCode), c)));
+ Add(new TableDefinition("payment-terms", "payment_terms")
+ .Field("condition", x => x.Condition)
+ .Rule((x, c) => InCodeList(x.Condition, c.Pack.GetFeature()?.PaymentConditions, nameof(PaymentTerm.Condition), c))
+ .Rule(async (x, c, ct) =>
+ {
+ if (x.PaymentMethodId is { } id && await c.GetAsync(id, ct).ConfigureAwait(false) is null)
+ {
+ c.Error(nameof(PaymentTerm.PaymentMethodId), ReferenceMissing);
+ }
+ }));
+ Add(new TableDefinition("bank-accounts", "bank_accounts") { SingleDefault = x => x.IsDefault }
+ .Field("iban", x => x.Iban, searchable: true)
+ .Field("default", x => x.IsDefault)
+ .Rule((x, c) =>
+ {
+ if (!string.IsNullOrWhiteSpace(x.Iban))
+ {
+ x.Iban = IbanValidator.Normalize(x.Iban);
+ if (!IbanValidator.IsValid(x.Iban))
+ {
+ c.Error(nameof(BankAccount.Iban), IbanInvalid);
+ }
+ }
+ else
+ {
+ x.Iban = null;
+ }
+
+ if (!string.IsNullOrWhiteSpace(x.Bic))
+ {
+ x.Bic = x.Bic.Trim().ToUpperInvariant();
+ if (!Bic().IsMatch(x.Bic))
+ {
+ c.Error(nameof(BankAccount.Bic), BicInvalid);
+ }
+ }
+ }));
+ Add(new TableDefinition("salespeople", "salespeople")
+ .Field("commission", x => x.CommissionPercent)
+ .Rule((x, c) =>
+ {
+ Percent(x.CommissionPercent, nameof(Salesperson.CommissionPercent), c);
+ Email(x.Email, nameof(Salesperson.Email), c);
+ }));
+ Add(new TableDefinition("carriers", "carriers")
+ .Field("vat-number", x => x.VatNumber, searchable: true)
+ .Rule((x, c) =>
+ {
+ Email(x.Email, nameof(Carrier.Email), c);
+ if (!string.IsNullOrWhiteSpace(x.VatNumber) && c.Pack.GetFeature() is { } rules)
+ {
+ x.VatNumber = rules.NormalizeVatNumber(x.VatNumber);
+ if (!rules.IsValidVatNumber(x.VatNumber))
+ {
+ c.Error(nameof(Carrier.VatNumber), VatNumberInvalid);
+ }
+ }
+ }));
+ Add(new TableDefinition("shipping-terms", "shipping_terms"));
+ Add(new TableDefinition("transport-means", "transport_means"));
+ Add(new TableDefinition("goods-appearances", "goods_appearances"));
+ Add(new TableDefinition("delivery-terms", "delivery_terms"));
+ Add(new TableDefinition("transport-reasons", "transport_reasons"));
+ Add(new TableDefinition("inventory-reasons", "inventory_reasons")
+ .Field("effect", x => x.Effect)
+ .Rule((x, c) =>
+ {
+ if (x.IsTransfer && x.Effect != StockEffect.None)
+ {
+ c.Error(nameof(InventoryReason.Effect), TransferEffect);
+ }
+ }));
+ Add(new TableDefinition("warehouses", "warehouses") { SingleDefault = x => x.IsDefault }
+ .Field("default", x => x.IsDefault));
+ Add(new TableDefinition("item-categories", "item_categories") { CodeLength = 20 }
+ .Field("level", x => x.Level)
+ .Rule(async (x, c, ct) =>
+ {
+ x.Level = 1;
+ if (x.ParentId is not { } parentId)
+ {
+ return;
+ }
+
+ var parent = parentId == x.Id ? null : await c.GetAsync(parentId, ct).ConfigureAwait(false);
+ if (parent is null || parent.Level >= MaxCategoryLevel)
+ {
+ c.Error(nameof(ItemCategory.ParentId), ParentInvalid);
+ return;
+ }
+
+ x.Level = parent.Level + 1;
+ }));
+ Add(new TableDefinition("party-categories", "party_categories"));
+ Add(new TableDefinition("price-lists", "price_lists")
+ .Field("currency", x => x.CurrencyCode)
+ .Rule(async (x, c, ct) =>
+ {
+ x.CurrencyCode = x.CurrencyCode.Trim().ToUpperInvariant();
+ if (!ThreeLetters().IsMatch(x.CurrencyCode))
+ {
+ c.Error(nameof(PriceList.CurrencyCode), CodePattern);
+ }
+
+ Validity(x.ValidFrom, x.ValidTo, nameof(PriceList.ValidTo), c);
+ if (x.RoundingStep < 0)
+ {
+ c.Error(nameof(PriceList.RoundingStep), NumberRange);
+ }
+
+ if (x.BasePriceListId is { } baseId && (baseId == x.Id || await c.GetAsync(baseId, ct).ConfigureAwait(false) is null))
+ {
+ c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
+ }
+ }));
+ Add(new TableDefinition("discount-policies", "discount_policies")
+ .Field("formula", x => x.Formula)
+ .Rule((x, c) =>
+ {
+ if (DiscountFormula.TryParse(x.Formula, out var steps))
+ {
+ x.Formula = DiscountFormula.Format(steps);
+ }
+ else
+ {
+ c.Error(nameof(DiscountPolicy.Formula), FormulaInvalid);
+ }
+ }));
+ Add(new TableDefinition("numerators", "document_numerators") { SameKey = row => x => x.Year == row.Year }
+ .Field("year", x => x.Year)
+ .Field("kind", x => x.Kind)
+ .Field("section", x => x.Section)
+ .Field("last", x => x.LastNumber)
+ .Rule((x, c) =>
+ {
+ if (x.Year is < 2000 or > 2100)
+ {
+ c.Error(nameof(DocumentNumerator.Year), YearRange);
+ }
+
+ if (x.LastNumber < 0)
+ {
+ c.Error(nameof(DocumentNumerator.LastNumber), NumberRange);
+ }
+
+ if (!DocumentNumberFormat.IsValid(x.Format))
+ {
+ c.Error(nameof(DocumentNumerator.Format), FormatInvalid);
+ }
+
+ // Invoices, credit notes and final entries are numbered without gaps (SPEC §11.1).
+ if (x.Kind is NumeratorKind.SalesInvoice or NumeratorKind.Journal)
+ {
+ x.GapsAllowed = false;
+ }
+ }));
+ Add(new TableDefinition("document-types", "document_types")
+ .Field("kind", x => x.Kind)
+ .Field("einvoice", x => x.EInvoiceType)
+ .Rule(async (x, c, ct) =>
+ {
+ if (!string.IsNullOrWhiteSpace(x.EInvoiceType))
+ {
+ x.EInvoiceType = x.EInvoiceType.Trim().ToUpperInvariant();
+ InCodeList(x.EInvoiceType, c.Pack.GetFeature()?.DocumentTypes, nameof(DocumentType.EInvoiceType), c);
+ }
+ else
+ {
+ x.EInvoiceType = null;
+ }
+
+ if (x.NumeratorId is { } numeratorId && await c.GetAsync(numeratorId, ct).ConfigureAwait(false) is null)
+ {
+ c.Error(nameof(DocumentType.NumeratorId), ReferenceMissing);
+ }
+
+ if (x.InventoryReasonId is { } reasonId && await c.GetAsync(reasonId, ct).ConfigureAwait(false) is null)
+ {
+ c.Error(nameof(DocumentType.InventoryReasonId), ReferenceMissing);
+ }
+ }));
+ Add(new TableDefinition("cost-centers", "cost_centers") { CodeLength = 20 }
+ .Rule(async (x, c, ct) =>
+ {
+ if (x.ParentId is { } parentId && (parentId == x.Id || await c.GetAsync(parentId, ct).ConfigureAwait(false) is null))
+ {
+ c.Error(nameof(CostCenter.ParentId), ParentInvalid);
+ }
+ }));
+ Add(new TableDefinition("jobs", "jobs") { CodeLength = 20 }
+ .Field("status", x => x.Status)
+ .Rule((x, c) => Validity(x.StartDate, x.EndDate, nameof(Job.EndDate), c)));
+ }
+
+ /// Every table, in the order of SPEC §11.1.
+ public IEnumerable All => _byKey.Values;
+
+ /// The definition of an entity.
+ /// The entity.
+ /// The definition.
+ public TableDefinition Get()
+ where T : CodedEntity, new() =>
+ (TableDefinition)(_byType.GetValueOrDefault(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not a company table."));
+
+ /// A definition by key.
+ /// The key, such as tax-codes.
+ /// The definition, or .
+ public TableDefinition? Find(string key) => _byKey.GetValueOrDefault(key);
+
+ private static void Pattern(string code, Regex pattern, TableRuleContext context)
+ {
+ if (code.Length > 0 && !pattern.IsMatch(code))
+ {
+ context.Error(nameof(CodedEntity.Code), CodePattern);
+ }
+ }
+
+ private static void Decimals(int value, int min, int max, string field, TableRuleContext context)
+ {
+ if (value < min || value > max)
+ {
+ context.Error(field, DecimalsRange);
+ }
+ }
+
+ private static void Percent(decimal value, string field, TableRuleContext context)
+ {
+ if (value is < 0 or > 100)
+ {
+ context.Error(field, PercentRange);
+ }
+ }
+
+ private static void Email(string? value, string field, TableRuleContext context)
+ {
+ if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value))
+ {
+ context.Error(field, EmailInvalid);
+ }
+ }
+
+ private static void Validity(DateOnly? from, DateOnly? to, string field, TableRuleContext context)
+ {
+ if (from is { } start && to is { } end && end < start)
+ {
+ context.Error(field, ValidityOrder);
+ }
+ }
+
+ private static void InCodeList(string? value, CodeList? list, string field, TableRuleContext context)
+ {
+ if (list is null || string.IsNullOrEmpty(value))
+ {
+ return;
+ }
+
+ var entry = list.Find(value);
+ if (entry is null)
+ {
+ context.Error(field, NotInCodeList);
+ }
+ else if (entry.Obsolete)
+ {
+ context.Warning(field, ObsoleteInCodeList);
+ }
+ }
+
+ [GeneratedRegex("^[A-Z]{2}$", RegexOptions.CultureInvariant)]
+ private static partial Regex TwoLetters();
+
+ [GeneratedRegex("^[A-Z]{3}$", RegexOptions.CultureInvariant)]
+ private static partial Regex ThreeLetters();
+
+ [GeneratedRegex("^[A-Z][0-9]{3}$", RegexOptions.CultureInvariant)]
+ private static partial Regex CadastralCode();
+
+ [GeneratedRegex("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$", RegexOptions.CultureInvariant)]
+ private static partial Regex Bic();
+
+ private void Add(TableDefinition definition)
+ where T : CodedEntity, new()
+ {
+ _byType.Add(typeof(T), definition);
+ _byKey.Add(definition.Key, definition);
+ }
+}
+
+/// A chain of discounts such as 10+5: each step applies to what the previous left.
+public static class DiscountFormula
+{
+ /// Reads a formula: percentages 0-100 separated by +, decimal comma or point.
+ /// The formula.
+ /// The percentages.
+ /// Whether it could be read.
+ public static bool TryParse(string? formula, out IReadOnlyList steps)
+ {
+ steps = [];
+ if (string.IsNullOrWhiteSpace(formula))
+ {
+ return false;
+ }
+
+ var result = new List();
+ foreach (var part in formula.Split('+', StringSplitOptions.TrimEntries))
+ {
+ if (!decimal.TryParse(part.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var step) || step > 100)
+ {
+ return false;
+ }
+
+ result.Add(step);
+ }
+
+ steps = result;
+ return true;
+ }
+
+ /// Writes a formula in the Italian form, such as 10+5,5.
+ /// The percentages.
+ /// The formula.
+ public static string Format(IEnumerable steps) =>
+ string.Join('+', steps.Select(s => s.ToString("0.##", CultureInfo.GetCultureInfo("it-IT"))));
+
+ /// The single discount equal to the chain: 10+5 is 14.5%.
+ /// The percentages.
+ /// The equivalent percentage.
+ public static decimal Equivalent(IEnumerable steps) =>
+ 100m - (steps.Aggregate(1m, (left, step) => left * (1 - (step / 100m))) * 100m);
+}
+
+/// The format of document numbers: {prefix}, {year}, {section} and {number} (with :D6 and similar).
+public static partial class DocumentNumberFormat
+{
+ /// Whether a format has the number and only known placeholders.
+ /// The format.
+ /// Whether it is valid.
+ public static bool IsValid(string? format) =>
+ !string.IsNullOrWhiteSpace(format) && format.Length <= 60 && NumberPlaceholder().IsMatch(format) &&
+ Placeholder().Matches(format).All(m => Known().IsMatch(m.Value));
+
+ /// Writes a number with a format.
+ /// The format.
+ /// The number.
+ /// The year.
+ /// The prefix.
+ /// The section.
+ /// The document number, such as FV/2026/000123.
+ public static string Apply(string format, long number, int year, string? prefix, string? section)
+ {
+ ArgumentNullException.ThrowIfNull(format);
+ return Placeholder().Replace(format, m =>
+ {
+ var token = m.Value[1..^1];
+ var colon = token.IndexOf(':', StringComparison.Ordinal);
+ var name = colon < 0 ? token : token[..colon];
+ var spec = colon < 0 ? null : token[(colon + 1)..];
+ return name switch
+ {
+ "number" => number.ToString(spec, CultureInfo.InvariantCulture),
+ "year" => year.ToString(CultureInfo.InvariantCulture),
+ "prefix" => prefix ?? string.Empty,
+ "section" => section ?? string.Empty,
+ _ => m.Value,
+ };
+ });
+ }
+
+ [GeneratedRegex(@"\{number(:D[1-9])?\}", RegexOptions.CultureInvariant)]
+ private static partial Regex NumberPlaceholder();
+
+ [GeneratedRegex(@"\{[^}]*\}", RegexOptions.CultureInvariant)]
+ private static partial Regex Placeholder();
+
+ [GeneratedRegex(@"^\{(number(:D[1-9])?|year|prefix|section)\}$", RegexOptions.CultureInvariant)]
+ private static partial Regex Known();
+}
diff --git a/src/Khaemhat.Application/Tables/TableDefinition.cs b/src/Khaemhat.Application/Tables/TableDefinition.cs
new file mode 100644
index 0000000..4e0df6f
--- /dev/null
+++ b/src/Khaemhat.Application/Tables/TableDefinition.cs
@@ -0,0 +1,205 @@
+using System.Globalization;
+using System.Linq.Expressions;
+using System.Reflection;
+using System.Text.RegularExpressions;
+using Khaemhat.Application.Querying;
+using Khaemhat.Core.Entities;
+using Khaemhat.Core.Tables;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+using Khaemhat.Fiscal.Abstractions;
+
+namespace Khaemhat.Application.Tables;
+
+/// A problem found on a field of a table row: an error blocks the save, a warning does not.
+/// The property, such as Code.
+/// The stable code, translated by the interface (tables.code.required).
+/// Whether it is only a warning.
+public sealed record TableProblem(string Field, string Code, bool IsWarning = false);
+
+/// What the rules of a table can use: the fiscal pack of the company and the other rows.
+public sealed class TableRuleContext
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly List _problems = [];
+
+ internal TableRuleContext(IUnitOfWork unitOfWork, IFiscalPack pack)
+ {
+ _unitOfWork = unitOfWork;
+ Pack = pack;
+ }
+
+ /// The fiscal pack of the company's country.
+ public IFiscalPack Pack { get; }
+
+ /// The problems found so far.
+ public IReadOnlyList Problems => _problems;
+
+ /// Adds an error.
+ /// The property.
+ /// The code.
+ public void Error(string field, string code) => _problems.Add(new TableProblem(field, code));
+
+ /// Adds a warning.
+ /// The property.
+ /// The code.
+ public void Warning(string field, string code) => _problems.Add(new TableProblem(field, code, IsWarning: true));
+
+ /// Reads another row by id.
+ /// The entity.
+ /// The id.
+ /// Cancellation.
+ /// The row, or .
+ public Task GetAsync(long id, CancellationToken cancellationToken)
+ where TOther : class, IEntity, new() =>
+ _unitOfWork.Repository().GetAsync(id, cancellationToken);
+
+ /// Whether a coded row with a code exists.
+ /// The entity.
+ /// The code.
+ /// Cancellation.
+ /// Whether it exists.
+ public async Task ExistsAsync(string? code, CancellationToken cancellationToken)
+ where TOther : CodedEntity, new() =>
+ !string.IsNullOrEmpty(code) &&
+ await _unitOfWork.Repository().CountAsync(Query.For().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) > 0;
+}
+
+/// A company table that the generic maschera and service handle (SPEC §11.1, mockup 076).
+public abstract class TableDefinition
+{
+ /// Creates the definition.
+ /// The key used in addresses and resources, such as tax-codes.
+ /// The database table.
+ protected TableDefinition(string key, string table)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(key);
+ ArgumentException.ThrowIfNullOrWhiteSpace(table);
+ Key = key;
+ Table = table;
+ }
+
+ /// The key, such as tax-codes.
+ public string Key { get; }
+
+ /// The database table, such as tax_codes.
+ public string Table { get; }
+
+ /// The entity type.
+ public abstract Type EntityType { get; }
+
+ /// The maximum length of the code.
+ public int CodeLength { get; init; } = 10;
+
+ /// Whether codes are kept as typed instead of upper case (municipality names are not codes).
+ public bool KeepCodeCase { get; init; }
+
+ /// The CSV columns: header and property.
+ public abstract IReadOnlyList CsvColumns { get; }
+}
+
+/// A CSV column of a table: the snake_case header and the property.
+/// The header.
+/// The property.
+public sealed record TableCsvColumn(string Header, PropertyInfo Property);
+
+/// A company table of .
+/// The entity.
+public sealed partial class TableDefinition : TableDefinition
+ where T : CodedEntity, new()
+{
+ private static readonly HashSet NotInCsv = new(StringComparer.Ordinal)
+ {
+ nameof(Entity.Id), nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy),
+ nameof(IAuditable.RowVersion), nameof(CodedEntity.IsDemo),
+ };
+
+ private readonly List> _rules = [];
+ private IReadOnlyList? _csv;
+
+ /// Creates the definition with the list fields code, description, disabled.
+ /// The key, such as tax-codes.
+ /// The database table.
+ public TableDefinition(string key, string table)
+ : base(key, table)
+ {
+ Fields = new ListFields()
+ .Add("code", x => x.Code, searchable: true)
+ .Add("description", x => x.Description, searchable: true)
+ .Add("disabled", x => x.Disabled)
+ .OrderByDefault(new ListSort("code"));
+ }
+
+ ///
+ public override Type EntityType => typeof(T);
+
+ /// The fields of the grid: filters, search and ordering.
+ public ListFields Fields { get; }
+
+ /// The rules run before every save, after the common ones (code and description).
+ public IReadOnlyList> Rules => _rules;
+
+ /// The flag that only one row may have (the default bank account, the default warehouse).
+ public Expression>? SingleDefault { get; init; }
+
+ /// The other fields that, with the code, make a row unique (the year of a numerator).
+ public Func>>? SameKey { get; init; }
+
+ /// Called before the rules, to fill derived fields (the kind of a VAT code).
+ public Action? Complete { get; init; }
+
+ ///
+ public override IReadOnlyList CsvColumns => _csv ??=
+ [
+ .. typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
+ .Where(p => p.CanWrite && !NotInCsv.Contains(p.Name) && !p.Name.EndsWith("Id", StringComparison.Ordinal))
+ .OrderBy(p => p.Name switch { nameof(CodedEntity.Code) => 0, nameof(CodedEntity.Description) => 1, _ => 2 })
+ .ThenBy(p => p.MetadataToken)
+ .Select(p => new TableCsvColumn(SnakeCase(p.Name), p)),
+ ];
+
+ /// Adds a rule.
+ /// The rule.
+ /// This, to chain.
+ public TableDefinition Rule(Func rule)
+ {
+ ArgumentNullException.ThrowIfNull(rule);
+ _rules.Add(rule);
+ return this;
+ }
+
+ /// Adds a rule that needs no other rows.
+ /// The rule.
+ /// This, to chain.
+ public TableDefinition Rule(Action rule)
+ {
+ ArgumentNullException.ThrowIfNull(rule);
+ _rules.Add((row, context, _) =>
+ {
+ rule(row, context);
+ return Task.CompletedTask;
+ });
+ return this;
+ }
+
+ /// Adds a grid field.
+ /// The type.
+ /// The id.
+ /// The property.
+ /// Whether the search box looks in it.
+ /// This, to chain.
+ public TableDefinition Field(string id, Expression> selector, bool searchable = false)
+ {
+ Fields.Add(id, selector, searchable);
+ return this;
+ }
+
+ internal static string SnakeCase(string name) =>
+ LowerUpper().Replace(UpperUpperLower().Replace(name, "$1_$2"), "$1_$2").ToLower(CultureInfo.InvariantCulture);
+
+ [GeneratedRegex("([A-Z])([A-Z][a-z])")]
+ private static partial Regex UpperUpperLower();
+
+ [GeneratedRegex("([a-z0-9])([A-Z])")]
+ private static partial Regex LowerUpper();
+}
diff --git a/src/Khaemhat.Application/Tables/TableService.cs b/src/Khaemhat.Application/Tables/TableService.cs
new file mode 100644
index 0000000..5d797d5
--- /dev/null
+++ b/src/Khaemhat.Application/Tables/TableService.cs
@@ -0,0 +1,622 @@
+using System.Data.Common;
+using System.Globalization;
+using System.Reflection;
+using Khaemhat.Application.Audit;
+using Khaemhat.Application.Querying;
+using Khaemhat.Application.Security;
+using Khaemhat.Core.Caching;
+using Khaemhat.Core.Tables;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+using Khaemhat.Fiscal.Abstractions;
+using Khaemhat.Infrastructure.Files;
+
+namespace Khaemhat.Application.Tables;
+
+/// What a delete did.
+public enum TableDeleteOutcome
+{
+ /// The row is gone.
+ Deleted = 0,
+
+ /// The row is used elsewhere: it was disabled instead.
+ Disabled = 1,
+}
+
+/// A row of a CSV import that could not be read or saved.
+/// The row number in the file, from 2 (1 is the header).
+/// The column, or for the whole row.
+/// The problem.
+public sealed record TableImportError(int Row, string? Field, string Code);
+
+/// The result of a CSV import: nothing is saved when there are errors.
+/// New rows.
+/// Rows changed (found by code).
+/// The errors.
+public sealed record TableImportResult(int Inserted, int Updated, IReadOnlyList Errors)
+{
+ /// Whether the import was saved.
+ public bool Succeeded => Errors.Count == 0;
+}
+
+///
+/// The company tables of SPEC §11.1 through one service (wiki Tabelle azienda): list, read, save with the common
+/// rules (code and description required, unique code) and those of the table, delete (or disable when the row is used),
+/// CSV export and import. The rows of each table are cached per company and invalidated on every change, also on the
+/// other instances when Redis is configured.
+///
+/// Reading needs company.settings.read, changing company.settings.write.
+public sealed class TableService
+{
+ /// Permission to see the tables.
+ public const string ReadPermission = "company.settings.read";
+
+ /// Permission to change the tables.
+ public const string WritePermission = "company.settings.write";
+
+ /// Error: the code is missing.
+ public const string CodeRequired = "tables.code.required";
+
+ /// Error: the code is too long.
+ public const string CodeTooLong = "tables.code.too-long";
+
+ /// Error: another row has the code.
+ public const string CodeDuplicate = "tables.code.duplicate";
+
+ /// Error: the description is missing.
+ public const string DescriptionRequired = "tables.description.required";
+
+ /// Error: the row changed or was deleted meanwhile.
+ public const string NotFound = "tables.not-found";
+
+ /// Import error: the header has no code column.
+ public const string CsvNoCode = "tables.csv.no-code";
+
+ /// Import error: a value cannot be read.
+ public const string CsvBadValue = "tables.csv.bad-value";
+
+ /// Import error: unknown column (a warning in the result: the column is ignored).
+ public const string CsvUnknownColumn = "tables.csv.unknown-column";
+
+ private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
+ private static readonly NullabilityInfoContext Nullability = new();
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly AuditTrail _audit;
+ private readonly ICacheProvider _cache;
+ private readonly CompanyFiscalContext _fiscal;
+ private readonly TableCatalog _catalog;
+
+ /// Creates the service.
+ /// Opens the company databases.
+ /// Checks permissions.
+ /// Writes the history.
+ /// The cache of the rows.
+ /// The fiscal pack of each company.
+ /// The tables.
+ public TableService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache, CompanyFiscalContext fiscal, TableCatalog catalog)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(permissions);
+ ArgumentNullException.ThrowIfNull(audit);
+ ArgumentNullException.ThrowIfNull(cache);
+ ArgumentNullException.ThrowIfNull(fiscal);
+ ArgumentNullException.ThrowIfNull(catalog);
+ _factory = factory;
+ _permissions = permissions;
+ _audit = audit;
+ _cache = cache;
+ _fiscal = fiscal;
+ _catalog = catalog;
+ }
+
+ /// The tables.
+ public TableCatalog Catalog => _catalog;
+
+ /// Every row of a table, from the cache (disabled ones included), ordered by code.
+ /// The entity.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The rows.
+ public async Task> AllAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
+ return await RowsAsync(company, _catalog.Get(), cancellationToken).ConfigureAwait(false);
+ }
+
+ /// The rows still in use (not disabled), for the choices on other records.
+ /// The entity.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The rows.
+ public async Task> ActiveAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new() =>
+ [.. (await AllAsync(actor, companyCode, cancellationToken).ConfigureAwait(false)).Where(r => !r.Disabled)];
+
+ /// A page of a table for the grid.
+ /// The entity.
+ /// Who reads.
+ /// The company.
+ /// Search, filters, ordering and page.
+ /// Cancellation.
+ /// The page.
+ public async Task> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ ArgumentNullException.ThrowIfNull(query);
+ var rows = await AllAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
+ return _catalog.Get().Fields.Apply(rows, query);
+ }
+
+ /// One row, read from the database.
+ /// The entity.
+ /// Who reads.
+ /// The company.
+ /// The id.
+ /// Cancellation.
+ /// The row, or .
+ public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ return await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Checks a row without saving it: the messages next to the fields.
+ /// The entity.
+ /// Who checks.
+ /// The company.
+ /// The row (normalized in place: trimmed code in upper case, derived fields).
+ /// Cancellation.
+ /// Errors and warnings.
+ public async Task> ValidateAsync(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ ArgumentNullException.ThrowIfNull(row);
+ var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
+ var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ return await CheckAsync(uow, pack, _catalog.Get(), row, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Saves a row: inserts it when is 0, updates it otherwise.
+ /// The entity.
+ /// Who saves.
+ /// The company.
+ /// The row.
+ /// Cancellation.
+ /// The saved row, with its id and new row version.
+ /// A rule failed; has Field:code.
+ /// Someone else changed the row meanwhile.
+ public async Task SaveAsync(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ ArgumentNullException.ThrowIfNull(row);
+ var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
+ var definition = _catalog.Get();
+ var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
+ await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
+ {
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ Throw(await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false));
+ await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
+ return row;
+ }
+
+ /// Deletes a row, or disables it when other records use it.
+ /// The entity.
+ /// Who deletes.
+ /// The company.
+ /// The row.
+ /// Cancellation.
+ /// What happened.
+ /// No such row.
+ public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
+ var definition = _catalog.Get();
+ var outcome = TableDeleteOutcome.Deleted;
+ try
+ {
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ var repository = uow.Repository();
+ var before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
+ await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (DbException)
+ {
+ // A foreign key refused the delete: the row is used, so it is only hidden from new choices.
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ var repository = uow.Repository();
+ var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
+ if (!row.Disabled)
+ {
+ var before = Clone(row);
+ row.Disabled = true;
+ await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Update, id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ outcome = TableDeleteOutcome.Disabled;
+ }
+
+ await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
+ return outcome;
+ }
+
+ /// Writes a table as CSV (Italian format: ;, decimal comma, byte order mark).
+ /// The entity.
+ /// Who exports.
+ /// The company.
+ /// The stream; left open.
+ /// Cancellation.
+ /// The rows written.
+ public async Task ExportCsvAsync(Actor actor, string companyCode, Stream output, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ ArgumentNullException.ThrowIfNull(output);
+ var rows = await AllAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
+ var columns = _catalog.Get().CsvColumns;
+ await using var writer = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
+ await writer.WriteRowAsync(columns.Select(c => (object?)c.Header), cancellationToken).ConfigureAwait(false);
+ foreach (var row in rows)
+ {
+ await writer.WriteRowAsync(columns.Select(c => Export(c.Property.GetValue(row))), cancellationToken).ConfigureAwait(false);
+ }
+
+ return rows.Count;
+ }
+
+ ///
+ /// Imports a CSV with the columns of the export (any order, missing columns keep their value): rows are matched by
+ /// code, new codes are inserted. Nothing is saved unless every row passes the rules.
+ ///
+ /// The entity.
+ /// Who imports.
+ /// The company.
+ /// The CSV.
+ /// Cancellation.
+ /// Counts and errors.
+ public async Task ImportCsvAsync(Actor actor, string companyCode, Stream content, CancellationToken cancellationToken = default)
+ where T : CodedEntity, new()
+ {
+ ArgumentNullException.ThrowIfNull(content);
+ var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
+ var definition = _catalog.Get();
+ var lines = await CsvReader.ReadAsync(content, null, cancellationToken).ConfigureAwait(false);
+ if (lines.Count == 0)
+ {
+ return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]);
+ }
+
+ var byHeader = definition.CsvColumns.ToDictionary(c => c.Header, StringComparer.OrdinalIgnoreCase);
+ var header = lines[0].Select(h => byHeader.GetValueOrDefault(h.Trim())).ToArray();
+ if (!header.Any(c => c?.Property.Name == nameof(CodedEntity.Code)))
+ {
+ return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]);
+ }
+
+ var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
+ var errors = new List();
+ var inserted = 0;
+ var updated = 0;
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ var existing = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items
+ .GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var pending = new List();
+
+ for (var i = 1; i < lines.Count; i++)
+ {
+ var line = lines[i];
+ var rowNumber = i + 1;
+ var codeIndex = Array.FindIndex(header, c => c?.Property.Name == nameof(CodedEntity.Code));
+ var code = codeIndex < line.Count ? line[codeIndex].Trim() : string.Empty;
+ var row = existing.TryGetValue(code, out var found) ? found : new T();
+ var rowErrors = false;
+ for (var c = 0; c < header.Length && c < line.Count; c++)
+ {
+ if (header[c] is not { } column)
+ {
+ continue;
+ }
+
+ if (TryParse(line[c], column.Property, out var value))
+ {
+ column.Property.SetValue(row, value);
+ }
+ else
+ {
+ errors.Add(new TableImportError(rowNumber, column.Header, CsvBadValue));
+ rowErrors = true;
+ }
+ }
+
+ if (!seen.Add(row.Code.Trim()))
+ {
+ errors.Add(new TableImportError(rowNumber, "code", CodeDuplicate));
+ continue;
+ }
+
+ if (rowErrors)
+ {
+ continue;
+ }
+
+ var problems = await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false);
+ errors.AddRange(problems.Where(p => !p.IsWarning).Select(p => new TableImportError(rowNumber, TableDefinition.SnakeCase(p.Field), p.Code)));
+ pending.Add(row);
+ }
+
+ if (errors.Count > 0)
+ {
+ return new TableImportResult(0, 0, errors);
+ }
+
+ foreach (var row in pending)
+ {
+ if (row.Id == 0)
+ {
+ inserted++;
+ }
+ else
+ {
+ updated++;
+ }
+
+ await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false);
+ }
+
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
+ return new TableImportResult(inserted, updated, []);
+ }
+
+ /// Saves rows without permission checks or rules: the seeders (§14), inside their own unit of work.
+ /// The entity.
+ /// The company unit of work.
+ /// The row.
+ /// Who writes, such as system.
+ /// Cancellation.
+ /// A task.
+ internal Task WriteAsync(IUnitOfWork unitOfWork, T row, string userName, CancellationToken cancellationToken)
+ where T : CodedEntity, new() =>
+ WriteAsync(unitOfWork, _catalog.Get(), row, userName, cancellationToken);
+
+ /// Forgets the cached rows of every table of a company (after the seeders).
+ /// The company.
+ /// Cancellation.
+ /// A task.
+ public ValueTask InvalidateAllAsync(string companyCode, CancellationToken cancellationToken = default) =>
+ _cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "tables"), cancellationToken);
+
+ private static async Task> CheckAsync(
+ IUnitOfWork uow, IFiscalPack pack, TableDefinition definition, T row, CancellationToken cancellationToken)
+ where T : CodedEntity, new()
+ {
+ row.Code = definition.KeepCodeCase ? row.Code.Trim() : row.Code.Trim().ToUpperInvariant();
+ row.Description = row.Description.Trim();
+ definition.Complete?.Invoke(row, pack);
+
+ var context = new TableRuleContext(uow, pack);
+ if (row.Code.Length == 0)
+ {
+ context.Error(nameof(CodedEntity.Code), CodeRequired);
+ }
+ else if (row.Code.Length > definition.CodeLength)
+ {
+ context.Error(nameof(CodedEntity.Code), CodeTooLong);
+ }
+ else
+ {
+ var code = row.Code;
+ var id = row.Id;
+ var query = Query.For().Where(x => x.Code == code && x.Id != id);
+ if (definition.SameKey is { } sameKey)
+ {
+ query = query.Where(sameKey(row));
+ }
+
+ if (await uow.Repository().CountAsync(query, cancellationToken).ConfigureAwait(false) > 0)
+ {
+ context.Error(nameof(CodedEntity.Code), CodeDuplicate);
+ }
+ }
+
+ if (row.Description.Length == 0)
+ {
+ context.Error(nameof(CodedEntity.Description), DescriptionRequired);
+ }
+
+ foreach (var rule in definition.Rules)
+ {
+ await rule(row, context, cancellationToken).ConfigureAwait(false);
+ }
+
+ return context.Problems;
+ }
+
+ private static void Throw(IReadOnlyList problems)
+ {
+ var errors = problems.Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
+ if (errors.Count > 0)
+ {
+ throw new ValidationFailedException(errors);
+ }
+ }
+
+ private static T Clone(T row)
+ where T : class, new()
+ {
+ var copy = new T();
+ foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite))
+ {
+ property.SetValue(copy, property.GetValue(row));
+ }
+
+ return copy;
+ }
+
+ private static object? Export(object? value) => value switch
+ {
+ bool b => b ? "1" : "0",
+ DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
+ Enum e => e.ToString(),
+ _ => value,
+ };
+
+ private static bool TryParse(string text, PropertyInfo property, out object? value)
+ {
+ text = text.Trim();
+ var type = property.PropertyType;
+ var target = Nullable.GetUnderlyingType(type) ?? type;
+ value = null;
+ if (text.Length == 0)
+ {
+ if (target == typeof(string))
+ {
+ value = Nullability.Create(property).WriteState == NullabilityState.Nullable ? null : string.Empty;
+ return true;
+ }
+
+ if (Nullable.GetUnderlyingType(type) is null)
+ {
+ value = Activator.CreateInstance(target);
+ }
+
+ return true;
+ }
+
+ if (target == typeof(string))
+ {
+ value = text;
+ return true;
+ }
+
+ if (target == typeof(bool))
+ {
+ var lower = text.ToLowerInvariant();
+ value = lower is "1" or "true" or "si" or "sì" or "s" or "x" or "vero";
+ return value is true || lower is "0" or "false" or "no" or "n" or "falso";
+ }
+
+ if (target == typeof(int) || target == typeof(long) || target == typeof(decimal))
+ {
+ // Italian (1.234,5) or invariant (1234.5): a comma is always the decimal point.
+ var normalized = text.Contains(',', StringComparison.Ordinal) ? text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : text;
+ if (!decimal.TryParse(normalized, NumberStyles.Number, CultureInfo.InvariantCulture, out var number))
+ {
+ return false;
+ }
+
+ if (target == typeof(decimal))
+ {
+ value = number;
+ return true;
+ }
+
+ if (decimal.Truncate(number) != number)
+ {
+ return false;
+ }
+
+ value = target == typeof(int) ? (object)(int)number : (long)number;
+ return true;
+ }
+
+ if (target == typeof(DateOnly))
+ {
+ var ok = DateOnly.TryParseExact(text, ["yyyy-MM-dd", "dd/MM/yyyy", "d/M/yyyy"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var date);
+ value = date;
+ return ok;
+ }
+
+ if (target.IsEnum)
+ {
+ var ok = Enum.TryParse(target, text, ignoreCase: true, out var parsed) && Enum.IsDefined(target, parsed!);
+ value = parsed;
+ return ok;
+ }
+
+ return false;
+ }
+
+ private async Task WriteAsync(IUnitOfWork uow, TableDefinition definition, T row, string userName, CancellationToken cancellationToken)
+ where T : CodedEntity, new()
+ {
+ var repository = uow.Repository();
+ if (definition.SingleDefault is { } flag && flag.Compile()(row))
+ {
+ await ClearOtherDefaultsAsync(repository, flag, row.Id, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (row.Id == 0)
+ {
+ row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, userName, cancellationToken).ConfigureAwait(false);
+ return;
+ }
+
+ var before = await repository.GetAsync(row.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
+ await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, userName, cancellationToken).ConfigureAwait(false);
+ }
+
+ private static async Task ClearOtherDefaultsAsync(IRepository repository, System.Linq.Expressions.Expression> flag, long id, CancellationToken cancellationToken)
+ where T : CodedEntity, new()
+ {
+ var others = await repository.ListAsync(Query.For().Where(flag).Where(x => x.Id != id), cancellationToken).ConfigureAwait(false);
+ var property = (PropertyInfo)((System.Linq.Expressions.MemberExpression)flag.Body).Member;
+ foreach (var other in others.Items)
+ {
+ property.SetValue(other, false);
+ await repository.UpdateAsync(other, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ private async Task> RowsAsync(string company, TableDefinition definition, CancellationToken cancellationToken)
+ where T : CodedEntity, new() =>
+ await _cache.GetOrCreateAsync>(
+ CacheKeys.For(company, "tables", definition.Key),
+ async ct =>
+ {
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
+ var page = await uow.Repository().ListAsync(Query.For().OrderBy(x => x.Code), ct).ConfigureAwait(false);
+ return [.. page.Items];
+ },
+ CacheTime,
+ cancellationToken).ConfigureAwait(false);
+
+ private ValueTask InvalidateAsync(string company, TableDefinition definition, CancellationToken cancellationToken) =>
+ _cache.PublishInvalidationAsync(CacheKeys.For(company, "tables", definition.Key), cancellationToken);
+
+ private async Task DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
+ {
+ 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.");
+ }
+
+ await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
+ return company;
+ }
+}
diff --git a/src/Khaemhat.Core/Tables/BaseTables.cs b/src/Khaemhat.Core/Tables/BaseTables.cs
new file mode 100644
index 0000000..af2378d
--- /dev/null
+++ b/src/Khaemhat.Core/Tables/BaseTables.cs
@@ -0,0 +1,469 @@
+using Khaemhat.Core.Entities;
+using Khaemhat.Core.Tax;
+
+namespace Khaemhat.Core.Tables;
+
+/// A row of a company table with a code the users type and a description (SPEC §11.1).
+public interface ICodedRecord : IEntity
+{
+ /// The code, unique in the table.
+ string Code { get; set; }
+
+ /// The description (or the name).
+ string Description { get; set; }
+
+ /// Hidden from choices on new records; kept for old ones.
+ bool Disabled { get; set; }
+}
+
+/// Base class of the coded tables.
+public abstract class CodedEntity : Entity, ICodedRecord, IDemoMarkable
+{
+ ///
+ public string Code { get; set; } = string.Empty;
+
+ ///
+ public string Description { get; set; } = string.Empty;
+
+ ///
+ public bool Disabled { get; set; }
+
+ ///
+ public bool IsDemo { get; set; }
+}
+
+/// A country (ISO 3166-1).
+public sealed class Country : CodedEntity
+{
+ /// ISO 3166-1 alpha-3 code.
+ public string? Iso3 { get; set; }
+
+ /// Member of the European Union (VIES, Intrastat, intra-EU VAT).
+ public bool EuMember { get; set; }
+
+ /// The prefix of VAT numbers, when different from the code (Greece: EL).
+ public string? VatPrefix { get; set; }
+
+ /// The usual currency (ISO 4217).
+ public string? CurrencyCode { get; set; }
+}
+
+/// An Italian province (code = the two-letter abbreviation).
+public sealed class Province : CodedEntity
+{
+ /// The region.
+ public string? Region { get; set; }
+}
+
+/// An Italian municipality (code = cadastral code, used by the fiscal code).
+public sealed class Municipality : CodedEntity
+{
+ /// The province abbreviation.
+ public string ProvinceCode { get; set; } = string.Empty;
+
+ /// The region.
+ public string? Region { get; set; }
+
+ /// The ISTAT code (6 digits).
+ public string? IstatCode { get; set; }
+
+ /// The postal codes, comma separated (one for most municipalities, a range for large cities).
+ public string? PostalCodes { get; set; }
+}
+
+/// A currency (ISO 4217).
+public sealed class Currency : CodedEntity
+{
+ /// The symbol, such as €.
+ public string? Symbol { get; set; }
+
+ /// Decimals of amounts.
+ public int Decimals { get; set; } = 2;
+}
+
+/// An exchange rate: units of the currency for one euro on a day (ECB reference rate or manual).
+public sealed class ExchangeRate : Entity
+{
+ /// The currency (ISO 4217).
+ public string CurrencyCode { get; set; } = string.Empty;
+
+ /// The day.
+ public DateOnly RateDate { get; set; }
+
+ /// Units of the currency for one euro.
+ public decimal Rate { get; set; }
+
+ /// Where the rate comes from: ECB or MANUAL.
+ public string Source { get; set; } = "MANUAL";
+}
+
+/// A unit of measure.
+public sealed class UnitOfMeasure : CodedEntity
+{
+ /// Decimals allowed in quantities.
+ public int Decimals { get; set; }
+
+ /// The text written in UnitaMisura of the e-invoice, when different from the code.
+ public string? EInvoiceCode { get; set; }
+}
+
+/// A VAT code (mockup 076).
+public sealed class TaxCode : CodedEntity
+{
+ /// The rate in percent.
+ public decimal Rate { get; set; }
+
+ /// The nature for zero-rate operations (N1...N7).
+ public string? Nature { get; set; }
+
+ /// The kind of operation, from rate and nature.
+ public TaxCodeKind Kind { get; set; }
+
+ /// When the tax becomes due.
+ public TaxExigibility Exigibility { get; set; }
+
+ /// Share of the purchase tax that cannot be deducted.
+ public decimal NonDeductiblePercent { get; set; }
+
+ /// The law printed on the invoice.
+ public string? LegalReference { get; set; }
+
+ /// First day of validity.
+ public DateOnly? ValidFrom { get; set; }
+
+ /// Last day of validity.
+ public DateOnly? ValidTo { get; set; }
+
+ /// The VAT account for sales (ledger, M7).
+ public string? SalesAccountCode { get; set; }
+
+ /// The VAT account for purchases (ledger, M7).
+ public string? PurchaseAccountCode { get; set; }
+}
+
+/// A payment method (MP01...MP23).
+public sealed class PaymentMethod : CodedEntity
+{
+ /// The FatturaPA code, such as MP05.
+ public string EInvoiceCode { get; set; } = "MP05";
+
+ /// Whether a bank of the customer (RiBa, direct debit) or of the company (transfer) is needed.
+ public bool NeedsBank { get; set; }
+}
+
+/// Payment terms with their installments (lines).
+public sealed class PaymentTerm : CodedEntity
+{
+ /// The payment method.
+ public long? PaymentMethodId { get; set; }
+
+ /// The FatturaPA condition: TP01 installments, TP02 full, TP03 advance.
+ public string Condition { get; set; } = "TP02";
+
+ /// All the VAT on the first installment.
+ public bool VatOnFirstInstallment { get; set; }
+}
+
+/// An installment of payment terms.
+public sealed class PaymentTermLine : Entity
+{
+ /// The payment terms.
+ public long PaymentTermId { get; set; }
+
+ /// The order of the installment, from 1.
+ public int Number { get; set; }
+
+ /// Days from the document date.
+ public int Days { get; set; }
+
+ /// Move the due date to the end of the month.
+ public bool EndOfMonth { get; set; }
+
+ /// A fixed day of the month after the end-of-month move, such as 10.
+ public int? FixedDay { get; set; }
+
+ /// Share of the amount, in percent.
+ public decimal Percent { get; set; }
+}
+
+/// A bank account of the company.
+public sealed class BankAccount : CodedEntity
+{
+ /// The bank.
+ public string? BankName { get; set; }
+
+ /// The IBAN, compact.
+ public string? Iban { get; set; }
+
+ /// The BIC.
+ public string? Bic { get; set; }
+
+ /// The SIA code for RiBa files.
+ public string? SiaCode { get; set; }
+
+ /// The CBI CUC code.
+ public string? CucCode { get; set; }
+
+ /// The ledger account (M7).
+ public string? AccountCode { get; set; }
+
+ /// The account proposed on documents.
+ public bool IsDefault { get; set; }
+}
+
+/// A sales agent (code + name in ).
+public sealed class Salesperson : CodedEntity
+{
+ /// The e-mail address.
+ public string? Email { get; set; }
+
+ /// The phone.
+ public string? Phone { get; set; }
+
+ /// The usual commission, in percent.
+ public decimal CommissionPercent { get; set; }
+
+ /// Subject to ENASARCO contributions.
+ public bool Enasarco { get; set; }
+}
+
+/// A carrier (code + name).
+public sealed class Carrier : CodedEntity
+{
+ /// The VAT number.
+ public string? VatNumber { get; set; }
+
+ /// The address.
+ public string? Address { get; set; }
+
+ /// The town.
+ public string? City { get; set; }
+
+ /// The phone.
+ public string? Phone { get; set; }
+
+ /// The e-mail address.
+ public string? Email { get; set; }
+
+ /// The registration number in the haulage register.
+ public string? RegisterNumber { get; set; }
+}
+
+/// Who pays the transport (porto: franco, assegnato...).
+public sealed class ShippingTerm : CodedEntity;
+
+/// Who carries the goods (mittente, destinatario, vettore).
+public sealed class TransportMean : CodedEntity;
+
+/// The appearance of the goods on the delivery note (cartoni, bancali...).
+public sealed class GoodsAppearance : CodedEntity;
+
+/// An Incoterms rule.
+public sealed class DeliveryTerm : CodedEntity;
+
+/// The reason of the transport (vendita, conto visione...).
+public sealed class TransportReason : CodedEntity;
+
+/// What a stock movement does to the quantity on hand.
+public enum StockEffect
+{
+ /// No effect on quantities.
+ None = 0,
+
+ /// Increases the stock (load).
+ Load = 1,
+
+ /// Decreases the stock (unload).
+ Unload = 2,
+}
+
+/// A warehouse movement reason.
+public sealed class InventoryReason : CodedEntity
+{
+ /// The effect on the quantity.
+ public StockEffect Effect { get; set; }
+
+ /// Whether it changes the stock value (purchases, sales) or only quantities (transfers).
+ public bool AffectsValue { get; set; } = true;
+
+ /// Whether it is a transfer between warehouses (needs a destination).
+ public bool IsTransfer { get; set; }
+}
+
+/// A warehouse.
+public sealed class Warehouse : CodedEntity
+{
+ /// The address.
+ public string? Address { get; set; }
+
+ /// The town.
+ public string? City { get; set; }
+
+ /// The province abbreviation.
+ public string? ProvinceCode { get; set; }
+
+ /// The warehouse proposed on documents.
+ public bool IsDefault { get; set; }
+}
+
+/// A category of items, on up to three levels.
+public sealed class ItemCategory : CodedEntity
+{
+ /// The parent category.
+ public long? ParentId { get; set; }
+
+ /// The level, 1 to 3.
+ public int Level { get; set; } = 1;
+}
+
+/// A category of customers and suppliers.
+public sealed class PartyCategory : CodedEntity;
+
+/// A price list (the prices are in item_prices, mockup 018).
+public sealed class PriceList : CodedEntity
+{
+ /// The currency (ISO 4217).
+ public string CurrencyCode { get; set; } = "EUR";
+
+ /// Prices include VAT (retail).
+ public bool VatIncluded { get; set; }
+
+ /// First day of validity.
+ public DateOnly? ValidFrom { get; set; }
+
+ /// Last day of validity.
+ public DateOnly? ValidTo { get; set; }
+
+ /// The list this one derives from.
+ public long? BasePriceListId { get; set; }
+
+ /// Change applied to the base list, in percent (negative for a discount).
+ public decimal MarkupPercent { get; set; }
+
+ /// Rounding step of derived prices, such as 0.05; zero for none.
+ public decimal RoundingStep { get; set; }
+}
+
+/// A discount policy: a chain of discounts such as 10+5.
+public sealed class DiscountPolicy : CodedEntity
+{
+ /// The chain of discounts in percent, separated by +.
+ public string Formula { get; set; } = string.Empty;
+}
+
+/// The family of a document numerator.
+public enum NumeratorKind
+{
+ /// Quotations.
+ Quotation = 0,
+
+ /// Customer orders.
+ SalesOrder = 1,
+
+ /// Delivery notes.
+ DeliveryNote = 2,
+
+ /// Sales invoices and credit notes (no gaps).
+ SalesInvoice = 3,
+
+ /// Supplier orders.
+ PurchaseOrder = 4,
+
+ /// Purchase protocol.
+ PurchaseInvoice = 5,
+
+ /// Warehouse movements.
+ Inventory = 6,
+
+ /// Journal entries (no gaps).
+ Journal = 7,
+
+ /// Anything else.
+ Other = 8,
+}
+
+/// A document numerator for a year (assignment at confirmation arrives with the documents, M5).
+public sealed class DocumentNumerator : CodedEntity
+{
+ /// The family.
+ public NumeratorKind Kind { get; set; }
+
+ /// The section (sezionale), such as A; empty for the main one.
+ public string? Section { get; set; }
+
+ /// The year.
+ public int Year { get; set; }
+
+ /// The prefix.
+ public string? Prefix { get; set; }
+
+ /// The format, such as {prefix}/{year}/{number:D6}.
+ public string Format { get; set; } = "{number}/{year}";
+
+ /// The last number assigned.
+ public long LastNumber { get; set; }
+
+ /// Whether gaps are allowed (never for invoices, credit notes and final entries).
+ public bool GapsAllowed { get; set; }
+}
+
+/// A type of document: the links between a document and its numerator, warehouse reason and SDI type.
+public sealed class DocumentType : CodedEntity
+{
+ /// The family of document.
+ public NumeratorKind Kind { get; set; }
+
+ /// The numerator.
+ public long? NumeratorId { get; set; }
+
+ /// The warehouse reason.
+ public long? InventoryReasonId { get; set; }
+
+ /// The SDI document type (TD01...).
+ public string? EInvoiceType { get; set; }
+
+ /// The journal template (ledger, M7).
+ public string? JournalTemplateCode { get; set; }
+
+ /// The VAT register (ledger, M7).
+ public string? VatRegisterCode { get; set; }
+
+ /// The print template.
+ public string? PrintTemplate { get; set; }
+}
+
+/// A cost centre.
+public sealed class CostCenter : CodedEntity
+{
+ /// The parent cost centre.
+ public long? ParentId { get; set; }
+}
+
+/// The state of a job.
+public enum JobStatus
+{
+ /// Open.
+ Open = 0,
+
+ /// Suspended.
+ Suspended = 1,
+
+ /// Closed.
+ Closed = 2,
+}
+
+/// A job (commessa).
+public sealed class Job : CodedEntity
+{
+ /// The customer, when the job is for one.
+ public long? PartyId { get; set; }
+
+ /// The start.
+ public DateOnly? StartDate { get; set; }
+
+ /// The end.
+ public DateOnly? EndDate { get; set; }
+
+ /// The state.
+ public JobStatus Status { get; set; }
+}
diff --git a/src/Khaemhat.Core/Tables/CompanyProfile.cs b/src/Khaemhat.Core/Tables/CompanyProfile.cs
new file mode 100644
index 0000000..e3b3d34
--- /dev/null
+++ b/src/Khaemhat.Core/Tables/CompanyProfile.cs
@@ -0,0 +1,180 @@
+using Khaemhat.Core.Entities;
+using Khaemhat.Core.Tax;
+
+namespace Khaemhat.Core.Tables;
+
+/// The data of the company itself, one row per company database (SPEC §11.1, mockup 075).
+public sealed class CompanyProfile : Entity
+{
+ /// The company name.
+ public string LegalName { get; set; } = string.Empty;
+
+ /// The name written on fiscal documents, when different.
+ public string? FiscalName { get; set; }
+
+ /// The VAT number, without the country prefix.
+ public string? VatNumber { get; set; }
+
+ /// The tax code.
+ public string? TaxCode { get; set; }
+
+ /// The province of the business register (REA).
+ public string? ReaOffice { get; set; }
+
+ /// The number in the business register (REA).
+ public string? ReaNumber { get; set; }
+
+ /// The share capital.
+ public decimal? ShareCapital { get; set; }
+
+ /// Sole shareholder: