feat: items and price lists with dated prices, derived lists and demo catalogue (#42)
Items get their own archive and record (mockup 017): codes from the per-category mask, EAN and NC8 checks, alternative units and bar codes, suppliers with the usual one, substitutes, notes and history. Only goods can be stocked; stock itself comes with the warehouse in M6. Costs are hidden from users without items.cost.read and kept as they were when those users save. A used item is disabled instead of deleted. Prices live in one item_prices table, either for a price list or as a customer's net price, each valid from a date, so documents keep the price of their day. Derived lists compute a price from their base list with markup and rounding when they have none of their own. The price grid (mockup 018) edits every list at one validity date, keeps changes pending and highlighted until saved, and computes mass updates as a preview. PriceListService.QuoteAsync gives documents (M5) the price search order net, list, base, item price with its source. Parties get the "Articoli e codici" tab: the codes a customer or supplier uses for our items, found by the item search in that party's documents. Demo data adds 120 items of a plumbing wholesaler, the PUBB and RIV lists, last year's prices, suppliers, units, codes and a customer's net prices; seed --demo [--scale N] loads them from the command line and repeats the catalogue for performance tests. ADR 0030 records the decisions; wiki, data model, CHANGELOG and STATUS are updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c8241a414e
commit
3dbbaba86e
46 files changed
+5318
-144
No files matched your search
@@ -53,6 +53,25 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
|||||||
(diventano anche clienti con lo stesso codice). Un'anagrafica usata da altri dati si disattiva invece di cancellarsi.
|
(diventano anche clienti con lo stesso codice). Un'anagrafica usata da altri dati si disattiva invece di cancellarsi.
|
||||||
- Dati di esempio delle anagrafiche con `KHAEMHAT_SEED_DEMO=true`: 3 agenti, 12 clienti di ogni tipo soggetto,
|
- Dati di esempio delle anagrafiche con `KHAEMHAT_SEED_DEMO=true`: 3 agenti, 12 clienti di ogni tipo soggetto,
|
||||||
5 fornitori, 2 prospect e 2 lead, con numeri inventati ma formalmente validi.
|
5 fornitori, 2 prospect e 2 lead, con numeri inventati ma formalmente validi.
|
||||||
|
- Articoli (ADR 0030): radar `/anagrafiche/articoli` con ricerca anche per codice a barre, filtri per tipo,
|
||||||
|
categoria, magazzino e stato, disattivazione e riattivazione; scheda con dati principali, UM alternative, codici
|
||||||
|
alternativi, listini e prezzi netti dei clienti, fornitori con il fornitore abituale, sostitutivi, note e allegati,
|
||||||
|
storico. Codice dalla maschera per categoria, verifica EAN con duplicati bloccati o segnalati secondo le
|
||||||
|
preferenze, NC8, solo le merci a magazzino; costi visibili solo con `items.cost.read` e conservati per chi non li
|
||||||
|
vede; un articolo usato si disattiva invece di cancellarsi.
|
||||||
|
- Listini (ADR 0030): prezzi con data di validità e storico, listino base, listini derivati con ricarico e
|
||||||
|
arrotondamento, griglia `/anagrafiche/listini` articoli x listini con modifica in cella, prezzi netti di un
|
||||||
|
cliente, margine e aggiornamento massivo con anteprima; ricerca del prezzo per i documenti (netto, listino del
|
||||||
|
documento o del cliente, base, articolo) con la fonte e gli sconti del cliente a cascata.
|
||||||
|
- Scheda *Articoli e codici* delle anagrafiche: i codici con cui un cliente o un fornitore chiama i tuoi articoli,
|
||||||
|
trovati dalla ricerca nei suoi documenti.
|
||||||
|
- 120 articoli di esempio con listini *Pubblico* e *Rivenditori*, prezzi dell'anno precedente, fornitori, UM e
|
||||||
|
codici alternativi, sostitutivi e prezzi netti di un cliente; `scripts/seed.sh --demo [--scale N]` carica i dati
|
||||||
|
di esempio da riga di comando e moltiplica il catalogo per le prove di prestazione.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Tabella *Listini*: nuovi campi *Listino base* (uno solo) e *Derivato da*; la migrazione marca come base il listino
|
||||||
|
`BASE` esistente.
|
||||||
|
|
||||||
## [0.3.0] - 2026-11-11
|
## [0.3.0] - 2026-11-11
|
||||||
|
|
||||||
|
|||||||
+161
-8
@@ -168,7 +168,7 @@ public sealed class M20261013_001_CreateParties : IMigration
|
|||||||
| `warehouses` | codice, descrizione, indirizzo | |
|
| `warehouses` | codice, descrizione, indirizzo | |
|
||||||
| `item_categories` | codice, descrizione, `parent_id` → (3 livelli) | |
|
| `item_categories` | codice, descrizione, `parent_id` → (3 livelli) | |
|
||||||
| `party_categories` | codice, descrizione | |
|
| `party_categories` | codice, descrizione | |
|
||||||
| `price_lists` | codice, descrizione, valuta, IVA inclusa, listino padre → | listini derivati |
|
| `price_lists` | codice, descrizione, valuta, IVA inclusa, `is_base` (listino base), listino di partenza →, ricarico %, passo di arrotondamento, validità | listini derivati (ADR 0030) |
|
||||||
| `discount_policies` | codice, descrizione, formula sconto | |
|
| `discount_policies` | codice, descrizione, formula sconto | |
|
||||||
| `document_types` | kind, numeratore →, causale magazzino →, causale contabile →, registro IVA →, TD SDI, modello stampa | catalogo statico |
|
| `document_types` | kind, numeratore →, causale magazzino →, causale contabile →, registro IVA →, TD SDI, modello stampa | catalogo statico |
|
||||||
| `cost_centers`, `jobs` | codice, descrizione | centri di costo, commesse |
|
| `cost_centers`, `jobs` | codice, descrizione | centri di costo, commesse |
|
||||||
@@ -185,18 +185,18 @@ public sealed class M20261013_001_CreateParties : IMigration
|
|||||||
| `party_purchase_terms` | `party_id` → (unico), pagamento →, lead time, minimo d'ordine, sconto, porto →, registro IVA, conto di costo, e-mail ordini | i dati di acquisto del fornitore |
|
| `party_purchase_terms` | `party_id` → (unico), pagamento →, lead time, minimo d'ordine, sconto, porto →, registro IVA, conto di costo, e-mail ordini | i dati di acquisto del fornitore |
|
||||||
| `party_fiscal` | `party_id` → (unico), codice destinatario, PEC, riferimento amministrazione, split payment, reverse charge, codice IVA →, esigibilità, bollo, ritenuta e aliquota, causale, cassa previdenza, ENASARCO, dichiarazione d'intento (numero, data, protocollo, codice IVA →, plafond, utilizzato, validità), EORI, GLN | |
|
| `party_fiscal` | `party_id` → (unico), codice destinatario, PEC, riferimento amministrazione, split payment, reverse charge, codice IVA →, esigibilità, bollo, ritenuta e aliquota, causale, cassa previdenza, ENASARCO, dichiarazione d'intento (numero, data, protocollo, codice IVA →, plafond, utilizzato, validità), EORI, GLN | |
|
||||||
| `intent_declarations` † | `party_id` →, direzione (ricevuta/emessa), protocollo, anno, plafond, utilizzato, residuo, validità | mockup 061 |
|
| `intent_declarations` † | `party_id` →, direzione (ricevuta/emessa), protocollo, anno, plafond, utilizzato, residuo, validità | mockup 061 |
|
||||||
| `party_item_codes` | `party_id` →, `item_id` →, codice e descrizione del cliente/fornitore | |
|
| `party_item_codes` | `party_id` → (cascata), `item_id` → (cascata), codice e descrizione del cliente/fornitore | salvati con la scheda dell'anagrafica; codice unico per anagrafica (ADR 0030) |
|
||||||
|
|
||||||
### 4.4 Articoli e listini (`Items`, CORE)
|
### 4.4 Articoli e listini (`Items`, CORE)
|
||||||
|
|
||||||
| Tabella | Colonne principali | Relazioni / note |
|
| Tabella | Colonne principali | Relazioni / note |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `items` | `code` (automatico), descrizioni, `item_type` (*merce/servizio/spesa/testo/cespite*), `category_id` →, UM →, IVA vendita/acquisto →, EAN, NC8, produttore, marca, pesi, deposito →, scorta minima, punto/lotto di riordino, costi (standard/ultimo/medio), gestione a magazzino, conti ricavo/costo → | immagine come allegato |
|
| `items` | `code` (automatico, maschera `{categoria}-{seq:0000}`), descrizioni, `kind` (*merce/servizio/spesa/testo/cespite*), `category_id` →, UM →, IVA vendita/acquisto →, EAN, NC8, produttore, marca, pesi, deposito →, scorta minima, punto/lotto di riordino, prezzo, costi (standard/ultimo/medio), gestione a magazzino (solo merci), conti ricavo/costo →, `disabled`, `is_demo` | immagine come allegato; disattivazione al posto della cancellazione se usato |
|
||||||
| `item_uoms` | `item_id` →, UM →, fattore di conversione | |
|
| `item_uoms` | `item_id` → (cascata), UM →, fattore di conversione, EAN della confezione | |
|
||||||
| `item_barcodes` | `item_id` →, codice, tipo | |
|
| `item_barcodes` | `item_id` → (cascata), codice, descrizione | codici alternativi, trovati dalla ricerca |
|
||||||
| `item_prices` | `item_id` →, `price_list_id` →, prezzo, validità, `party_id` → (prezzo netto cliente) | griglia listino x articolo (mockup 018) |
|
| `item_prices` | `item_id` → (cascata), `price_list_id` → oppure `party_id` → (prezzo netto cliente), prezzo, `valid_from` | storico per data di validità; griglia listino x articolo (mockup 018, ADR 0030) |
|
||||||
| `item_suppliers` | `item_id` →, `party_id` →, codice fornitore, prezzo, lead time, minimo | |
|
| `item_suppliers` | `item_id` → (cascata), `party_id` →, codice fornitore, prezzo, lead time, minimo, `is_default` (fornitore abituale) | |
|
||||||
| `item_substitutes` | `item_id` →, `substitute_item_id` → | |
|
| `item_substitutes` | `item_id` → (cascata), `substitute_id` →, note | |
|
||||||
|
|
||||||
### 4.5 Documenti, vendite e acquisti (`Sales`, `Purchases`, CORE)
|
### 4.5 Documenti, vendite e acquisti (`Sales`, `Purchases`, CORE)
|
||||||
|
|
||||||
@@ -728,6 +728,7 @@ Migrazioni applicate in ordine:
|
|||||||
- `core` 20261111014 `create_catalog_tables` (M20261111_014_CreateCatalogTables)
|
- `core` 20261111014 `create_catalog_tables` (M20261111_014_CreateCatalogTables)
|
||||||
- `core` 20261111015 `create_code_sequences` (M20261111_015_CreateCodeSequences)
|
- `core` 20261111015 `create_code_sequences` (M20261111_015_CreateCodeSequences)
|
||||||
- `core` 20261112001 `create_parties` (M20261112_001_CreateParties)
|
- `core` 20261112001 `create_parties` (M20261112_001_CreateParties)
|
||||||
|
- `core` 20261112002 `create_items` (M20261112_002_CreateItems)
|
||||||
|
|
||||||
#### `attachments`
|
#### `attachments`
|
||||||
|
|
||||||
@@ -1131,6 +1132,22 @@ Migrazioni applicate in ordine:
|
|||||||
|
|
||||||
- indice unico `ux_inventory_reasons_code` su `code`
|
- indice unico `ux_inventory_reasons_code` su `code`
|
||||||
|
|
||||||
|
#### `item_barcodes`
|
||||||
|
|
||||||
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `id` | Int64 | no | | chiave primaria, identity |
|
||||||
|
| `item_id` | Int64 | no | | -> `items` (Cascade) |
|
||||||
|
| `code` | String(40) | no | | |
|
||||||
|
| `description` | String(100) | 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 `ix_item_barcodes_code` su `code`
|
||||||
|
|
||||||
#### `item_categories`
|
#### `item_categories`
|
||||||
|
|
||||||
| Colonna | Tipo | Null | Default | Note |
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
@@ -1150,6 +1167,123 @@ Migrazioni applicate in ordine:
|
|||||||
|
|
||||||
- indice unico `ux_item_categories_code` su `code`
|
- indice unico `ux_item_categories_code` su `code`
|
||||||
|
|
||||||
|
#### `item_prices`
|
||||||
|
|
||||||
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `id` | Int64 | no | | chiave primaria, identity |
|
||||||
|
| `item_id` | Int64 | no | | -> `items` (Cascade) |
|
||||||
|
| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) |
|
||||||
|
| `party_id` | Int64 | sì | | -> `parties` (Restrict) |
|
||||||
|
| `price` | Decimal(19,6) | no | | |
|
||||||
|
| `valid_from` | 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 `ix_item_prices_item` su `item_id`
|
||||||
|
- indice `ix_item_prices_party` su `party_id`
|
||||||
|
- indice `ix_item_prices_price_list` su `price_list_id`
|
||||||
|
|
||||||
|
#### `item_substitutes`
|
||||||
|
|
||||||
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `id` | Int64 | no | | chiave primaria, identity |
|
||||||
|
| `item_id` | Int64 | no | | -> `items` (Cascade) |
|
||||||
|
| `substitute_id` | Int64 | no | | -> `items` (Restrict) |
|
||||||
|
| `notes` | String(200) | 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_item_substitutes_pair` su `item_id`, `substitute_id`
|
||||||
|
|
||||||
|
#### `item_suppliers`
|
||||||
|
|
||||||
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `id` | Int64 | no | | chiave primaria, identity |
|
||||||
|
| `item_id` | Int64 | no | | -> `items` (Cascade) |
|
||||||
|
| `party_id` | Int64 | no | | -> `parties` (Restrict) |
|
||||||
|
| `supplier_code` | String(40) | sì | | |
|
||||||
|
| `price` | Decimal(19,6) | sì | | |
|
||||||
|
| `lead_time_days` | Int32 | sì | | |
|
||||||
|
| `minimum_quantity` | Decimal(19,6) | sì | | |
|
||||||
|
| `is_default` | 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_suppliers_item_party` su `item_id`, `party_id`
|
||||||
|
|
||||||
|
#### `item_uoms`
|
||||||
|
|
||||||
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `id` | Int64 | no | | chiave primaria, identity |
|
||||||
|
| `item_id` | Int64 | no | | -> `items` (Cascade) |
|
||||||
|
| `unit_of_measure_id` | Int64 | no | | -> `units_of_measure` (Restrict) |
|
||||||
|
| `factor` | Decimal(19,6) | no | `1` | |
|
||||||
|
| `barcode` | String(20) | 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_item_uoms_item_unit` su `item_id`, `unit_of_measure_id`
|
||||||
|
|
||||||
|
#### `items`
|
||||||
|
|
||||||
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `id` | Int64 | no | | chiave primaria, identity |
|
||||||
|
| `code` | String(30) | no | | |
|
||||||
|
| `kind` | String(40) | no | | |
|
||||||
|
| `description` | String(200) | no | | |
|
||||||
|
| `extended_description` | Text | sì | | |
|
||||||
|
| `category_id` | Int64 | sì | | -> `item_categories` (Restrict) |
|
||||||
|
| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) |
|
||||||
|
| `sales_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||||
|
| `purchase_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) |
|
||||||
|
| `barcode` | String(20) | sì | | |
|
||||||
|
| `customs_code` | String(10) | sì | | |
|
||||||
|
| `manufacturer` | String(100) | sì | | |
|
||||||
|
| `brand` | String(100) | sì | | |
|
||||||
|
| `net_weight` | Decimal(19,6) | sì | | |
|
||||||
|
| `gross_weight` | Decimal(19,6) | sì | | |
|
||||||
|
| `stocked` | Bool | no | `false` | |
|
||||||
|
| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) |
|
||||||
|
| `minimum_stock` | Decimal(19,6) | sì | | |
|
||||||
|
| `reorder_point` | Decimal(19,6) | sì | | |
|
||||||
|
| `reorder_lot` | Decimal(19,6) | sì | | |
|
||||||
|
| `price` | Decimal(19,6) | sì | | |
|
||||||
|
| `standard_cost` | Decimal(19,6) | sì | | |
|
||||||
|
| `last_cost` | Decimal(19,6) | sì | | |
|
||||||
|
| `average_cost` | Decimal(19,6) | sì | | |
|
||||||
|
| `revenue_account_code` | String(20) | sì | | |
|
||||||
|
| `cost_account_code` | String(20) | sì | | |
|
||||||
|
| `notes` | Text | sì | | |
|
||||||
|
| `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 `ix_items_barcode` su `barcode`
|
||||||
|
- indice `ix_items_category` su `category_id`
|
||||||
|
- indice `ix_items_description` su `description`
|
||||||
|
- indice unico `ux_items_code` su `code`
|
||||||
|
|
||||||
#### `jobs`
|
#### `jobs`
|
||||||
|
|
||||||
| Colonna | Tipo | Null | Default | Note |
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
@@ -1407,6 +1541,24 @@ Migrazioni applicate in ordine:
|
|||||||
|
|
||||||
- indice unico `ux_party_fiscal_party` su `party_id`
|
- indice unico `ux_party_fiscal_party` su `party_id`
|
||||||
|
|
||||||
|
#### `party_item_codes`
|
||||||
|
|
||||||
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `id` | Int64 | no | | chiave primaria, identity |
|
||||||
|
| `party_id` | Int64 | no | | -> `parties` (Cascade) |
|
||||||
|
| `item_id` | Int64 | no | | -> `items` (Cascade) |
|
||||||
|
| `code` | String(40) | no | | |
|
||||||
|
| `description` | String(200) | 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 `ix_party_item_codes_item` su `item_id`
|
||||||
|
- indice unico `ux_party_item_codes_party_code` su `party_id`, `code`
|
||||||
|
|
||||||
#### `party_purchase_terms`
|
#### `party_purchase_terms`
|
||||||
|
|
||||||
| Colonna | Tipo | Null | Default | Note |
|
| Colonna | Tipo | Null | Default | Note |
|
||||||
@@ -1536,6 +1688,7 @@ Migrazioni applicate in ordine:
|
|||||||
| `updated_at` | DateTimeUtc | sì | | |
|
| `updated_at` | DateTimeUtc | sì | | |
|
||||||
| `updated_by` | String(100) | sì | | |
|
| `updated_by` | String(100) | sì | | |
|
||||||
| `row_version` | Int64 | no | `1` | |
|
| `row_version` | Int64 | no | `1` | |
|
||||||
|
| `is_base` | Bool | no | `false` | |
|
||||||
|
|
||||||
- indice unico `ux_price_lists_code` su `code`
|
- indice unico `ux_price_lists_code` su `code`
|
||||||
|
|
||||||
|
|||||||
+5
-4
@@ -7,9 +7,10 @@
|
|||||||
Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profilo, esercizi e cambi con le maschere
|
Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profilo, esercizi e cambi con le maschere
|
||||||
(#38, #39), dati di base e `scripts/seed.sh --base` (#45) con province e comuni ISTAT e CAP GeoNames (ADR 0028;
|
(#38, #39), dati di base e `scripts/seed.sh --base` (#45) con province e comuni ISTAT e CAP GeoNames (ADR 0028;
|
||||||
mancano le banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43), anagrafiche con radar, scheda, controlli, VIES e
|
mancano le banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43), anagrafiche con radar, scheda, controlli, VIES e
|
||||||
21 anagrafiche di esempio (#41, ADR 0029). ADR 0025-0029.
|
21 anagrafiche di esempio (#41, ADR 0029), articoli e listini con prezzi a validità, listini derivati,
|
||||||
**Prossimo passo:** articoli e listini (#42) con `party_item_codes` e `seed --demo`, import/export guidato (#44),
|
aggiornamento massivo, codici delle anagrafiche, 120 articoli di esempio e `seed --demo [--scale N]` (#42, ADR 0030).
|
||||||
chiusura M4 (#46). #35 (PNG ad alta risoluzione) resta
|
ADR 0025-0030.
|
||||||
|
**Prossimo passo:** import/export guidato (#44), chiusura M4 come `v0.4.0` (#46). #35 (PNG ad alta risoluzione) resta
|
||||||
aperta e non blocca.
|
aperta e non blocca.
|
||||||
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
|
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
|
||||||
password (mockup 003); schede *Layout salvati* (M4) e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
|
password (mockup 003); schede *Layout salvati* (M4) e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
|
||||||
@@ -18,7 +19,7 @@ filtro predefinito nei radar.
|
|||||||
## Fatto
|
## Fatto
|
||||||
|
|
||||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
|
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
|
||||||
- ADR 0001-0029.
|
- ADR 0001-0030.
|
||||||
- Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice).
|
- Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice).
|
||||||
- Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid).
|
- Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid).
|
||||||
- Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`,
|
- Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`,
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# ADR 0030 - Articoli e listini: prezzi con validità, listini derivati, ricerca del prezzo
|
||||||
|
|
||||||
|
- **Stato:** accettata
|
||||||
|
- **Data:** 2026-11-12
|
||||||
|
- **Modifica:** SPEC §9 (modello dati degli articoli), §11.2, §11.3, §14; milestone M4, issue #42
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
SPEC §11.2 descrive la scheda articolo (mockup 017) con UM alternative, codici alternativi, listini, fornitori,
|
||||||
|
sostitutivi, giacenze e movimenti, e la griglia dei listini (mockup 018) con modifica in cella e aggiornamento
|
||||||
|
massivo. §11.3 fissa l'ordine di ricerca del prezzo di una riga (netto cliente-articolo, listino del cliente o del
|
||||||
|
documento, listino base, prezzo dell'articolo) e dice che i listini hanno validità, possono essere derivati e hanno
|
||||||
|
regole di arrotondamento. Restavano aperti: dove stanno i prezzi netti dei clienti, come convivono prezzi vecchi e
|
||||||
|
nuovi, quale listino è "il base", come si calcola un listino derivato, che cosa vede chi non può vedere i costi, che
|
||||||
|
cosa si fa delle giacenze prima del magazzino (M6).
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
1. **Una tabella di prezzi.** `item_prices` tiene sia i prezzi di listino (`price_list_id`) sia i **prezzi netti**
|
||||||
|
di un cliente (`party_id`): una riga ha esattamente uno dei due. Ogni riga ha un `valid_from`; il prezzo in vigore
|
||||||
|
a una data è quello con l'**inizio più recente non successivo** alla data (una riga senza data vale sempre).
|
||||||
|
Scrivere un prezzo con una data nuova aggiunge una riga, così i documenti già fatti e quelli datati prima
|
||||||
|
ritrovano il prezzo di allora; scriverlo con la stessa data cambia la riga, e "nessun prezzo" la toglie. Un prezzo
|
||||||
|
uguale a quello già in vigore non si riscrive.
|
||||||
|
2. **Listino base.** `price_lists.is_base` marca il listino base (al più uno, regola della tabella); in mancanza
|
||||||
|
vale quello con codice `BASE`, che i dati di base creano già marcato. La migrazione marca il `BASE` esistente.
|
||||||
|
3. **Listini derivati.** Un listino con `base_price_list_id` senza un proprio prezzo per l'articolo prende il prezzo
|
||||||
|
del listino di partenza alla stessa data, applica `markup_percent` (anche negativo) e arrotonda a `rounding_step`
|
||||||
|
(al centesimo se zero). Il prezzo scritto nel listino derivato vince su quello calcolato. La derivazione si segue
|
||||||
|
per al più cinque livelli. Il calcolo è in `PriceBook`, che lavora in memoria sui prezzi letti una volta.
|
||||||
|
4. **Ricerca del prezzo** (`PriceListService.QuoteAsync`, usata dai documenti da M5): netto del cliente, poi il
|
||||||
|
listino del documento o del cliente se valido alla data, poi il listino base, poi `items.price`. La risposta dice
|
||||||
|
la **fonte** (`PriceSource`), che la riga del documento conserva. Gli sconti 1 e 2 del cliente si propongono come
|
||||||
|
formula a cascata (`10+5`), **mai su un prezzo netto**.
|
||||||
|
5. **Griglia dei listini.** Legge e scrive tutti i prezzi a **una data di validità** scelta in alto (oggi di
|
||||||
|
default). Le celle modificate e quelle calcolate dall'aggiornamento massivo restano in sospeso, evidenziate, finché
|
||||||
|
non si salva; l'anteprima dell'aggiornamento massivo (`PreviewAsync`) non scrive nulla. Le celle dei listini
|
||||||
|
derivati senza prezzo proprio sono in corsivo.
|
||||||
|
6. **Costi.** Costo standard, ultimo costo e costo medio si vedono solo con `items.cost.read`; per gli altri il
|
||||||
|
servizio li restituisce vuoti e al salvataggio conserva quelli in archivio. Ultimo costo e costo medio non si
|
||||||
|
scrivono dalla scheda: li aggiornano i carichi di magazzino (M6); fino ad allora li valorizzano solo i dati di
|
||||||
|
esempio. Il margine è sul prezzo: (prezzo - costo) / prezzo.
|
||||||
|
7. **Tipi e magazzino.** Solo le merci possono essere *gestite a magazzino*; servizi, spese, righe descrittive e
|
||||||
|
cespiti non lo sono mai (il servizio lo corregge). Giacenze, impegni, movimenti e proposta di riordino arrivano
|
||||||
|
con il magazzino (M6): la scheda li annuncia, i campi di riordino si compilano già.
|
||||||
|
8. **Codici.** Il codice segue la maschera `items` (`{categoria}-{seq:0000}`, ADR 0027); se la maschera usa la
|
||||||
|
categoria, la categoria è obbligatoria. Il codice a barre principale e quelli delle UM alternative hanno la
|
||||||
|
verifica EAN; un codice a barre già usato da un altro articolo è un avviso, o un errore se le preferenze chiedono
|
||||||
|
codici a barre univoci. La ricerca degli articoli trova esattamente anche i **codici alternativi** e, nei
|
||||||
|
documenti di un'anagrafica, i **codici che quell'anagrafica usa** (`party_item_codes`).
|
||||||
|
9. **Codici dell'anagrafica.** `party_item_codes` si gestisce nella scheda *Articoli e codici* dell'anagrafica e si
|
||||||
|
salva con essa (un codice non si ripete per la stessa anagrafica); i controlli sono di `ItemService`.
|
||||||
|
10. **Cancellazione.** Un articolo usato (sostitutivo di un altro, in documenti da M5) si disattiva invece di
|
||||||
|
cancellarsi, come le anagrafiche (ADR 0029). Un cliente con prezzi netti non si cancella.
|
||||||
|
11. **Dati di esempio.** `DemoItemsSeeder` crea 120 articoli fittizi di un grossista termoidraulico (SPEC §14) in dieci
|
||||||
|
categorie, due listini derivati dal base (*Pubblico* +45% arrotondato a 0,10, *Rivenditori* -10%), un prezzo
|
||||||
|
dell'anno precedente per lo storico, prezzi netti e codici di Rossi Impianti, fornitori abituali, UM alternative,
|
||||||
|
codici alternativi e sostitutivi. I codici a barre hanno prefisso 200, riservato all'uso interno. Il comando
|
||||||
|
`seed --demo [--scale N]` esegue prima i dati di base e poi quelli di esempio, ripetendo il catalogo N volte.
|
||||||
|
|
||||||
|
## Conseguenze
|
||||||
|
|
||||||
|
- I documenti (M5) chiamano `PriceListService.QuoteAsync` dentro la propria unità di lavoro e salvano prezzo e fonte;
|
||||||
|
la stessa logica serve l'API (`items`, `price-lists`) e il tool MCP `search_items`.
|
||||||
|
- Cambiare un prezzo non tocca i documenti esistenti; per correggere un prezzo sbagliato si riscrive con la stessa
|
||||||
|
data, per un aumento si usa una data nuova.
|
||||||
|
- Il magazzino (M6) aggiornerà `last_cost` e `average_cost` e aggiungerà le schede *Giacenze* e *Movimenti*.
|
||||||
@@ -73,12 +73,13 @@ listino, agente, esito VIES, split payment). Il blocco del **fatturato** arriva
|
|||||||
| **Condizioni** | condizioni di vendita (clienti), di acquisto (fornitori, e clienti che sono anche fornitori), conti contabili |
|
| **Condizioni** | condizioni di vendita (clienti), di acquisto (fornitori, e clienti che sono anche fornitori), conti contabili |
|
||||||
| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento, identificativi |
|
| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento, identificativi |
|
||||||
| **Banche** | conti correnti della controparte (IBAN), uno predefinito |
|
| **Banche** | conti correnti della controparte (IBAN), uno predefinito |
|
||||||
|
| **Articoli e codici** | i codici con cui il cliente o il fornitore identifica i tuoi articoli: codice, articolo (ricerca F4), descrizione; nei documenti di quell'anagrafica la ricerca degli articoli trova anche questi codici (vedi [Articoli e listini](Articoli-e-listini)) |
|
||||||
| **Note e allegati** | note libere e file allegati all'anagrafica |
|
| **Note e allegati** | note libere e file allegati all'anagrafica |
|
||||||
| **Storico** | modifiche registrate: chi, quando, cosa |
|
| **Storico** | modifiche registrate: chi, quando, cosa |
|
||||||
|
|
||||||
Una scheda con errori mostra il numero degli errori nell'etichetta; le liste mostrano quante righe contengono. La
|
Una scheda con errori mostra il numero degli errori nell'etichetta; le liste mostrano quante righe contengono. La
|
||||||
scheda *Articoli e codici* (codici con cui la controparte identifica i tuoi articoli) arriva con gli articoli, la
|
scheda *CRM* arriva con il modulo CRM. Nella scheda *Articoli e codici* lo stesso codice non si ripete per la stessa
|
||||||
scheda *CRM* con il modulo CRM.
|
anagrafica.
|
||||||
|
|
||||||
### Dati principali
|
### Dati principali
|
||||||
|
|
||||||
|
|||||||
+140
-90
@@ -1,153 +1,203 @@
|
|||||||
# Articoli e listini
|
# Articoli e listini
|
||||||
|
|
||||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4)
|
> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** non ancora rilasciata (milestone M4)
|
||||||
> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `items.*` (es. `items.cost.read` per vedere i costi) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §11.6
|
> **Modulo di licenza:** CORE · **Permessi principali:** `items.item.read` (consultare), `items.item.write` (inserire, modificare, disattivare, prezzi), `items.item.delete` (eliminare), `items.cost.read` (vedere costi e margini) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §14 · **Decisioni:** ADR 0030
|
||||||
|
|
||||||
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe di solo testo e cespiti.
|
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella
|
||||||
Nella scheda articolo stanno codici, unità di misura, IVA, conti contabili, prezzi e costi, i parametri di
|
scheda articolo stanno codici, unità di misura, IVA, conti, prezzi e costi e i parametri di **riordino**. I
|
||||||
**riordino** e le **giacenze** per deposito in tempo reale. I **listini** raccolgono i prezzi di vendita per gruppi di
|
**listini** raccolgono i prezzi di vendita per gruppi di clienti, con una data di validità, e si aggiornano anche in
|
||||||
clienti e si aggiornano anche in modo massivo.
|
modo massivo.
|
||||||
|
|
||||||
## Dove si trova
|
## Dove si trova
|
||||||
|
|
||||||
Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**; le categorie articolo sono in **Anagrafiche →
|
Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**. Le **categorie articolo**, le **intestazioni dei
|
||||||
Categorie**.
|
listini** e le **unità di misura** sono tabelle dell'azienda (vedi [Tabelle azienda](Tabelle-azienda)).
|
||||||
|
|
||||||
|
## L'elenco degli articoli
|
||||||
|
|
||||||
|
L'elenco è una griglia con ricerca per codice, descrizione, codice a barre (anche alternativo) e marca, e le colonne
|
||||||
|
codice, descrizione, tipo, categoria, UM, **prezzo base**, **costo medio** (solo con il permesso di vedere i costi),
|
||||||
|
magazzino e stato. I filtri rapidi scelgono tipo, categoria, articoli a magazzino e **attivi / disattivati**. Dalla
|
||||||
|
toolbar si disattivano e riattivano gli articoli selezionati e si apre la griglia dei listini.
|
||||||
|
|
||||||
## La scheda articolo
|
## La scheda articolo
|
||||||
|
|
||||||

|

|
||||||
*Mockup 017 — scheda articolo: azioni Movimenti, Etichette, Proposta riordino; intestazione con disponibilità e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).*
|
*Mockup 017 — scheda articolo: intestazione con prezzo e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).*
|
||||||
|
|
||||||
**Toolbar**: comandi standard e le azioni contestuali **Movimenti** (movimenti di magazzino dell'articolo),
|
**Intestazione**: codice, descrizione, tipo e categoria; a destra il **prezzo base in vigore oggi** con costo medio,
|
||||||
**Etichette** (stampa etichette), **Proposta riordino**.
|
ultimo costo, costo standard e **margine** (i costi solo con il permesso `items.cost.read`).
|
||||||
|
|
||||||
**Intestazione**: a sinistra codice, avvisi (ad esempio *Sotto punto di riordino*), EAN e categoria; al centro
|
**Schede**:
|
||||||
descrizione, UM, marca, peso, nomenclatura NC8, aliquota IVA e chip con prezzi di listino, disponibilità
|
|
||||||
(*Disp. · Imp. · Ord.*), fornitore abituale, scorta minima e punto di riordino; a destra il **costo medio** con
|
|
||||||
ultimo costo, costo standard e margine.
|
|
||||||
|
|
||||||
**Schede**: *Dati principali*, *UM alternative*, *Codici alternativi*, *Listini*, *Fornitori*, *Sostitutivi*,
|
| Scheda | Contenuto |
|
||||||
*Movimenti*, *Immagini e allegati*.
|
|---|---|
|
||||||
|
| **Dati principali** | i gruppi *Identità*, *Unità, codici e IVA*, *Prezzi e costi*, *Magazzino e riordino*, *Contabilità* |
|
||||||
|
| **UM alternative** | unità diverse da quella base con il **fattore** (una scatola da 10 pezzi ha fattore 10) e l'EAN della confezione |
|
||||||
|
| **Codici alternativi** | codici a barre dei produttori e codici dei vecchi gestionali: la ricerca li trova esattamente |
|
||||||
|
| **Listini** | i prezzi in vigore oggi in ogni listino, i prezzi di listino scritti con la loro data e i **prezzi netti dei clienti** |
|
||||||
|
| **Fornitori** | chi fornisce l'articolo, con codice e prezzo del fornitore, giorni di consegna, minimo d'ordine e il **fornitore abituale** |
|
||||||
|
| **Sostitutivi** | articoli equivalenti da proporre quando quello richiesto manca |
|
||||||
|
| **Note e allegati** | note libere e file (immagini, schede tecniche) |
|
||||||
|
| **Storico** | modifiche registrate: chi, quando, cosa |
|
||||||
|
|
||||||
|
Una scheda con errori mostra il numero degli errori nell'etichetta, come nelle [Anagrafiche](Anagrafiche).
|
||||||
|
|
||||||
### Campi principali
|
### Campi principali
|
||||||
|
|
||||||
| Gruppo | Campi |
|
| Gruppo | Campi |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **Identità** | Codice (automatico), Tipo, Categoria, **Descrizione** *, Descrizione estesa, Marca, Produttore |
|
| **Identità** | Codice (automatico), Tipo, Categoria, **Descrizione** *, Descrizione estesa, Marca, Produttore |
|
||||||
| **Codici, UM e fisco** | UM base, EAN (con verifica della cifra di controllo), NC8 (Intrastat), IVA vendita, IVA acquisto, Peso netto, Conto ricavo, Conto costo |
|
| **Unità, codici e IVA** | UM base, codice a barre (EAN, con verifica della cifra di controllo), nomenclatura **NC8** (otto cifre, per Intrastat), IVA vendita, IVA acquisto, Peso netto e lordo |
|
||||||
| **Prezzi e costi** | prezzi dei listini principali (es. base, pubblico IVA inclusa, rivenditori), Costo standard, Ultimo costo, Medio ponderato (gli ultimi due calcolati) |
|
| **Prezzi e costi** | Prezzo dell'articolo (vale solo se nessun listino ha un prezzo), Costo standard, Ultimo costo, Costo medio |
|
||||||
| **Riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino**, Fornitore abituale |
|
| **Magazzino e riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino** |
|
||||||
| **Giacenze per deposito (tempo reale)** | per ogni deposito: Giacenza, Impegnato, Ordinato, Disponibile, Valore, con riga di totale |
|
| **Contabilità** | Conto ricavo, Conto costo |
|
||||||
|
|
||||||
### Tipi di articolo
|
### Tipi di articolo
|
||||||
|
|
||||||
| Tipo | Uso | Magazzino |
|
| Tipo | Uso | Magazzino |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| **Merce** | beni venduti o acquistati | sì, se *Gestito a magazzino* |
|
| **Merce** | beni venduti o acquistati | sì, se *Gestito a magazzino* |
|
||||||
| **Servizio** | prestazioni (es. installazione, assistenza a ore) | no |
|
| **Servizio** | prestazioni (installazione, assistenza a ore) | no |
|
||||||
| **Spesa** | spese accessorie in fattura (trasporto, incasso) | no |
|
| **Spesa** | spese accessorie in fattura (trasporto, incasso) | no |
|
||||||
| **Testo** | righe descrittive ricorrenti | no |
|
| **Descrittivo** | righe di solo testo ricorrenti | no |
|
||||||
| **Cespite** | beni strumentali (collegati al registro cespiti con il modulo Cespiti) | da definire in sviluppo |
|
| **Cespite** | beni strumentali (registro cespiti con il modulo Cespiti) | no |
|
||||||
|
|
||||||
### Unità di misura e codici
|
Solo le merci possono essere gestite a magazzino: per gli altri tipi l'opzione è spenta e Khaemhat la corregge al
|
||||||
|
salvataggio.
|
||||||
|
|
||||||
- **UM base** (ad esempio `PZ`, `MT`, `H`, `NR`) dalla tabella delle unità di misura, con il codice usato nell'XML
|
### Costi
|
||||||
SDI; le **UM alternative** hanno un fattore di conversione (ad esempio confezione da 10 pezzi).
|
|
||||||
- **Codici alternativi**: altri codici a barre (EAN) e codici interni; nella ricerca F4 un articolo si trova anche
|
|
||||||
per EAN e per il **codice che il cliente usa** per quell'articolo (impostato nella scheda *Articoli e codici* del
|
|
||||||
cliente, vedi [Anagrafiche](Anagrafiche)).
|
|
||||||
- **Fornitori**: chi fornisce l'articolo, con codice e prezzo del fornitore; uno è il **fornitore abituale** usato
|
|
||||||
dalla proposta di riordino.
|
|
||||||
- **Sostitutivi**: articoli equivalenti proposti quando quello richiesto non è disponibile.
|
|
||||||
|
|
||||||
### Prezzi e costi
|
- **Costo standard**: valore scritto a mano.
|
||||||
|
- **Ultimo costo** e **costo medio**: li aggiornano i carichi di magazzino (DDT di carico, fatture di acquisto) che
|
||||||
|
arrivano con il magazzino (M6); fino ad allora sono valorizzati solo nei dati di esempio. Il costo medio è il
|
||||||
|
criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
|
||||||
|
- Il **margine** è calcolato sul prezzo: (prezzo - costo) / prezzo.
|
||||||
|
- Chi non ha il permesso `items.cost.read` non vede i costi (né nella scheda né nell'elenco né nei listini) e,
|
||||||
|
quando salva, i costi in archivio restano quelli di prima.
|
||||||
|
|
||||||
- I **prezzi di vendita** stanno nei listini (vedi sotto); la scheda mostra quelli dei listini principali.
|
### Giacenze e riordino
|
||||||
- **Costo standard**: valore impostato a mano.
|
|
||||||
- **Ultimo costo** e **costo medio ponderato**: aggiornati dai carichi di magazzino (DDT di carico, fatture di
|
|
||||||
acquisto). Il costo medio è il criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
|
|
||||||
- Il **margine** è mostrato solo a chi ha il permesso di vedere costi e margini.
|
|
||||||
|
|
||||||
### Riordino e giacenze
|
Con **Gestito a magazzino** l'articolo parteciperà a movimenti, giacenze per deposito (*Giacenza, Impegnato,
|
||||||
|
Ordinato, Disponibile, Valore*) e **proposta di riordino**: questi arrivano con il magazzino (M6). Scorta minima,
|
||||||
|
punto e lotto di riordino si possono già compilare.
|
||||||
|
|
||||||
Con **Gestito a magazzino** attivo l'articolo partecipa ai movimenti, alle giacenze e alla **proposta di riordino**:
|
### Controlli al salvataggio
|
||||||
quando la disponibilità scende sotto il **punto di riordino** l'articolo viene proposto per un ordine al fornitore
|
|
||||||
abituale, in multipli del **lotto**. La griglia *Giacenze per deposito* mostra:
|
|
||||||
|
|
||||||
| Colonna | Significato |
|
- Descrizione obbligatoria; categoria obbligatoria se la maschera del codice la usa.
|
||||||
|---|---|
|
- Codice a barre con cifra di controllo corretta (EAN-8, EAN-13, UPC). Un codice a barre già usato da un altro
|
||||||
| **Giacenza** | quantità fisicamente presente |
|
articolo blocca il salvataggio se nelle preferenze è attivo *Blocca duplicati per EAN* (impostazione di
|
||||||
| **Impegnato** | quantità riservata da ordini clienti confermati |
|
partenza), altrimenti è solo un avviso.
|
||||||
| **Ordinato** | quantità in arrivo da ordini fornitore |
|
- NC8 di otto cifre; quantità, pesi, prezzi e costi non negativi; fattori delle UM maggiori di zero.
|
||||||
| **Disponibile** | giacenza - impegnato |
|
- Nelle schede di dettaglio: la stessa UM, lo stesso codice alternativo, lo stesso fornitore o sostitutivo non si
|
||||||
| **Valore** | giacenza x costo medio |
|
ripetono; un articolo non è sostitutivo di sé stesso; un prezzo netto vale per un cliente.
|
||||||
|
|
||||||
|
### Disattivare ed eliminare
|
||||||
|
|
||||||
|
**Disattiva** toglie l'articolo dalle ricerche dei documenti nuovi senza perdere nulla. **Elimina** cancella
|
||||||
|
l'articolo solo se nessun altro dato lo usa (ad esempio se è sostitutivo di un altro articolo, e da M5 se compare
|
||||||
|
nei documenti); altrimenti Khaemhat lo **disattiva** al posto dell'eliminazione e lo dice.
|
||||||
|
|
||||||
|
## Codici articolo
|
||||||
|
|
||||||
|
Il codice segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (categoria `VALV` →
|
||||||
|
`VALV-0013`). Maschera, codice manuale e blocco dei duplicati per EAN si impostano in *Tabelle azienda →
|
||||||
|
Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)). Il codice si assegna al primo
|
||||||
|
salvataggio.
|
||||||
|
|
||||||
|
I **codici che un cliente o un fornitore usa** per i tuoi articoli si scrivono nella scheda *Articoli e codici*
|
||||||
|
dell'anagrafica (vedi [Anagrafiche](Anagrafiche)): nei documenti di quel cliente la ricerca F4 trova l'articolo
|
||||||
|
anche con il suo codice.
|
||||||
|
|
||||||
## Listini
|
## Listini
|
||||||
|
|
||||||

|

|
||||||
*Mockup 018 — griglia listino x articolo: costo medio, LIST01 Base, LIST02 Pubblico, LIST03 Rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata e scheda con pallino di modifica.*
|
*Mockup 018 — griglia listino x articolo: costo medio, listini base, pubblico e rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata.*
|
||||||
|
|
||||||
La maschera **Listini** è una **griglia articoli x listini**: per ogni articolo (codice, descrizione, UM, costo
|
Un **listino** ha codice, descrizione, valuta, *IVA inclusa*, validità e, se è derivato, il listino da cui
|
||||||
medio) una colonna per ciascun listino, più eventuali colonne di **prezzi netti per cliente** e il **margine**.
|
**deriva**, il **ricarico %** (anche negativo, come uno sconto) e il **passo di arrotondamento**. Le intestazioni si
|
||||||
|
gestiscono nella tabella *Listini* dell'azienda; uno solo è il **listino base** (in partenza `BASE`).
|
||||||
|
|
||||||
- Filtri: ricerca, **Categoria**, **Listino**, **Validità** (la data a cui leggere i prezzi, ad esempio *Oggi*),
|
### La griglia dei listini
|
||||||
chip *Mostra margine*.
|
|
||||||
- I prezzi si modificano direttamente nelle celle; le modifiche restano evidenziate e la scheda mostra il pallino
|
|
||||||
arancione finché non salvi. Il piede riporta il numero di articoli, le modifiche non salvate e la data di validità
|
|
||||||
dei nuovi prezzi.
|
|
||||||
- Azioni: **Aggiornamento massivo**, **Nuovo listino**; icone per salvare, annullare, stampare, esportare,
|
|
||||||
applicare una variazione percentuale, ripristinare, duplicare.
|
|
||||||
|
|
||||||
Ogni listino ha una **validità** (i prezzi nuovi valgono da una data, i vecchi restano per i documenti precedenti),
|
**Anagrafiche → Listini** è una griglia **articoli x listini**: per ogni articolo codice, descrizione, UM, costo
|
||||||
può essere **derivato** da un altro listino (ad esempio pubblico = base + 40%) e ha le proprie regole di
|
medio (con il permesso) e una colonna per ciascun listino attivo.
|
||||||
**arrotondamento**.
|
|
||||||
|
- In alto: ricerca, **Listino** (tutti o uno solo), **Validità** (la data a cui leggere e scrivere i prezzi, oggi
|
||||||
|
in partenza), **Prezzi netti di** un cliente (aggiunge la colonna dei suoi prezzi netti) e **Mostra margine**.
|
||||||
|
- I prezzi si scrivono nelle celle (vuoto toglie il prezzo a quella data). Le celle cambiate restano **evidenziate
|
||||||
|
da salvare**; il piede riporta articoli, modifiche non salvate e data di validità dei nuovi prezzi. **Salva**
|
||||||
|
scrive tutto insieme, **Annulla modifiche** torna ai prezzi salvati.
|
||||||
|
- Le celle in *corsivo* sono **calcolate** da un listino derivato che non ha un prezzo proprio per l'articolo: il
|
||||||
|
suggerimento dice da quale listino. Scrivere un prezzo nella cella lo rende proprio di quel listino.
|
||||||
|
- Con modifiche non salvate non si cambiano validità o cliente: prima salva o annulla.
|
||||||
|
- **Nuovo listino** apre la tabella dei listini.
|
||||||
|
|
||||||
|
### Validità dei prezzi
|
||||||
|
|
||||||
|
Ogni prezzo vale **dalla sua data** fino al prezzo successivo dello stesso listino (o dello stesso cliente).
|
||||||
|
Scrivere un prezzo con una data nuova **aggiunge** un prezzo e lascia quello vecchio ai documenti datati prima;
|
||||||
|
scriverlo con la stessa data lo corregge. I documenti già fatti conservano sempre il prezzo di allora.
|
||||||
|
|
||||||
|
### Listini derivati
|
||||||
|
|
||||||
|
Un listino derivato senza un proprio prezzo per un articolo prende il prezzo del listino di partenza alla stessa
|
||||||
|
data, applica il ricarico e arrotonda al passo (al centesimo se il passo è zero). Esempio dei dati di esempio:
|
||||||
|
*Pubblico* = base + 45% arrotondato a 0,10; *Rivenditori* = base - 10%. Un prezzo scritto nel listino derivato vince
|
||||||
|
su quello calcolato.
|
||||||
|
|
||||||
### Aggiornamento massivo
|
### Aggiornamento massivo
|
||||||
|
|
||||||
1. Premi **Aggiornamento massivo**.
|
1. Premi **Aggiornamento massivo**.
|
||||||
2. Scegli **che cosa** aggiornare: un listino, una categoria o le righe selezionate.
|
2. Scegli il **listino da aggiornare** e da dove **calcolare**: i prezzi attuali dello stesso listino o un altro
|
||||||
3. Scegli la **variazione**: percentuale (anche negativa) oppure a partire da un altro listino.
|
listino.
|
||||||
4. Scegli l'**arrotondamento**: a 0,10, 0,50 o 1,00, per eccesso o per difetto.
|
3. Scrivi la **variazione %** (anche negativa).
|
||||||
5. Indica la **data di validità** dei nuovi prezzi.
|
4. Scegli l'**arrotondamento** (0,01, 0,10, 0,50, 1,00) e il **verso** (al più vicino, per eccesso, per difetto).
|
||||||
6. Controlla le righe aggiornate (restano evidenziate) e **Salva**.
|
5. Indica la data da cui valgono i nuovi prezzi (**Valido dal**).
|
||||||
|
6. Scegli gli **articoli**: tutti, quelli di una categoria o solo i selezionati.
|
||||||
|
7. Premi **Calcola i prezzi**: le celle calcolate restano evidenziate; controllale e **Salva**.
|
||||||
|
|
||||||
L'aggiornamento listini è disponibile anche come procedura pianificabile (vedi [Automazioni](Automazioni)).
|
Il calcolo non scrive nulla finché non salvi; gli articoli il cui prezzo non cambia sono esclusi.
|
||||||
|
|
||||||
## Come viene scelto il prezzo in un documento
|
## Come viene scelto il prezzo in un documento
|
||||||
|
|
||||||
Quando inserisci un articolo in una riga di vendita, Khaemhat cerca il prezzo in quest'ordine e si ferma al primo
|
Quando inserisci un articolo in una riga di vendita (da M5), Khaemhat cerca il prezzo valido alla data del documento
|
||||||
che trova:
|
in quest'ordine e si ferma al primo che trova:
|
||||||
|
|
||||||
| Ordine | Fonte | Esempio |
|
| Ordine | Fonte | Esempio |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 1 | **prezzo netto cliente-articolo** | prezzo concordato con Rossi Impianti per quella valvola |
|
| 1 | **prezzo netto cliente-articolo** | prezzo concordato con Rossi Impianti per quella valvola |
|
||||||
| 2 | **listino del cliente** | il cliente usa LIST03 Rivenditori |
|
| 2 | **listino del documento o del cliente** | il cliente usa il listino *Rivenditori* |
|
||||||
| 3 | **listino base** | LIST01 Base |
|
| 3 | **listino base** | *Base* |
|
||||||
| 4 | **prezzo dell'articolo** | prezzo indicato nella scheda |
|
| 4 | **prezzo dell'articolo** | prezzo scritto nella scheda |
|
||||||
|
|
||||||
La riga ricorda **da dove viene il prezzo** (la fonte), così è sempre possibile capire perché è stato proposto
|
La riga ricorda **da dove viene il prezzo** (la fonte). Sul prezzo di listino si propongono gli sconti del cliente a
|
||||||
quel valore. Sul prezzo si applicano poi gli sconti del cliente e della riga (anche a cascata, come `5+2`). Se è
|
cascata (come `10+5`); su un **prezzo netto** non si applicano sconti.
|
||||||
attiva la compilazione automatica *Ultimo prezzo praticato al cliente*, Khaemhat lo mostra come riferimento.
|
|
||||||
|
|
||||||
## Codici automatici
|
|
||||||
|
|
||||||
Il codice articolo segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (ad esempio
|
|
||||||
categoria `VALV` → `VALV-0013`); la maschera, l'eventuale codice manuale e il blocco dei **duplicati per EAN** si
|
|
||||||
impostano in *Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)).
|
|
||||||
|
|
||||||
## Permessi e licenza
|
## Permessi e licenza
|
||||||
|
|
||||||
Articoli e listini sono nel modulo **CORE**. I costi e i margini sono visibili solo agli utenti con il permesso
|
Articoli e listini sono nel modulo **CORE**. Per scrivere i prezzi nella griglia serve `items.item.write`; i costi
|
||||||
`items.cost.read` (flag *vede costi e margini*). Il collegamento ai cespiti richiede il modulo **ASSET**; i conti
|
e i margini richiedono `items.cost.read` (il ruolo *Magazzino* gestisce gli articoli ma non vede i costi). Il
|
||||||
contabili sono usati con il modulo **ACCT**.
|
collegamento ai cespiti richiede il modulo **ASSET**; i conti contabili sono usati con il modulo **ACCT**.
|
||||||
|
|
||||||
|
## Dati di esempio
|
||||||
|
|
||||||
|
I dati di esempio (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) creano 120 articoli fittizi di un
|
||||||
|
grossista termoidraulico in dieci categorie (valvolame, raccorderia, tubi, caldaie, sanitari, consumabili, pompe,
|
||||||
|
utensili, servizi, spese), i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi dell'anno precedente per
|
||||||
|
lo storico, fornitori abituali, UM alternative, codici alternativi, sostitutivi e i prezzi netti e i codici di
|
||||||
|
Rossi Impianti. I codici a barre di esempio iniziano con `200`, prefisso riservato all'uso interno.
|
||||||
|
|
||||||
## Domande frequenti
|
## Domande frequenti
|
||||||
|
|
||||||
- **Ho cambiato un prezzo di listino ma la fattura di ieri non cambia.** È corretto: i documenti conservano il
|
- **Ho cambiato un prezzo di listino ma la fattura di ieri non cambia.** È corretto: i documenti conservano il
|
||||||
prezzo con cui sono stati fatti; la validità del listino vale per i documenti nuovi.
|
prezzo con cui sono stati fatti; i prezzi nuovi valgono dalla loro data.
|
||||||
- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente:
|
- **Ho scritto un prezzo con la data sbagliata.** Imposta quella data in *Validità*, svuota la cella e salva: il
|
||||||
la fonte del prezzo è indicata nella riga.
|
prezzo a quella data viene tolto.
|
||||||
- **Un articolo di servizio non compare nelle giacenze.** I servizi e le spese non sono gestiti a magazzino.
|
- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente: la
|
||||||
|
fonte del prezzo è indicata nella riga.
|
||||||
|
- **Non vedo il costo medio.** Serve il permesso di vedere costi e margini (`items.cost.read`).
|
||||||
|
- **Un servizio non si può mettere a magazzino.** È voluto: solo le merci vanno a magazzino.
|
||||||
|
|
||||||
## Pagine correlate
|
## Pagine correlate
|
||||||
|
|
||||||
|
|||||||
@@ -130,7 +130,10 @@ soggetto (fra cui un comune con split payment, un cliente bloccato, uno disattiv
|
|||||||
uno con dichiarazione d'intento), 5 fornitori (professionista con ritenuta, agente ENASARCO, fornitore UE),
|
uno con dichiarazione d'intento), 5 fornitori (professionista con ritenuta, agente ENASARCO, fornitore UE),
|
||||||
2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono numeri inventati ma formalmente validi, perché passino
|
2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono numeri inventati ma formalmente validi, perché passino
|
||||||
i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non sono marcati e si rimuovono a mano.
|
i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non sono marcati e si rimuovono a mano.
|
||||||
Il resto della tabella arriva con le milestone dei rispettivi moduli.
|
Ci sono poi **120 articoli** in dieci categorie con i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi
|
||||||
|
dell'anno precedente, fornitori abituali, UM e codici alternativi, sostitutivi e i prezzi netti e i codici di un
|
||||||
|
cliente (ADR 0030, vedi [Articoli e listini](Articoli-e-listini)). I codici a barre di esempio iniziano con `200`,
|
||||||
|
prefisso riservato all'uso interno. Il resto della tabella arriva con le milestone dei rispettivi moduli.
|
||||||
I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo
|
I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo
|
||||||
stesso caricamento è usato come prova automatica di correttezza.
|
stesso caricamento è usato come prova automatica di correttezza.
|
||||||
|
|
||||||
@@ -162,7 +165,7 @@ esempio.
|
|||||||
|
|
||||||
## Da riga di comando
|
## Da riga di comando
|
||||||
|
|
||||||
Lo script `scripts/seed.sh` aggiunge le tabelle di base fuori dall'interfaccia. Esegue la sequenza di avvio
|
Lo script `scripts/seed.sh` aggiunge le tabelle di base e i dati di esempio fuori dall'interfaccia. Esegue la sequenza di avvio
|
||||||
(migrazioni, prima azienda) senza servire pagine, poi lavora su un'azienda o su tutte quelle attive e stampa le righe
|
(migrazioni, prima azienda) senza servire pagine, poi lavora su un'azienda o su tutte quelle attive e stampa le righe
|
||||||
aggiunte per tabella. Usa le stesse variabili `KHAEMHAT_*` del servizio.
|
aggiunte per tabella. Usa le stesse variabili `KHAEMHAT_*` del servizio.
|
||||||
|
|
||||||
@@ -171,13 +174,20 @@ Nel container (lo script è in `/app/scripts/`):
|
|||||||
```
|
```
|
||||||
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base
|
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base
|
||||||
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base --company DEMO
|
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base --company DEMO
|
||||||
|
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --company DEMO
|
||||||
|
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --scale 10 --company PROVA
|
||||||
```
|
```
|
||||||
|
|
||||||
In sviluppo, dalla cartella del repository: `scripts/seed.sh --base [--company CODICE]`.
|
In sviluppo, dalla cartella del repository: `scripts/seed.sh --base|--demo [--scale N] [--company CODICE]`.
|
||||||
|
|
||||||
Le opzioni `--demo [--scale N]` per i dati di esempio (`--scale N` moltiplica i volumi, per le prove di prestazione)
|
| Opzione | Effetto |
|
||||||
arrivano con gli articoli (#42); oggi vengono rifiutate con un messaggio. Le anagrafiche di esempio si caricano già
|
|---|---|
|
||||||
al primo avvio con `KHAEMHAT_SEED_DEMO=true`.
|
| `--base` | aggiunge i codici di base mancanti |
|
||||||
|
| `--demo` | prima i dati di base, poi i dati di esempio; ogni gruppo (anagrafiche, articoli) si carica solo nell'azienda che non ne ha ancora |
|
||||||
|
| `--scale N` | solo con `--demo`: ripete il catalogo articoli N volte (da 1 a 100), per le prove di prestazione |
|
||||||
|
| `--company CODICE` | lavora solo su quell'azienda invece che su tutte quelle attive |
|
||||||
|
|
||||||
|
I dati di esempio si caricano anche al primo avvio con `KHAEMHAT_SEED_DEMO=true`.
|
||||||
|
|
||||||
## Migrazioni
|
## Migrazioni
|
||||||
|
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
|
|||||||
| **Depositi** | magazzini, anche mobili (es. furgone) |
|
| **Depositi** | magazzini, anche mobili (es. furgone) |
|
||||||
| **Categorie articolo** | su tre livelli |
|
| **Categorie articolo** | su tre livelli |
|
||||||
| **Categorie controparte** | classificazione di clienti e fornitori |
|
| **Categorie controparte** | classificazione di clienti e fornitori |
|
||||||
| **Listini** | intestazioni dei listini (i prezzi sono in [Articoli e listini](Articoli-e-listini)) |
|
| **Listini** | intestazioni dei listini: valuta, IVA inclusa, validità, **Listino base** (uno solo, in partenza `BASE`), **Derivato da** con ricarico % e arrotondamento (i prezzi sono in [Articoli e listini](Articoli-e-listini)) |
|
||||||
| **Politiche di sconto** | regole di sconto riutilizzabili (struttura definita in sviluppo) |
|
| **Politiche di sconto** | regole di sconto riutilizzabili (struttura definita in sviluppo) |
|
||||||
| **Tipi documento** | catalogo dei documenti con numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa |
|
| **Tipi documento** | catalogo dei documenti con numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa |
|
||||||
| **Centri di costo** | per l'analisi dei costi e dei ricavi |
|
| **Centri di costo** | per l'analisi dei costi e dei ricavi |
|
||||||
|
|||||||
+3
-2
@@ -1,10 +1,11 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Adds the missing base tables to the company databases (SPEC §14, ADR 0026). Rows already there are never changed.
|
# Adds the missing base tables to the company databases (SPEC §14, ADR 0026), and with --demo the demo data to the
|
||||||
|
# tables still empty (--scale N repeats the demo catalogues N times). Rows already there are never changed.
|
||||||
# scripts/seed.sh --base [--company CODE]
|
# scripts/seed.sh --base [--company CODE]
|
||||||
|
# scripts/seed.sh --demo [--scale N] [--company CODE]
|
||||||
# In the container (shipped as /app/scripts/seed.sh, same KHAEMHAT_* variables as the service):
|
# In the container (shipped as /app/scripts/seed.sh, same KHAEMHAT_* variables as the service):
|
||||||
# docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base
|
# docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base
|
||||||
# On a development machine it runs the project with the variables already set in the shell (see scripts/run-dev.sh).
|
# On a development machine it runs the project with the variables already set in the shell (see scripts/run-dev.sh).
|
||||||
# The demo data (--demo [--scale N]) arrive with parties and items.
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
if [[ -f /app/Khaemhat.Web.dll ]]; then
|
if [[ -f /app/Khaemhat.Web.dll ]]; then
|
||||||
|
|||||||
@@ -0,0 +1,885 @@
|
|||||||
|
using System.Data.Common;
|
||||||
|
using Khaemhat.Application.Audit;
|
||||||
|
using Khaemhat.Application.Querying;
|
||||||
|
using Khaemhat.Application.Security;
|
||||||
|
using Khaemhat.Application.Tables;
|
||||||
|
using Khaemhat.Core.Instance;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Core.Parties;
|
||||||
|
using Khaemhat.Core.Tables;
|
||||||
|
using Khaemhat.Core.Validation;
|
||||||
|
using Khaemhat.Data;
|
||||||
|
using Khaemhat.Data.Querying;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Items;
|
||||||
|
|
||||||
|
/// <summary>An item with all its details, as the record screen edits it (mockup 017).</summary>
|
||||||
|
public sealed class ItemRecord
|
||||||
|
{
|
||||||
|
/// <summary>The item.</summary>
|
||||||
|
public Item Item { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>The alternative units.</summary>
|
||||||
|
public List<ItemUnit> Units { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>The alternative codes.</summary>
|
||||||
|
public List<ItemBarcode> Barcodes { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>The prices: of the price lists and net of the customers, each with its validity.</summary>
|
||||||
|
public List<ItemPrice> Prices { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>The suppliers.</summary>
|
||||||
|
public List<ItemSupplier> Suppliers { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>The substitutes.</summary>
|
||||||
|
public List<ItemSubstitute> Substitutes { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A row of the items radar.</summary>
|
||||||
|
/// <param name="Id">The item.</param>
|
||||||
|
/// <param name="Code">The code.</param>
|
||||||
|
/// <param name="Description">The description.</param>
|
||||||
|
/// <param name="Kind">What the item is.</param>
|
||||||
|
/// <param name="CategoryId">The category.</param>
|
||||||
|
/// <param name="UnitOfMeasureId">The base unit.</param>
|
||||||
|
/// <param name="Barcode">The main bar code.</param>
|
||||||
|
/// <param name="Brand">The brand.</param>
|
||||||
|
/// <param name="Stocked">Kept in stock.</param>
|
||||||
|
/// <param name="AverageCost">The average cost, only for who can see costs.</param>
|
||||||
|
/// <param name="Disabled">Disabled.</param>
|
||||||
|
public sealed record ItemRow(
|
||||||
|
long Id, string Code, string Description, ItemKind Kind, long? CategoryId, long? UnitOfMeasureId, string? Barcode, string? Brand, bool Stocked,
|
||||||
|
decimal? AverageCost, bool Disabled)
|
||||||
|
{
|
||||||
|
/// <summary>The price of the base list today.</summary>
|
||||||
|
public decimal? BasePrice { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What happened to an item asked to be deleted.</summary>
|
||||||
|
public enum ItemDeleteOutcome
|
||||||
|
{
|
||||||
|
/// <summary>Deleted.</summary>
|
||||||
|
Deleted = 0,
|
||||||
|
|
||||||
|
/// <summary>Used by other data: disabled instead.</summary>
|
||||||
|
Disabled = 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Items (SPEC §11.2, mockup 017, ADR 0030): list, search by code, description, bar codes and codes of the parties,
|
||||||
|
/// record with units, codes, prices, suppliers and substitutes, checks, automatic code per category, history.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>Permissions <c>items.item.read</c>, <c>write</c>, <c>delete</c>; costs only with <c>items.cost.read</c>.</remarks>
|
||||||
|
public sealed class ItemService
|
||||||
|
{
|
||||||
|
/// <summary>Permission to read items and price lists.</summary>
|
||||||
|
public const string ReadPermission = "items.item.read";
|
||||||
|
|
||||||
|
/// <summary>Permission to write items and price lists.</summary>
|
||||||
|
public const string WritePermission = "items.item.write";
|
||||||
|
|
||||||
|
/// <summary>Permission to delete items.</summary>
|
||||||
|
public const string DeletePermission = "items.item.delete";
|
||||||
|
|
||||||
|
/// <summary>Permission to see costs and margins.</summary>
|
||||||
|
public const string CostPermission = "items.cost.read";
|
||||||
|
|
||||||
|
/// <summary>The entity of the attachments of an item.</summary>
|
||||||
|
public const string Entity = "items.item";
|
||||||
|
|
||||||
|
/// <summary>The code rule of the items (ADR 0027).</summary>
|
||||||
|
public const string CodeRule = "items";
|
||||||
|
|
||||||
|
/// <summary>Error: no description.</summary>
|
||||||
|
public const string DescriptionRequired = "items.description.required";
|
||||||
|
|
||||||
|
/// <summary>Error: the code is used by another item.</summary>
|
||||||
|
public const string CodeDuplicate = "items.code.duplicate";
|
||||||
|
|
||||||
|
/// <summary>Error: the code mask needs the category.</summary>
|
||||||
|
public const string CategoryRequired = "items.category.required";
|
||||||
|
|
||||||
|
/// <summary>Error: the bar code has a wrong check digit.</summary>
|
||||||
|
public const string BarcodeInvalid = "items.barcode.invalid";
|
||||||
|
|
||||||
|
/// <summary>Error or warning (by preference): another item has the bar code.</summary>
|
||||||
|
public const string BarcodeDuplicate = "items.barcode.duplicate";
|
||||||
|
|
||||||
|
/// <summary>Error: the NC8 code is not eight digits.</summary>
|
||||||
|
public const string CustomsCodeInvalid = "items.customs-code.invalid";
|
||||||
|
|
||||||
|
/// <summary>Error: a negative quantity, weight, price or cost.</summary>
|
||||||
|
public const string NotNegative = "items.value.negative";
|
||||||
|
|
||||||
|
/// <summary>Error: the factor of a unit is not above zero.</summary>
|
||||||
|
public const string FactorInvalid = "items.factor.invalid";
|
||||||
|
|
||||||
|
/// <summary>Error: a unit is listed twice, or is the base unit.</summary>
|
||||||
|
public const string UnitDuplicate = "items.unit.duplicate";
|
||||||
|
|
||||||
|
/// <summary>Error: a required detail field is empty.</summary>
|
||||||
|
public const string DetailRequired = "items.detail.required";
|
||||||
|
|
||||||
|
/// <summary>Error: the party of a supplier row is not a supplier.</summary>
|
||||||
|
public const string SupplierInvalid = "items.supplier.invalid";
|
||||||
|
|
||||||
|
/// <summary>Error: a supplier or a substitute is listed twice.</summary>
|
||||||
|
public const string DetailDuplicate = "items.detail.duplicate";
|
||||||
|
|
||||||
|
/// <summary>Error: an item cannot be its own substitute.</summary>
|
||||||
|
public const string SubstituteSelf = "items.substitute.self";
|
||||||
|
|
||||||
|
/// <summary>Error: a price is neither of a price list nor of a customer, or of both.</summary>
|
||||||
|
public const string PriceTarget = "items.price.target";
|
||||||
|
|
||||||
|
/// <summary>Error: a net price is for a customer only.</summary>
|
||||||
|
public const string PriceParty = "items.price.party";
|
||||||
|
|
||||||
|
/// <summary>Error: two prices of the same list or customer start on the same day.</summary>
|
||||||
|
public const string PriceDuplicate = "items.price.duplicate";
|
||||||
|
|
||||||
|
/// <summary>Error: the code of a party is used for another item.</summary>
|
||||||
|
public const string PartyCodeDuplicate = "items.party-code.duplicate";
|
||||||
|
|
||||||
|
/// <summary>Error: the item does not exist.</summary>
|
||||||
|
public const string NotFound = "items.not-found";
|
||||||
|
|
||||||
|
private readonly IUnitOfWorkFactory _factory;
|
||||||
|
private readonly PermissionService _permissions;
|
||||||
|
private readonly AuditTrail _audit;
|
||||||
|
private readonly CodeRuleService _codes;
|
||||||
|
private readonly TimeProvider _clock;
|
||||||
|
|
||||||
|
/// <summary>Creates the service.</summary>
|
||||||
|
/// <param name="factory">The units of work.</param>
|
||||||
|
/// <param name="permissions">The permissions.</param>
|
||||||
|
/// <param name="audit">The audit trail.</param>
|
||||||
|
/// <param name="codes">The automatic codes.</param>
|
||||||
|
/// <param name="clock">The clock.</param>
|
||||||
|
public ItemService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CodeRuleService codes, TimeProvider clock)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(factory);
|
||||||
|
ArgumentNullException.ThrowIfNull(permissions);
|
||||||
|
ArgumentNullException.ThrowIfNull(audit);
|
||||||
|
ArgumentNullException.ThrowIfNull(codes);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
_factory = factory;
|
||||||
|
_permissions = permissions;
|
||||||
|
_audit = audit;
|
||||||
|
_codes = codes;
|
||||||
|
_clock = clock;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The fields of the items radar.</summary>
|
||||||
|
public static ListFields<Item> Fields { get; } = new ListFields<Item>()
|
||||||
|
.Add("code", i => i.Code, searchable: true)
|
||||||
|
.Add("description", i => i.Description, searchable: true)
|
||||||
|
.Add("barcode", i => i.Barcode, searchable: true)
|
||||||
|
.Add("brand", i => i.Brand, searchable: true)
|
||||||
|
.Add("manufacturer", i => i.Manufacturer, searchable: true)
|
||||||
|
.Add("kind", i => i.Kind)
|
||||||
|
.Add("category", i => i.CategoryId)
|
||||||
|
.Add("unit", i => i.UnitOfMeasureId)
|
||||||
|
.Add("stocked", i => i.Stocked)
|
||||||
|
.Add("disabled", i => i.Disabled)
|
||||||
|
.OrderByDefault(new ListSort("code"));
|
||||||
|
|
||||||
|
/// <summary>The items for the radar, with the price of the base list today.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="query">Search, filters, sort, page.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The page.</returns>
|
||||||
|
public async Task<ListPage<ItemRow>> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(query);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
var page = await uow.Repository<Item, long>().ListAsync(Fields.Apply(Query.For<Item>(), query), cancellationToken).ConfigureAwait(false);
|
||||||
|
var book = await BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||||
|
var today = Today();
|
||||||
|
IReadOnlyList<ItemRow> rows =
|
||||||
|
[
|
||||||
|
.. page.Items.Select(i => RowOf(i, costs) with
|
||||||
|
{
|
||||||
|
BasePrice = book.Base is { } baseList ? book.ListPrice(i.Id, baseList.Id, today).Price : i.Price,
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
return new ListPage<ItemRow>(rows, page.TotalCount, new Dictionary<string, decimal>());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The active items matching a text, for the lookups: code, description, bar code and brand, or exactly an
|
||||||
|
/// alternative code or the code a party uses for the item.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="text">The text.</param>
|
||||||
|
/// <param name="partyId">The party of the document, whose codes count too.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>At most 20 items.</returns>
|
||||||
|
public async Task<IReadOnlyList<ItemRow>> SearchAsync(Actor actor, string companyCode, string? text, long? partyId = null, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
var items = uow.Repository<Item, long>();
|
||||||
|
var page = await items.ListAsync(
|
||||||
|
Fields.Apply(Query.For<Item>(), new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 }),
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
var found = page.Items.ToList();
|
||||||
|
var exact = text?.Trim();
|
||||||
|
if (!string.IsNullOrEmpty(exact))
|
||||||
|
{
|
||||||
|
var ids = (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(b => b.Code == exact), cancellationToken).ConfigureAwait(false))
|
||||||
|
.Items.Select(b => b.ItemId).ToList();
|
||||||
|
if (partyId is { } party)
|
||||||
|
{
|
||||||
|
ids.AddRange((await uow.Repository<PartyItemCode, long>().ListAsync(
|
||||||
|
Query.For<PartyItemCode>().Where(c => c.PartyId == party && c.Code == exact), cancellationToken).ConfigureAwait(false)).Items.Select(c => c.ItemId));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var id in ids.Distinct().Where(id => found.All(i => i.Id != id)))
|
||||||
|
{
|
||||||
|
if (await items.GetAsync(id, cancellationToken).ConfigureAwait(false) is { Disabled: false } item)
|
||||||
|
{
|
||||||
|
found.Insert(0, item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [.. found.Take(20).Select(i => RowOf(i, costs))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An item with its details; costs hidden without <c>items.cost.read</c>.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="id">The item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The record, or none.</returns>
|
||||||
|
public async Task<ItemRecord?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
var record = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (record is not null && !costs)
|
||||||
|
{
|
||||||
|
HideCosts(record);
|
||||||
|
}
|
||||||
|
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A new item with the usual values: goods kept in stock, unit PZ, VAT 22, the default warehouse.</summary>
|
||||||
|
/// <param name="actor">Who asks.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The record to fill.</returns>
|
||||||
|
public async Task<ItemRecord> NewAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
var unit = await uow.Repository<UnitOfMeasure, long>().FindAsync(Query.For<UnitOfMeasure>().Where(u => u.Code == "PZ" && !u.Disabled), cancellationToken).ConfigureAwait(false);
|
||||||
|
var tax = await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "22" && !t.Disabled), cancellationToken).ConfigureAwait(false);
|
||||||
|
var warehouse = await uow.Repository<Warehouse, long>().FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
|
||||||
|
return new ItemRecord
|
||||||
|
{
|
||||||
|
Item = new Item
|
||||||
|
{
|
||||||
|
Kind = ItemKind.Goods, Stocked = true, UnitOfMeasureId = unit?.Id, SalesTaxCodeId = tax?.Id, PurchaseTaxCodeId = tax?.Id, WarehouseId = warehouse?.Id,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Checks a record without saving it (also cleans it, as the save would).</summary>
|
||||||
|
/// <param name="actor">Who asks.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="record">The record.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>Errors and warnings.</returns>
|
||||||
|
public async Task<IReadOnlyList<TableProblem>> ValidateAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(record);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
return await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Saves an item and its details in one transaction; a new item gets its code from the rule of the items
|
||||||
|
/// (<c>{categoria}</c> is the code of its category). Without <c>items.cost.read</c> the costs stay as they were.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who saves.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="record">The record.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The record as saved.</returns>
|
||||||
|
/// <exception cref="ValidationFailedException">With the errors (<c>field:code</c>).</exception>
|
||||||
|
public async Task<ItemRecord> SaveAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(record);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||||
|
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
|
||||||
|
var item = record.Item;
|
||||||
|
long id;
|
||||||
|
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var before = item.Id == 0 ? null : await LoadAsync(uow, item.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]);
|
||||||
|
|
||||||
|
// The last and average costs come from the receipts (M6); the standard cost only from who sees costs.
|
||||||
|
item.LastCost = before?.Item.LastCost;
|
||||||
|
item.AverageCost = before?.Item.AverageCost;
|
||||||
|
if (!costs)
|
||||||
|
{
|
||||||
|
item.StandardCost = before?.Item.StandardCost;
|
||||||
|
}
|
||||||
|
|
||||||
|
var problems = (await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||||
|
if (problems.Count > 0)
|
||||||
|
{
|
||||||
|
throw new ValidationFailedException(problems);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.Code.Length == 0)
|
||||||
|
{
|
||||||
|
var category = item.CategoryId is { } categoryId ? (await uow.Repository<ItemCategory, long>().GetAsync(categoryId, cancellationToken).ConfigureAwait(false))?.Code : null;
|
||||||
|
item.Code = await CodeRuleService.AssignAsync(uow, rule, Today(), category, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||||
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Disables or enables items (radar selection).</summary>
|
||||||
|
/// <param name="actor">Who does it.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="ids">The items.</param>
|
||||||
|
/// <param name="disabled">Disable or enable.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>How many changed.</returns>
|
||||||
|
public async Task<int> SetDisabledAsync(Actor actor, string companyCode, IEnumerable<long> ids, bool disabled, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(ids);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var repository = uow.Repository<Item, long>();
|
||||||
|
var changed = 0;
|
||||||
|
foreach (var id in ids.Distinct())
|
||||||
|
{
|
||||||
|
if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } item && item.Disabled != disabled)
|
||||||
|
{
|
||||||
|
var before = Clone(item);
|
||||||
|
item.Disabled = disabled;
|
||||||
|
await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||||
|
await _audit.RecordAsync(uow, AuditAction.Update, id, before, item, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||||
|
changed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Deletes an item; one used by other data (a substitute, documents from M5) is disabled instead.</summary>
|
||||||
|
/// <param name="actor">Who deletes.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="id">The item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>What happened.</returns>
|
||||||
|
public async Task<ItemDeleteOutcome> DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var before = await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||||
|
await uow.Repository<Item, long>().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);
|
||||||
|
return ItemDeleteOutcome.Deleted;
|
||||||
|
}
|
||||||
|
catch (DbException)
|
||||||
|
{
|
||||||
|
await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false);
|
||||||
|
return ItemDeleteOutcome.Disabled;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The history of an item and of its prices, newest first.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="id">The item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The changes.</returns>
|
||||||
|
public async Task<IReadOnlyList<AuditEntry>> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
var entries = new List<AuditEntry>();
|
||||||
|
foreach (var entity in new[] { nameof(Item), nameof(ItemPrice) })
|
||||||
|
{
|
||||||
|
entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The rows of some items, for the lookups that show them by id.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="ids">The items.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The rows found.</returns>
|
||||||
|
public async Task<IReadOnlyList<ItemRow>> RowsAsync(Actor actor, string companyCode, IEnumerable<long> ids, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(ids);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||||
|
long[] wanted = [.. ids.Distinct()];
|
||||||
|
if (wanted.Length == 0)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
return [.. (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => wanted.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||||
|
.Select(i => RowOf(i, costs))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Checks the codes of a party: code and item required, no code twice.</summary>
|
||||||
|
/// <param name="codes">The codes.</param>
|
||||||
|
/// <returns>The errors.</returns>
|
||||||
|
public static IReadOnlyList<TableProblem> CheckPartyCodes(IReadOnlyList<PartyItemCode> codes)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(codes);
|
||||||
|
var problems = new List<TableProblem>();
|
||||||
|
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
for (var i = 0; i < codes.Count; i++)
|
||||||
|
{
|
||||||
|
var code = codes[i];
|
||||||
|
code.Code = code.Code.Trim();
|
||||||
|
code.Description = Clean(code.Description);
|
||||||
|
if (code.Code.Length == 0)
|
||||||
|
{
|
||||||
|
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", DetailRequired));
|
||||||
|
}
|
||||||
|
else if (!seen.Add(code.Code))
|
||||||
|
{
|
||||||
|
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", PartyCodeDuplicate));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (code.ItemId == 0)
|
||||||
|
{
|
||||||
|
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.ItemId)}", DetailRequired));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return problems;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether an actor sees costs and margins.</summary>
|
||||||
|
/// <param name="actor">The actor.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>Whether costs are visible.</returns>
|
||||||
|
public async Task<bool> CanSeeCostsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(actor);
|
||||||
|
return (actor.IsInstanceAccount || string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
|
||||||
|
&& (await _permissions.CheckAsync(actor, CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The prices of some items and all the price lists, in memory.</summary>
|
||||||
|
/// <param name="uow">The unit of work of the company.</param>
|
||||||
|
/// <param name="itemIds">The items.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The book.</returns>
|
||||||
|
public static async Task<PriceBook> BookAsync(IUnitOfWork uow, IReadOnlyList<long> itemIds, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(uow);
|
||||||
|
ArgumentNullException.ThrowIfNull(itemIds);
|
||||||
|
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||||
|
var prices = new List<ItemPrice>();
|
||||||
|
foreach (var chunk in itemIds.Distinct().Chunk(500))
|
||||||
|
{
|
||||||
|
long[] ids = [.. chunk];
|
||||||
|
prices.AddRange((await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(p => ids.Contains(p.ItemId)), cancellationToken).ConfigureAwait(false)).Items);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new PriceBook(lists, prices);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||||
|
|
||||||
|
private static ItemRow RowOf(Item i, bool costs) =>
|
||||||
|
new(i.Id, i.Code, i.Description, i.Kind, i.CategoryId, i.UnitOfMeasureId, i.Barcode, i.Brand, i.Stocked, costs ? i.AverageCost : null, i.Disabled);
|
||||||
|
|
||||||
|
private static void HideCosts(ItemRecord record)
|
||||||
|
{
|
||||||
|
record.Item.StandardCost = null;
|
||||||
|
record.Item.LastCost = null;
|
||||||
|
record.Item.AverageCost = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<bool> TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) =>
|
||||||
|
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code), cancellationToken).ConfigureAwait(false) > 0;
|
||||||
|
|
||||||
|
private static async Task<ItemRecord?> LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ItemRecord
|
||||||
|
{
|
||||||
|
Item = item,
|
||||||
|
Units = [.. (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
|
Barcodes = [.. (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
|
Prices = [.. (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
|
Suppliers = [.. (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
|
Substitutes = [.. (await uow.Repository<ItemSubstitute, long>().ListAsync(Query.For<ItemSubstitute>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<long> WriteAsync(IUnitOfWork uow, ItemRecord record, ItemRecord? before, string userName, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var item = record.Item;
|
||||||
|
var items = uow.Repository<Item, long>();
|
||||||
|
if (before is null)
|
||||||
|
{
|
||||||
|
item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
|
||||||
|
await _audit.RecordAsync<Item>(uow, AuditAction.Insert, item.Id, null, item, userName, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await items.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||||
|
await _audit.RecordAsync(uow, AuditAction.Update, item.Id, before.Item, item, userName, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var id = item.Id;
|
||||||
|
await ReplaceAsync(uow, record.Units, before?.Units ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ReplaceAsync(uow, record.Barcodes, before?.Barcodes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ReplaceAsync(uow, record.Suppliers, before?.Suppliers ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ReplaceAsync(uow, record.Substitutes, before?.Substitutes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ReplaceAsync(uow, record.Prices, before?.Prices ?? [], u => u.ItemId = id, cancellationToken, async (old, row, ct) =>
|
||||||
|
await _audit.RecordAsync(uow, old is null ? AuditAction.Insert : row is null ? AuditAction.Delete : AuditAction.Update, id, old, row, userName, ct).ConfigureAwait(false))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The lists: rows removed are deleted, rows kept are updated, new rows inserted; the prices are written in the history.
|
||||||
|
private static async Task ReplaceAsync<T>(
|
||||||
|
IUnitOfWork uow, List<T> rows, List<T> before, Action<T> link, CancellationToken cancellationToken, Func<T?, T?, CancellationToken, Task>? audit = null)
|
||||||
|
where T : Core.Entities.Entity<long>, new()
|
||||||
|
{
|
||||||
|
var repository = uow.Repository<T, long>();
|
||||||
|
var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet();
|
||||||
|
foreach (var old in before.Where(b => !kept.Contains(b.Id)))
|
||||||
|
{
|
||||||
|
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (audit is not null)
|
||||||
|
{
|
||||||
|
await audit(old, null, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var previous = before.ToDictionary(b => b.Id);
|
||||||
|
foreach (var row in rows)
|
||||||
|
{
|
||||||
|
link(row);
|
||||||
|
if (row.Id != 0 && previous.TryGetValue(row.Id, out var old))
|
||||||
|
{
|
||||||
|
row.RowVersion = old.RowVersion;
|
||||||
|
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (audit is not null)
|
||||||
|
{
|
||||||
|
await audit(old, row, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (audit is not null)
|
||||||
|
{
|
||||||
|
await audit(null, row, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<IReadOnlyList<TableProblem>> CheckAsync(IUnitOfWork uow, CodeRule rule, ItemRecord record, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var problems = new List<TableProblem>();
|
||||||
|
var item = record.Item;
|
||||||
|
Normalize(item);
|
||||||
|
if (item.Description.Length == 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(nameof(Item.Description), DescriptionRequired));
|
||||||
|
}
|
||||||
|
|
||||||
|
var id = item.Id;
|
||||||
|
if (item.Code.Length > 0)
|
||||||
|
{
|
||||||
|
var code = item.Code;
|
||||||
|
if (await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code && i.Id != id), cancellationToken).ConfigureAwait(false) > 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(nameof(Item.Code), CodeDuplicate));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (item.CategoryId is null && CodeMask.TryParse(rule.Mask, out var mask, out _) && mask!.UsesCategory)
|
||||||
|
{
|
||||||
|
problems.Add(new(nameof(Item.CategoryId), CategoryRequired));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.Barcode is { } barcode)
|
||||||
|
{
|
||||||
|
if (!EanValidator.IsValid(barcode))
|
||||||
|
{
|
||||||
|
problems.Add(new(nameof(Item.Barcode), BarcodeInvalid));
|
||||||
|
}
|
||||||
|
else if (await BarcodeUsedAsync(uow, barcode, id, cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
problems.Add(new(nameof(Item.Barcode), BarcodeDuplicate, IsWarning: !rule.UniqueBarcode));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.CustomsCode is { } customs && (customs.Length != 8 || !customs.All(char.IsAsciiDigit)))
|
||||||
|
{
|
||||||
|
problems.Add(new(nameof(Item.CustomsCode), CustomsCodeInvalid));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (value, field) in new (decimal?, string)[]
|
||||||
|
{
|
||||||
|
(item.NetWeight, nameof(Item.NetWeight)), (item.GrossWeight, nameof(Item.GrossWeight)), (item.MinimumStock, nameof(Item.MinimumStock)),
|
||||||
|
(item.ReorderPoint, nameof(Item.ReorderPoint)), (item.ReorderLot, nameof(Item.ReorderLot)), (item.Price, nameof(Item.Price)),
|
||||||
|
(item.StandardCost, nameof(Item.StandardCost)),
|
||||||
|
})
|
||||||
|
{
|
||||||
|
if (value < 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field, NotNegative));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckUnits(record, problems);
|
||||||
|
CheckBarcodes(record, problems);
|
||||||
|
await CheckPricesAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
|
||||||
|
await CheckSuppliersAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
|
||||||
|
CheckSubstitutes(record, problems);
|
||||||
|
return problems;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Normalize(Item item)
|
||||||
|
{
|
||||||
|
item.Code = item.Code.Trim();
|
||||||
|
item.Description = item.Description.Trim();
|
||||||
|
item.ExtendedDescription = Clean(item.ExtendedDescription);
|
||||||
|
item.Barcode = Clean(item.Barcode);
|
||||||
|
item.CustomsCode = Clean(item.CustomsCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).Replace(".", string.Empty, StringComparison.Ordinal);
|
||||||
|
item.Manufacturer = Clean(item.Manufacturer);
|
||||||
|
item.Brand = Clean(item.Brand);
|
||||||
|
item.RevenueAccountCode = Clean(item.RevenueAccountCode);
|
||||||
|
item.CostAccountCode = Clean(item.CostAccountCode);
|
||||||
|
item.Notes = Clean(item.Notes);
|
||||||
|
|
||||||
|
// Only goods move in the warehouse.
|
||||||
|
if (item.Kind != ItemKind.Goods)
|
||||||
|
{
|
||||||
|
item.Stocked = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<bool> BarcodeUsedAsync(IUnitOfWork uow, string barcode, long id, CancellationToken cancellationToken) =>
|
||||||
|
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Barcode == barcode && i.Id != id), cancellationToken).ConfigureAwait(false) > 0
|
||||||
|
|| await uow.Repository<ItemBarcode, long>().CountAsync(Query.For<ItemBarcode>().Where(b => b.Code == barcode && b.ItemId != id), cancellationToken).ConfigureAwait(false) > 0;
|
||||||
|
|
||||||
|
private static void CheckUnits(ItemRecord record, List<TableProblem> problems)
|
||||||
|
{
|
||||||
|
var seen = new HashSet<long>();
|
||||||
|
if (record.Item.UnitOfMeasureId is { } baseUnit)
|
||||||
|
{
|
||||||
|
seen.Add(baseUnit);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < record.Units.Count; i++)
|
||||||
|
{
|
||||||
|
var unit = record.Units[i];
|
||||||
|
unit.Barcode = Clean(unit.Barcode);
|
||||||
|
if (unit.UnitOfMeasureId == 0)
|
||||||
|
{
|
||||||
|
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", DetailRequired));
|
||||||
|
}
|
||||||
|
else if (!seen.Add(unit.UnitOfMeasureId))
|
||||||
|
{
|
||||||
|
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", UnitDuplicate));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unit.Factor <= 0)
|
||||||
|
{
|
||||||
|
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Factor)}", FactorInvalid));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unit.Barcode is { } barcode && !EanValidator.IsValid(barcode))
|
||||||
|
{
|
||||||
|
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Barcode)}", BarcodeInvalid));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckBarcodes(ItemRecord record, List<TableProblem> problems)
|
||||||
|
{
|
||||||
|
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
if (record.Item.Barcode is { } main)
|
||||||
|
{
|
||||||
|
seen.Add(main);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < record.Barcodes.Count; i++)
|
||||||
|
{
|
||||||
|
var code = record.Barcodes[i];
|
||||||
|
code.Code = code.Code.Trim();
|
||||||
|
code.Description = Clean(code.Description);
|
||||||
|
if (code.Code.Length == 0)
|
||||||
|
{
|
||||||
|
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailRequired));
|
||||||
|
}
|
||||||
|
else if (!seen.Add(code.Code))
|
||||||
|
{
|
||||||
|
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailDuplicate));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task CheckPricesAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var seen = new HashSet<(long?, long?, DateOnly?)>();
|
||||||
|
var parties = uow.Repository<Party, long>();
|
||||||
|
for (var i = 0; i < record.Prices.Count; i++)
|
||||||
|
{
|
||||||
|
var price = record.Prices[i];
|
||||||
|
var field = $"Prices.{i}.";
|
||||||
|
if ((price.PriceListId is null) == (price.PartyId is null))
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemPrice.PriceListId), PriceTarget));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A row added on the screen and not filled has id 0.
|
||||||
|
if (price.PriceListId is 0 || price.PartyId is 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field + (price.PartyId is null ? nameof(ItemPrice.PriceListId) : nameof(ItemPrice.PartyId)), DetailRequired));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (price.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemPrice.PartyId), PriceParty));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (price.Price < 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemPrice.Price), NotNegative));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!seen.Add((price.PriceListId, price.PartyId, price.ValidFrom)))
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemPrice.ValidFrom), PriceDuplicate));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task CheckSuppliersAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var seen = new HashSet<long>();
|
||||||
|
var parties = uow.Repository<Party, long>();
|
||||||
|
for (var i = 0; i < record.Suppliers.Count; i++)
|
||||||
|
{
|
||||||
|
var supplier = record.Suppliers[i];
|
||||||
|
var field = $"Suppliers.{i}.";
|
||||||
|
supplier.SupplierCode = Clean(supplier.SupplierCode);
|
||||||
|
if (supplier.PartyId == 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailRequired));
|
||||||
|
}
|
||||||
|
else if (!seen.Add(supplier.PartyId))
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailDuplicate));
|
||||||
|
}
|
||||||
|
else if (await parties.GetAsync(supplier.PartyId, cancellationToken).ConfigureAwait(false) is not { IsSupplier: true })
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemSupplier.PartyId), SupplierInvalid));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (supplier.Price < 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemSupplier.Price), NotNegative));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (supplier.MinimumQuantity < 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemSupplier.MinimumQuantity), NotNegative));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (supplier.LeadTimeDays < 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field + nameof(ItemSupplier.LeadTimeDays), NotNegative));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One usual supplier: the first one marked.
|
||||||
|
var found = false;
|
||||||
|
foreach (var supplier in record.Suppliers.Where(s => s.IsDefault))
|
||||||
|
{
|
||||||
|
supplier.IsDefault = !found;
|
||||||
|
found = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckSubstitutes(ItemRecord record, List<TableProblem> problems)
|
||||||
|
{
|
||||||
|
var seen = new HashSet<long>();
|
||||||
|
for (var i = 0; i < record.Substitutes.Count; i++)
|
||||||
|
{
|
||||||
|
var substitute = record.Substitutes[i];
|
||||||
|
var field = $"Substitutes.{i}.{nameof(ItemSubstitute.SubstituteId)}";
|
||||||
|
substitute.Notes = Clean(substitute.Notes);
|
||||||
|
if (substitute.SubstituteId == 0)
|
||||||
|
{
|
||||||
|
problems.Add(new(field, DetailRequired));
|
||||||
|
}
|
||||||
|
else if (substitute.SubstituteId == record.Item.Id)
|
||||||
|
{
|
||||||
|
problems.Add(new(field, SubstituteSelf));
|
||||||
|
}
|
||||||
|
else if (!seen.Add(substitute.SubstituteId))
|
||||||
|
{
|
||||||
|
problems.Add(new(field, DetailDuplicate));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
|
|
||||||
|
private static Item Clone(Item item)
|
||||||
|
{
|
||||||
|
var copy = new Item();
|
||||||
|
foreach (var property in typeof(Item).GetProperties().Where(p => p.CanRead && p.CanWrite))
|
||||||
|
{
|
||||||
|
property.SetValue(copy, property.GetValue(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
using Khaemhat.Application.Tables;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Core.Parties;
|
||||||
|
using Khaemhat.Core.Tables;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Items;
|
||||||
|
|
||||||
|
/// <summary>The price proposed for an item and where it comes from (<c>price_source</c> of the document lines).</summary>
|
||||||
|
/// <param name="Price">The price, or none.</param>
|
||||||
|
/// <param name="Source">Where it comes from.</param>
|
||||||
|
/// <param name="PriceListId">The price list it comes from.</param>
|
||||||
|
/// <param name="VatIncluded">The price includes VAT (a price list with VAT included).</param>
|
||||||
|
/// <param name="ValidFrom">The price is valid from this day.</param>
|
||||||
|
public sealed record PriceQuote(decimal? Price, PriceSource Source, long? PriceListId, bool VatIncluded, DateOnly? ValidFrom)
|
||||||
|
{
|
||||||
|
/// <summary>No price.</summary>
|
||||||
|
public static PriceQuote None { get; } = new(null, PriceSource.None, null, false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The discounts proposed on a line.</summary>
|
||||||
|
/// <param name="Formula">The chain, such as <c>5+2</c>, or none.</param>
|
||||||
|
/// <param name="Equivalent">The single discount equal to the chain, in percent.</param>
|
||||||
|
public sealed record DiscountQuote(string? Formula, decimal Equivalent)
|
||||||
|
{
|
||||||
|
/// <summary>No discount.</summary>
|
||||||
|
public static DiscountQuote None { get; } = new(null, 0m);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A price of a price list for an item at a date.</summary>
|
||||||
|
/// <param name="Price">The price, or none.</param>
|
||||||
|
/// <param name="Derived">The price is computed from the base list of a derived list, not written.</param>
|
||||||
|
/// <param name="ValidFrom">The price is valid from this day.</param>
|
||||||
|
public sealed record PriceCell(decimal? Price, bool Derived, DateOnly? ValidFrom)
|
||||||
|
{
|
||||||
|
/// <summary>No price.</summary>
|
||||||
|
public static PriceCell Empty { get; } = new(null, false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The prices of some items in memory, and the search of SPEC §11.3 (ADR 0030): net price of the party for the item,
|
||||||
|
/// then the price list of the party or of the document, then the base price list, then the price of the item. A
|
||||||
|
/// derived list without its own price takes the price of its base list with the markup and the rounding of the list.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PriceBook
|
||||||
|
{
|
||||||
|
// A derived list of a derived list... is followed at most this deep (the table forbids only a list on itself).
|
||||||
|
private const int MaxDepth = 5;
|
||||||
|
|
||||||
|
private readonly Dictionary<long, PriceList> _lists;
|
||||||
|
private readonly ILookup<(long Item, long List), ItemPrice> _listPrices;
|
||||||
|
private readonly ILookup<(long Item, long Party), ItemPrice> _netPrices;
|
||||||
|
|
||||||
|
/// <summary>Creates the book.</summary>
|
||||||
|
/// <param name="lists">The price lists of the company.</param>
|
||||||
|
/// <param name="prices">The prices of the items wanted (all their rows).</param>
|
||||||
|
public PriceBook(IEnumerable<PriceList> lists, IEnumerable<ItemPrice> prices)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(lists);
|
||||||
|
ArgumentNullException.ThrowIfNull(prices);
|
||||||
|
_lists = lists.ToDictionary(l => l.Id);
|
||||||
|
var all = prices.ToList();
|
||||||
|
_listPrices = all.Where(p => p.PriceListId is not null).ToLookup(p => (p.ItemId, p.PriceListId!.Value));
|
||||||
|
_netPrices = all.Where(p => p.PartyId is not null).ToLookup(p => (p.ItemId, p.PartyId!.Value));
|
||||||
|
Base = BaseOf(_lists.Values);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The base price list: the one marked, or the one with code <c>BASE</c>.</summary>
|
||||||
|
public PriceList? Base { get; }
|
||||||
|
|
||||||
|
/// <summary>The price lists.</summary>
|
||||||
|
public IReadOnlyCollection<PriceList> Lists => _lists.Values;
|
||||||
|
|
||||||
|
/// <summary>The base price list among some.</summary>
|
||||||
|
/// <param name="lists">The price lists.</param>
|
||||||
|
/// <returns>The base one, or none.</returns>
|
||||||
|
public static PriceList? BaseOf(IEnumerable<PriceList> lists)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(lists);
|
||||||
|
var active = lists.Where(l => !l.Disabled).OrderBy(l => l.Code, StringComparer.Ordinal).ToList();
|
||||||
|
return active.FirstOrDefault(l => l.IsBase) ?? active.FirstOrDefault(l => l.Code == "BASE");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The row in effect at a date: the latest start not after it (a row without start is always valid).</summary>
|
||||||
|
/// <param name="rows">The rows of one item and one list or party.</param>
|
||||||
|
/// <param name="date">The date.</param>
|
||||||
|
/// <returns>The row, or none.</returns>
|
||||||
|
public static ItemPrice? At(IEnumerable<ItemPrice> rows, DateOnly date)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(rows);
|
||||||
|
return rows.Where(r => r.ValidFrom is null || r.ValidFrom <= date).OrderByDescending(r => r.ValidFrom ?? DateOnly.MinValue).FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether a price list can be used at a date: active and within its validity.</summary>
|
||||||
|
/// <param name="list">The list.</param>
|
||||||
|
/// <param name="date">The date.</param>
|
||||||
|
/// <returns>Whether it is valid.</returns>
|
||||||
|
public static bool IsValid(PriceList list, DateOnly date)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(list);
|
||||||
|
return !list.Disabled && (list.ValidFrom is null || list.ValidFrom <= date) && (list.ValidTo is null || list.ValidTo >= date);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The price of an item in a list at a date, derived from the base list when the list has none.</summary>
|
||||||
|
/// <param name="itemId">The item.</param>
|
||||||
|
/// <param name="listId">The list.</param>
|
||||||
|
/// <param name="date">The date.</param>
|
||||||
|
/// <returns>The price.</returns>
|
||||||
|
public PriceCell ListPrice(long itemId, long listId, DateOnly date) => ListPrice(itemId, listId, date, 0);
|
||||||
|
|
||||||
|
/// <summary>The price written in a list for an item at a date, without derivation.</summary>
|
||||||
|
/// <param name="itemId">The item.</param>
|
||||||
|
/// <param name="listId">The list.</param>
|
||||||
|
/// <param name="date">The date.</param>
|
||||||
|
/// <returns>The row, or none.</returns>
|
||||||
|
public ItemPrice? OwnPrice(long itemId, long listId, DateOnly date) => At(_listPrices[(itemId, listId)], date);
|
||||||
|
|
||||||
|
/// <summary>The net price of a party for an item at a date.</summary>
|
||||||
|
/// <param name="itemId">The item.</param>
|
||||||
|
/// <param name="partyId">The party.</param>
|
||||||
|
/// <param name="date">The date.</param>
|
||||||
|
/// <returns>The row, or none.</returns>
|
||||||
|
public ItemPrice? NetPrice(long itemId, long partyId, DateOnly date) => At(_netPrices[(itemId, partyId)], date);
|
||||||
|
|
||||||
|
/// <summary>The price proposed for an item (SPEC §11.3): net of the party, list, base list, item.</summary>
|
||||||
|
/// <param name="item">The item.</param>
|
||||||
|
/// <param name="partyId">The party of the document.</param>
|
||||||
|
/// <param name="priceListId">The price list of the party or of the document.</param>
|
||||||
|
/// <param name="date">The date of the document.</param>
|
||||||
|
/// <returns>The price and its source.</returns>
|
||||||
|
public PriceQuote Quote(Item item, long? partyId, long? priceListId, DateOnly date)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(item);
|
||||||
|
if (partyId is { } party && NetPrice(item.Id, party, date) is { } net)
|
||||||
|
{
|
||||||
|
return new PriceQuote(net.Price, PriceSource.PartyNet, null, false, net.ValidFrom);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (priceListId is { } listId && _lists.TryGetValue(listId, out var list) && IsValid(list, date)
|
||||||
|
&& ListPrice(item.Id, listId, date) is { Price: { } listPrice } cell)
|
||||||
|
{
|
||||||
|
return new PriceQuote(listPrice, PriceSource.PartyPriceList, listId, list.VatIncluded, cell.ValidFrom);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Base is { } baseList && baseList.Id != priceListId && IsValid(baseList, date)
|
||||||
|
&& ListPrice(item.Id, baseList.Id, date) is { Price: { } basePrice } baseCell)
|
||||||
|
{
|
||||||
|
return new PriceQuote(basePrice, PriceSource.BasePriceList, baseList.Id, baseList.VatIncluded, baseCell.ValidFrom);
|
||||||
|
}
|
||||||
|
|
||||||
|
return item.Price is { } own ? new PriceQuote(own, PriceSource.Item, null, false, null) : PriceQuote.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The discounts of the party on a price (SPEC §11.3): none on a net price, else the two of the sales terms.</summary>
|
||||||
|
/// <param name="price">The price proposed.</param>
|
||||||
|
/// <param name="terms">The sales terms of the party.</param>
|
||||||
|
/// <returns>The discounts.</returns>
|
||||||
|
public static DiscountQuote Discounts(PriceQuote price, PartySalesTerms? terms)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(price);
|
||||||
|
if (price.Source == PriceSource.PartyNet || terms is null)
|
||||||
|
{
|
||||||
|
return DiscountQuote.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
decimal[] steps = [.. new[] { terms.Discount1, terms.Discount2 }.Where(d => d is > 0).Select(d => d!.Value)];
|
||||||
|
return steps.Length == 0 ? DiscountQuote.None : new DiscountQuote(DiscountFormula.Format(steps), DiscountFormula.Equivalent(steps));
|
||||||
|
}
|
||||||
|
|
||||||
|
private PriceCell ListPrice(long itemId, long listId, DateOnly date, int depth)
|
||||||
|
{
|
||||||
|
if (depth > MaxDepth || !_lists.TryGetValue(listId, out var list))
|
||||||
|
{
|
||||||
|
return PriceCell.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (OwnPrice(itemId, listId, date) is { } own)
|
||||||
|
{
|
||||||
|
return new PriceCell(own.Price, false, own.ValidFrom);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (list.BasePriceListId is { } parent && ListPrice(itemId, parent, date, depth + 1) is { Price: { } basePrice } from)
|
||||||
|
{
|
||||||
|
return new PriceCell(PriceRounding.Round(PriceRounding.Change(basePrice, list.MarkupPercent), list.RoundingStep), true, from.ValidFrom);
|
||||||
|
}
|
||||||
|
|
||||||
|
return PriceCell.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
using Khaemhat.Application.Audit;
|
||||||
|
using Khaemhat.Application.Querying;
|
||||||
|
using Khaemhat.Application.Security;
|
||||||
|
using Khaemhat.Application.Tables;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Core.Parties;
|
||||||
|
using Khaemhat.Core.Tables;
|
||||||
|
using Khaemhat.Data;
|
||||||
|
using Khaemhat.Data.Querying;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Items;
|
||||||
|
|
||||||
|
/// <summary>A column of the price grid: a price list.</summary>
|
||||||
|
/// <param name="Id">The list.</param>
|
||||||
|
/// <param name="Code">Its code.</param>
|
||||||
|
/// <param name="Description">Its description.</param>
|
||||||
|
/// <param name="IsBase">The base list.</param>
|
||||||
|
/// <param name="Derived">Derived from another list.</param>
|
||||||
|
/// <param name="VatIncluded">Prices with VAT.</param>
|
||||||
|
public sealed record PriceListColumn(long Id, string Code, string Description, bool IsBase, bool Derived, bool VatIncluded);
|
||||||
|
|
||||||
|
/// <summary>A row of the price grid: an item with its price in every list at the date.</summary>
|
||||||
|
/// <param name="ItemId">The item.</param>
|
||||||
|
/// <param name="Code">Its code.</param>
|
||||||
|
/// <param name="Description">Its description.</param>
|
||||||
|
/// <param name="UnitOfMeasureId">Its unit.</param>
|
||||||
|
/// <param name="AverageCost">Its average cost (standard when none), only for who sees costs.</param>
|
||||||
|
/// <param name="Prices">The prices by list.</param>
|
||||||
|
/// <param name="Net">The net price of the party chosen, if any.</param>
|
||||||
|
public sealed record PriceGridRow(
|
||||||
|
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal? AverageCost, IReadOnlyDictionary<long, PriceCell> Prices, PriceCell? Net);
|
||||||
|
|
||||||
|
/// <summary>The price grid (mockup 018).</summary>
|
||||||
|
/// <param name="Lists">The columns.</param>
|
||||||
|
/// <param name="Page">The rows.</param>
|
||||||
|
public sealed record PriceGrid(IReadOnlyList<PriceListColumn> Lists, ListPage<PriceGridRow> Page);
|
||||||
|
|
||||||
|
/// <summary>A price to write: of a list or net of a customer, valid from a day; no price removes the row of that day.</summary>
|
||||||
|
/// <param name="ItemId">The item.</param>
|
||||||
|
/// <param name="PriceListId">The list.</param>
|
||||||
|
/// <param name="PartyId">The customer.</param>
|
||||||
|
/// <param name="Price">The price, or none to remove it.</param>
|
||||||
|
/// <param name="ValidFrom">Valid from this day.</param>
|
||||||
|
public sealed record PriceEdit(long ItemId, long? PriceListId, long? PartyId, decimal? Price, DateOnly? ValidFrom);
|
||||||
|
|
||||||
|
/// <summary>A mass update of a price list (mockup 018): from the list itself or another one, a percent and a rounding.</summary>
|
||||||
|
public sealed record BulkUpdate
|
||||||
|
{
|
||||||
|
/// <summary>The list to update.</summary>
|
||||||
|
public long PriceListId { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The list the prices start from; none: the list itself.</summary>
|
||||||
|
public long? SourcePriceListId { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The change in percent, also negative.</summary>
|
||||||
|
public decimal Percent { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The rounding step, such as 0.10, 0.50 or 1.00; zero: cents.</summary>
|
||||||
|
public decimal RoundingStep { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Rounding up, down or to the nearest.</summary>
|
||||||
|
public RoundingDirection Direction { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The prices are read at this day and the new ones are valid from it.</summary>
|
||||||
|
public DateOnly Date { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Only the items of this category.</summary>
|
||||||
|
public long? CategoryId { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Only these items (the selection); none: all the active items with a price.</summary>
|
||||||
|
public IReadOnlyList<long>? ItemIds { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Price lists (mockup 018, ADR 0030): the grid of items by lists at a date with the net prices of a customer, mass
|
||||||
|
/// updates, the writing of prices with their validity, and the price and discounts proposed for a document line.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>Permissions <c>items.item.read</c> and <c>write</c>; costs and margins with <c>items.cost.read</c>.</remarks>
|
||||||
|
public sealed class PriceListService
|
||||||
|
{
|
||||||
|
/// <summary>Error: a price is negative.</summary>
|
||||||
|
public const string NotNegative = ItemService.NotNegative;
|
||||||
|
|
||||||
|
/// <summary>Error: the list of a mass update does not exist.</summary>
|
||||||
|
public const string ListUnknown = "items.price-list.unknown";
|
||||||
|
|
||||||
|
private readonly IUnitOfWorkFactory _factory;
|
||||||
|
private readonly PermissionService _permissions;
|
||||||
|
private readonly AuditTrail _audit;
|
||||||
|
private readonly ItemService _items;
|
||||||
|
|
||||||
|
/// <summary>Creates the service.</summary>
|
||||||
|
/// <param name="factory">The units of work.</param>
|
||||||
|
/// <param name="permissions">The permissions.</param>
|
||||||
|
/// <param name="audit">The audit trail.</param>
|
||||||
|
/// <param name="items">The items (for the cost permission).</param>
|
||||||
|
public PriceListService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ItemService items)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(factory);
|
||||||
|
ArgumentNullException.ThrowIfNull(permissions);
|
||||||
|
ArgumentNullException.ThrowIfNull(audit);
|
||||||
|
ArgumentNullException.ThrowIfNull(items);
|
||||||
|
_factory = factory;
|
||||||
|
_permissions = permissions;
|
||||||
|
_audit = audit;
|
||||||
|
_items = items;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The active price lists: the base one first, then by code.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The lists.</returns>
|
||||||
|
public async Task<IReadOnlyList<PriceListColumn>> ListsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
return await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The price grid: a page of items (no text items) with the price of every list at a date.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="query">Search, filters (those of the items radar), sort, page.</param>
|
||||||
|
/// <param name="date">The day the prices are read at.</param>
|
||||||
|
/// <param name="partyId">The customer whose net prices are shown.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The grid.</returns>
|
||||||
|
public async Task<PriceGrid> GridAsync(Actor actor, string companyCode, ListQuery query, DateOnly date, long? partyId, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(query);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
var costs = await _items.CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
var columns = await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||||
|
var page = await uow.Repository<Item, long>().ListAsync(
|
||||||
|
ItemService.Fields.Apply(Query.For<Item>().Where(i => i.Kind != ItemKind.Text), query), cancellationToken).ConfigureAwait(false);
|
||||||
|
var book = await ItemService.BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||||
|
IReadOnlyList<PriceGridRow> rows =
|
||||||
|
[
|
||||||
|
.. page.Items.Select(i => new PriceGridRow(
|
||||||
|
i.Id, i.Code, i.Description, i.UnitOfMeasureId, costs ? i.AverageCost ?? i.StandardCost : null,
|
||||||
|
columns.ToDictionary(c => c.Id, c => book.ListPrice(i.Id, c.Id, date)),
|
||||||
|
partyId is { } party ? book.NetPrice(i.Id, party, date) is { } net ? new PriceCell(net.Price, false, net.ValidFrom) : PriceCell.Empty : null)),
|
||||||
|
];
|
||||||
|
return new PriceGrid(columns, new ListPage<PriceGridRow>(rows, page.TotalCount, new Dictionary<string, decimal>()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Computes a mass update without saving it: for every item with a price in the source list at the date, the new
|
||||||
|
/// price of the list, changed by the percent and rounded. The screen shows them highlighted until saved.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who asks.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="update">The update.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The prices to write; unchanged ones are left out.</returns>
|
||||||
|
/// <exception cref="ValidationFailedException">When the lists are unknown or the step negative.</exception>
|
||||||
|
public async Task<IReadOnlyList<PriceEdit>> PreviewAsync(Actor actor, string companyCode, BulkUpdate update, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(update);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
var lists = uow.Repository<PriceList, long>();
|
||||||
|
var source = update.SourcePriceListId ?? update.PriceListId;
|
||||||
|
if (await lists.GetAsync(update.PriceListId, cancellationToken).ConfigureAwait(false) is null || await lists.GetAsync(source, cancellationToken).ConfigureAwait(false) is null)
|
||||||
|
{
|
||||||
|
throw new ValidationFailedException([nameof(BulkUpdate.PriceListId) + ":" + ListUnknown]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (update.RoundingStep < 0)
|
||||||
|
{
|
||||||
|
throw new ValidationFailedException([nameof(BulkUpdate.RoundingStep) + ":" + TableCatalog.NumberRange]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var select = Query.For<Item>().Where(i => !i.Disabled && i.Kind != ItemKind.Text);
|
||||||
|
if (update.CategoryId is { } category)
|
||||||
|
{
|
||||||
|
select = select.Where(i => i.CategoryId == category);
|
||||||
|
}
|
||||||
|
|
||||||
|
var items = (await uow.Repository<Item, long>().ListAsync(select, cancellationToken).ConfigureAwait(false)).Items;
|
||||||
|
if (update.ItemIds is { } wanted)
|
||||||
|
{
|
||||||
|
var only = wanted.ToHashSet();
|
||||||
|
items = [.. items.Where(i => only.Contains(i.Id))];
|
||||||
|
}
|
||||||
|
|
||||||
|
var book = await ItemService.BookAsync(uow, [.. items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||||
|
var edits = new List<PriceEdit>();
|
||||||
|
foreach (var item in items.OrderBy(i => i.Code, StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
if (book.ListPrice(item.Id, source, update.Date).Price is not { } from)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var price = PriceRounding.Round(PriceRounding.Change(from, update.Percent), update.RoundingStep, update.Direction);
|
||||||
|
if (book.ListPrice(item.Id, update.PriceListId, update.Date).Price != price)
|
||||||
|
{
|
||||||
|
edits.Add(new PriceEdit(item.Id, update.PriceListId, null, price, update.Date));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return edits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes prices: a row of the same list or customer and day is changed (or removed when the price is none), else a
|
||||||
|
/// new row starts that day, so the prices before it stay for older documents. A price equal to the one in effect is
|
||||||
|
/// not written again. Every change goes in the history of the item.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who saves.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="edits">The prices.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>How many rows were written or removed.</returns>
|
||||||
|
/// <exception cref="ValidationFailedException">With the errors (<c>index:code</c>).</exception>
|
||||||
|
public async Task<int> SaveAsync(Actor actor, string companyCode, IReadOnlyList<PriceEdit> edits, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(edits);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var problems = new List<string>();
|
||||||
|
var parties = uow.Repository<Party, long>();
|
||||||
|
for (var i = 0; i < edits.Count; i++)
|
||||||
|
{
|
||||||
|
var edit = edits[i];
|
||||||
|
if ((edit.PriceListId is null) == (edit.PartyId is null))
|
||||||
|
{
|
||||||
|
problems.Add(i + ":" + ItemService.PriceTarget);
|
||||||
|
}
|
||||||
|
else if (edit.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
|
||||||
|
{
|
||||||
|
problems.Add(i + ":" + ItemService.PriceParty);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (edit.Price < 0)
|
||||||
|
{
|
||||||
|
problems.Add(i + ":" + NotNegative);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (problems.Count > 0)
|
||||||
|
{
|
||||||
|
throw new ValidationFailedException(problems);
|
||||||
|
}
|
||||||
|
|
||||||
|
var prices = uow.Repository<ItemPrice, long>();
|
||||||
|
var written = 0;
|
||||||
|
foreach (var group in edits.GroupBy(e => e.ItemId))
|
||||||
|
{
|
||||||
|
var itemId = group.Key;
|
||||||
|
var rows = (await prices.ListAsync(Query.For<ItemPrice>().Where(p => p.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items.ToList();
|
||||||
|
foreach (var edit in group)
|
||||||
|
{
|
||||||
|
var same = rows.Where(r => r.PriceListId == edit.PriceListId && r.PartyId == edit.PartyId).ToList();
|
||||||
|
var day = same.FirstOrDefault(r => r.ValidFrom == edit.ValidFrom);
|
||||||
|
if (edit.Price is not { } price)
|
||||||
|
{
|
||||||
|
if (day is not null)
|
||||||
|
{
|
||||||
|
await prices.DeleteAsync(day.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
await _audit.RecordAsync(uow, AuditAction.Delete, itemId, day, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||||
|
rows.Remove(day);
|
||||||
|
written++;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (day is not null)
|
||||||
|
{
|
||||||
|
if (day.Price != price)
|
||||||
|
{
|
||||||
|
var before = Copy(day);
|
||||||
|
day.Price = price;
|
||||||
|
await prices.UpdateAsync(day, cancellationToken).ConfigureAwait(false);
|
||||||
|
await _audit.RecordAsync(uow, AuditAction.Update, itemId, before, day, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||||
|
written++;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (edit.ValidFrom is { } from && PriceBook.At(same, from) is { } current && current.Price == price)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var row = new ItemPrice { ItemId = itemId, PriceListId = edit.PriceListId, PartyId = edit.PartyId, Price = price, ValidFrom = edit.ValidFrom };
|
||||||
|
row.Id = await prices.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||||
|
await _audit.RecordAsync<ItemPrice>(uow, AuditAction.Insert, itemId, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||||
|
rows.Add(row);
|
||||||
|
written++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The price and the discounts proposed for an item on a document (SPEC §11.3): net price of the party, then the
|
||||||
|
/// list given or the one of the party, then the base list, then the item; the discounts of the party unless net.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="actor">Who asks.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="itemId">The item.</param>
|
||||||
|
/// <param name="partyId">The party of the document.</param>
|
||||||
|
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
|
||||||
|
/// <param name="date">The date of the document.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The price and the discounts.</returns>
|
||||||
|
public async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
|
||||||
|
Actor actor, string companyCode, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
return await QuoteAsync(uow, itemId, partyId, priceListId, date, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The price and the discounts of a line, inside the unit of work of a document.</summary>
|
||||||
|
/// <param name="uow">The unit of work of the company.</param>
|
||||||
|
/// <param name="itemId">The item.</param>
|
||||||
|
/// <param name="partyId">The party of the document.</param>
|
||||||
|
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
|
||||||
|
/// <param name="date">The date of the document.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The price and the discounts.</returns>
|
||||||
|
public static async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
|
||||||
|
IUnitOfWork uow, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(uow);
|
||||||
|
var item = await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
|
||||||
|
var terms = partyId is { } party
|
||||||
|
? await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == party), cancellationToken).ConfigureAwait(false)
|
||||||
|
: null;
|
||||||
|
var book = await ItemService.BookAsync(uow, [itemId], cancellationToken).ConfigureAwait(false);
|
||||||
|
var price = book.Quote(item, partyId, priceListId ?? terms?.PriceListId, date);
|
||||||
|
return (price, PriceBook.Discounts(price, terms));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<IReadOnlyList<PriceListColumn>> ColumnsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>().Where(l => !l.Disabled), cancellationToken).ConfigureAwait(false)).Items;
|
||||||
|
var baseList = PriceBook.BaseOf(lists);
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. lists.OrderBy(l => l.Id == baseList?.Id ? 0 : 1).ThenBy(l => l.Code, StringComparer.Ordinal)
|
||||||
|
.Select(l => new PriceListColumn(l.Id, l.Code, l.Description, l.Id == baseList?.Id, l.BasePriceListId is not null, l.VatIncluded)),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ItemPrice Copy(ItemPrice price) => new()
|
||||||
|
{
|
||||||
|
Id = price.Id, ItemId = price.ItemId, PriceListId = price.PriceListId, PartyId = price.PartyId, Price = price.Price, ValidFrom = price.ValidFrom,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ using Khaemhat.Core.Instance;
|
|||||||
using Khaemhat.Application.Querying;
|
using Khaemhat.Application.Querying;
|
||||||
using Khaemhat.Application.Security;
|
using Khaemhat.Application.Security;
|
||||||
using Khaemhat.Application.Tables;
|
using Khaemhat.Application.Tables;
|
||||||
|
using Khaemhat.Application.Items;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
using Khaemhat.Core.Parties;
|
using Khaemhat.Core.Parties;
|
||||||
using Khaemhat.Core.Tables;
|
using Khaemhat.Core.Tables;
|
||||||
using Khaemhat.Core.Validation;
|
using Khaemhat.Core.Validation;
|
||||||
@@ -37,6 +39,9 @@ public sealed class PartyRecord
|
|||||||
|
|
||||||
/// <summary>The bank accounts.</summary>
|
/// <summary>The bank accounts.</summary>
|
||||||
public List<PartyBankAccount> BankAccounts { get; set; } = [];
|
public List<PartyBankAccount> BankAccounts { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>The codes the party uses for our items (tab <i>Articoli e codici</i>).</summary>
|
||||||
|
public List<PartyItemCode> ItemCodes { get; set; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Which parties a radar shows (menu <i>Anagrafiche</i>).</summary>
|
/// <summary>Which parties a radar shows (menu <i>Anagrafiche</i>).</summary>
|
||||||
@@ -538,6 +543,26 @@ public sealed class PartyService
|
|||||||
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
|
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The rows of some parties, for the lookups that show them by id.</summary>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="ids">The parties.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The rows found.</returns>
|
||||||
|
public async Task<IReadOnlyList<PartyRow>> RowsAsync(Actor actor, string companyCode, IEnumerable<long> ids, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(ids);
|
||||||
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||||
|
long[] wanted = [.. ids.Distinct()];
|
||||||
|
if (wanted.Length == 0)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||||
|
return [.. (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => wanted.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.Select(RowOf)];
|
||||||
|
}
|
||||||
|
|
||||||
private static PartyRow RowOf(Party p) =>
|
private static PartyRow RowOf(Party p) =>
|
||||||
new(p.Id, p.Code, p.Name, p.Kind, p.IsAlsoSupplier, p.SubjectType, p.VatNumber, p.TaxCode, p.City, p.Province, p.CountryCode, p.SalespersonId, p.CategoryId, p.Disabled);
|
new(p.Id, p.Code, p.Name, p.Kind, p.IsAlsoSupplier, p.SubjectType, p.VatNumber, p.TaxCode, p.City, p.Province, p.CountryCode, p.SalespersonId, p.CategoryId, p.Disabled);
|
||||||
|
|
||||||
@@ -563,6 +588,7 @@ public sealed class PartyService
|
|||||||
Addresses = [.. (await uow.Repository<PartyAddress, long>().ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
Addresses = [.. (await uow.Repository<PartyAddress, long>().ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
Contacts = [.. (await uow.Repository<PartyContact, long>().ListAsync(Query.For<PartyContact>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
Contacts = [.. (await uow.Repository<PartyContact, long>().ListAsync(Query.For<PartyContact>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
BankAccounts = [.. (await uow.Repository<PartyBankAccount, long>().ListAsync(Query.For<PartyBankAccount>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
BankAccounts = [.. (await uow.Repository<PartyBankAccount, long>().ListAsync(Query.For<PartyBankAccount>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
|
ItemCodes = [.. (await uow.Repository<PartyItemCode, long>().ListAsync(Query.For<PartyItemCode>().Where(a => a.PartyId == id).OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -588,6 +614,7 @@ public sealed class PartyService
|
|||||||
await ReplaceAsync(uow, record.Addresses, before?.Addresses ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
await ReplaceAsync(uow, record.Addresses, before?.Addresses ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||||
await ReplaceAsync(uow, record.Contacts, before?.Contacts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
await ReplaceAsync(uow, record.Contacts, before?.Contacts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||||
await ReplaceAsync(uow, record.BankAccounts, before?.BankAccounts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
await ReplaceAsync(uow, record.BankAccounts, before?.BankAccounts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ReplaceAsync(uow, record.ItemCodes, before?.ItemCodes ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -922,6 +949,8 @@ public sealed class PartyService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
problems.AddRange(ItemService.CheckPartyCodes(record.ItemCodes));
|
||||||
|
|
||||||
// One default per list: the first one marked wins.
|
// One default per list: the first one marked wins.
|
||||||
OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v);
|
OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v);
|
||||||
OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v);
|
OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v);
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
|
|||||||
cancellationToken).ConfigureAwait(false);
|
cancellationToken).ConfigureAwait(false);
|
||||||
await context.EnsureAsync("item_categories", [new ItemCategory { Code = "GEN", Description = "Generica" }], 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("party_categories", Coded<PartyCategory>(("GEN", "Generica")), cancellationToken).ConfigureAwait(false);
|
||||||
await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base" }], cancellationToken).ConfigureAwait(false);
|
await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base", IsBase = true }], cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
var year = context.Today.Year;
|
var year = context.Today.Year;
|
||||||
var numerators = new Dictionary<string, DocumentNumerator>(StringComparer.Ordinal);
|
var numerators = new Dictionary<string, DocumentNumerator>(StringComparer.Ordinal);
|
||||||
|
|||||||
@@ -0,0 +1,382 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Khaemhat.Application.Items;
|
||||||
|
using Khaemhat.Application.Modules;
|
||||||
|
using Khaemhat.Application.Tables;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Core.Parties;
|
||||||
|
using Khaemhat.Core.Tables;
|
||||||
|
using Khaemhat.Core.Validation;
|
||||||
|
using Khaemhat.Data;
|
||||||
|
using Khaemhat.Data.Querying;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Seeding;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The items of the demo company (SPEC §14, issue #42): 120 items of a plumbing and heating wholesaler in ten categories
|
||||||
|
/// (goods, services, expenses and description lines), two price lists derived from the base one (public with markup and
|
||||||
|
/// rounding, resellers with a discount), prices with an older row for the history, the net prices and the item codes of
|
||||||
|
/// a customer, usual suppliers, alternative units and codes, substitutes, demo costs. Names and brands are fictitious;
|
||||||
|
/// the bar codes use the prefix 200-299, reserved for internal use, with a valid check digit. Runs only on a company
|
||||||
|
/// without items; <c>seed --demo --scale N</c> repeats the catalogue N times. The rows are marked as demo.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="codes">The automatic code rules.</param>
|
||||||
|
public sealed class DemoItemsSeeder(CodeRuleService codes) : ISeeder
|
||||||
|
{
|
||||||
|
/// <summary>The items of one scale.</summary>
|
||||||
|
public const int ItemsPerScale = 120;
|
||||||
|
|
||||||
|
private static readonly string[] Sizes = ["1/2\"", "3/4\"", "1\"", "1 1/4\"", "1 1/2\"", "2\""];
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string ModuleCode => ModuleCodes.Core;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public SeedKind Kind => SeedKind.Demo;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public int Order => 20;
|
||||||
|
|
||||||
|
/// <summary>The catalogue of one scale, in order.</summary>
|
||||||
|
/// <returns>The items to create.</returns>
|
||||||
|
public static IReadOnlyList<DemoItem> Catalogue()
|
||||||
|
{
|
||||||
|
var items = new List<DemoItem>();
|
||||||
|
|
||||||
|
// Valves: ball valves with lever and butterfly handle, check valves, gate valves.
|
||||||
|
for (var i = 0; i < Sizes.Length; i++)
|
||||||
|
{
|
||||||
|
items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato leva", "PZ", 12.80m + (i * 9.6m), "Idrodemo", "84818081", 0.25m + (i * 0.2m)));
|
||||||
|
items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato farfalla", "PZ", 11.90m + (i * 9.1m), "Idrodemo", "84818081", 0.24m + (i * 0.2m)));
|
||||||
|
items.Add(Goods("VALV", "Valvola di ritegno " + Sizes[i] + " a molla", "PZ", 9.40m + (i * 6.2m), "Idrodemo", "84813091", 0.2m + (i * 0.15m)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
items.Add(Goods("VALV", "Saracinesca " + Sizes[i] + " ottone", "PZ", 14.50m + (i * 8.3m), "Idrodemo", "84818081", 0.4m + (i * 0.25m)));
|
||||||
|
}
|
||||||
|
|
||||||
|
items.Add(Goods("VALV", "Valvola miscelatrice termostatica 3/4\"", "PZ", 54m, "Idrodemo", "84818019", 0.7m));
|
||||||
|
items.Add(Goods("VALV", "Riduttore di pressione 1/2\" con manometro", "PZ", 39.50m, "Idrodemo", "84811019", 0.6m));
|
||||||
|
items.Add(Goods("VALV", "Filtro autopulente 3/4\"", "PZ", 68m, "Idrodemo", "84212100", 0.9m));
|
||||||
|
|
||||||
|
// Fittings: five shapes in four sizes.
|
||||||
|
foreach (var shape in new[] { "Manicotto", "Gomito 90 gradi", "Raccordo a T", "Nipplo", "Riduzione" })
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
items.Add(Goods("RACC", shape + " " + Sizes[i] + " ottone M/F", "PZ", 1.60m + (i * 1.35m) + (shape.Length / 10m), "Raccordemo", "74122000", 0.05m + (i * 0.04m)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pipes: copper bars, multilayer and polyethylene rolls.
|
||||||
|
foreach (var (diameter, price) in new[] { (12, 2.10m), (14, 2.45m), (15, 2.78m), (16, 3.05m), (18, 3.60m), (22, 4.85m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("TUBI", "Tubo rame " + diameter.ToString(CultureInfo.InvariantCulture) + "x1 barra 5 m", "M", price, "Ramedemo", "74111010", 0.4m));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (diameter, price) in new[] { (16, 1.15m), (20, 1.65m), (26, 2.70m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("TUBI", "Tubo multistrato " + diameter.ToString(CultureInfo.InvariantCulture) + "x2 rotolo 100 m", "M", price, "Plastidemo", "39172110", 0.15m));
|
||||||
|
items.Add(Goods("TUBI", "Tubo polietilene PE100 " + (diameter + 9).ToString(CultureInfo.InvariantCulture) + " mm rotolo 50 m", "M", price * 0.8m, "Plastidemo", "39172110", 0.2m));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Heating: boilers, radiators, thermostats, manifolds, expansion vessels.
|
||||||
|
foreach (var (kw, price) in new[] { (24, 1180m), (28, 1290m), (35, 1520m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("CALD", "Caldaia a condensazione " + kw.ToString(CultureInfo.InvariantCulture) + " kW", "PZ", price, "Termodemo", "84031090", 32m + kw));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (height, price) in new[] { (500, 9.20m), (600, 10.40m), (700, 11.60m), (800, 12.90m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("CALD", "Elemento radiatore alluminio interasse " + height.ToString(CultureInfo.InvariantCulture), "PZ", price, "Termodemo", "76169990", 1.2m));
|
||||||
|
}
|
||||||
|
|
||||||
|
items.Add(Goods("CALD", "Termostato ambiente digitale", "PZ", 48m, "Termodemo", "90321020", 0.3m));
|
||||||
|
items.Add(Goods("CALD", "Cronotermostato settimanale wifi", "PZ", 129m, "Termodemo", "90321020", 0.35m));
|
||||||
|
for (var ways = 2; ways <= 5; ways++)
|
||||||
|
{
|
||||||
|
items.Add(Goods("CALD", "Collettore " + ways.ToString(CultureInfo.InvariantCulture) + " vie con valvole", "PZ", 58m + (ways * 23m), "Idrodemo", "84818081", 0.6m * ways));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (liters, price) in new[] { (8, 32m), (18, 46m), (24, 58m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("CALD", "Vaso di espansione " + liters.ToString(CultureInfo.InvariantCulture) + " l", "PZ", price, "Termodemo", "73110099", liters / 4m));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Taps and sanitary.
|
||||||
|
foreach (var (name, price) in new[] { ("Miscelatore lavabo monocomando", 64m), ("Miscelatore bidet monocomando", 61m), ("Miscelatore doccia esterno", 72m), ("Miscelatore cucina canna alta", 89m), ("Sifone lavabo 1 1/4\"", 7.80m), ("Sifone lavello doppio", 14.50m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("SAN", name, "PZ", price, "Rubidemo", "84818011", 0.9m));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var length in new[] { 30, 40, 50 })
|
||||||
|
{
|
||||||
|
items.Add(Goods("SAN", "Flessibile inox 1/2\" F/F " + length.ToString(CultureInfo.InvariantCulture) + " cm", "PZ", 3.10m + (length / 20m), "Rubidemo", "83071000", 0.12m));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Consumables.
|
||||||
|
foreach (var (name, unit, price) in new[]
|
||||||
|
{
|
||||||
|
("Nastro PTFE 12 mm x 12 m", "PZ", 0.95m), ("Canapa pettinata 100 g", "PZ", 2.40m), ("Pasta sigillante 500 g", "PZ", 6.90m),
|
||||||
|
("Silicone sanitario trasparente 280 ml", "PZ", 5.20m), ("Kit guarnizioni assortite", "CF", 9.80m), ("Collare fissatubo 1/2\" con tassello", "CF", 12.40m),
|
||||||
|
("Tassello nylon 8 mm", "CF", 4.60m), ("Fascetta stringitubo 20-32", "CF", 7.30m), ("Saldatura stagno-rame 250 g", "PZ", 18.50m), ("Disossidante 125 ml", "PZ", 4.10m),
|
||||||
|
})
|
||||||
|
{
|
||||||
|
items.Add(Goods("CONS", name, unit, price, null, null, 0.2m));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pumps.
|
||||||
|
foreach (var (name, price) in new[] { ("Circolatore elettronico 25-40", 168m), ("Circolatore elettronico 25-60", 196m), ("Circolatore elettronico 25-80", 254m), ("Pompa sommersa 0,75 kW", 312m), ("Pompa sommersa 1,1 kW", 389m), ("Pompa sommersa 1,5 kW", 465m), ("Autoclave 24 l 0,8 kW", 278m), ("Autoclave 60 l 1,1 kW", 412m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("POMP", name, "PZ", price, "Pompdemo", "84137035", 4.5m));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tools.
|
||||||
|
foreach (var (name, price) in new[] { ("Chiave stringitubi 14\"", 24.50m), ("Tagliatubi rame 3-35 mm", 19.80m), ("Piegatubi a molla set", 15.40m), ("Svasatubi", 28.90m), ("Cannello a gas", 32m), ("Pinza regolabile 250 mm", 16.70m), ("Seghetto per metalli", 12.30m), ("Livella 60 cm", 14.90m) })
|
||||||
|
{
|
||||||
|
items.Add(Goods("UTEN", name, "PZ", price, "Utendemo", "82055980", 0.6m));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Services, expenses and description lines: never in stock.
|
||||||
|
items.Add(Other(ItemKind.Service, "SERV", "Manodopera idraulico", "ORE", 38m));
|
||||||
|
items.Add(Other(ItemKind.Service, "SERV", "Manodopera apprendista", "ORE", 26m));
|
||||||
|
items.Add(Other(ItemKind.Service, "SERV", "Uscita e diritto di chiamata", "SERV", 35m));
|
||||||
|
items.Add(Other(ItemKind.Service, "SERV", "Sopralluogo tecnico", "SERV", 60m));
|
||||||
|
items.Add(Other(ItemKind.Service, "SERV", "Manutenzione annuale caldaia", "SERV", 95m));
|
||||||
|
items.Add(Other(ItemKind.Service, "SERV", "Analisi fumi e libretto impianto", "SERV", 45m));
|
||||||
|
items.Add(Other(ItemKind.Service, "SERV", "Dichiarazione di conformità impianto", "SERV", 120m));
|
||||||
|
items.Add(Other(ItemKind.Expense, "SPESE", "Spese di trasporto", "SERV", 15m));
|
||||||
|
items.Add(Other(ItemKind.Expense, "SPESE", "Spese di imballo", "SERV", 5m));
|
||||||
|
items.Add(Other(ItemKind.Expense, "SPESE", "Smaltimento materiale rimosso", "SERV", 25m));
|
||||||
|
items.Add(Other(ItemKind.Text, "SERV", "Riga descrittiva", "NR", null));
|
||||||
|
items.Add(Other(ItemKind.Text, "SERV", "Materiale fornito dal cliente", "NR", null));
|
||||||
|
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
var uow = context.UnitOfWork;
|
||||||
|
if (await uow.Repository<Item, long>().CountAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false) > 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var categories = await context.EnsureAsync(
|
||||||
|
"item_categories",
|
||||||
|
[
|
||||||
|
new ItemCategory { Code = "VALV", Description = "Valvolame", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "RACC", Description = "Raccorderia", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "TUBI", Description = "Tubi", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "CALD", Description = "Caldaie e riscaldamento", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "SAN", Description = "Rubinetteria e sanitari", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "CONS", Description = "Materiale di consumo", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "POMP", Description = "Pompe e circolatori", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "UTEN", Description = "Utensili", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "SERV", Description = "Servizi e manodopera", IsDemo = true },
|
||||||
|
new ItemCategory { Code = "SPESE", Description = "Spese accessorie", IsDemo = true },
|
||||||
|
],
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
var lists = uow.Repository<PriceList, long>();
|
||||||
|
var allLists = (await lists.ListAsync(Query.For<PriceList>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||||
|
var baseList = PriceBook.BaseOf(allLists);
|
||||||
|
if (baseList is null)
|
||||||
|
{
|
||||||
|
baseList = new PriceList { Code = "BASE", Description = "Listino base", IsBase = true, IsDemo = true };
|
||||||
|
baseList.Id = await lists.InsertAsync(baseList, cancellationToken).ConfigureAwait(false);
|
||||||
|
context.Count("price_lists");
|
||||||
|
}
|
||||||
|
|
||||||
|
await context.EnsureAsync(
|
||||||
|
"price_lists",
|
||||||
|
[
|
||||||
|
new PriceList { Code = "PUBB", Description = "Pubblico", BasePriceListId = baseList.Id, MarkupPercent = 45m, RoundingStep = 0.10m, IsDemo = true },
|
||||||
|
new PriceList { Code = "RIV", Description = "Rivenditori", BasePriceListId = baseList.Id, MarkupPercent = -10m, RoundingStep = 0.01m, IsDemo = true },
|
||||||
|
],
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var units = (await uow.Repository<UnitOfMeasure, long>().ListAsync(Query.For<UnitOfMeasure>(), cancellationToken).ConfigureAwait(false)).Items
|
||||||
|
.ToDictionary(u => u.Code, u => u.Id, StringComparer.OrdinalIgnoreCase);
|
||||||
|
var tax = (await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "22"), cancellationToken).ConfigureAwait(false))?.Id;
|
||||||
|
var warehouse = (await uow.Repository<Warehouse, long>().FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault), cancellationToken).ConfigureAwait(false))?.Id;
|
||||||
|
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items
|
||||||
|
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
|
||||||
|
long? PartyOf(string name) => parties.TryGetValue(name, out var id) ? id : null;
|
||||||
|
var suppliers = new Dictionary<string, long?>(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["VALV"] = PartyOf("Metalli Nord S.p.A."), ["RACC"] = PartyOf("Metalli Nord S.p.A."), ["TUBI"] = PartyOf("Metalli Nord S.p.A."),
|
||||||
|
["SAN"] = PartyOf("Metalli Nord S.p.A."), ["CONS"] = PartyOf("Plastica Sud S.r.l."), ["CALD"] = PartyOf("Elektro Werke Süd GmbH"),
|
||||||
|
["POMP"] = PartyOf("Elektro Werke Süd GmbH"), ["UTEN"] = PartyOf("Plastica Sud S.r.l."),
|
||||||
|
};
|
||||||
|
var customer = PartyOf("Rossi Impianti S.r.l.");
|
||||||
|
|
||||||
|
var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false);
|
||||||
|
var items = uow.Repository<Item, long>();
|
||||||
|
var thisYear = new DateOnly(context.Today.Year, 1, 1);
|
||||||
|
var lastYear = thisYear.AddYears(-1);
|
||||||
|
var catalogue = Catalogue();
|
||||||
|
var created = new List<(DemoItem Seed, Item Item)>();
|
||||||
|
var ean = 0;
|
||||||
|
for (var round = 1; round <= Math.Max(1, context.Scale); round++)
|
||||||
|
{
|
||||||
|
foreach (var seed in catalogue)
|
||||||
|
{
|
||||||
|
var category = categories[seed.Category];
|
||||||
|
var cost = seed.Price is { } p && seed.Kind == ItemKind.Goods ? Math.Round(p * 0.58m, 2) : (decimal?)null;
|
||||||
|
var item = new Item
|
||||||
|
{
|
||||||
|
Kind = seed.Kind,
|
||||||
|
Description = round == 1 ? seed.Description : seed.Description + " (serie " + round.ToString(CultureInfo.InvariantCulture) + ")",
|
||||||
|
CategoryId = category.Id,
|
||||||
|
UnitOfMeasureId = units.TryGetValue(seed.Unit, out var unit) ? unit : null,
|
||||||
|
SalesTaxCodeId = tax,
|
||||||
|
PurchaseTaxCodeId = tax,
|
||||||
|
Barcode = seed.Kind == ItemKind.Goods ? Ean(++ean) : null,
|
||||||
|
CustomsCode = seed.CustomsCode,
|
||||||
|
Brand = seed.Brand,
|
||||||
|
Manufacturer = seed.Brand is null ? null : seed.Brand + " Industrie",
|
||||||
|
NetWeight = seed.Weight,
|
||||||
|
GrossWeight = seed.Weight is { } w ? Math.Round(w * 1.08m, 3) : null,
|
||||||
|
Stocked = seed.Kind == ItemKind.Goods,
|
||||||
|
WarehouseId = seed.Kind == ItemKind.Goods ? warehouse : null,
|
||||||
|
MinimumStock = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 5m : null,
|
||||||
|
ReorderPoint = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 10m : null,
|
||||||
|
ReorderLot = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 20m : null,
|
||||||
|
Price = seed.Kind is ItemKind.Service or ItemKind.Expense ? seed.Price : null,
|
||||||
|
StandardCost = cost,
|
||||||
|
AverageCost = cost,
|
||||||
|
LastCost = cost is { } c ? Math.Round(c * 1.02m, 2) : null,
|
||||||
|
IsDemo = true,
|
||||||
|
};
|
||||||
|
item.Code = await CodeRuleService.AssignAsync(
|
||||||
|
uow, rule, context.Today, category.Code,
|
||||||
|
async (code, ct) => await items.CountAsync(Query.For<Item>().Where(i => i.Code == code), ct).ConfigureAwait(false) > 0,
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
|
||||||
|
context.Count("items");
|
||||||
|
created.Add((seed, item));
|
||||||
|
|
||||||
|
if (seed.Kind == ItemKind.Goods && seed.Price is { } price)
|
||||||
|
{
|
||||||
|
// The price of this year, and the one of last year for the history.
|
||||||
|
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = price, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
|
||||||
|
await AddAsync(uow, context, "item_prices",
|
||||||
|
new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = PriceRounding.Round(price * 0.96m, 0.10m), ValidFrom = lastYear }, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (suppliers.GetValueOrDefault(seed.Category) is { } supplier)
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "item_suppliers", new ItemSupplier
|
||||||
|
{
|
||||||
|
ItemId = item.Id, PartyId = supplier, SupplierCode = "F-" + item.Code, Price = cost, LeadTimeDays = 7, MinimumQuantity = seed.Unit == "M" ? 50m : 1m, IsDefault = true,
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await DetailsAsync(uow, context, created, units, customer, baseList, thisYear, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task DetailsAsync(IUnitOfWork uow, SeedContext context, List<(DemoItem Seed, Item Item)> created, Dictionary<string, long> units,
|
||||||
|
long? customer, PriceList baseList, DateOnly thisYear, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
Item? Find(string description) => created.FirstOrDefault(c => c.Item.Description == description).Item;
|
||||||
|
|
||||||
|
// Copper bars are sold also by the bar of 5 m; small valves and fittings by the box of 10.
|
||||||
|
foreach (var (seed, item) in created.Where(c => c.Item.Description.StartsWith("Tubo rame", StringComparison.Ordinal)))
|
||||||
|
{
|
||||||
|
if (units.TryGetValue("PZ", out var bar))
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = bar, Factor = 5m }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (seed, item) in created.Where(c => c.Seed.Category is "VALV" or "RACC" && c.Seed.Unit == "PZ").Take(30))
|
||||||
|
{
|
||||||
|
if (units.TryGetValue("CT", out var box))
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = box, Factor = 10m, Barcode = Ean(500_000 + (int)item.Id) }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The codes of the old system, found by the search.
|
||||||
|
foreach (var (seed, item) in created.Where(c => c.Seed.Category == "VALV").Take(6))
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "item_barcodes", new ItemBarcode { ItemId = item.Id, Code = "OLD-" + item.Id.ToString("00000", CultureInfo.InvariantCulture), Description = "Codice del gestionale precedente" }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Substitutes: the butterfly valve for the lever one of the same size, the bigger boiler for the smaller one.
|
||||||
|
foreach (var size in Sizes)
|
||||||
|
{
|
||||||
|
if (Find("Valvola a sfera " + size + " ottone cromato leva") is { } lever && Find("Valvola a sfera " + size + " ottone cromato farfalla") is { } butterfly)
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = lever.Id, SubstituteId = butterfly.Id, Notes = "Stessa misura, maniglia a farfalla" }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Find("Caldaia a condensazione 24 kW") is { } small && Find("Caldaia a condensazione 28 kW") is { } big)
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = small.Id, SubstituteId = big.Id, Notes = "Potenza superiore, stessi attacchi" }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (customer is not { } rossi)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The usual customer has net prices on the valves and calls some items with its own codes.
|
||||||
|
var valves = created.Where(c => c.Seed.Category == "VALV" && c.Seed.Price is not null).Take(8).ToList();
|
||||||
|
for (var i = 0; i < valves.Count; i++)
|
||||||
|
{
|
||||||
|
var (seed, item) = valves[i];
|
||||||
|
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PartyId = rossi, Price = PriceRounding.Round(seed.Price!.Value * 0.95m, 0.05m), ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (i < 5)
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "party_item_codes",
|
||||||
|
new PartyItemCode { PartyId = rossi, ItemId = item.Id, Code = "RI-" + (100 + i).ToString(CultureInfo.InvariantCulture), Description = "Valvola " + (i + 1).ToString(CultureInfo.InvariantCulture) }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A price of the public list written by hand, over the derived one.
|
||||||
|
if (Find("Caldaia a condensazione 24 kW") is { } boiler
|
||||||
|
&& await uow.Repository<PriceList, long>().FindAsync(Query.For<PriceList>().Where(l => l.Code == "PUBB"), cancellationToken).ConfigureAwait(false) is { } publicList
|
||||||
|
&& publicList.BasePriceListId == baseList.Id)
|
||||||
|
{
|
||||||
|
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = boiler.Id, PriceListId = publicList.Id, Price = 1690m, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task AddAsync<T>(IUnitOfWork uow, SeedContext context, string table, T row, CancellationToken cancellationToken)
|
||||||
|
where T : class, Khaemhat.Core.Entities.IEntity<long>, new()
|
||||||
|
{
|
||||||
|
await uow.Repository<T, long>().InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||||
|
context.Count(table);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A fictitious EAN-13 with the prefix 200, for internal use, and a valid check digit.</summary>
|
||||||
|
/// <param name="number">The progressive number.</param>
|
||||||
|
/// <returns>The code.</returns>
|
||||||
|
public static string Ean(int number)
|
||||||
|
{
|
||||||
|
var digits = "200" + number.ToString("000000000", CultureInfo.InvariantCulture);
|
||||||
|
return digits + EanValidator.CheckDigit(digits).ToString(CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DemoItem Goods(string category, string description, string unit, decimal price, string? brand, string? customs, decimal? weight) =>
|
||||||
|
new(category, ItemKind.Goods, description, unit, Math.Round(price, 2), brand, customs, weight);
|
||||||
|
|
||||||
|
private static DemoItem Other(ItemKind kind, string category, string description, string unit, decimal? price) =>
|
||||||
|
new(category, kind, description, unit, price, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An item of the demo catalogue.</summary>
|
||||||
|
/// <param name="Category">The category code.</param>
|
||||||
|
/// <param name="Kind">What it is.</param>
|
||||||
|
/// <param name="Description">The description.</param>
|
||||||
|
/// <param name="Unit">The unit code.</param>
|
||||||
|
/// <param name="Price">The price of the base list (goods) or of the item (services and expenses).</param>
|
||||||
|
/// <param name="Brand">The fictitious brand.</param>
|
||||||
|
/// <param name="CustomsCode">The combined nomenclature.</param>
|
||||||
|
/// <param name="Weight">The net weight in kg.</param>
|
||||||
|
public sealed record DemoItem(string Category, ItemKind Kind, string Description, string Unit, decimal? Price, string? Brand, string? CustomsCode, decimal? Weight);
|
||||||
@@ -73,6 +73,9 @@ public sealed class SeedContext
|
|||||||
/// <summary>Today.</summary>
|
/// <summary>Today.</summary>
|
||||||
public DateOnly Today { get; }
|
public DateOnly Today { get; }
|
||||||
|
|
||||||
|
/// <summary>How many times the demo seeders repeat their catalogues (<c>seed --demo --scale N</c>), at least 1.</summary>
|
||||||
|
public int Scale { get; init; } = 1;
|
||||||
|
|
||||||
/// <summary>Rows added, by table.</summary>
|
/// <summary>Rows added, by table.</summary>
|
||||||
public IReadOnlyDictionary<string, int> Added => _added;
|
public IReadOnlyDictionary<string, int> Added => _added;
|
||||||
|
|
||||||
@@ -242,7 +245,16 @@ public sealed partial class SeedRunner : ICompanySeeder
|
|||||||
/// <param name="kind">Base or demo.</param>
|
/// <param name="kind">Base or demo.</param>
|
||||||
/// <param name="cancellationToken">Cancellation.</param>
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
/// <returns>What was added.</returns>
|
/// <returns>What was added.</returns>
|
||||||
public async Task<SeedReport> RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default)
|
public Task<SeedReport> RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default) =>
|
||||||
|
RunAsync(companyCode, kind, 1, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Runs every seeder of a kind on a company, the demo ones repeating their catalogues.</summary>
|
||||||
|
/// <param name="companyCode">The company.</param>
|
||||||
|
/// <param name="kind">Base or demo.</param>
|
||||||
|
/// <param name="scale">How many times the demo catalogues are repeated (<c>--scale</c>), at least 1.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>What was added.</returns>
|
||||||
|
public async Task<SeedReport> RunAsync(string companyCode, SeedKind kind, int scale, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var company = CompanyCodes.Normalize(companyCode);
|
var company = CompanyCodes.Normalize(companyCode);
|
||||||
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||||
@@ -251,7 +263,7 @@ public sealed partial class SeedRunner : ICompanySeeder
|
|||||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||||
context = new SeedContext(company, uow, pack, today);
|
context = new SeedContext(company, uow, pack, today) { Scale = Math.Max(1, scale) };
|
||||||
foreach (var seeder in _seeders.Where(s => s.Kind == kind))
|
foreach (var seeder in _seeders.Where(s => s.Kind == kind))
|
||||||
{
|
{
|
||||||
await seeder.RunAsync(context, cancellationToken).ConfigureAwait(false);
|
await seeder.RunAsync(context, cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
@@ -63,6 +63,9 @@ public sealed partial class TableCatalog
|
|||||||
/// <summary>Error: a transfer reason must not change quantities by itself.</summary>
|
/// <summary>Error: a transfer reason must not change quantities by itself.</summary>
|
||||||
public const string TransferEffect = "tables.inventory-reason.transfer";
|
public const string TransferEffect = "tables.inventory-reason.transfer";
|
||||||
|
|
||||||
|
/// <summary>Error: another price list is already the base one.</summary>
|
||||||
|
public const string BaseDuplicate = "tables.price-list.base-duplicate";
|
||||||
|
|
||||||
/// <summary>The maximum depth of item categories.</summary>
|
/// <summary>The maximum depth of item categories.</summary>
|
||||||
public const int MaxCategoryLevel = 3;
|
public const int MaxCategoryLevel = 3;
|
||||||
|
|
||||||
@@ -247,6 +250,12 @@ public sealed partial class TableCatalog
|
|||||||
{
|
{
|
||||||
c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
|
c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var id = x.Id;
|
||||||
|
if (x.IsBase && await c.CountAsync<PriceList>(p => p.IsBase && p.Id != id, ct).ConfigureAwait(false) > 0)
|
||||||
|
{
|
||||||
|
c.Error(nameof(PriceList.IsBase), BaseDuplicate);
|
||||||
|
}
|
||||||
}));
|
}));
|
||||||
Add(new TableDefinition<DiscountPolicy>("discount-policies", "discount_policies")
|
Add(new TableDefinition<DiscountPolicy>("discount-policies", "discount_policies")
|
||||||
.Field("formula", x => x.Formula)
|
.Field("formula", x => x.Formula)
|
||||||
|
|||||||
@@ -54,6 +54,15 @@ public sealed class TableRuleContext
|
|||||||
where TOther : class, IEntity<long>, new() =>
|
where TOther : class, IEntity<long>, new() =>
|
||||||
_unitOfWork.Repository<TOther, long>().GetAsync(id, cancellationToken);
|
_unitOfWork.Repository<TOther, long>().GetAsync(id, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Counts the rows of another table that match.</summary>
|
||||||
|
/// <typeparam name="TOther">The other table.</typeparam>
|
||||||
|
/// <param name="where">The condition.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>How many rows match.</returns>
|
||||||
|
public Task<int> CountAsync<TOther>(System.Linq.Expressions.Expression<Func<TOther, bool>> where, CancellationToken cancellationToken)
|
||||||
|
where TOther : class, IEntity<long>, new() =>
|
||||||
|
_unitOfWork.Repository<TOther, long>().CountAsync(Query.For<TOther>().Where(where), cancellationToken);
|
||||||
|
|
||||||
/// <summary>Whether a coded row with a code exists.</summary>
|
/// <summary>Whether a coded row with a code exists.</summary>
|
||||||
/// <typeparam name="TOther">The entity.</typeparam>
|
/// <typeparam name="TOther">The entity.</typeparam>
|
||||||
/// <param name="code">The code.</param>
|
/// <param name="code">The code.</param>
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
using Khaemhat.Core.Entities;
|
||||||
|
|
||||||
|
namespace Khaemhat.Core.Items;
|
||||||
|
|
||||||
|
/// <summary>What an item is (SPEC §11.2).</summary>
|
||||||
|
public enum ItemKind
|
||||||
|
{
|
||||||
|
/// <summary>Goods bought or sold; kept in stock when <see cref="Item.Stocked"/>.</summary>
|
||||||
|
Goods = 0,
|
||||||
|
|
||||||
|
/// <summary>A service, such as installation or hours of assistance.</summary>
|
||||||
|
Service = 1,
|
||||||
|
|
||||||
|
/// <summary>An ancillary expense on invoices (transport, collection).</summary>
|
||||||
|
Expense = 2,
|
||||||
|
|
||||||
|
/// <summary>A recurring descriptive line.</summary>
|
||||||
|
Text = 3,
|
||||||
|
|
||||||
|
/// <summary>A fixed asset (linked to the asset register with the ASSET module).</summary>
|
||||||
|
Asset = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Where the price proposed on a document line comes from (SPEC §11.3).</summary>
|
||||||
|
public enum PriceSource
|
||||||
|
{
|
||||||
|
/// <summary>No price found.</summary>
|
||||||
|
None = 0,
|
||||||
|
|
||||||
|
/// <summary>The net price agreed with the party for the item.</summary>
|
||||||
|
PartyNet = 1,
|
||||||
|
|
||||||
|
/// <summary>The price list of the party (or of the document).</summary>
|
||||||
|
PartyPriceList = 2,
|
||||||
|
|
||||||
|
/// <summary>The base price list of the company.</summary>
|
||||||
|
BasePriceList = 3,
|
||||||
|
|
||||||
|
/// <summary>The price written on the item.</summary>
|
||||||
|
Item = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An item (<c>items</c>, mockup 017).</summary>
|
||||||
|
public sealed class Item : Entity<long>, IDemoMarkable
|
||||||
|
{
|
||||||
|
/// <summary>The code, automatic (ADR 0027, mask <c>{categoria}-{seq:0000}</c>).</summary>
|
||||||
|
public string Code { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>What the item is.</summary>
|
||||||
|
public ItemKind Kind { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The description used on documents.</summary>
|
||||||
|
public string Description { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>A longer description.</summary>
|
||||||
|
public string? ExtendedDescription { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The category (<c>item_categories</c>).</summary>
|
||||||
|
public long? CategoryId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The base unit of measure (<c>units_of_measure</c>).</summary>
|
||||||
|
public long? UnitOfMeasureId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The VAT code of sales (<c>tax_codes</c>).</summary>
|
||||||
|
public long? SalesTaxCodeId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The VAT code of purchases (<c>tax_codes</c>).</summary>
|
||||||
|
public long? PurchaseTaxCodeId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The main bar code (EAN/GTIN).</summary>
|
||||||
|
public string? Barcode { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The combined nomenclature code (NC8, Intrastat).</summary>
|
||||||
|
public string? CustomsCode { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The manufacturer.</summary>
|
||||||
|
public string? Manufacturer { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The brand.</summary>
|
||||||
|
public string? Brand { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Net weight in kilograms.</summary>
|
||||||
|
public decimal? NetWeight { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Gross weight in kilograms.</summary>
|
||||||
|
public decimal? GrossWeight { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The item is kept in stock (movements, balances, reorder from M6).</summary>
|
||||||
|
public bool Stocked { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The usual warehouse (<c>warehouses</c>).</summary>
|
||||||
|
public long? WarehouseId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The minimum stock.</summary>
|
||||||
|
public decimal? MinimumStock { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The reorder point: below it the item is proposed for an order.</summary>
|
||||||
|
public decimal? ReorderPoint { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The reorder lot: orders are proposed in multiples of it.</summary>
|
||||||
|
public decimal? ReorderLot { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The price written on the item, the last fallback of the price search.</summary>
|
||||||
|
public decimal? Price { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The standard cost, set by hand.</summary>
|
||||||
|
public decimal? StandardCost { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The last purchase cost (updated by the receipts, M6).</summary>
|
||||||
|
public decimal? LastCost { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The weighted average cost (updated by the receipts, M6).</summary>
|
||||||
|
public decimal? AverageCost { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The revenue account (chart of accounts, M7).</summary>
|
||||||
|
public string? RevenueAccountCode { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The cost account (chart of accounts, M7).</summary>
|
||||||
|
public string? CostAccountCode { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Free notes.</summary>
|
||||||
|
public string? Notes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Disabled: no longer proposed in new documents.</summary>
|
||||||
|
public bool Disabled { get; set; }
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool IsDemo { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An alternative unit of measure of an item (<c>item_uoms</c>): a box of 10 pieces has factor 10.</summary>
|
||||||
|
public sealed class ItemUnit : Entity<long>
|
||||||
|
{
|
||||||
|
/// <summary>The item.</summary>
|
||||||
|
public long ItemId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The unit (<c>units_of_measure</c>).</summary>
|
||||||
|
public long UnitOfMeasureId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>How many base units one of this unit holds.</summary>
|
||||||
|
public decimal Factor { get; set; } = 1m;
|
||||||
|
|
||||||
|
/// <summary>The bar code of the package.</summary>
|
||||||
|
public string? Barcode { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An alternative code of an item (<c>item_barcodes</c>): another EAN or an internal code.</summary>
|
||||||
|
public sealed class ItemBarcode : Entity<long>
|
||||||
|
{
|
||||||
|
/// <summary>The item.</summary>
|
||||||
|
public long ItemId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The code.</summary>
|
||||||
|
public string Code { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>What the code is, such as <i>confezione</i> or <i>codice interno</i>.</summary>
|
||||||
|
public string? Description { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A price of an item (<c>item_prices</c>): in a price list, or net for a party. A price is valid from a date (none:
|
||||||
|
/// always); the price at a date is the one with the latest start not after it, so old prices stay for old documents.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ItemPrice : Entity<long>
|
||||||
|
{
|
||||||
|
/// <summary>The item.</summary>
|
||||||
|
public long ItemId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The price list (<c>price_lists</c>), or none for a net price of a party.</summary>
|
||||||
|
public long? PriceListId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The party of a net price (<c>parties</c>), or none for a price list.</summary>
|
||||||
|
public long? PartyId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The price.</summary>
|
||||||
|
public decimal Price { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The price is valid from this day (none: always).</summary>
|
||||||
|
public DateOnly? ValidFrom { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A supplier of an item (<c>item_suppliers</c>) with its code and price; one is the usual one.</summary>
|
||||||
|
public sealed class ItemSupplier : Entity<long>
|
||||||
|
{
|
||||||
|
/// <summary>The item.</summary>
|
||||||
|
public long ItemId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The supplier (<c>parties</c>).</summary>
|
||||||
|
public long PartyId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The code of the item at the supplier.</summary>
|
||||||
|
public string? SupplierCode { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The purchase price.</summary>
|
||||||
|
public decimal? Price { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The lead time in days.</summary>
|
||||||
|
public int? LeadTimeDays { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The minimum quantity of an order.</summary>
|
||||||
|
public decimal? MinimumQuantity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The usual supplier, used by the reorder proposal.</summary>
|
||||||
|
public bool IsDefault { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An equivalent item proposed when this one is missing (<c>item_substitutes</c>).</summary>
|
||||||
|
public sealed class ItemSubstitute : Entity<long>
|
||||||
|
{
|
||||||
|
/// <summary>The item.</summary>
|
||||||
|
public long ItemId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The substitute (<c>items</c>).</summary>
|
||||||
|
public long SubstituteId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Notes, such as the differences.</summary>
|
||||||
|
public string? Notes { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The code a customer or a supplier uses for one of our items (<c>party_item_codes</c>).</summary>
|
||||||
|
public sealed class PartyItemCode : Entity<long>
|
||||||
|
{
|
||||||
|
/// <summary>The party.</summary>
|
||||||
|
public long PartyId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The item.</summary>
|
||||||
|
public long ItemId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The code of the party.</summary>
|
||||||
|
public string Code { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The description of the party.</summary>
|
||||||
|
public string? Description { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
namespace Khaemhat.Core.Items;
|
||||||
|
|
||||||
|
/// <summary>How a price is rounded to a step.</summary>
|
||||||
|
public enum RoundingDirection
|
||||||
|
{
|
||||||
|
/// <summary>To the nearest step, halves away from zero.</summary>
|
||||||
|
Nearest = 0,
|
||||||
|
|
||||||
|
/// <summary>Up to the next step (per eccesso).</summary>
|
||||||
|
Up = 1,
|
||||||
|
|
||||||
|
/// <summary>Down to the previous step (per difetto).</summary>
|
||||||
|
Down = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The arithmetic of prices: percent changes and rounding to a step such as 0,10, 0,50 or 1,00.</summary>
|
||||||
|
public static class PriceRounding
|
||||||
|
{
|
||||||
|
/// <summary>Rounds a price to a step; with no step, to the cent.</summary>
|
||||||
|
/// <param name="value">The price.</param>
|
||||||
|
/// <param name="step">The step, such as 0.10; zero or less means cents.</param>
|
||||||
|
/// <param name="direction">Nearest, up or down.</param>
|
||||||
|
/// <returns>The rounded price.</returns>
|
||||||
|
public static decimal Round(decimal value, decimal step, RoundingDirection direction = RoundingDirection.Nearest)
|
||||||
|
{
|
||||||
|
if (step <= 0)
|
||||||
|
{
|
||||||
|
step = 0.01m;
|
||||||
|
}
|
||||||
|
|
||||||
|
var units = value / step;
|
||||||
|
units = direction switch
|
||||||
|
{
|
||||||
|
RoundingDirection.Up => decimal.Ceiling(Math.Round(units, 10)),
|
||||||
|
RoundingDirection.Down => decimal.Floor(Math.Round(units, 10)),
|
||||||
|
_ => Math.Round(units, MidpointRounding.AwayFromZero),
|
||||||
|
};
|
||||||
|
return Normalize(units * step);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Applies a percent change: +10 adds a tenth, -5 takes off a twentieth.</summary>
|
||||||
|
/// <param name="value">The price.</param>
|
||||||
|
/// <param name="percent">The change in percent.</param>
|
||||||
|
/// <returns>The changed price, not rounded.</returns>
|
||||||
|
public static decimal Change(decimal value, decimal percent) => value * (1m + (percent / 100m));
|
||||||
|
|
||||||
|
/// <summary>The margin of a price over a cost, in percent of the price.</summary>
|
||||||
|
/// <param name="price">The price.</param>
|
||||||
|
/// <param name="cost">The cost.</param>
|
||||||
|
/// <returns>The margin, or none without a positive price or a cost.</returns>
|
||||||
|
public static decimal? Margin(decimal? price, decimal? cost) =>
|
||||||
|
price is > 0 && cost is { } c ? Math.Round((price.Value - c) / price.Value * 100m, 1, MidpointRounding.AwayFromZero) : null;
|
||||||
|
|
||||||
|
// Four decimals at most, and two when the rest are zeros (12.3000 becomes 12.30).
|
||||||
|
private static decimal Normalize(decimal value)
|
||||||
|
{
|
||||||
|
var rounded = Math.Round(value, 4, MidpointRounding.AwayFromZero);
|
||||||
|
return rounded == Math.Round(rounded, 2) ? Math.Round(rounded, 2) : rounded;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -342,6 +342,9 @@ public sealed class PriceList : CodedEntity
|
|||||||
|
|
||||||
/// <summary>Rounding step of derived prices, such as 0.05; zero for none.</summary>
|
/// <summary>Rounding step of derived prices, such as 0.05; zero for none.</summary>
|
||||||
public decimal RoundingStep { get; set; }
|
public decimal RoundingStep { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The base price list of the company: the third step of the price search (SPEC §11.3, ADR 0030).</summary>
|
||||||
|
public bool IsBase { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>A discount policy: a chain of discounts such as <c>10+5</c>.</summary>
|
/// <summary>A discount policy: a chain of discounts such as <c>10+5</c>.</summary>
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Data.Mapping;
|
||||||
|
|
||||||
|
namespace Khaemhat.Data.CompanyDatabase;
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="Item"/> to <c>items</c>.</summary>
|
||||||
|
public sealed class ItemMap : EntityMap<Item>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
public ItemMap()
|
||||||
|
{
|
||||||
|
ToTable("items");
|
||||||
|
Map(x => x.Code).MaxLength(30);
|
||||||
|
Map(x => x.Description).MaxLength(200);
|
||||||
|
Map(x => x.Barcode).MaxLength(20);
|
||||||
|
Map(x => x.CustomsCode).MaxLength(10);
|
||||||
|
Map(x => x.Manufacturer).MaxLength(100);
|
||||||
|
Map(x => x.Brand).MaxLength(100);
|
||||||
|
Map(x => x.RevenueAccountCode).MaxLength(20);
|
||||||
|
Map(x => x.CostAccountCode).MaxLength(20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="ItemUnit"/> to <c>item_uoms</c>.</summary>
|
||||||
|
public sealed class ItemUnitMap : EntityMap<ItemUnit>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
public ItemUnitMap()
|
||||||
|
{
|
||||||
|
ToTable("item_uoms");
|
||||||
|
Map(x => x.Barcode).MaxLength(20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="ItemBarcode"/> to <c>item_barcodes</c>.</summary>
|
||||||
|
public sealed class ItemBarcodeMap : EntityMap<ItemBarcode>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
public ItemBarcodeMap()
|
||||||
|
{
|
||||||
|
ToTable("item_barcodes");
|
||||||
|
Map(x => x.Code).MaxLength(40);
|
||||||
|
Map(x => x.Description).MaxLength(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="ItemPrice"/> to <c>item_prices</c>.</summary>
|
||||||
|
public sealed class ItemPriceMap : EntityMap<ItemPrice>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
public ItemPriceMap() => ToTable("item_prices");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="ItemSupplier"/> to <c>item_suppliers</c>.</summary>
|
||||||
|
public sealed class ItemSupplierMap : EntityMap<ItemSupplier>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
public ItemSupplierMap()
|
||||||
|
{
|
||||||
|
ToTable("item_suppliers");
|
||||||
|
Map(x => x.SupplierCode).MaxLength(40);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="ItemSubstitute"/> to <c>item_substitutes</c>.</summary>
|
||||||
|
public sealed class ItemSubstituteMap : EntityMap<ItemSubstitute>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
public ItemSubstituteMap()
|
||||||
|
{
|
||||||
|
ToTable("item_substitutes");
|
||||||
|
Map(x => x.Notes).MaxLength(200);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Map of <see cref="PartyItemCode"/> to <c>party_item_codes</c>.</summary>
|
||||||
|
public sealed class PartyItemCodeMap : EntityMap<PartyItemCode>
|
||||||
|
{
|
||||||
|
/// <summary>Creates the map.</summary>
|
||||||
|
public PartyItemCodeMap()
|
||||||
|
{
|
||||||
|
ToTable("party_item_codes");
|
||||||
|
Map(x => x.Code).MaxLength(40);
|
||||||
|
Map(x => x.Description).MaxLength(200);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
using Khaemhat.Data.Migrations;
|
||||||
|
using Khaemhat.Data.Schema;
|
||||||
|
|
||||||
|
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Items and their details (SPEC §11.2, issue #42): alternative units and codes, prices of the price lists and net
|
||||||
|
/// prices of the parties, suppliers, substitutes, and the codes the parties use for our items. The details go with the
|
||||||
|
/// item; an item used as a substitute or a party with prices cannot be deleted.
|
||||||
|
/// </summary>
|
||||||
|
[Migration(20261112_002, "create_items")]
|
||||||
|
public sealed class M20261112_002_CreateItems : IMigration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Up(ISchemaBuilder schema)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(schema);
|
||||||
|
schema.AlterTable("price_lists", t => t.Bool("is_base").NotNull().Default(false));
|
||||||
|
schema.Sql(d => "UPDATE price_lists SET is_base = " + d.Literal(true, ColumnType.Bool) + " WHERE code = 'BASE'");
|
||||||
|
schema.CreateTable("items", t =>
|
||||||
|
{
|
||||||
|
t.Id();
|
||||||
|
t.String("code", 30).NotNull();
|
||||||
|
t.String("kind", 40).NotNull();
|
||||||
|
t.String("description", 200).NotNull();
|
||||||
|
t.Text("extended_description");
|
||||||
|
t.Int64("category_id");
|
||||||
|
t.Int64("unit_of_measure_id");
|
||||||
|
t.Int64("sales_tax_code_id");
|
||||||
|
t.Int64("purchase_tax_code_id");
|
||||||
|
t.String("barcode", 20);
|
||||||
|
t.String("customs_code", 10);
|
||||||
|
t.String("manufacturer", 100);
|
||||||
|
t.String("brand", 100);
|
||||||
|
t.Decimal("net_weight");
|
||||||
|
t.Decimal("gross_weight");
|
||||||
|
t.Bool("stocked").NotNull().Default(false);
|
||||||
|
t.Int64("warehouse_id");
|
||||||
|
t.Decimal("minimum_stock");
|
||||||
|
t.Decimal("reorder_point");
|
||||||
|
t.Decimal("reorder_lot");
|
||||||
|
t.Decimal("price");
|
||||||
|
t.Decimal("standard_cost");
|
||||||
|
t.Decimal("last_cost");
|
||||||
|
t.Decimal("average_cost");
|
||||||
|
t.String("revenue_account_code", 20);
|
||||||
|
t.String("cost_account_code", 20);
|
||||||
|
t.Text("notes");
|
||||||
|
t.Bool("disabled").NotNull().Default(false);
|
||||||
|
t.DemoColumn();
|
||||||
|
t.AuditColumns();
|
||||||
|
t.Unique("ux_items_code", "code");
|
||||||
|
t.Index("ix_items_description", "description");
|
||||||
|
t.Index("ix_items_barcode", "barcode");
|
||||||
|
t.Index("ix_items_category", "category_id");
|
||||||
|
t.ForeignKey("fk_items_category", "category_id", "item_categories", ReferentialAction.Restrict);
|
||||||
|
t.ForeignKey("fk_items_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict);
|
||||||
|
t.ForeignKey("fk_items_sales_tax_code", "sales_tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||||
|
t.ForeignKey("fk_items_purchase_tax_code", "purchase_tax_code_id", "tax_codes", ReferentialAction.Restrict);
|
||||||
|
t.ForeignKey("fk_items_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
schema.CreateTable("item_uoms", t =>
|
||||||
|
{
|
||||||
|
t.Id();
|
||||||
|
t.Int64("item_id").NotNull();
|
||||||
|
t.Int64("unit_of_measure_id").NotNull();
|
||||||
|
t.Decimal("factor").NotNull().Default(1m);
|
||||||
|
t.String("barcode", 20);
|
||||||
|
t.AuditColumns();
|
||||||
|
t.Unique("ux_item_uoms_item_unit", "item_id", "unit_of_measure_id");
|
||||||
|
t.ForeignKey("fk_item_uoms_item", "item_id", "items", ReferentialAction.Cascade);
|
||||||
|
t.ForeignKey("fk_item_uoms_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
schema.CreateTable("item_barcodes", t =>
|
||||||
|
{
|
||||||
|
t.Id();
|
||||||
|
t.Int64("item_id").NotNull();
|
||||||
|
t.String("code", 40).NotNull();
|
||||||
|
t.String("description", 100);
|
||||||
|
t.AuditColumns();
|
||||||
|
t.Index("ix_item_barcodes_code", "code");
|
||||||
|
t.ForeignKey("fk_item_barcodes_item", "item_id", "items", ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
schema.CreateTable("item_prices", t =>
|
||||||
|
{
|
||||||
|
t.Id();
|
||||||
|
t.Int64("item_id").NotNull();
|
||||||
|
t.Int64("price_list_id");
|
||||||
|
t.Int64("party_id");
|
||||||
|
t.Decimal("price").NotNull();
|
||||||
|
t.Date("valid_from");
|
||||||
|
t.AuditColumns();
|
||||||
|
t.Index("ix_item_prices_item", "item_id");
|
||||||
|
t.Index("ix_item_prices_price_list", "price_list_id");
|
||||||
|
t.Index("ix_item_prices_party", "party_id");
|
||||||
|
t.ForeignKey("fk_item_prices_item", "item_id", "items", ReferentialAction.Cascade);
|
||||||
|
t.ForeignKey("fk_item_prices_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict);
|
||||||
|
t.ForeignKey("fk_item_prices_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
schema.CreateTable("item_suppliers", t =>
|
||||||
|
{
|
||||||
|
t.Id();
|
||||||
|
t.Int64("item_id").NotNull();
|
||||||
|
t.Int64("party_id").NotNull();
|
||||||
|
t.String("supplier_code", 40);
|
||||||
|
t.Decimal("price");
|
||||||
|
t.Int32("lead_time_days");
|
||||||
|
t.Decimal("minimum_quantity");
|
||||||
|
t.Bool("is_default").NotNull().Default(false);
|
||||||
|
t.AuditColumns();
|
||||||
|
t.Unique("ux_item_suppliers_item_party", "item_id", "party_id");
|
||||||
|
t.ForeignKey("fk_item_suppliers_item", "item_id", "items", ReferentialAction.Cascade);
|
||||||
|
t.ForeignKey("fk_item_suppliers_party", "party_id", "parties", ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
schema.CreateTable("item_substitutes", t =>
|
||||||
|
{
|
||||||
|
t.Id();
|
||||||
|
t.Int64("item_id").NotNull();
|
||||||
|
t.Int64("substitute_id").NotNull();
|
||||||
|
t.String("notes", 200);
|
||||||
|
t.AuditColumns();
|
||||||
|
t.Unique("ux_item_substitutes_pair", "item_id", "substitute_id");
|
||||||
|
t.ForeignKey("fk_item_substitutes_item", "item_id", "items", ReferentialAction.Cascade);
|
||||||
|
t.ForeignKey("fk_item_substitutes_substitute", "substitute_id", "items", ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
schema.CreateTable("party_item_codes", t =>
|
||||||
|
{
|
||||||
|
t.Id();
|
||||||
|
t.Int64("party_id").NotNull();
|
||||||
|
t.Int64("item_id").NotNull();
|
||||||
|
t.String("code", 40).NotNull();
|
||||||
|
t.String("description", 200);
|
||||||
|
t.AuditColumns();
|
||||||
|
t.Unique("ux_party_item_codes_party_code", "party_id", "code");
|
||||||
|
t.Index("ix_party_item_codes_item", "item_id");
|
||||||
|
t.ForeignKey("fk_party_item_codes_party", "party_id", "parties", ReferentialAction.Cascade);
|
||||||
|
t.ForeignKey("fk_party_item_codes_item", "item_id", "items", ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
@page "/anagrafiche/categorie"
|
||||||
|
@attribute [Authorize]
|
||||||
|
@using Khaemhat.Web.Items
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
@* The menu entry Anagrafiche > Categorie: the item categories are a company table, kept with the others. *@
|
||||||
|
@code {
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void OnInitialized() => Navigation.NavigateTo(ItemScreens.CategoriesUrl, new NavigationOptions { ReplaceHistoryEntry = true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,782 @@
|
|||||||
|
@page "/anagrafiche/articoli/nuovo"
|
||||||
|
@page "/anagrafiche/articoli/{Id:long}"
|
||||||
|
@attribute [Authorize]
|
||||||
|
@inherits MasterDataPage<ItemRecord>
|
||||||
|
@using Khaemhat.Application.Audit
|
||||||
|
@using Khaemhat.Application.Items
|
||||||
|
@using Khaemhat.Application.Parties
|
||||||
|
@using Khaemhat.Application.Security
|
||||||
|
@using Khaemhat.Application.Tables
|
||||||
|
@using Khaemhat.Core.Common
|
||||||
|
@using Khaemhat.Core.Items
|
||||||
|
@using Khaemhat.Web.Items
|
||||||
|
@using Khaemhat.Web.Parties
|
||||||
|
@using Khaemhat.Web.Components.Pages.Parties
|
||||||
|
@using Khaemhat.Web.Tables
|
||||||
|
@inject ShellSession Session
|
||||||
|
@inject ItemService Items
|
||||||
|
@inject PriceListService PriceLists
|
||||||
|
@inject PartyService Parties
|
||||||
|
@inject TableService Tables
|
||||||
|
@inject AttachmentService Attachments
|
||||||
|
|
||||||
|
@* The record of an item (SPEC §11.2, mockup 017): header with code, description and the base price today, tabs for
|
||||||
|
main data, alternative units, alternative codes, prices of the lists and net prices of the customers, suppliers,
|
||||||
|
substitutes, notes with attachments, history. Stock and movements per warehouse arrive with the warehouse (M6). The
|
||||||
|
checks are those of ItemService: errors stop the save and open the tab of the first one, warnings show after saving. *@
|
||||||
|
<KhPageTitle Text="@PageTitle" Icon="box" />
|
||||||
|
|
||||||
|
@if (!_loaded)
|
||||||
|
{
|
||||||
|
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||||
|
}
|
||||||
|
else if (Session.Company is null)
|
||||||
|
{
|
||||||
|
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Items.NoCompany"]</h1></div>
|
||||||
|
}
|
||||||
|
else if (!Session.Permissions.Allows(ItemService.ReadPermission))
|
||||||
|
{
|
||||||
|
<div class="kh-message">
|
||||||
|
<KhIcon Name="lock" Class="lg" />
|
||||||
|
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||||
|
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (Record is null)
|
||||||
|
{
|
||||||
|
<div class="kh-message">
|
||||||
|
<KhIcon Name="alert" Class="lg" />
|
||||||
|
<h1>@T["Items.NotFound"]</h1>
|
||||||
|
<a class="btn" href="@ItemScreens.RadarUrl">@T["Items.Title"]</a>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<KhRecordLayout Page="this">
|
||||||
|
<Heading>
|
||||||
|
<KhDocHead KindIcon="box" KindLabel="@T["Items.Kinds." + I.Kind]" Number="@(I.Code.Length > 0 ? I.Code : T["Items.CodeAuto"])"
|
||||||
|
PartyName="@(I.Description.Length > 0 ? I.Description : T["Items.NewTitle"])" PartyLines="HeadLines"
|
||||||
|
TotalLabel="@BaseLabel" TotalValue="@(BasePrice is { } price ? T.Money(price) : null)" SubValues="HeadStats">
|
||||||
|
<State>
|
||||||
|
@if (I.Disabled)
|
||||||
|
{
|
||||||
|
<KhBadge Tone="KhTone.Neutral">@T["Items.States.Disabled"]</KhBadge>
|
||||||
|
}
|
||||||
|
else if (!IsNew)
|
||||||
|
{
|
||||||
|
<KhBadge Tone="KhTone.Ok">@T["Items.States.Active"]</KhBadge>
|
||||||
|
}
|
||||||
|
@if (!I.Stocked)
|
||||||
|
{
|
||||||
|
<KhBadge Tone="KhTone.Info">@T["Items.States.NotStocked"]</KhBadge>
|
||||||
|
}
|
||||||
|
@if (I.IsDemo)
|
||||||
|
{
|
||||||
|
<KhBadge Tone="KhTone.Info">@T["Items.States.Demo"]</KhBadge>
|
||||||
|
}
|
||||||
|
@if (IsModified)
|
||||||
|
{
|
||||||
|
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
|
||||||
|
}
|
||||||
|
</State>
|
||||||
|
<Chips>
|
||||||
|
@if (PartyScreens.Describe(_lookups.Categories, I.CategoryId, full: true) is { } category)
|
||||||
|
{
|
||||||
|
<KhChip Icon="folder" Text="@T["Items.Fields.CategoryId"]" Value="@category" />
|
||||||
|
}
|
||||||
|
@if (PartyScreens.Describe(_lookups.Units, I.UnitOfMeasureId) is { } unit)
|
||||||
|
{
|
||||||
|
<KhChip Icon="layers" Text="@T["Items.Fields.UnitOfMeasureId"]" Value="@unit" />
|
||||||
|
}
|
||||||
|
@if (PartyScreens.Describe(_lookups.TaxCodes, I.SalesTaxCodeId) is { } tax)
|
||||||
|
{
|
||||||
|
<KhChip Icon="euro" Text="@T["Items.Fields.SalesTaxCodeId"]" Value="@tax" />
|
||||||
|
}
|
||||||
|
@if (Record.Suppliers.FirstOrDefault(s => s.IsDefault) is { } supplier && _parties.TryGetValue(supplier.PartyId, out var party))
|
||||||
|
{
|
||||||
|
<KhChip Icon="truck" Text="@T["Items.Fields.Supplier"]" Value="@party.Name" />
|
||||||
|
}
|
||||||
|
</Chips>
|
||||||
|
</KhDocHead>
|
||||||
|
</Heading>
|
||||||
|
<ChildContent>
|
||||||
|
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
|
||||||
|
@switch (ActiveTab)
|
||||||
|
{
|
||||||
|
case ItemScreens.Tabs.Main:
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.Identity"]" Icon="box">
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Code"]" Name="Code" Value="@I.Code" ValueChanged="v => Change(() => I.Code = v ?? string.Empty)" Mono="true"
|
||||||
|
Placeholder="@T["Items.CodeAuto"]" Span="4" MaxLength="30" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.Kind"]" Name="Kind" Options="KindChoices" Value="@I.Kind.ToString()" Span="4" ValueChanged="SetKind" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.CategoryId"]" Name="CategoryId" Options="_lookups.Categories" Empty="" Span="4"
|
||||||
|
Value="@PartyScreens.Text(I.CategoryId)" ValueChanged="v => Change(() => I.CategoryId = PartyScreens.Id(v))" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Description"]" Name="Description" Value="@I.Description" ValueChanged="v => Change(() => I.Description = v ?? string.Empty)"
|
||||||
|
Span="12" MaxLength="200" Required="true" />
|
||||||
|
<KhTextArea Label="@T["Items.Fields.ExtendedDescription"]" Name="ExtendedDescription" Value="@I.ExtendedDescription"
|
||||||
|
ValueChanged="v => Change(() => I.ExtendedDescription = v)" Span="12" Rows="3" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Brand"]" Name="Brand" Value="@I.Brand" ValueChanged="v => Change(() => I.Brand = v)" Span="6" MaxLength="100" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Manufacturer"]" Name="Manufacturer" Value="@I.Manufacturer" ValueChanged="v => Change(() => I.Manufacturer = v)" Span="6" MaxLength="100" />
|
||||||
|
<KhCheck Label="@T["Items.Fields.Disabled"]" Name="Disabled" Value="I.Disabled" ValueChanged="v => Change(() => I.Disabled = v)" Span="4" />
|
||||||
|
</KhFieldGroup>
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.Codes"]" Icon="key">
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.UnitOfMeasureId"]" Name="UnitOfMeasureId" Options="_lookups.Units" Empty="" Span="4"
|
||||||
|
Value="@PartyScreens.Text(I.UnitOfMeasureId)" ValueChanged="v => Change(() => I.UnitOfMeasureId = PartyScreens.Id(v))" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Barcode"]" Name="Barcode" Value="@I.Barcode" ValueChanged="v => Change(() => I.Barcode = v)" Mono="true" Span="4" MaxLength="20" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.CustomsCode"]" Name="CustomsCode" Value="@I.CustomsCode" ValueChanged="v => Change(() => I.CustomsCode = v)" Mono="true" Span="4" MaxLength="10" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.SalesTaxCodeId"]" Name="SalesTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="6"
|
||||||
|
Value="@PartyScreens.Text(I.SalesTaxCodeId)" ValueChanged="v => Change(() => I.SalesTaxCodeId = PartyScreens.Id(v))" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.PurchaseTaxCodeId"]" Name="PurchaseTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="6"
|
||||||
|
Value="@PartyScreens.Text(I.PurchaseTaxCodeId)" ValueChanged="v => Change(() => I.PurchaseTaxCodeId = PartyScreens.Id(v))" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.NetWeight"]" Name="NetWeight" Value="I.NetWeight" ValueChanged="v => Change(() => I.NetWeight = v)" Min="0" Decimals="3" Span="6" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.GrossWeight"]" Name="GrossWeight" Value="I.GrossWeight" ValueChanged="v => Change(() => I.GrossWeight = v)" Min="0" Decimals="3" Span="6" />
|
||||||
|
</KhFieldGroup>
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.Prices"]" Icon="euro">
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.ItemPrice"]" Name="Price" Value="I.Price" ValueChanged="v => Change(() => I.Price = v)" Min="0" Span="6"
|
||||||
|
Hint="@T["Items.Hints.ItemPrice"]" />
|
||||||
|
@if (_costs)
|
||||||
|
{
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.StandardCost"]" Name="StandardCost" Value="I.StandardCost" ValueChanged="v => Change(() => I.StandardCost = v)" Min="0" Span="6" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.LastCost"]" Name="LastCost" Value="I.LastCost" ReadOnly="true" Span="4" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.AverageCost"]" Name="AverageCost" Value="I.AverageCost" ReadOnly="true" Span="4" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Margin"]" Name="Margin" Value="@ItemScreens.MarginText(BasePrice, Cost, T.Culture)" ReadOnly="true" Span="4" />
|
||||||
|
<p class="muted sm c12">@T["Items.Hints.Costs"]</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="muted sm c6">@T["Items.Hints.CostsHidden"]</p>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.Stock"]" Icon="layers">
|
||||||
|
<KhCheck Label="@T["Items.Fields.Stocked"]" Name="Stocked" Value="I.Stocked" ValueChanged="v => Change(() => I.Stocked = v)" Span="6"
|
||||||
|
Disabled="@(I.Kind != ItemKind.Goods)" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.WarehouseId"]" Name="WarehouseId" Options="_lookups.Warehouses" Empty="" Span="6"
|
||||||
|
Value="@PartyScreens.Text(I.WarehouseId)" ValueChanged="v => Change(() => I.WarehouseId = PartyScreens.Id(v))" Disabled="@(!I.Stocked)" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.MinimumStock"]" Name="MinimumStock" Value="I.MinimumStock" ValueChanged="v => Change(() => I.MinimumStock = v)" Min="0" Decimals="3" Span="4" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.ReorderPoint"]" Name="ReorderPoint" Value="I.ReorderPoint" ValueChanged="v => Change(() => I.ReorderPoint = v)" Min="0" Decimals="3" Span="4" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.ReorderLot"]" Name="ReorderLot" Value="I.ReorderLot" ValueChanged="v => Change(() => I.ReorderLot = v)" Min="0" Decimals="3" Span="4" />
|
||||||
|
<p class="muted sm c12">@T[I.Kind == ItemKind.Goods ? "Items.Hints.Stock" : "Items.Hints.NotStocked"]</p>
|
||||||
|
</KhFieldGroup>
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.Accounts"]" Icon="book" Wide="true">
|
||||||
|
<KhTextBox Label="@T["Items.Fields.RevenueAccountCode"]" Name="RevenueAccountCode" Value="@I.RevenueAccountCode" ValueChanged="v => Change(() => I.RevenueAccountCode = v)"
|
||||||
|
Mono="true" Span="3" MaxLength="20" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.CostAccountCode"]" Name="CostAccountCode" Value="@I.CostAccountCode" ValueChanged="v => Change(() => I.CostAccountCode = v)"
|
||||||
|
Mono="true" Span="3" MaxLength="20" />
|
||||||
|
</KhFieldGroup>
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ItemScreens.Tabs.Units:
|
||||||
|
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Items.Hints.Units"]</p>
|
||||||
|
@for (var i = 0; i < Record.Units.Count; i++)
|
||||||
|
{
|
||||||
|
var index = i;
|
||||||
|
var u = Record.Units[i];
|
||||||
|
<KhFieldGroup Title="@(PartyScreens.Describe(_lookups.Units, u.UnitOfMeasureId, full: true) ?? T["Items.Actions.AddUnit"])" Icon="layers" Wide="true">
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.UnitOfMeasureId"]" Name="@Key("Units", index, "UnitOfMeasureId")" Options="_lookups.Units" Empty="" Span="4" Required="true"
|
||||||
|
Value="@PartyScreens.Text(u.UnitOfMeasureId is 0 ? null : u.UnitOfMeasureId)" ValueChanged="v => Change(() => u.UnitOfMeasureId = PartyScreens.Id(v) ?? 0)" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.Factor"]" Name="@Key("Units", index, "Factor")" Value="u.Factor" ValueChanged="v => Change(() => u.Factor = v ?? 0)" Min="0" Decimals="4" Span="3" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Barcode"]" Name="@Key("Units", index, "Barcode")" Value="@u.Barcode" ValueChanged="v => Change(() => u.Barcode = v)" Mono="true" Span="3" MaxLength="20" />
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c2 kh-endrow">
|
||||||
|
<button type="button" class="btn danger" @onclick="() => Remove(Record.Units, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
}
|
||||||
|
<DetailFooter Empty="@(Record.Units.Count == 0 ? T["Items.Empty.Units"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddUnit"]"
|
||||||
|
OnAdd="() => Add(Record.Units, new ItemUnit())" />
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ItemScreens.Tabs.Barcodes:
|
||||||
|
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Items.Hints.Barcodes"]</p>
|
||||||
|
@for (var i = 0; i < Record.Barcodes.Count; i++)
|
||||||
|
{
|
||||||
|
var index = i;
|
||||||
|
var b = Record.Barcodes[i];
|
||||||
|
<KhFieldGroup Title="@(b.Code.Length > 0 ? b.Code : T["Items.Actions.AddBarcode"])" Icon="key" Wide="true">
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Code"]" Name="@Key("Barcodes", index, "Code")" Value="@b.Code" ValueChanged="v => Change(() => b.Code = v ?? string.Empty)"
|
||||||
|
Mono="true" Span="4" Required="true" MaxLength="40" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Description"]" Name="@Key("Barcodes", index, "Description")" Value="@b.Description" ValueChanged="v => Change(() => b.Description = v)"
|
||||||
|
Span="6" MaxLength="100" />
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c2 kh-endrow">
|
||||||
|
<button type="button" class="btn danger" @onclick="() => Remove(Record.Barcodes, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
}
|
||||||
|
<DetailFooter Empty="@(Record.Barcodes.Count == 0 ? T["Items.Empty.Barcodes"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddBarcode"]"
|
||||||
|
OnAdd="() => Add(Record.Barcodes, new ItemBarcode())" />
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ItemScreens.Tabs.Prices:
|
||||||
|
@if (_today is { } today && !IsNew)
|
||||||
|
{
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.Today"]" Icon="tag" Wide="true">
|
||||||
|
<table class="kh-table c12">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>@T["Items.Fields.PriceListId"]</th>
|
||||||
|
<th class="num">@T["Items.Fields.Price"]</th>
|
||||||
|
<th>@T["Items.Fields.ValidFrom"]</th>
|
||||||
|
<th>@T["Items.Fields.Source"]</th>
|
||||||
|
@if (_costs)
|
||||||
|
{
|
||||||
|
<th class="num">@T["Items.Fields.Margin"]</th>
|
||||||
|
}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var list in _columns)
|
||||||
|
{
|
||||||
|
var cell = today.Prices.GetValueOrDefault(list.Id) ?? PriceCell.Empty;
|
||||||
|
<tr>
|
||||||
|
<td><span class="code">@list.Code</span> @list.Description</td>
|
||||||
|
<td class="num">@(cell.Price is { } p ? T.Money(p) : "-")</td>
|
||||||
|
<td>@(cell.ValidFrom is { } from ? T.Date(from) : null)</td>
|
||||||
|
<td class="muted sm">@(cell.Derived ? T["Items.Hints.Derived"] : null)</td>
|
||||||
|
@if (_costs)
|
||||||
|
{
|
||||||
|
<td class="num">@ItemScreens.MarginText(cell.Price, Cost, T.Culture)</td>
|
||||||
|
}
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</KhFieldGroup>
|
||||||
|
}
|
||||||
|
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Items.Hints.Prices"]</p>
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.ListPrices"]" Icon="tag" Wide="true">
|
||||||
|
@foreach (var index in PriceRows(net: false))
|
||||||
|
{
|
||||||
|
var p = Record.Prices[index];
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.PriceListId"]" Name="@Key("Prices", index, "PriceListId")" Options="_lookups.PriceLists" Empty="" Span="5" Required="true"
|
||||||
|
Value="@PartyScreens.Text(p.PriceListId is 0 ? null : p.PriceListId)" ValueChanged="v => Change(() => p.PriceListId = PartyScreens.Id(v) ?? 0)" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.Price"]" Name="@Key("Prices", index, "Price")" Value="p.Price" ValueChanged="v => Change(() => p.Price = v ?? 0)" Min="0" Span="3" />
|
||||||
|
<KhDateBox Label="@T["Items.Fields.ValidFrom"]" Name="@Key("Prices", index, "ValidFrom")" Value="p.ValidFrom" ValueChanged="v => Change(() => p.ValidFrom = v)" Span="2" />
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c2 kh-endrow">
|
||||||
|
<button type="button" class="btn danger" @onclick="() => Remove(Record.Prices, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (!Record.Prices.Any(p => p.PartyId is null))
|
||||||
|
{
|
||||||
|
<p class="muted sm c12">@T["Items.Empty.ListPrices"]</p>
|
||||||
|
}
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c12">
|
||||||
|
<button type="button" class="btn" @onclick="AddListPrice"><KhIcon Name="plus" /> @T["Items.Actions.AddPrice"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.NetPrices"]" Icon="users" Wide="true">
|
||||||
|
@foreach (var index in PriceRows(net: true))
|
||||||
|
{
|
||||||
|
var p = Record.Prices[index];
|
||||||
|
<KhHotlink TItem="PartyRow" Label="@T["Items.Fields.PartyId"]" Name="@Key("Prices", index, "PartyId")" Span="5" Required="true"
|
||||||
|
Value="PartyOf(p.PartyId)" ValueChanged="v => SetParty(v, id => p.PartyId = id ?? 0)"
|
||||||
|
Search="SearchCustomersAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenCustomer" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.Price"]" Name="@Key("Prices", index, "Price")" Value="p.Price" ValueChanged="v => Change(() => p.Price = v ?? 0)" Min="0" Span="3" />
|
||||||
|
<KhDateBox Label="@T["Items.Fields.ValidFrom"]" Name="@Key("Prices", index, "ValidFrom")" Value="p.ValidFrom" ValueChanged="v => Change(() => p.ValidFrom = v)" Span="2" />
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c2 kh-endrow">
|
||||||
|
<button type="button" class="btn danger" @onclick="() => Remove(Record.Prices, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (!Record.Prices.Any(p => p.PartyId is not null))
|
||||||
|
{
|
||||||
|
<p class="muted sm c12">@T["Items.Empty.NetPrices"]</p>
|
||||||
|
}
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c12">
|
||||||
|
<button type="button" class="btn" @onclick="AddNetPrice"><KhIcon Name="plus" /> @T["Items.Actions.AddNetPrice"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ItemScreens.Tabs.Suppliers:
|
||||||
|
@for (var i = 0; i < Record.Suppliers.Count; i++)
|
||||||
|
{
|
||||||
|
var index = i;
|
||||||
|
var s = Record.Suppliers[i];
|
||||||
|
<KhFieldGroup Title="@(PartyOf(s.PartyId)?.Name ?? T["Items.Actions.AddSupplier"])" Icon="truck" Wide="true">
|
||||||
|
<KhHotlink TItem="PartyRow" Label="@T["Items.Fields.Supplier"]" Name="@Key("Suppliers", index, "PartyId")" Span="5" Required="true"
|
||||||
|
Value="PartyOf(s.PartyId)" ValueChanged="v => SetParty(v, id => s.PartyId = id ?? 0)"
|
||||||
|
Search="SearchSuppliersAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenSupplier" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.SupplierCode"]" Name="@Key("Suppliers", index, "SupplierCode")" Value="@s.SupplierCode" ValueChanged="v => Change(() => s.SupplierCode = v)"
|
||||||
|
Mono="true" Span="4" MaxLength="40" />
|
||||||
|
<KhCheck Label="@T["Items.Fields.IsDefault"]" Name="@Key("Suppliers", index, "IsDefault")" Value="s.IsDefault" ValueChanged="v => Change(() => s.IsDefault = v)" Span="3" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.Price"]" Name="@Key("Suppliers", index, "Price")" Value="s.Price" ValueChanged="v => Change(() => s.Price = v)" Min="0" Span="3" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.LeadTimeDays"]" Name="@Key("Suppliers", index, "LeadTimeDays")" Value="s.LeadTimeDays" ValueChanged="v => Change(() => s.LeadTimeDays = (int?)v)"
|
||||||
|
Min="0" Decimals="0" Span="3" />
|
||||||
|
<KhNumberBox Label="@T["Items.Fields.MinimumQuantity"]" Name="@Key("Suppliers", index, "MinimumQuantity")" Value="s.MinimumQuantity" ValueChanged="v => Change(() => s.MinimumQuantity = v)"
|
||||||
|
Min="0" Decimals="3" Span="3" />
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c3 kh-endrow">
|
||||||
|
<button type="button" class="btn danger" @onclick="() => Remove(Record.Suppliers, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
}
|
||||||
|
<DetailFooter Empty="@(Record.Suppliers.Count == 0 ? T["Items.Empty.Suppliers"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddSupplier"]"
|
||||||
|
OnAdd="() => Add(Record.Suppliers, new ItemSupplier { IsDefault = Record.Suppliers.Count == 0 })" />
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ItemScreens.Tabs.Substitutes:
|
||||||
|
@for (var i = 0; i < Record.Substitutes.Count; i++)
|
||||||
|
{
|
||||||
|
var index = i;
|
||||||
|
var s = Record.Substitutes[i];
|
||||||
|
<KhFieldGroup Title="@(ItemOf(s.SubstituteId)?.Description ?? T["Items.Actions.AddSubstitute"])" Icon="refresh" Wide="true">
|
||||||
|
<KhHotlink TItem="ItemRow" Label="@T["Items.Fields.SubstituteId"]" Name="@Key("Substitutes", index, "SubstituteId")" Span="5" Required="true"
|
||||||
|
Value="ItemOf(s.SubstituteId)" ValueChanged="v => SetItem(v, id => s.SubstituteId = id ?? 0)"
|
||||||
|
Search="SearchItemsAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Description" OnOpen="OpenItem" />
|
||||||
|
<KhTextBox Label="@T["Items.Fields.Notes"]" Name="@Key("Substitutes", index, "Notes")" Value="@s.Notes" ValueChanged="v => Change(() => s.Notes = v)" Span="5" MaxLength="200" />
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c2 kh-endrow">
|
||||||
|
<button type="button" class="btn danger" @onclick="() => Remove(Record.Substitutes, index)"><KhIcon Name="trash" /> @T["Items.Actions.Remove"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
}
|
||||||
|
<DetailFooter Empty="@(Record.Substitutes.Count == 0 ? T["Items.Empty.Substitutes"] : null)" CanAdd="!IsReadOnly" AddText="@T["Items.Actions.AddSubstitute"]"
|
||||||
|
OnAdd="() => Add(Record.Substitutes, new ItemSubstitute())" />
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ItemScreens.Tabs.Notes:
|
||||||
|
<KhFieldGroup Title="@T["Items.Groups.Notes"]" Icon="edit" Wide="true">
|
||||||
|
<KhTextArea Label="@T["Items.Fields.Notes"]" Name="Notes" Value="@I.Notes" ValueChanged="v => Change(() => I.Notes = v)" Span="12" Rows="6" />
|
||||||
|
</KhFieldGroup>
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
</KhForm>
|
||||||
|
@if (ActiveTab == ItemScreens.Tabs.Notes && !IsNew && Session.Permissions.Allows(AttachmentService.ReadPermission))
|
||||||
|
{
|
||||||
|
<div class="kh-tab-body"><KhAttachmentList Entity="@ItemService.Entity" EntityId="I.Id" OnCountChanged="c => _attachments = c" /></div>
|
||||||
|
}
|
||||||
|
@if (ActiveTab == ItemScreens.Tabs.History)
|
||||||
|
{
|
||||||
|
<div class="kh-tab-body"><KhAuditList Items="_history" FieldName="FieldLabel" /></div>
|
||||||
|
}
|
||||||
|
</ChildContent>
|
||||||
|
</KhRecordLayout>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private ItemLookups _lookups = ItemLookups.Empty;
|
||||||
|
private IReadOnlyList<AuditItem> _history = [];
|
||||||
|
private IReadOnlyList<PriceListColumn> _columns = [];
|
||||||
|
private readonly Dictionary<long, PartyRow> _parties = [];
|
||||||
|
private readonly Dictionary<long, ItemRow> _items = [];
|
||||||
|
private PriceGridRow? _today;
|
||||||
|
private int _attachments;
|
||||||
|
private bool _costs;
|
||||||
|
private bool _loaded;
|
||||||
|
private bool _busy;
|
||||||
|
|
||||||
|
/// <summary>The item, absent for a new one.</summary>
|
||||||
|
[Parameter]
|
||||||
|
public long? Id { get; set; }
|
||||||
|
|
||||||
|
private Item I => Record!.Item;
|
||||||
|
|
||||||
|
private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission);
|
||||||
|
|
||||||
|
private string PageTitle => Record is null ? T["Items.Title"] : IsNew ? T["Items.NewTitle"] : (Record.Item.Code + " · " + Record.Item.Description);
|
||||||
|
|
||||||
|
private PriceListColumn? BaseList => _columns.FirstOrDefault(c => c.IsBase);
|
||||||
|
|
||||||
|
private decimal? BasePrice => BaseList is { } list && _today?.Prices.GetValueOrDefault(list.Id) is { Price: { } price } ? price : I.Price;
|
||||||
|
|
||||||
|
private string BaseLabel => BaseList is { } list ? T["Items.Radar.BasePrice"] + " · " + list.Code : T["Items.Fields.ItemPrice"];
|
||||||
|
|
||||||
|
private decimal? Cost => I.AverageCost ?? I.StandardCost;
|
||||||
|
|
||||||
|
private IReadOnlyList<KhStat>? HeadStats => !_costs || IsNew ? null :
|
||||||
|
[
|
||||||
|
new(T["Items.Fields.AverageCost"], Cost is { } cost ? T.Money(cost) : "-"),
|
||||||
|
new(T["Items.Fields.Margin"], ItemScreens.MarginText(BasePrice, Cost, T.Culture) ?? "-"),
|
||||||
|
];
|
||||||
|
|
||||||
|
private IReadOnlyList<string> HeadLines
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
var lines = new List<string>();
|
||||||
|
if (string.Join(" · ", new[] { I.Brand, I.Manufacturer }.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct()) is { Length: > 0 } brand)
|
||||||
|
{
|
||||||
|
lines.Add(brand);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (I.Barcode is { } barcode)
|
||||||
|
{
|
||||||
|
lines.Add(T["Items.Fields.Barcode"] + " " + barcode);
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private IReadOnlyList<KhOption<string>> KindChoices => ItemScreens.Choices<ItemKind>(T, "Kinds");
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override bool IsReadOnly => !CanWrite;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override bool IsNew => Record is { Item.Id: 0 };
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override bool CanDelete => base.CanDelete && Session.Permissions.Allows(ItemService.DeletePermission);
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override string? NewUrl => CanWrite ? ItemScreens.NewUrl : null;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] :
|
||||||
|
[
|
||||||
|
TabOf(ItemScreens.Tabs.Main, "box", "Main"),
|
||||||
|
TabOf(ItemScreens.Tabs.Units, "layers", "Units", Record.Units.Count),
|
||||||
|
TabOf(ItemScreens.Tabs.Barcodes, "key", "Barcodes", Record.Barcodes.Count),
|
||||||
|
TabOf(ItemScreens.Tabs.Prices, "tag", "Prices", Record.Prices.Count),
|
||||||
|
TabOf(ItemScreens.Tabs.Suppliers, "truck", "Suppliers", Record.Suppliers.Count),
|
||||||
|
TabOf(ItemScreens.Tabs.Substitutes, "refresh", "Substitutes", Record.Substitutes.Count),
|
||||||
|
TabOf(ItemScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments),
|
||||||
|
TabOf(ItemScreens.Tabs.History, "history", "History"),
|
||||||
|
];
|
||||||
|
|
||||||
|
private KhTabItem TabOf(string id, string icon, string text, int? count = null)
|
||||||
|
{
|
||||||
|
// A tab with errors shows how many; otherwise how many details it holds.
|
||||||
|
var errors = Validation.Messages.Count(m => ItemScreens.TabOf(m.Field) == id);
|
||||||
|
return new(id, icon, T["Items.Tabs." + text], errors > 0 ? errors : count is > 0 ? count : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override async Task OnParametersSetAsync()
|
||||||
|
{
|
||||||
|
await Session.EnsureLoadedAsync();
|
||||||
|
if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission))
|
||||||
|
{
|
||||||
|
if (!_loaded)
|
||||||
|
{
|
||||||
|
_lookups = await ItemLookups.ForRecordAsync(Tables, actor, company);
|
||||||
|
_costs = await Items.CanSeeCostsAsync(actor, company);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Record is null || Record.Item.Id != (Id ?? 0))
|
||||||
|
{
|
||||||
|
await ReloadAsync();
|
||||||
|
MarkSaved();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_loaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override async Task ReloadAsync()
|
||||||
|
{
|
||||||
|
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Validation.Clear();
|
||||||
|
if (Id is { } id)
|
||||||
|
{
|
||||||
|
Record = await Items.GetAsync(actor, company, id);
|
||||||
|
await LoadSideAsync(actor, company);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Record = await Items.NewAsync(actor, company);
|
||||||
|
_history = [];
|
||||||
|
_attachments = 0;
|
||||||
|
_today = null;
|
||||||
|
_columns = await PriceLists.ListsAsync(actor, company);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task LoadSideAsync(Actor actor, string company)
|
||||||
|
{
|
||||||
|
if (Record is not { Item.Id: > 0 } record)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_history = [.. (await Items.HistoryAsync(actor, company, record.Item.Id)).Select(AuditTrailService.Item)];
|
||||||
|
_attachments = Session.Permissions.Allows(AttachmentService.ReadPermission)
|
||||||
|
? await Attachments.CountAsync(actor, company, ItemService.Entity, record.Item.Id)
|
||||||
|
: 0;
|
||||||
|
var grid = await PriceLists.GridAsync(actor, company,
|
||||||
|
new ListQuery { Filters = [ListFilter.Of("code", ListFilterOperator.Equals, record.Item.Code)], Limit = 1 }, Today, null);
|
||||||
|
_columns = grid.Lists;
|
||||||
|
_today = grid.Page.Items.FirstOrDefault(r => r.ItemId == record.Item.Id);
|
||||||
|
|
||||||
|
// The names shown by the links: customers of the net prices, suppliers, substitutes.
|
||||||
|
long[] parties = [.. record.Prices.Where(p => p.PartyId is not null).Select(p => p.PartyId!.Value).Concat(record.Suppliers.Select(s => s.PartyId)).Where(p => !_parties.ContainsKey(p))];
|
||||||
|
if (parties.Length > 0 && Session.Permissions.Allows(PartyService.ReadPermission))
|
||||||
|
{
|
||||||
|
foreach (var row in await Parties.RowsAsync(actor, company, parties))
|
||||||
|
{
|
||||||
|
_parties[row.Id] = row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
long[] items = [.. record.Substitutes.Select(s => s.SubstituteId).Where(i => !_items.ContainsKey(i))];
|
||||||
|
if (items.Length > 0)
|
||||||
|
{
|
||||||
|
foreach (var row in await Items.RowsAsync(actor, company, items))
|
||||||
|
{
|
||||||
|
_items[row.Id] = row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateOnly Today => DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override async Task<bool> SaveCoreAsync()
|
||||||
|
{
|
||||||
|
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_busy = true;
|
||||||
|
Validation.Clear();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var wasNew = IsNew;
|
||||||
|
var problems = await Items.ValidateAsync(actor, company, Record);
|
||||||
|
if (problems.Any(p => !p.IsWarning))
|
||||||
|
{
|
||||||
|
Refuse(problems.Where(p => !p.IsWarning).Select(p => ((string?)p.Field, p.Code)));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Record = await Items.SaveAsync(actor, company, Record);
|
||||||
|
await LoadSideAsync(actor, company);
|
||||||
|
if (problems.Count > 0)
|
||||||
|
{
|
||||||
|
Toasts.Show(ToastKind.Warning, T.Format("Items.Actions.Warnings", string.Join(" ", problems.Select(p => Message(p.Code)))));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasNew)
|
||||||
|
{
|
||||||
|
MarkSaved();
|
||||||
|
Navigation.NavigateTo(ItemScreens.RecordUrl(Record.Item.Id), new NavigationOptions { ReplaceHistoryEntry = true });
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (ValidationFailedException ex)
|
||||||
|
{
|
||||||
|
Refuse(ex.Errors.Select(TableValues.SplitError));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (ConcurrencyException)
|
||||||
|
{
|
||||||
|
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Refuse(IEnumerable<(string? Field, string Code)> errors)
|
||||||
|
{
|
||||||
|
foreach (var (field, code) in errors)
|
||||||
|
{
|
||||||
|
Validation.Add(field, Message(code));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show the tab of the first error when the open one has none.
|
||||||
|
if (!Validation.Messages.Any(m => ItemScreens.TabOf(m.Field) == ActiveTab) && Validation.Messages.FirstOrDefault() is { } first)
|
||||||
|
{
|
||||||
|
_ = ShowTabAsync(ItemScreens.TabOf(first.Field));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"];
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override async Task DeleteCoreAsync()
|
||||||
|
{
|
||||||
|
if (Record is not { Item.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await Items.DeleteAsync(actor, company, record.Item.Id) == ItemDeleteOutcome.Disabled)
|
||||||
|
{
|
||||||
|
Toasts.Show(ToastKind.Info, T["Items.Actions.DeletedInstead"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Navigation.NavigateTo(ItemScreens.RadarUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override Task RadarAsync()
|
||||||
|
{
|
||||||
|
Navigation.NavigateTo(ItemScreens.RadarUrl);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override Task AttachmentsAsync() => ShowTabAsync(ItemScreens.Tabs.Notes);
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override IEnumerable<ToolbarItem> ContextActions()
|
||||||
|
{
|
||||||
|
if (Record is null || IsNew)
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return new ToolbarItem("pricelists", "tag", T["Items.Actions.PriceLists"])
|
||||||
|
{
|
||||||
|
Kind = ToolbarKind.Action, OnClick = () =>
|
||||||
|
{
|
||||||
|
Navigation.NavigateTo(ItemScreens.PriceListsUrl);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override IEnumerable<ToolbarItem> MenuCommands()
|
||||||
|
{
|
||||||
|
if (Record is null || IsNew || !CanWrite)
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return new ToolbarItem("disable", I.Disabled ? "check-circle" : "x-circle", T[I.Disabled ? "Items.Actions.Enable" : "Items.Actions.Disable"])
|
||||||
|
{
|
||||||
|
Kind = ToolbarKind.Menu, Disabled = IsModified || _busy, OnClick = ToggleDisabledAsync,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ToggleDisabledAsync()
|
||||||
|
{
|
||||||
|
if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var disabled = !I.Disabled;
|
||||||
|
await Items.SetDisabledAsync(actor, company, [I.Id], disabled);
|
||||||
|
Toasts.Show(ToastKind.Success, T.Format(disabled ? "Items.Actions.Disabled" : "Items.Actions.Enabled", 1));
|
||||||
|
Record = await Items.GetAsync(actor, company, I.Id) ?? Record;
|
||||||
|
await LoadSideAsync(actor, company);
|
||||||
|
StateHasChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Change(Action change)
|
||||||
|
{
|
||||||
|
change();
|
||||||
|
MarkModified();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Key(string list, int index, string field) => list + "." + index.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + field;
|
||||||
|
|
||||||
|
private void Add<TDetail>(List<TDetail> list, TDetail detail)
|
||||||
|
{
|
||||||
|
list.Add(detail);
|
||||||
|
MarkModified();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Remove<TDetail>(List<TDetail> list, int index)
|
||||||
|
{
|
||||||
|
if (index < list.Count)
|
||||||
|
{
|
||||||
|
list.RemoveAt(index);
|
||||||
|
Validation.Clear();
|
||||||
|
MarkModified();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The positions of the list prices or of the net prices: the errors name a row by its position in Prices.
|
||||||
|
private List<int> PriceRows(bool net) => [.. Enumerable.Range(0, Record!.Prices.Count).Where(i => Record.Prices[i].PartyId is not null == net)];
|
||||||
|
|
||||||
|
private void AddListPrice() => Add(Record!.Prices, new ItemPrice { PriceListId = BaseList?.Id ?? 0, ValidFrom = Today });
|
||||||
|
|
||||||
|
private void AddNetPrice() => Add(Record!.Prices, new ItemPrice { PartyId = 0, ValidFrom = Today });
|
||||||
|
|
||||||
|
private void SetKind(string? value) => Change(() =>
|
||||||
|
{
|
||||||
|
I.Kind = Enum.Parse<ItemKind>(value!);
|
||||||
|
// Only goods go in stock.
|
||||||
|
if (I.Kind != ItemKind.Goods)
|
||||||
|
{
|
||||||
|
I.Stocked = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
private PartyRow? PartyOf(long? id) => id is { } key && _parties.TryGetValue(key, out var row) ? row : null;
|
||||||
|
|
||||||
|
private ItemRow? ItemOf(long id) => _items.TryGetValue(id, out var row) ? row : null;
|
||||||
|
|
||||||
|
private void SetParty(PartyRow? row, Action<long?> set) => Change(() =>
|
||||||
|
{
|
||||||
|
if (row is not null)
|
||||||
|
{
|
||||||
|
_parties[row.Id] = row;
|
||||||
|
}
|
||||||
|
|
||||||
|
set(row?.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
private void SetItem(ItemRow? row, Action<long?> set) => Change(() =>
|
||||||
|
{
|
||||||
|
if (row is not null)
|
||||||
|
{
|
||||||
|
_items[row.Id] = row;
|
||||||
|
}
|
||||||
|
|
||||||
|
set(row?.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
private async Task<IReadOnlyList<PartyRow>> SearchCustomersAsync(string text, CancellationToken cancellationToken) =>
|
||||||
|
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
|
||||||
|
? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
private async Task<IReadOnlyList<PartyRow>> SearchSuppliersAsync(string text, CancellationToken cancellationToken) =>
|
||||||
|
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
|
||||||
|
? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
private async Task<IReadOnlyList<ItemRow>> SearchItemsAsync(string text, CancellationToken cancellationToken) =>
|
||||||
|
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||||
|
? [.. (await Items.SearchAsync(actor, company, text, null, cancellationToken)).Where(r => r.Id != I.Id)]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
private void OpenCustomer(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, row.Id));
|
||||||
|
|
||||||
|
private void OpenSupplier(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Suppliers, row.Id));
|
||||||
|
|
||||||
|
private void OpenItem(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id));
|
||||||
|
|
||||||
|
private string? FieldLabel(string field)
|
||||||
|
{
|
||||||
|
var key = "Items.Fields." + field.Split('.')[^1];
|
||||||
|
return T.Contains(key) ? T[key] : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
@page "/anagrafiche/articoli"
|
||||||
|
@attribute [Authorize]
|
||||||
|
@using Khaemhat.Application.Items
|
||||||
|
@using Khaemhat.Application.Tables
|
||||||
|
@using Khaemhat.Core.Items
|
||||||
|
@using Khaemhat.Web.Items
|
||||||
|
@using Khaemhat.Web.Parties
|
||||||
|
@inject ShellSession Session
|
||||||
|
@inject ItemService Items
|
||||||
|
@inject TableService Tables
|
||||||
|
@inject ToastService Toasts
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
@* The radar of the items (SPEC §11.2): search on code, description, bar code, brand and producer; filters for kind,
|
||||||
|
category, stock and state; the price of the base list today and, for who may see it, the average cost. Selection to
|
||||||
|
disable or enable; Enter or double click opens the record. Stock arrives with the warehouse (M6). *@
|
||||||
|
<KhPageTitle Text="@T["Items.Title"]" Icon="box" />
|
||||||
|
|
||||||
|
@if (!_loaded)
|
||||||
|
{
|
||||||
|
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||||
|
}
|
||||||
|
else if (Session.Company is null)
|
||||||
|
{
|
||||||
|
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Items.NoCompany"]</h1></div>
|
||||||
|
}
|
||||||
|
else if (!Session.Permissions.Allows(ItemService.ReadPermission))
|
||||||
|
{
|
||||||
|
<div class="kh-message">
|
||||||
|
<KhIcon Name="lock" Class="lg" />
|
||||||
|
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||||
|
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<KhRadar TItem="ItemRow" @ref="_radar" Id="items" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="CanWrite" SelectionChanged="SetSelection"
|
||||||
|
OnOpen="Open" QuickFilters="QuickFilters" InitialFilters="InitialFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Items.Radar.Search"]"
|
||||||
|
ExportName="articoli" Label="@T["Items.Title"]">
|
||||||
|
<Toolbar>
|
||||||
|
@if (CanWrite)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn primary" @onclick="New"><KhIcon Name="plus" /> @T["Items.New"]</button>
|
||||||
|
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(true)">
|
||||||
|
<KhIcon Name="x-circle" /> @T["Items.Actions.Disable"]
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn" disabled="@(_selected.Count == 0 || _busy)" @onclick="() => SetDisabledAsync(false)">
|
||||||
|
<KhIcon Name="check-circle" /> @T["Items.Actions.Enable"]
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
<a class="btn" href="@ItemScreens.PriceListsUrl"><KhIcon Name="tag" /> @T["Items.Actions.PriceLists"]</a>
|
||||||
|
</Toolbar>
|
||||||
|
</KhRadar>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private ItemLookups _lookups = ItemLookups.Empty;
|
||||||
|
private KhRadar<ItemRow>? _radar;
|
||||||
|
private List<long> _selected = [];
|
||||||
|
private bool _costs;
|
||||||
|
private bool _loaded;
|
||||||
|
private bool _busy;
|
||||||
|
|
||||||
|
private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission);
|
||||||
|
|
||||||
|
private static IReadOnlyList<ListFilter> InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")];
|
||||||
|
|
||||||
|
private IReadOnlyList<KhColumn<ItemRow>> Columns =>
|
||||||
|
[
|
||||||
|
new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "130px" },
|
||||||
|
new("description", T["Items.Fields.Description"], r => r.Description),
|
||||||
|
new("category", T["Items.Radar.Category"], r => PartyScreens.Describe(_lookups.Categories, r.CategoryId)) { Width = "110px" },
|
||||||
|
new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "60px" },
|
||||||
|
new("barcode", T["Items.Fields.Barcode"], r => r.Barcode) { Width = "140px", Visible = false },
|
||||||
|
new("brand", T["Items.Fields.Brand"], r => r.Brand) { Width = "130px" },
|
||||||
|
new("kind", T["Items.Radar.Kind"], r => T["Items.Kinds." + r.Kind]) { Width = "100px" },
|
||||||
|
new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false, Visible = _costs, Export = _costs },
|
||||||
|
new("basePrice", T["Items.Radar.BasePrice"], r => r.BasePrice) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false },
|
||||||
|
new("state", T["Items.Radar.State"], r => StateOf(r).Text)
|
||||||
|
{
|
||||||
|
Sortable = false, Width = "130px",
|
||||||
|
Template = r => @<KhBadge Tone="StateOf(r).Tone">@StateOf(r).Text</KhBadge>,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
private IReadOnlyList<KhQuickFilter> QuickFilters =>
|
||||||
|
[
|
||||||
|
new("kind", T["Items.Radar.Kind"], [new(string.Empty, T["Items.Radar.All"]), .. ItemScreens.Choices<ItemKind>(T, "Kinds")]),
|
||||||
|
new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]),
|
||||||
|
new("stocked", T["Items.Radar.Stocked"],
|
||||||
|
[new(string.Empty, T["Items.Radar.All"]), new("true", T["Items.Fields.Stocked"]), new("false", T["Items.States.NotStocked"])]),
|
||||||
|
new("disabled", T["Items.Radar.State"],
|
||||||
|
[new(string.Empty, T["Items.Radar.All"]), new("false", T["Items.Radar.Active"]), new("true", T["Items.Radar.Disabled"])]),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override async Task OnParametersSetAsync()
|
||||||
|
{
|
||||||
|
await Session.EnsureLoadedAsync();
|
||||||
|
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission))
|
||||||
|
{
|
||||||
|
_lookups = await ItemLookups.ForRadarAsync(Tables, actor, company);
|
||||||
|
_costs = await Items.CanSeeCostsAsync(actor, company);
|
||||||
|
}
|
||||||
|
|
||||||
|
_loaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private (string Text, KhTone Tone) StateOf(ItemRow row) => row switch
|
||||||
|
{
|
||||||
|
{ Disabled: true } => (T["Items.States.Disabled"], KhTone.Neutral),
|
||||||
|
{ Stocked: false } => (T["Items.States.NotStocked"], KhTone.Info),
|
||||||
|
_ => (T["Items.States.Active"], KhTone.Ok),
|
||||||
|
};
|
||||||
|
|
||||||
|
private Task<ListPage<ItemRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||||
|
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||||
|
? Items.ListAsync(actor, company, query, cancellationToken)
|
||||||
|
: Task.FromResult(new ListPage<ItemRow>([], 0, new Dictionary<string, decimal>()));
|
||||||
|
|
||||||
|
private void SetSelection(IReadOnlyCollection<object> keys) => _selected = [.. keys.OfType<long>()];
|
||||||
|
|
||||||
|
private static string? RowClassOf(ItemRow row) => row.Disabled ? "muted" : null;
|
||||||
|
|
||||||
|
private void Open(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id));
|
||||||
|
|
||||||
|
private void New() => Navigation.NavigateTo(ItemScreens.NewUrl);
|
||||||
|
|
||||||
|
private async Task SetDisabledAsync(bool disabled)
|
||||||
|
{
|
||||||
|
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected.Count == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_busy = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var count = await Items.SetDisabledAsync(actor, company, _selected, disabled);
|
||||||
|
Toasts.Show(ToastKind.Success, T.Format(disabled ? "Items.Actions.Disabled" : "Items.Actions.Enabled", count));
|
||||||
|
if (_radar is not null)
|
||||||
|
{
|
||||||
|
await _radar.ReloadAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
@page "/anagrafiche/listini"
|
||||||
|
@attribute [Authorize]
|
||||||
|
@using Khaemhat.Application.Items
|
||||||
|
@using Khaemhat.Application.Parties
|
||||||
|
@using Khaemhat.Application.Security
|
||||||
|
@using Khaemhat.Application.Tables
|
||||||
|
@using Khaemhat.Core.Items
|
||||||
|
@using Khaemhat.Web.Items
|
||||||
|
@using Khaemhat.Web.Parties
|
||||||
|
@using Khaemhat.Web.Tables
|
||||||
|
@inject ShellSession Session
|
||||||
|
@inject PriceListService PriceLists
|
||||||
|
@inject ItemService Items
|
||||||
|
@inject PartyService Parties
|
||||||
|
@inject TableService Tables
|
||||||
|
@inject ToastService Toasts
|
||||||
|
@inject DialogService Dialogs
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
@* The price grid (SPEC §11.2, mockup 018): one row per item, one column per active price list with the price in effect
|
||||||
|
at the validity date, the net prices of a customer and the margin. A price is changed in its cell (double click or
|
||||||
|
F2) and a mass update computes many at once: the changed cells stay highlighted until saved, and every saved price
|
||||||
|
starts at the validity date, so older documents keep the price of their day (ADR 0030). *@
|
||||||
|
<KhPageTitle Text="@T["Items.PriceLists.Title"]" Icon="tag" />
|
||||||
|
|
||||||
|
@if (!_loaded)
|
||||||
|
{
|
||||||
|
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||||
|
}
|
||||||
|
else if (Session.Company is null)
|
||||||
|
{
|
||||||
|
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Items.NoCompany"]</h1></div>
|
||||||
|
}
|
||||||
|
else if (!Session.Permissions.Allows(ItemService.ReadPermission))
|
||||||
|
{
|
||||||
|
<div class="kh-message">
|
||||||
|
<KhIcon Name="lock" Class="lg" />
|
||||||
|
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||||
|
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (_lists.Count == 0)
|
||||||
|
{
|
||||||
|
<div class="kh-message">
|
||||||
|
<KhIcon Name="tag" Class="lg" />
|
||||||
|
<h1>@T["Items.PriceLists.NoLists"]</h1>
|
||||||
|
<a class="btn" href="tabelle/listini">@T["Items.PriceLists.NewList"]</a>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="kh-pricebar">
|
||||||
|
<div class="f">
|
||||||
|
<label for="kh-pl-list">@T["Items.PriceLists.List"]</label>
|
||||||
|
<select id="kh-pl-list" class="in" @onchange="e => _onlyList = PartyScreens.Id(e.Value as string)">
|
||||||
|
<option value="" selected="@(_onlyList is null)">@T["Items.PriceLists.All"]</option>
|
||||||
|
@foreach (var list in _lists)
|
||||||
|
{
|
||||||
|
<option value="@list.Id" selected="@(_onlyList == list.Id)">@list.Code · @list.Description</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="kh-pricebar-date">
|
||||||
|
<KhDateBox Label="@T["Items.PriceLists.Validity"]" Name="validity" Value="_date" ValueChanged="SetDateAsync" Span="12" />
|
||||||
|
</div>
|
||||||
|
@if (Session.Permissions.Allows(PartyService.ReadPermission))
|
||||||
|
{
|
||||||
|
<div class="kh-pricebar-party">
|
||||||
|
<KhHotlink TItem="PartyRow" Label="@T["Items.PriceLists.Net"]" Name="party" Span="12" Value="_party" ValueChanged="SetPartyAsync"
|
||||||
|
Search="SearchCustomersAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (_costs)
|
||||||
|
{
|
||||||
|
<label class="kh-pricebar-check"><input type="checkbox" checked="@_showMargin" @onchange="e => _showMargin = e.Value is true" /> @T["Items.PriceLists.ShowMargin"]</label>
|
||||||
|
}
|
||||||
|
<span class="grow"></span>
|
||||||
|
<KhBadge Tone="KhTone.Info">@(_party is null ? T.Format("Items.PriceLists.Count", _lists.Count) : T.Format("Items.PriceLists.CountNet", _lists.Count))</KhBadge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<KhRadar TItem="PriceGridRow" @ref="_radar" Id="pricelists" Columns="Columns" Source="ListAsync" KeyOf="r => r.ItemId" Selectable="CanWrite"
|
||||||
|
SelectionChanged="SetSelection" OnOpen="Open" QuickFilters="QuickFilters" InitialFilters="InitialFilters" RowClass="RowClassOf"
|
||||||
|
SearchPlaceholder="@T["Items.PriceLists.Search"]" ExportName="listini" Label="@T["Items.PriceLists.Title"]" Class="kh-pricegrid">
|
||||||
|
<Toolbar>
|
||||||
|
@if (CanWrite)
|
||||||
|
{
|
||||||
|
<button type="button" class="btn primary" disabled="@(_pending.Count == 0 || _busy)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Items.PriceLists.Save"]</button>
|
||||||
|
<button type="button" class="btn" disabled="@(_pending.Count == 0 || _busy)" @onclick="UndoAsync"><KhIcon Name="undo" /> @T["Items.PriceLists.Undo"]</button>
|
||||||
|
<button type="button" class="btn" disabled="@_busy" @onclick="OpenBulk"><KhIcon Name="zap" /> @T["Items.PriceLists.Bulk"]</button>
|
||||||
|
}
|
||||||
|
@if (Session.Permissions.Allows(TableService.WritePermission))
|
||||||
|
{
|
||||||
|
<a class="btn" href="tabelle/listini"><KhIcon Name="plus" /> @T["Items.PriceLists.NewList"]</a>
|
||||||
|
}
|
||||||
|
</Toolbar>
|
||||||
|
<Summary>
|
||||||
|
<span class="kh-pricefoot">@T.Format("Items.PriceLists.Footer", _pending.Count, T.Date(_date))</span>
|
||||||
|
</Summary>
|
||||||
|
</KhRadar>
|
||||||
|
|
||||||
|
<div class="callout info kh-pricehint"><KhIcon Name="info" /> <span>@T["Items.PriceLists.Hint"]</span></div>
|
||||||
|
|
||||||
|
<KhDialog Open="_bulkOpen" Title="@T["Items.Bulk.Title"]" Icon="zap" Size="md" OnClose="() => _bulkOpen = false">
|
||||||
|
<ChildContent>
|
||||||
|
<KhForm Validation="_bulkValidation" Layout="KhFormLayout.Grid">
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Bulk.List"]" Name="PriceListId" Options="ListChoices" Value="@PartyScreens.Text(_bulk.PriceListId)" Span="6" Required="true"
|
||||||
|
ValueChanged="v => _bulk = _bulk with { PriceListId = PartyScreens.Id(v) ?? 0 }" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Bulk.Source"]" Name="SourcePriceListId" Options="ListChoices" Empty="@T["Items.Bulk.SourceSame"]" Span="6"
|
||||||
|
Value="@PartyScreens.Text(_bulk.SourcePriceListId)" ValueChanged="v => _bulk = _bulk with { SourcePriceListId = PartyScreens.Id(v) }" />
|
||||||
|
<KhNumberBox Label="@T["Items.Bulk.Percent"]" Name="Percent" Value="_bulk.Percent" ValueChanged="v => _bulk = _bulk with { Percent = v ?? 0 }" Min="-99" Max="1000" Span="4" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Bulk.Step"]" Name="RoundingStep" Options="StepChoices" Value="@StepText(_bulk.RoundingStep)" Span="4"
|
||||||
|
ValueChanged="SetStep" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Bulk.Direction"]" Name="Direction" Options="DirectionChoices" Value="@_bulk.Direction.ToString()" Span="4"
|
||||||
|
ValueChanged="SetDirection" />
|
||||||
|
<KhSelect TValue="string" Label="@T["Items.Fields.CategoryId"]" Name="CategoryId" Options="_lookups.Categories" Empty="@T["Items.Bulk.ScopeAll"]" Span="6"
|
||||||
|
Value="@PartyScreens.Text(_bulk.CategoryId)" ValueChanged="v => _bulk = _bulk with { CategoryId = PartyScreens.Id(v) }" />
|
||||||
|
<KhDateBox Label="@T["Items.Bulk.Date"]" Name="Date" Value="_bulk.Date" ValueChanged="v => _bulk = _bulk with { Date = v ?? _date }" Span="6" Required="true" />
|
||||||
|
@if (_selected.Count > 0)
|
||||||
|
{
|
||||||
|
<KhCheck Label="@T.Format("Items.Bulk.ScopeSelected", _selected.Count)" Name="Selected" Value="_bulkSelected" ValueChanged="v => _bulkSelected = v" Span="12" />
|
||||||
|
}
|
||||||
|
</KhForm>
|
||||||
|
</ChildContent>
|
||||||
|
<Footer>
|
||||||
|
<button type="button" class="btn" @onclick="() => _bulkOpen = false">@T["Common.Cancel"]</button>
|
||||||
|
<button type="button" class="btn primary" disabled="@_busy" @onclick="ApplyBulkAsync"><KhIcon Name="zap" /> @T["Items.Bulk.Apply"]</button>
|
||||||
|
</Footer>
|
||||||
|
</KhDialog>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private readonly Dictionary<Target, Pending> _pending = [];
|
||||||
|
private readonly KhValidation _bulkValidation = new();
|
||||||
|
private IReadOnlyList<PriceListColumn> _lists = [];
|
||||||
|
private ItemLookups _lookups = ItemLookups.Empty;
|
||||||
|
private KhRadar<PriceGridRow>? _radar;
|
||||||
|
private List<long> _selected = [];
|
||||||
|
private PartyRow? _party;
|
||||||
|
private long? _onlyList;
|
||||||
|
private DateOnly _date = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
private BulkUpdate _bulk = new();
|
||||||
|
private bool _bulkOpen;
|
||||||
|
private bool _bulkSelected;
|
||||||
|
private bool _showMargin = true;
|
||||||
|
private bool _costs;
|
||||||
|
private bool _loaded;
|
||||||
|
private bool _busy;
|
||||||
|
|
||||||
|
/// <summary>A cell of the grid: a list price, or the net price of a customer.</summary>
|
||||||
|
private readonly record struct Target(long ItemId, long? PriceListId, long? PartyId);
|
||||||
|
|
||||||
|
/// <summary>A price changed and not saved: none removes the price of that day.</summary>
|
||||||
|
private readonly record struct Pending(decimal? Price, DateOnly ValidFrom);
|
||||||
|
|
||||||
|
private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission);
|
||||||
|
|
||||||
|
private static IReadOnlyList<ListFilter> InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")];
|
||||||
|
|
||||||
|
private PriceListColumn? MarginList => _lists.FirstOrDefault(l => l.Id == _onlyList) ?? _lists.FirstOrDefault(l => l.IsBase) ?? _lists.FirstOrDefault();
|
||||||
|
|
||||||
|
private IReadOnlyList<KhOption<string>> ListChoices => [.. _lists.Select(l => new KhOption<string>(PartyScreens.Text(l.Id)!, l.Code + " · " + l.Description))];
|
||||||
|
|
||||||
|
private IReadOnlyList<KhOption<string>> DirectionChoices => ItemScreens.Choices<RoundingDirection>(T, "Directions");
|
||||||
|
|
||||||
|
private IReadOnlyList<KhOption<string>> StepChoices =>
|
||||||
|
[.. new[] { 0.01m, 0.10m, 0.50m, 1.00m }.Select(s => new KhOption<string>(StepText(s), s.ToString("0.00", T.Culture)))];
|
||||||
|
|
||||||
|
private void SetStep(string? value) =>
|
||||||
|
_bulk = _bulk with { RoundingStep = decimal.TryParse(value, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out var step) ? step : 0.01m };
|
||||||
|
|
||||||
|
private void SetDirection(string? value) => _bulk = _bulk with { Direction = Enum.TryParse<RoundingDirection>(value, out var direction) ? direction : RoundingDirection.Nearest };
|
||||||
|
|
||||||
|
private static string StepText(decimal step) => step.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private IReadOnlyList<KhColumn<PriceGridRow>> Columns
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
var columns = new List<KhColumn<PriceGridRow>>
|
||||||
|
{
|
||||||
|
new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "120px" },
|
||||||
|
new("description", T["Items.Fields.Description"], r => r.Description),
|
||||||
|
new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "60px" },
|
||||||
|
};
|
||||||
|
if (_costs)
|
||||||
|
{
|
||||||
|
columns.Add(new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false });
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var list in _lists.Where(l => _onlyList is null || l.Id == _onlyList))
|
||||||
|
{
|
||||||
|
var id = list.Id;
|
||||||
|
columns.Add(new("list-" + PartyScreens.Text(id), list.Code + " " + list.Description, r => PriceOf(r, id))
|
||||||
|
{
|
||||||
|
Kind = KhColumnKind.Money, Width = "120px", Sortable = false,
|
||||||
|
CellClass = r => CellClassOf(r, new Target(r.ItemId, id, null)),
|
||||||
|
Edit = CanWrite ? (r, text) => EditAsync(new Target(r.ItemId, id, null), CurrentOf(r, id), text) : null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_party is { } party)
|
||||||
|
{
|
||||||
|
var partyId = party.Id;
|
||||||
|
columns.Add(new("net", T.Format("Items.PriceLists.NetColumn", party.Name), r => NetOf(r, partyId))
|
||||||
|
{
|
||||||
|
Kind = KhColumnKind.Money, Width = "140px", Sortable = false,
|
||||||
|
CellClass = r => CellClassOf(r, new Target(r.ItemId, null, partyId)),
|
||||||
|
Edit = CanWrite ? (r, text) => EditAsync(new Target(r.ItemId, null, partyId), r.Net?.Price, text) : null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_costs && _showMargin && MarginList is { } marginList)
|
||||||
|
{
|
||||||
|
var id = marginList.Id;
|
||||||
|
columns.Add(new("margin", T.Format("Items.PriceLists.Margin", marginList.Code), r => ItemScreens.MarginText(PriceOf(r, id), r.AverageCost, T.Culture))
|
||||||
|
{
|
||||||
|
Width = "100px", Sortable = false, CellClass = _ => "num",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private IReadOnlyList<KhQuickFilter> QuickFilters =>
|
||||||
|
[
|
||||||
|
new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]),
|
||||||
|
new("disabled", T["Items.Radar.State"],
|
||||||
|
[new(string.Empty, T["Items.Radar.All"]), new("false", T["Items.Radar.Active"]), new("true", T["Items.Radar.Disabled"])]),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override async Task OnParametersSetAsync()
|
||||||
|
{
|
||||||
|
await Session.EnsureLoadedAsync();
|
||||||
|
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission))
|
||||||
|
{
|
||||||
|
_lookups = await ItemLookups.ForRadarAsync(Tables, actor, company);
|
||||||
|
_lists = await PriceLists.ListsAsync(actor, company);
|
||||||
|
_costs = await Items.CanSeeCostsAsync(actor, company);
|
||||||
|
}
|
||||||
|
|
||||||
|
_loaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ListPage<PriceGridRow>> ListAsync(ListQuery query, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||||
|
{
|
||||||
|
return new ListPage<PriceGridRow>([], 0, new Dictionary<string, decimal>());
|
||||||
|
}
|
||||||
|
|
||||||
|
var grid = await PriceLists.GridAsync(actor, company, query, _date, _party?.Id, cancellationToken);
|
||||||
|
return grid.Page;
|
||||||
|
}
|
||||||
|
|
||||||
|
private decimal? CurrentOf(PriceGridRow row, long listId) => row.Prices.GetValueOrDefault(listId)?.Price;
|
||||||
|
|
||||||
|
private decimal? PriceOf(PriceGridRow row, long listId) =>
|
||||||
|
_pending.TryGetValue(new Target(row.ItemId, listId, null), out var pending) ? pending.Price : CurrentOf(row, listId);
|
||||||
|
|
||||||
|
private decimal? NetOf(PriceGridRow row, long partyId) =>
|
||||||
|
_pending.TryGetValue(new Target(row.ItemId, null, partyId), out var pending) ? pending.Price : row.Net?.Price;
|
||||||
|
|
||||||
|
private string? CellClassOf(PriceGridRow row, Target target)
|
||||||
|
{
|
||||||
|
if (_pending.ContainsKey(target))
|
||||||
|
{
|
||||||
|
return "kh-changed";
|
||||||
|
}
|
||||||
|
|
||||||
|
return target.PriceListId is { } list && row.Prices.GetValueOrDefault(list) is { Derived: true } ? "kh-derived" : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<string?> EditAsync(Target target, decimal? current, string text)
|
||||||
|
{
|
||||||
|
if (!ItemScreens.TryParsePrice(text, T.Culture, out var price))
|
||||||
|
{
|
||||||
|
return Task.FromResult<string?>(T["Items.PriceLists.Invalid"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back to the price in effect: nothing to save for this cell.
|
||||||
|
if (price == current)
|
||||||
|
{
|
||||||
|
_pending.Remove(target);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_pending[target] = new Pending(price, _date);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The grid calls this as a plain delegate: the page renders again for Save and Undo to follow the count.
|
||||||
|
StateHasChanged();
|
||||||
|
return Task.FromResult<string?>(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? RowClassOf(PriceGridRow row) => null;
|
||||||
|
|
||||||
|
private void SetSelection(IReadOnlyCollection<object> keys) => _selected = [.. keys.OfType<long>()];
|
||||||
|
|
||||||
|
private void Open(PriceGridRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.ItemId));
|
||||||
|
|
||||||
|
private async Task SetDateAsync(DateOnly? value)
|
||||||
|
{
|
||||||
|
if (_pending.Count > 0)
|
||||||
|
{
|
||||||
|
Toasts.Show(ToastKind.Warning, T["Items.PriceLists.Leave"]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_date = value ?? DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
await ReloadAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SetPartyAsync(PartyRow? value)
|
||||||
|
{
|
||||||
|
if (_pending.Keys.Any(k => k.PartyId is not null))
|
||||||
|
{
|
||||||
|
Toasts.Show(ToastKind.Warning, T["Items.PriceLists.Leave"]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_party = value;
|
||||||
|
await ReloadAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IReadOnlyList<PartyRow>> SearchCustomersAsync(string text, CancellationToken cancellationToken) =>
|
||||||
|
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||||
|
? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
private async Task ReloadAsync()
|
||||||
|
{
|
||||||
|
StateHasChanged();
|
||||||
|
if (_radar is not null)
|
||||||
|
{
|
||||||
|
await _radar.ReloadAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SaveAsync()
|
||||||
|
{
|
||||||
|
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_pending.Count == 0)
|
||||||
|
{
|
||||||
|
Toasts.Show(ToastKind.Info, T["Items.PriceLists.NoChanges"]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_busy = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IReadOnlyList<PriceEdit> edits = [.. _pending.Select(p => new PriceEdit(p.Key.ItemId, p.Key.PriceListId, p.Key.PartyId, p.Value.Price, p.Value.ValidFrom))];
|
||||||
|
var written = await PriceLists.SaveAsync(actor, company, edits);
|
||||||
|
_pending.Clear();
|
||||||
|
Toasts.Show(ToastKind.Success, T.Format("Items.PriceLists.Saved", written));
|
||||||
|
await ReloadAsync();
|
||||||
|
}
|
||||||
|
catch (ValidationFailedException ex)
|
||||||
|
{
|
||||||
|
Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"],
|
||||||
|
string.Join(" ", ex.Errors.Select(TableValues.SplitError).Select(e => e.Code).Distinct().Select(c => T.Contains(c) ? T[c] : T["CompanyTables.UnknownError"])));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UndoAsync()
|
||||||
|
{
|
||||||
|
if (_pending.Count == 0
|
||||||
|
|| !await Dialogs.ConfirmAsync(new(T["Items.PriceLists.UndoTitle"], T["Items.PriceLists.UndoText"], T["Items.PriceLists.Undo"], T["Common.Cancel"], Danger: true)))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_pending.Clear();
|
||||||
|
await ReloadAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenBulk()
|
||||||
|
{
|
||||||
|
_bulkValidation.Clear();
|
||||||
|
_bulk = new BulkUpdate
|
||||||
|
{
|
||||||
|
PriceListId = _onlyList ?? _lists.FirstOrDefault(l => l.IsBase)?.Id ?? _lists[0].Id, RoundingStep = 0.10m, Direction = RoundingDirection.Nearest, Date = _date,
|
||||||
|
};
|
||||||
|
_bulkSelected = _selected.Count > 0;
|
||||||
|
_bulkOpen = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ApplyBulkAsync()
|
||||||
|
{
|
||||||
|
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_busy = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var update = _bulk with { ItemIds = _bulkSelected && _selected.Count > 0 ? [.. _selected] : null };
|
||||||
|
var edits = await PriceLists.PreviewAsync(actor, company, update);
|
||||||
|
foreach (var edit in edits)
|
||||||
|
{
|
||||||
|
_pending[new Target(edit.ItemId, edit.PriceListId, edit.PartyId)] = new Pending(edit.Price, edit.ValidFrom ?? update.Date);
|
||||||
|
}
|
||||||
|
|
||||||
|
_bulkOpen = false;
|
||||||
|
Toasts.Show(edits.Count == 0 ? ToastKind.Info : ToastKind.Success, edits.Count == 0 ? T["Items.Bulk.None"] : T.Format("Items.Bulk.Result", edits.Count));
|
||||||
|
await ReloadAsync();
|
||||||
|
}
|
||||||
|
catch (ValidationFailedException ex)
|
||||||
|
{
|
||||||
|
_bulkValidation.Clear();
|
||||||
|
foreach (var (field, code) in ex.Errors.Select(TableValues.SplitError))
|
||||||
|
{
|
||||||
|
_bulkValidation.Add(field, T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,17 +7,21 @@
|
|||||||
@attribute [Authorize]
|
@attribute [Authorize]
|
||||||
@inherits MasterDataPage<PartyRecord>
|
@inherits MasterDataPage<PartyRecord>
|
||||||
@using Khaemhat.Application.Audit
|
@using Khaemhat.Application.Audit
|
||||||
|
@using Khaemhat.Application.Items
|
||||||
@using Khaemhat.Application.Parties
|
@using Khaemhat.Application.Parties
|
||||||
@using Khaemhat.Application.Security
|
@using Khaemhat.Application.Security
|
||||||
@using Khaemhat.Application.Tables
|
@using Khaemhat.Application.Tables
|
||||||
@using Khaemhat.Core.Common
|
@using Khaemhat.Core.Common
|
||||||
|
@using Khaemhat.Core.Items
|
||||||
@using Khaemhat.Core.Parties
|
@using Khaemhat.Core.Parties
|
||||||
@using Khaemhat.Fiscal.Abstractions
|
@using Khaemhat.Fiscal.Abstractions
|
||||||
@using Khaemhat.Infrastructure.Http
|
@using Khaemhat.Infrastructure.Http
|
||||||
|
@using Khaemhat.Web.Items
|
||||||
@using Khaemhat.Web.Parties
|
@using Khaemhat.Web.Parties
|
||||||
@using Khaemhat.Web.Tables
|
@using Khaemhat.Web.Tables
|
||||||
@inject ShellSession Session
|
@inject ShellSession Session
|
||||||
@inject PartyService Parties
|
@inject PartyService Parties
|
||||||
|
@inject ItemService Items
|
||||||
@inject TableService Tables
|
@inject TableService Tables
|
||||||
@inject AutoFillService AutoFill
|
@inject AutoFillService AutoFill
|
||||||
@inject AttachmentService Attachments
|
@inject AttachmentService Attachments
|
||||||
@@ -388,6 +392,32 @@ else
|
|||||||
OnAdd="() => Add(Record.BankAccounts, new PartyBankAccount { IsDefault = Record.BankAccounts.Count == 0 })" />
|
OnAdd="() => Add(Record.BankAccounts, new PartyBankAccount { IsDefault = Record.BankAccounts.Count == 0 })" />
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case PartyScreens.Tabs.ItemCodes:
|
||||||
|
<p class="muted kh-pad sm"><KhIcon Name="info" /> @T["Parties.ItemCodesHint"]</p>
|
||||||
|
@for (var i = 0; i < Record.ItemCodes.Count; i++)
|
||||||
|
{
|
||||||
|
var index = i;
|
||||||
|
var c = Record.ItemCodes[i];
|
||||||
|
<KhFieldGroup Title="@(c.Code.Length > 0 ? c.Code : T["Parties.Actions.AddItemCode"])" Icon="box" Wide="true">
|
||||||
|
<KhTextBox Label="@T["Parties.Fields.ItemCode"]" Name="@Key("ItemCodes", index, "Code")" Value="@c.Code" ValueChanged="v => Change(() => c.Code = v ?? string.Empty)"
|
||||||
|
Mono="true" Span="3" Required="true" MaxLength="40" />
|
||||||
|
<KhHotlink TItem="ItemRow" Label="@T["Parties.Fields.ItemId"]" Name="@Key("ItemCodes", index, "ItemId")" Span="4" Required="true"
|
||||||
|
Value="ItemOf(c.ItemId)" ValueChanged="v => SetItem(c, v)" Search="SearchItemsAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Description"
|
||||||
|
OnOpen="OpenItem" />
|
||||||
|
<KhTextBox Label="@T["Parties.Fields.ItemDescription"]" Name="@Key("ItemCodes", index, "Description")" Value="@c.Description" ValueChanged="v => Change(() => c.Description = v)"
|
||||||
|
Span="3" MaxLength="200" />
|
||||||
|
@if (!IsReadOnly)
|
||||||
|
{
|
||||||
|
<div class="c2 kh-endrow">
|
||||||
|
<button type="button" class="btn danger" @onclick="() => Remove(Record.ItemCodes, index)"><KhIcon Name="trash" /> @T["Parties.Actions.Remove"]</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</KhFieldGroup>
|
||||||
|
}
|
||||||
|
<DetailFooter Empty="@(Record.ItemCodes.Count == 0 ? T["Parties.Empty.ItemCodes"] : null)" CanAdd="@(!IsReadOnly && CanReadItems)" AddText="@T["Parties.Actions.AddItemCode"]"
|
||||||
|
OnAdd="() => Add(Record.ItemCodes, new PartyItemCode())" />
|
||||||
|
break;
|
||||||
|
|
||||||
case PartyScreens.Tabs.Notes:
|
case PartyScreens.Tabs.Notes:
|
||||||
<KhFieldGroup Title="@T["Parties.Groups.Notes"]" Icon="edit" Wide="true">
|
<KhFieldGroup Title="@T["Parties.Groups.Notes"]" Icon="edit" Wide="true">
|
||||||
<KhTextArea Label="@T["Parties.Fields.Notes"]" Name="Notes" Value="@P.Notes" ValueChanged="v => Change(() => P.Notes = v)" Span="12" Rows="6" />
|
<KhTextArea Label="@T["Parties.Fields.Notes"]" Name="Notes" Value="@P.Notes" ValueChanged="v => Change(() => P.Notes = v)" Span="12" Rows="6" />
|
||||||
@@ -412,6 +442,7 @@ else
|
|||||||
private PartyLookups _lookups = PartyLookups.Empty;
|
private PartyLookups _lookups = PartyLookups.Empty;
|
||||||
private IReadOnlyList<AuditItem> _history = [];
|
private IReadOnlyList<AuditItem> _history = [];
|
||||||
private IReadOnlyList<PlaceSuggestion> _places = [];
|
private IReadOnlyList<PlaceSuggestion> _places = [];
|
||||||
|
private readonly Dictionary<long, ItemRow> _items = [];
|
||||||
private int _attachments;
|
private int _attachments;
|
||||||
private bool _loaded;
|
private bool _loaded;
|
||||||
private bool _busy;
|
private bool _busy;
|
||||||
@@ -431,6 +462,8 @@ else
|
|||||||
|
|
||||||
private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission);
|
private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission);
|
||||||
|
|
||||||
|
private bool CanReadItems => Session.Permissions.Allows(ItemService.ReadPermission);
|
||||||
|
|
||||||
private string KindIcon => Record?.Party.Kind switch
|
private string KindIcon => Record?.Party.Kind switch
|
||||||
{
|
{
|
||||||
PartyKind.Supplier => "truck",
|
PartyKind.Supplier => "truck",
|
||||||
@@ -517,6 +550,7 @@ else
|
|||||||
TabOf(PartyScreens.Tabs.Terms, "coins", "Terms"),
|
TabOf(PartyScreens.Tabs.Terms, "coins", "Terms"),
|
||||||
TabOf(PartyScreens.Tabs.Fiscal, "file-check", "Fiscal"),
|
TabOf(PartyScreens.Tabs.Fiscal, "file-check", "Fiscal"),
|
||||||
TabOf(PartyScreens.Tabs.Banks, "euro", "Banks", Record.BankAccounts.Count),
|
TabOf(PartyScreens.Tabs.Banks, "euro", "Banks", Record.BankAccounts.Count),
|
||||||
|
TabOf(PartyScreens.Tabs.ItemCodes, "box", "ItemCodes", Record.ItemCodes.Count),
|
||||||
TabOf(PartyScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments),
|
TabOf(PartyScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments),
|
||||||
TabOf(PartyScreens.Tabs.History, "history", "History"),
|
TabOf(PartyScreens.Tabs.History, "history", "History"),
|
||||||
];
|
];
|
||||||
@@ -581,6 +615,15 @@ else
|
|||||||
}
|
}
|
||||||
|
|
||||||
_history = [.. (await Parties.HistoryAsync(actor, company, record.Party.Id)).Select(AuditTrailService.Item)];
|
_history = [.. (await Parties.HistoryAsync(actor, company, record.Party.Id)).Select(AuditTrailService.Item)];
|
||||||
|
long[] items = [.. record.ItemCodes.Select(c => c.ItemId).Where(i => i > 0 && !_items.ContainsKey(i))];
|
||||||
|
if (items.Length > 0 && CanReadItems)
|
||||||
|
{
|
||||||
|
foreach (var row in await Items.RowsAsync(actor, company, items))
|
||||||
|
{
|
||||||
|
_items[row.Id] = row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
_attachments = Session.Permissions.Allows(AttachmentService.ReadPermission)
|
_attachments = Session.Permissions.Allows(AttachmentService.ReadPermission)
|
||||||
? await Attachments.CountAsync(actor, company, PartyService.Entity, record.Party.Id)
|
? await Attachments.CountAsync(actor, company, PartyService.Entity, record.Party.Id)
|
||||||
: 0;
|
: 0;
|
||||||
@@ -807,6 +850,26 @@ else
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ItemRow? ItemOf(long id) => _items.TryGetValue(id, out var row) ? row : null;
|
||||||
|
|
||||||
|
private void SetItem(PartyItemCode code, ItemRow? row) => Change(() =>
|
||||||
|
{
|
||||||
|
if (row is not null)
|
||||||
|
{
|
||||||
|
_items[row.Id] = row;
|
||||||
|
}
|
||||||
|
|
||||||
|
code.ItemId = row?.Id ?? 0;
|
||||||
|
code.Description ??= row?.Description;
|
||||||
|
});
|
||||||
|
|
||||||
|
private async Task<IReadOnlyList<ItemRow>> SearchItemsAsync(string text, CancellationToken cancellationToken) =>
|
||||||
|
Session.Actor is { } actor && Session.Company?.Code is { } company && CanReadItems
|
||||||
|
? await Items.SearchAsync(actor, company, text, null, cancellationToken)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
private void OpenItem(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id));
|
||||||
|
|
||||||
private void SetKind(string? value) => Change(() => P.Kind = Enum.Parse<PartyKind>(value!));
|
private void SetKind(string? value) => Change(() => P.Kind = Enum.Parse<PartyKind>(value!));
|
||||||
|
|
||||||
private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse<PartyAddressKind>(value!));
|
private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse<PartyAddressKind>(value!));
|
||||||
|
|||||||
@@ -145,12 +145,15 @@ internal static class KhaemhatServices
|
|||||||
services.AddSingleton<CodeRuleService>();
|
services.AddSingleton<CodeRuleService>();
|
||||||
services.AddSingleton<AutoFillService>();
|
services.AddSingleton<AutoFillService>();
|
||||||
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
|
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
|
||||||
|
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
|
||||||
|
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
|
||||||
services.AddSingleton<ExchangeRateService>();
|
services.AddSingleton<ExchangeRateService>();
|
||||||
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
|
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
|
||||||
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
|
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
|
||||||
services.AddSingleton<IScheduledJob, EcbRatesJob>();
|
services.AddSingleton<IScheduledJob, EcbRatesJob>();
|
||||||
services.AddSingleton<ISeeder, BaseTablesSeeder>();
|
services.AddSingleton<ISeeder, BaseTablesSeeder>();
|
||||||
services.AddSingleton<ISeeder, DemoPartiesSeeder>();
|
services.AddSingleton<ISeeder, DemoPartiesSeeder>();
|
||||||
|
services.AddSingleton<ISeeder, DemoItemsSeeder>();
|
||||||
services.AddSingleton<SeedRunner>();
|
services.AddSingleton<SeedRunner>();
|
||||||
|
|
||||||
// Companies and start.
|
// Companies and start.
|
||||||
|
|||||||
@@ -8,10 +8,17 @@ using Khaemhat.Infrastructure.Logging;
|
|||||||
|
|
||||||
namespace Khaemhat.Web.Hosting;
|
namespace Khaemhat.Web.Hosting;
|
||||||
|
|
||||||
|
/// <summary>What <c>seed</c> was asked to do.</summary>
|
||||||
|
/// <param name="Demo">Add the demo data too, after the base data, to the tables still empty.</param>
|
||||||
|
/// <param name="Scale">How many times the demo catalogues are repeated.</param>
|
||||||
|
/// <param name="Company">The company, or <see langword="null"/> for every active one.</param>
|
||||||
|
public sealed record SeedOptions(bool Demo, int Scale, string? Company);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The command line of <c>scripts/seed.sh</c> (SPEC §4, §14): <c>seed --base [--company CODE]</c> runs the start
|
/// The command line of <c>scripts/seed.sh</c> (SPEC §4, §14): <c>seed --base|--demo [--scale N] [--company CODE]</c>
|
||||||
/// sequence without serving anything (migrations, first company), then adds the missing base data to one company or to
|
/// runs the start sequence without serving anything (migrations, first company), then adds the missing base data, and
|
||||||
/// every active one, and prints what it added. Rows already there are never changed (ADR 0026).
|
/// with <c>--demo</c> the demo data, to one company or to every active one, and prints what it added. Rows already there
|
||||||
|
/// are never changed (ADR 0026); each demo seeder fills only its tables still empty.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class SeedCommand
|
public static class SeedCommand
|
||||||
{
|
{
|
||||||
@@ -21,6 +28,9 @@ public static class SeedCommand
|
|||||||
/// <summary>Exit code of a wrong command line.</summary>
|
/// <summary>Exit code of a wrong command line.</summary>
|
||||||
public const int UsageError = 64;
|
public const int UsageError = 64;
|
||||||
|
|
||||||
|
/// <summary>The largest <c>--scale</c>.</summary>
|
||||||
|
public const int MaxScale = 100;
|
||||||
|
|
||||||
/// <summary>Whether the arguments ask for this command.</summary>
|
/// <summary>Whether the arguments ask for this command.</summary>
|
||||||
/// <param name="args">The arguments.</param>
|
/// <param name="args">The arguments.</param>
|
||||||
/// <returns><see langword="true"/> for <c>seed ...</c>.</returns>
|
/// <returns><see langword="true"/> for <c>seed ...</c>.</returns>
|
||||||
@@ -28,15 +38,18 @@ public static class SeedCommand
|
|||||||
|
|
||||||
/// <summary>Reads the options after the verb.</summary>
|
/// <summary>Reads the options after the verb.</summary>
|
||||||
/// <param name="args">The arguments, verb included.</param>
|
/// <param name="args">The arguments, verb included.</param>
|
||||||
/// <param name="company">The company, or <see langword="null"/> for every active one.</param>
|
/// <param name="options">What to do, when the line is valid.</param>
|
||||||
/// <param name="error">The problem, or <see langword="null"/>.</param>
|
/// <param name="error">The problem, or <see langword="null"/>.</param>
|
||||||
/// <returns><see langword="true"/> when the line is valid.</returns>
|
/// <returns><see langword="true"/> when the line is valid.</returns>
|
||||||
public static bool TryParse(string[] args, out string? company, out string? error)
|
public static bool TryParse(string[] args, out SeedOptions? options, out string? error)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(args);
|
ArgumentNullException.ThrowIfNull(args);
|
||||||
company = null;
|
options = null;
|
||||||
error = null;
|
error = null;
|
||||||
var wantsBase = false;
|
var wantsBase = false;
|
||||||
|
var wantsDemo = false;
|
||||||
|
int? scale = null;
|
||||||
|
string? company = null;
|
||||||
for (var i = 1; i < args.Length; i++)
|
for (var i = 1; i < args.Length; i++)
|
||||||
{
|
{
|
||||||
switch (args[i])
|
switch (args[i])
|
||||||
@@ -44,9 +57,13 @@ public static class SeedCommand
|
|||||||
case "--base":
|
case "--base":
|
||||||
wantsBase = true;
|
wantsBase = true;
|
||||||
break;
|
break;
|
||||||
case "--demo" or "--scale":
|
case "--demo":
|
||||||
error = "seed --demo: i dati dimostrativi arrivano con anagrafiche e articoli (M4, issue #41 e #42).";
|
wantsDemo = true;
|
||||||
return false;
|
break;
|
||||||
|
case "--scale" when i + 1 < args.Length && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n is >= 1 and <= MaxScale:
|
||||||
|
scale = n;
|
||||||
|
i++;
|
||||||
|
break;
|
||||||
case "--company" when i + 1 < args.Length && CompanyCodes.IsValid(CompanyCodes.Normalize(args[i + 1])):
|
case "--company" when i + 1 < args.Length && CompanyCodes.IsValid(CompanyCodes.Normalize(args[i + 1])):
|
||||||
company = CompanyCodes.Normalize(args[++i]);
|
company = CompanyCodes.Normalize(args[++i]);
|
||||||
break;
|
break;
|
||||||
@@ -56,12 +73,20 @@ public static class SeedCommand
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!wantsBase)
|
if (!wantsBase && !wantsDemo)
|
||||||
{
|
{
|
||||||
error = "Uso: seed --base [--company CODICE]";
|
error = "Uso: seed --base | --demo [--scale N] [--company CODICE]";
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return error is null;
|
if (scale is not null && !wantsDemo)
|
||||||
|
{
|
||||||
|
error = "--scale vale solo con --demo.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
options = new SeedOptions(wantsDemo, scale ?? 1, company);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Runs the command.</summary>
|
/// <summary>Runs the command.</summary>
|
||||||
@@ -69,7 +94,7 @@ public static class SeedCommand
|
|||||||
/// <returns>The exit code: 0 done, 1 failed, 64 wrong command line.</returns>
|
/// <returns>The exit code: 0 done, 1 failed, 64 wrong command line.</returns>
|
||||||
public static async Task<int> RunAsync(string[] args)
|
public static async Task<int> RunAsync(string[] args)
|
||||||
{
|
{
|
||||||
if (!TryParse(args, out var company, out var error))
|
if (!TryParse(args, out var options, out var error) || options is null)
|
||||||
{
|
{
|
||||||
await Console.Error.WriteLineAsync(error).ConfigureAwait(false);
|
await Console.Error.WriteLineAsync(error).ConfigureAwait(false);
|
||||||
return UsageError;
|
return UsageError;
|
||||||
@@ -84,6 +109,7 @@ public static class SeedCommand
|
|||||||
{
|
{
|
||||||
await services.GetRequiredService<StartupOrchestrator>().RunAsync().ConfigureAwait(false);
|
await services.GetRequiredService<StartupOrchestrator>().RunAsync().ConfigureAwait(false);
|
||||||
var registry = services.GetRequiredService<ICompanyRegistry>();
|
var registry = services.GetRequiredService<ICompanyRegistry>();
|
||||||
|
var company = options.Company;
|
||||||
IReadOnlyList<string> codes = company is null
|
IReadOnlyList<string> codes = company is null
|
||||||
? [.. (await registry.ListAsync().ConfigureAwait(false)).Where(c => c.Status == CompanyStatus.Active).Select(c => c.Code)]
|
? [.. (await registry.ListAsync().ConfigureAwait(false)).Where(c => c.Status == CompanyStatus.Active).Select(c => c.Code)]
|
||||||
: await registry.FindAsync(company).ConfigureAwait(false) is { } found ? [found.Code] : [];
|
: await registry.FindAsync(company).ConfigureAwait(false) is { } found ? [found.Code] : [];
|
||||||
@@ -96,11 +122,13 @@ public static class SeedCommand
|
|||||||
var runner = services.GetRequiredService<SeedRunner>();
|
var runner = services.GetRequiredService<SeedRunner>();
|
||||||
foreach (var code in codes)
|
foreach (var code in codes)
|
||||||
{
|
{
|
||||||
|
// The demo data need the base tables: --demo runs the base seeders first.
|
||||||
var report = await runner.RunAsync(code, SeedKind.Base).ConfigureAwait(false);
|
var report = await runner.RunAsync(code, SeedKind.Base).ConfigureAwait(false);
|
||||||
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{code}: dati di base {report.DataVersion}, {report.Total} righe aggiunte."));
|
Print(code, "dati di base " + report.DataVersion, report);
|
||||||
foreach (var (table, count) in report.Added.Where(a => a.Value > 0).OrderBy(a => a.Key, StringComparer.Ordinal))
|
if (options.Demo)
|
||||||
{
|
{
|
||||||
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $" {table}: {count}"));
|
Print(code, "dati dimostrativi, scala " + options.Scale.ToString(CultureInfo.InvariantCulture),
|
||||||
|
await runner.RunAsync(code, SeedKind.Demo, options.Scale).ConfigureAwait(false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,4 +140,13 @@ public static class SeedCommand
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void Print(string company, string what, SeedReport report)
|
||||||
|
{
|
||||||
|
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{company}: {what}, {report.Total} righe aggiunte."));
|
||||||
|
foreach (var (table, count) in report.Added.Where(a => a.Value > 0).OrderBy(a => a.Key, StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $" {table}: {count}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
using Khaemhat.Application.Security;
|
||||||
|
using Khaemhat.Application.Tables;
|
||||||
|
using Khaemhat.Core.Tables;
|
||||||
|
using Khaemhat.Web.Tables;
|
||||||
|
using Khaemhat.Web.Ui;
|
||||||
|
|
||||||
|
namespace Khaemhat.Web.Items;
|
||||||
|
|
||||||
|
/// <summary>The company tables an item points to, read once per page as choices (<c>code · description</c>).</summary>
|
||||||
|
public sealed class ItemLookups
|
||||||
|
{
|
||||||
|
/// <summary>Nothing loaded.</summary>
|
||||||
|
public static ItemLookups Empty { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Item categories, by id.</summary>
|
||||||
|
public IReadOnlyList<KhOption<string>> Categories { get; private init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Units of measure, by id.</summary>
|
||||||
|
public IReadOnlyList<KhOption<string>> Units { get; private init; } = [];
|
||||||
|
|
||||||
|
/// <summary>VAT codes, by id.</summary>
|
||||||
|
public IReadOnlyList<KhOption<string>> TaxCodes { get; private init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Warehouses, by id.</summary>
|
||||||
|
public IReadOnlyList<KhOption<string>> Warehouses { get; private init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Price lists, by id.</summary>
|
||||||
|
public IReadOnlyList<KhOption<string>> PriceLists { get; private init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Reads the choices the radar and the price grid need.</summary>
|
||||||
|
/// <param name="tables">The tables.</param>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="company">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The choices.</returns>
|
||||||
|
public static async Task<ItemLookups> ForRadarAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new()
|
||||||
|
{
|
||||||
|
Categories = await ReadAsync<ItemCategory>(tables, actor, company, cancellationToken).ConfigureAwait(false),
|
||||||
|
Units = await ReadAsync<UnitOfMeasure>(tables, actor, company, cancellationToken).ConfigureAwait(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Reads every choice of the record page.</summary>
|
||||||
|
/// <param name="tables">The tables.</param>
|
||||||
|
/// <param name="actor">Who reads.</param>
|
||||||
|
/// <param name="company">The company.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation.</param>
|
||||||
|
/// <returns>The choices.</returns>
|
||||||
|
public static async Task<ItemLookups> ForRecordAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new()
|
||||||
|
{
|
||||||
|
Categories = await ReadAsync<ItemCategory>(tables, actor, company, cancellationToken).ConfigureAwait(false),
|
||||||
|
Units = await ReadAsync<UnitOfMeasure>(tables, actor, company, cancellationToken).ConfigureAwait(false),
|
||||||
|
TaxCodes = await ReadAsync<TaxCode>(tables, actor, company, cancellationToken).ConfigureAwait(false),
|
||||||
|
Warehouses = await ReadAsync<Warehouse>(tables, actor, company, cancellationToken).ConfigureAwait(false),
|
||||||
|
PriceLists = await ReadAsync<PriceList>(tables, actor, company, cancellationToken).ConfigureAwait(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
private static async Task<IReadOnlyList<KhOption<string>>> ReadAsync<T>(TableService tables, Actor actor, string company, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var choices = await TableValues.LookupAsync(tables, typeof(T), false, actor, company, cancellationToken).ConfigureAwait(false);
|
||||||
|
return [.. choices.Select(c => new KhOption<string>(c.Value, c.Text))];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Khaemhat.Application.Localization;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Web.Ui;
|
||||||
|
|
||||||
|
namespace Khaemhat.Web.Items;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Addresses, tabs and choices of the item screens (SPEC §11.2, mockups 017 and 018): the radar
|
||||||
|
/// <c>/anagrafiche/articoli</c>, the record of an item under it, and the price grid <c>/anagrafiche/listini</c>.
|
||||||
|
/// </summary>
|
||||||
|
public static class ItemScreens
|
||||||
|
{
|
||||||
|
/// <summary>The radar of the items.</summary>
|
||||||
|
public const string RadarUrl = "anagrafiche/articoli";
|
||||||
|
|
||||||
|
/// <summary>A new item.</summary>
|
||||||
|
public const string NewUrl = RadarUrl + "/nuovo";
|
||||||
|
|
||||||
|
/// <summary>The price grid.</summary>
|
||||||
|
public const string PriceListsUrl = "anagrafiche/listini";
|
||||||
|
|
||||||
|
/// <summary>The table of the item categories, where <c>/anagrafiche/categorie</c> leads.</summary>
|
||||||
|
public const string CategoriesUrl = "tabelle/categorie-articoli";
|
||||||
|
|
||||||
|
/// <summary>The tab ids of the record page, in order.</summary>
|
||||||
|
public static class Tabs
|
||||||
|
{
|
||||||
|
/// <summary>Main data.</summary>
|
||||||
|
public const string Main = "dati";
|
||||||
|
|
||||||
|
/// <summary>Alternative units.</summary>
|
||||||
|
public const string Units = "um";
|
||||||
|
|
||||||
|
/// <summary>Alternative codes.</summary>
|
||||||
|
public const string Barcodes = "codici";
|
||||||
|
|
||||||
|
/// <summary>Prices of the lists and net prices of the customers.</summary>
|
||||||
|
public const string Prices = "listini";
|
||||||
|
|
||||||
|
/// <summary>Suppliers.</summary>
|
||||||
|
public const string Suppliers = "fornitori";
|
||||||
|
|
||||||
|
/// <summary>Substitutes.</summary>
|
||||||
|
public const string Substitutes = "sostitutivi";
|
||||||
|
|
||||||
|
/// <summary>Notes and attachments.</summary>
|
||||||
|
public const string Notes = "note";
|
||||||
|
|
||||||
|
/// <summary>History.</summary>
|
||||||
|
public const string History = "storico";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The record of an item.</summary>
|
||||||
|
/// <param name="id">The item.</param>
|
||||||
|
/// <returns>The address, relative to the base.</returns>
|
||||||
|
public static string RecordUrl(long id) => RadarUrl + "/" + id.ToString(CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
/// <summary>The tab that holds a field of the service (<c>Prices.0.Price</c>, <c>Suppliers.1.PartyId</c>).</summary>
|
||||||
|
/// <param name="field">The field.</param>
|
||||||
|
/// <returns>The tab id.</returns>
|
||||||
|
public static string TabOf(string? field)
|
||||||
|
{
|
||||||
|
var head = (field ?? string.Empty).Split('.')[0];
|
||||||
|
return head switch
|
||||||
|
{
|
||||||
|
"Units" => Tabs.Units,
|
||||||
|
"Barcodes" => Tabs.Barcodes,
|
||||||
|
"Prices" => Tabs.Prices,
|
||||||
|
"Suppliers" => Tabs.Suppliers,
|
||||||
|
"Substitutes" => Tabs.Substitutes,
|
||||||
|
nameof(Item.Notes) => Tabs.Notes,
|
||||||
|
_ => Tabs.Main,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The choices of an enum, with the texts <c>Items.<group>.<value></c>.</summary>
|
||||||
|
/// <typeparam name="TEnum">The enum.</typeparam>
|
||||||
|
/// <param name="texts">The texts.</param>
|
||||||
|
/// <param name="group">The group of texts.</param>
|
||||||
|
/// <returns>The choices.</returns>
|
||||||
|
public static IReadOnlyList<KhOption<string>> Choices<TEnum>(ITexts texts, string group)
|
||||||
|
where TEnum : struct, Enum
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(texts);
|
||||||
|
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<string>(v.ToString(), texts["Items." + group + "." + v]))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The margin on the price as text, such as <c>45%</c>; none without both values.</summary>
|
||||||
|
/// <param name="price">The price.</param>
|
||||||
|
/// <param name="cost">The cost.</param>
|
||||||
|
/// <param name="culture">The culture of the texts.</param>
|
||||||
|
/// <returns>The text.</returns>
|
||||||
|
public static string? MarginText(decimal? price, decimal? cost, CultureInfo culture) =>
|
||||||
|
PriceRounding.Margin(price, cost) is { } margin ? margin.ToString("0.#", culture) + "%" : null;
|
||||||
|
|
||||||
|
/// <summary>Reads a price typed in a cell: empty means no price, otherwise a number not below zero.</summary>
|
||||||
|
/// <param name="text">The text typed.</param>
|
||||||
|
/// <param name="culture">The culture of the texts.</param>
|
||||||
|
/// <param name="price">The price, or <see langword="null"/> for none.</param>
|
||||||
|
/// <returns>Whether the text is valid.</returns>
|
||||||
|
public static bool TryParsePrice(string? text, CultureInfo culture, out decimal? price)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(culture);
|
||||||
|
price = null;
|
||||||
|
var clean = (text ?? string.Empty).Replace("€", string.Empty, StringComparison.Ordinal).Trim();
|
||||||
|
if (clean.Length == 0)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!decimal.TryParse(clean, NumberStyles.Number, culture, out var value) || value < 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
price = Math.Round(value, 4, MidpointRounding.AwayFromZero);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,9 @@ public static class PartyScreens
|
|||||||
/// <summary>Bank accounts.</summary>
|
/// <summary>Bank accounts.</summary>
|
||||||
public const string Banks = "banche";
|
public const string Banks = "banche";
|
||||||
|
|
||||||
|
/// <summary>The codes the party uses for our items.</summary>
|
||||||
|
public const string ItemCodes = "articoli";
|
||||||
|
|
||||||
/// <summary>Notes and attachments.</summary>
|
/// <summary>Notes and attachments.</summary>
|
||||||
public const string Notes = "note";
|
public const string Notes = "note";
|
||||||
|
|
||||||
@@ -124,6 +127,7 @@ public static class PartyScreens
|
|||||||
"Addresses" => Tabs.Addresses,
|
"Addresses" => Tabs.Addresses,
|
||||||
"Contacts" => Tabs.Contacts,
|
"Contacts" => Tabs.Contacts,
|
||||||
"BankAccounts" => Tabs.Banks,
|
"BankAccounts" => Tabs.Banks,
|
||||||
|
"ItemCodes" => Tabs.ItemCodes,
|
||||||
"Sales" or "Purchase" => Tabs.Terms,
|
"Sales" or "Purchase" => Tabs.Terms,
|
||||||
"Fiscal" => Tabs.Fiscal,
|
"Fiscal" => Tabs.Fiscal,
|
||||||
nameof(Party.Notes) => Tabs.Notes,
|
nameof(Party.Notes) => Tabs.Notes,
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
{
|
||||||
|
"Items": {
|
||||||
|
"Title": "Articoli",
|
||||||
|
"NoCompany": "Scegli un'azienda per vedere gli articoli.",
|
||||||
|
"NotFound": "Articolo non trovato",
|
||||||
|
"CodeAuto": "Automatico",
|
||||||
|
"NewTitle": "Nuovo articolo",
|
||||||
|
"New": "Nuovo articolo",
|
||||||
|
"Radar": {
|
||||||
|
"Search": "Cerca per codice, descrizione, codice a barre, marca",
|
||||||
|
"All": "Tutti",
|
||||||
|
"Active": "Attivi",
|
||||||
|
"Disabled": "Disattivati",
|
||||||
|
"Kind": "Tipo",
|
||||||
|
"Category": "Categoria",
|
||||||
|
"Unit": "UM",
|
||||||
|
"BasePrice": "Prezzo base",
|
||||||
|
"AverageCost": "Costo medio",
|
||||||
|
"Stocked": "Magazzino",
|
||||||
|
"State": "Stato"
|
||||||
|
},
|
||||||
|
"States": {
|
||||||
|
"Active": "Attivo",
|
||||||
|
"Disabled": "Disattivato",
|
||||||
|
"Demo": "Esempio",
|
||||||
|
"NotStocked": "Non a magazzino"
|
||||||
|
},
|
||||||
|
"Kinds": {
|
||||||
|
"Goods": "Merce",
|
||||||
|
"Service": "Servizio",
|
||||||
|
"Expense": "Spesa",
|
||||||
|
"Text": "Descrittivo",
|
||||||
|
"Asset": "Cespite"
|
||||||
|
},
|
||||||
|
"Directions": {
|
||||||
|
"Nearest": "Al più vicino",
|
||||||
|
"Up": "Per eccesso",
|
||||||
|
"Down": "Per difetto"
|
||||||
|
},
|
||||||
|
"Tabs": {
|
||||||
|
"Main": "Dati principali",
|
||||||
|
"Units": "UM alternative",
|
||||||
|
"Barcodes": "Codici alternativi",
|
||||||
|
"Prices": "Listini",
|
||||||
|
"Suppliers": "Fornitori",
|
||||||
|
"Substitutes": "Sostitutivi",
|
||||||
|
"Notes": "Note e allegati",
|
||||||
|
"History": "Storico"
|
||||||
|
},
|
||||||
|
"Groups": {
|
||||||
|
"Identity": "Identità",
|
||||||
|
"Codes": "Unità, codici e IVA",
|
||||||
|
"Prices": "Prezzi e costi",
|
||||||
|
"Stock": "Magazzino e riordino",
|
||||||
|
"Accounts": "Contabilità",
|
||||||
|
"Today": "Prezzi in vigore oggi",
|
||||||
|
"ListPrices": "Prezzi di listino",
|
||||||
|
"NetPrices": "Prezzi netti dei clienti",
|
||||||
|
"Notes": "Note"
|
||||||
|
},
|
||||||
|
"Fields": {
|
||||||
|
"Code": "Codice",
|
||||||
|
"Kind": "Tipo",
|
||||||
|
"Description": "Descrizione",
|
||||||
|
"ExtendedDescription": "Descrizione estesa",
|
||||||
|
"CategoryId": "Categoria",
|
||||||
|
"UnitOfMeasureId": "Unità di misura",
|
||||||
|
"SalesTaxCodeId": "IVA vendite",
|
||||||
|
"PurchaseTaxCodeId": "IVA acquisti",
|
||||||
|
"Barcode": "Codice a barre",
|
||||||
|
"CustomsCode": "Nomenclatura combinata",
|
||||||
|
"Manufacturer": "Produttore",
|
||||||
|
"Brand": "Marca",
|
||||||
|
"NetWeight": "Peso netto (kg)",
|
||||||
|
"GrossWeight": "Peso lordo (kg)",
|
||||||
|
"Stocked": "Gestito a magazzino",
|
||||||
|
"WarehouseId": "Deposito preferito",
|
||||||
|
"MinimumStock": "Scorta minima",
|
||||||
|
"ReorderPoint": "Punto di riordino",
|
||||||
|
"ReorderLot": "Lotto di riordino",
|
||||||
|
"Price": "Prezzo",
|
||||||
|
"ItemPrice": "Prezzo dell'articolo",
|
||||||
|
"StandardCost": "Costo standard",
|
||||||
|
"LastCost": "Ultimo costo",
|
||||||
|
"AverageCost": "Costo medio",
|
||||||
|
"Margin": "Margine",
|
||||||
|
"RevenueAccountCode": "Conto ricavi",
|
||||||
|
"CostAccountCode": "Conto costi",
|
||||||
|
"Notes": "Note",
|
||||||
|
"Disabled": "Disattivato",
|
||||||
|
"Factor": "Fattore di conversione",
|
||||||
|
"PriceListId": "Listino",
|
||||||
|
"PartyId": "Cliente",
|
||||||
|
"ValidFrom": "Valido dal",
|
||||||
|
"SupplierCode": "Codice del fornitore",
|
||||||
|
"Supplier": "Fornitore",
|
||||||
|
"LeadTimeDays": "Giorni di consegna",
|
||||||
|
"MinimumQuantity": "Quantità minima",
|
||||||
|
"IsDefault": "Preferito",
|
||||||
|
"SubstituteId": "Articolo sostitutivo",
|
||||||
|
"ItemId": "Articolo",
|
||||||
|
"Source": "Origine"
|
||||||
|
},
|
||||||
|
"Hints": {
|
||||||
|
"Costs": "Ultimo costo e costo medio arrivano dai carichi di magazzino, con gli acquisti (M6).",
|
||||||
|
"CostsHidden": "I costi sono visibili solo a chi ha il permesso di vederli.",
|
||||||
|
"Stock": "Giacenze, impegni e movimenti per deposito arrivano con il magazzino (M6).",
|
||||||
|
"NotStocked": "Servizi, spese, righe descrittive e cespiti non vanno a magazzino.",
|
||||||
|
"ItemPrice": "Vale solo quando nessun listino ha un prezzo per l'articolo.",
|
||||||
|
"Prices": "Ogni prezzo vale dalla sua data fino al prezzo successivo dello stesso listino o cliente: i documenti già fatti conservano il prezzo di allora.",
|
||||||
|
"Derived": "Calcolato dal listino di partenza con ricarico e arrotondamento",
|
||||||
|
"Units": "Il fattore dice quante unità base vale una unità alternativa: una scatola da 10 pezzi ha fattore 10.",
|
||||||
|
"Barcodes": "Codici a barre dei produttori e codici dei vecchi gestionali: la ricerca li trova esattamente."
|
||||||
|
},
|
||||||
|
"Empty": {
|
||||||
|
"Units": "Nessuna unità alternativa.",
|
||||||
|
"Barcodes": "Nessun codice alternativo.",
|
||||||
|
"ListPrices": "Nessun prezzo di listino scritto: valgono i listini derivati e il prezzo dell'articolo.",
|
||||||
|
"NetPrices": "Nessun prezzo netto per un cliente.",
|
||||||
|
"Suppliers": "Nessun fornitore abituale.",
|
||||||
|
"Substitutes": "Nessun articolo sostitutivo."
|
||||||
|
},
|
||||||
|
"Actions": {
|
||||||
|
"Disable": "Disattiva",
|
||||||
|
"Enable": "Riattiva",
|
||||||
|
"Disabled": "{0} articoli disattivati",
|
||||||
|
"Enabled": "{0} articoli riattivati",
|
||||||
|
"DeletedInstead": "Articolo usato da altri dati: è stato disattivato invece che eliminato.",
|
||||||
|
"Remove": "Rimuovi",
|
||||||
|
"AddUnit": "Aggiungi unità",
|
||||||
|
"AddBarcode": "Aggiungi codice",
|
||||||
|
"AddPrice": "Aggiungi prezzo di listino",
|
||||||
|
"AddNetPrice": "Aggiungi prezzo netto",
|
||||||
|
"AddSupplier": "Aggiungi fornitore",
|
||||||
|
"AddSubstitute": "Aggiungi sostitutivo",
|
||||||
|
"PriceLists": "Listini",
|
||||||
|
"Warnings": "Salvato con avvisi: {0}"
|
||||||
|
},
|
||||||
|
"PriceLists": {
|
||||||
|
"Title": "Listini",
|
||||||
|
"Search": "Cerca articolo",
|
||||||
|
"List": "Listino",
|
||||||
|
"All": "Tutti",
|
||||||
|
"Validity": "Validità",
|
||||||
|
"Net": "Prezzi netti di",
|
||||||
|
"NetColumn": "{0} (netto)",
|
||||||
|
"ShowMargin": "Mostra margine",
|
||||||
|
"Margin": "Margine {0}",
|
||||||
|
"Count": "{0} listini",
|
||||||
|
"CountNet": "{0} listini + prezzi netti cliente",
|
||||||
|
"Footer": "Modifiche non salvate: {0} · validità nuovi prezzi dal {1}",
|
||||||
|
"Hint": "Aggiornamento massivo: scegli listino, categoria o selezione, variazione % (anche negativa) o da altro listino, arrotondamento (0,10 / 0,50 / 1,00, per eccesso o per difetto) e data di validità; le righe aggiornate restano evidenziate finché non salvi.",
|
||||||
|
"Save": "Salva",
|
||||||
|
"Undo": "Annulla modifiche",
|
||||||
|
"UndoTitle": "Annullare le modifiche?",
|
||||||
|
"UndoText": "I prezzi cambiati e non salvati tornano come prima.",
|
||||||
|
"Bulk": "Aggiornamento massivo",
|
||||||
|
"NewList": "Nuovo listino",
|
||||||
|
"Saved": "{0} prezzi salvati",
|
||||||
|
"NoChanges": "Nessuna modifica da salvare.",
|
||||||
|
"Invalid": "Prezzo non valido: scrivi un numero non negativo, o lascia vuoto per togliere il prezzo.",
|
||||||
|
"Derived": "Calcolato da {0}",
|
||||||
|
"Pending": "Da salvare",
|
||||||
|
"Leave": "Ci sono prezzi non salvati: salvali o annulla le modifiche prima di cambiare validità o cliente.",
|
||||||
|
"NoLists": "Nessun listino attivo: creane uno nelle tabelle dell'azienda."
|
||||||
|
},
|
||||||
|
"Bulk": {
|
||||||
|
"Title": "Aggiornamento massivo",
|
||||||
|
"List": "Listino da aggiornare",
|
||||||
|
"Source": "Calcola da",
|
||||||
|
"SourceSame": "Prezzi attuali dello stesso listino",
|
||||||
|
"Percent": "Variazione %",
|
||||||
|
"Step": "Arrotondamento",
|
||||||
|
"Direction": "Verso",
|
||||||
|
"Date": "Valido dal",
|
||||||
|
"Scope": "Articoli",
|
||||||
|
"ScopeCategory": "Tutti quelli della categoria scelta",
|
||||||
|
"ScopeAll": "Tutti gli articoli",
|
||||||
|
"ScopeSelected": "Solo i selezionati ({0})",
|
||||||
|
"Apply": "Calcola i prezzi",
|
||||||
|
"Result": "{0} prezzi calcolati: restano evidenziati finché non salvi.",
|
||||||
|
"None": "Nessun prezzo da cambiare."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"items": {
|
||||||
|
"description": {
|
||||||
|
"required": "La descrizione è obbligatoria."
|
||||||
|
},
|
||||||
|
"code": {
|
||||||
|
"duplicate": "Codice già usato da un altro articolo."
|
||||||
|
},
|
||||||
|
"category": {
|
||||||
|
"required": "Il codice usa la categoria: scegline una."
|
||||||
|
},
|
||||||
|
"barcode": {
|
||||||
|
"invalid": "Codice a barre EAN non valido: controlla le cifre e il carattere di controllo.",
|
||||||
|
"duplicate": "Un altro articolo ha lo stesso codice a barre."
|
||||||
|
},
|
||||||
|
"customs-code": {
|
||||||
|
"invalid": "La nomenclatura combinata ha 8 cifre."
|
||||||
|
},
|
||||||
|
"value": {
|
||||||
|
"negative": "Il valore non può essere negativo."
|
||||||
|
},
|
||||||
|
"factor": {
|
||||||
|
"invalid": "Il fattore di conversione deve essere maggiore di zero."
|
||||||
|
},
|
||||||
|
"unit": {
|
||||||
|
"duplicate": "Unità già presente, o uguale all'unità base."
|
||||||
|
},
|
||||||
|
"detail": {
|
||||||
|
"required": "Campo obbligatorio.",
|
||||||
|
"duplicate": "Già presente nell'elenco."
|
||||||
|
},
|
||||||
|
"supplier": {
|
||||||
|
"invalid": "Scegli un fornitore."
|
||||||
|
},
|
||||||
|
"substitute": {
|
||||||
|
"self": "Un articolo non può sostituire sé stesso."
|
||||||
|
},
|
||||||
|
"price": {
|
||||||
|
"target": "Un prezzo va su un listino oppure su un cliente.",
|
||||||
|
"party": "I prezzi netti vanno su un cliente.",
|
||||||
|
"duplicate": "Esiste già un prezzo per lo stesso listino o cliente e la stessa data."
|
||||||
|
},
|
||||||
|
"party-code": {
|
||||||
|
"duplicate": "Codice già usato per un altro articolo di questa anagrafica."
|
||||||
|
},
|
||||||
|
"not-found": "Articolo non trovato.",
|
||||||
|
"price-list": {
|
||||||
|
"unknown": "Listino non trovato."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,7 +61,8 @@
|
|||||||
"TaxCodeDone": "Codice fiscale calcolato",
|
"TaxCodeDone": "Codice fiscale calcolato",
|
||||||
"TaxCodeMissing": "Servono cognome, nome, data, sesso e comune di nascita.",
|
"TaxCodeMissing": "Servono cognome, nome, data, sesso e comune di nascita.",
|
||||||
"Places": "{0} comuni con questo CAP: scegli quello giusto.",
|
"Places": "{0} comuni con questo CAP: scegli quello giusto.",
|
||||||
"Warnings": "Salvato con avvisi: {0}"
|
"Warnings": "Salvato con avvisi: {0}",
|
||||||
|
"AddItemCode": "Aggiungi codice articolo"
|
||||||
},
|
},
|
||||||
"Vies": {
|
"Vies": {
|
||||||
"Valid": "Partita IVA valida nel VIES",
|
"Valid": "Partita IVA valida nel VIES",
|
||||||
@@ -78,6 +79,7 @@
|
|||||||
"Terms": "Condizioni",
|
"Terms": "Condizioni",
|
||||||
"Fiscal": "Fiscale e SDI",
|
"Fiscal": "Fiscale e SDI",
|
||||||
"Banks": "Banche",
|
"Banks": "Banche",
|
||||||
|
"ItemCodes": "Articoli e codici",
|
||||||
"Notes": "Note e allegati",
|
"Notes": "Note e allegati",
|
||||||
"History": "Storico"
|
"History": "Storico"
|
||||||
},
|
},
|
||||||
@@ -198,7 +200,10 @@
|
|||||||
"BranchCode": "CAB",
|
"BranchCode": "CAB",
|
||||||
"BirthDate": "Data di nascita",
|
"BirthDate": "Data di nascita",
|
||||||
"Sex": "Sesso",
|
"Sex": "Sesso",
|
||||||
"BirthPlace": "Comune di nascita (codice catastale)"
|
"BirthPlace": "Comune di nascita (codice catastale)",
|
||||||
|
"ItemCode": "Codice dell'anagrafica",
|
||||||
|
"ItemId": "Nostro articolo",
|
||||||
|
"ItemDescription": "Descrizione dell'anagrafica"
|
||||||
},
|
},
|
||||||
"Kinds": {
|
"Kinds": {
|
||||||
"Customer": "Cliente",
|
"Customer": "Cliente",
|
||||||
@@ -237,12 +242,14 @@
|
|||||||
"Empty": {
|
"Empty": {
|
||||||
"Addresses": "Nessun altro indirizzo: la sede legale è nei dati principali.",
|
"Addresses": "Nessun altro indirizzo: la sede legale è nei dati principali.",
|
||||||
"Contacts": "Nessun contatto.",
|
"Contacts": "Nessun contatto.",
|
||||||
"Banks": "Nessun conto corrente."
|
"Banks": "Nessun conto corrente.",
|
||||||
|
"ItemCodes": "Nessun codice articolo di questa anagrafica."
|
||||||
},
|
},
|
||||||
"TermsHint": "Le condizioni si propongono nei documenti; nel documento si possono cambiare.",
|
"TermsHint": "Le condizioni si propongono nei documenti; nel documento si possono cambiare.",
|
||||||
"NoTerms": "Un prospect o un lead non ha condizioni: si impostano quando diventa cliente.",
|
"NoTerms": "Un prospect o un lead non ha condizioni: si impostano quando diventa cliente.",
|
||||||
"IntentHint": "Il residuo scende con le fatture emesse in esenzione (arriva con la fatturazione, M5).",
|
"IntentHint": "Il residuo scende con le fatture emesse in esenzione (arriva con la fatturazione, M5).",
|
||||||
"AccountsHint": "I sottoconti del partitario si creano alla prima registrazione (M7)."
|
"AccountsHint": "I sottoconti del partitario si creano alla prima registrazione (M7).",
|
||||||
|
"ItemCodesHint": "I codici con cui il cliente o il fornitore chiama i nostri articoli: nei suoi documenti la ricerca dell'articolo li trova."
|
||||||
},
|
},
|
||||||
"parties": {
|
"parties": {
|
||||||
"name": {
|
"name": {
|
||||||
|
|||||||
@@ -269,7 +269,8 @@
|
|||||||
"GapsAllowed": "Ammessi buchi di numerazione",
|
"GapsAllowed": "Ammessi buchi di numerazione",
|
||||||
"CurrencyCode": "Valuta",
|
"CurrencyCode": "Valuta",
|
||||||
"VatIncluded": "IVA inclusa",
|
"VatIncluded": "IVA inclusa",
|
||||||
"BasePriceListId": "Listino base",
|
"IsBase": "Listino base",
|
||||||
|
"BasePriceListId": "Derivato da",
|
||||||
"MarkupPercent": "% ricarico",
|
"MarkupPercent": "% ricarico",
|
||||||
"RoundingStep": "Arrotondamento",
|
"RoundingStep": "Arrotondamento",
|
||||||
"Formula": "Formula",
|
"Formula": "Formula",
|
||||||
@@ -451,6 +452,9 @@
|
|||||||
"number": {
|
"number": {
|
||||||
"range": "Numero fuori intervallo."
|
"range": "Numero fuori intervallo."
|
||||||
},
|
},
|
||||||
|
"price-list": {
|
||||||
|
"base-duplicate": "Un altro listino è già il listino base: toglilo da quello prima."
|
||||||
|
},
|
||||||
"inventory-reason": {
|
"inventory-reason": {
|
||||||
"transfer": "Un trasferimento non ha effetto di carico o scarico."
|
"transfer": "Un trasferimento non ha effetto di carico o scarico."
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -220,7 +220,8 @@ public static class TableScreens
|
|||||||
Fields =
|
Fields =
|
||||||
[
|
[
|
||||||
new(nameof(PriceList.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, Required = true, InGrid = true, Width = "80px", Span = 4 },
|
new(nameof(PriceList.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, Required = true, InGrid = true, Width = "80px", Span = 4 },
|
||||||
new(nameof(PriceList.VatIncluded), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 8 },
|
new(nameof(PriceList.VatIncluded), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 4 },
|
||||||
|
new(nameof(PriceList.IsBase), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 4 },
|
||||||
new(nameof(PriceList.ValidFrom), TableFieldKind.Date),
|
new(nameof(PriceList.ValidFrom), TableFieldKind.Date),
|
||||||
new(nameof(PriceList.ValidTo), TableFieldKind.Date),
|
new(nameof(PriceList.ValidTo), TableFieldKind.Date),
|
||||||
new(nameof(PriceList.BasePriceListId), TableFieldKind.Lookup) { Lookup = typeof(PriceList) },
|
new(nameof(PriceList.BasePriceListId), TableFieldKind.Lookup) { Lookup = typeof(PriceList) },
|
||||||
|
|||||||
@@ -316,3 +316,19 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
|
|||||||
.kh-sheet, .kh-sheet * { visibility: visible; }
|
.kh-sheet, .kh-sheet * { visibility: visible; }
|
||||||
.kh-sheet { position: absolute; left: 0; top: 0; zoom: 1 !important; width: 210mm; min-height: 0; box-shadow: none; margin: 0; }
|
.kh-sheet { position: absolute; left: 0; top: 0; zoom: 1 !important; width: 210mm; min-height: 0; box-shadow: none; margin: 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Price grid (mockup 018): filter bar, cells changed and not saved, prices derived from another list. */
|
||||||
|
.kh-pricebar { display: flex; align-items: flex-end; gap: 12px; flex-wrap: wrap; margin-bottom: 10px; }
|
||||||
|
.kh-pricebar .grow { flex: 1; }
|
||||||
|
.kh-pricebar > .f { min-width: 200px; }
|
||||||
|
.kh-pricebar-date { width: 160px; }
|
||||||
|
.kh-pricebar-party { width: 340px; max-width: 100%; }
|
||||||
|
.kh-pricebar-check { display: flex; gap: 6px; align-items: center; height: 30px; font-size: 12.5px; }
|
||||||
|
/* The filter bar and the hint take room: the grid is shorter than in the other radars and the radar does not shrink under the hint. */
|
||||||
|
.kh-radar.kh-pricegrid { flex: none; }
|
||||||
|
.kh-pricegrid .kh-radarpanel .kh-gridwrap { height: calc(100vh - 470px); min-height: 240px; }
|
||||||
|
.kh-pricehint { margin-top: 10px; }
|
||||||
|
.kh-pricefoot { margin-left: 14px; }
|
||||||
|
/* Stronger than the striped and hovered rows, so every pending cell shows. */
|
||||||
|
.grid tbody tr td.kh-changed { background: var(--kh-warn-soft); font-weight: 600; }
|
||||||
|
.grid td.kh-derived { color: var(--kh-text-2); font-style: italic; }
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using Khaemhat.Application.Items;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Core.Parties;
|
||||||
|
using Khaemhat.Core.Tables;
|
||||||
|
|
||||||
|
namespace Khaemhat.Application.Tests;
|
||||||
|
|
||||||
|
/// <summary>The search of the price of a line (SPEC §11.3, ADR 0030): net price, list, base list, item; validity and derived lists.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class PriceBookTests
|
||||||
|
{
|
||||||
|
private static readonly DateOnly Jan = new(2026, 1, 1);
|
||||||
|
private static readonly DateOnly Jun = new(2026, 6, 1);
|
||||||
|
private static readonly PriceList Base = new() { Id = 1, Code = "BASE", Description = "Base", IsBase = true };
|
||||||
|
private static readonly PriceList Public = new() { Id = 2, Code = "PUBB", Description = "Pubblico", BasePriceListId = 1, MarkupPercent = 45m, RoundingStep = 0.10m };
|
||||||
|
private static readonly PriceList Resellers = new() { Id = 3, Code = "RIV", Description = "Rivenditori", BasePriceListId = 1, MarkupPercent = -10m };
|
||||||
|
private static readonly PriceList Expired = new() { Id = 4, Code = "OLD", Description = "Scaduto", ValidTo = new DateOnly(2025, 12, 31) };
|
||||||
|
private static readonly Item Valve = new() { Id = 10, Code = "VALV-0001", Description = "Valvola", Price = 30m };
|
||||||
|
private static readonly Item Service = new() { Id = 11, Code = "SERV-0001", Description = "Manodopera", Price = 38m };
|
||||||
|
|
||||||
|
private static PriceBook Book() => new(
|
||||||
|
[Base, Public, Resellers, Expired],
|
||||||
|
[
|
||||||
|
new ItemPrice { ItemId = 10, PriceListId = 1, Price = 30.70m, ValidFrom = new DateOnly(2025, 1, 1) },
|
||||||
|
new ItemPrice { ItemId = 10, PriceListId = 1, Price = 32m, ValidFrom = Jan },
|
||||||
|
new ItemPrice { ItemId = 10, PriceListId = 1, Price = 34m, ValidFrom = Jun },
|
||||||
|
new ItemPrice { ItemId = 10, PriceListId = 3, Price = 27.50m, ValidFrom = Jan },
|
||||||
|
new ItemPrice { ItemId = 10, PriceListId = 4, Price = 1m },
|
||||||
|
new ItemPrice { ItemId = 10, PartyId = 99, Price = 30.40m, ValidFrom = Jan },
|
||||||
|
]);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ListPrice_IsTheLatestStartNotAfterTheDate()
|
||||||
|
{
|
||||||
|
var book = Book();
|
||||||
|
Assert.AreEqual(30.70m, book.ListPrice(10, 1, new DateOnly(2025, 6, 1)).Price);
|
||||||
|
Assert.AreEqual(32m, book.ListPrice(10, 1, new DateOnly(2026, 5, 31)).Price);
|
||||||
|
Assert.AreEqual(new PriceCell(34m, false, Jun), book.ListPrice(10, 1, new DateOnly(2026, 7, 1)));
|
||||||
|
Assert.IsNull(book.ListPrice(10, 1, new DateOnly(2024, 12, 31)).Price, "Nothing before the first price.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DerivedList_TakesTheBaseWithMarkupAndRounding_UnlessItHasItsOwn()
|
||||||
|
{
|
||||||
|
var book = Book();
|
||||||
|
Assert.AreEqual(new PriceCell(46.40m, true, Jan), book.ListPrice(10, 2, new DateOnly(2026, 3, 1)), "32 + 45% = 46.40.");
|
||||||
|
Assert.AreEqual(49.30m, book.ListPrice(10, 2, Jun).Price, "34 + 45% = 49.30.");
|
||||||
|
Assert.AreEqual(new PriceCell(27.50m, false, Jan), book.ListPrice(10, 3, Jun), "Its own price wins over the derived one.");
|
||||||
|
Assert.AreEqual(PriceCell.Empty, book.ListPrice(11, 2, Jun), "No base price, nothing to derive.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void Quote_SearchesNet_ThenList_ThenBase_ThenItem()
|
||||||
|
{
|
||||||
|
var book = Book();
|
||||||
|
Assert.AreEqual(new PriceQuote(30.40m, PriceSource.PartyNet, null, false, Jan), book.Quote(Valve, 99, 2, Jun));
|
||||||
|
Assert.AreEqual(PriceSource.PartyPriceList, book.Quote(Valve, 5, 3, Jun).Source);
|
||||||
|
Assert.AreEqual(27.50m, book.Quote(Valve, 5, 3, Jun).Price);
|
||||||
|
Assert.AreEqual(new PriceQuote(34m, PriceSource.BasePriceList, 1, false, Jun), book.Quote(Valve, 5, 4, Jun), "An expired list is skipped.");
|
||||||
|
Assert.AreEqual(new PriceQuote(38m, PriceSource.Item, null, false, null), book.Quote(Service, null, null, Jun));
|
||||||
|
Assert.AreEqual(PriceQuote.None, book.Quote(new Item { Id = 12 }, null, null, Jun));
|
||||||
|
Assert.AreEqual(Base, book.Base);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void BaseOf_IsTheMarkedList_ElseTheCodeBase()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(2, PriceBook.BaseOf([new PriceList { Id = 1, Code = "BASE" }, new PriceList { Id = 2, Code = "A", IsBase = true }])!.Id);
|
||||||
|
Assert.AreEqual(1, PriceBook.BaseOf([new PriceList { Id = 1, Code = "BASE" }, new PriceList { Id = 2, Code = "A" }])!.Id);
|
||||||
|
Assert.IsNull(PriceBook.BaseOf([new PriceList { Id = 1, Code = "BASE", Disabled = true }]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void Discounts_ComeFromTheTerms_ButNotOnANetPrice()
|
||||||
|
{
|
||||||
|
var terms = new PartySalesTerms { Discount1 = 10m, Discount2 = 5m };
|
||||||
|
var fromList = new PriceQuote(100m, PriceSource.BasePriceList, 1, false, Jan);
|
||||||
|
var discounts = PriceBook.Discounts(fromList, terms);
|
||||||
|
Assert.AreEqual("10+5", discounts.Formula);
|
||||||
|
Assert.AreEqual(14.5m, discounts.Equivalent);
|
||||||
|
Assert.AreEqual(DiscountQuote.None, PriceBook.Discounts(fromList with { Source = PriceSource.PartyNet }, terms));
|
||||||
|
Assert.AreEqual(DiscountQuote.None, PriceBook.Discounts(fromList, new PartySalesTerms()));
|
||||||
|
Assert.AreEqual(DiscountQuote.None, PriceBook.Discounts(fromList, null));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using Khaemhat.Core.Items;
|
||||||
|
|
||||||
|
namespace Khaemhat.Core.Tests.Common;
|
||||||
|
|
||||||
|
/// <summary>The rounding of the prices of a list (issue #42, mockup 018): steps of 0.10, 0.50, 1.00, up or down.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class PriceRoundingTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("46.43", "0.10", RoundingDirection.Nearest, "46.40")]
|
||||||
|
[DataRow("46.45", "0.10", RoundingDirection.Nearest, "46.50")]
|
||||||
|
[DataRow("46.41", "0.10", RoundingDirection.Up, "46.50")]
|
||||||
|
[DataRow("46.49", "0.10", RoundingDirection.Down, "46.40")]
|
||||||
|
[DataRow("12.345", "0.50", RoundingDirection.Nearest, "12.50")]
|
||||||
|
[DataRow("12.345", "0.50", RoundingDirection.Down, "12.00")]
|
||||||
|
[DataRow("12.01", "1.00", RoundingDirection.Up, "13.00")]
|
||||||
|
[DataRow("12.00", "1.00", RoundingDirection.Up, "12.00")]
|
||||||
|
[DataRow("1.23456", "0", RoundingDirection.Nearest, "1.23")]
|
||||||
|
[DataRow("0.123456", "0.0001", RoundingDirection.Nearest, "0.1235")]
|
||||||
|
public void Round_GoesToTheStep(string value, string step, RoundingDirection direction, string expected) =>
|
||||||
|
Assert.AreEqual(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture),
|
||||||
|
PriceRounding.Round(decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture), decimal.Parse(step, System.Globalization.CultureInfo.InvariantCulture), direction));
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void Round_KeepsTwoDecimals_WhenTheRestAreZeros() =>
|
||||||
|
Assert.AreEqual("46.40", PriceRounding.Round(46.4000m, 0.10m).ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void Change_AddsOrTakesOffAPercent()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(46.4m, PriceRounding.Change(32m, 45m));
|
||||||
|
Assert.AreEqual(28.8m, PriceRounding.Change(32m, -10m));
|
||||||
|
Assert.AreEqual(32m, PriceRounding.Change(32m, 0m));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void Margin_IsOnThePrice()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(45m, PriceRounding.Margin(32m, 17.60m));
|
||||||
|
Assert.AreEqual(-10m, PriceRounding.Margin(10m, 11m));
|
||||||
|
Assert.IsNull(PriceRounding.Margin(0m, 5m));
|
||||||
|
Assert.IsNull(PriceRounding.Margin(10m, null));
|
||||||
|
Assert.IsNull(PriceRounding.Margin(null, 5m));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -77,6 +77,7 @@ public sealed class MappingTests
|
|||||||
"goods_appearances", "delivery_terms", "transport_reasons", "inventory_reasons", "warehouses", "item_categories", "party_categories", "price_lists",
|
"goods_appearances", "delivery_terms", "transport_reasons", "inventory_reasons", "warehouses", "item_categories", "party_categories", "price_lists",
|
||||||
"discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences",
|
"discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences",
|
||||||
"parties", "party_addresses", "party_contacts", "party_bank_accounts", "party_sales_terms", "party_purchase_terms", "party_fiscal",
|
"parties", "party_addresses", "party_contacts", "party_bank_accounts", "party_sales_terms", "party_purchase_terms", "party_fiscal",
|
||||||
|
"items", "item_uoms", "item_barcodes", "item_prices", "item_suppliers", "item_substitutes", "party_item_codes",
|
||||||
];
|
];
|
||||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using Khaemhat.Application.Items;
|
||||||
|
using Khaemhat.Application.Querying;
|
||||||
|
using Khaemhat.Application.Security;
|
||||||
|
using Khaemhat.Application.Seeding;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Core.Security;
|
||||||
|
using Khaemhat.Core.Validation;
|
||||||
|
using Khaemhat.Web.Tests.Hosting;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Khaemhat.Web.Tests.Items;
|
||||||
|
|
||||||
|
/// <summary>The demo items (SPEC §14, issue #42): 120 per scale, valid bar codes, derived lists, and every item passes the checks.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class DemoItemsTests
|
||||||
|
{
|
||||||
|
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void Catalogue_HasTheItemsOfTheSpecification_WithValidBarCodes()
|
||||||
|
{
|
||||||
|
var catalogue = DemoItemsSeeder.Catalogue();
|
||||||
|
Assert.HasCount(DemoItemsSeeder.ItemsPerScale, catalogue);
|
||||||
|
Assert.HasCount(catalogue.Count, catalogue.Select(i => i.Description).Distinct().ToList(), "No description twice.");
|
||||||
|
Assert.IsTrue(catalogue.All(i => i.Kind != ItemKind.Goods || i.Price > 0));
|
||||||
|
Assert.IsTrue(catalogue.Any(i => i.Kind == ItemKind.Service) && catalogue.Any(i => i.Kind == ItemKind.Expense) && catalogue.Any(i => i.Kind == ItemKind.Text));
|
||||||
|
foreach (var n in new[] { 1, 99, 500_123 })
|
||||||
|
{
|
||||||
|
Assert.IsTrue(EanValidator.IsValid(DemoItemsSeeder.Ean(n)), DemoItemsSeeder.Ean(n));
|
||||||
|
Assert.StartsWith("200", DemoItemsSeeder.Ean(n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task DemoSeed_FillsAnEmptyCompanyOnce_WithItemsThatPassTheChecks()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var runner = app.Services.GetRequiredService<SeedRunner>();
|
||||||
|
var items = app.Services.GetRequiredService<ItemService>();
|
||||||
|
var prices = app.Services.GetRequiredService<PriceListService>();
|
||||||
|
var first = await runner.RunAsync(company, SeedKind.Demo);
|
||||||
|
Assert.AreEqual(DemoItemsSeeder.ItemsPerScale, first.Added["items"]);
|
||||||
|
Assert.AreEqual(2, first.Added["price_lists"]);
|
||||||
|
Assert.IsGreaterThan(0, first.Added["item_suppliers"]);
|
||||||
|
Assert.IsGreaterThan(0, first.Added["party_item_codes"]);
|
||||||
|
Assert.IsEmpty((await runner.RunAsync(company, SeedKind.Demo)).Added, "Only an empty company gets the demo data.");
|
||||||
|
|
||||||
|
var lists = await prices.ListsAsync(Root, company);
|
||||||
|
CollectionAssert.AreEqual(new[] { "BASE", "PUBB", "RIV" }, lists.Select(l => l.Code).ToArray());
|
||||||
|
var grid = await prices.GridAsync(Root, company, new ListQuery { Search = "sfera 1/2", Limit = 10 }, DateOnly.FromDateTime(DateTime.Today), null);
|
||||||
|
var lever = grid.Page.Items[0];
|
||||||
|
Assert.IsTrue(lever.Prices[lists[1].Id].Derived, "The public list is derived from the base one.");
|
||||||
|
Assert.IsNotNull(lever.AverageCost);
|
||||||
|
|
||||||
|
var all = (await items.ListAsync(Root, company, new ListQuery { Limit = 200 })).Items;
|
||||||
|
Assert.HasCount(DemoItemsSeeder.ItemsPerScale, all);
|
||||||
|
foreach (var row in all)
|
||||||
|
{
|
||||||
|
var record = (await items.GetAsync(Root, company, row.Id))!;
|
||||||
|
Assert.IsTrue(record.Item.IsDemo);
|
||||||
|
var errors = (await items.ValidateAsync(Root, company, record)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||||
|
Assert.IsEmpty(errors, row.Code + " " + row.Description + ": " + string.Join(", ", errors));
|
||||||
|
}
|
||||||
|
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Scale_RepeatsTheCatalogue()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var report = await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo, 2);
|
||||||
|
Assert.AreEqual(2 * DemoItemsSeeder.ItemsPerScale, report.Added["items"]);
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Web.Items;
|
||||||
|
using Khaemhat.Web.Tests.Shell;
|
||||||
|
|
||||||
|
namespace Khaemhat.Web.Tests.Items;
|
||||||
|
|
||||||
|
/// <summary>Addresses, tabs and cell values of the item screens (issue #42).</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ItemScreensTests
|
||||||
|
{
|
||||||
|
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TabOf_FindsTheTabOfAField()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Main, ItemScreens.TabOf("Barcode"));
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Units, ItemScreens.TabOf("Units.0.Factor"));
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Barcodes, ItemScreens.TabOf("Barcodes.2.Code"));
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Prices, ItemScreens.TabOf("Prices.1.PartyId"));
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Suppliers, ItemScreens.TabOf("Suppliers.0.PartyId"));
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Substitutes, ItemScreens.TabOf("Substitutes.0.SubstituteId"));
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Notes, ItemScreens.TabOf("Notes"));
|
||||||
|
Assert.AreEqual(ItemScreens.Tabs.Main, ItemScreens.TabOf(null));
|
||||||
|
Assert.AreEqual("anagrafiche/articoli/12", ItemScreens.RecordUrl(12));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("€ 1.180,00", "1180")]
|
||||||
|
[DataRow("32,5", "32.5")]
|
||||||
|
[DataRow(" 0,12345 ", "0.1235")]
|
||||||
|
public void TryParsePrice_ReadsWhatTheCellShows(string text, string expected)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(ItemScreens.TryParsePrice(text, Italian, out var price));
|
||||||
|
Assert.AreEqual(decimal.Parse(expected, CultureInfo.InvariantCulture), price);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TryParsePrice_EmptyIsNoPrice_AndRefusesTheRest()
|
||||||
|
{
|
||||||
|
Assert.IsTrue(ItemScreens.TryParsePrice(" ", Italian, out var none));
|
||||||
|
Assert.IsNull(none);
|
||||||
|
Assert.IsFalse(ItemScreens.TryParsePrice("-3", Italian, out _));
|
||||||
|
Assert.IsFalse(ItemScreens.TryParsePrice("abc", Italian, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MarginText_IsAPercentOfThePrice()
|
||||||
|
{
|
||||||
|
Assert.AreEqual("45%", ItemScreens.MarginText(32m, 17.60m, Italian));
|
||||||
|
Assert.AreEqual("33,3%", ItemScreens.MarginText(30m, 20m, Italian));
|
||||||
|
Assert.IsNull(ItemScreens.MarginText(null, 20m, Italian));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryChoice_HasAText()
|
||||||
|
{
|
||||||
|
Assert.IsTrue(ItemScreens.Choices<ItemKind>(ShellTests.Texts, "Kinds").All(o => !o.Text.StartsWith("Items.", StringComparison.Ordinal)));
|
||||||
|
Assert.IsTrue(ItemScreens.Choices<RoundingDirection>(ShellTests.Texts, "Directions").All(o => !o.Text.StartsWith("Items.", StringComparison.Ordinal)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
using Khaemhat.Application.Items;
|
||||||
|
using Khaemhat.Application.Parties;
|
||||||
|
using Khaemhat.Application.Querying;
|
||||||
|
using Khaemhat.Application.Security;
|
||||||
|
using Khaemhat.Application.Tables;
|
||||||
|
using Khaemhat.Core.Items;
|
||||||
|
using Khaemhat.Core.Parties;
|
||||||
|
using Khaemhat.Core.Security;
|
||||||
|
using Khaemhat.Core.Tables;
|
||||||
|
using Khaemhat.Web.Tests.Hosting;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Khaemhat.Web.Tests.Items;
|
||||||
|
|
||||||
|
/// <summary>Items and price lists on a real instance (issue #42): codes, details, checks, costs, search, prices with validity.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ItemServiceTests
|
||||||
|
{
|
||||||
|
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Item_GetsTheCodeOfItsCategory_AndItsDetailsAreSavedWithIt()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var items = app.Services.GetRequiredService<ItemService>();
|
||||||
|
var (category, box, _) = await TablesAsync(app, company);
|
||||||
|
var substitute = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("Valvola a farfalla 1/2\"", category));
|
||||||
|
|
||||||
|
var record = await items.NewAsync(Root, company);
|
||||||
|
Assert.AreEqual(ItemKind.Goods, record.Item.Kind);
|
||||||
|
Assert.IsTrue(record.Item.Stocked);
|
||||||
|
Assert.IsNotNull(record.Item.UnitOfMeasureId, "PZ by default.");
|
||||||
|
Assert.IsNotNull(record.Item.SalesTaxCodeId, "VAT 22 by default.");
|
||||||
|
record.Item.Description = " Valvola a sfera 1/2\" ";
|
||||||
|
record.Item.CategoryId = category;
|
||||||
|
record.Item.Barcode = "2000000000015";
|
||||||
|
record.Units.Add(new ItemUnit { UnitOfMeasureId = box, Factor = 10m });
|
||||||
|
record.Barcodes.Add(new ItemBarcode { Code = " OLD-77 " });
|
||||||
|
record.Substitutes.Add(new ItemSubstitute { SubstituteId = substitute.Item.Id });
|
||||||
|
var saved = await items.SaveAsync(Root, company, record);
|
||||||
|
|
||||||
|
Assert.AreEqual("VALV-0002", saved.Item.Code);
|
||||||
|
Assert.AreEqual("Valvola a sfera 1/2\"", saved.Item.Description);
|
||||||
|
Assert.AreEqual(10m, saved.Units.Single().Factor);
|
||||||
|
Assert.AreEqual("OLD-77", saved.Barcodes.Single().Code);
|
||||||
|
Assert.AreEqual(substitute.Item.Id, saved.Substitutes.Single().SubstituteId);
|
||||||
|
|
||||||
|
// A service is never in stock; the search finds the alternative code exactly.
|
||||||
|
saved.Item.Kind = ItemKind.Service;
|
||||||
|
var service = await items.SaveAsync(Root, company, saved);
|
||||||
|
Assert.IsFalse(service.Item.Stocked);
|
||||||
|
Assert.AreEqual(saved.Item.Id, (await items.SearchAsync(Root, company, "OLD-77")).Single().Id);
|
||||||
|
Assert.IsNotEmpty(await items.HistoryAsync(Root, company, saved.Item.Id));
|
||||||
|
|
||||||
|
var list = await items.ListAsync(Root, company, new ListQuery { Search = "sfera" });
|
||||||
|
Assert.AreEqual("VALV-0002", list.Items.Single().Code);
|
||||||
|
|
||||||
|
// Used as a substitute, the other item is disabled instead of deleted.
|
||||||
|
Assert.AreEqual(ItemDeleteOutcome.Disabled, await items.DeleteAsync(Root, company, substitute.Item.Id));
|
||||||
|
Assert.AreEqual(ItemDeleteOutcome.Deleted, await items.DeleteAsync(Root, company, saved.Item.Id));
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Save_RefusesWhatTheRulesDoNotAllow()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var items = app.Services.GetRequiredService<ItemService>();
|
||||||
|
var (category, box, _) = await TablesAsync(app, company);
|
||||||
|
var other = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId, r.Item.Barcode) = ("Altro", category, "2000000000022"));
|
||||||
|
|
||||||
|
async Task<string[]> ErrorsAsync(Action<ItemRecord> fill)
|
||||||
|
{
|
||||||
|
var record = await items.NewAsync(Root, company);
|
||||||
|
record.Item.Description = "Prova";
|
||||||
|
record.Item.CategoryId = category;
|
||||||
|
fill(record);
|
||||||
|
return [.. (await items.ValidateAsync(Root, company, record)).Select(p => p.Field + ":" + p.Code + (p.IsWarning ? "!" : string.Empty))];
|
||||||
|
}
|
||||||
|
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Description = " "), "Description:" + ItemService.DescriptionRequired);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.CategoryId = null), "CategoryId:" + ItemService.CategoryRequired);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Code = other.Item.Code), "Code:" + ItemService.CodeDuplicate);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Barcode = "2000000000016"), "Barcode:" + ItemService.BarcodeInvalid);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Barcode = "2000000000022"), "Barcode:" + ItemService.BarcodeDuplicate,
|
||||||
|
"By default the code rules want the bar code unique.");
|
||||||
|
var rules = app.Services.GetRequiredService<CodeRuleService>();
|
||||||
|
await rules.SaveAsync(Root, company, [.. (await rules.RulesAsync(Root, company)).Select(r => r with { UniqueBarcode = false })]);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Barcode = "2000000000022"), "Barcode:" + ItemService.BarcodeDuplicate + "!",
|
||||||
|
"Without the rule the same bar code is a warning.");
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.CustomsCode = "8481"), "CustomsCode:" + ItemService.CustomsCodeInvalid);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.MinimumStock = -1), "MinimumStock:" + ItemService.NotNegative);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Units.Add(new ItemUnit { UnitOfMeasureId = box, Factor = 0 })), "Units.0.Factor:" + ItemService.FactorInvalid);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Units.Add(new ItemUnit { UnitOfMeasureId = r.Item.UnitOfMeasureId!.Value, Factor = 1 })), "Units.0.UnitOfMeasureId:" + ItemService.UnitDuplicate);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Units.Add(new ItemUnit())), "Units.0.UnitOfMeasureId:" + ItemService.DetailRequired);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Barcodes.AddRange([new ItemBarcode { Code = "X1" }, new ItemBarcode { Code = "X1" }])), "Barcodes.1.Code:" + ItemService.DetailDuplicate);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Prices.Add(new ItemPrice { Price = 1 })), "Prices.0.PriceListId:" + ItemService.PriceTarget);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Prices.Add(new ItemPrice { PartyId = 0, Price = 1 })), "Prices.0.PartyId:" + ItemService.DetailRequired);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Suppliers.Add(new ItemSupplier())), "Suppliers.0.PartyId:" + ItemService.DetailRequired);
|
||||||
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Substitutes.Add(new ItemSubstitute())), "Substitutes.0.SubstituteId:" + ItemService.DetailRequired);
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task Costs_AreHiddenAndKept_ForWhoCannotSeeThem()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var items = app.Services.GetRequiredService<ItemService>();
|
||||||
|
var users = app.Services.GetRequiredService<UserService>();
|
||||||
|
var (category, _, _) = await TablesAsync(app, company);
|
||||||
|
var item = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId, r.Item.StandardCost) = ("Caldaia", category, 800m));
|
||||||
|
var (user, _) = await users.CreateAsync(Root, company, new NewCompanyUser("magazzino", "Magazzino", null, UserKind.Human, ["WAREHOUSE"], new UserFlags(false, false, false, false)));
|
||||||
|
var warehouse = new Actor("magazzino", UserLevel.Standard, null, user.Id, company);
|
||||||
|
|
||||||
|
Assert.IsFalse(await items.CanSeeCostsAsync(warehouse, company));
|
||||||
|
var seen = (await items.GetAsync(warehouse, company, item.Item.Id))!;
|
||||||
|
Assert.IsNull(seen.Item.StandardCost);
|
||||||
|
seen.Item.Brand = "Termodemo";
|
||||||
|
seen.Item.StandardCost = 1m;
|
||||||
|
await items.SaveAsync(warehouse, company, seen);
|
||||||
|
Assert.AreEqual(800m, (await items.GetAsync(Root, company, item.Item.Id))!.Item.StandardCost, "The cost stays as it was.");
|
||||||
|
Assert.IsNull((await items.ListAsync(warehouse, company, new ListQuery())).Items.Single().AverageCost);
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task PriceGrid_ReadsAndWritesPricesAtADate_KeepingTheOlderOnes()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var items = app.Services.GetRequiredService<ItemService>();
|
||||||
|
var prices = app.Services.GetRequiredService<PriceListService>();
|
||||||
|
var tables = app.Services.GetRequiredService<TableService>();
|
||||||
|
var (category, _, baseList) = await TablesAsync(app, company);
|
||||||
|
var derived = await tables.SaveAsync(Root, company, new PriceList { Code = "PUBB", Description = "Pubblico", BasePriceListId = baseList, MarkupPercent = 45m, RoundingStep = 0.10m });
|
||||||
|
var valve = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("Valvola", category));
|
||||||
|
var customer = await CustomerAsync(app, company);
|
||||||
|
var jan = new DateOnly(2026, 1, 1);
|
||||||
|
var jun = new DateOnly(2026, 6, 1);
|
||||||
|
|
||||||
|
Assert.AreEqual(2, await prices.SaveAsync(Root, company,
|
||||||
|
[new PriceEdit(valve.Item.Id, baseList, null, 32m, jan), new PriceEdit(valve.Item.Id, null, customer, 30.40m, jan)]));
|
||||||
|
Assert.AreEqual(1, await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, 34m, jun)]));
|
||||||
|
Assert.AreEqual(0, await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, 34m, new DateOnly(2026, 7, 1))]),
|
||||||
|
"The price in effect is not written again.");
|
||||||
|
|
||||||
|
var march = await prices.GridAsync(Root, company, new ListQuery(), new DateOnly(2026, 3, 1), customer);
|
||||||
|
var row = march.Page.Items.Single();
|
||||||
|
Assert.AreEqual(baseList, march.Lists[0].Id, "The base list first.");
|
||||||
|
Assert.AreEqual(32m, row.Prices[baseList].Price);
|
||||||
|
Assert.AreEqual(new PriceCell(46.40m, true, jan), row.Prices[derived.Id]);
|
||||||
|
Assert.AreEqual(30.40m, row.Net!.Price);
|
||||||
|
Assert.AreEqual(34m, (await prices.GridAsync(Root, company, new ListQuery(), jun, null)).Page.Items.Single().Prices[baseList].Price);
|
||||||
|
|
||||||
|
// The quote of a document line: net price for the customer, base list for anybody else.
|
||||||
|
Assert.AreEqual((30.40m, PriceSource.PartyNet), Short(await prices.QuoteAsync(Root, company, valve.Item.Id, customer, null, jun)));
|
||||||
|
Assert.AreEqual((34m, PriceSource.BasePriceList), Short(await prices.QuoteAsync(Root, company, valve.Item.Id, null, null, jun)));
|
||||||
|
Assert.AreEqual((49.30m, PriceSource.PartyPriceList), Short(await prices.QuoteAsync(Root, company, valve.Item.Id, null, derived.Id, jun)));
|
||||||
|
|
||||||
|
// The same day changes the row; no price removes it.
|
||||||
|
await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, 35m, jun)]);
|
||||||
|
Assert.AreEqual(35m, (await prices.GridAsync(Root, company, new ListQuery(), jun, null)).Page.Items.Single().Prices[baseList].Price);
|
||||||
|
await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, null, jun)]);
|
||||||
|
Assert.AreEqual(32m, (await prices.GridAsync(Root, company, new ListQuery(), jun, null)).Page.Items.Single().Prices[baseList].Price);
|
||||||
|
Assert.IsTrue((await items.HistoryAsync(Root, company, valve.Item.Id)).Count >= 4, "Every price goes in the history of the item.");
|
||||||
|
|
||||||
|
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, null, null, 1m, jun)]));
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task BulkUpdate_ComputesTheChangedPrices_WithoutSavingThem()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var items = app.Services.GetRequiredService<ItemService>();
|
||||||
|
var prices = app.Services.GetRequiredService<PriceListService>();
|
||||||
|
var tables = app.Services.GetRequiredService<TableService>();
|
||||||
|
var (category, _, baseList) = await TablesAsync(app, company);
|
||||||
|
var resellers = await tables.SaveAsync(Root, company, new PriceList { Code = "RIV", Description = "Rivenditori" });
|
||||||
|
var a = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("A", category));
|
||||||
|
var b = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("B", category));
|
||||||
|
var date = new DateOnly(2026, 1, 1);
|
||||||
|
await prices.SaveAsync(Root, company, [new PriceEdit(a.Item.Id, baseList, null, 10m, date), new PriceEdit(b.Item.Id, baseList, null, 21.37m, date)]);
|
||||||
|
|
||||||
|
var up = await prices.PreviewAsync(Root, company, new BulkUpdate { PriceListId = baseList, Percent = 5m, RoundingStep = 0.50m, Direction = RoundingDirection.Up, Date = date });
|
||||||
|
CollectionAssert.AreEqual(new[] { 10.50m, 22.50m }, up.Select(e => e.Price).ToArray());
|
||||||
|
Assert.AreEqual(10m, (await prices.GridAsync(Root, company, new ListQuery(), date, null)).Page.Items.First(r => r.ItemId == a.Item.Id).Prices[baseList].Price, "Nothing saved.");
|
||||||
|
|
||||||
|
var fromBase = await prices.PreviewAsync(Root, company,
|
||||||
|
new BulkUpdate { PriceListId = resellers.Id, SourcePriceListId = baseList, Percent = -10m, RoundingStep = 0.10m, Date = date, ItemIds = [b.Item.Id] });
|
||||||
|
Assert.AreEqual(new PriceEdit(b.Item.Id, resellers.Id, null, 19.20m, date), fromBase.Single());
|
||||||
|
Assert.IsEmpty(await prices.PreviewAsync(Root, company, new BulkUpdate { PriceListId = baseList, Date = date }), "No change, nothing to write.");
|
||||||
|
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => prices.PreviewAsync(Root, company, new BulkUpdate { PriceListId = 999, Date = date }));
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task PartyItemCodes_AreSavedWithTheParty_AndFoundByTheSearchOfItsDocuments()
|
||||||
|
{
|
||||||
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||||
|
await using (app)
|
||||||
|
{
|
||||||
|
var items = app.Services.GetRequiredService<ItemService>();
|
||||||
|
var parties = app.Services.GetRequiredService<PartyService>();
|
||||||
|
var (category, _, _) = await TablesAsync(app, company);
|
||||||
|
var valve = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("Valvola", category));
|
||||||
|
var customer = await CustomerAsync(app, company);
|
||||||
|
|
||||||
|
var record = (await parties.GetAsync(Root, company, customer))!;
|
||||||
|
record.ItemCodes.Add(new PartyItemCode { ItemId = valve.Item.Id, Code = " RI-100 " });
|
||||||
|
record.ItemCodes.Add(new PartyItemCode { ItemId = valve.Item.Id, Code = "RI-100" });
|
||||||
|
Assert.IsTrue((await parties.ValidateAsync(Root, company, record)).Any(p => p.Field == "ItemCodes.1.Code" && p.Code == ItemService.PartyCodeDuplicate));
|
||||||
|
record.ItemCodes.RemoveAt(1);
|
||||||
|
var saved = await parties.SaveAsync(Root, company, record);
|
||||||
|
Assert.AreEqual("RI-100", saved.ItemCodes.Single().Code);
|
||||||
|
|
||||||
|
Assert.AreEqual(valve.Item.Id, (await items.SearchAsync(Root, company, "RI-100", customer)).Single().Id);
|
||||||
|
Assert.IsEmpty(await items.SearchAsync(Root, company, "RI-100"), "Another party does not use that code.");
|
||||||
|
Assert.AreEqual("Valvola", (await items.RowsAsync(Root, company, [valve.Item.Id])).Single().Description);
|
||||||
|
Assert.AreEqual(customer, (await parties.RowsAsync(Root, company, [customer])).Single().Id);
|
||||||
|
await app.StopAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (decimal? Price, PriceSource Source) Short((PriceQuote Price, DiscountQuote Discounts) quote) => (quote.Price.Price, quote.Price.Source);
|
||||||
|
|
||||||
|
private static async Task<ItemRecord> SaveAsync(ItemService items, string company, Action<ItemRecord> fill)
|
||||||
|
{
|
||||||
|
var record = await items.NewAsync(Root, company);
|
||||||
|
fill(record);
|
||||||
|
return await items.SaveAsync(Root, company, record);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<(long Category, long Box, long BaseList)> TablesAsync(Microsoft.AspNetCore.Builder.WebApplication app, string company)
|
||||||
|
{
|
||||||
|
var tables = app.Services.GetRequiredService<TableService>();
|
||||||
|
var category = await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" });
|
||||||
|
var units = await tables.ListAsync<UnitOfMeasure>(Root, company, new ListQuery { Limit = 100 });
|
||||||
|
var lists = await tables.ListAsync<PriceList>(Root, company, new ListQuery { Limit = 100 });
|
||||||
|
return (category.Id, units.Items.Single(u => u.Code == "CT").Id, lists.Items.Single(l => l.IsBase).Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<long> CustomerAsync(Microsoft.AspNetCore.Builder.WebApplication app, string company)
|
||||||
|
{
|
||||||
|
var parties = app.Services.GetRequiredService<PartyService>();
|
||||||
|
var record = await parties.NewAsync(Root, company, PartyKind.Customer);
|
||||||
|
record.Party.Name = "Rossi Impianti S.r.l.";
|
||||||
|
record.Party.VatNumber = "01234567897";
|
||||||
|
return (await parties.SaveAsync(Root, company, record)).Party.Id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -271,6 +271,6 @@ public sealed partial class LocalizationRulesTests
|
|||||||
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
|
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
|
||||||
private static partial Regex EntityPattern();
|
private static partial Regex EntityPattern();
|
||||||
|
|
||||||
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties)\\.[A-Za-z0-9_.]+)\"")]
|
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items)\\.[A-Za-z0-9_.]+)\"")]
|
||||||
private static partial Regex KeyPattern();
|
private static partial Regex KeyPattern();
|
||||||
}
|
}
|
||||||
@@ -108,11 +108,12 @@ public sealed partial class TableScreensTests
|
|||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void EveryErrorCode_HasAText()
|
public void EveryErrorCode_HasAText()
|
||||||
{
|
{
|
||||||
var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask), typeof(Khaemhat.Application.Parties.PartyService) }
|
var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask), typeof(Khaemhat.Application.Parties.PartyService), typeof(Khaemhat.Application.Items.ItemService), typeof(Khaemhat.Application.Items.PriceListService) }
|
||||||
.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string)))
|
.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string)))
|
||||||
.Select(f => (string)f.GetRawConstantValue()!)
|
.Select(f => (string)f.GetRawConstantValue()!)
|
||||||
.Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal)
|
.Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal)
|
||||||
|| c.StartsWith("codes.", StringComparison.Ordinal) || (c.StartsWith("parties.", StringComparison.Ordinal) && !c.StartsWith("parties.party", StringComparison.Ordinal)))
|
|| c.StartsWith("codes.", StringComparison.Ordinal) || (c.StartsWith("parties.", StringComparison.Ordinal) && !c.StartsWith("parties.party", StringComparison.Ordinal))
|
||||||
|
|| (c.StartsWith("items.", StringComparison.Ordinal) && !c.StartsWith("items.item", StringComparison.Ordinal) && !c.StartsWith("items.cost", StringComparison.Ordinal)))
|
||||||
.Where(c => !c.EndsWith('.'))
|
.Where(c => !c.EndsWith('.'))
|
||||||
.Concat(Enum.GetValues<PeriodState>().Select(FiscalYearService.ErrorOf))
|
.Concat(Enum.GetValues<PeriodState>().Select(FiscalYearService.ErrorOf))
|
||||||
.ToList();
|
.ToList();
|
||||||
@@ -191,13 +192,17 @@ public sealed partial class TableScreensTests
|
|||||||
Assert.IsFalse(SeedCommand.Matches(["--urls", "http://localhost:5080"]));
|
Assert.IsFalse(SeedCommand.Matches(["--urls", "http://localhost:5080"]));
|
||||||
|
|
||||||
Assert.IsTrue(SeedCommand.TryParse(["seed", "--base"], out var all, out _));
|
Assert.IsTrue(SeedCommand.TryParse(["seed", "--base"], out var all, out _));
|
||||||
Assert.IsNull(all, "Every active company.");
|
Assert.AreEqual(new SeedOptions(false, 1, null), all, "Base data of every active company.");
|
||||||
Assert.IsTrue(SeedCommand.TryParse(["seed", "--company", "demo", "--base"], out var one, out _));
|
Assert.IsTrue(SeedCommand.TryParse(["seed", "--company", "demo", "--base"], out var one, out _));
|
||||||
Assert.AreEqual("DEMO", one);
|
Assert.AreEqual("DEMO", one!.Company);
|
||||||
|
Assert.IsTrue(SeedCommand.TryParse(["seed", "--demo", "--scale", "3", "--company", "demo"], out var demo, out _));
|
||||||
|
Assert.AreEqual(new SeedOptions(true, 3, "DEMO"), demo);
|
||||||
|
|
||||||
Assert.IsFalse(SeedCommand.TryParse(["seed"], out _, out var usage));
|
Assert.IsFalse(SeedCommand.TryParse(["seed"], out _, out var usage));
|
||||||
Assert.IsNotNull(usage);
|
Assert.IsNotNull(usage);
|
||||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo"], out _, out _), "Demo data arrive with parties and items.");
|
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--scale", "2"], out _, out _), "The scale is for the demo data.");
|
||||||
|
Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo", "--scale", "0"], out _, out _));
|
||||||
|
Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo", "--scale", "101"], out _, out _));
|
||||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--company"], out _, out _));
|
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--company"], out _, out _));
|
||||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--other"], out _, out _));
|
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--other"], out _, out _));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user