Adds the company tables of SPEC 11.1 behind one generic service so that every table gets the same rules, history, cache and CSV import/export, plus the company profile, fiscal years with monthly lock and the base-data seeder. - 26 coded tables, exchange rates, company profile, fiscal years and periods: entities, maps and migrations 010-014 - TableService + TableCatalog: unique codes, per-table rules (VAT codes are checked by the fiscal pack), delete or disable when in use, single default, CSV export/import all-or-nothing, cache with cross-instance invalidation - CompanyProfileService (Italian identifiers through the pack), FiscalYearService with the date check used by every dated record - EcbRatesClient and the ECB rates system task; CsvReader - ISeeder/SeedRunner with the data version in company settings; base tables from the pack (IBaseTablesTemplate) and an embedded ISO country list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
25f8a7ad30
commit
34e196424f
33 files changed
+6049
-3
No files matched your search
@@ -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`
|
||||
|
||||
<!-- END GENERATED -->
|
||||
@@ -39,7 +39,8 @@ public interface IScheduledJob
|
||||
/// <param name="JobType">The job type.</param>
|
||||
/// <param name="Cron">When it runs.</param>
|
||||
/// <param name="TimeoutSeconds">Its timeout.</param>
|
||||
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600);
|
||||
/// <param name="UsesNetwork">Whether it calls services outside the instance (the tests run it with a stub).</param>
|
||||
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600, bool UsesNetwork = false);
|
||||
|
||||
/// <summary>
|
||||
/// The scheduler (SPEC §9.4; mockup 083): reads <c>sys_scheduled_tasks</c>, runs the due ones with a lock in
|
||||
@@ -49,13 +50,14 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
|
||||
/// </summary>
|
||||
public sealed class JobScheduler
|
||||
{
|
||||
/// <summary>The system tasks (M2, attachments trash from M3).</summary>
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
|
||||
public static readonly IReadOnlyList<SystemTaskDefinition> 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;
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Base data shipped with the code (SPEC §14). -->
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Seeding/Data/*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
|
||||
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="IBaseTablesTemplate"/>), 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).
|
||||
/// </summary>
|
||||
/// <param name="years">Creates the current fiscal year.</param>
|
||||
public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
|
||||
{
|
||||
/// <summary>The currencies of the ECB reference rates, plus the euro: code, name, symbol, decimals.</summary>
|
||||
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),
|
||||
];
|
||||
|
||||
/// <summary>The numerators of the base data: code, description, family, section, format, gaps allowed.</summary>
|
||||
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),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public SeedKind Kind => SeedKind.Base;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 0;
|
||||
|
||||
/// <inheritdoc />
|
||||
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<ShippingTerm>(("FRANCO", "Porto franco"), ("ASSEGNATO", "Porto assegnato"), ("ADDEBITO", "Franco con addebito in fattura")), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await context.EnsureAsync("transport_means", Coded<TransportMean>(("MITT", "Mittente"), ("DEST", "Destinatario"), ("VETT", "Vettore")), cancellationToken).ConfigureAwait(false);
|
||||
await context.EnsureAsync(
|
||||
"goods_appearances",
|
||||
Coded<GoodsAppearance>(("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<TransportReason>(
|
||||
("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<PartyCategory>(("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<string, DocumentNumerator>(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<IBaseTablesTemplate>() 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<FiscalYear, long>()
|
||||
.CountAsync(Query.For<FiscalYear>().Where(y => y.StartDate <= context.Today && y.EndDate >= context.Today), cancellationToken).ConfigureAwait(false);
|
||||
if (calendar == 0 && await context.UnitOfWork.Repository<FiscalYear, long>().CountAsync(Query.For<FiscalYear>(), cancellationToken).ConfigureAwait(false) == 0)
|
||||
{
|
||||
await years.CreateAsync(context.UnitOfWork, context.Today, "system", cancellationToken).ConfigureAwait(false);
|
||||
context.Count("fiscal_years");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The countries of the embedded list (ISO 3166-1, Italian names, EU members, currency).</summary>
|
||||
/// <returns>The rows.</returns>
|
||||
public static IReadOnlyList<Country> 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<PaymentTerm, long>().ListAsync(Query.For<PaymentTerm>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(t => t.Code)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var lines = context.UnitOfWork.Repository<PaymentTermLine, long>();
|
||||
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<TaxCode> 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<UnitOfMeasure> 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<InventoryReason> 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<DeliveryTerm> Incoterms() => Coded<DeliveryTerm>(
|
||||
("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<T> Coded<T>(params (string Code, string Description)[] rows)
|
||||
where T : CodedEntity, new() =>
|
||||
rows.Select(r => new T { Code = r.Code, Description = r.Description });
|
||||
}
|
||||
@@ -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
|
||||
|
@@ -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;
|
||||
|
||||
/// <summary>The kind of data a seeder loads (SPEC §14).</summary>
|
||||
public enum SeedKind
|
||||
{
|
||||
/// <summary>The base tables every company needs.</summary>
|
||||
Base = 0,
|
||||
|
||||
/// <summary>The fictitious demo company.</summary>
|
||||
Demo = 1,
|
||||
}
|
||||
|
||||
/// <summary>A source of base or demo data (SPEC §14). Seeders are idempotent: they add what is missing and change nothing else.</summary>
|
||||
public interface ISeeder
|
||||
{
|
||||
/// <summary>The licence module whose tables it fills (<c>CORE</c>, <c>ACCT</c>...).</summary>
|
||||
string ModuleCode { get; }
|
||||
|
||||
/// <summary>Base or demo.</summary>
|
||||
SeedKind Kind { get; }
|
||||
|
||||
/// <summary>The order among seeders of the same kind (lower first).</summary>
|
||||
int Order { get; }
|
||||
|
||||
/// <summary>Loads the data.</summary>
|
||||
/// <param name="context">The company, its unit of work and fiscal pack.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task RunAsync(SeedContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>What a seeder works with, and the counts of what it added.</summary>
|
||||
public sealed class SeedContext
|
||||
{
|
||||
private readonly Dictionary<string, int> _added = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Creates the context.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="unitOfWork">The company unit of work, committed by the runner.</param>
|
||||
/// <param name="pack">The fiscal pack of the company.</param>
|
||||
/// <param name="today">Today, for the current year.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The company.</summary>
|
||||
public string CompanyCode { get; }
|
||||
|
||||
/// <summary>The company unit of work.</summary>
|
||||
public IUnitOfWork UnitOfWork { get; }
|
||||
|
||||
/// <summary>The fiscal pack.</summary>
|
||||
public IFiscalPack Pack { get; }
|
||||
|
||||
/// <summary>Today.</summary>
|
||||
public DateOnly Today { get; }
|
||||
|
||||
/// <summary>Rows added, by table.</summary>
|
||||
public IReadOnlyDictionary<string, int> Added => _added;
|
||||
|
||||
/// <summary>Adds the rows whose code is missing; existing rows are left as the users made them.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="table">The table, for the counts.</param>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Every row of the seed as stored (the existing one when the code was there).</returns>
|
||||
public async Task<IReadOnlyDictionary<string, T>> EnsureAsync<T>(string table, IEnumerable<T> rows, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var repository = UnitOfWork.Repository<T, long>();
|
||||
var existing = (await repository.ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
var result = new Dictionary<string, T>(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;
|
||||
}
|
||||
|
||||
/// <summary>Adds one row when nothing matches a condition.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="table">The table, for the counts.</param>
|
||||
/// <param name="match">Finds the row.</param>
|
||||
/// <param name="row">The row to add.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stored row.</returns>
|
||||
public async Task<T> EnsureOneAsync<T>(string table, System.Linq.Expressions.Expression<Func<T, bool>> match, T row, CancellationToken cancellationToken)
|
||||
where T : class, IEntity<long>, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
var repository = UnitOfWork.Repository<T, long>();
|
||||
var found = await repository.FindAsync(Query.For<T>().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;
|
||||
}
|
||||
|
||||
/// <summary>Counts a row added by hand.</summary>
|
||||
/// <param name="table">The table.</param>
|
||||
public void Count(string table) => _added[table] = _added.GetValueOrDefault(table) + 1;
|
||||
}
|
||||
|
||||
/// <summary>The outcome of a seed run.</summary>
|
||||
/// <param name="DataVersion">The data version now recorded, such as <c>IT 2026.2</c>.</param>
|
||||
/// <param name="Added">Rows added, by table.</param>
|
||||
public sealed record SeedReport(string DataVersion, IReadOnlyDictionary<string, int> Added)
|
||||
{
|
||||
/// <summary>Total rows added.</summary>
|
||||
public int Total => Added.Values.Sum();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the seeders of a kind on a company in one unit of work and records the data version in the company setting
|
||||
/// <see cref="VersionSetting"/> (SPEC §14). At company creation and at every start it runs the base seeders when
|
||||
/// <c>KHAEMHAT_SEED_BASE</c> is on; the button <i>Aggiorna tabelle di base</i> and <c>scripts/seed.sh --base</c> run
|
||||
/// them on demand. Being idempotent, running again only adds what a newer data version brings.
|
||||
/// </summary>
|
||||
public sealed partial class SeedRunner : ICompanySeeder
|
||||
{
|
||||
/// <summary>The company setting with the version of the base data.</summary>
|
||||
public const string VersionSetting = "seed.base.version";
|
||||
|
||||
private readonly IReadOnlyList<ISeeder> _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<SeedRunner> _logger;
|
||||
|
||||
/// <summary>Creates the runner.</summary>
|
||||
/// <param name="seeders">The seeders.</param>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="permissions">Checks permissions (the button).</param>
|
||||
/// <param name="tables">The tables (cache invalidation).</param>
|
||||
/// <param name="years">The fiscal years (cache invalidation).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public SeedRunner(
|
||||
IEnumerable<ISeeder> seeders, IUnitOfWorkFactory factory, CompanyFiscalContext fiscal, PermissionService permissions, TableService tables,
|
||||
FiscalYearService years, TimeProvider clock, ILogger<SeedRunner> 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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 10;
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The button <i>Aggiorna tabelle di base</i>: runs the base seeders for a company.</summary>
|
||||
/// <param name="actor">Who asks: needs <c>company.settings.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was added.</returns>
|
||||
public async Task<SeedReport> 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);
|
||||
}
|
||||
|
||||
/// <summary>The data version recorded in a company, or <see langword="null"/> before the first run.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The version.</returns>
|
||||
public async Task<string?> 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<CompanySetting, long>().FindAsync(Query.For<CompanySetting>().Where(s => s.Key == VersionSetting), cancellationToken).ConfigureAwait(false);
|
||||
return setting?.Value;
|
||||
}
|
||||
|
||||
/// <summary>Runs every seeder of a kind on a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="kind">Base or demo.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was added.</returns>
|
||||
public async Task<SeedReport> 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<CompanySetting, long>();
|
||||
var setting = await settings.FindAsync(Query.For<CompanySetting>().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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The fiscal pack of each company: the one of <c>company_profile.country</c>, or of <c>KHAEMHAT_COUNTRY</c> while the
|
||||
/// profile is missing (ADR 0025). The country is cached per company.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the context.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="packs">The fiscal packs.</param>
|
||||
/// <param name="cache">The cache.</param>
|
||||
/// <param name="options">The instance options (<c>KHAEMHAT_COUNTRY</c>).</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The country given to new companies.</summary>
|
||||
public string DefaultCountry => _defaultCountry;
|
||||
|
||||
/// <summary>The pack of the instance's default country.</summary>
|
||||
public IFiscalPack DefaultPack => _packs.ForCountry(_defaultCountry);
|
||||
|
||||
/// <summary>The fiscal pack of a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The pack.</returns>
|
||||
public async Task<IFiscalPack> 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<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), ct).ConfigureAwait(false);
|
||||
return profile?.Country ?? _defaultCountry;
|
||||
},
|
||||
CacheTime,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return _packs.TryForCountry(country, out var pack) ? pack : DefaultPack;
|
||||
}
|
||||
|
||||
/// <summary>Forgets the cached country of a company (after the profile changes).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
|
||||
_cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "fiscal"), cancellationToken);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public sealed partial class CompanyProfileService
|
||||
{
|
||||
/// <summary>Error: the name is missing.</summary>
|
||||
public const string NameRequired = "profile.name.required";
|
||||
|
||||
/// <summary>Error: no fiscal pack for the country.</summary>
|
||||
public const string CountryUnknown = "profile.country.unknown";
|
||||
|
||||
/// <summary>Error: the month is outside 1-12.</summary>
|
||||
public const string MonthRange = "profile.month.range";
|
||||
|
||||
/// <summary>Error: a code that must be two letters.</summary>
|
||||
public const string TwoLettersRequired = "profile.two-letters";
|
||||
|
||||
/// <summary>Error: the tax code is not valid.</summary>
|
||||
public const string TaxCodeInvalid = "profile.tax-code.invalid";
|
||||
|
||||
/// <summary>Error: the recipient code is not seven characters.</summary>
|
||||
public const string RecipientCodeInvalid = "profile.recipient-code.invalid";
|
||||
|
||||
/// <summary>Error: a value outside the list (<c>SU/SM</c>, <c>LS/LN</c>).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="packs">The installed fiscal packs.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The profile, or a new one with the defaults of the instance when the company has none yet.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The profile (<see cref="Core.Entities.Entity{TKey}.Id"/> 0 when new).</returns>
|
||||
public async Task<CompanyProfile> 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);
|
||||
}
|
||||
|
||||
/// <summary>Checks a profile without saving it.</summary>
|
||||
/// <param name="profile">The profile (normalized in place).</param>
|
||||
/// <returns>Errors and warnings by field.</returns>
|
||||
public IReadOnlyList<TableProblem> Validate(CompanyProfile profile)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
var problems = new List<TableProblem>();
|
||||
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<ITaxIdentifierRules>() 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<IEInvoiceFormat>() 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;
|
||||
}
|
||||
|
||||
/// <summary>Saves the profile (inserted the first time).</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="profile">The profile.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The saved profile.</returns>
|
||||
/// <exception cref="ValidationFailedException">A rule failed (<c>Field:code</c>).</exception>
|
||||
public async Task<CompanyProfile> 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<CompanyProfile, long>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A new profile with the defaults of the instance (country from <c>KHAEMHAT_COUNTRY</c>).</summary>
|
||||
/// <param name="companyName">The name proposed.</param>
|
||||
/// <returns>The profile.</returns>
|
||||
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<CompanyProfile?> LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>().OrderBy(x => x.Id), cancellationToken);
|
||||
|
||||
private static void CheckTwoLetters(string? value, string field, List<TableProblem> problems, Action<string?> 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();
|
||||
}
|
||||
|
||||
/// <summary>The common access check of the company services.</summary>
|
||||
internal static class CompanyGuard
|
||||
{
|
||||
/// <summary>Checks that the actor works in the company and has the permission.</summary>
|
||||
/// <param name="permissions">The permission service.</param>
|
||||
/// <param name="actor">Who acts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="permission">The permission.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The normalized company code.</returns>
|
||||
public static async Task<string> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The exchange rates of a company (SPEC §11.1): the ECB reference rates loaded by <see cref="EcbRatesJob"/> for the
|
||||
/// currencies of the table, and rates typed by hand. The rate of a day is the last one on or before it.
|
||||
/// </summary>
|
||||
public sealed class ExchangeRateService
|
||||
{
|
||||
/// <summary>The source of the ECB rates.</summary>
|
||||
public const string EcbSource = "ECB";
|
||||
|
||||
/// <summary>The source of the rates typed by hand.</summary>
|
||||
public const string ManualSource = "MANUAL";
|
||||
|
||||
/// <summary>Error: the rate is not positive.</summary>
|
||||
public const string RateInvalid = "tables.exchange-rate.invalid";
|
||||
|
||||
/// <summary>The fields of the grid.</summary>
|
||||
public static readonly ListFields<ExchangeRate> Fields = new ListFields<ExchangeRate>()
|
||||
.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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
public ExchangeRateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
}
|
||||
|
||||
/// <summary>A page of rates.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<ListPage<ExchangeRate>> 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<ExchangeRate, long>();
|
||||
var filtered = Fields.Apply(Query.For<ExchangeRate>(), query);
|
||||
var page = await repository.ListAsync(filtered, cancellationToken).ConfigureAwait(false);
|
||||
return new ListPage<ExchangeRate>(page.Items, page.TotalCount, new Dictionary<string, decimal>());
|
||||
}
|
||||
|
||||
/// <summary>The rate of a currency on a day: the last one on or before it; 1 for the euro.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="currency">The currency.</param>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rate, or <see langword="null"/> when none is known.</returns>
|
||||
public async Task<ExchangeRate?> 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<ExchangeRate, long>()
|
||||
.FindAsync(Query.For<ExchangeRate>().Where(x => x.CurrencyCode == code && x.RateDate <= date).OrderByDescending(x => x.RateDate), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Saves a rate typed by hand (replacing the one of the same day).</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="currency">The currency.</param>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <param name="rate">Units of the currency for one euro.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rate.</returns>
|
||||
/// <exception cref="ValidationFailedException">The rate is not positive or the currency is not in the table.</exception>
|
||||
public async Task<ExchangeRate> 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<Currency, long>().CountAsync(Query.For<Currency>().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;
|
||||
}
|
||||
|
||||
/// <summary>Stores ECB rates for the currencies of a company's table (manual rates of the same day are kept).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="rates">The ECB rates.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many rates were added or changed.</returns>
|
||||
public async Task<int> StoreEcbAsync(string companyCode, IReadOnlyList<EcbRate> 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<Currency, long>().ListAsync(Query.For<Currency>().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<ExchangeRate?> FindAsync(IUnitOfWork uow, string currency, DateOnly date, CancellationToken cancellationToken) =>
|
||||
uow.Repository<ExchangeRate, long>().FindAsync(Query.For<ExchangeRate>().Where(x => x.CurrencyCode == currency && x.RateDate == date), cancellationToken);
|
||||
|
||||
private async Task<ExchangeRate> UpsertAsync(IUnitOfWork uow, ExchangeRate rate, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<ExchangeRate, long>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days.</summary>
|
||||
/// <param name="client">The ECB client.</param>
|
||||
/// <param name="rates">The exchange rates.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "tables.ecb-rates";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> 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.");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A fiscal year with its months, as mockup 052 shows it.</summary>
|
||||
/// <param name="Year">The year.</param>
|
||||
/// <param name="Periods">The months, in order.</param>
|
||||
public sealed record FiscalYearView(FiscalYear Year, IReadOnlyList<FiscalPeriod> Periods);
|
||||
|
||||
/// <summary>What a date may receive.</summary>
|
||||
public enum PeriodUse
|
||||
{
|
||||
/// <summary>A document or entry without VAT (warehouse, quotations, orders).</summary>
|
||||
NoVat = 0,
|
||||
|
||||
/// <summary>A document or entry with VAT: refused once the VAT of the period is settled.</summary>
|
||||
Vat = 1,
|
||||
}
|
||||
|
||||
/// <summary>Why a date is refused (or <see cref="Open"/>).</summary>
|
||||
public enum PeriodState
|
||||
{
|
||||
/// <summary>The date is in an open period.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>No fiscal year contains the date.</summary>
|
||||
NoYear = 1,
|
||||
|
||||
/// <summary>The year is closed or being closed.</summary>
|
||||
YearClosed = 2,
|
||||
|
||||
/// <summary>The month is locked.</summary>
|
||||
Locked = 3,
|
||||
|
||||
/// <summary>The VAT of the month was settled (only for <see cref="PeriodUse.Vat"/>).</summary>
|
||||
Settled = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="CheckAsync"/>), used by
|
||||
/// every service that writes dated records. Years and months are cached per company.
|
||||
/// </summary>
|
||||
public sealed class FiscalYearService
|
||||
{
|
||||
/// <summary>Error: the date of the new year overlaps an existing year.</summary>
|
||||
public const string Overlap = "fiscal.year.overlap";
|
||||
|
||||
/// <summary>Error: the year is closed: its months cannot change.</summary>
|
||||
public const string YearClosedError = "fiscal.year.closed";
|
||||
|
||||
/// <summary>Error: the month cannot become open again because the VAT is settled (reopened with the settlement, M7).</summary>
|
||||
public const string SettledError = "fiscal.period.settled";
|
||||
|
||||
/// <summary>The error code thrown by <see cref="DemandOpenAsync"/>, followed by the <see cref="PeriodState"/>.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="cache">The cache.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The years, newest first, with their months.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The years.</returns>
|
||||
public async Task<IReadOnlyList<FiscalYearView>> 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)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a year with its months: after the last year, or the one containing <paramref name="day"/> when there are
|
||||
/// none (starting in the month of the profile).
|
||||
/// </summary>
|
||||
/// <param name="actor">Who creates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="day">A day of the first year, when the company has none.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new year.</returns>
|
||||
public async Task<FiscalYearView> 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;
|
||||
}
|
||||
|
||||
/// <summary>Locks or unlocks a month (unlocking a settled month is refused).</summary>
|
||||
/// <param name="actor">Who changes it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="periodId">The month.</param>
|
||||
/// <param name="locked">Lock or unlock.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The month.</returns>
|
||||
/// <exception cref="ValidationFailedException">The year is closed, or the month is settled.</exception>
|
||||
public async Task<FiscalPeriod> 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<FiscalPeriod, long>();
|
||||
period = await periods.GetAsync(periodId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TableService.NotFound);
|
||||
var year = await uow.Repository<FiscalYear, long>().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;
|
||||
}
|
||||
|
||||
/// <summary>Whether a date can receive a document or entry.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="use">With or without VAT.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The state of the date.</returns>
|
||||
public async Task<PeriodState> 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);
|
||||
}
|
||||
|
||||
/// <summary>Throws when a date cannot receive a document or entry.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="use">With or without VAT.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
/// <exception cref="ValidationFailedException">The date is refused: <c>fiscal.date.locked</c> and similar.</exception>
|
||||
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)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The error code of a refused date, such as <c>fiscal.date.locked</c>.</summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <returns>The code.</returns>
|
||||
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",
|
||||
};
|
||||
|
||||
/// <summary>The state of a date in a calendar.</summary>
|
||||
/// <param name="calendar">The years with their months.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <param name="use">With or without VAT.</param>
|
||||
/// <returns>The state.</returns>
|
||||
public static PeriodState StateOf(IEnumerable<FiscalYearView> 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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="day"/> when there are none.
|
||||
/// </summary>
|
||||
/// <param name="uow">The company unit of work.</param>
|
||||
/// <param name="day">A day of the first year.</param>
|
||||
/// <param name="userName">Who creates.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new year.</returns>
|
||||
internal async Task<FiscalYearView> CreateAsync(IUnitOfWork uow, DateOnly day, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var years = uow.Repository<FiscalYear, long>();
|
||||
var last = await years.FindAsync(Query.For<FiscalYear>().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<FiscalYear>().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<FiscalPeriod>();
|
||||
var repository = uow.Repository<FiscalPeriod, long>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Forgets the cached calendar of a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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<IReadOnlyList<FiscalYearView>> CalendarAsync(string company, CancellationToken cancellationToken) =>
|
||||
await _cache.GetOrCreateAsync<List<FiscalYearView>>(
|
||||
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<FiscalYear, long>().ListAsync(Query.For<FiscalYear>().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items;
|
||||
var periods = (await uow.Repository<FiscalPeriod, long>().ListAsync(Query.For<FiscalPeriod>().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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The company tables of SPEC §11.1 handled by <see cref="TableService"/>, each with its rules. Keys are in English
|
||||
/// (<c>tax-codes</c>); the interface gives them Italian addresses and names through the resources.
|
||||
/// </summary>
|
||||
public sealed partial class TableCatalog
|
||||
{
|
||||
/// <summary>Error: a percentage outside 0-100.</summary>
|
||||
public const string PercentRange = "tables.percent.range";
|
||||
|
||||
/// <summary>Error: the end of validity is before the start.</summary>
|
||||
public const string ValidityOrder = "tables.validity.order";
|
||||
|
||||
/// <summary>Error: the code does not follow the pattern of the table.</summary>
|
||||
public const string CodePattern = "tables.code.pattern";
|
||||
|
||||
/// <summary>Error: a value not in the fiscal pack's code list.</summary>
|
||||
public const string NotInCodeList = "tables.code-list.unknown";
|
||||
|
||||
/// <summary>Warning: a value that the code list marks obsolete.</summary>
|
||||
public const string ObsoleteInCodeList = "tables.code-list.obsolete";
|
||||
|
||||
/// <summary>Error: decimals outside the allowed range.</summary>
|
||||
public const string DecimalsRange = "tables.decimals.range";
|
||||
|
||||
/// <summary>Error: the IBAN is not valid.</summary>
|
||||
public const string IbanInvalid = "tables.iban.invalid";
|
||||
|
||||
/// <summary>Error: the BIC is not valid.</summary>
|
||||
public const string BicInvalid = "tables.bic.invalid";
|
||||
|
||||
/// <summary>Error: the e-mail address is not valid.</summary>
|
||||
public const string EmailInvalid = "tables.email.invalid";
|
||||
|
||||
/// <summary>Error: the VAT number is not valid.</summary>
|
||||
public const string VatNumberInvalid = "tables.vat-number.invalid";
|
||||
|
||||
/// <summary>Error: the parent does not exist, is the row itself or is too deep.</summary>
|
||||
public const string ParentInvalid = "tables.parent.invalid";
|
||||
|
||||
/// <summary>Error: a referenced row does not exist.</summary>
|
||||
public const string ReferenceMissing = "tables.reference.missing";
|
||||
|
||||
/// <summary>Error: the discount formula cannot be read.</summary>
|
||||
public const string FormulaInvalid = "tables.discount.formula";
|
||||
|
||||
/// <summary>Error: the numerator format has no <c>{number}</c>.</summary>
|
||||
public const string FormatInvalid = "tables.numerator.format";
|
||||
|
||||
/// <summary>Error: the year is outside 2000-2100.</summary>
|
||||
public const string YearRange = "tables.year.range";
|
||||
|
||||
/// <summary>Error: the last number is negative.</summary>
|
||||
public const string NumberRange = "tables.number.range";
|
||||
|
||||
/// <summary>Error: a transfer reason must not change quantities by itself.</summary>
|
||||
public const string TransferEffect = "tables.inventory-reason.transfer";
|
||||
|
||||
/// <summary>The maximum depth of item categories.</summary>
|
||||
public const int MaxCategoryLevel = 3;
|
||||
|
||||
private readonly Dictionary<Type, TableDefinition> _byType = [];
|
||||
private readonly Dictionary<string, TableDefinition> _byKey = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Creates the catalog.</summary>
|
||||
public TableCatalog()
|
||||
{
|
||||
Add(new TableDefinition<Country>("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<Province>("provinces", "provinces") { CodeLength = 2 }
|
||||
.Field("region", x => x.Region, searchable: true)
|
||||
.Rule((x, c) => Pattern(x.Code, TwoLetters(), c)));
|
||||
Add(new TableDefinition<Municipality>("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<Currency>("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<UnitOfMeasure>("units", "units_of_measure")
|
||||
.Rule((x, c) => Decimals(x.Decimals, 0, 6, nameof(UnitOfMeasure.Decimals), c)));
|
||||
Add(new TableDefinition<TaxCode>("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<PaymentMethod>("payment-methods", "payment_methods")
|
||||
.Field("einvoice", x => x.EInvoiceCode)
|
||||
.Rule((x, c) => InCodeList(x.EInvoiceCode, c.Pack.GetFeature<IEInvoiceFormat>()?.PaymentMethods, nameof(PaymentMethod.EInvoiceCode), c)));
|
||||
Add(new TableDefinition<PaymentTerm>("payment-terms", "payment_terms")
|
||||
.Field("condition", x => x.Condition)
|
||||
.Rule((x, c) => InCodeList(x.Condition, c.Pack.GetFeature<IEInvoiceFormat>()?.PaymentConditions, nameof(PaymentTerm.Condition), c))
|
||||
.Rule(async (x, c, ct) =>
|
||||
{
|
||||
if (x.PaymentMethodId is { } id && await c.GetAsync<PaymentMethod>(id, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
c.Error(nameof(PaymentTerm.PaymentMethodId), ReferenceMissing);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<BankAccount>("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<Salesperson>("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<Carrier>("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<ITaxIdentifierRules>() is { } rules)
|
||||
{
|
||||
x.VatNumber = rules.NormalizeVatNumber(x.VatNumber);
|
||||
if (!rules.IsValidVatNumber(x.VatNumber))
|
||||
{
|
||||
c.Error(nameof(Carrier.VatNumber), VatNumberInvalid);
|
||||
}
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<ShippingTerm>("shipping-terms", "shipping_terms"));
|
||||
Add(new TableDefinition<TransportMean>("transport-means", "transport_means"));
|
||||
Add(new TableDefinition<GoodsAppearance>("goods-appearances", "goods_appearances"));
|
||||
Add(new TableDefinition<DeliveryTerm>("delivery-terms", "delivery_terms"));
|
||||
Add(new TableDefinition<TransportReason>("transport-reasons", "transport_reasons"));
|
||||
Add(new TableDefinition<InventoryReason>("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<Warehouse>("warehouses", "warehouses") { SingleDefault = x => x.IsDefault }
|
||||
.Field("default", x => x.IsDefault));
|
||||
Add(new TableDefinition<ItemCategory>("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<ItemCategory>(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<PartyCategory>("party-categories", "party_categories"));
|
||||
Add(new TableDefinition<PriceList>("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<PriceList>(baseId, ct).ConfigureAwait(false) is null))
|
||||
{
|
||||
c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<DiscountPolicy>("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<DocumentNumerator>("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<DocumentType>("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<IEInvoiceFormat>()?.DocumentTypes, nameof(DocumentType.EInvoiceType), c);
|
||||
}
|
||||
else
|
||||
{
|
||||
x.EInvoiceType = null;
|
||||
}
|
||||
|
||||
if (x.NumeratorId is { } numeratorId && await c.GetAsync<DocumentNumerator>(numeratorId, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
c.Error(nameof(DocumentType.NumeratorId), ReferenceMissing);
|
||||
}
|
||||
|
||||
if (x.InventoryReasonId is { } reasonId && await c.GetAsync<InventoryReason>(reasonId, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
c.Error(nameof(DocumentType.InventoryReasonId), ReferenceMissing);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<CostCenter>("cost-centers", "cost_centers") { CodeLength = 20 }
|
||||
.Rule(async (x, c, ct) =>
|
||||
{
|
||||
if (x.ParentId is { } parentId && (parentId == x.Id || await c.GetAsync<CostCenter>(parentId, ct).ConfigureAwait(false) is null))
|
||||
{
|
||||
c.Error(nameof(CostCenter.ParentId), ParentInvalid);
|
||||
}
|
||||
}));
|
||||
Add(new TableDefinition<Job>("jobs", "jobs") { CodeLength = 20 }
|
||||
.Field("status", x => x.Status)
|
||||
.Rule((x, c) => Validity(x.StartDate, x.EndDate, nameof(Job.EndDate), c)));
|
||||
}
|
||||
|
||||
/// <summary>Every table, in the order of SPEC §11.1.</summary>
|
||||
public IEnumerable<TableDefinition> All => _byKey.Values;
|
||||
|
||||
/// <summary>The definition of an entity.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <returns>The definition.</returns>
|
||||
public TableDefinition<T> Get<T>()
|
||||
where T : CodedEntity, new() =>
|
||||
(TableDefinition<T>)(_byType.GetValueOrDefault(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not a company table."));
|
||||
|
||||
/// <summary>A definition by key.</summary>
|
||||
/// <param name="key">The key, such as <c>tax-codes</c>.</param>
|
||||
/// <returns>The definition, or <see langword="null"/>.</returns>
|
||||
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<T>(TableDefinition<T> definition)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
_byType.Add(typeof(T), definition);
|
||||
_byKey.Add(definition.Key, definition);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A chain of discounts such as <c>10+5</c>: each step applies to what the previous left.</summary>
|
||||
public static class DiscountFormula
|
||||
{
|
||||
/// <summary>Reads a formula: percentages 0-100 separated by <c>+</c>, decimal comma or point.</summary>
|
||||
/// <param name="formula">The formula.</param>
|
||||
/// <param name="steps">The percentages.</param>
|
||||
/// <returns>Whether it could be read.</returns>
|
||||
public static bool TryParse(string? formula, out IReadOnlyList<decimal> steps)
|
||||
{
|
||||
steps = [];
|
||||
if (string.IsNullOrWhiteSpace(formula))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = new List<decimal>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Writes a formula in the Italian form, such as <c>10+5,5</c>.</summary>
|
||||
/// <param name="steps">The percentages.</param>
|
||||
/// <returns>The formula.</returns>
|
||||
public static string Format(IEnumerable<decimal> steps) =>
|
||||
string.Join('+', steps.Select(s => s.ToString("0.##", CultureInfo.GetCultureInfo("it-IT"))));
|
||||
|
||||
/// <summary>The single discount equal to the chain: 10+5 is 14.5%.</summary>
|
||||
/// <param name="steps">The percentages.</param>
|
||||
/// <returns>The equivalent percentage.</returns>
|
||||
public static decimal Equivalent(IEnumerable<decimal> steps) =>
|
||||
100m - (steps.Aggregate(1m, (left, step) => left * (1 - (step / 100m))) * 100m);
|
||||
}
|
||||
|
||||
/// <summary>The format of document numbers: <c>{prefix}</c>, <c>{year}</c>, <c>{section}</c> and <c>{number}</c> (with <c>:D6</c> and similar).</summary>
|
||||
public static partial class DocumentNumberFormat
|
||||
{
|
||||
/// <summary>Whether a format has the number and only known placeholders.</summary>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <returns>Whether it is valid.</returns>
|
||||
public static bool IsValid(string? format) =>
|
||||
!string.IsNullOrWhiteSpace(format) && format.Length <= 60 && NumberPlaceholder().IsMatch(format) &&
|
||||
Placeholder().Matches(format).All(m => Known().IsMatch(m.Value));
|
||||
|
||||
/// <summary>Writes a number with a format.</summary>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="number">The number.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="prefix">The prefix.</param>
|
||||
/// <param name="section">The section.</param>
|
||||
/// <returns>The document number, such as <c>FV/2026/000123</c>.</returns>
|
||||
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();
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A problem found on a field of a table row: an error blocks the save, a warning does not.</summary>
|
||||
/// <param name="Field">The property, such as <c>Code</c>.</param>
|
||||
/// <param name="Code">The stable code, translated by the interface (<c>tables.code.required</c>).</param>
|
||||
/// <param name="IsWarning">Whether it is only a warning.</param>
|
||||
public sealed record TableProblem(string Field, string Code, bool IsWarning = false);
|
||||
|
||||
/// <summary>What the rules of a table can use: the fiscal pack of the company and the other rows.</summary>
|
||||
public sealed class TableRuleContext
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly List<TableProblem> _problems = [];
|
||||
|
||||
internal TableRuleContext(IUnitOfWork unitOfWork, IFiscalPack pack)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
Pack = pack;
|
||||
}
|
||||
|
||||
/// <summary>The fiscal pack of the company's country.</summary>
|
||||
public IFiscalPack Pack { get; }
|
||||
|
||||
/// <summary>The problems found so far.</summary>
|
||||
public IReadOnlyList<TableProblem> Problems => _problems;
|
||||
|
||||
/// <summary>Adds an error.</summary>
|
||||
/// <param name="field">The property.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
public void Error(string field, string code) => _problems.Add(new TableProblem(field, code));
|
||||
|
||||
/// <summary>Adds a warning.</summary>
|
||||
/// <param name="field">The property.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
public void Warning(string field, string code) => _problems.Add(new TableProblem(field, code, IsWarning: true));
|
||||
|
||||
/// <summary>Reads another row by id.</summary>
|
||||
/// <typeparam name="TOther">The entity.</typeparam>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The row, or <see langword="null"/>.</returns>
|
||||
public Task<TOther?> GetAsync<TOther>(long id, CancellationToken cancellationToken)
|
||||
where TOther : class, IEntity<long>, new() =>
|
||||
_unitOfWork.Repository<TOther, long>().GetAsync(id, cancellationToken);
|
||||
|
||||
/// <summary>Whether a coded row with a code exists.</summary>
|
||||
/// <typeparam name="TOther">The entity.</typeparam>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Whether it exists.</returns>
|
||||
public async Task<bool> ExistsAsync<TOther>(string? code, CancellationToken cancellationToken)
|
||||
where TOther : CodedEntity, new() =>
|
||||
!string.IsNullOrEmpty(code) &&
|
||||
await _unitOfWork.Repository<TOther, long>().CountAsync(Query.For<TOther>().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>A company table that the generic maschera and service handle (SPEC §11.1, mockup 076).</summary>
|
||||
public abstract class TableDefinition
|
||||
{
|
||||
/// <summary>Creates the definition.</summary>
|
||||
/// <param name="key">The key used in addresses and resources, such as <c>tax-codes</c>.</param>
|
||||
/// <param name="table">The database table.</param>
|
||||
protected TableDefinition(string key, string table)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(table);
|
||||
Key = key;
|
||||
Table = table;
|
||||
}
|
||||
|
||||
/// <summary>The key, such as <c>tax-codes</c>.</summary>
|
||||
public string Key { get; }
|
||||
|
||||
/// <summary>The database table, such as <c>tax_codes</c>.</summary>
|
||||
public string Table { get; }
|
||||
|
||||
/// <summary>The entity type.</summary>
|
||||
public abstract Type EntityType { get; }
|
||||
|
||||
/// <summary>The maximum length of the code.</summary>
|
||||
public int CodeLength { get; init; } = 10;
|
||||
|
||||
/// <summary>Whether codes are kept as typed instead of upper case (municipality names are not codes).</summary>
|
||||
public bool KeepCodeCase { get; init; }
|
||||
|
||||
/// <summary>The CSV columns: header and property.</summary>
|
||||
public abstract IReadOnlyList<TableCsvColumn> CsvColumns { get; }
|
||||
}
|
||||
|
||||
/// <summary>A CSV column of a table: the snake_case header and the property.</summary>
|
||||
/// <param name="Header">The header.</param>
|
||||
/// <param name="Property">The property.</param>
|
||||
public sealed record TableCsvColumn(string Header, PropertyInfo Property);
|
||||
|
||||
/// <summary>A company table of <typeparamref name="T"/>.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
public sealed partial class TableDefinition<T> : TableDefinition
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
private static readonly HashSet<string> NotInCsv = new(StringComparer.Ordinal)
|
||||
{
|
||||
nameof(Entity<long>.Id), nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy),
|
||||
nameof(IAuditable.RowVersion), nameof(CodedEntity.IsDemo),
|
||||
};
|
||||
|
||||
private readonly List<Func<T, TableRuleContext, CancellationToken, Task>> _rules = [];
|
||||
private IReadOnlyList<TableCsvColumn>? _csv;
|
||||
|
||||
/// <summary>Creates the definition with the list fields <c>code</c>, <c>description</c>, <c>disabled</c>.</summary>
|
||||
/// <param name="key">The key, such as <c>tax-codes</c>.</param>
|
||||
/// <param name="table">The database table.</param>
|
||||
public TableDefinition(string key, string table)
|
||||
: base(key, table)
|
||||
{
|
||||
Fields = new ListFields<T>()
|
||||
.Add("code", x => x.Code, searchable: true)
|
||||
.Add("description", x => x.Description, searchable: true)
|
||||
.Add("disabled", x => x.Disabled)
|
||||
.OrderByDefault(new ListSort("code"));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Type EntityType => typeof(T);
|
||||
|
||||
/// <summary>The fields of the grid: filters, search and ordering.</summary>
|
||||
public ListFields<T> Fields { get; }
|
||||
|
||||
/// <summary>The rules run before every save, after the common ones (code and description).</summary>
|
||||
public IReadOnlyList<Func<T, TableRuleContext, CancellationToken, Task>> Rules => _rules;
|
||||
|
||||
/// <summary>The flag that only one row may have (the default bank account, the default warehouse).</summary>
|
||||
public Expression<Func<T, bool>>? SingleDefault { get; init; }
|
||||
|
||||
/// <summary>The other fields that, with the code, make a row unique (the year of a numerator).</summary>
|
||||
public Func<T, Expression<Func<T, bool>>>? SameKey { get; init; }
|
||||
|
||||
/// <summary>Called before the rules, to fill derived fields (the kind of a VAT code).</summary>
|
||||
public Action<T, IFiscalPack>? Complete { get; init; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<TableCsvColumn> 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)),
|
||||
];
|
||||
|
||||
/// <summary>Adds a rule.</summary>
|
||||
/// <param name="rule">The rule.</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public TableDefinition<T> Rule(Func<T, TableRuleContext, CancellationToken, Task> rule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
_rules.Add(rule);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds a rule that needs no other rows.</summary>
|
||||
/// <param name="rule">The rule.</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public TableDefinition<T> Rule(Action<T, TableRuleContext> rule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rule);
|
||||
_rules.Add((row, context, _) =>
|
||||
{
|
||||
rule(row, context);
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds a grid field.</summary>
|
||||
/// <typeparam name="TValue">The type.</typeparam>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="selector">The property.</param>
|
||||
/// <param name="searchable">Whether the search box looks in it.</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public TableDefinition<T> Field<TValue>(string id, Expression<Func<T, TValue>> 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();
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>What a delete did.</summary>
|
||||
public enum TableDeleteOutcome
|
||||
{
|
||||
/// <summary>The row is gone.</summary>
|
||||
Deleted = 0,
|
||||
|
||||
/// <summary>The row is used elsewhere: it was disabled instead.</summary>
|
||||
Disabled = 1,
|
||||
}
|
||||
|
||||
/// <summary>A row of a CSV import that could not be read or saved.</summary>
|
||||
/// <param name="Row">The row number in the file, from 2 (1 is the header).</param>
|
||||
/// <param name="Field">The column, or <see langword="null"/> for the whole row.</param>
|
||||
/// <param name="Code">The problem.</param>
|
||||
public sealed record TableImportError(int Row, string? Field, string Code);
|
||||
|
||||
/// <summary>The result of a CSV import: nothing is saved when there are errors.</summary>
|
||||
/// <param name="Inserted">New rows.</param>
|
||||
/// <param name="Updated">Rows changed (found by code).</param>
|
||||
/// <param name="Errors">The errors.</param>
|
||||
public sealed record TableImportResult(int Inserted, int Updated, IReadOnlyList<TableImportError> Errors)
|
||||
{
|
||||
/// <summary>Whether the import was saved.</summary>
|
||||
public bool Succeeded => Errors.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The company tables of SPEC §11.1 through one service (wiki <i>Tabelle azienda</i>): 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.
|
||||
/// </summary>
|
||||
/// <remarks>Reading needs <c>company.settings.read</c>, changing <c>company.settings.write</c>.</remarks>
|
||||
public sealed class TableService
|
||||
{
|
||||
/// <summary>Permission to see the tables.</summary>
|
||||
public const string ReadPermission = "company.settings.read";
|
||||
|
||||
/// <summary>Permission to change the tables.</summary>
|
||||
public const string WritePermission = "company.settings.write";
|
||||
|
||||
/// <summary>Error: the code is missing.</summary>
|
||||
public const string CodeRequired = "tables.code.required";
|
||||
|
||||
/// <summary>Error: the code is too long.</summary>
|
||||
public const string CodeTooLong = "tables.code.too-long";
|
||||
|
||||
/// <summary>Error: another row has the code.</summary>
|
||||
public const string CodeDuplicate = "tables.code.duplicate";
|
||||
|
||||
/// <summary>Error: the description is missing.</summary>
|
||||
public const string DescriptionRequired = "tables.description.required";
|
||||
|
||||
/// <summary>Error: the row changed or was deleted meanwhile.</summary>
|
||||
public const string NotFound = "tables.not-found";
|
||||
|
||||
/// <summary>Import error: the header has no <c>code</c> column.</summary>
|
||||
public const string CsvNoCode = "tables.csv.no-code";
|
||||
|
||||
/// <summary>Import error: a value cannot be read.</summary>
|
||||
public const string CsvBadValue = "tables.csv.bad-value";
|
||||
|
||||
/// <summary>Import error: unknown column (a warning in the result: the column is ignored).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="cache">The cache of the rows.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="catalog">The tables.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The tables.</summary>
|
||||
public TableCatalog Catalog => _catalog;
|
||||
|
||||
/// <summary>Every row of a table, from the cache (disabled ones included), ordered by code.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<T>> AllAsync<T>(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<T>(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The rows still in use (not disabled), for the choices on other records.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<T>> ActiveAsync<T>(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new() =>
|
||||
[.. (await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false)).Where(r => !r.Disabled)];
|
||||
|
||||
/// <summary>A page of a table for the grid.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">Search, filters, ordering and page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<ListPage<T>> ListAsync<T>(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var rows = await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
return _catalog.Get<T>().Fields.Apply(rows, query);
|
||||
}
|
||||
|
||||
/// <summary>One row, read from the database.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The row, or <see langword="null"/>.</returns>
|
||||
public async Task<T?> GetAsync<T>(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<T, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Checks a row without saving it: the messages next to the fields.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who checks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="row">The row (normalized in place: trimmed code in upper case, derived fields).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Errors and warnings.</returns>
|
||||
public async Task<IReadOnlyList<TableProblem>> ValidateAsync<T>(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<T>(), row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Saves a row: inserts it when <see cref="Core.Entities.Entity{TKey}.Id"/> is 0, updates it otherwise.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The saved row, with its id and new row version.</returns>
|
||||
/// <exception cref="ValidationFailedException">A rule failed; <see cref="ValidationFailedException.Errors"/> has <c>Field:code</c>.</exception>
|
||||
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the row meanwhile.</exception>
|
||||
public async Task<T> SaveAsync<T>(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<T>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Deletes a row, or disables it when other records use it.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The row.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened.</returns>
|
||||
/// <exception cref="KeyNotFoundException">No such row.</exception>
|
||||
public async Task<TableDeleteOutcome> DeleteAsync<T>(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<T>();
|
||||
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<T, long>();
|
||||
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<T, long>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Writes a table as CSV (Italian format: <c>;</c>, decimal comma, byte order mark).</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who exports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="output">The stream; left open.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows written.</returns>
|
||||
public async Task<int> ExportCsvAsync<T>(Actor actor, string companyCode, Stream output, CancellationToken cancellationToken = default)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var rows = await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
var columns = _catalog.Get<T>().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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="content">The CSV.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Counts and errors.</returns>
|
||||
public async Task<TableImportResult> ImportCsvAsync<T>(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<T>();
|
||||
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<TableImportError>();
|
||||
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<T, long>().ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var pending = new List<T>();
|
||||
|
||||
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<T>.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, []);
|
||||
}
|
||||
|
||||
/// <summary>Saves rows without permission checks or rules: the seeders (§14), inside their own unit of work.</summary>
|
||||
/// <typeparam name="T">The entity.</typeparam>
|
||||
/// <param name="unitOfWork">The company unit of work.</param>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="userName">Who writes, such as <c>system</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
internal Task WriteAsync<T>(IUnitOfWork unitOfWork, T row, string userName, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new() =>
|
||||
WriteAsync(unitOfWork, _catalog.Get<T>(), row, userName, cancellationToken);
|
||||
|
||||
/// <summary>Forgets the cached rows of every table of a company (after the seeders).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask InvalidateAllAsync(string companyCode, CancellationToken cancellationToken = default) =>
|
||||
_cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "tables"), cancellationToken);
|
||||
|
||||
private static async Task<IReadOnlyList<TableProblem>> CheckAsync<T>(
|
||||
IUnitOfWork uow, IFiscalPack pack, TableDefinition<T> 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<T>().Where(x => x.Code == code && x.Id != id);
|
||||
if (definition.SameKey is { } sameKey)
|
||||
{
|
||||
query = query.Where(sameKey(row));
|
||||
}
|
||||
|
||||
if (await uow.Repository<T, long>().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<TableProblem> 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>(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<T>(IUnitOfWork uow, TableDefinition<T> definition, T row, string userName, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
var repository = uow.Repository<T, long>();
|
||||
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<T>(IRepository<T, long> repository, System.Linq.Expressions.Expression<Func<T, bool>> flag, long id, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
var others = await repository.ListAsync(Query.For<T>().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<IReadOnlyList<T>> RowsAsync<T>(string company, TableDefinition<T> definition, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new() =>
|
||||
await _cache.GetOrCreateAsync<List<T>>(
|
||||
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<T, long>().ListAsync(Query.For<T>().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<string> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Core.Tables;
|
||||
|
||||
/// <summary>A row of a company table with a code the users type and a description (SPEC §11.1).</summary>
|
||||
public interface ICodedRecord : IEntity<long>
|
||||
{
|
||||
/// <summary>The code, unique in the table.</summary>
|
||||
string Code { get; set; }
|
||||
|
||||
/// <summary>The description (or the name).</summary>
|
||||
string Description { get; set; }
|
||||
|
||||
/// <summary>Hidden from choices on new records; kept for old ones.</summary>
|
||||
bool Disabled { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Base class of the coded tables.</summary>
|
||||
public abstract class CodedEntity : Entity<long>, ICodedRecord, IDemoMarkable
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A country (ISO 3166-1).</summary>
|
||||
public sealed class Country : CodedEntity
|
||||
{
|
||||
/// <summary>ISO 3166-1 alpha-3 code.</summary>
|
||||
public string? Iso3 { get; set; }
|
||||
|
||||
/// <summary>Member of the European Union (VIES, Intrastat, intra-EU VAT).</summary>
|
||||
public bool EuMember { get; set; }
|
||||
|
||||
/// <summary>The prefix of VAT numbers, when different from the code (Greece: <c>EL</c>).</summary>
|
||||
public string? VatPrefix { get; set; }
|
||||
|
||||
/// <summary>The usual currency (ISO 4217).</summary>
|
||||
public string? CurrencyCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An Italian province (code = the two-letter abbreviation).</summary>
|
||||
public sealed class Province : CodedEntity
|
||||
{
|
||||
/// <summary>The region.</summary>
|
||||
public string? Region { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An Italian municipality (code = cadastral code, used by the fiscal code).</summary>
|
||||
public sealed class Municipality : CodedEntity
|
||||
{
|
||||
/// <summary>The province abbreviation.</summary>
|
||||
public string ProvinceCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The region.</summary>
|
||||
public string? Region { get; set; }
|
||||
|
||||
/// <summary>The ISTAT code (6 digits).</summary>
|
||||
public string? IstatCode { get; set; }
|
||||
|
||||
/// <summary>The postal codes, comma separated (one for most municipalities, a range for large cities).</summary>
|
||||
public string? PostalCodes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A currency (ISO 4217).</summary>
|
||||
public sealed class Currency : CodedEntity
|
||||
{
|
||||
/// <summary>The symbol, such as €.</summary>
|
||||
public string? Symbol { get; set; }
|
||||
|
||||
/// <summary>Decimals of amounts.</summary>
|
||||
public int Decimals { get; set; } = 2;
|
||||
}
|
||||
|
||||
/// <summary>An exchange rate: units of the currency for one euro on a day (ECB reference rate or manual).</summary>
|
||||
public sealed class ExchangeRate : Entity<long>
|
||||
{
|
||||
/// <summary>The currency (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The day.</summary>
|
||||
public DateOnly RateDate { get; set; }
|
||||
|
||||
/// <summary>Units of the currency for one euro.</summary>
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
/// <summary>Where the rate comes from: <c>ECB</c> or <c>MANUAL</c>.</summary>
|
||||
public string Source { get; set; } = "MANUAL";
|
||||
}
|
||||
|
||||
/// <summary>A unit of measure.</summary>
|
||||
public sealed class UnitOfMeasure : CodedEntity
|
||||
{
|
||||
/// <summary>Decimals allowed in quantities.</summary>
|
||||
public int Decimals { get; set; }
|
||||
|
||||
/// <summary>The text written in <c>UnitaMisura</c> of the e-invoice, when different from the code.</summary>
|
||||
public string? EInvoiceCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A VAT code (mockup 076).</summary>
|
||||
public sealed class TaxCode : CodedEntity
|
||||
{
|
||||
/// <summary>The rate in percent.</summary>
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
/// <summary>The nature for zero-rate operations (N1...N7).</summary>
|
||||
public string? Nature { get; set; }
|
||||
|
||||
/// <summary>The kind of operation, from rate and nature.</summary>
|
||||
public TaxCodeKind Kind { get; set; }
|
||||
|
||||
/// <summary>When the tax becomes due.</summary>
|
||||
public TaxExigibility Exigibility { get; set; }
|
||||
|
||||
/// <summary>Share of the purchase tax that cannot be deducted.</summary>
|
||||
public decimal NonDeductiblePercent { get; set; }
|
||||
|
||||
/// <summary>The law printed on the invoice.</summary>
|
||||
public string? LegalReference { get; set; }
|
||||
|
||||
/// <summary>First day of validity.</summary>
|
||||
public DateOnly? ValidFrom { get; set; }
|
||||
|
||||
/// <summary>Last day of validity.</summary>
|
||||
public DateOnly? ValidTo { get; set; }
|
||||
|
||||
/// <summary>The VAT account for sales (ledger, M7).</summary>
|
||||
public string? SalesAccountCode { get; set; }
|
||||
|
||||
/// <summary>The VAT account for purchases (ledger, M7).</summary>
|
||||
public string? PurchaseAccountCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A payment method (MP01...MP23).</summary>
|
||||
public sealed class PaymentMethod : CodedEntity
|
||||
{
|
||||
/// <summary>The FatturaPA code, such as <c>MP05</c>.</summary>
|
||||
public string EInvoiceCode { get; set; } = "MP05";
|
||||
|
||||
/// <summary>Whether a bank of the customer (RiBa, direct debit) or of the company (transfer) is needed.</summary>
|
||||
public bool NeedsBank { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Payment terms with their installments (lines).</summary>
|
||||
public sealed class PaymentTerm : CodedEntity
|
||||
{
|
||||
/// <summary>The payment method.</summary>
|
||||
public long? PaymentMethodId { get; set; }
|
||||
|
||||
/// <summary>The FatturaPA condition: TP01 installments, TP02 full, TP03 advance.</summary>
|
||||
public string Condition { get; set; } = "TP02";
|
||||
|
||||
/// <summary>All the VAT on the first installment.</summary>
|
||||
public bool VatOnFirstInstallment { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An installment of payment terms.</summary>
|
||||
public sealed class PaymentTermLine : Entity<long>
|
||||
{
|
||||
/// <summary>The payment terms.</summary>
|
||||
public long PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>The order of the installment, from 1.</summary>
|
||||
public int Number { get; set; }
|
||||
|
||||
/// <summary>Days from the document date.</summary>
|
||||
public int Days { get; set; }
|
||||
|
||||
/// <summary>Move the due date to the end of the month.</summary>
|
||||
public bool EndOfMonth { get; set; }
|
||||
|
||||
/// <summary>A fixed day of the month after the end-of-month move, such as 10.</summary>
|
||||
public int? FixedDay { get; set; }
|
||||
|
||||
/// <summary>Share of the amount, in percent.</summary>
|
||||
public decimal Percent { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A bank account of the company.</summary>
|
||||
public sealed class BankAccount : CodedEntity
|
||||
{
|
||||
/// <summary>The bank.</summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>The IBAN, compact.</summary>
|
||||
public string? Iban { get; set; }
|
||||
|
||||
/// <summary>The BIC.</summary>
|
||||
public string? Bic { get; set; }
|
||||
|
||||
/// <summary>The SIA code for RiBa files.</summary>
|
||||
public string? SiaCode { get; set; }
|
||||
|
||||
/// <summary>The CBI CUC code.</summary>
|
||||
public string? CucCode { get; set; }
|
||||
|
||||
/// <summary>The ledger account (M7).</summary>
|
||||
public string? AccountCode { get; set; }
|
||||
|
||||
/// <summary>The account proposed on documents.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A sales agent (code + name in <see cref="CodedEntity.Description"/>).</summary>
|
||||
public sealed class Salesperson : CodedEntity
|
||||
{
|
||||
/// <summary>The e-mail address.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>The usual commission, in percent.</summary>
|
||||
public decimal CommissionPercent { get; set; }
|
||||
|
||||
/// <summary>Subject to ENASARCO contributions.</summary>
|
||||
public bool Enasarco { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A carrier (code + name).</summary>
|
||||
public sealed class Carrier : CodedEntity
|
||||
{
|
||||
/// <summary>The VAT number.</summary>
|
||||
public string? VatNumber { get; set; }
|
||||
|
||||
/// <summary>The address.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>The town.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>The phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>The e-mail address.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The registration number in the haulage register.</summary>
|
||||
public string? RegisterNumber { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Who pays the transport (porto: franco, assegnato...).</summary>
|
||||
public sealed class ShippingTerm : CodedEntity;
|
||||
|
||||
/// <summary>Who carries the goods (mittente, destinatario, vettore).</summary>
|
||||
public sealed class TransportMean : CodedEntity;
|
||||
|
||||
/// <summary>The appearance of the goods on the delivery note (cartoni, bancali...).</summary>
|
||||
public sealed class GoodsAppearance : CodedEntity;
|
||||
|
||||
/// <summary>An Incoterms rule.</summary>
|
||||
public sealed class DeliveryTerm : CodedEntity;
|
||||
|
||||
/// <summary>The reason of the transport (vendita, conto visione...).</summary>
|
||||
public sealed class TransportReason : CodedEntity;
|
||||
|
||||
/// <summary>What a stock movement does to the quantity on hand.</summary>
|
||||
public enum StockEffect
|
||||
{
|
||||
/// <summary>No effect on quantities.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>Increases the stock (load).</summary>
|
||||
Load = 1,
|
||||
|
||||
/// <summary>Decreases the stock (unload).</summary>
|
||||
Unload = 2,
|
||||
}
|
||||
|
||||
/// <summary>A warehouse movement reason.</summary>
|
||||
public sealed class InventoryReason : CodedEntity
|
||||
{
|
||||
/// <summary>The effect on the quantity.</summary>
|
||||
public StockEffect Effect { get; set; }
|
||||
|
||||
/// <summary>Whether it changes the stock value (purchases, sales) or only quantities (transfers).</summary>
|
||||
public bool AffectsValue { get; set; } = true;
|
||||
|
||||
/// <summary>Whether it is a transfer between warehouses (needs a destination).</summary>
|
||||
public bool IsTransfer { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A warehouse.</summary>
|
||||
public sealed class Warehouse : CodedEntity
|
||||
{
|
||||
/// <summary>The address.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>The town.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>The province abbreviation.</summary>
|
||||
public string? ProvinceCode { get; set; }
|
||||
|
||||
/// <summary>The warehouse proposed on documents.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A category of items, on up to three levels.</summary>
|
||||
public sealed class ItemCategory : CodedEntity
|
||||
{
|
||||
/// <summary>The parent category.</summary>
|
||||
public long? ParentId { get; set; }
|
||||
|
||||
/// <summary>The level, 1 to 3.</summary>
|
||||
public int Level { get; set; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>A category of customers and suppliers.</summary>
|
||||
public sealed class PartyCategory : CodedEntity;
|
||||
|
||||
/// <summary>A price list (the prices are in <c>item_prices</c>, mockup 018).</summary>
|
||||
public sealed class PriceList : CodedEntity
|
||||
{
|
||||
/// <summary>The currency (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = "EUR";
|
||||
|
||||
/// <summary>Prices include VAT (retail).</summary>
|
||||
public bool VatIncluded { get; set; }
|
||||
|
||||
/// <summary>First day of validity.</summary>
|
||||
public DateOnly? ValidFrom { get; set; }
|
||||
|
||||
/// <summary>Last day of validity.</summary>
|
||||
public DateOnly? ValidTo { get; set; }
|
||||
|
||||
/// <summary>The list this one derives from.</summary>
|
||||
public long? BasePriceListId { get; set; }
|
||||
|
||||
/// <summary>Change applied to the base list, in percent (negative for a discount).</summary>
|
||||
public decimal MarkupPercent { get; set; }
|
||||
|
||||
/// <summary>Rounding step of derived prices, such as 0.05; zero for none.</summary>
|
||||
public decimal RoundingStep { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A discount policy: a chain of discounts such as <c>10+5</c>.</summary>
|
||||
public sealed class DiscountPolicy : CodedEntity
|
||||
{
|
||||
/// <summary>The chain of discounts in percent, separated by +.</summary>
|
||||
public string Formula { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The family of a document numerator.</summary>
|
||||
public enum NumeratorKind
|
||||
{
|
||||
/// <summary>Quotations.</summary>
|
||||
Quotation = 0,
|
||||
|
||||
/// <summary>Customer orders.</summary>
|
||||
SalesOrder = 1,
|
||||
|
||||
/// <summary>Delivery notes.</summary>
|
||||
DeliveryNote = 2,
|
||||
|
||||
/// <summary>Sales invoices and credit notes (no gaps).</summary>
|
||||
SalesInvoice = 3,
|
||||
|
||||
/// <summary>Supplier orders.</summary>
|
||||
PurchaseOrder = 4,
|
||||
|
||||
/// <summary>Purchase protocol.</summary>
|
||||
PurchaseInvoice = 5,
|
||||
|
||||
/// <summary>Warehouse movements.</summary>
|
||||
Inventory = 6,
|
||||
|
||||
/// <summary>Journal entries (no gaps).</summary>
|
||||
Journal = 7,
|
||||
|
||||
/// <summary>Anything else.</summary>
|
||||
Other = 8,
|
||||
}
|
||||
|
||||
/// <summary>A document numerator for a year (assignment at confirmation arrives with the documents, M5).</summary>
|
||||
public sealed class DocumentNumerator : CodedEntity
|
||||
{
|
||||
/// <summary>The family.</summary>
|
||||
public NumeratorKind Kind { get; set; }
|
||||
|
||||
/// <summary>The section (sezionale), such as <c>A</c>; empty for the main one.</summary>
|
||||
public string? Section { get; set; }
|
||||
|
||||
/// <summary>The year.</summary>
|
||||
public int Year { get; set; }
|
||||
|
||||
/// <summary>The prefix.</summary>
|
||||
public string? Prefix { get; set; }
|
||||
|
||||
/// <summary>The format, such as <c>{prefix}/{year}/{number:D6}</c>.</summary>
|
||||
public string Format { get; set; } = "{number}/{year}";
|
||||
|
||||
/// <summary>The last number assigned.</summary>
|
||||
public long LastNumber { get; set; }
|
||||
|
||||
/// <summary>Whether gaps are allowed (never for invoices, credit notes and final entries).</summary>
|
||||
public bool GapsAllowed { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A type of document: the links between a document and its numerator, warehouse reason and SDI type.</summary>
|
||||
public sealed class DocumentType : CodedEntity
|
||||
{
|
||||
/// <summary>The family of document.</summary>
|
||||
public NumeratorKind Kind { get; set; }
|
||||
|
||||
/// <summary>The numerator.</summary>
|
||||
public long? NumeratorId { get; set; }
|
||||
|
||||
/// <summary>The warehouse reason.</summary>
|
||||
public long? InventoryReasonId { get; set; }
|
||||
|
||||
/// <summary>The SDI document type (TD01...).</summary>
|
||||
public string? EInvoiceType { get; set; }
|
||||
|
||||
/// <summary>The journal template (ledger, M7).</summary>
|
||||
public string? JournalTemplateCode { get; set; }
|
||||
|
||||
/// <summary>The VAT register (ledger, M7).</summary>
|
||||
public string? VatRegisterCode { get; set; }
|
||||
|
||||
/// <summary>The print template.</summary>
|
||||
public string? PrintTemplate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A cost centre.</summary>
|
||||
public sealed class CostCenter : CodedEntity
|
||||
{
|
||||
/// <summary>The parent cost centre.</summary>
|
||||
public long? ParentId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a job.</summary>
|
||||
public enum JobStatus
|
||||
{
|
||||
/// <summary>Open.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>Suspended.</summary>
|
||||
Suspended = 1,
|
||||
|
||||
/// <summary>Closed.</summary>
|
||||
Closed = 2,
|
||||
}
|
||||
|
||||
/// <summary>A job (commessa).</summary>
|
||||
public sealed class Job : CodedEntity
|
||||
{
|
||||
/// <summary>The customer, when the job is for one.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <summary>The start.</summary>
|
||||
public DateOnly? StartDate { get; set; }
|
||||
|
||||
/// <summary>The end.</summary>
|
||||
public DateOnly? EndDate { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public JobStatus Status { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Core.Tables;
|
||||
|
||||
/// <summary>The data of the company itself, one row per company database (SPEC §11.1, mockup 075).</summary>
|
||||
public sealed class CompanyProfile : Entity<long>
|
||||
{
|
||||
/// <summary>The company name.</summary>
|
||||
public string LegalName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The name written on fiscal documents, when different.</summary>
|
||||
public string? FiscalName { get; set; }
|
||||
|
||||
/// <summary>The VAT number, without the country prefix.</summary>
|
||||
public string? VatNumber { get; set; }
|
||||
|
||||
/// <summary>The tax code.</summary>
|
||||
public string? TaxCode { get; set; }
|
||||
|
||||
/// <summary>The province of the business register (REA).</summary>
|
||||
public string? ReaOffice { get; set; }
|
||||
|
||||
/// <summary>The number in the business register (REA).</summary>
|
||||
public string? ReaNumber { get; set; }
|
||||
|
||||
/// <summary>The share capital.</summary>
|
||||
public decimal? ShareCapital { get; set; }
|
||||
|
||||
/// <summary>Sole shareholder: <c>SU</c> one, <c>SM</c> more; empty when it does not apply.</summary>
|
||||
public string? Shareholders { get; set; }
|
||||
|
||||
/// <summary>Liquidation: <c>LN</c> not in liquidation, <c>LS</c> in liquidation.</summary>
|
||||
public string? LiquidationStatus { get; set; }
|
||||
|
||||
/// <summary>The street.</summary>
|
||||
public string? Address { get; set; }
|
||||
|
||||
/// <summary>The street number.</summary>
|
||||
public string? StreetNumber { get; set; }
|
||||
|
||||
/// <summary>The postal code.</summary>
|
||||
public string? PostalCode { get; set; }
|
||||
|
||||
/// <summary>The town.</summary>
|
||||
public string? City { get; set; }
|
||||
|
||||
/// <summary>The province abbreviation.</summary>
|
||||
public string? ProvinceCode { get; set; }
|
||||
|
||||
/// <summary>The country of the address (ISO 3166-1).</summary>
|
||||
public string? AddressCountry { get; set; }
|
||||
|
||||
/// <summary>The phone.</summary>
|
||||
public string? Phone { get; set; }
|
||||
|
||||
/// <summary>The e-mail address.</summary>
|
||||
public string? Email { get; set; }
|
||||
|
||||
/// <summary>The certified e-mail address.</summary>
|
||||
public string? Pec { get; set; }
|
||||
|
||||
/// <summary>The web site.</summary>
|
||||
public string? Website { get; set; }
|
||||
|
||||
/// <summary>The tax regime, such as <c>RF01</c>.</summary>
|
||||
public string TaxRegime { get; set; } = "RF01";
|
||||
|
||||
/// <summary>The company's own recipient code for incoming e-invoices.</summary>
|
||||
public string? RecipientCode { get; set; }
|
||||
|
||||
/// <summary>The logo (an attachment of entity <c>company_profile</c>).</summary>
|
||||
public long? LogoAttachmentId { get; set; }
|
||||
|
||||
/// <summary>The bank account proposed on documents.</summary>
|
||||
public long? DefaultBankAccountId { get; set; }
|
||||
|
||||
/// <summary>The accounting currency (ISO 4217).</summary>
|
||||
public string CurrencyCode { get; set; } = "EUR";
|
||||
|
||||
/// <summary>The country whose fiscal pack applies (ISO 3166-1), from <c>KHAEMHAT_COUNTRY</c> at creation.</summary>
|
||||
public string Country { get; set; } = "IT";
|
||||
|
||||
/// <summary>The VAT settlement periodicity.</summary>
|
||||
public VatPeriodicity VatPeriodicity { get; set; }
|
||||
|
||||
/// <summary>The deductible share for companies with exempt operations (pro-rata), in percent; 100 when it does not apply.</summary>
|
||||
public decimal ProRataPercent { get; set; } = 100m;
|
||||
|
||||
/// <summary>VAT on cash basis (art. 32-bis DL 83/2012).</summary>
|
||||
public bool CashVat { get; set; }
|
||||
|
||||
/// <summary>The first month of the fiscal year (1 for calendar years).</summary>
|
||||
public int FiscalYearStartMonth { get; set; } = 1;
|
||||
|
||||
/// <summary>The transmitter of e-invoices, when not the company: country.</summary>
|
||||
public string? TransmitterCountry { get; set; }
|
||||
|
||||
/// <summary>The transmitter of e-invoices: tax identifier.</summary>
|
||||
public string? TransmitterId { get; set; }
|
||||
|
||||
/// <summary>The intermediary that sends the returns (LIPE, F24): name.</summary>
|
||||
public string? IntermediaryName { get; set; }
|
||||
|
||||
/// <summary>The intermediary: tax code.</summary>
|
||||
public string? IntermediaryTaxCode { get; set; }
|
||||
|
||||
/// <summary>The text printed at the bottom of documents.</summary>
|
||||
public string? FooterNotes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a fiscal year (SPEC §11.1, mockup 052).</summary>
|
||||
public enum FiscalYearStatus
|
||||
{
|
||||
/// <summary>Entries allowed.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>Closing entries in progress: only closing entries.</summary>
|
||||
Closing = 1,
|
||||
|
||||
/// <summary>Read only.</summary>
|
||||
Closed = 2,
|
||||
}
|
||||
|
||||
/// <summary>A fiscal year.</summary>
|
||||
public sealed class FiscalYear : Entity<long>
|
||||
{
|
||||
/// <summary>The code, such as <c>2026</c> or <c>2026/27</c>.</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The first day.</summary>
|
||||
public DateOnly StartDate { get; set; }
|
||||
|
||||
/// <summary>The last day.</summary>
|
||||
public DateOnly EndDate { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public FiscalYearStatus Status { get; set; }
|
||||
|
||||
/// <summary>The first page number of the journal printed for this year.</summary>
|
||||
public int JournalFirstPage { get; set; } = 1;
|
||||
|
||||
/// <summary>The number of the last final journal entry.</summary>
|
||||
public long LastFinalEntryNumber { get; set; }
|
||||
|
||||
/// <summary>The date of the last final journal entry.</summary>
|
||||
public DateOnly? LastFinalEntryDate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a fiscal period.</summary>
|
||||
public enum FiscalPeriodStatus
|
||||
{
|
||||
/// <summary>Documents and entries allowed.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>The VAT of the period was settled: no new entries with VAT.</summary>
|
||||
Settled = 1,
|
||||
|
||||
/// <summary>Locked: no new documents or entries dated in the period.</summary>
|
||||
Locked = 2,
|
||||
}
|
||||
|
||||
/// <summary>A month of a fiscal year.</summary>
|
||||
public sealed class FiscalPeriod : Entity<long>
|
||||
{
|
||||
/// <summary>The fiscal year.</summary>
|
||||
public long FiscalYearId { get; set; }
|
||||
|
||||
/// <summary>The number in the year, from 1.</summary>
|
||||
public int Number { get; set; }
|
||||
|
||||
/// <summary>The first day.</summary>
|
||||
public DateOnly StartDate { get; set; }
|
||||
|
||||
/// <summary>The last day.</summary>
|
||||
public DateOnly EndDate { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public FiscalPeriodStatus Status { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>The company data and the fiscal years with their periods (SPEC §11.1, mockup 075 and 052).</summary>
|
||||
[Migration(20261111_010, "create_company_profile")]
|
||||
public sealed class M20261111_010_CreateCompanyProfile : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Countries, provinces, municipalities, currencies, exchange rates and units of measure (SPEC §11.1).</summary>
|
||||
[Migration(20261111_011, "create_geography_and_currencies")]
|
||||
public sealed class M20261111_011_CreateGeographyAndCurrencies : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
});
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>VAT codes, payment methods and terms, bank accounts and salespeople (SPEC §11.1, mockup 076).</summary>
|
||||
[Migration(20261111_012, "create_tax_and_payment_tables")]
|
||||
public sealed class M20261111_012_CreateTaxAndPaymentTables : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Carriers, transport tables, warehouse reasons and warehouses (SPEC §11.1).</summary>
|
||||
[Migration(20261111_013, "create_logistics_tables")]
|
||||
public sealed class M20261111_013_CreateLogisticsTables : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Categories, price lists, discounts, numerators, document types, cost centres and jobs (SPEC §11.1).</summary>
|
||||
[Migration(20261111_014, "create_catalog_tables")]
|
||||
public sealed class M20261111_014_CreateCatalogTables : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="CompanyProfile"/> to <c>company_profile</c>.</summary>
|
||||
public sealed class CompanyProfileMap : EntityMap<CompanyProfile>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="FiscalYear"/> to <c>fiscal_years</c>.</summary>
|
||||
public sealed class FiscalYearMap : EntityMap<FiscalYear>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public FiscalYearMap()
|
||||
{
|
||||
ToTable("fiscal_years");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="FiscalPeriod"/> to <c>fiscal_periods</c>.</summary>
|
||||
public sealed class FiscalPeriodMap : EntityMap<FiscalPeriod>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public FiscalPeriodMap()
|
||||
{
|
||||
ToTable("fiscal_periods");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Country"/> to <c>countries</c>.</summary>
|
||||
public sealed class CountryMap : EntityMap<Country>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Province"/> to <c>provinces</c>.</summary>
|
||||
public sealed class ProvinceMap : EntityMap<Province>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ProvinceMap()
|
||||
{
|
||||
ToTable("provinces");
|
||||
Map(x => x.Code).MaxLength(2);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Region).MaxLength(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Municipality"/> to <c>municipalities</c>.</summary>
|
||||
public sealed class MunicipalityMap : EntityMap<Municipality>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Currency"/> to <c>currencies</c>.</summary>
|
||||
public sealed class CurrencyMap : EntityMap<Currency>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CurrencyMap()
|
||||
{
|
||||
ToTable("currencies");
|
||||
Map(x => x.Code).MaxLength(3);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Symbol).MaxLength(5);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ExchangeRate"/> to <c>exchange_rates</c>.</summary>
|
||||
public sealed class ExchangeRateMap : EntityMap<ExchangeRate>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ExchangeRateMap()
|
||||
{
|
||||
ToTable("exchange_rates");
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
Map(x => x.Source).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="UnitOfMeasure"/> to <c>units_of_measure</c>.</summary>
|
||||
public sealed class UnitOfMeasureMap : EntityMap<UnitOfMeasure>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public UnitOfMeasureMap()
|
||||
{
|
||||
ToTable("units_of_measure");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.EInvoiceCode).MaxLength(10);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="TaxCode"/> to <c>tax_codes</c>.</summary>
|
||||
public sealed class TaxCodeMap : EntityMap<TaxCode>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PaymentMethod"/> to <c>payment_methods</c>.</summary>
|
||||
public sealed class PaymentMethodMap : EntityMap<PaymentMethod>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentMethodMap()
|
||||
{
|
||||
ToTable("payment_methods");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.EInvoiceCode).MaxLength(4);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PaymentTerm"/> to <c>payment_terms</c>.</summary>
|
||||
public sealed class PaymentTermMap : EntityMap<PaymentTerm>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentTermMap()
|
||||
{
|
||||
ToTable("payment_terms");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Condition).MaxLength(4);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PaymentTermLine"/> to <c>payment_term_lines</c>.</summary>
|
||||
public sealed class PaymentTermLineMap : EntityMap<PaymentTermLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PaymentTermLineMap()
|
||||
{
|
||||
ToTable("payment_term_lines");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="BankAccount"/> to <c>bank_accounts</c>.</summary>
|
||||
public sealed class BankAccountMap : EntityMap<BankAccount>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Salesperson"/> to <c>salespeople</c>.</summary>
|
||||
public sealed class SalespersonMap : EntityMap<Salesperson>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Carrier"/> to <c>carriers</c>.</summary>
|
||||
public sealed class CarrierMap : EntityMap<Carrier>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ShippingTerm"/> to <c>shipping_terms</c>.</summary>
|
||||
public sealed class ShippingTermMap : EntityMap<ShippingTerm>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ShippingTermMap()
|
||||
{
|
||||
ToTable("shipping_terms");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="TransportMean"/> to <c>transport_means</c>.</summary>
|
||||
public sealed class TransportMeanMap : EntityMap<TransportMean>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public TransportMeanMap()
|
||||
{
|
||||
ToTable("transport_means");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="GoodsAppearance"/> to <c>goods_appearances</c>.</summary>
|
||||
public sealed class GoodsAppearanceMap : EntityMap<GoodsAppearance>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public GoodsAppearanceMap()
|
||||
{
|
||||
ToTable("goods_appearances");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DeliveryTerm"/> to <c>delivery_terms</c>.</summary>
|
||||
public sealed class DeliveryTermMap : EntityMap<DeliveryTerm>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DeliveryTermMap()
|
||||
{
|
||||
ToTable("delivery_terms");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="TransportReason"/> to <c>transport_reasons</c>.</summary>
|
||||
public sealed class TransportReasonMap : EntityMap<TransportReason>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public TransportReasonMap()
|
||||
{
|
||||
ToTable("transport_reasons");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="InventoryReason"/> to <c>inventory_reasons</c>.</summary>
|
||||
public sealed class InventoryReasonMap : EntityMap<InventoryReason>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public InventoryReasonMap()
|
||||
{
|
||||
ToTable("inventory_reasons");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Warehouse"/> to <c>warehouses</c>.</summary>
|
||||
public sealed class WarehouseMap : EntityMap<Warehouse>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemCategory"/> to <c>item_categories</c>.</summary>
|
||||
public sealed class ItemCategoryMap : EntityMap<ItemCategory>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemCategoryMap()
|
||||
{
|
||||
ToTable("item_categories");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PartyCategory"/> to <c>party_categories</c>.</summary>
|
||||
public sealed class PartyCategoryMap : EntityMap<PartyCategory>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PartyCategoryMap()
|
||||
{
|
||||
ToTable("party_categories");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="PriceList"/> to <c>price_lists</c>.</summary>
|
||||
public sealed class PriceListMap : EntityMap<PriceList>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public PriceListMap()
|
||||
{
|
||||
ToTable("price_lists");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.CurrencyCode).MaxLength(3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DiscountPolicy"/> to <c>discount_policies</c>.</summary>
|
||||
public sealed class DiscountPolicyMap : EntityMap<DiscountPolicy>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public DiscountPolicyMap()
|
||||
{
|
||||
ToTable("discount_policies");
|
||||
Map(x => x.Code).MaxLength(10);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.Formula).MaxLength(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DocumentNumerator"/> to <c>document_numerators</c>.</summary>
|
||||
public sealed class DocumentNumeratorMap : EntityMap<DocumentNumerator>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="DocumentType"/> to <c>document_types</c>.</summary>
|
||||
public sealed class DocumentTypeMap : EntityMap<DocumentType>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="CostCenter"/> to <c>cost_centers</c>.</summary>
|
||||
public sealed class CostCenterMap : EntityMap<CostCenter>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CostCenterMap()
|
||||
{
|
||||
ToTable("cost_centers");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Job"/> to <c>jobs</c>.</summary>
|
||||
public sealed class JobMap : EntityMap<Job>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public JobMap()
|
||||
{
|
||||
ToTable("jobs");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
}
|
||||
}
|
||||
@@ -192,3 +192,51 @@ public interface IIntrastatExporter
|
||||
/// <returns>A task that completes when the file is written.</returns>
|
||||
Task WriteAsync(IntrastatReturn intrastatReturn, Stream output, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A payment method of the base data.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="EInvoiceCode">The code of the e-invoice format.</param>
|
||||
/// <param name="NeedsBank">Whether a bank is needed (transfer, bank receipt, direct debit).</param>
|
||||
public sealed record PaymentMethodTemplate(string Code, string Description, string EInvoiceCode, bool NeedsBank);
|
||||
|
||||
/// <summary>An installment of payment terms of the base data.</summary>
|
||||
/// <param name="Days">Days from the document date.</param>
|
||||
/// <param name="EndOfMonth">Whether the due date moves to the end of the month.</param>
|
||||
/// <param name="Percent">Share of the amount, in percent.</param>
|
||||
public sealed record InstallmentTemplate(int Days, bool EndOfMonth, decimal Percent);
|
||||
|
||||
/// <summary>Payment terms of the base data.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="PaymentMethodCode">The payment method (a <see cref="PaymentMethodTemplate.Code"/>).</param>
|
||||
/// <param name="Condition">The condition of the e-invoice format (installments, full, advance).</param>
|
||||
/// <param name="Installments">The installments.</param>
|
||||
public sealed record PaymentTermTemplate(string Code, string Description, string PaymentMethodCode, string Condition, IReadOnlyList<InstallmentTemplate> Installments);
|
||||
|
||||
/// <summary>A document type of the base data.</summary>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Kind">The family.</param>
|
||||
/// <param name="NumeratorCode">The numerator of the base data (<c>FAT</c>, <c>DDT</c>...), if the document is numbered by the company.</param>
|
||||
/// <param name="InventoryReasonCode">The warehouse reason of the base data (<c>SCA</c>, <c>CAR</c>...), if the document moves goods.</param>
|
||||
/// <param name="EInvoiceType">The type of the e-invoice format, if the document is sent electronically.</param>
|
||||
public sealed record DocumentTypeTemplate(
|
||||
string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IBaseTablesTemplate
|
||||
{
|
||||
/// <summary>The payment methods.</summary>
|
||||
IReadOnlyList<PaymentMethodTemplate> PaymentMethods { get; }
|
||||
|
||||
/// <summary>The payment terms.</summary>
|
||||
IReadOnlyList<PaymentTermTemplate> PaymentTerms { get; }
|
||||
|
||||
/// <summary>The document types.</summary>
|
||||
IReadOnlyList<DocumentTypeTemplate> DocumentTypes { get; }
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class ItalianBaseTables : IBaseTablesTemplate
|
||||
{
|
||||
private static readonly InstallmentTemplate Now = new(0, false, 100m);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<PaymentMethodTemplate> 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),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<PaymentTermTemplate> 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)]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<DocumentTypeTemplate> DocumentTypes { get; } =
|
||||
[
|
||||
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null),
|
||||
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null),
|
||||
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null),
|
||||
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01"),
|
||||
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01"),
|
||||
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24"),
|
||||
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02"),
|
||||
new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04"),
|
||||
new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05"),
|
||||
new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06"),
|
||||
new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null),
|
||||
new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16"),
|
||||
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17"),
|
||||
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18"),
|
||||
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19"),
|
||||
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null),
|
||||
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null),
|
||||
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
|
||||
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
|
||||
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null),
|
||||
];
|
||||
}
|
||||
@@ -19,6 +19,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
|
||||
AddFeature<ITaxIdentifierRules>(new ItalianTaxIdentifierRules());
|
||||
AddFeature<IBaseTablesTemplate>(new ItalianBaseTables());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Reads CSV files written by <see cref="CsvWriter"/> 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
|
||||
/// (<c>;</c>, <c>,</c> or tab) unless given.
|
||||
/// </summary>
|
||||
public static class CsvReader
|
||||
{
|
||||
/// <summary>The separators tried, in order of preference.</summary>
|
||||
private static readonly char[] Separators = [';', ',', '\t'];
|
||||
|
||||
/// <summary>Reads every row of a text.</summary>
|
||||
/// <param name="text">The content.</param>
|
||||
/// <param name="separator">The separator, or <see langword="null"/> to guess it.</param>
|
||||
/// <returns>The rows; empty lines are skipped.</returns>
|
||||
public static IReadOnlyList<IReadOnlyList<string>> 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<IReadOnlyList<string>>();
|
||||
var row = new List<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a stream as UTF-8 (the byte order mark is optional).</summary>
|
||||
/// <param name="content">The stream.</param>
|
||||
/// <param name="separator">The separator, or <see langword="null"/> to guess it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public static async Task<IReadOnlyList<IReadOnlyList<string>>> 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Globalization;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Http;
|
||||
|
||||
/// <summary>A reference rate of the European Central Bank: units of the currency for one euro.</summary>
|
||||
/// <param name="Currency">The currency (ISO 4217).</param>
|
||||
/// <param name="Date">The day of the rate.</param>
|
||||
/// <param name="Rate">Units of the currency for one euro.</param>
|
||||
public sealed record EcbRate(string Currency, DateOnly Date, decimal Rate);
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<c>eurofxref-daily.xml</c>, or the last 90 days in <c>eurofxref-hist-90d.xml</c>).
|
||||
/// </summary>
|
||||
public sealed class EcbRatesClient
|
||||
{
|
||||
/// <summary>The address of the reference rates.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the client.</summary>
|
||||
/// <param name="http">The HTTP client (its base address defaults to <see cref="DefaultBaseAddress"/>).</param>
|
||||
public EcbRatesClient(HttpClient http)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(http);
|
||||
_http = http;
|
||||
_http.BaseAddress ??= DefaultBaseAddress;
|
||||
}
|
||||
|
||||
/// <summary>Reads the rates of the last working day, or of the last 90 days.</summary>
|
||||
/// <param name="last90Days">Whether to read the last 90 days (to fill gaps after a stop).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rates.</returns>
|
||||
/// <exception cref="HttpRequestException">The service did not answer.</exception>
|
||||
/// <exception cref="FormatException">The answer is not the expected XML.</exception>
|
||||
public async Task<IReadOnlyList<EcbRate>> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the ECB XML.</summary>
|
||||
/// <param name="xml">The XML.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rates.</returns>
|
||||
/// <exception cref="FormatException">The XML is not the ECB format.</exception>
|
||||
public static async Task<IReadOnlyList<EcbRate>> 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<EcbRate>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<IFiscalPack, ItalyFiscalPack>();
|
||||
services.AddSingleton(sp => new FiscalPackCatalog(sp.GetServices<IFiscalPack>()));
|
||||
|
||||
// Company tables, profile and fiscal years (#38, #39), base data (#45), checks against European services (#40).
|
||||
services.AddSingleton<CompanyFiscalContext>();
|
||||
services.AddSingleton<TableCatalog>();
|
||||
services.AddSingleton<TableService>();
|
||||
services.AddSingleton<CompanyProfileService>();
|
||||
services.AddSingleton<FiscalYearService>();
|
||||
services.AddSingleton<ExchangeRateService>();
|
||||
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
|
||||
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
|
||||
services.AddSingleton<IScheduledJob, EcbRatesJob>();
|
||||
services.AddSingleton<ISeeder, BaseTablesSeeder>();
|
||||
services.AddSingleton<SeedRunner>();
|
||||
|
||||
// Companies and start.
|
||||
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
|
||||
services.AddSingleton<CompanyService>();
|
||||
services.AddSingleton<CompanyContextResolver>();
|
||||
services.AddScoped<ICompanyContext, WebCompanyContext>();
|
||||
|
||||
@@ -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<TaxCode>().CsvColumns.Select(c => c.Header).ToList(), "non_deductible_percent");
|
||||
CollectionAssert.Contains(catalog.Get<PaymentMethod>().CsvColumns.Select(c => c.Header).ToList(), "e_invoice_code");
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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<IBaseTablesTemplate>();
|
||||
var format = Pack.Require<IEInvoiceFormat>();
|
||||
|
||||
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<IBaseTablesTemplate>();
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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 = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
|
||||
<gesmes:subject>Reference rates</gesmes:subject>
|
||||
<Cube>
|
||||
<Cube time="2026-11-10">
|
||||
<Cube currency="USD" rate="1.1563"/>
|
||||
<Cube currency="JPY" rate="177.12"/>
|
||||
</Cube>
|
||||
<Cube time="2026-11-09">
|
||||
<Cube currency="USD" rate="1.1501"/>
|
||||
</Cube>
|
||||
</Cube>
|
||||
</gesmes:Envelope>
|
||||
""";
|
||||
|
||||
[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("<html><body>Maintenance</body></html>"));
|
||||
using var broken = new MemoryStream(Encoding.UTF8.GetBytes("not xml"));
|
||||
|
||||
await Assert.ThrowsExactlyAsync<FormatException>(() => EcbRatesClient.ParseAsync(html));
|
||||
await Assert.ThrowsExactlyAsync<FormatException>(() => EcbRatesClient.ParseAsync(broken));
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ public sealed class CompanyIsolationTests
|
||||
|
||||
var scheduler = services.GetRequiredService<JobScheduler>();
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Company tables, profile, fiscal years and base data on a real instance (issues #38, #39, #45).</summary>
|
||||
[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<TableService>();
|
||||
var pack = services.GetRequiredService<FiscalPackCatalog>().ForCountry("IT");
|
||||
|
||||
var taxCodes = await tables.AllAsync<TaxCode>(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<Country>(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<DocumentType>(Root, company)).Single(d => d.Code == "FI");
|
||||
var numerators = await tables.AllAsync<DocumentNumerator>(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<IUnitOfWorkFactory>().CreateAsync(DatabaseScope.Company(company)))
|
||||
{
|
||||
var terms = (await uow.Repository<PaymentTerm, long>().FindAsync(Query.For<PaymentTerm>().Where(t => t.Code == "RB306090")))!;
|
||||
var lines = (await uow.Repository<PaymentTermLine, long>().ListAsync(Query.For<PaymentTermLine>().Where(l => l.PaymentTermId == terms.Id))).Items;
|
||||
Assert.HasCount(3, lines);
|
||||
Assert.AreEqual(100m, lines.Sum(l => l.Percent));
|
||||
}
|
||||
|
||||
var years = await services.GetRequiredService<FiscalYearService>().ListAsync(Root, company);
|
||||
Assert.HasCount(1, years);
|
||||
Assert.HasCount(12, years[0].Periods);
|
||||
|
||||
var runner = services.GetRequiredService<SeedRunner>();
|
||||
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<TableService>();
|
||||
|
||||
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<ValidationFailedException>(() => tables.SaveAsync(Root, company, noNature));
|
||||
CollectionAssert.Contains(refused.Errors.ToList(), "Nature:fiscal.tax.nature-required");
|
||||
|
||||
var duplicate = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => 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<TaxCode>(Root, company, new ListQuery { Search = "ESE10B" });
|
||||
Assert.AreEqual(1, page.Total, "The cache is refreshed after a save.");
|
||||
|
||||
var badIban = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => 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<BankAccount>(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<TableService>();
|
||||
|
||||
var transfer = (await tables.AllAsync<PaymentMethod>(Root, company)).Single(m => m.Code == "BON");
|
||||
Assert.AreEqual(TableDeleteOutcome.Disabled, await tables.DeleteAsync<PaymentMethod>(Root, company, transfer.Id), "Payment terms use it.");
|
||||
Assert.IsTrue((await tables.GetAsync<PaymentMethod>(Root, company, transfer.Id))!.Disabled);
|
||||
Assert.IsFalse((await tables.ActiveAsync<PaymentMethod>(Root, company)).Any(m => m.Code == "BON"));
|
||||
|
||||
var pagopa = (await tables.AllAsync<PaymentMethod>(Root, company)).Single(m => m.Code == "PAGOPA");
|
||||
Assert.AreEqual(TableDeleteOutcome.Deleted, await tables.DeleteAsync<PaymentMethod>(Root, company, pagopa.Id));
|
||||
|
||||
using var export = new MemoryStream();
|
||||
var written = await tables.ExportCsvAsync<UnitOfMeasure>(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<UnitOfMeasure>(Root, company, import);
|
||||
|
||||
Assert.IsTrue(result.Succeeded, string.Join(", ", result.Errors));
|
||||
Assert.AreEqual((1, written), (result.Inserted, result.Updated));
|
||||
var units = await tables.AllAsync<UnitOfMeasure>(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<UnitOfMeasure>(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<UnitOfMeasure>(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<FiscalYearService>();
|
||||
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<ValidationFailedException>(() => 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<CompanyProfileService>();
|
||||
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<ValidationFailedException>(() => 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<ValidationFailedException>(() => profiles.SaveAsync(Root, company, saved));
|
||||
CollectionAssert.Contains(unknown.Errors.ToList(), "Country:" + CompanyProfileService.CountryUnknown);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user