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: SU one, SM more; empty when it does not apply. + public string? Shareholders { get; set; } + + /// Liquidation: LN not in liquidation, LS in liquidation. + public string? LiquidationStatus { get; set; } + + /// The street. + public string? Address { get; set; } + + /// The street number. + public string? StreetNumber { get; set; } + + /// The postal code. + public string? PostalCode { get; set; } + + /// The town. + public string? City { get; set; } + + /// The province abbreviation. + public string? ProvinceCode { get; set; } + + /// The country of the address (ISO 3166-1). + public string? AddressCountry { get; set; } + + /// The phone. + public string? Phone { get; set; } + + /// The e-mail address. + public string? Email { get; set; } + + /// The certified e-mail address. + public string? Pec { get; set; } + + /// The web site. + public string? Website { get; set; } + + /// The tax regime, such as RF01. + public string TaxRegime { get; set; } = "RF01"; + + /// The company's own recipient code for incoming e-invoices. + public string? RecipientCode { get; set; } + + /// The logo (an attachment of entity company_profile). + public long? LogoAttachmentId { get; set; } + + /// The bank account proposed on documents. + public long? DefaultBankAccountId { get; set; } + + /// The accounting currency (ISO 4217). + public string CurrencyCode { get; set; } = "EUR"; + + /// The country whose fiscal pack applies (ISO 3166-1), from KHAEMHAT_COUNTRY at creation. + public string Country { get; set; } = "IT"; + + /// The VAT settlement periodicity. + public VatPeriodicity VatPeriodicity { get; set; } + + /// The deductible share for companies with exempt operations (pro-rata), in percent; 100 when it does not apply. + public decimal ProRataPercent { get; set; } = 100m; + + /// VAT on cash basis (art. 32-bis DL 83/2012). + public bool CashVat { get; set; } + + /// The first month of the fiscal year (1 for calendar years). + public int FiscalYearStartMonth { get; set; } = 1; + + /// The transmitter of e-invoices, when not the company: country. + public string? TransmitterCountry { get; set; } + + /// The transmitter of e-invoices: tax identifier. + public string? TransmitterId { get; set; } + + /// The intermediary that sends the returns (LIPE, F24): name. + public string? IntermediaryName { get; set; } + + /// The intermediary: tax code. + public string? IntermediaryTaxCode { get; set; } + + /// The text printed at the bottom of documents. + public string? FooterNotes { get; set; } +} + +/// The state of a fiscal year (SPEC §11.1, mockup 052). +public enum FiscalYearStatus +{ + /// Entries allowed. + Open = 0, + + /// Closing entries in progress: only closing entries. + Closing = 1, + + /// Read only. + Closed = 2, +} + +/// A fiscal year. +public sealed class FiscalYear : Entity +{ + /// The code, such as 2026 or 2026/27. + public string Code { get; set; } = string.Empty; + + /// The first day. + public DateOnly StartDate { get; set; } + + /// The last day. + public DateOnly EndDate { get; set; } + + /// The state. + public FiscalYearStatus Status { get; set; } + + /// The first page number of the journal printed for this year. + public int JournalFirstPage { get; set; } = 1; + + /// The number of the last final journal entry. + public long LastFinalEntryNumber { get; set; } + + /// The date of the last final journal entry. + public DateOnly? LastFinalEntryDate { get; set; } +} + +/// The state of a fiscal period. +public enum FiscalPeriodStatus +{ + /// Documents and entries allowed. + Open = 0, + + /// The VAT of the period was settled: no new entries with VAT. + Settled = 1, + + /// Locked: no new documents or entries dated in the period. + Locked = 2, +} + +/// A month of a fiscal year. +public sealed class FiscalPeriod : Entity +{ + /// The fiscal year. + public long FiscalYearId { get; set; } + + /// The number in the year, from 1. + public int Number { get; set; } + + /// The first day. + public DateOnly StartDate { get; set; } + + /// The last day. + public DateOnly EndDate { get; set; } + + /// The state. + public FiscalPeriodStatus Status { get; set; } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_010_CreateCompanyProfile.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_010_CreateCompanyProfile.cs new file mode 100644 index 0000000..04df548 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_010_CreateCompanyProfile.cs @@ -0,0 +1,83 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The company data and the fiscal years with their periods (SPEC §11.1, mockup 075 and 052). +[Migration(20261111_010, "create_company_profile")] +public sealed class M20261111_010_CreateCompanyProfile : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("company_profile", t => + { + t.Id(); + t.String("legal_name", 200).NotNull(); + t.String("fiscal_name", 200); + t.String("vat_number", 28); + t.String("tax_code", 16); + t.String("rea_office", 2); + t.String("rea_number", 20); + t.Decimal("share_capital"); + t.String("shareholders", 2); + t.String("liquidation_status", 2); + t.String("address", 200); + t.String("street_number", 8); + t.String("postal_code", 10); + t.String("city", 100); + t.String("province_code", 2); + t.String("address_country", 2); + t.String("phone", 30); + t.String("email", 254); + t.String("pec", 254); + t.String("website", 200); + t.String("tax_regime", 4).NotNull(); + t.String("recipient_code", 7); + t.Int64("logo_attachment_id"); + t.Int64("default_bank_account_id"); + t.String("currency_code", 3).NotNull(); + t.String("country", 2).NotNull(); + t.String("vat_periodicity", 40).NotNull(); + t.Decimal("pro_rata_percent").NotNull(); + t.Bool("cash_vat").NotNull().Default(false); + t.Int32("fiscal_year_start_month").NotNull(); + t.String("transmitter_country", 2); + t.String("transmitter_id", 28); + t.String("intermediary_name", 200); + t.String("intermediary_tax_code", 16); + t.Text("footer_notes"); + t.AuditColumns(); + }); + + schema.CreateTable("fiscal_years", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.Date("start_date").NotNull(); + t.Date("end_date").NotNull(); + t.String("status", 40).NotNull(); + t.Int32("journal_first_page").NotNull(); + t.Int64("last_final_entry_number").NotNull(); + t.Date("last_final_entry_date"); + t.AuditColumns(); + t.Unique("ux_fiscal_years_code", "code"); + t.Unique("ux_fiscal_years_start_date", "start_date"); + }); + + schema.CreateTable("fiscal_periods", t => + { + t.Id(); + t.Int64("fiscal_year_id").NotNull(); + t.Int32("number").NotNull(); + t.Date("start_date").NotNull(); + t.Date("end_date").NotNull(); + t.String("status", 40).NotNull(); + t.AuditColumns(); + t.Unique("ux_fiscal_periods_fiscal_year_id_number", "fiscal_year_id", "number"); + t.Index("ix_fiscal_periods_start_date", "start_date"); + t.ForeignKey("fk_fiscal_periods_fiscal_year", "fiscal_year_id", "fiscal_years", ReferentialAction.Cascade); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_011_CreateGeographyAndCurrencies.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_011_CreateGeographyAndCurrencies.cs new file mode 100644 index 0000000..f52af45 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_011_CreateGeographyAndCurrencies.cs @@ -0,0 +1,95 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Countries, provinces, municipalities, currencies, exchange rates and units of measure (SPEC §11.1). +[Migration(20261111_011, "create_geography_and_currencies")] +public sealed class M20261111_011_CreateGeographyAndCurrencies : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("countries", t => + { + t.Id(); + t.String("code", 2).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("iso3", 3); + t.Bool("eu_member").NotNull().Default(false); + t.String("vat_prefix", 2); + t.String("currency_code", 3); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_countries_code", "code"); + }); + + schema.CreateTable("provinces", t => + { + t.Id(); + t.String("code", 2).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("region", 60); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_provinces_code", "code"); + }); + + schema.CreateTable("municipalities", t => + { + t.Id(); + t.String("code", 4).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("province_code", 2).NotNull(); + t.String("region", 60); + t.String("istat_code", 6); + t.String("postal_codes", 400); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_municipalities_code", "code"); + t.Index("ix_municipalities_description", "description"); + t.Index("ix_municipalities_province_code", "province_code"); + }); + + schema.CreateTable("currencies", t => + { + t.Id(); + t.String("code", 3).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("symbol", 5); + t.Int32("decimals").NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_currencies_code", "code"); + }); + + schema.CreateTable("exchange_rates", t => + { + t.Id(); + t.String("currency_code", 3).NotNull(); + t.Date("rate_date").NotNull(); + t.Decimal("rate").NotNull(); + t.String("source", 10).NotNull(); + t.AuditColumns(); + t.Unique("ux_exchange_rates_currency_code_rate_date", "currency_code", "rate_date"); + }); + + schema.CreateTable("units_of_measure", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int32("decimals").NotNull(); + t.String("e_invoice_code", 10); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_units_of_measure_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_012_CreateTaxAndPaymentTables.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_012_CreateTaxAndPaymentTables.cs new file mode 100644 index 0000000..c431495 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_012_CreateTaxAndPaymentTables.cs @@ -0,0 +1,110 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// VAT codes, payment methods and terms, bank accounts and salespeople (SPEC §11.1, mockup 076). +[Migration(20261111_012, "create_tax_and_payment_tables")] +public sealed class M20261111_012_CreateTaxAndPaymentTables : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("tax_codes", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Decimal("rate").NotNull(); + t.String("nature", 5); + t.String("kind", 40).NotNull(); + t.String("exigibility", 40).NotNull(); + t.Decimal("non_deductible_percent").NotNull(); + t.String("legal_reference", 200); + t.Date("valid_from"); + t.Date("valid_to"); + t.String("sales_account_code", 20); + t.String("purchase_account_code", 20); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_tax_codes_code", "code"); + }); + + schema.CreateTable("payment_methods", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("e_invoice_code", 4).NotNull(); + t.Bool("needs_bank").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_payment_methods_code", "code"); + }); + + schema.CreateTable("payment_terms", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("payment_method_id"); + t.String("condition", 4).NotNull(); + t.Bool("vat_on_first_installment").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_payment_terms_code", "code"); + t.ForeignKey("fk_payment_terms_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict); + }); + + schema.CreateTable("payment_term_lines", t => + { + t.Id(); + t.Int64("payment_term_id").NotNull(); + t.Int32("number").NotNull(); + t.Int32("days").NotNull(); + t.Bool("end_of_month").NotNull().Default(false); + t.Int32("fixed_day"); + t.Decimal("percent").NotNull(); + t.AuditColumns(); + t.Unique("ux_payment_term_lines_payment_term_id_number", "payment_term_id", "number"); + t.ForeignKey("fk_payment_term_lines_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Cascade); + }); + + schema.CreateTable("bank_accounts", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("bank_name", 100); + t.String("iban", 34); + t.String("bic", 11); + t.String("sia_code", 5); + t.String("cuc_code", 8); + t.String("account_code", 20); + t.Bool("is_default").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_bank_accounts_code", "code"); + }); + + schema.CreateTable("salespeople", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("email", 254); + t.String("phone", 30); + t.Decimal("commission_percent").NotNull(); + t.Bool("enasarco").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_salespeople_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_013_CreateLogisticsTables.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_013_CreateLogisticsTables.cs new file mode 100644 index 0000000..d643c5c --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_013_CreateLogisticsTables.cs @@ -0,0 +1,115 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Carriers, transport tables, warehouse reasons and warehouses (SPEC §11.1). +[Migration(20261111_013, "create_logistics_tables")] +public sealed class M20261111_013_CreateLogisticsTables : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("carriers", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("vat_number", 28); + t.String("address", 200); + t.String("city", 100); + t.String("phone", 30); + t.String("email", 254); + t.String("register_number", 30); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_carriers_code", "code"); + }); + + schema.CreateTable("shipping_terms", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_shipping_terms_code", "code"); + }); + + schema.CreateTable("transport_means", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_transport_means_code", "code"); + }); + + schema.CreateTable("goods_appearances", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_goods_appearances_code", "code"); + }); + + schema.CreateTable("delivery_terms", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_delivery_terms_code", "code"); + }); + + schema.CreateTable("transport_reasons", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_transport_reasons_code", "code"); + }); + + schema.CreateTable("inventory_reasons", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("effect", 40).NotNull(); + t.Bool("affects_value").NotNull().Default(false); + t.Bool("is_transfer").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_inventory_reasons_code", "code"); + }); + + schema.CreateTable("warehouses", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("address", 200); + t.String("city", 100); + t.String("province_code", 2); + t.Bool("is_default").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_warehouses_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_014_CreateCatalogTables.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_014_CreateCatalogTables.cs new file mode 100644 index 0000000..921750a --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_014_CreateCatalogTables.cs @@ -0,0 +1,135 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Categories, price lists, discounts, numerators, document types, cost centres and jobs (SPEC §11.1). +[Migration(20261111_014, "create_catalog_tables")] +public sealed class M20261111_014_CreateCatalogTables : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("item_categories", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("parent_id"); + t.Int32("level").NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_item_categories_code", "code"); + t.ForeignKey("fk_item_categories_parent", "parent_id", "item_categories", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_categories", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_party_categories_code", "code"); + }); + + schema.CreateTable("price_lists", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("currency_code", 3).NotNull(); + t.Bool("vat_included").NotNull().Default(false); + t.Date("valid_from"); + t.Date("valid_to"); + t.Int64("base_price_list_id"); + t.Decimal("markup_percent").NotNull(); + t.Decimal("rounding_step").NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_price_lists_code", "code"); + t.ForeignKey("fk_price_lists_base_price_list", "base_price_list_id", "price_lists", ReferentialAction.Restrict); + }); + + schema.CreateTable("discount_policies", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("formula", 60).NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_discount_policies_code", "code"); + }); + + schema.CreateTable("document_numerators", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("kind", 40).NotNull(); + t.String("section", 10); + t.Int32("year").NotNull(); + t.String("prefix", 10); + t.String("format", 60).NotNull(); + t.Int64("last_number").NotNull(); + t.Bool("gaps_allowed").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_document_numerators_code_year", "code", "year"); + }); + + schema.CreateTable("document_types", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("kind", 40).NotNull(); + t.Int64("numerator_id"); + t.Int64("inventory_reason_id"); + t.String("e_invoice_type", 4); + t.String("journal_template_code", 10); + t.String("vat_register_code", 10); + t.String("print_template", 60); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_document_types_code", "code"); + t.ForeignKey("fk_document_types_inventory_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict); + }); + + schema.CreateTable("cost_centers", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("parent_id"); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_cost_centers_code", "code"); + t.ForeignKey("fk_cost_centers_parent", "parent_id", "cost_centers", ReferentialAction.Restrict); + }); + + schema.CreateTable("jobs", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("party_id"); + t.Date("start_date"); + t.Date("end_date"); + t.String("status", 40).NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_jobs_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs new file mode 100644 index 0000000..a0d2894 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs @@ -0,0 +1,437 @@ +using Khaemhat.Core.Tables; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to company_profile. +public sealed class CompanyProfileMap : EntityMap +{ + /// Creates the map. + public CompanyProfileMap() + { + ToTable("company_profile"); + Map(x => x.LegalName).MaxLength(200); + Map(x => x.FiscalName).MaxLength(200); + Map(x => x.VatNumber).MaxLength(28); + Map(x => x.TaxCode).MaxLength(16); + Map(x => x.ReaOffice).MaxLength(2); + Map(x => x.ReaNumber).MaxLength(20); + Map(x => x.Shareholders).MaxLength(2); + Map(x => x.LiquidationStatus).MaxLength(2); + Map(x => x.Address).MaxLength(200); + Map(x => x.StreetNumber).MaxLength(8); + Map(x => x.PostalCode).MaxLength(10); + Map(x => x.City).MaxLength(100); + Map(x => x.ProvinceCode).MaxLength(2); + Map(x => x.AddressCountry).MaxLength(2); + Map(x => x.Phone).MaxLength(30); + Map(x => x.Email).MaxLength(254); + Map(x => x.Pec).MaxLength(254); + Map(x => x.Website).MaxLength(200); + Map(x => x.TaxRegime).MaxLength(4); + Map(x => x.RecipientCode).MaxLength(7); + Map(x => x.CurrencyCode).MaxLength(3); + Map(x => x.Country).MaxLength(2); + Map(x => x.TransmitterCountry).MaxLength(2); + Map(x => x.TransmitterId).MaxLength(28); + Map(x => x.IntermediaryName).MaxLength(200); + Map(x => x.IntermediaryTaxCode).MaxLength(16); + } +} + +/// Map of to fiscal_years. +public sealed class FiscalYearMap : EntityMap +{ + /// Creates the map. + public FiscalYearMap() + { + ToTable("fiscal_years"); + Map(x => x.Code).MaxLength(10); + } +} + +/// Map of to fiscal_periods. +public sealed class FiscalPeriodMap : EntityMap +{ + /// Creates the map. + public FiscalPeriodMap() + { + ToTable("fiscal_periods"); + } +} + +/// Map of to countries. +public sealed class CountryMap : EntityMap +{ + /// Creates the map. + public CountryMap() + { + ToTable("countries"); + Map(x => x.Code).MaxLength(2); + Map(x => x.Description).MaxLength(100); + Map(x => x.Iso3).MaxLength(3); + Map(x => x.VatPrefix).MaxLength(2); + Map(x => x.CurrencyCode).MaxLength(3); + } +} + +/// Map of to provinces. +public sealed class ProvinceMap : EntityMap +{ + /// Creates the map. + public ProvinceMap() + { + ToTable("provinces"); + Map(x => x.Code).MaxLength(2); + Map(x => x.Description).MaxLength(100); + Map(x => x.Region).MaxLength(60); + } +} + +/// Map of to municipalities. +public sealed class MunicipalityMap : EntityMap +{ + /// Creates the map. + public MunicipalityMap() + { + ToTable("municipalities"); + Map(x => x.Code).MaxLength(4); + Map(x => x.Description).MaxLength(100); + Map(x => x.ProvinceCode).MaxLength(2); + Map(x => x.Region).MaxLength(60); + Map(x => x.IstatCode).MaxLength(6); + Map(x => x.PostalCodes).MaxLength(400); + } +} + +/// Map of to currencies. +public sealed class CurrencyMap : EntityMap +{ + /// Creates the map. + public CurrencyMap() + { + ToTable("currencies"); + Map(x => x.Code).MaxLength(3); + Map(x => x.Description).MaxLength(100); + Map(x => x.Symbol).MaxLength(5); + } +} + +/// Map of to exchange_rates. +public sealed class ExchangeRateMap : EntityMap +{ + /// Creates the map. + public ExchangeRateMap() + { + ToTable("exchange_rates"); + Map(x => x.CurrencyCode).MaxLength(3); + Map(x => x.Source).MaxLength(10); + } +} + +/// Map of to units_of_measure. +public sealed class UnitOfMeasureMap : EntityMap +{ + /// Creates the map. + public UnitOfMeasureMap() + { + ToTable("units_of_measure"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.EInvoiceCode).MaxLength(10); + } +} + +/// Map of to tax_codes. +public sealed class TaxCodeMap : EntityMap +{ + /// Creates the map. + public TaxCodeMap() + { + ToTable("tax_codes"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Nature).MaxLength(5); + Map(x => x.LegalReference).MaxLength(200); + Map(x => x.SalesAccountCode).MaxLength(20); + Map(x => x.PurchaseAccountCode).MaxLength(20); + } +} + +/// Map of to payment_methods. +public sealed class PaymentMethodMap : EntityMap +{ + /// Creates the map. + public PaymentMethodMap() + { + ToTable("payment_methods"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.EInvoiceCode).MaxLength(4); + } +} + +/// Map of to payment_terms. +public sealed class PaymentTermMap : EntityMap +{ + /// Creates the map. + public PaymentTermMap() + { + ToTable("payment_terms"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Condition).MaxLength(4); + } +} + +/// Map of to payment_term_lines. +public sealed class PaymentTermLineMap : EntityMap +{ + /// Creates the map. + public PaymentTermLineMap() + { + ToTable("payment_term_lines"); + } +} + +/// Map of to bank_accounts. +public sealed class BankAccountMap : EntityMap +{ + /// Creates the map. + public BankAccountMap() + { + ToTable("bank_accounts"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.BankName).MaxLength(100); + Map(x => x.Iban).MaxLength(34); + Map(x => x.Bic).MaxLength(11); + Map(x => x.SiaCode).MaxLength(5); + Map(x => x.CucCode).MaxLength(8); + Map(x => x.AccountCode).MaxLength(20); + } +} + +/// Map of to salespeople. +public sealed class SalespersonMap : EntityMap +{ + /// Creates the map. + public SalespersonMap() + { + ToTable("salespeople"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Email).MaxLength(254); + Map(x => x.Phone).MaxLength(30); + } +} + +/// Map of to carriers. +public sealed class CarrierMap : EntityMap +{ + /// Creates the map. + public CarrierMap() + { + ToTable("carriers"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.VatNumber).MaxLength(28); + Map(x => x.Address).MaxLength(200); + Map(x => x.City).MaxLength(100); + Map(x => x.Phone).MaxLength(30); + Map(x => x.Email).MaxLength(254); + Map(x => x.RegisterNumber).MaxLength(30); + } +} + +/// Map of to shipping_terms. +public sealed class ShippingTermMap : EntityMap +{ + /// Creates the map. + public ShippingTermMap() + { + ToTable("shipping_terms"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to transport_means. +public sealed class TransportMeanMap : EntityMap +{ + /// Creates the map. + public TransportMeanMap() + { + ToTable("transport_means"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to goods_appearances. +public sealed class GoodsAppearanceMap : EntityMap +{ + /// Creates the map. + public GoodsAppearanceMap() + { + ToTable("goods_appearances"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to delivery_terms. +public sealed class DeliveryTermMap : EntityMap +{ + /// Creates the map. + public DeliveryTermMap() + { + ToTable("delivery_terms"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to transport_reasons. +public sealed class TransportReasonMap : EntityMap +{ + /// Creates the map. + public TransportReasonMap() + { + ToTable("transport_reasons"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to inventory_reasons. +public sealed class InventoryReasonMap : EntityMap +{ + /// Creates the map. + public InventoryReasonMap() + { + ToTable("inventory_reasons"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to warehouses. +public sealed class WarehouseMap : EntityMap +{ + /// Creates the map. + public WarehouseMap() + { + ToTable("warehouses"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Address).MaxLength(200); + Map(x => x.City).MaxLength(100); + Map(x => x.ProvinceCode).MaxLength(2); + } +} + +/// Map of to item_categories. +public sealed class ItemCategoryMap : EntityMap +{ + /// Creates the map. + public ItemCategoryMap() + { + ToTable("item_categories"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to party_categories. +public sealed class PartyCategoryMap : EntityMap +{ + /// Creates the map. + public PartyCategoryMap() + { + ToTable("party_categories"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to price_lists. +public sealed class PriceListMap : EntityMap +{ + /// Creates the map. + public PriceListMap() + { + ToTable("price_lists"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.CurrencyCode).MaxLength(3); + } +} + +/// Map of to discount_policies. +public sealed class DiscountPolicyMap : EntityMap +{ + /// Creates the map. + public DiscountPolicyMap() + { + ToTable("discount_policies"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Formula).MaxLength(60); + } +} + +/// Map of to document_numerators. +public sealed class DocumentNumeratorMap : EntityMap +{ + /// Creates the map. + public DocumentNumeratorMap() + { + ToTable("document_numerators"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Section).MaxLength(10); + Map(x => x.Prefix).MaxLength(10); + Map(x => x.Format).MaxLength(60); + } +} + +/// Map of to document_types. +public sealed class DocumentTypeMap : EntityMap +{ + /// Creates the map. + public DocumentTypeMap() + { + ToTable("document_types"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.EInvoiceType).MaxLength(4); + Map(x => x.JournalTemplateCode).MaxLength(10); + Map(x => x.VatRegisterCode).MaxLength(10); + Map(x => x.PrintTemplate).MaxLength(60); + } +} + +/// Map of to cost_centers. +public sealed class CostCenterMap : EntityMap +{ + /// Creates the map. + public CostCenterMap() + { + ToTable("cost_centers"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to jobs. +public sealed class JobMap : EntityMap +{ + /// Creates the map. + public JobMap() + { + ToTable("jobs"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Description).MaxLength(100); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs index f1b0f65..ba26feb 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Features.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -192,3 +192,51 @@ public interface IIntrastatExporter /// A task that completes when the file is written. Task WriteAsync(IntrastatReturn intrastatReturn, Stream output, CancellationToken cancellationToken); } + +/// A payment method of the base data. +/// The code. +/// The description. +/// The code of the e-invoice format. +/// Whether a bank is needed (transfer, bank receipt, direct debit). +public sealed record PaymentMethodTemplate(string Code, string Description, string EInvoiceCode, bool NeedsBank); + +/// An installment of payment terms of the base data. +/// Days from the document date. +/// Whether the due date moves to the end of the month. +/// Share of the amount, in percent. +public sealed record InstallmentTemplate(int Days, bool EndOfMonth, decimal Percent); + +/// Payment terms of the base data. +/// The code. +/// The description. +/// The payment method (a ). +/// The condition of the e-invoice format (installments, full, advance). +/// The installments. +public sealed record PaymentTermTemplate(string Code, string Description, string PaymentMethodCode, string Condition, IReadOnlyList Installments); + +/// A document type of the base data. +/// The code. +/// The description. +/// The family. +/// The numerator of the base data (FAT, DDT...), if the document is numbered by the company. +/// The warehouse reason of the base data (SCA, CAR...), if the document moves goods. +/// The type of the e-invoice format, if the document is sent electronically. +public sealed record DocumentTypeTemplate( + string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType); + +/// +/// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes +/// of the e-invoice format, and document types with their electronic type. The rest of the base data is the same in +/// every country. +/// +public interface IBaseTablesTemplate +{ + /// The payment methods. + IReadOnlyList PaymentMethods { get; } + + /// The payment terms. + IReadOnlyList PaymentTerms { get; } + + /// The document types. + IReadOnlyList DocumentTypes { get; } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs new file mode 100644 index 0000000..1b7b629 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs @@ -0,0 +1,70 @@ +using Khaemhat.Core.Tables; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The Italian rows of the base tables (SPEC §14): payment methods with the FatturaPA codes MP, the usual payment terms +/// (rimessa diretta, bonifico, RiBa at 30/60/90 days end of month) and the document types with their SDI type TD. +/// +public sealed class ItalianBaseTables : IBaseTablesTemplate +{ + private static readonly InstallmentTemplate Now = new(0, false, 100m); + + /// + public IReadOnlyList PaymentMethods { get; } = + [ + new("CONT", "Contanti", "MP01", false), + new("ASS", "Assegno", "MP02", false), + new("BON", "Bonifico bancario", "MP05", true), + new("CARTA", "Carta di pagamento", "MP08", false), + new("RIBA", "Ricevuta bancaria (RiBa)", "MP12", true), + new("MAV", "MAV", "MP13", true), + new("DOM", "Domiciliazione bancaria", "MP16", true), + new("SDD", "Addebito diretto SEPA (SDD Core)", "MP20", true), + new("SDDB", "Addebito diretto SEPA B2B", "MP21", true), + new("PAGOPA", "PagoPA", "MP23", false), + ]; + + /// + public IReadOnlyList PaymentTerms { get; } = + [ + new("RD", "Rimessa diretta", "BON", "TP02", [Now]), + new("CONT", "Contanti alla consegna", "CONT", "TP02", [Now]), + new("ANT", "Pagamento anticipato", "BON", "TP03", [Now]), + new("BB30", "Bonifico 30 gg data fattura", "BON", "TP02", [new(30, false, 100m)]), + new("BB30FM", "Bonifico 30 gg fine mese", "BON", "TP02", [new(30, true, 100m)]), + new("BB60FM", "Bonifico 60 gg fine mese", "BON", "TP02", [new(60, true, 100m)]), + new("BB3060FM", "Bonifico 30-60 gg fine mese", "BON", "TP01", [new(30, true, 50m), new(60, true, 50m)]), + new("RB30FM", "RiBa 30 gg fine mese", "RIBA", "TP02", [new(30, true, 100m)]), + new("RB60FM", "RiBa 60 gg fine mese", "RIBA", "TP02", [new(60, true, 100m)]), + new("RB3060FM", "RiBa 30-60 gg fine mese", "RIBA", "TP01", [new(30, true, 50m), new(60, true, 50m)]), + new("RB306090", "RiBa 30-60-90 gg fine mese", "RIBA", "TP01", [new(30, true, 33.33m), new(60, true, 33.33m), new(90, true, 33.34m)]), + new("SDD30", "Addebito SEPA 30 gg data fattura", "SDD", "TP02", [new(30, false, 100m)]), + ]; + + /// + public IReadOnlyList DocumentTypes { get; } = + [ + new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null), + new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null), + new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null), + new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01"), + new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01"), + new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24"), + new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02"), + new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04"), + new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05"), + new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06"), + new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null), + new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16"), + new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17"), + new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18"), + new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19"), + new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null), + new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null), + new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null), + new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null), + new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null), + ]; +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 1316fce..73755e6 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -19,6 +19,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new FixedAssetRulesIt()); AddFeature(new F24Exporter()); AddFeature(new ItalianTaxIdentifierRules()); + AddFeature(new ItalianBaseTables()); } /// diff --git a/src/Khaemhat.Infrastructure/Files/CsvReader.cs b/src/Khaemhat.Infrastructure/Files/CsvReader.cs new file mode 100644 index 0000000..4a6306c --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/CsvReader.cs @@ -0,0 +1,124 @@ +using System.Text; + +namespace Khaemhat.Infrastructure.Files; + +/// +/// Reads CSV files written by or by spreadsheets (RFC 4180): quoted fields with doubled quotes, +/// line breaks inside quotes, an optional UTF-8 byte order mark. The separator is guessed from the first line +/// (;, , or tab) unless given. +/// +public static class CsvReader +{ + /// The separators tried, in order of preference. + private static readonly char[] Separators = [';', ',', '\t']; + + /// Reads every row of a text. + /// The content. + /// The separator, or to guess it. + /// The rows; empty lines are skipped. + public static IReadOnlyList> Parse(string text, char? separator = null) + { + ArgumentNullException.ThrowIfNull(text); + if (text.Length > 0 && text[0] == '') + { + text = text[1..]; + } + + var sep = separator ?? Guess(text); + var rows = new List>(); + var row = new List(); + var field = new StringBuilder(); + var quoted = false; + var fieldStarted = false; + + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + if (quoted) + { + if (c == '"') + { + if (i + 1 < text.Length && text[i + 1] == '"') + { + field.Append('"'); + i++; + } + else + { + quoted = false; + } + } + else + { + field.Append(c); + } + + continue; + } + + if (c == '"' && field.Length == 0) + { + quoted = true; + fieldStarted = true; + } + else if (c == sep) + { + row.Add(field.ToString()); + field.Clear(); + fieldStarted = true; + } + else if (c is '\r' or '\n') + { + if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n') + { + i++; + } + + EndRow(); + } + else + { + field.Append(c); + fieldStarted = true; + } + } + + EndRow(); + return rows; + + void EndRow() + { + if (fieldStarted || field.Length > 0 || row.Count > 0) + { + row.Add(field.ToString()); + if (row.Count > 1 || row[0].Length > 0) + { + rows.Add(row); + } + } + + row = []; + field.Clear(); + fieldStarted = false; + } + } + + /// Reads a stream as UTF-8 (the byte order mark is optional). + /// The stream. + /// The separator, or to guess it. + /// Cancellation. + /// The rows. + public static async Task>> ReadAsync(Stream content, char? separator = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true); + return Parse(await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false), separator); + } + + private static char Guess(string text) + { + var end = text.IndexOfAny(['\r', '\n']); + var first = end < 0 ? text : text[..end]; + return Separators.OrderByDescending(s => first.Count(c => c == s)).First(); + } +} diff --git a/src/Khaemhat.Infrastructure/Http/EcbRatesClient.cs b/src/Khaemhat.Infrastructure/Http/EcbRatesClient.cs new file mode 100644 index 0000000..c0a1613 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Http/EcbRatesClient.cs @@ -0,0 +1,99 @@ +using System.Globalization; +using System.Xml; +using System.Xml.Linq; + +namespace Khaemhat.Infrastructure.Http; + +/// A reference rate of the European Central Bank: units of the currency for one euro. +/// The currency (ISO 4217). +/// The day of the rate. +/// Units of the currency for one euro. +public sealed record EcbRate(string Currency, DateOnly Date, decimal Rate); + +/// +/// The euro foreign exchange reference rates of the European Central Bank (SPEC §11.1, §11.12), published on working +/// days around 16:00 CET as an XML file (eurofxref-daily.xml, or the last 90 days in eurofxref-hist-90d.xml). +/// +public sealed class EcbRatesClient +{ + /// The address of the reference rates. + public static readonly Uri DefaultBaseAddress = new("https://www.ecb.europa.eu/stats/eurofxref/"); + + private const string Namespace = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"; + + private readonly HttpClient _http; + + /// Creates the client. + /// The HTTP client (its base address defaults to ). + public EcbRatesClient(HttpClient http) + { + ArgumentNullException.ThrowIfNull(http); + _http = http; + _http.BaseAddress ??= DefaultBaseAddress; + } + + /// Reads the rates of the last working day, or of the last 90 days. + /// Whether to read the last 90 days (to fill gaps after a stop). + /// Cancellation. + /// The rates. + /// The service did not answer. + /// The answer is not the expected XML. + public async Task> GetAsync(bool last90Days = false, CancellationToken cancellationToken = default) + { + var path = new Uri(last90Days ? "eurofxref-hist-90d.xml" : "eurofxref-daily.xml", UriKind.Relative); + using var response = await _http.GetAsync(path, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + var content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using (content.ConfigureAwait(false)) + { + return await ParseAsync(content, cancellationToken).ConfigureAwait(false); + } + } + + /// Reads the ECB XML. + /// The XML. + /// Cancellation. + /// The rates. + /// The XML is not the ECB format. + public static async Task> ParseAsync(Stream xml, CancellationToken cancellationToken = default) + { + XDocument document; + try + { + var settings = new XmlReaderSettings { Async = true, DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; + using var reader = XmlReader.Create(xml, settings); + document = await XDocument.LoadAsync(reader, LoadOptions.None, cancellationToken).ConfigureAwait(false); + } + catch (XmlException ex) + { + throw new FormatException("The ECB answer is not XML.", ex); + } + + XNamespace ns = Namespace; + var rates = new List(); + foreach (var day in document.Descendants(ns + "Cube").Where(c => c.Attribute("time") is not null)) + { + if (!DateOnly.TryParseExact(day.Attribute("time")!.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + { + throw new FormatException("The ECB answer has a date that cannot be read."); + } + + foreach (var cube in day.Elements(ns + "Cube")) + { + var currency = cube.Attribute("currency")?.Value; + var text = cube.Attribute("rate")?.Value; + if (currency is { Length: 3 } && decimal.TryParse(text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var rate) && rate > 0) + { + rates.Add(new EcbRate(currency, date, rate)); + } + } + } + + if (rates.Count == 0) + { + throw new FormatException("The ECB answer has no rates."); + } + + return rates; + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index cc0bb87..4993dbe 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -11,7 +11,9 @@ using Khaemhat.Application.Modules; using Khaemhat.Application.Notifications; using Khaemhat.Application.Preferences; using Khaemhat.Application.Search; +using Khaemhat.Application.Seeding; using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; using Khaemhat.Core.Caching; using Khaemhat.Core.Files; using Khaemhat.Core.Logging; @@ -27,6 +29,7 @@ using Khaemhat.Fiscal.Abstractions; using Khaemhat.Fiscal.Italy; using Khaemhat.Infrastructure.Caching; using Khaemhat.Infrastructure.Files; +using Khaemhat.Infrastructure.Http; using Khaemhat.Infrastructure.Licensing; using Khaemhat.Infrastructure.Logging; using Khaemhat.Infrastructure.Security; @@ -132,8 +135,22 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(sp => new FiscalPackCatalog(sp.GetServices())); + // Company tables, profile and fiscal years (#38, #39), base data (#45), checks against European services (#40). + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(30)); + services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(20)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + // Companies and start. services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); diff --git a/tests/Khaemhat.Application.Tests/TableRulesTests.cs b/tests/Khaemhat.Application.Tests/TableRulesTests.cs new file mode 100644 index 0000000..bcfe063 --- /dev/null +++ b/tests/Khaemhat.Application.Tests/TableRulesTests.cs @@ -0,0 +1,74 @@ +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; + +namespace Khaemhat.Application.Tests; + +[TestClass] +public sealed class TableRulesTests +{ + [TestMethod] + [DataRow("{number}/{year}", true)] + [DataRow("{prefix}/{year}/{number:D6}", true)] + [DataRow("{section}-{number:D4}", true)] + [DataRow("{year}", false)] + [DataRow("{number}/{anno}", false)] + [DataRow("", false)] + public void NumberFormat_NeedsTheNumberAndKnownPlaceholders(string format, bool valid) => + Assert.AreEqual(valid, DocumentNumberFormat.IsValid(format)); + + [TestMethod] + public void NumberFormat_WritesTheNumber() + { + Assert.AreEqual("FV/2026/000123", DocumentNumberFormat.Apply("{prefix}/{year}/{number:D6}", 123, 2026, "FV", null)); + Assert.AreEqual("7/AF/2026", DocumentNumberFormat.Apply("{number}/{section}/{year}", 7, 2026, null, "AF")); + } + + [TestMethod] + public void DiscountFormula_ChainsTheSteps() + { + Assert.IsTrue(DiscountFormula.TryParse("10 + 5", out var steps)); + Assert.AreEqual("10+5", DiscountFormula.Format(steps)); + Assert.AreEqual(14.5m, DiscountFormula.Equivalent(steps)); + Assert.IsTrue(DiscountFormula.TryParse("2,5", out var single)); + Assert.AreEqual("2,5", DiscountFormula.Format(single)); + Assert.IsFalse(DiscountFormula.TryParse("10+abc", out _)); + Assert.IsFalse(DiscountFormula.TryParse("120", out _)); + Assert.IsFalse(DiscountFormula.TryParse("-5", out _)); + } + + [TestMethod] + public void PeriodState_FollowsYearAndMonth() + { + var year = new FiscalYear { Id = 1, StartDate = new(2026, 1, 1), EndDate = new(2026, 12, 31) }; + var march = new FiscalPeriod { FiscalYearId = 1, Number = 3, StartDate = new(2026, 3, 1), EndDate = new(2026, 3, 31), Status = FiscalPeriodStatus.Locked }; + var april = new FiscalPeriod { FiscalYearId = 1, Number = 4, StartDate = new(2026, 4, 1), EndDate = new(2026, 4, 30), Status = FiscalPeriodStatus.Settled }; + FiscalYearView[] calendar = [new(year, [march, april])]; + + Assert.AreEqual(PeriodState.Open, FiscalYearService.StateOf(calendar, new(2026, 5, 2), PeriodUse.Vat)); + Assert.AreEqual(PeriodState.Locked, FiscalYearService.StateOf(calendar, new(2026, 3, 31), PeriodUse.NoVat)); + Assert.AreEqual(PeriodState.Settled, FiscalYearService.StateOf(calendar, new(2026, 4, 10), PeriodUse.Vat)); + Assert.AreEqual(PeriodState.Open, FiscalYearService.StateOf(calendar, new(2026, 4, 10), PeriodUse.NoVat)); + Assert.AreEqual(PeriodState.NoYear, FiscalYearService.StateOf(calendar, new(2027, 1, 1), PeriodUse.NoVat)); + + year.Status = FiscalYearStatus.Closed; + Assert.AreEqual(PeriodState.YearClosed, FiscalYearService.StateOf(calendar, new(2026, 5, 2), PeriodUse.NoVat)); + Assert.AreEqual("fiscal.date.locked", FiscalYearService.ErrorOf(PeriodState.Locked)); + } + + [TestMethod] + public void Catalog_HasEveryTableOnce_WithCsvColumnsStartingWithTheCode() + { + var catalog = new TableCatalog(); + + Assert.HasCount(26, catalog.All.ToList()); + foreach (var table in catalog.All) + { + Assert.AreEqual("code", table.CsvColumns[0].Header, table.Key); + Assert.AreEqual("description", table.CsvColumns[1].Header, table.Key); + Assert.IsFalse(table.CsvColumns.Any(c => c.Header is "id" or "row_version" or "is_demo" || c.Header.EndsWith("_id", StringComparison.Ordinal)), table.Key); + } + + CollectionAssert.Contains(catalog.Get().CsvColumns.Select(c => c.Header).ToList(), "non_deductible_percent"); + CollectionAssert.Contains(catalog.Get().CsvColumns.Select(c => c.Header).ToList(), "e_invoice_code"); + } +} diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 9f904a4..5361681 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -72,6 +72,10 @@ public sealed class MappingTests "sys_companies", "sys_data_protection_keys", "sys_job_locks", "sys_job_runs", "sys_license_activations", "sys_licenses", "sys_log", "sys_notification_reads", "sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_user_settings", "sys_users", "attachments", "audit_log", "company_settings", "notification_reads", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users", + "company_profile", "fiscal_years", "fiscal_periods", "countries", "provinces", "municipalities", "currencies", "exchange_rates", "units_of_measure", + "tax_codes", "payment_methods", "payment_terms", "payment_term_lines", "bank_accounts", "salespeople", "carriers", "shipping_terms", "transport_means", + "goods_appearances", "delivery_terms", "transport_reasons", "inventory_reasons", "warehouses", "item_categories", "party_categories", "price_lists", + "discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/ItalianBaseTablesTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/ItalianBaseTablesTests.cs new file mode 100644 index 0000000..5823e85 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/ItalianBaseTablesTests.cs @@ -0,0 +1,37 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +[TestClass] +public sealed class ItalianBaseTablesTests +{ + private static readonly ItalyFiscalPack Pack = new(); + + [TestMethod] + public void Template_UsesOnlyActiveCodesOfTheFatturaPaLists() + { + var template = Pack.Require(); + var format = Pack.Require(); + + Assert.IsTrue(template.PaymentMethods.All(m => format.PaymentMethods.IsActive(m.EInvoiceCode))); + Assert.IsTrue(template.PaymentTerms.All(t => format.PaymentConditions.IsActive(t.Condition))); + Assert.IsTrue(template.DocumentTypes.Where(d => d.EInvoiceType is not null).All(d => format.DocumentTypes.IsActive(d.EInvoiceType))); + } + + [TestMethod] + public void PaymentTerms_AreCompleteAndReferToKnownMethods() + { + var template = Pack.Require(); + var methods = template.PaymentMethods.Select(m => m.Code).ToHashSet(StringComparer.Ordinal); + + foreach (var terms in template.PaymentTerms) + { + Assert.AreEqual(100m, terms.Installments.Sum(i => i.Percent), terms.Code); + Assert.Contains(terms.PaymentMethodCode, methods, terms.Code); + Assert.AreEqual(terms.Installments.Count > 1, terms.Condition == "TP01", terms.Code); + } + + Assert.AreEqual(template.PaymentTerms.Count, template.PaymentTerms.Select(t => t.Code).Distinct(StringComparer.Ordinal).Count()); + Assert.AreEqual(template.DocumentTypes.Count, template.DocumentTypes.Select(t => t.Code).Distinct(StringComparer.Ordinal).Count()); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Files/CsvReaderAndEcbTests.cs b/tests/Khaemhat.Infrastructure.Tests/Files/CsvReaderAndEcbTests.cs new file mode 100644 index 0000000..5bbef2e --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Files/CsvReaderAndEcbTests.cs @@ -0,0 +1,87 @@ +using System.Text; +using Khaemhat.Infrastructure.Files; +using Khaemhat.Infrastructure.Http; + +namespace Khaemhat.Infrastructure.Tests.Files; + +[TestClass] +public sealed class CsvReaderTests +{ + [TestMethod] + public void Parse_ReadsQuotesNewLinesAndTheByteOrderMark() + { + var rows = CsvReader.Parse("code;description\r\nA;\"Uno; due\"\r\nB;\"riga\ncon \"\"virgolette\"\"\"\r\n\r\nC;\n"); + + Assert.HasCount(4, rows); + CollectionAssert.AreEqual(new[] { "code", "description" }, rows[0].ToArray()); + CollectionAssert.AreEqual(new[] { "A", "Uno; due" }, rows[1].ToArray()); + CollectionAssert.AreEqual(new[] { "B", "riga\ncon \"virgolette\"" }, rows[2].ToArray()); + CollectionAssert.AreEqual(new[] { "C", string.Empty }, rows[3].ToArray()); + } + + [TestMethod] + public void Parse_GuessesTheSeparator() + { + Assert.AreEqual("2", CsvReader.Parse("a,b\n1,2")[1][1]); + Assert.AreEqual("2", CsvReader.Parse("a\tb\n1\t2")[1][1]); + Assert.AreEqual("1,5", CsvReader.Parse("a;b\n1,5;2")[1][0]); + } + + [TestMethod] + public async Task WriterOutput_IsReadBack() + { + using var buffer = new MemoryStream(); + await using (var writer = new CsvWriter(buffer, CsvOptions.Italian, leaveOpen: true)) + { + writer.WriteRow("code", "note"); + writer.WriteRow("X1", "a;b \"c\""); + } + + buffer.Position = 0; + var rows = await CsvReader.ReadAsync(buffer); + + CollectionAssert.AreEqual(new[] { "X1", "a;b \"c\"" }, rows[1].ToArray()); + } +} + +[TestClass] +public sealed class EcbRatesClientTests +{ + private const string Daily = """ + + + Reference rates + + + + + + + + + + + """; + + [TestMethod] + public async Task Parse_ReadsEveryDayAndCurrency() + { + using var xml = new MemoryStream(Encoding.UTF8.GetBytes(Daily)); + + var rates = await EcbRatesClient.ParseAsync(xml); + + Assert.HasCount(3, rates); + Assert.AreEqual(new EcbRate("USD", new DateOnly(2026, 11, 10), 1.1563m), rates[0]); + Assert.AreEqual(177.12m, rates.Single(r => r.Currency == "JPY").Rate); + } + + [TestMethod] + public async Task Parse_RefusesAnswersThatAreNotRates() + { + using var html = new MemoryStream(Encoding.UTF8.GetBytes("Maintenance")); + using var broken = new MemoryStream(Encoding.UTF8.GetBytes("not xml")); + + await Assert.ThrowsExactlyAsync(() => EcbRatesClient.ParseAsync(html)); + await Assert.ThrowsExactlyAsync(() => EcbRatesClient.ParseAsync(broken)); + } +} diff --git a/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.cs b/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.cs index bec4d29..d2a86fd 100644 --- a/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.cs +++ b/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.cs @@ -68,7 +68,7 @@ public sealed class CompanyIsolationTests var scheduler = services.GetRequiredService(); await scheduler.EnsureSystemTasksAsync(); - foreach (var task in JobScheduler.SystemTasks) + foreach (var task in JobScheduler.SystemTasks.Where(t => !t.UsesNetwork)) { Assert.AreEqual(JobOutcome.Succeeded, await scheduler.RunAsync(task.Code), task.Code); } diff --git a/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs b/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs new file mode 100644 index 0000000..2583c97 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs @@ -0,0 +1,206 @@ +using System.Text; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Seeding; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Tax; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Tables; + +/// Company tables, profile, fiscal years and base data on a real instance (issues #38, #39, #45). +[TestClass] +public sealed class CompanyTablesTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task BaseData_IsLoadedAtStart_AndRunningItAgainAddsNothing() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var services = app.Services; + var tables = services.GetRequiredService(); + var pack = services.GetRequiredService().ForCountry("IT"); + + var taxCodes = await tables.AllAsync(Root, company); + Assert.HasCount(pack.TaxCodes.BaseCodes.Count, taxCodes); + var reverseCharge = taxCodes.Single(t => t.Code == "RC17"); + Assert.AreEqual((TaxCodeKind.ReverseCharge, "N6.9"), (reverseCharge.Kind, reverseCharge.Nature)); + + var countries = await tables.AllAsync(Root, company); + Assert.AreEqual(27, countries.Count(c => c.EuMember && c.Code != "XI"), "The 27 member states."); + Assert.AreEqual("EL", countries.Single(c => c.Code == "GR").VatPrefix); + Assert.AreEqual("EUR", countries.Single(c => c.Code == "BG").CurrencyCode); + + var invoice = (await tables.AllAsync(Root, company)).Single(d => d.Code == "FI"); + var numerators = await tables.AllAsync(Root, company); + Assert.AreEqual(("TD01", "FAT"), (invoice.EInvoiceType, numerators.Single(n => n.Id == invoice.NumeratorId).Code)); + Assert.IsFalse(numerators.Single(n => n.Code == "FAT").GapsAllowed); + + await using (var uow = await services.GetRequiredService().CreateAsync(DatabaseScope.Company(company))) + { + var terms = (await uow.Repository().FindAsync(Query.For().Where(t => t.Code == "RB306090")))!; + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => l.PaymentTermId == terms.Id))).Items; + Assert.HasCount(3, lines); + Assert.AreEqual(100m, lines.Sum(l => l.Percent)); + } + + var years = await services.GetRequiredService().ListAsync(Root, company); + Assert.HasCount(1, years); + Assert.HasCount(12, years[0].Periods); + + var runner = services.GetRequiredService(); + Assert.AreEqual("IT 2026.2", await runner.VersionAsync(company)); + var again = await runner.UpdateBaseAsync(Root, company); + Assert.AreEqual(0, again.Total, string.Join(", ", again.Added.Select(a => a.Key + "=" + a.Value))); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Save_AppliesTheRulesOfTheTableAndOfTheFiscalPack() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var tables = app.Services.GetRequiredService(); + + var noNature = new TaxCode { Code = "zero", Description = "Senza natura", Rate = 0 }; + var problems = await tables.ValidateAsync(Root, company, noNature); + Assert.AreEqual("ZERO", noNature.Code, "Codes are upper case."); + Assert.IsTrue(problems.Any(p => p is { Field: "Nature", Code: "fiscal.tax.nature-required", IsWarning: false })); + var refused = await Assert.ThrowsExactlyAsync(() => tables.SaveAsync(Root, company, noNature)); + CollectionAssert.Contains(refused.Errors.ToList(), "Nature:fiscal.tax.nature-required"); + + var duplicate = await Assert.ThrowsExactlyAsync(() => tables.SaveAsync(Root, company, new TaxCode { Code = "22", Description = "Doppio", Rate = 22 })); + CollectionAssert.Contains(duplicate.Errors.ToList(), "Code:" + TableService.CodeDuplicate); + + var exempt = await tables.SaveAsync(Root, company, new TaxCode { Code = "ESE10B", Description = "Esente art. 10 n. 1", Rate = 0, Nature = "n4", LegalReference = "Art. 10 DPR 633/72" }); + Assert.AreEqual((TaxCodeKind.Exempt, "N4"), (exempt.Kind, exempt.Nature)); + var page = await tables.ListAsync(Root, company, new ListQuery { Search = "ESE10B" }); + Assert.AreEqual(1, page.Total, "The cache is refreshed after a save."); + + var badIban = await Assert.ThrowsExactlyAsync(() => tables.SaveAsync(Root, company, new BankAccount { Code = "B1", Description = "Banca", Iban = "IT00X0000000000000000000000" })); + CollectionAssert.Contains(badIban.Errors.ToList(), "Iban:" + TableCatalog.IbanInvalid); + + var account = await tables.SaveAsync(Root, company, new BankAccount { Code = "B1", Description = "Banca", Iban = "it60 x054 2811 1010 0000 0123 456", IsDefault = true }); + var second = await tables.SaveAsync(Root, company, new BankAccount { Code = "B2", Description = "Altra banca", IsDefault = true }); + var accounts = await tables.AllAsync(Root, company); + Assert.AreEqual("IT60X0542811101000000123456", account.Iban); + Assert.AreEqual(second.Id, accounts.Single(a => a.IsDefault).Id, "Only one default account."); + + var numerator = new DocumentNumerator { Code = "FAT", Description = "Fatture anno prossimo", Kind = NumeratorKind.SalesInvoice, Year = 2099, Format = "{number}/{year}", GapsAllowed = true }; + await tables.SaveAsync(Root, company, numerator); + Assert.IsFalse(numerator.GapsAllowed, "Invoices are numbered without gaps."); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Delete_DisablesRowsInUse_AndCsvRoundTrips() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var tables = app.Services.GetRequiredService(); + + var transfer = (await tables.AllAsync(Root, company)).Single(m => m.Code == "BON"); + Assert.AreEqual(TableDeleteOutcome.Disabled, await tables.DeleteAsync(Root, company, transfer.Id), "Payment terms use it."); + Assert.IsTrue((await tables.GetAsync(Root, company, transfer.Id))!.Disabled); + Assert.IsFalse((await tables.ActiveAsync(Root, company)).Any(m => m.Code == "BON")); + + var pagopa = (await tables.AllAsync(Root, company)).Single(m => m.Code == "PAGOPA"); + Assert.AreEqual(TableDeleteOutcome.Deleted, await tables.DeleteAsync(Root, company, pagopa.Id)); + + using var export = new MemoryStream(); + var written = await tables.ExportCsvAsync(Root, company, export); + var exported = Encoding.UTF8.GetString(export.ToArray()).TrimStart(''); + var header = exported[..exported.IndexOf('\r', StringComparison.Ordinal)].Split(';'); + var box = string.Join(';', header.Select(h => h switch { "code" => "BOX", "description" => "Scatoloni", _ => string.Empty })); + var csv = exported.Replace("Chilogrammi", "Chili", StringComparison.Ordinal) + box + "\r\n"; + using var import = new MemoryStream(Encoding.UTF8.GetBytes(csv)); + var result = await tables.ImportCsvAsync(Root, company, import); + + Assert.IsTrue(result.Succeeded, string.Join(", ", result.Errors)); + Assert.AreEqual((1, written), (result.Inserted, result.Updated)); + var units = await tables.AllAsync(Root, company); + Assert.AreEqual("Chili", units.Single(u => u.Code == "KG").Description); + Assert.AreEqual(3, units.Single(u => u.Code == "KG").Decimals); + + using var bad = new MemoryStream(Encoding.UTF8.GetBytes("code;description;decimals\nX;Ics;tre\nY;;0\n")); + var refused = await tables.ImportCsvAsync(Root, company, bad); + Assert.IsFalse(refused.Succeeded); + CollectionAssert.AreEquivalent( + new[] { new TableImportError(2, "decimals", TableService.CsvBadValue), new TableImportError(3, "description", TableService.DescriptionRequired) }, + refused.Errors.ToArray()); + Assert.IsFalse((await tables.AllAsync(Root, company)).Any(u => u.Code == "Y"), "Nothing is saved when a row is wrong."); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task LockedMonths_RefuseDates_AndTheNextYearFollowsTheLast() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var years = app.Services.GetRequiredService(); + var current = (await years.ListAsync(Root, company)).Single(); + var first = current.Periods[0]; + + Assert.AreEqual(PeriodState.Open, await years.CheckAsync(company, first.StartDate, PeriodUse.Vat)); + await years.SetLockedAsync(Root, company, first.Id, locked: true); + Assert.AreEqual(PeriodState.Locked, await years.CheckAsync(company, first.EndDate, PeriodUse.NoVat)); + var refused = await Assert.ThrowsExactlyAsync(() => years.DemandOpenAsync(company, first.StartDate, PeriodUse.NoVat)); + CollectionAssert.Contains(refused.Errors.ToList(), "fiscal.date.locked"); + await years.SetLockedAsync(Root, company, first.Id, locked: false); + Assert.AreEqual(PeriodState.Open, await years.CheckAsync(company, first.StartDate, PeriodUse.Vat)); + + var next = await years.CreateNextAsync(Root, company, current.Year.StartDate); + Assert.AreEqual(current.Year.EndDate.AddDays(1), next.Year.StartDate); + Assert.AreEqual(PeriodState.NoYear, await years.CheckAsync(company, next.Year.EndDate.AddDays(1), PeriodUse.NoVat)); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Profile_StartsFromTheInstanceDefaults_AndChecksTheItalianIdentifiers() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var profiles = app.Services.GetRequiredService(); + var profile = await profiles.GetAsync(Root, company); + Assert.AreEqual((0L, "IT", "RF01", VatPeriodicity.Monthly), (profile.Id, profile.Country, profile.TaxRegime, profile.VatPeriodicity)); + + profile.LegalName = "Prova S.r.l."; + profile.VatNumber = "01234567890"; + profile.RecipientCode = "abc"; + profile.ProvinceCode = "milano"; + var refused = await Assert.ThrowsExactlyAsync(() => profiles.SaveAsync(Root, company, profile)); + CollectionAssert.IsSubsetOf( + new[] { "VatNumber:" + TableCatalog.VatNumberInvalid, "RecipientCode:" + CompanyProfileService.RecipientCodeInvalid, "ProvinceCode:" + CompanyProfileService.TwoLettersRequired }, + refused.Errors.ToList()); + + profile.VatNumber = "IT 01234567897"; + profile.RecipientCode = "abc1234"; + profile.ProvinceCode = "mi"; + var saved = await profiles.SaveAsync(Root, company, profile); + Assert.AreNotEqual(0L, saved.Id); + Assert.AreEqual(("01234567897", "ABC1234", "MI"), (saved.VatNumber, saved.RecipientCode, saved.ProvinceCode)); + + saved.Country = "ZZ"; + var unknown = await Assert.ThrowsExactlyAsync(() => profiles.SaveAsync(Root, company, saved)); + CollectionAssert.Contains(unknown.Errors.ToList(), "Country:" + CompanyProfileService.CountryUnknown); + await app.StopAsync(); + } + } +}