diff --git a/CHANGELOG.md b/CHANGELOG.md
index 85c4084..7203944 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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.
- 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.
+- 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
diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md
index 9e8550a..471e9b0 100644
--- a/docs/DATA-MODEL.md
+++ b/docs/DATA-MODEL.md
@@ -168,7 +168,7 @@ public sealed class M20261013_001_CreateParties : IMigration
| `warehouses` | codice, descrizione, indirizzo | |
| `item_categories` | codice, descrizione, `parent_id` → (3 livelli) | |
| `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 | |
| `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 |
@@ -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_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 |
-| `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)
| 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 |
-| `item_uoms` | `item_id` →, UM →, fattore di conversione | |
-| `item_barcodes` | `item_id` →, codice, tipo | |
-| `item_prices` | `item_id` →, `price_list_id` →, prezzo, validità, `party_id` → (prezzo netto cliente) | griglia listino x articolo (mockup 018) |
-| `item_suppliers` | `item_id` →, `party_id` →, codice fornitore, prezzo, lead time, minimo | |
-| `item_substitutes` | `item_id` →, `substitute_item_id` → | |
+| `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` → (cascata), UM →, fattore di conversione, EAN della confezione | |
+| `item_barcodes` | `item_id` → (cascata), codice, descrizione | codici alternativi, trovati dalla ricerca |
+| `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` → (cascata), `party_id` →, codice fornitore, prezzo, lead time, minimo, `is_default` (fornitore abituale) | |
+| `item_substitutes` | `item_id` → (cascata), `substitute_id` →, note | |
### 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` 20261111015 `create_code_sequences` (M20261111_015_CreateCodeSequences)
- `core` 20261112001 `create_parties` (M20261112_001_CreateParties)
+- `core` 20261112002 `create_items` (M20261112_002_CreateItems)
#### `attachments`
@@ -1131,6 +1132,22 @@ Migrazioni applicate in ordine:
- 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`
| Colonna | Tipo | Null | Default | Note |
@@ -1150,6 +1167,123 @@ Migrazioni applicate in ordine:
- 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`
| Colonna | Tipo | Null | Default | Note |
@@ -1407,6 +1541,24 @@ Migrazioni applicate in ordine:
- 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`
| Colonna | Tipo | Null | Default | Note |
@@ -1536,6 +1688,7 @@ Migrazioni applicate in ordine:
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
+| `is_base` | Bool | no | `false` | |
- indice unico `ux_price_lists_code` su `code`
diff --git a/docs/STATUS.md b/docs/STATUS.md
index ed3999c..fe26fec 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -7,9 +7,10 @@
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;
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.
-**Prossimo passo:** articoli e listini (#42) con `party_item_codes` e `seed --demo`, import/export guidato (#44),
-chiusura M4 (#46). #35 (PNG ad alta risoluzione) resta
+21 anagrafiche di esempio (#41, ADR 0029), articoli e listini con prezzi a validità, listini derivati,
+aggiornamento massivo, codici delle anagrafiche, 120 articoli di esempio e `seed --demo [--scale N]` (#42, ADR 0030).
+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.
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
@@ -18,7 +19,7 @@ filtro predefinito nei radar.
## Fatto
- 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).
- 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`,
diff --git a/docs/adr/0030-articoli-e-listini.md b/docs/adr/0030-articoli-e-listini.md
new file mode 100644
index 0000000..129af9c
--- /dev/null
+++ b/docs/adr/0030-articoli-e-listini.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*.
diff --git a/docs/wiki/Anagrafiche.md b/docs/wiki/Anagrafiche.md
index 1e740c2..ebfb4b4 100644
--- a/docs/wiki/Anagrafiche.md
+++ b/docs/wiki/Anagrafiche.md
@@ -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 |
| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento, identificativi |
| **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 |
| **Storico** | modifiche registrate: chi, quando, cosa |
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* con il modulo CRM.
+scheda *CRM* arriva con il modulo CRM. Nella scheda *Articoli e codici* lo stesso codice non si ripete per la stessa
+anagrafica.
### Dati principali
diff --git a/docs/wiki/Articoli-e-listini.md b/docs/wiki/Articoli-e-listini.md
index f5312bf..3adb5d8 100644
--- a/docs/wiki/Articoli-e-listini.md
+++ b/docs/wiki/Articoli-e-listini.md
@@ -1,153 +1,203 @@
# Articoli e listini
-> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **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
+> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** non ancora rilasciata (milestone M4)
+> **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.
-Nella scheda articolo stanno codici, unità di misura, IVA, conti contabili, prezzi e costi, i parametri di
-**riordino** e le **giacenze** per deposito in tempo reale. I **listini** raccolgono i prezzi di vendita per gruppi di
-clienti e si aggiornano anche in modo massivo.
+L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella
+scheda articolo stanno codici, unità di misura, IVA, conti, prezzi e costi e i parametri di **riordino**. I
+**listini** raccolgono i prezzi di vendita per gruppi di clienti, con una data di validità, e si aggiornano anche in
+modo massivo.
## Dove si trova
-Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**; le categorie articolo sono in **Anagrafiche →
-Categorie**.
+Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**. Le **categorie articolo**, le **intestazioni dei
+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

-*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),
-**Etichette** (stampa etichette), **Proposta riordino**.
+**Intestazione**: codice, descrizione, tipo e categoria; a destra il **prezzo base in vigore oggi** con costo medio,
+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
-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**:
-**Schede**: *Dati principali*, *UM alternative*, *Codici alternativi*, *Listini*, *Fornitori*, *Sostitutivi*,
-*Movimenti*, *Immagini e allegati*.
+| Scheda | Contenuto |
+|---|---|
+| **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
| Gruppo | Campi |
|---|---|
| **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 |
-| **Prezzi e costi** | prezzi dei listini principali (es. base, pubblico IVA inclusa, rivenditori), Costo standard, Ultimo costo, Medio ponderato (gli ultimi due calcolati) |
-| **Riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino**, Fornitore abituale |
-| **Giacenze per deposito (tempo reale)** | per ogni deposito: Giacenza, Impegnato, Ordinato, Disponibile, Valore, con riga di totale |
+| **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** | Prezzo dell'articolo (vale solo se nessun listino ha un prezzo), Costo standard, Ultimo costo, Costo medio |
+| **Magazzino e riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino** |
+| **Contabilità** | Conto ricavo, Conto costo |
### Tipi di articolo
| Tipo | Uso | 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 |
-| **Testo** | righe descrittive ricorrenti | no |
-| **Cespite** | beni strumentali (collegati al registro cespiti con il modulo Cespiti) | da definire in sviluppo |
+| **Descrittivo** | righe di solo testo ricorrenti | no |
+| **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
- 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.
+### Costi
-### 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.
-- **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.
+### Giacenze e riordino
-### 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**:
-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:
+### Controlli al salvataggio
-| Colonna | Significato |
-|---|---|
-| **Giacenza** | quantità fisicamente presente |
-| **Impegnato** | quantità riservata da ordini clienti confermati |
-| **Ordinato** | quantità in arrivo da ordini fornitore |
-| **Disponibile** | giacenza - impegnato |
-| **Valore** | giacenza x costo medio |
+- 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
+ articolo blocca il salvataggio se nelle preferenze è attivo *Blocca duplicati per EAN* (impostazione di
+ partenza), altrimenti è solo un avviso.
+- NC8 di otto cifre; quantità, pesi, prezzi e costi non negativi; fattori delle UM maggiori di zero.
+- Nelle schede di dettaglio: la stessa UM, lo stesso codice alternativo, lo stesso fornitore o sostitutivo non si
+ 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

-*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
-medio) una colonna per ciascun listino, più eventuali colonne di **prezzi netti per cliente** e il **margine**.
+Un **listino** ha codice, descrizione, valuta, *IVA inclusa*, validità e, se è derivato, il listino da cui
+**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*),
- 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.
+### La griglia dei listini
-Ogni listino ha una **validità** (i prezzi nuovi valgono da una data, i vecchi restano per i documenti precedenti),
-può essere **derivato** da un altro listino (ad esempio pubblico = base + 40%) e ha le proprie regole di
-**arrotondamento**.
+**Anagrafiche → Listini** è una griglia **articoli x listini**: per ogni articolo codice, descrizione, UM, costo
+medio (con il permesso) e una colonna per ciascun listino attivo.
+
+- 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
1. Premi **Aggiornamento massivo**.
-2. Scegli **che cosa** aggiornare: un listino, una categoria o le righe selezionate.
-3. Scegli la **variazione**: percentuale (anche negativa) oppure a partire da un altro listino.
-4. Scegli l'**arrotondamento**: a 0,10, 0,50 o 1,00, per eccesso o per difetto.
-5. Indica la **data di validità** dei nuovi prezzi.
-6. Controlla le righe aggiornate (restano evidenziate) e **Salva**.
+2. Scegli il **listino da aggiornare** e da dove **calcolare**: i prezzi attuali dello stesso listino o un altro
+ listino.
+3. Scrivi la **variazione %** (anche negativa).
+4. Scegli l'**arrotondamento** (0,01, 0,10, 0,50, 1,00) e il **verso** (al più vicino, per eccesso, per difetto).
+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
-Quando inserisci un articolo in una riga di vendita, Khaemhat cerca il prezzo in quest'ordine e si ferma al primo
-che trova:
+Quando inserisci un articolo in una riga di vendita (da M5), Khaemhat cerca il prezzo valido alla data del documento
+in quest'ordine e si ferma al primo che trova:
| Ordine | Fonte | Esempio |
|---|---|---|
| 1 | **prezzo netto cliente-articolo** | prezzo concordato con Rossi Impianti per quella valvola |
-| 2 | **listino del cliente** | il cliente usa LIST03 Rivenditori |
-| 3 | **listino base** | LIST01 Base |
-| 4 | **prezzo dell'articolo** | prezzo indicato nella scheda |
+| 2 | **listino del documento o del cliente** | il cliente usa il listino *Rivenditori* |
+| 3 | **listino base** | *Base* |
+| 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
-quel valore. Sul prezzo si applicano poi gli sconti del cliente e della riga (anche a cascata, come `5+2`). Se è
-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)).
+La riga ricorda **da dove viene il prezzo** (la fonte). Sul prezzo di listino si propongono gli sconti del cliente a
+cascata (come `10+5`); su un **prezzo netto** non si applicano sconti.
## Permessi e licenza
-Articoli e listini sono nel modulo **CORE**. I costi e i margini sono visibili solo agli utenti con il permesso
-`items.cost.read` (flag *vede costi e margini*). Il collegamento ai cespiti richiede il modulo **ASSET**; i conti
-contabili sono usati con il modulo **ACCT**.
+Articoli e listini sono nel modulo **CORE**. Per scrivere i prezzi nella griglia serve `items.item.write`; i costi
+e i margini richiedono `items.cost.read` (il ruolo *Magazzino* gestisce gli articoli ma non vede i costi). Il
+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
- **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.
-- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente:
- la fonte del prezzo è indicata nella riga.
-- **Un articolo di servizio non compare nelle giacenze.** I servizi e le spese non sono gestiti a magazzino.
+ prezzo con cui sono stati fatti; i prezzi nuovi valgono dalla loro data.
+- **Ho scritto un prezzo con la data sbagliata.** Imposta quella data in *Validità*, svuota la cella e salva: il
+ prezzo a quella data viene tolto.
+- **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
diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md
index a960add..c8abe45 100644
--- a/docs/wiki/Dati-di-base-e-esempio.md
+++ b/docs/wiki/Dati-di-base-e-esempio.md
@@ -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),
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.
-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
stesso caricamento è usato come prova automatica di correttezza.
@@ -162,7 +165,7 @@ esempio.
## 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
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 --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)
-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`.
+| Opzione | Effetto |
+|---|---|
+| `--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
diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md
index 9dcb209..635de41 100644
--- a/docs/wiki/Tabelle-azienda.md
+++ b/docs/wiki/Tabelle-azienda.md
@@ -108,7 +108,7 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
| **Depositi** | magazzini, anche mobili (es. furgone) |
| **Categorie articolo** | su tre livelli |
| **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) |
| **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 |
diff --git a/scripts/seed.sh b/scripts/seed.sh
index ccef53d..bb82fdc 100755
--- a/scripts/seed.sh
+++ b/scripts/seed.sh
@@ -1,10 +1,11 @@
#!/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 --demo [--scale N] [--company CODE]
# 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
# 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
if [[ -f /app/Khaemhat.Web.dll ]]; then
diff --git a/src/Khaemhat.Application/Items/ItemService.cs b/src/Khaemhat.Application/Items/ItemService.cs
new file mode 100644
index 0000000..903e3e1
--- /dev/null
+++ b/src/Khaemhat.Application/Items/ItemService.cs
@@ -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;
+
+/// An item with all its details, as the record screen edits it (mockup 017).
+public sealed class ItemRecord
+{
+ /// The item.
+ public Item Item { get; set; } = new();
+
+ /// The alternative units.
+ public List Units { get; set; } = [];
+
+ /// The alternative codes.
+ public List Barcodes { get; set; } = [];
+
+ /// The prices: of the price lists and net of the customers, each with its validity.
+ public List Prices { get; set; } = [];
+
+ /// The suppliers.
+ public List Suppliers { get; set; } = [];
+
+ /// The substitutes.
+ public List Substitutes { get; set; } = [];
+}
+
+/// A row of the items radar.
+/// The item.
+/// The code.
+/// The description.
+/// What the item is.
+/// The category.
+/// The base unit.
+/// The main bar code.
+/// The brand.
+/// Kept in stock.
+/// The average cost, only for who can see costs.
+/// Disabled.
+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)
+{
+ /// The price of the base list today.
+ public decimal? BasePrice { get; init; }
+}
+
+/// What happened to an item asked to be deleted.
+public enum ItemDeleteOutcome
+{
+ /// Deleted.
+ Deleted = 0,
+
+ /// Used by other data: disabled instead.
+ Disabled = 1,
+}
+
+///
+/// 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.
+///
+/// Permissions items.item.read, write, delete; costs only with items.cost.read.
+public sealed class ItemService
+{
+ /// Permission to read items and price lists.
+ public const string ReadPermission = "items.item.read";
+
+ /// Permission to write items and price lists.
+ public const string WritePermission = "items.item.write";
+
+ /// Permission to delete items.
+ public const string DeletePermission = "items.item.delete";
+
+ /// Permission to see costs and margins.
+ public const string CostPermission = "items.cost.read";
+
+ /// The entity of the attachments of an item.
+ public const string Entity = "items.item";
+
+ /// The code rule of the items (ADR 0027).
+ public const string CodeRule = "items";
+
+ /// Error: no description.
+ public const string DescriptionRequired = "items.description.required";
+
+ /// Error: the code is used by another item.
+ public const string CodeDuplicate = "items.code.duplicate";
+
+ /// Error: the code mask needs the category.
+ public const string CategoryRequired = "items.category.required";
+
+ /// Error: the bar code has a wrong check digit.
+ public const string BarcodeInvalid = "items.barcode.invalid";
+
+ /// Error or warning (by preference): another item has the bar code.
+ public const string BarcodeDuplicate = "items.barcode.duplicate";
+
+ /// Error: the NC8 code is not eight digits.
+ public const string CustomsCodeInvalid = "items.customs-code.invalid";
+
+ /// Error: a negative quantity, weight, price or cost.
+ public const string NotNegative = "items.value.negative";
+
+ /// Error: the factor of a unit is not above zero.
+ public const string FactorInvalid = "items.factor.invalid";
+
+ /// Error: a unit is listed twice, or is the base unit.
+ public const string UnitDuplicate = "items.unit.duplicate";
+
+ /// Error: a required detail field is empty.
+ public const string DetailRequired = "items.detail.required";
+
+ /// Error: the party of a supplier row is not a supplier.
+ public const string SupplierInvalid = "items.supplier.invalid";
+
+ /// Error: a supplier or a substitute is listed twice.
+ public const string DetailDuplicate = "items.detail.duplicate";
+
+ /// Error: an item cannot be its own substitute.
+ public const string SubstituteSelf = "items.substitute.self";
+
+ /// Error: a price is neither of a price list nor of a customer, or of both.
+ public const string PriceTarget = "items.price.target";
+
+ /// Error: a net price is for a customer only.
+ public const string PriceParty = "items.price.party";
+
+ /// Error: two prices of the same list or customer start on the same day.
+ public const string PriceDuplicate = "items.price.duplicate";
+
+ /// Error: the code of a party is used for another item.
+ public const string PartyCodeDuplicate = "items.party-code.duplicate";
+
+ /// Error: the item does not exist.
+ 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;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ /// The audit trail.
+ /// The automatic codes.
+ /// The clock.
+ 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;
+ }
+
+ /// The fields of the items radar.
+ public static ListFields Fields { get; } = new ListFields()
+ .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"));
+
+ /// The items for the radar, with the price of the base list today.
+ /// Who reads.
+ /// The company.
+ /// Search, filters, sort, page.
+ /// Cancellation.
+ /// The page.
+ public async Task> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(query);
+ var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, 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().ListAsync(Fields.Apply(Query.For(), query), cancellationToken).ConfigureAwait(false);
+ var book = await BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
+ var today = Today();
+ IReadOnlyList 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(rows, page.TotalCount, new Dictionary());
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who reads.
+ /// The company.
+ /// The text.
+ /// The party of the document, whose codes count too.
+ /// Cancellation.
+ /// At most 20 items.
+ public async Task> 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();
+ var page = await items.ListAsync(
+ Fields.Apply(Query.For(), 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().ListAsync(Query.For().Where(b => b.Code == exact), cancellationToken).ConfigureAwait(false))
+ .Items.Select(b => b.ItemId).ToList();
+ if (partyId is { } party)
+ {
+ ids.AddRange((await uow.Repository().ListAsync(
+ Query.For().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))];
+ }
+
+ /// An item with its details; costs hidden without items.cost.read.
+ /// Who reads.
+ /// The company.
+ /// The item.
+ /// Cancellation.
+ /// The record, or none.
+ public async Task 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;
+ }
+
+ /// A new item with the usual values: goods kept in stock, unit PZ, VAT 22, the default warehouse.
+ /// Who asks.
+ /// The company.
+ /// Cancellation.
+ /// The record to fill.
+ public async Task 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().FindAsync(Query.For().Where(u => u.Code == "PZ" && !u.Disabled), cancellationToken).ConfigureAwait(false);
+ var tax = await uow.Repository().FindAsync(Query.For().Where(t => t.Code == "22" && !t.Disabled), cancellationToken).ConfigureAwait(false);
+ var warehouse = await uow.Repository().FindAsync(Query.For().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,
+ },
+ };
+ }
+
+ /// Checks a record without saving it (also cleans it, as the save would).
+ /// Who asks.
+ /// The company.
+ /// The record.
+ /// Cancellation.
+ /// Errors and warnings.
+ public async Task> 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);
+ }
+
+ ///
+ /// Saves an item and its details in one transaction; a new item gets its code from the rule of the items
+ /// ({categoria} is the code of its category). Without items.cost.read the costs stay as they were.
+ ///
+ /// Who saves.
+ /// The company.
+ /// The record.
+ /// Cancellation.
+ /// The record as saved.
+ /// With the errors (field:code).
+ public async Task 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().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);
+ }
+
+ /// Disables or enables items (radar selection).
+ /// Who does it.
+ /// The company.
+ /// The items.
+ /// Disable or enable.
+ /// Cancellation.
+ /// How many changed.
+ public async Task SetDisabledAsync(Actor actor, string companyCode, IEnumerable 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();
+ 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;
+ }
+
+ /// Deletes an item; one used by other data (a substitute, documents from M5) is disabled instead.
+ /// Who deletes.
+ /// The company.
+ /// The item.
+ /// Cancellation.
+ /// What happened.
+ public async Task 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
+ await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return ItemDeleteOutcome.Deleted;
+ }
+ catch (DbException)
+ {
+ await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false);
+ return ItemDeleteOutcome.Disabled;
+ }
+ }
+
+ /// The history of an item and of its prices, newest first.
+ /// Who reads.
+ /// The company.
+ /// The item.
+ /// Cancellation.
+ /// The changes.
+ public async Task> 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();
+ 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)];
+ }
+
+ /// The rows of some items, for the lookups that show them by id.
+ /// Who reads.
+ /// The company.
+ /// The items.
+ /// Cancellation.
+ /// The rows found.
+ public async Task> RowsAsync(Actor actor, string companyCode, IEnumerable 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().ListAsync(Query.For().Where(i => wanted.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
+ .Select(i => RowOf(i, costs))];
+ }
+
+ /// Checks the codes of a party: code and item required, no code twice.
+ /// The codes.
+ /// The errors.
+ public static IReadOnlyList CheckPartyCodes(IReadOnlyList codes)
+ {
+ ArgumentNullException.ThrowIfNull(codes);
+ var problems = new List();
+ var seen = new HashSet(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;
+ }
+
+ /// Whether an actor sees costs and margins.
+ /// The actor.
+ /// The company.
+ /// Cancellation.
+ /// Whether costs are visible.
+ public async Task 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;
+ }
+
+ /// The prices of some items and all the price lists, in memory.
+ /// The unit of work of the company.
+ /// The items.
+ /// Cancellation.
+ /// The book.
+ public static async Task BookAsync(IUnitOfWork uow, IReadOnlyList itemIds, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(uow);
+ ArgumentNullException.ThrowIfNull(itemIds);
+ var lists = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items;
+ var prices = new List();
+ foreach (var chunk in itemIds.Distinct().Chunk(500))
+ {
+ long[] ids = [.. chunk];
+ prices.AddRange((await uow.Repository().ListAsync(Query.For().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 TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) =>
+ await uow.Repository().CountAsync(Query.For().Where(i => i.Code == code), cancellationToken).ConfigureAwait(false) > 0;
+
+ private static async Task LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
+ {
+ if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item)
+ {
+ return null;
+ }
+
+ return new ItemRecord
+ {
+ Item = item,
+ Units = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
+ Barcodes = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
+ Prices = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
+ Suppliers = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
+ Substitutes = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
+ };
+ }
+
+ private async Task WriteAsync(IUnitOfWork uow, ItemRecord record, ItemRecord? before, string userName, CancellationToken cancellationToken)
+ {
+ var item = record.Item;
+ var items = uow.Repository();
+ if (before is null)
+ {
+ item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(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(
+ IUnitOfWork uow, List rows, List before, Action link, CancellationToken cancellationToken, Func? audit = null)
+ where T : Core.Entities.Entity, new()
+ {
+ var repository = uow.Repository();
+ 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> CheckAsync(IUnitOfWork uow, CodeRule rule, ItemRecord record, CancellationToken cancellationToken)
+ {
+ var problems = new List();
+ 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().CountAsync(Query.For().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 BarcodeUsedAsync(IUnitOfWork uow, string barcode, long id, CancellationToken cancellationToken) =>
+ await uow.Repository().CountAsync(Query.For().Where(i => i.Barcode == barcode && i.Id != id), cancellationToken).ConfigureAwait(false) > 0
+ || await uow.Repository().CountAsync(Query.For().Where(b => b.Code == barcode && b.ItemId != id), cancellationToken).ConfigureAwait(false) > 0;
+
+ private static void CheckUnits(ItemRecord record, List problems)
+ {
+ var seen = new HashSet();
+ 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 problems)
+ {
+ var seen = new HashSet(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 problems, CancellationToken cancellationToken)
+ {
+ var seen = new HashSet<(long?, long?, DateOnly?)>();
+ var parties = uow.Repository();
+ 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 problems, CancellationToken cancellationToken)
+ {
+ var seen = new HashSet();
+ var parties = uow.Repository();
+ 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 problems)
+ {
+ var seen = new HashSet();
+ 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;
+ }
+}
diff --git a/src/Khaemhat.Application/Items/PriceBook.cs b/src/Khaemhat.Application/Items/PriceBook.cs
new file mode 100644
index 0000000..734e7b0
--- /dev/null
+++ b/src/Khaemhat.Application/Items/PriceBook.cs
@@ -0,0 +1,188 @@
+using Khaemhat.Application.Tables;
+using Khaemhat.Core.Items;
+using Khaemhat.Core.Parties;
+using Khaemhat.Core.Tables;
+
+namespace Khaemhat.Application.Items;
+
+/// The price proposed for an item and where it comes from (price_source of the document lines).
+/// The price, or none.
+/// Where it comes from.
+/// The price list it comes from.
+/// The price includes VAT (a price list with VAT included).
+/// The price is valid from this day.
+public sealed record PriceQuote(decimal? Price, PriceSource Source, long? PriceListId, bool VatIncluded, DateOnly? ValidFrom)
+{
+ /// No price.
+ public static PriceQuote None { get; } = new(null, PriceSource.None, null, false, null);
+}
+
+/// The discounts proposed on a line.
+/// The chain, such as 5+2, or none.
+/// The single discount equal to the chain, in percent.
+public sealed record DiscountQuote(string? Formula, decimal Equivalent)
+{
+ /// No discount.
+ public static DiscountQuote None { get; } = new(null, 0m);
+}
+
+/// A price of a price list for an item at a date.
+/// The price, or none.
+/// The price is computed from the base list of a derived list, not written.
+/// The price is valid from this day.
+public sealed record PriceCell(decimal? Price, bool Derived, DateOnly? ValidFrom)
+{
+ /// No price.
+ public static PriceCell Empty { get; } = new(null, false, null);
+}
+
+///
+/// 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.
+///
+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 _lists;
+ private readonly ILookup<(long Item, long List), ItemPrice> _listPrices;
+ private readonly ILookup<(long Item, long Party), ItemPrice> _netPrices;
+
+ /// Creates the book.
+ /// The price lists of the company.
+ /// The prices of the items wanted (all their rows).
+ public PriceBook(IEnumerable lists, IEnumerable 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);
+ }
+
+ /// The base price list: the one marked, or the one with code BASE.
+ public PriceList? Base { get; }
+
+ /// The price lists.
+ public IReadOnlyCollection Lists => _lists.Values;
+
+ /// The base price list among some.
+ /// The price lists.
+ /// The base one, or none.
+ public static PriceList? BaseOf(IEnumerable 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");
+ }
+
+ /// The row in effect at a date: the latest start not after it (a row without start is always valid).
+ /// The rows of one item and one list or party.
+ /// The date.
+ /// The row, or none.
+ public static ItemPrice? At(IEnumerable rows, DateOnly date)
+ {
+ ArgumentNullException.ThrowIfNull(rows);
+ return rows.Where(r => r.ValidFrom is null || r.ValidFrom <= date).OrderByDescending(r => r.ValidFrom ?? DateOnly.MinValue).FirstOrDefault();
+ }
+
+ /// Whether a price list can be used at a date: active and within its validity.
+ /// The list.
+ /// The date.
+ /// Whether it is valid.
+ 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);
+ }
+
+ /// The price of an item in a list at a date, derived from the base list when the list has none.
+ /// The item.
+ /// The list.
+ /// The date.
+ /// The price.
+ public PriceCell ListPrice(long itemId, long listId, DateOnly date) => ListPrice(itemId, listId, date, 0);
+
+ /// The price written in a list for an item at a date, without derivation.
+ /// The item.
+ /// The list.
+ /// The date.
+ /// The row, or none.
+ public ItemPrice? OwnPrice(long itemId, long listId, DateOnly date) => At(_listPrices[(itemId, listId)], date);
+
+ /// The net price of a party for an item at a date.
+ /// The item.
+ /// The party.
+ /// The date.
+ /// The row, or none.
+ public ItemPrice? NetPrice(long itemId, long partyId, DateOnly date) => At(_netPrices[(itemId, partyId)], date);
+
+ /// The price proposed for an item (SPEC §11.3): net of the party, list, base list, item.
+ /// The item.
+ /// The party of the document.
+ /// The price list of the party or of the document.
+ /// The date of the document.
+ /// The price and its source.
+ 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;
+ }
+
+ /// The discounts of the party on a price (SPEC §11.3): none on a net price, else the two of the sales terms.
+ /// The price proposed.
+ /// The sales terms of the party.
+ /// The discounts.
+ 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;
+ }
+}
diff --git a/src/Khaemhat.Application/Items/PriceListService.cs b/src/Khaemhat.Application/Items/PriceListService.cs
new file mode 100644
index 0000000..64adc17
--- /dev/null
+++ b/src/Khaemhat.Application/Items/PriceListService.cs
@@ -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;
+
+/// A column of the price grid: a price list.
+/// The list.
+/// Its code.
+/// Its description.
+/// The base list.
+/// Derived from another list.
+/// Prices with VAT.
+public sealed record PriceListColumn(long Id, string Code, string Description, bool IsBase, bool Derived, bool VatIncluded);
+
+/// A row of the price grid: an item with its price in every list at the date.
+/// The item.
+/// Its code.
+/// Its description.
+/// Its unit.
+/// Its average cost (standard when none), only for who sees costs.
+/// The prices by list.
+/// The net price of the party chosen, if any.
+public sealed record PriceGridRow(
+ long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal? AverageCost, IReadOnlyDictionary Prices, PriceCell? Net);
+
+/// The price grid (mockup 018).
+/// The columns.
+/// The rows.
+public sealed record PriceGrid(IReadOnlyList Lists, ListPage Page);
+
+/// A price to write: of a list or net of a customer, valid from a day; no price removes the row of that day.
+/// The item.
+/// The list.
+/// The customer.
+/// The price, or none to remove it.
+/// Valid from this day.
+public sealed record PriceEdit(long ItemId, long? PriceListId, long? PartyId, decimal? Price, DateOnly? ValidFrom);
+
+/// A mass update of a price list (mockup 018): from the list itself or another one, a percent and a rounding.
+public sealed record BulkUpdate
+{
+ /// The list to update.
+ public long PriceListId { get; init; }
+
+ /// The list the prices start from; none: the list itself.
+ public long? SourcePriceListId { get; init; }
+
+ /// The change in percent, also negative.
+ public decimal Percent { get; init; }
+
+ /// The rounding step, such as 0.10, 0.50 or 1.00; zero: cents.
+ public decimal RoundingStep { get; init; }
+
+ /// Rounding up, down or to the nearest.
+ public RoundingDirection Direction { get; init; }
+
+ /// The prices are read at this day and the new ones are valid from it.
+ public DateOnly Date { get; init; }
+
+ /// Only the items of this category.
+ public long? CategoryId { get; init; }
+
+ /// Only these items (the selection); none: all the active items with a price.
+ public IReadOnlyList? ItemIds { get; init; }
+}
+
+///
+/// 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.
+///
+/// Permissions items.item.read and write; costs and margins with items.cost.read.
+public sealed class PriceListService
+{
+ /// Error: a price is negative.
+ public const string NotNegative = ItemService.NotNegative;
+
+ /// Error: the list of a mass update does not exist.
+ public const string ListUnknown = "items.price-list.unknown";
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly AuditTrail _audit;
+ private readonly ItemService _items;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ /// The audit trail.
+ /// The items (for the cost permission).
+ 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;
+ }
+
+ /// The active price lists: the base one first, then by code.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The lists.
+ public async Task> 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);
+ }
+
+ /// The price grid: a page of items (no text items) with the price of every list at a date.
+ /// Who reads.
+ /// The company.
+ /// Search, filters (those of the items radar), sort, page.
+ /// The day the prices are read at.
+ /// The customer whose net prices are shown.
+ /// Cancellation.
+ /// The grid.
+ public async Task 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().ListAsync(
+ ItemService.Fields.Apply(Query.For().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 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(rows, page.TotalCount, new Dictionary()));
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who asks.
+ /// The company.
+ /// The update.
+ /// Cancellation.
+ /// The prices to write; unchanged ones are left out.
+ /// When the lists are unknown or the step negative.
+ public async Task> 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();
+ 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().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().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();
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who saves.
+ /// The company.
+ /// The prices.
+ /// Cancellation.
+ /// How many rows were written or removed.
+ /// With the errors (index:code).
+ public async Task SaveAsync(Actor actor, string companyCode, IReadOnlyList 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();
+ var parties = uow.Repository();
+ 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();
+ var written = 0;
+ foreach (var group in edits.GroupBy(e => e.ItemId))
+ {
+ var itemId = group.Key;
+ var rows = (await prices.ListAsync(Query.For().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(uow, AuditAction.Insert, itemId, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
+ rows.Add(row);
+ written++;
+ }
+ }
+
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return written;
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who asks.
+ /// The company.
+ /// The item.
+ /// The party of the document.
+ /// The list of the document; none: the one of the party.
+ /// The date of the document.
+ /// Cancellation.
+ /// The price and the discounts.
+ 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);
+ }
+
+ /// The price and the discounts of a line, inside the unit of work of a document.
+ /// The unit of work of the company.
+ /// The item.
+ /// The party of the document.
+ /// The list of the document; none: the one of the party.
+ /// The date of the document.
+ /// Cancellation.
+ /// The price and the discounts.
+ 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().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
+ var terms = partyId is { } party
+ ? await uow.Repository().FindAsync(Query.For().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> ColumnsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
+ {
+ var lists = (await uow.Repository().ListAsync(Query.For().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,
+ };
+}
diff --git a/src/Khaemhat.Application/Parties/PartyService.cs b/src/Khaemhat.Application/Parties/PartyService.cs
index 04c85b3..553e4c8 100644
--- a/src/Khaemhat.Application/Parties/PartyService.cs
+++ b/src/Khaemhat.Application/Parties/PartyService.cs
@@ -4,6 +4,8 @@ using Khaemhat.Core.Instance;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
+using Khaemhat.Application.Items;
+using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Validation;
@@ -37,6 +39,9 @@ public sealed class PartyRecord
/// The bank accounts.
public List BankAccounts { get; set; } = [];
+
+ /// The codes the party uses for our items (tab Articoli e codici).
+ public List ItemCodes { get; set; } = [];
}
/// Which parties a radar shows (menu Anagrafiche).
@@ -538,6 +543,26 @@ public sealed class PartyService
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
}
+ /// The rows of some parties, for the lookups that show them by id.
+ /// Who reads.
+ /// The company.
+ /// The parties.
+ /// Cancellation.
+ /// The rows found.
+ public async Task> RowsAsync(Actor actor, string companyCode, IEnumerable 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().ListAsync(Query.For().Where(p => wanted.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.Select(RowOf)];
+ }
+
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);
@@ -563,6 +588,7 @@ public sealed class PartyService
Addresses = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
Contacts = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
BankAccounts = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
+ ItemCodes = [.. (await uow.Repository().ListAsync(Query.For().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.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.ItemCodes, before?.ItemCodes ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
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.
OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v);
OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v);
diff --git a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs
index dd317c0..4564270 100644
--- a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs
+++ b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs
@@ -100,7 +100,7 @@ public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("item_categories", [new ItemCategory { Code = "GEN", Description = "Generica" }], cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("party_categories", Coded(("GEN", "Generica")), cancellationToken).ConfigureAwait(false);
- await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base" }], cancellationToken).ConfigureAwait(false);
+ await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base", IsBase = true }], cancellationToken).ConfigureAwait(false);
var year = context.Today.Year;
var numerators = new Dictionary(StringComparer.Ordinal);
diff --git a/src/Khaemhat.Application/Seeding/DemoItemsSeeder.cs b/src/Khaemhat.Application/Seeding/DemoItemsSeeder.cs
new file mode 100644
index 0000000..868d86b
--- /dev/null
+++ b/src/Khaemhat.Application/Seeding/DemoItemsSeeder.cs
@@ -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;
+
+///
+/// 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; seed --demo --scale N repeats the catalogue N times. The rows are marked as demo.
+///
+/// The automatic code rules.
+public sealed class DemoItemsSeeder(CodeRuleService codes) : ISeeder
+{
+ /// The items of one scale.
+ public const int ItemsPerScale = 120;
+
+ private static readonly string[] Sizes = ["1/2\"", "3/4\"", "1\"", "1 1/4\"", "1 1/2\"", "2\""];
+
+ ///
+ public string ModuleCode => ModuleCodes.Core;
+
+ ///
+ public SeedKind Kind => SeedKind.Demo;
+
+ ///
+ public int Order => 20;
+
+ /// The catalogue of one scale, in order.
+ /// The items to create.
+ public static IReadOnlyList Catalogue()
+ {
+ var items = new List();
+
+ // 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;
+ }
+
+ ///
+ public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var uow = context.UnitOfWork;
+ if (await uow.Repository().CountAsync(Query.For(), 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();
+ var allLists = (await lists.ListAsync(Query.For(), 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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items
+ .ToDictionary(u => u.Code, u => u.Id, StringComparer.OrdinalIgnoreCase);
+ var tax = (await uow.Repository().FindAsync(Query.For().Where(t => t.Code == "22"), cancellationToken).ConfigureAwait(false))?.Id;
+ var warehouse = (await uow.Repository().FindAsync(Query.For().Where(w => w.IsDefault), cancellationToken).ConfigureAwait(false))?.Id;
+ var parties = (await uow.Repository().ListAsync(Query.For(), 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(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();
+ 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().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 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().FindAsync(Query.For().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(IUnitOfWork uow, SeedContext context, string table, T row, CancellationToken cancellationToken)
+ where T : class, Khaemhat.Core.Entities.IEntity, new()
+ {
+ await uow.Repository().InsertAsync(row, cancellationToken).ConfigureAwait(false);
+ context.Count(table);
+ }
+
+ /// A fictitious EAN-13 with the prefix 200, for internal use, and a valid check digit.
+ /// The progressive number.
+ /// The code.
+ 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);
+}
+
+/// An item of the demo catalogue.
+/// The category code.
+/// What it is.
+/// The description.
+/// The unit code.
+/// The price of the base list (goods) or of the item (services and expenses).
+/// The fictitious brand.
+/// The combined nomenclature.
+/// The net weight in kg.
+public sealed record DemoItem(string Category, ItemKind Kind, string Description, string Unit, decimal? Price, string? Brand, string? CustomsCode, decimal? Weight);
diff --git a/src/Khaemhat.Application/Seeding/Seeding.cs b/src/Khaemhat.Application/Seeding/Seeding.cs
index 7550e37..1008f89 100644
--- a/src/Khaemhat.Application/Seeding/Seeding.cs
+++ b/src/Khaemhat.Application/Seeding/Seeding.cs
@@ -73,6 +73,9 @@ public sealed class SeedContext
/// Today.
public DateOnly Today { get; }
+ /// How many times the demo seeders repeat their catalogues (seed --demo --scale N), at least 1.
+ public int Scale { get; init; } = 1;
+
/// Rows added, by table.
public IReadOnlyDictionary Added => _added;
@@ -242,7 +245,16 @@ public sealed partial class SeedRunner : ICompanySeeder
/// Base or demo.
/// Cancellation.
/// What was added.
- public async Task RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default)
+ public Task RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default) =>
+ RunAsync(companyCode, kind, 1, cancellationToken);
+
+ /// Runs every seeder of a kind on a company, the demo ones repeating their catalogues.
+ /// The company.
+ /// Base or demo.
+ /// How many times the demo catalogues are repeated (--scale), at least 1.
+ /// Cancellation.
+ /// What was added.
+ public async Task RunAsync(string companyCode, SeedKind kind, int scale, CancellationToken cancellationToken = default)
{
var company = CompanyCodes.Normalize(companyCode);
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 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))
{
await seeder.RunAsync(context, cancellationToken).ConfigureAwait(false);
diff --git a/src/Khaemhat.Application/Tables/TableCatalog.cs b/src/Khaemhat.Application/Tables/TableCatalog.cs
index bf004c4..b50a8fe 100644
--- a/src/Khaemhat.Application/Tables/TableCatalog.cs
+++ b/src/Khaemhat.Application/Tables/TableCatalog.cs
@@ -63,6 +63,9 @@ public sealed partial class TableCatalog
/// Error: a transfer reason must not change quantities by itself.
public const string TransferEffect = "tables.inventory-reason.transfer";
+ /// Error: another price list is already the base one.
+ public const string BaseDuplicate = "tables.price-list.base-duplicate";
+
/// The maximum depth of item categories.
public const int MaxCategoryLevel = 3;
@@ -247,6 +250,12 @@ public sealed partial class TableCatalog
{
c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
}
+
+ var id = x.Id;
+ if (x.IsBase && await c.CountAsync(p => p.IsBase && p.Id != id, ct).ConfigureAwait(false) > 0)
+ {
+ c.Error(nameof(PriceList.IsBase), BaseDuplicate);
+ }
}));
Add(new TableDefinition("discount-policies", "discount_policies")
.Field("formula", x => x.Formula)
diff --git a/src/Khaemhat.Application/Tables/TableDefinition.cs b/src/Khaemhat.Application/Tables/TableDefinition.cs
index 4e0df6f..6e0fdb5 100644
--- a/src/Khaemhat.Application/Tables/TableDefinition.cs
+++ b/src/Khaemhat.Application/Tables/TableDefinition.cs
@@ -54,6 +54,15 @@ public sealed class TableRuleContext
where TOther : class, IEntity, new() =>
_unitOfWork.Repository().GetAsync(id, cancellationToken);
+ /// Counts the rows of another table that match.
+ /// The other table.
+ /// The condition.
+ /// Cancellation.
+ /// How many rows match.
+ public Task CountAsync(System.Linq.Expressions.Expression> where, CancellationToken cancellationToken)
+ where TOther : class, IEntity, new() =>
+ _unitOfWork.Repository().CountAsync(Query.For().Where(where), cancellationToken);
+
/// Whether a coded row with a code exists.
/// The entity.
/// The code.
diff --git a/src/Khaemhat.Core/Items/Items.cs b/src/Khaemhat.Core/Items/Items.cs
new file mode 100644
index 0000000..485ab46
--- /dev/null
+++ b/src/Khaemhat.Core/Items/Items.cs
@@ -0,0 +1,234 @@
+using Khaemhat.Core.Entities;
+
+namespace Khaemhat.Core.Items;
+
+/// What an item is (SPEC §11.2).
+public enum ItemKind
+{
+ /// Goods bought or sold; kept in stock when .
+ Goods = 0,
+
+ /// A service, such as installation or hours of assistance.
+ Service = 1,
+
+ /// An ancillary expense on invoices (transport, collection).
+ Expense = 2,
+
+ /// A recurring descriptive line.
+ Text = 3,
+
+ /// A fixed asset (linked to the asset register with the ASSET module).
+ Asset = 4,
+}
+
+/// Where the price proposed on a document line comes from (SPEC §11.3).
+public enum PriceSource
+{
+ /// No price found.
+ None = 0,
+
+ /// The net price agreed with the party for the item.
+ PartyNet = 1,
+
+ /// The price list of the party (or of the document).
+ PartyPriceList = 2,
+
+ /// The base price list of the company.
+ BasePriceList = 3,
+
+ /// The price written on the item.
+ Item = 4,
+}
+
+/// An item (items, mockup 017).
+public sealed class Item : Entity, IDemoMarkable
+{
+ /// The code, automatic (ADR 0027, mask {categoria}-{seq:0000}).
+ public string Code { get; set; } = string.Empty;
+
+ /// What the item is.
+ public ItemKind Kind { get; set; }
+
+ /// The description used on documents.
+ public string Description { get; set; } = string.Empty;
+
+ /// A longer description.
+ public string? ExtendedDescription { get; set; }
+
+ /// The category (item_categories).
+ public long? CategoryId { get; set; }
+
+ /// The base unit of measure (units_of_measure).
+ public long? UnitOfMeasureId { get; set; }
+
+ /// The VAT code of sales (tax_codes).
+ public long? SalesTaxCodeId { get; set; }
+
+ /// The VAT code of purchases (tax_codes).
+ public long? PurchaseTaxCodeId { get; set; }
+
+ /// The main bar code (EAN/GTIN).
+ public string? Barcode { get; set; }
+
+ /// The combined nomenclature code (NC8, Intrastat).
+ public string? CustomsCode { get; set; }
+
+ /// The manufacturer.
+ public string? Manufacturer { get; set; }
+
+ /// The brand.
+ public string? Brand { get; set; }
+
+ /// Net weight in kilograms.
+ public decimal? NetWeight { get; set; }
+
+ /// Gross weight in kilograms.
+ public decimal? GrossWeight { get; set; }
+
+ /// The item is kept in stock (movements, balances, reorder from M6).
+ public bool Stocked { get; set; }
+
+ /// The usual warehouse (warehouses).
+ public long? WarehouseId { get; set; }
+
+ /// The minimum stock.
+ public decimal? MinimumStock { get; set; }
+
+ /// The reorder point: below it the item is proposed for an order.
+ public decimal? ReorderPoint { get; set; }
+
+ /// The reorder lot: orders are proposed in multiples of it.
+ public decimal? ReorderLot { get; set; }
+
+ /// The price written on the item, the last fallback of the price search.
+ public decimal? Price { get; set; }
+
+ /// The standard cost, set by hand.
+ public decimal? StandardCost { get; set; }
+
+ /// The last purchase cost (updated by the receipts, M6).
+ public decimal? LastCost { get; set; }
+
+ /// The weighted average cost (updated by the receipts, M6).
+ public decimal? AverageCost { get; set; }
+
+ /// The revenue account (chart of accounts, M7).
+ public string? RevenueAccountCode { get; set; }
+
+ /// The cost account (chart of accounts, M7).
+ public string? CostAccountCode { get; set; }
+
+ /// Free notes.
+ public string? Notes { get; set; }
+
+ /// Disabled: no longer proposed in new documents.
+ public bool Disabled { get; set; }
+
+ ///
+ public bool IsDemo { get; set; }
+}
+
+/// An alternative unit of measure of an item (item_uoms): a box of 10 pieces has factor 10.
+public sealed class ItemUnit : Entity
+{
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The unit (units_of_measure).
+ public long UnitOfMeasureId { get; set; }
+
+ /// How many base units one of this unit holds.
+ public decimal Factor { get; set; } = 1m;
+
+ /// The bar code of the package.
+ public string? Barcode { get; set; }
+}
+
+/// An alternative code of an item (item_barcodes): another EAN or an internal code.
+public sealed class ItemBarcode : Entity
+{
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The code.
+ public string Code { get; set; } = string.Empty;
+
+ /// What the code is, such as confezione or codice interno.
+ public string? Description { get; set; }
+}
+
+///
+/// A price of an item (item_prices): 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.
+///
+public sealed class ItemPrice : Entity
+{
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The price list (price_lists), or none for a net price of a party.
+ public long? PriceListId { get; set; }
+
+ /// The party of a net price (parties), or none for a price list.
+ public long? PartyId { get; set; }
+
+ /// The price.
+ public decimal Price { get; set; }
+
+ /// The price is valid from this day (none: always).
+ public DateOnly? ValidFrom { get; set; }
+}
+
+/// A supplier of an item (item_suppliers) with its code and price; one is the usual one.
+public sealed class ItemSupplier : Entity
+{
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The supplier (parties).
+ public long PartyId { get; set; }
+
+ /// The code of the item at the supplier.
+ public string? SupplierCode { get; set; }
+
+ /// The purchase price.
+ public decimal? Price { get; set; }
+
+ /// The lead time in days.
+ public int? LeadTimeDays { get; set; }
+
+ /// The minimum quantity of an order.
+ public decimal? MinimumQuantity { get; set; }
+
+ /// The usual supplier, used by the reorder proposal.
+ public bool IsDefault { get; set; }
+}
+
+/// An equivalent item proposed when this one is missing (item_substitutes).
+public sealed class ItemSubstitute : Entity
+{
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The substitute (items).
+ public long SubstituteId { get; set; }
+
+ /// Notes, such as the differences.
+ public string? Notes { get; set; }
+}
+
+/// The code a customer or a supplier uses for one of our items (party_item_codes).
+public sealed class PartyItemCode : Entity
+{
+ /// The party.
+ public long PartyId { get; set; }
+
+ /// The item.
+ public long ItemId { get; set; }
+
+ /// The code of the party.
+ public string Code { get; set; } = string.Empty;
+
+ /// The description of the party.
+ public string? Description { get; set; }
+}
diff --git a/src/Khaemhat.Core/Items/PriceRounding.cs b/src/Khaemhat.Core/Items/PriceRounding.cs
new file mode 100644
index 0000000..e624f8f
--- /dev/null
+++ b/src/Khaemhat.Core/Items/PriceRounding.cs
@@ -0,0 +1,60 @@
+namespace Khaemhat.Core.Items;
+
+/// How a price is rounded to a step.
+public enum RoundingDirection
+{
+ /// To the nearest step, halves away from zero.
+ Nearest = 0,
+
+ /// Up to the next step (per eccesso).
+ Up = 1,
+
+ /// Down to the previous step (per difetto).
+ Down = 2,
+}
+
+/// The arithmetic of prices: percent changes and rounding to a step such as 0,10, 0,50 or 1,00.
+public static class PriceRounding
+{
+ /// Rounds a price to a step; with no step, to the cent.
+ /// The price.
+ /// The step, such as 0.10; zero or less means cents.
+ /// Nearest, up or down.
+ /// The rounded price.
+ 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);
+ }
+
+ /// Applies a percent change: +10 adds a tenth, -5 takes off a twentieth.
+ /// The price.
+ /// The change in percent.
+ /// The changed price, not rounded.
+ public static decimal Change(decimal value, decimal percent) => value * (1m + (percent / 100m));
+
+ /// The margin of a price over a cost, in percent of the price.
+ /// The price.
+ /// The cost.
+ /// The margin, or none without a positive price or a cost.
+ 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;
+ }
+}
diff --git a/src/Khaemhat.Core/Tables/BaseTables.cs b/src/Khaemhat.Core/Tables/BaseTables.cs
index af2378d..77326c5 100644
--- a/src/Khaemhat.Core/Tables/BaseTables.cs
+++ b/src/Khaemhat.Core/Tables/BaseTables.cs
@@ -342,6 +342,9 @@ public sealed class PriceList : CodedEntity
/// Rounding step of derived prices, such as 0.05; zero for none.
public decimal RoundingStep { get; set; }
+
+ /// The base price list of the company: the third step of the price search (SPEC §11.3, ADR 0030).
+ public bool IsBase { get; set; }
}
/// A discount policy: a chain of discounts such as 10+5.
diff --git a/src/Khaemhat.Data/CompanyDatabase/ItemMaps.cs b/src/Khaemhat.Data/CompanyDatabase/ItemMaps.cs
new file mode 100644
index 0000000..2beac5d
--- /dev/null
+++ b/src/Khaemhat.Data/CompanyDatabase/ItemMaps.cs
@@ -0,0 +1,86 @@
+using Khaemhat.Core.Items;
+using Khaemhat.Data.Mapping;
+
+namespace Khaemhat.Data.CompanyDatabase;
+
+/// Map of to items.
+public sealed class ItemMap : EntityMap
+{
+ /// Creates the map.
+ 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);
+ }
+}
+
+/// Map of to item_uoms.
+public sealed class ItemUnitMap : EntityMap
+{
+ /// Creates the map.
+ public ItemUnitMap()
+ {
+ ToTable("item_uoms");
+ Map(x => x.Barcode).MaxLength(20);
+ }
+}
+
+/// Map of to item_barcodes.
+public sealed class ItemBarcodeMap : EntityMap
+{
+ /// Creates the map.
+ public ItemBarcodeMap()
+ {
+ ToTable("item_barcodes");
+ Map(x => x.Code).MaxLength(40);
+ Map(x => x.Description).MaxLength(100);
+ }
+}
+
+/// Map of to item_prices.
+public sealed class ItemPriceMap : EntityMap
+{
+ /// Creates the map.
+ public ItemPriceMap() => ToTable("item_prices");
+}
+
+/// Map of to item_suppliers.
+public sealed class ItemSupplierMap : EntityMap
+{
+ /// Creates the map.
+ public ItemSupplierMap()
+ {
+ ToTable("item_suppliers");
+ Map(x => x.SupplierCode).MaxLength(40);
+ }
+}
+
+/// Map of to item_substitutes.
+public sealed class ItemSubstituteMap : EntityMap
+{
+ /// Creates the map.
+ public ItemSubstituteMap()
+ {
+ ToTable("item_substitutes");
+ Map(x => x.Notes).MaxLength(200);
+ }
+}
+
+/// Map of to party_item_codes.
+public sealed class PartyItemCodeMap : EntityMap
+{
+ /// Creates the map.
+ public PartyItemCodeMap()
+ {
+ ToTable("party_item_codes");
+ Map(x => x.Code).MaxLength(40);
+ Map(x => x.Description).MaxLength(200);
+ }
+}
diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_002_CreateItems.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_002_CreateItems.cs
new file mode 100644
index 0000000..13e69c5
--- /dev/null
+++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_002_CreateItems.cs
@@ -0,0 +1,146 @@
+using Khaemhat.Data.Migrations;
+using Khaemhat.Data.Schema;
+
+namespace Khaemhat.Data.CompanyDatabase.Migrations;
+
+///
+/// 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.
+///
+[Migration(20261112_002, "create_items")]
+public sealed class M20261112_002_CreateItems : IMigration
+{
+ ///
+ 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);
+ });
+ }
+}
diff --git a/src/Khaemhat.Web/Components/Pages/Items/ItemCategoriesPage.razor b/src/Khaemhat.Web/Components/Pages/Items/ItemCategoriesPage.razor
new file mode 100644
index 0000000..5697233
--- /dev/null
+++ b/src/Khaemhat.Web/Components/Pages/Items/ItemCategoriesPage.razor
@@ -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 {
+ ///
+ protected override void OnInitialized() => Navigation.NavigateTo(ItemScreens.CategoriesUrl, new NavigationOptions { ReplaceHistoryEntry = true });
+}
diff --git a/src/Khaemhat.Web/Components/Pages/Items/ItemPage.razor b/src/Khaemhat.Web/Components/Pages/Items/ItemPage.razor
new file mode 100644
index 0000000..3bc8c85
--- /dev/null
+++ b/src/Khaemhat.Web/Components/Pages/Items/ItemPage.razor
@@ -0,0 +1,782 @@
+@page "/anagrafiche/articoli/nuovo"
+@page "/anagrafiche/articoli/{Id:long}"
+@attribute [Authorize]
+@inherits MasterDataPage
+@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. *@
+
+
+@if (!_loaded)
+{
+
@T["Common.Loading"]
+}
+else if (Session.Company is null)
+{
+
@T["Items.NoCompany"]
+}
+else if (!Session.Permissions.Allows(ItemService.ReadPermission))
+{
+