diff --git a/CHANGELOG.md b/CHANGELOG.md index 75133c9..b291c48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,61 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. ## [Unreleased] +## [0.6.0] - 2026-11-12 + +M6 — Acquisti e Magazzino. Il ciclo passivo dall'ordine al fornitore alla fattura protocollata, le fatture +elettroniche ricevute importate in bozza, le autofatture con la loro scadenza e un magazzino che si aggiorna da solo +con i documenti: giacenze per deposito, costo medio, inventario, riordino e valorizzazione. + +### Added +- Movimenti di magazzino dai documenti (#59, ADR 0035): alla conferma DDT, fatture immediate e accompagnatorie, note, + DDT e fatture fornitore, note di credito fornitore e movimenti `MM` scrivono i loro movimenti nella stessa + transazione (`inventory_entries`, `inventory_entry_lines`); l'annullamento li toglie. La causale del tipo documento + decide carico, scarico o trasferimento; la fattura di un DDT non muove di nuovo la merce, la nota di credito la + muove all'inverso. Tabella `item_balances` con giacenza per deposito, impegnato (ordini clienti) e ordinato + (ordini fornitore). +- Costo medio ponderato per articolo ricalcolato dalla storia dei movimenti a ogni modifica, anche per documenti con + data passata; ultimo costo e date di ultimo carico e scarico; il prezzo della fattura fornitore corregge il costo + dei carichi che fattura. +- Documenti del ciclo passivo nelle maschere dei documenti (#55, #56, #58): ordini fornitori, ricevimenti merce (DDT + fornitore con il numero e la data del fornitore), fatture e note di credito fornitore con **protocollo** IVA alla + conferma e rifiuto del doppio numero del fornitore nello stesso anno, autofatture e movimenti di magazzino con + causale e depositi. Menu *Acquisti* e *Magazzino*. +- Controllo dei prezzi: sulla fattura fornitore un avviso elenca le righe con un prezzo diverso dall'ordine o dal + ricevimento e la differenza totale. +- Autofatture e integrazioni: il pacchetto italiano (`SelfInvoiceRulesIt`) riconosce dalla fattura del fornitore + l'integrazione dovuta (TD16, TD17, TD18, TD19, TD28) e la scadenza; la fattura lo mostra con **Crea autofattura**, + che prepara la bozza con l'aliquota ordinaria; *Acquisti → Autofatture* elenca le integrazioni da emettere. Tipi + `AF20`-`AF29` nelle tabelle di base. +- Lettura delle fatture elettroniche ricevute (#57): `FatturaPaReader` (FPR12, FPA12, FSM10, lotti, allegati) e + lettore CMS/CAdES dei file `.p7m` con verifica dell'impronta e della firma, scritti in casa. +- Import delle fatture passive (#57): *Acquisti → Importa fatture* legge XML, P7M e ZIP, trova o crea il fornitore, + segnala doppioni, tipi non d'acquisto, totali diversi e firme non verificate, e registra in bozza fatture (TD01, + TD02, TD03, TD05, TD06, TD24-TD27) e note di credito (TD04, TD08) con articoli abbinati per codice del fornitore, + EAN e codice, codice IVA per aliquota e natura, sconti di riga e file allegato. Le regole TD stanno nel pacchetto + fiscale (`IncomingInvoiceRulesIt`). +- Giacenze e disponibilità (#60): indicatori, filtri per deposito, categoria e stato (*Disponibile*, *Da riordinare*, + *Sottoscorta*, *Esaurito*), movimenti di un articolo con saldo progressivo. +- Inventario fisico (#60): apertura per deposito, data e categoria con la giacenza contabile congelata, conteggi + scritti o importati dal file del lettore, rettifiche `INVP` e `INVN` alla data del conteggio; tabelle `stock_takes` + e `stock_take_lines`. +- Proposta di riordino (#60): articoli sotto il punto di riordino o la scorta minima, quantità dal lotto o dalla + soglia con il minimo d'ordine del fornitore, fornitore preferito con prezzo e arrivo previsto, ordini fornitore in + bozza uno per fornitore. +- Valorizzazione a data con costo medio, ultimo costo o costo standard e classi ABC; ricostruzione del magazzino da + interfaccia con avanzamento e come job di sistema `inventory.rebuild` ogni domenica alle 2:15. +- Widget *Sottoscorta* della dashboard con i dati veri. +- Dati di esempio di acquisti e magazzino (#61): esistenze iniziali, ordini ricevuti per intero e in parte, fatture + con una differenza di prezzo e una integrazione AF18 da emettere, un inventario in conteggio. +- ADR 0035; pagine wiki *Acquisti* e *Magazzino* complete con le schermate, guida all'uso aggiornata. + +### Changed +- Import *Giacenze iniziali*: non è più solo verifica, scrive e conferma un movimento `APE` per deposito. +- I documenti confermati senza numero interno (DDT fornitore) si presentano come *Senza numero* invece di *Bozza*. +- *Tipi documento*: fattura immediata, fattura e nota di credito fornitore ricevono la causale di magazzino (`SCA`, + `CAR`, `RESF`); la migrazione la assegna anche nelle aziende esistenti dove manca. I tipi `AF20`-`AF29` mancanti si + aggiungono con *Aggiorna da tabelle base* o `scripts/seed.sh --base`. + ## [0.5.0] - 2026-11-12 M5 — Motore documenti e Vendite. Un solo motore per tutti i documenti, con numerazione, totali, scadenze e diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index d60d59f..94d8181 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -730,6 +730,7 @@ Migrazioni applicate in ordine: - `core` 20261112001 `create_parties` (M20261112_001_CreateParties) - `core` 20261112002 `create_items` (M20261112_002_CreateItems) - `core` 20261112003 `create_documents` (M20261112_003_CreateDocuments) +- `core` 20261113001 `create_inventory` (M20261113_001_CreateInventory) #### `attachments` @@ -1306,12 +1307,61 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_inventory_documents_date` su `document_date` - indice `ix_inventory_documents_party` su `party_id` - indice `ix_inventory_documents_status` su `status` - indice unico `ux_inventory_documents_number` su `numerator_id`, `number` +#### `inventory_entries` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `entry_date` | Date | no | | | +| `source_family` | String(40) | sì | | | +| `source_document_id` | Int64 | sì | | | +| `source_kind` | String(40) | sì | | | +| `source_number` | String(30) | sì | | | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `party_id` | Int64 | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_inventory_entries_date` su `entry_date` +- indice `ix_inventory_entries_source` su `source_family`, `source_document_id` + +#### `inventory_entry_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `entry_id` | Int64 | no | | -> `inventory_entries` (Cascade) | +| `entry_date` | Date | no | | | +| `item_id` | Int64 | no | | -> `items` (Restrict) | +| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) | +| `quantity` | Decimal(19,6) | no | | | +| `valued` | Bool | no | `false` | | +| `unit_cost` | Decimal(19,6) | no | `0` | | +| `value` | Decimal(19,6) | no | `0` | | +| `source_line_id` | Int64 | sì | | | +| `sort_order` | Int32 | no | `0` | | +| `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_inventory_entry_lines_entry` su `entry_id` +- indice `ix_inventory_entry_lines_item` su `item_id`, `entry_date` +- indice `ix_inventory_entry_lines_warehouse` su `warehouse_id`, `item_id` + #### `inventory_reasons` | Colonna | Tipo | Null | Default | Note | @@ -1332,6 +1382,31 @@ Migrazioni applicate in ordine: - indice unico `ux_inventory_reasons_code` su `code` +#### `item_balances` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) | +| `on_hand` | Decimal(19,6) | no | `0` | | +| `committed` | Decimal(19,6) | no | `0` | | +| `ordered` | Decimal(19,6) | no | `0` | | +| `in_transit` | Decimal(19,6) | no | `0` | | +| `average_cost` | Decimal(19,6) | no | `0` | | +| `value` | Decimal(19,6) | no | `0` | | +| `last_cost` | Decimal(19,6) | sì | | | +| `last_load_date` | Date | sì | | | +| `last_unload_date` | Date | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_item_balances_warehouse` su `warehouse_id` +- indice unico `ux_item_balances_item_warehouse` su `item_id`, `warehouse_id` + #### `item_barcodes` | Colonna | Tipo | Null | Default | Note | @@ -2038,6 +2113,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_purchase_documents_date` su `document_date` - indice `ix_purchase_documents_party` su `party_id` @@ -2169,6 +2246,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_purchase_orders_date` su `document_date` - indice `ix_purchase_orders_party` su `party_id` @@ -2333,6 +2412,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_sale_documents_date` su `document_date` - indice `ix_sale_documents_party` su `party_id` @@ -2464,6 +2545,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_sale_orders_date` su `document_date` - indice `ix_sale_orders_party` su `party_id` @@ -2595,6 +2678,8 @@ Migrazioni applicate in ordine: | `updated_at` | DateTimeUtc | sì | | | | `updated_by` | String(100) | sì | | | | `row_version` | Int64 | no | `1` | | +| `to_warehouse_id` | Int64 | sì | | | +| `vat_date` | Date | sì | | | - indice `ix_sale_quotations_date` su `document_date` - indice `ix_sale_quotations_party` su `party_id` @@ -2651,6 +2736,50 @@ Chiave primaria: `module`, `version`. - indice unico `ux_shipping_terms_code` su `code` +#### `stock_take_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `stock_take_id` | Int64 | no | | -> `stock_takes` (Cascade) | +| `item_id` | Int64 | no | | -> `items` (Restrict) | +| `book_quantity` | Decimal(19,6) | no | `0` | | +| `counted_quantity` | Decimal(19,6) | sì | | | +| `unit_cost` | Decimal(19,6) | no | `0` | | +| `notes` | String(200) | sì | | | +| `sort_order` | Int32 | no | `0` | | +| `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_stock_take_lines_item` su `stock_take_id`, `item_id` + +#### `stock_takes` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `take_date` | Date | no | | | +| `warehouse_id` | Int64 | no | | -> `warehouses` (Restrict) | +| `description` | String(100) | no | | | +| `category_id` | Int64 | sì | | -> `item_categories` (Restrict) | +| `status` | String(40) | no | | | +| `adjustment_document_id` | Int64 | sì | | | +| `loss_document_id` | Int64 | sì | | | +| `posted_at` | DateTimeUtc | sì | | | +| `posted_by` | String(100) | sì | | | +| `notes` | Text | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_stock_takes_date` su `take_date` + #### `tax_codes` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/STATUS.md b/docs/STATUS.md index ab96acd..8ff9c89 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -3,18 +3,20 @@ > Punto di ripresa per ogni sessione. Aggiornare a fine sessione. **Ultimo aggiornamento:** 2026-11-12 -**Milestone corrente:** M6 — Acquisti e Magazzino (issue #55-#61), **non ancora iniziata**: si parte quando il -titolare lo dice. M5 chiusa: PR #124 in `main`, tag `v0.5.0`, immagine e release. -**Prossimo passo:** M6 dall'issue #55. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo +**Milestone corrente:** M7 — Contabilità generale (issue #62-#68), **non ancora iniziata**: si parte quando il +titolare lo dice. M6 chiusa: PR #125 in `main`, tag `v0.6.0`, immagine e release. +**Prossimo passo:** M7 dall'issue #62. #35 (PNG ad alta risoluzione) resta aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile). Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della password (mockup 003); schede *Layout salvati* e *Notifiche* del profilo; rinomina e filtro predefinito nei radar; logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e modelli e-mail per azienda (M12). +Da M6: schermata dell'import fatture con file caricati (serve un caricamento via CDP); nei movimenti di un articolo il +numero del fornitore al posto di *DDT fornitore* senza numero; FIFO e LIFO a lotti (dopo la 1.0). ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7. -- ADR 0001-0034. +- ADR 0001-0035. - 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`, @@ -66,6 +68,15 @@ logo PNG nel PDF (oggi solo JPEG, ADR 0034); coda della posta persistente e mode e-mail con SMTP e coda scritti in casa (#52, ADR 0034); log *Documenti*; profilo e un anno di vendite di esempio; wiki con la *Guida all'uso* e le schermate reali, README come guida per sviluppatori (#53). Test: 660 verdi in locale, 23 di PostgreSQL saltati (girano in CI). +- **M6 (chiusa, `v0.6.0`, PR #125):** movimenti di magazzino dai documenti nella + stessa transazione, costo medio ponderato ricalcolato dalla storia, impegnato e ordinato, correzione del costo dalla + fattura fornitore (#59, ADR 0035); ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, + doppioni rifiutati, controllo dei prezzi, autofatture TD16-TD29 consigliate dal pacchetto italiano con scadenza + (#55, #56, #58); lettura FatturaPA e `.p7m` (CMS scritto in casa) e import delle fatture passive in bozza (#57); + giacenze, movimenti di un articolo, inventario fisico, proposta di riordino, valorizzazione con classi ABC, + ricostruzione anche come job settimanale, widget *Sottoscorta* (#60); giacenze iniziali da file con movimento `APE`; + acquisti e magazzino nei dati di esempio, wiki *Acquisti* e *Magazzino* con le schermate, guida all'uso (#61). + Test: 709 verdi in locale, 23 di PostgreSQL saltati (girano in CI). - Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13) e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36, M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91, diff --git a/docs/adr/0035-magazzino-e-ciclo-passivo.md b/docs/adr/0035-magazzino-e-ciclo-passivo.md new file mode 100644 index 0000000..adb870e --- /dev/null +++ b/docs/adr/0035-magazzino-e-ciclo-passivo.md @@ -0,0 +1,80 @@ +# ADR 0035 - Magazzino e ciclo passivo + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** SPEC §11.5, §11.6, §12.12; milestone M6, issue #55-#61 + +## Contesto + +SPEC §11.6 chiede giacenze per deposito con impegnato, ordinato e disponibile aggiornati nella stessa transazione del +documento, costo medio ponderato (FIFO e LIFO predisposti), inventario fisico, proposta di riordino, valorizzazione a +data e una ricostruzione; §11.5 il ciclo passivo con protocollo IVA, import delle fatture elettroniche ricevute, +controllo dei prezzi rispetto all'ordine e autofatture TD16-TD29. Il motore documenti di M5 (ADR 0032) sa già quali +generi hanno effetto *Inventory*; restavano aperti: come si registra un movimento, come si calcola il costo quando i +documenti arrivano fuori ordine di data, come non contare due volte la merce di una fattura nata da un DDT, come +portare le novità nelle aziende create prima, dove stanno le regole italiane di autofatture e import. + +## Decisione + +1. **La causale decide, il genere filtra.** Ogni tipo documento ha una causale di magazzino (`inventory_reasons`: + carico, scarico, nessun effetto; flag *trasferimento* e *muove il valore*). `StockEffectMatrix` (in `Khaemhat.Core`) + dice quali generi la applicano (DDT, fatture immediate e accompagnatorie, note, DDT e fatture fornitore, note di + credito fornitore, movimenti `MM`) e quali hanno costi d'acquisto che muovono la media (DDT fornitore, fattura + fornitore, movimento con prezzo). Ordini clienti e fornitori non muovono la giacenza: il loro **residuo** è + l'impegnato e l'ordinato. Le causali di base sono 12 (`CAR`, `SCA`, `RESC`, `RESF`, `TRA`, `INVP`, `INVN`, `CVU`, + `CVR`, `OMA`, `AUTO`, `APE`). +2. **Movimenti come righe derivate.** `InventoryPoster` gira dentro la transazione del motore documenti: alla conferma + scrive un `inventory_entries` per documento con una riga per articolo e deposito (`inventory_entry_lines`, quantità + nell'unità base, con segno); all'annullamento o alla modifica di un documento in vigore lo riscrive da capo. Le righe + che vengono da un documento che ha già mosso la merce nello stesso verso (la fattura di un DDT) sono saltate; + la nota di credito di una fattura la muove all'inverso. +3. **Storia ricalcolata, non saldi incrementali.** Dopo ogni modifica la storia degli articoli toccati viene + ripercorsa per data e ordine di registrazione (`StockCostCalculator`): giacenza per deposito, costo medio ponderato + dell'articolo su tutti i depositi, ultimo costo, date di ultimo carico e scarico, e i risultati vanno in + `item_balances` e nella scheda articolo. Così un documento con una data passata dà lo stesso risultato di uno + inserito in ordine. Ogni carico con valore sposta la media; gli altri movimenti escono alla media del momento; con + giacenza a zero o negativa il carico successivo fissa la media. La giacenza negativa non blocca la conferma (non + si fermano le consegne), si vede nelle giacenze e nella dashboard. +4. **La fattura corregge il costo del carico.** Il prezzo di una fattura fornitore confermata sostituisce, per la quota + fatturata, il costo dei carichi dei DDT fornitore che fattura; la differenza di prezzo rispetto a ordine e ricevimento + è anche mostrata come avviso sulla fattura (`PurchaseService.PriceDifferencesAsync`), senza bloccare. +5. **Ricostruzione.** `InventoryService.RebuildAsync` cancella i movimenti e riposta tutti i documenti in vigore, + dal più vecchio e, a parità di data, i DDT prima delle fatture, poi ricalcola ogni articolo; gira a mano (con + avanzamento) e ogni domenica come job di sistema `inventory.rebuild`. +6. **Inventario come documento a sé.** `stock_takes` e `stock_take_lines` fotografano la giacenza contabile alla + data del conteggio; la registrazione crea due movimenti `MM` (`INVP` e `INVN`) alla stessa data. Gli articoli non + contati non vengono toccati; non c'è blocco dei movimenti durante il conteggio, perché le rettifiche sono datate + e la storia ricalcolata tiene conto dei movimenti successivi. +7. **Valorizzazione.** Costo medio ponderato, ultimo costo e costo standard a qualsiasi data, con classi ABC (80% e + 95% del valore). FIFO e LIFO restano **predisposti**: il criterio è un parametro del calcolo + (`StockValuationMethod`) e i movimenti conservano data, quantità e costo di ogni carico, ma i due metodi non sono + ancora offerti perché richiedono i lotti di carico, rimandati a dopo la 1.0. +8. **Tabelle di base nelle aziende esistenti.** La migrazione `M20261113_001_CreateInventory` crea le tabelle e + assegna la causale ai tipi di base che non l'hanno (`FI` → `SCA`, `FF` → `CAR`, `NCF` → `RESF`), senza toccare una + causale scelta dall'utente. I tipi nuovi (`AF20`-`AF29`) e le causali mancanti si aggiungono con *Aggiorna da + tabelle base* o `scripts/seed.sh --base`, che aggiungono i codici mancanti senza modificare quelli esistenti + (ADR 0026). Il tracciato + *Giacenze iniziali* scrive un movimento `APE` per deposito. +9. **Regole italiane nel pacchetto fiscale.** `ISelfInvoiceRules` (`SelfInvoiceRulesIt`) decide dall'anagrafica del + fornitore (paese, UE), dal genere delle righe (beni o servizi) e dalle nature IVA quale autofattura serve (TD16, + TD17, TD18, TD19, TD28) e la scadenza (15 del mese successivo; 90 giorni per TD20 e TD29). + `IIncomingInvoiceRules` (`IncomingInvoiceRulesIt`) traduce il tipo FatturaPA nel tipo documento d'acquisto (TD01, + TD02, TD03, TD05, TD06, TD24-TD27 in `FF`; TD04 e TD08 in `NCF`; gli altri sono rifiutati). L'applicazione non + conosce i codici TD. +10. **Import delle fatture ricevute.** `PurchaseInvoiceImportService` legge XML, P7M e ZIP con il lettore di #57, trova + il fornitore per partita IVA o codice fiscale (o lo crea), rifiuta i doppioni (stesso fornitore, numero, anno), + abbina le righe per codice del fornitore, EAN e codice articolo, il codice IVA per aliquota e natura, porta gli + sconti percentuali nello sconto di riga e gli altri nel prezzo netto, e salva una bozza con il file allegato. + Totale diverso, firma non verificata e sconti sul totale sono avvisi, non errori. + +## Conseguenze + +- Le quantità e i costi sono sempre ricostruibili dai documenti: i movimenti sono un dato derivato e la ricostruzione + è anche la verifica di coerenza. +- Ricalcolare la storia di un articolo costa più di un aggiornamento incrementale; con le dimensioni di una PMI + (migliaia di movimenti per articolo all'anno) resta nell'ordine dei millisecondi, e i documenti toccano pochi + articoli alla volta. Se servirà, un punto di partenza annuale (chiusura del magazzino) accorcia la storia. +- I documenti fornitore senza numero interno (`DDTF`) si riconoscono dal numero del fornitore; l'interfaccia li mostra + come *Senza numero*. +- Rimandati: lotti, matricole e ubicazioni; FIFO e LIFO; libro inventari e scritture delle rimanenze (M7); XML delle + autofatture e scarico dal canale SDI (M9); report di magazzino stampabili (M13). diff --git a/docs/wiki/Acquisti.md b/docs/wiki/Acquisti.md index 9622b67..c9ed07e 100644 --- a/docs/wiki/Acquisti.md +++ b/docs/wiki/Acquisti.md @@ -1,178 +1,179 @@ # Acquisti -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6) -> **Modulo di licenza:** CORE (XML delle autofatture e canale SDI con EINV, registrazione con ACCT) · **Permessi principali:** famiglia `purchases.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.3, §11.5 +> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6) +> **Modulo di licenza:** CORE (XML delle autofatture con EINV, registrazione contabile con ACCT) · **Permessi principali:** `purchases.order.*` (ordini fornitore), `inventory.entry.*` (DDT fornitore), `purchases.invoice.*` (fatture, note di credito, import, autofatture) · **Specifica:** SPEC §11.3, §11.5, ADR 0035 -Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche generati dalla proposta di riordino), -**DDT di carico** con controllo delle quantità ricevute, **fatture di acquisto** con protocollo IVA e conti per riga, -**note di credito** dei fornitori, **import delle fatture passive** XML/P7M ricevute dallo SDI e le **autofatture e -integrazioni** (TD16-TD29) per reverse charge e acquisti dall'estero. +Il modulo **Acquisti** copre il ciclo passivo: **ordini ai fornitori** (anche dalla proposta di riordino), +**ricevimento della merce** con il DDT del fornitore, **fatture e note di credito dei fornitori** con il protocollo +IVA, **import delle fatture elettroniche** ricevute (XML, P7M, ZIP) e le **autofatture e integrazioni** (TD16-TD29) +per inversione contabile e acquisti dall'estero. + +> **In questa versione** ci sono ordini, ricevimenti, fatture e note di credito fornitore con protocollo, carico a +> magazzino e costo medio, controllo dei prezzi rispetto a ordine e ricevimento, import delle fatture elettroniche e +> autofatture in bozza con la loro scadenza. Arrivano più avanti: la **registrazione contabile** e i registri IVA (M7), +> i **pagamenti** e lo scadenzario (M8), il **file XML** delle autofatture e lo scarico dal canale SDI (M9). ## Dove si trova -Menu **Acquisti** → *Ordini fornitori*, *DDT di carico*, *Fatture di acquisto*, *Import XML SDI*, *Autofatture*. +Menu **Acquisti** → *Ordini fornitori*, *Ricevimenti merce*, *Fatture passive*, *Importa fatture*, *Autofatture*. -Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali): -vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) e [Vendite](Vendite) per il motore documenti. +Le maschere sono quelle comuni a tutti i documenti (toolbar, intestazione, schede, righe con castelletto e totali, +trasformazioni, stampa, allegati): vedi [Vendite](Vendite) per il funzionamento del motore documenti e +[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) per la tastiera. ``` -Proposta di riordino ──► Ordine fornitore ──ricevi merce──► DDT di carico ──registra fattura──► Fattura di acquisto - ▲ - Fattura passiva XML/P7M (SDI) ──import──┘ (abbinamento all'ordine o al DDT) +Proposta di riordino ──► Ordine fornitore ──Crea DDT fornitore (carico)──► Ricevimento ──Crea Fattura fornitore──► Fattura + ▲ + Fattura elettronica XML / P7M / ZIP ──Importa fatture──► Fattura in bozza ─┘ +Fattura di un fornitore estero o in reverse charge ──Crea autofattura──► Autofattura / integrazione (TD16-TD29) ``` ## Ordini fornitori -![031 · Ordine fornitore generato dalla proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/031-ordine-fornitore.png) -*Mockup 031 — ordine fornitore confermato, nato dalla proposta di riordino, con il pannello Origine del fabbisogno (anteprima ridotta).* +Un **ordine fornitore** (`OF`) dice al fornitore che cosa ti serve; non muove il magazzino ma, una volta +**confermato**, aumenta l'**ordinato** degli articoli finché non arriva la merce (vedi [Magazzino](Magazzino)). -Azioni: **Invia al fornitore** (e-mail con il PDF dell'ordine), **Ricevi merce (DDT carico)**, **Chiudi residuo**. +- Scegliendo il fornitore si applicano le sue condizioni (pagamento, banca, porto, valuta). +- Scegliendo un articolo, Khaemhat propone il **prezzo del fornitore** dalla scheda articolo (*Fornitori*). +- Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi + [Magazzino](Magazzino#proposta-di-riordino)) o copiando un altro documento. +- Quando la merce arriva, **Crea DDT fornitore (carico)** porta le righe ancora da ricevere nel ricevimento: puoi scegliere + righe e quantità, così un ordine può essere ricevuto in più volte. Lo stato diventa *Evaso in parte* ed *Evaso*; + **Chiudi** chiude un residuo che non arriverà più. -- L'intestazione mostra la **data prevista** di consegna, calcolata come data dell'ordine + **lead time** del - fornitore, e lo stato di ricevimento (*Ricevuto 0%*…). -- Le righe riportano il **codice del fornitore** per l'articolo; il prezzo proposto è quello del fornitore. -- Il pannello **Origine del fabbisogno** spiega perché si ordina: sottoscorta, impegni da ordini clienti, lotto di - riordino. -- Schede: *Righe*, *Testata*, *Totali*, *Ricevimenti*, *Note*, *Allegati*, *Collegamenti*. -- Un ordine confermato aggiorna l'**ordinato** degli articoli (vedi [Magazzino](Magazzino)). +![Khaemhat 0.6.0 · ricevimento della merce](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-ricevimento.png) -Gli ordini nascono a mano, dalla **proposta di riordino** (un ordine in bozza per fornitore, vedi -[Magazzino](Magazzino)) o dall'azione **Ordina a fornitore** di un ordine cliente. +## Ricevimenti merce (DDT fornitore) -## DDT di carico +Il **DDT fornitore (carico)** (`DDTF`) registra la merce arrivata. Non ha un numero interno: nella testata scrivi il +**numero e la data del DDT del fornitore**, che lo identificano (nell'elenco compare come *Senza numero*). -![032 · DDT di carico con controllo quantità ricevute](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/032-ddt-di-carico.png) -*Mockup 032 — ricevimento con confronto ordinato/ricevuto, riga con 20 pezzi mancanti e aggiornamento del costo medio (anteprima ridotta).* +1. Dall'ordine premi **Crea DDT fornitore (carico)**, oppure crea un ricevimento e richiama l'ordine. +2. Controlla le **quantità ricevute** riga per riga e il **deposito** di arrivo. +3. **Conferma**: la merce viene **caricata a magazzino** con la causale `CAR` e aggiorna **costo medio** e **ultimo + costo** degli articoli; l'ordine segna le quantità evase. -Il **DDT di carico** registra la merce ricevuta. Azioni: **Registra fattura da questo DDT**, **Stampa etichette**, -**Riapri**. +Un ricevimento confermato resta modificabile finché non è fatturato; dal ricevimento **Crea Fattura fornitore** +prepara la fattura con le stesse righe. -1. Dall'ordine fornitore premi **Ricevi merce** oppure crea un DDT di carico e usa **Evadi da…** per richiamare - l'ordine. -2. Indica numero e data del **DDT del fornitore**. -3. Conta la merce: per ogni riga inserisci la quantità **ricevuta**; si può **scansionare l'EAN o il codice - fornitore** per contare. La colonna *Controllo* segnala le differenze (*OK*, *Mancanti 20*…). -4. **Conferma**: la merce viene **caricata a magazzino** (causale *Carico da fornitore*, deposito indicato), si - aggiornano **ultimo costo** e **costo medio ponderato** dell'articolo. +## Fatture passive -Se arriva meno del previsto, il **residuo** resta aperto sull'ordine; se non arriverà più si chiude con **Chiudi -residuo**. Un messaggio sotto le righe riassume differenze e variazioni del costo medio. +![Khaemhat 0.6.0 · fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png) -## Fatture di acquisto - -![033 · Fattura di acquisto da XML con conti e centri di costo per riga](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/033-fattura-di-acquisto.png) -*Mockup 033 — fattura di acquisto in bozza nata da XML, con protocollo, flag Verifica prezzi, righe con conto e centro di costo, castelletto con IVA detraibile (anteprima ridotta).* - -Azioni: **Registra (protocolla)**, **Contabilizza**, **Confronta con ordine**, **Apri XML**. +La **fattura fornitore** (`FF`) e la **nota di credito fornitore** (`NCF`) registrano i documenti del fornitore. | Dato | Descrizione | |---|---| -| **Data di registrazione** e **data/numero del documento** del fornitore | la registrazione determina il periodo IVA | -| **Protocollo** | numero progressivo del registro IVA acquisti (es. `ACQ/2026/000613`), assegnato alla registrazione | -| **Conto e centro di costo per riga** | ogni riga ha il proprio conto di costo e centro di costo (proposti da articolo, categoria o fornitore) | -| **Indetraibilità** | codici IVA con indetraibilità parziale o totale (es. telefonia 50%): il castelletto mostra imponibile, imposta e quota **detraibile** | -| **Ritenute e cassa** | per i professionisti: ritenuta d'acconto, cassa previdenza; il totale mostra il **netto a pagare** | -| **Registrazione contabile** | scheda con l'anteprima della registrazione (con modulo Contabilità) | +| **N. documento fornitore** e **data** | numero e data scritti dal fornitore (nella testata) | +| **Data** | data di registrazione: decide il periodo IVA | +| **Protocollo** | numero progressivo del registro IVA acquisti (numeratore `PRA`), assegnato alla **conferma**; nell'elenco compare nella colonna *Protocollo* | +| **Righe** | articoli, righe descrittive e spese con il codice IVA di ogni riga; per i professionisti ritenuta d'acconto e cassa come nelle vendite | +| **Scadenze** | calcolate dal pagamento del fornitore | -Schede: *Righe*, *Testata*, *Totali*, *Scadenze*, *Ritenute e cassa*, *Registrazione contabile*, *Note*, -*Allegati*, *Collegamenti*. +La fattura nasce dal ricevimento (**Crea Fattura fornitore**), dall'ordine (per servizi o merce senza DDT), dall'**import +della fattura elettronica** (vedi sotto) o a mano. **Conferma** assegna il protocollo e la rende definitiva; una +fattura confermata si corregge con una **nota di credito fornitore** (**Crea Nota di credito fornitore**). -**Registra (protocolla)** assegna il protocollo e rende la fattura definitiva; **Contabilizza** crea la registrazione -(automatica alla conferma o in batch, secondo le preferenze). La fattura può nascere: +**Magazzino.** Una fattura di merce senza DDT carica il magazzino alla conferma; una fattura nata da un ricevimento +non carica di nuovo, ma il suo **prezzo corregge il costo** del carico. La nota di credito fornitore scarica la merce +resa (causale `RESF`). -- dal **DDT di carico** (**Registra fattura da questo DDT**), che la collega ai carichi; -- dall'**import XML** (vedi sotto); -- a mano, ad esempio per fatture cartacee o estere. +**Controllo dei prezzi.** Se una riga della fattura ha un prezzo diverso da quello dell'ordine o del ricevimento da +cui viene, sopra le righe compare un avviso con la differenza totale e, riga per riga, il prezzo atteso e quello +fatturato. È un avviso: decidi tu se registrare la fattura o chiedere una nota di credito. -Le **note di credito dei fornitori** si registrano allo stesso modo e chiudono le partite collegate. +## Importare le fatture elettroniche -## Import delle fatture passive XML/P7M +![Khaemhat 0.6.0 · import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png) -![034 · Import fatture passive XML/P7M](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/034-import-xml-sdi.png) -*Mockup 034 — quattro file in import (pronto, con ritenuta e cassa, fornitore da creare, duplicato) e mappatura delle righe sull'ordine con differenza di prezzo (anteprima ridotta).* +**Acquisti → Importa fatture** (o il link nell'elenco delle fatture passive) registra in bozza le fatture ricevute +dallo SDI o dal tuo intermediario. -1. Carica i file con **Carica XML / P7M / ZIP**, oppure **Leggi inbox** (cartella di ingresso dell'istanza) o - **Scarica dal canale SDI** (con il modulo Fatturazione elettronica). -2. Per ogni file Khaemhat legge fornitore, numero, data, tipo documento (TD) e totale e mostra un **esito**: - *Pronto*, *Fornitore da creare*, *Duplicato*, oppure avvisi (ad esempio *Ritenuta 20% · cassa 4%*). -3. Il **fornitore** viene riconosciuto da **partita IVA o codice fiscale**; se non esiste si crea al volo dai dati - dell'XML. -4. **Mappatura righe**: ogni riga XML viene abbinata a un articolo cercando, in ordine, il **codice del fornitore**, - l'**EAN** e la **descrizione** (ricerca approssimata). Le righe non abbinate diventano descrittive o si abbinano a - mano. -5. **Abbina a ordine**: confronta prezzi e quantità con l'ordine fornitore; le differenze sono evidenziate (es. - *+3,4%*). -6. **Salva bozza** o **Registra fattura di acquisto**. Se ci sono differenze la fattura nasce **in bozza** con il - flag *Verifica prezzi*. +1. **Caricamento**: scegli uno o più file: **XML FatturaPA**, file firmati **.p7m** o archivi **ZIP** che li + contengono (fino a 50 MB per file). I file che non sono fatture elettroniche leggibili sono elencati a parte con il + motivo. +2. **Controllo**: per ogni fattura vedi fornitore (nuovo o già in anagrafica), numero, data, tipo, totale e un esito: + *Pronta*, oppure *Già registrata* (stesso fornitore, stesso numero, stesso anno), *Non è un acquisto* (per esempio + un'autofattura emessa dall'azienda stessa), *Totale diverso* (il totale del file non torna con le righe), *Firma non + verificata*, *Sconto sul totale*. **Leggi** mostra righe, riepilogo IVA e pagamento del file. +3. **Registrazione**: spunta le fatture e premi **Registra in bozza**. Per ognuna Khaemhat: + - trova il **fornitore** dalla partita IVA o dal codice fiscale, o lo **crea** dai dati del file; + - crea una **fattura fornitore** (tipi TD01, TD02, TD03, TD05, TD06, TD24-TD27) o una **nota di credito fornitore** + (TD04, TD08) in bozza, con numero e data del fornitore e la causale nelle note; + - abbina ogni riga a un **articolo** cercando il **codice del fornitore** (scheda articolo, *Fornitori*), poi l'**EAN**, + poi il **codice articolo**; le righe non abbinate diventano righe libere con descrizione, prezzo e IVA; + - riporta gli **sconti** percentuali come sconto di riga e gli altri nel prezzo netto; + - sceglie il **codice IVA** dell'azienda con la stessa aliquota e natura; + - **allega il file** originale alla fattura (scheda *Allegati*, tipo *Fattura elettronica*). -L'**XML originale** viene allegato alla fattura; per i file **P7M** la **firma CAdES** viene verificata. I file già -importati sono riconosciuti come duplicati. +Le fatture importate restano **in bozza**: controllale e confermale per protocollarle. Se un codice IVA manca (per +esempio una natura non usata finora), aggiungilo in [Tabelle azienda](Tabelle-azienda) → *Codici IVA* e ripeti +l'import. ## Autofatture e integrazioni (TD16-TD29) -![035 · Autofattura / integrazione reverse charge](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/035-autofattura-integrazione.png) -*Mockup 035 — integrazione TD17 per servizi da un fornitore estero: IVA integrata, effetto neutro, registri RC vendite e acquisti, scadenza di invio allo SDI (anteprima ridotta).* +![Khaemhat 0.6.0 · integrazione da emettere su una fattura intracomunitaria](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-autofattura.png) -Quando l'IVA è dovuta dall'acquirente (inversione contabile) l'azienda deve **integrare** la fattura ricevuta o -emettere un'**autofattura**, trasmettendola allo SDI. In Khaemhat questi documenti stanno in **Acquisti → -Autofatture** e nascono dalla fattura di acquisto d'origine. +Quando l'IVA è dovuta da chi compra (inversione contabile, acquisti dall'estero) l'azienda deve **integrare** la +fattura ricevuta o emettere un'**autofattura** e trasmetterla allo SDI. Khaemhat lo riconosce da solo dalla fattura +fornitore (paese del fornitore, beni o servizi, natura IVA delle righe) e mostra sopra le righe quale documento serve e **entro quando**: -| Codice | Documento | Quando si usa | +| Tipo | Quando | Scadenza | |---|---|---| -| **TD16** | Integrazione fattura reverse charge interno | acquisti nazionali in inversione contabile (art. 17 c.6 DPR 633/72, es. subappalto edile) | -| **TD17** | Integrazione/autofattura per acquisto di servizi dall'estero | servizi da fornitori UE ed extra-UE | -| **TD18** | Integrazione per acquisto di beni intracomunitari | beni da fornitori UE | -| **TD19** | Integrazione/autofattura per acquisto di beni ex art. 17 c.2 DPR 633/72 | beni già in Italia acquistati da soggetti non residenti | -| **TD20** | Autofattura per regolarizzazione e integrazione delle fatture | regolarizzazione nei casi previsti (definizione aggiornata dalle specifiche v1.9) | -| **TD21** | Autofattura per splafonamento | acquisti oltre il plafond dell'esportatore abituale | -| **TD22** | Estrazione beni da deposito IVA | | -| **TD23** | Estrazione beni da deposito IVA con versamento dell'IVA | | -| **TD28** | Acquisti da San Marino con IVA | fatture cartacee con IVA da operatori sammarinesi | -| **TD29** | Comunicazione per omessa o irregolare fatturazione | introdotto con le specifiche v1.9 (dal 1° aprile 2025) | +| **AF16** (TD16) | inversione contabile interna: righe con natura N6.x (subappalti, rottami, cellulari…) | 15 del mese dopo il ricevimento | +| **AF17** (TD17) | servizi da un fornitore estero, UE o extra UE | 15 del mese dopo | +| **AF18** (TD18) | beni da un fornitore di un altro Paese UE | 15 del mese dopo | +| **AF19** (TD19) | beni già in Italia comprati da un soggetto non residente (art. 17 c.2) | 15 del mese dopo | +| **AF28** (TD28) | acquisti da San Marino con IVA in fattura | 15 del mese dopo | +| **AF20**, **AF29** | regolarizzazione di una fattura non ricevuta o irregolare | 90 giorni | +| AF21, AF22, AF23 | splafonamento, estrazione da deposito IVA | a mano, quando servono | -Come funziona (esempio TD17, mockup 035): +![Khaemhat 0.6.0 · integrazioni da emettere](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-autofatture-in-attesa.png) -1. La fattura estera viene registrata negli acquisti. -2. Si crea l'integrazione: le righe sono **riprese dalla fattura estera** con imponibile e aliquota; Khaemhat - calcola l'**IVA integrata**. -3. **Conferma e genera XML**: nell'XML il **fornitore estero** compare come cedente/prestatore e la **nostra azienda** - come cessionario/committente. -4. La registrazione va contemporaneamente nel **registro IVA vendite RC** e nel **registro IVA acquisti RC**: l'effetto - è **neutro** (IVA a debito = IVA a credito, salvo indetraibilità). Il pannello *Effetto contabile* mostra le due - righe. -5. L'XML va inviato **entro il 15 del mese successivo**: Khaemhat mostra la scadenza nel documento e un promemoria - nella dashboard. +**Acquisti → Autofatture** elenca in alto le **integrazioni da emettere**, la scadenza più vicina per prima. **Crea +autofattura** (qui o nella fattura fornitore) prepara il documento in bozza: le righe della fattura con il **codice IVA +ordinario** al posto della natura, il numero e la data della fattura del fornitore come documento collegato, la data +di oggi. Controllalo ed **emettilo**: prende il numero dal numeratore `AUT` delle autofatture. -Schede: *Righe*, *Testata*, *Registrazione IVA*, *XML SDI*, *Collegamenti*. Le definizioni ufficiali dei codici sono -in [Fiscalità italiana](Fiscalita-italiana). +Il **file XML** dell'autofattura (con il fornitore come cedente e l'azienda come cessionario) e l'invio allo SDI +arrivano con la [Fatturazione elettronica](Fatturazione-elettronica) (M9); la doppia registrazione nei registri IVA +vendite e acquisti con la [Contabilità](Contabilita) (M7). Le definizioni ufficiali dei codici TD sono in +[Fiscalità italiana](Fiscalita-italiana). ## Fatture da fornitori forfettari -Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2 nell'XML del fornitore) e riportano il -**bollo** quando dovuto; non sono soggette a ritenuta d'acconto. Nella scheda del fornitore il flag *Regime -forfettario* (gruppo *Ritenute e contributi*) indica questa situazione; i controlli automatici sulla fattura -importata saranno definiti in sviluppo. +Le fatture dei fornitori in **regime forfettario** non hanno IVA (natura N2.2) e riportano il **bollo** quando dovuto; +non sono soggette a ritenuta. All'import la riga prende il codice IVA dell'azienda con natura N2.2; non serve +nessuna autofattura. ## Stati -Ordini e DDT di carico seguono gli stati del motore documenti: *Bozza*, *Confermato*, *Ricevuto parzialmente* / -*Ricevuto*, *Chiuso*, *Annullato*. Le fatture di acquisto sono *Bozza* finché non vengono **registrate -(protocollate)**; i badge indicano anche *Da XML SDI*, *Verifica prezzi*, *Caricato a magazzino*, *Da fatturare*. +| Documento | Stati | +|---|---| +| Ordine fornitore, ricevimento | *Bozza*, *Confermato*, *Evaso in parte*, *Evaso*, *Chiuso*, *Annullato* | +| Fattura e nota di credito fornitore | *Bozza*, *Confermato* (protocollata), *Annullato* | +| Autofattura | *Bozza*, *Emessa* e, con la fatturazione elettronica, gli stati dello SDI | ## Permessi e licenza -Ordini, carichi, fatture di acquisto e import da file sono nel modulo **CORE**. La generazione e l'invio dell'XML -delle autofatture e lo scarico dal canale SDI richiedono **EINV**; la registrazione contabile e i registri IVA -**ACCT**; i pagamenti **FIN**. Costi e margini sono visibili solo a chi ha il permesso `items.cost.read`. +Ordini, ricevimenti, fatture, import e autofatture sono nel modulo **CORE**. Gli ordini richiedono +`purchases.order.read`/`write`; i ricevimenti, che muovono il magazzino, `inventory.entry.read`/`write` (e +`inventory.entry.post` per confermarli); fatture, note di credito, import e autofatture `purchases.invoice.read`/`write`. +L'XML delle autofatture richiederà **EINV**, la registrazione contabile **ACCT**, i pagamenti **FIN**. Costi e margini +sono visibili solo con `items.cost.read`. ## Domande frequenti -- **L'import segna "Duplicato".** La fattura risulta già importata: non va registrata una seconda volta (il - criterio esatto di riconoscimento sarà definito in sviluppo). -- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice del fornitore nella scheda articolo (*Fornitori*): - la volta successiva l'abbinamento sarà automatico. -- **Ho ricevuto meno merce di quella ordinata.** Conferma il DDT con la quantità ricevuta: il residuo resta aperto - sull'ordine. +- **L'import dice "Già registrata".** Lo stesso fornitore ha già un documento con quel numero nello stesso anno: non + va registrata due volte. +- **Una riga dell'XML non trova l'articolo.** Aggiungi il codice che usa il fornitore nella scheda articolo + (*Fornitori*, codice fornitore): dalla volta successiva l'abbinamento è automatico. +- **Ho ricevuto meno merce di quella ordinata.** Conferma il ricevimento con la quantità arrivata: il residuo resta + aperto sull'ordine e l'ordinato degli articoli lo tiene in conto. +- **La fattura ha un prezzo diverso dall'ordine.** L'avviso sopra le righe lo segnala; se la fattura è giusta + confermala e il costo medio si allinea al prezzo fatturato. +- **Non vedo l'avviso dell'autofattura.** Compare sulle fatture di fornitori esteri o con righe in natura N6.x, + finché non c'è un'autofattura collegata. L'elenco *Integrazioni da emettere* mostra solo le fatture **confermate**. ## Pagine correlate diff --git a/docs/wiki/Articoli-e-listini.md b/docs/wiki/Articoli-e-listini.md index 07585b6..ff3cc93 100644 --- a/docs/wiki/Articoli-e-listini.md +++ b/docs/wiki/Articoli-e-listini.md @@ -1,6 +1,6 @@ # Articoli e listini -> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti con il magazzino, M6) +> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti dalla 0.6.0, M6) > **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 descrittive e cespiti. Nella @@ -75,18 +75,20 @@ salvataggio. ### 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)). +- **Ultimo costo** e **costo medio**: li calcolano i carichi di magazzino (DDT fornitore, fatture fornitore, esistenze + iniziali, movimenti di carico) dalla versione 0.6.0. Il costo medio è il criterio di valorizzazione del magazzino + (vedi [Magazzino](Magazzino#costo-medio-e-valorizzazione)). - 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. ### Giacenze e riordino -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** l'articolo partecipa a movimenti, giacenze per deposito (*Giacenza, Impegnato, +Ordinato, Disponibile, Valore*) e **proposta di riordino** (vedi [Magazzino](Magazzino)). **Scorta minima**, **punto +di riordino** e **lotto di riordino** decidono lo stato dell'articolo nelle giacenze e la quantità proposta; il +**fornitore preferito** della scheda *Fornitori*, con prezzo, minimo d'ordine e lead time, è quello a cui la +proposta ordina. ### Controlli al salvataggio diff --git a/docs/wiki/Attivita-programmate.md b/docs/wiki/Attivita-programmate.md index faec5c4..1de2141 100644 --- a/docs/wiki/Attivita-programmate.md +++ b/docs/wiki/Attivita-programmate.md @@ -137,13 +137,16 @@ il dettaglio dell'ultima. Le esecuzioni sono registrate nel database di sistema. ## Job di sistema -Nella versione 0.2.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`): +Nella versione 0.6.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`): | Codice | Cosa fa | Quando | |---|---|---| | `system.sessions-cleanup` | elimina le sessioni scadute o revocate da più di 30 giorni, nel database di sistema e in ogni azienda non disattivata | al minuto 15 di ogni ora | | `system.license-check` | ricalcola la licenza; avvisa gli amministratori a 30, 14, 7, 3 e 1 giorno dalla scadenza e quando è scaduta | ogni ora | | `system.log-retention` | elimina gli eventi di log più vecchi della retention del loro livello | ogni notte alle 03:30 | +| `system.attachments-trash` | svuota il cestino degli allegati oltre i giorni di conservazione | ogni notte alle 03:45 | +| `system.ecb-rates` | scarica i cambi di riferimento della BCE (richiede la rete) | nei giorni feriali alle 16:30 | +| `inventory.rebuild` | ricostruisce il magazzino di ogni azienda attiva dai documenti in vigore (vedi [Magazzino](Magazzino#ricostruzione)) | la domenica alle 02:15 | Oltre alle attività degli amministratori, Khaemhat esegue sempre alcuni **job di sistema**: pulizia (log e sessioni secondo la retention), controllo della licenza, aggiornamento dei cambi BCE, lettura dell'inbox e dei canali SDI, diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index 7fa9a19..b30a694 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -1,6 +1,6 @@ # Changelog -> **Stato:** completa per 0.5.0 · **Ultima revisione:** 2026-11-12 +> **Stato:** completa per 0.6.0 · **Ultima revisione:** 2026-11-12 Le novità di ogni versione sono nel file [`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository @@ -11,6 +11,7 @@ Le novità di ogni versione sono nel file | Versione | Data | Contenuto | |---|---|---| +| 0.6.0 | 2026-11-12 | M6 — Acquisti e Magazzino: ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo e controllo dei prezzi; import delle fatture elettroniche XML, P7M e ZIP con fornitore e articoli abbinati; autofatture e integrazioni TD16-TD29 con la loro scadenza; giacenze per deposito con impegnato, ordinato e costo medio ponderato, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione; giacenze iniziali da file; acquisti e magazzino nei dati di esempio. | | 0.5.0 | 2026-11-12 | M5 — Motore documenti e Vendite: preventivi, ordini, DDT, fatture, note di credito, pro forma e parcelle con numerazione senza buchi, castelletto IVA, bollo, ritenute e scadenze; documenti collegati riga per riga e *Crea …* per passare dall'uno all'altro; fatturazione differita guidata; anteprima di stampa e PDF salvato tra gli allegati; invio per e-mail con SMTP interno; un anno di vendite nei dati di esempio; [Guida all'uso](Guida-utente) con le schermate. | | 0.4.0 | 2026-11-12 | M4 — Tabelle, anagrafiche, articoli: pacchetto fiscale italiano, profilo azienda, esercizi e cambi, 26 tabelle azienda con province, comuni e CAP, clienti, fornitori e contatti con controlli e VIES, articoli e listini con prezzi a validità, codici automatici, import/export guidato (anche del piano dei conti, per ora solo verifica) e dati di esempio. | | 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). | diff --git a/docs/wiki/Dashboard.md b/docs/wiki/Dashboard.md index 5ca7fb5..1326c54 100644 --- a/docs/wiki/Dashboard.md +++ b/docs/wiki/Dashboard.md @@ -56,7 +56,7 @@ magazzino* M6, *CRM* M11), senza numeri finti. | **Attività CRM** | le attività del giorno (chiamate, riunioni, visite) | richiede il modulo CRM | | **Promemoria personali** | note libere, visibili solo a te | | | **Scorciatoie** | pulsanti configurabili verso maschere e azioni frequenti | | -| **Sottoscorta** | articoli sotto la scorta minima | | +| **Sottoscorta** | gli articoli più urgenti da riordinare (esauriti, sottoscorta, sotto il punto di riordino) con disponibile e scorta; un clic apre i movimenti dell'articolo, **Riordina** la proposta di riordino | dalla 0.6.0 | | **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM | | **Ultimi documenti** | ultimi documenti aperti o creati | | | **Stato del sistema** | versione, database, cache, licenza, aziende aperte, attività programmate di oggi, ognuno con un pallino verde, giallo o rosso | solo account di istanza | diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index 85b07bf..7029ee1 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -1,6 +1,6 @@ # Dati di base e di esempio -> **Stato:** completa per M5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (dati di esempio di acquisti, magazzino e contabilità con i moduli, completi in M9) +> **Stato:** completa per M5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (dati di esempio di contabilità con il modulo, completi in M9) > **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14 ## A cosa serve @@ -148,7 +148,19 @@ pagina delle stampe) e **un anno di vendite** costruite con il motore dei docume Le fatture e la nota condividono il numeratore (`1/2026` … `7/2026`), senza buchi e in ordine di data. Tutti i documenti sono marcati come dimostrativi e la stampa lo scrive in evidenza. Il caricamento non si ripete se -l'azienda ha già documenti di vendita. Il resto della tabella arriva con le milestone dei rispettivi moduli. +l'azienda ha già documenti di vendita. + +**Da M6** ci sono anche **acquisti e magazzino**, costruiti allo stesso modo: + +| Documenti | Che cosa mostrano | +|---|---| +| 1 movimento di esistenze iniziali al 1° gennaio (`APE`) | la giacenza di partenza di ogni articolo; un articolo su cinque parte con poca merce, così le vendite lo portano sotto scorta e la [proposta di riordino](Magazzino#proposta-di-riordino) ha qualcosa da proporre | +| 2 ordini fornitori | uno ricevuto per intero, uno ricevuto in parte (il resto è nell'*ordinato*) | +| 2 ricevimenti merce | i carichi dei due ordini | +| 3 fatture fornitore | una dal ricevimento con un prezzo più alto dell'ordine (vedi l'avviso sulle differenze), la parcella del commercialista, la fattura di un fornitore tedesco che aspetta la sua **integrazione AF18** | +| 1 inventario aperto | 12 articoli già contati, due con una differenza | + +Il caricamento non si ripete se l'azienda ha già documenti di acquisto o di magazzino. 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. diff --git a/docs/wiki/Guida-utente.md b/docs/wiki/Guida-utente.md index 979fd8c..e5b266e 100644 --- a/docs/wiki/Guida-utente.md +++ b/docs/wiki/Guida-utente.md @@ -1,6 +1,6 @@ # Guida all'uso -> **Stato:** completa per la versione 0.5 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5) +> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6) Questa pagina accompagna chi usa Khaemhat ogni giorno: dall'accesso alla fattura inviata al cliente, un passo per volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina che lo spiega per intero. Chi deve @@ -9,18 +9,19 @@ volta, con le schermate della versione attuale. Ogni passo rimanda alla pagina c ## Che cosa c'è in questa versione -| Area | In 0.5.0 | Arriva con | +| Area | In 0.6.0 | Arriva con | |---|---|---| | Accesso e sicurezza | password, verifica in due passaggi, codici di recupero, blocco dopo i tentativi sbagliati | — | | Interfaccia | menu, schede, ricerca globale, notifiche, aiuto F1, dashboard a widget, temi e colori | — | | Tabelle azienda | profilo azienda, esercizi, cambi, codici IVA, pagamenti, banche, depositi, tipi documento, numeratori e le altre tabelle di base | — | | Anagrafiche | clienti, fornitori, contatti, controlli di partita IVA e codice fiscale, VIES | CRM (lead, opportunità): M11 | -| Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente | giacenze: M6 | -| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail | magazzino M6, contabilità M7, partite M8, XML SDI M9 | -| Acquisti e magazzino | — | M6 | +| Articoli | articoli, categorie, listini con prezzi a validità, prezzi netti per cliente, costo medio e ultimo costo dai movimenti | — | +| Vendite | preventivi, ordini, DDT, fatture, note, pro forma, fatturazione differita, stampa PDF, invio per e-mail, scarico del magazzino e impegno | contabilità M7, partite M8, XML SDI M9 | +| Acquisti | ordini fornitori, ricevimenti, fatture e note di credito fornitore con protocollo, controllo dei prezzi, import delle fatture elettroniche XML/P7M/ZIP, autofatture e integrazioni in bozza con scadenza | registri IVA M7, pagamenti M8, XML delle autofatture M9 | +| Magazzino | giacenze per deposito, impegnato e ordinato, costo medio, movimenti e trasferimenti, inventario fisico, proposta di riordino, valorizzazione con classi ABC, ricostruzione | libro inventari M7 | | Contabilità, IVA, scadenzario | — | M7, M8 | | Fatturazione elettronica | — | M9 | -| Import ed export | clienti, fornitori, articoli e prezzi da CSV, Excel e JSON; esportazione dai radar | giacenze iniziali M6, piano dei conti M7 | +| Import ed export | clienti, fornitori, articoli, prezzi e giacenze iniziali da CSV, Excel e JSON; esportazione dai radar | piano dei conti M7 | | Amministrazione da interfaccia | utenti e licenze da variabili e riga di comando | pagine di amministrazione: M12 | Le voci di menu delle aree non ancora pronte aprono una pagina che dice che cosa conterranno. @@ -121,22 +122,53 @@ La **stampante** della toolbar (`Ctrl+P`) apre l'anteprima: **Stampa** con la st Dal menu **⋯** del documento, **Invia per e-mail** propone destinatario, oggetto e testo; il PDF parte in allegato e l'esito finisce nel log. Vedi [Vendite](Vendite#invio-per-e-mail). -## 8. Allegati +## 8. Comprare + +![Fattura fornitore con differenza di prezzo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-fattura-differenze.png) + +Il ciclo passivo usa le stesse maschere delle vendite. In **Acquisti → Ordini fornitori** prepari l'ordine (il prezzo +è quello del fornitore nella scheda articolo); quando arriva la merce **Crea DDT fornitore (carico)** registra il +ricevimento, anche in più volte, e alla conferma carica il magazzino. **Crea Fattura fornitore** prepara la fattura: +alla conferma prende il **protocollo** IVA. Se il prezzo fatturato è diverso da quello dell'ordine o del ricevimento, +un avviso sopra le righe lo segnala. + +![Import delle fatture passive](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/acquisti-importa-fatture.png) + +Le fatture elettroniche ricevute si caricano da **Acquisti → Importa fatture**: XML, P7M o ZIP, anche molti file +insieme. Khaemhat trova o crea il fornitore, abbina gli articoli, scarta i doppioni e registra le fatture in bozza con +il file allegato. Per le fatture di fornitori esteri o in inversione contabile indica quale **autofattura** serve ed +entro quando; **Acquisti → Autofatture** le elenca tutte. Vedi [Acquisti](Acquisti). + +## 9. Il magazzino + +![Giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png) + +**Magazzino → Giacenze** mostra per ogni articolo giacenza, impegnato, ordinato, disponibile, costo medio e valore, +con lo stato rispetto a scorta minima e punto di riordino; apri una riga per vedere i movimenti. I documenti +confermati muovono il magazzino da soli: non serve registrare a parte carichi e scarichi. + +![Proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png) + +**Proposte di riordino** calcola che cosa ordinare e a quale fornitore e crea gli ordini in bozza, uno per fornitore. +**Inventario** guida il conteggio fisico (anche dal file del lettore di codici a barre) e registra le rettifiche; +**Valorizzazione** calcola il valore del magazzino a una data con le classi ABC. Vedi [Magazzino](Magazzino). + +## 10. Allegati ![Pannello allegati](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/allegati-pannello.png) Ogni anagrafica e ogni documento ha la scheda **Allegati**: carichi file dal computer, li vedi in anteprima, scarichi tutto in un archivio ZIP. I PDF che Khaemhat genera sono **versionati**: ogni stampa salvata o e-mail inviata aggiunge una versione e le precedenti restano. Vedi [Allegati e file](Allegati-e-file). -## 9. Importare ed esportare +## 11. Importare ed esportare ![Mappatura delle colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png) -**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli e prezzi di listino da un file +**Amministrazione → Import/Export** porta in Khaemhat clienti, fornitori, articoli, prezzi di listino e giacenze iniziali da un file CSV, Excel o JSON: scegli il file, abbini le colonne, guarda l'anteprima con gli errori riga per riga e conferma. Ogni radar esporta le righe visibili. Vedi [Import/Export](Import-Export). -## 10. Personalizzare +## 12. Personalizzare ![Il mio profilo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/preferenze-profilo.png) @@ -157,4 +189,5 @@ prezzi) sono in **Tabelle azienda → Preferenze**. Vedi [Preferenze utente](Pre [Primi passi](Primi-passi) · [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) · [Anagrafiche](Anagrafiche) · [Articoli e listini](Articoli-e-listini) · [Tabelle azienda](Tabelle-azienda) · [Vendite](Vendite) · +[Acquisti](Acquisti) · [Magazzino](Magazzino) · [Allegati e file](Allegati-e-file) · [Import/Export](Import-Export) · [Preferenze utente](Preferenze-utente) diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 5ad5149..fb78f92 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -1,6 +1,6 @@ # Khaemhat -> **Stato:** completa per 0.5.0 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.5.0 (M5; sviluppo in corso) +> **Stato:** completa per 0.6.0 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6; sviluppo in corso) ![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png) diff --git a/docs/wiki/Import-Export.md b/docs/wiki/Import-Export.md index 385c906..af9ccc5 100644 --- a/docs/wiki/Import-Export.md +++ b/docs/wiki/Import-Export.md @@ -1,6 +1,6 @@ # Import/Export -> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (scrittura di giacenze iniziali in M6, piano dei conti in M7; saldi e partite di apertura in M7 e M9) +> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (giacenze iniziali dalla 0.6.0, piano dei conti in M7; saldi e partite di apertura in M7 e M9) > **Modulo di licenza:** CORE (piano dei conti: ACCT) · **Livello richiesto:** amministratore, oppure permesso di scrittura o di export dell'entità · **Specifica:** SPEC §11.7, §12.12 · **Decisione:** ADR 0031 ## A cosa serve @@ -94,11 +94,14 @@ obbligatoria. Unità alternative, codici alternativi, fornitori e sostitutivi re netto), non entrambi. Stesso articolo, listino o cliente e data: il prezzo si sostituisce; una data nuova aggiunge un prezzo che vale da quel giorno, come nella griglia dei listini. Le righe senza errori si scrivono tutte insieme. -### Giacenze iniziali (solo verifica fino a M6) +### Giacenze iniziali -`articolo`\*, `deposito` (vuoto: il deposito dell'articolo), `quantita`\* (maggiore di zero), `costo_unitario`. -L'articolo deve essere merce gestita a magazzino. Il controllo serve a preparare il file: la scrittura del movimento -di apertura arriva con il [Magazzino](Magazzino). +`articolo`\*, `deposito` (vuoto: il deposito dell'articolo, poi quello predefinito), `quantita`\* (maggiore di zero), +`costo_unitario` (vuoto: costo medio, standard o ultimo costo dell'articolo). L'articolo deve essere merce gestita a +magazzino e non può comparire due volte nello stesso deposito. Dalla 0.6.0 l'import scrive **un movimento di +magazzino per deposito** con la causale `APE` (esistenza iniziale) alla data dell'import e lo conferma: giacenze e +costo medio partono da lì (vedi [Magazzino](Magazzino#esistenze-iniziali)). Se la causale `APE` manca, le righe sono +saltate con un messaggio: aggiungila con *Aggiorna da tabelle base*. ### Piano dei conti (solo verifica fino a M7) diff --git a/docs/wiki/Magazzino.md b/docs/wiki/Magazzino.md index f00e295..b7cf4f7 100644 --- a/docs/wiki/Magazzino.md +++ b/docs/wiki/Magazzino.md @@ -1,148 +1,194 @@ # Magazzino -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M6) -> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.entry.post`, `items.cost.read`, famiglia `inventory.*` · **Specifica:** SPEC §11.6, §22 +> **Stato:** completa per la versione 0.6 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.6.0 (M6) +> **Modulo di licenza:** CORE · **Permessi principali:** `inventory.stock.read` (giacenze), `inventory.entry.*` (movimenti, inventario), `inventory.entry.post` (conferma, rettifiche, ricostruzione), `items.cost.read` (costi e valori) · **Specifica:** SPEC §11.6, ADR 0035 Il **magazzino** tiene la quantità e il valore di ogni articolo in ogni **deposito**. Le giacenze si aggiornano da -sole con i documenti (DDT, fatture accompagnatorie, carichi, resi) e con i movimenti manuali; da qui si fanno -trasferimenti tra depositi, inventari fisici, la proposta di riordino e la valorizzazione. +sole quando confermi un documento che muove la merce (DDT, fatture accompagnatorie, carichi dai fornitori, resi, +movimenti manuali); da qui consulti giacenze e movimenti, fai l'**inventario fisico**, generi la **proposta di +riordino** e calcoli la **valorizzazione** a una data. + +> **In questa versione** ci sono giacenze per deposito, impegnato e ordinato, costo medio ponderato, movimenti per +> articolo, movimenti manuali e trasferimenti, inventario fisico con import dei conteggi, proposta di riordino, +> valorizzazione con analisi ABC e ricostruzione. Arrivano più avanti: le **scritture contabili** delle rimanenze e il +> **libro inventari** (M7), i report di magazzino stampabili (M13), FIFO e LIFO a lotti (dopo la 1.0). ## Dove si trova -Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario fisico*, *Sottoscorta* (proposta di riordino), -*Trasferimenti*. I depositi e le causali di magazzino sono in [Tabelle azienda](Tabelle-azienda). +Menu **Magazzino** → *Giacenze*, *Movimenti*, *Inventario*, *Proposte di riordino*. I **depositi** e le **causali +di magazzino** sono in [Tabelle azienda](Tabelle-azienda); scorta minima, punto e lotto di riordino e fornitori +abituali sono nella scheda dell'articolo (vedi [Articoli e listini](Articoli-e-listini)). -## Le quattro quantità +## Le quantità | Quantità | Significato | Da dove nasce | |---|---|---| -| **Giacenza** | merce fisicamente presente nel deposito | carichi e scarichi confermati | -| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | ordini clienti, trasferimenti in bozza | -| **Ordinato** | merce in arrivo dai fornitori | ordini fornitore confermati e non ancora ricevuti | -| **Disponibile** | **giacenza - impegnato** | calcolata | +| **Giacenza** | merce presente nel deposito | movimenti dei documenti confermati | +| **Impegnato** | merce riservata a ordini clienti confermati e non ancora evasi | residuo degli ordini clienti | +| **Ordinato** | merce in arrivo dai fornitori | residuo degli ordini fornitore confermati | +| **Disponibile** | giacenza meno impegnato | calcolata | -Il sistema registra anche la merce **in transito** e il **valore medio** per articolo e deposito. Tutte queste -quantità sono aggiornate **nella stessa transazione** del documento che le muove: non c'è mai un momento in cui il -documento è confermato e la giacenza no. +Tutte si aggiornano **nella stessa operazione** che conferma il documento: non c'è mai un momento in cui il documento +è confermato e la giacenza no. Se annulli il documento, i suoi movimenti spariscono e le quantità tornano come prima. + +## Quali documenti muovono il magazzino + +Ogni tipo documento ha una **causale di magazzino** (in *Tabelle azienda → Tipi documento*) che decide se carica, +scarica o trasferisce. Con i tipi di base: + +| Documento | Causale | Effetto | +|---|---|---| +| DDT, fattura immediata, fattura accompagnatoria | `SCA` scarico per vendita | scarica al costo medio | +| DDT fornitore (carico), fattura fornitore | `CAR` carico da acquisto | carica e aggiorna il costo medio | +| Nota di credito fornitore | `RESF` reso a fornitore | scarica | +| Movimento di magazzino (`MM`) | quella scelta nel movimento | carico, scarico o trasferimento | +| Ordini clienti e fornitori, preventivi, fatture differite | nessuna | solo impegnato e ordinato | + +Una fattura nata da un DDT **non muove di nuovo** la merce: le sue righe trovano il carico o lo scarico già fatto +dal DDT. Il prezzo della fattura fornitore però **corregge il costo** del carico: se il fornitore fattura a un prezzo +diverso da quello del DDT, il costo medio viene ricalcolato con il prezzo fatturato. + +Le causali di base sono: `CAR` carico da acquisto, `SCA` scarico per vendita, `RESC` reso da cliente, `RESF` reso a +fornitore, `TRA` trasferimento tra depositi, `INVP` e `INVN` rettifiche inventariali, `CVU` e `CVR` uscita e rientro +in conto visione (solo quantità), `OMA` omaggio, `AUTO` autoconsumo, `APE` esistenza iniziale. Per un'azienda creata +con una versione precedente le causali e i tipi documento mancanti si aggiungono con **Aggiorna da tabelle base** nel +menu `…` della tabella (vedi [Tabelle azienda](Tabelle-azienda)) o, per tutte le tabelle, con `scripts/seed.sh --base`. ## Giacenze e disponibilità -![036 · Giacenze, disponibilità, sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/036-giacenze.png) -*Mockup 036 — striscia di indicatori (valore magazzino, articoli gestiti, sottoscorta, sotto riordino, in arrivo) e griglia giacenze con stato (anteprima ridotta).* +![Khaemhat 0.6.0 · giacenze e disponibilità](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-giacenze.png) -In alto una **striscia di indicatori**: valore del magazzino, articoli gestiti, articoli **sottoscorta**, articoli -**sotto il punto di riordino**, valore **in arrivo** (ordinato). +In alto la striscia degli indicatori: **articoli in giacenza**, **sottoscorta**, **esauriti**, **articoli in +arrivo** (con ordini fornitore aperti) e **valore di magazzino** (visibile solo con `items.cost.read`). -La griglia mostra per ogni articolo: categoria, UM, **giacenza**, **impegnato**, **ordinato**, **disponibile**, -**scorta minima**, **punto di riordino**, **costo medio**, **valore** e uno **stato**: +Sotto, il filtro **Deposito** (tutti o uno solo) e la casella **Anche gli articoli senza giacenza**; poi il radar +con ricerca per codice o descrizione e i filtri rapidi **Categoria** e **Stato**. Per ogni articolo: categoria, unità, +giacenza, impegnato, ordinato, disponibile, scorta minima, costo medio, valore e uno **stato**: | Stato | Quando | |---|---| -| *OK* | disponibilità sopra il punto di riordino | -| *Sotto riordino* | disponibilità sotto il punto di riordino | -| *Sottoscorta* | disponibilità sotto la scorta minima (riga evidenziata) | -| *Esaurito · in arrivo* | giacenza a zero con ordini fornitore aperti | +| *Disponibile* | il disponibile più l'ordinato supera il punto di riordino | +| *Da riordinare* | disponibile più ordinato pari o sotto il punto di riordino | +| *Sottoscorta* | disponibile sotto la scorta minima | +| *Esaurito* | disponibile sotto zero, o a zero per un articolo con scorta minima o punto di riordino | -Filtri: ricerca (articolo, EAN, descrizione), **Deposito**, **Categoria**, **Mostra** (*Solo gestiti a magazzino*), -chip *Evidenzia sottoscorta*. Azioni: **Proposta di riordino**, **Inventario**. Il dettaglio per deposito di un -singolo articolo è anche nella scheda articolo (vedi [Articoli e listini](Articoli-e-listini)). +Le colonne *Ultimo carico* e *Ultimo scarico* si aggiungono dal selettore delle colonne del radar. I pulsanti +portano alla **proposta di riordino** e all'**inventario**, aprono la **valorizzazione** e la **ricostruzione**. -## Movimenti e trasferimenti +## Movimenti di un articolo -![037 · Movimento di magazzino manuale (trasferimento)](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/037-movimento-magazzino.png) -*Mockup 037 — trasferimento in bozza dal deposito SEDE al deposito furgone, con disponibilità all'origine e valore (anteprima ridotta).* +![Khaemhat 0.6.0 · movimenti di un articolo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-movimenti-articolo.png) -I **movimenti manuali** servono per tutto ciò che non passa da un documento di vendita o acquisto: carichi e scarichi -rettificativi, omaggi interni, consumi, **trasferimenti** tra depositi. Ogni movimento ha una **causale di -magazzino** che ne stabilisce l'effetto (carico, scarico, trasferimento). +Apri una riga delle giacenze (doppio clic o **Invio**) per vedere i movimenti dell'articolo in ordine di data: il +documento che li ha generati (il link lo apre), la causale, il cliente o fornitore, il deposito, la quantità, il +costo unitario e il **saldo progressivo**. **Apri l'articolo** porta alla scheda. Il widget *Sottoscorta* della +[Dashboard](Dashboard) apre direttamente questa finestra sull'articolo scelto. -Per un trasferimento: +## Movimenti manuali e trasferimenti -1. **Magazzino → Trasferimenti** (o *Movimenti*), **Nuovo**. -2. Scegli la causale di trasferimento, il **deposito di origine** e quello di **destinazione**. -3. Inserisci le righe: la colonna *Disp. origine* mostra quanto è disponibile nel deposito di partenza. -4. Se serve, **Stampa lista prelievo** per chi prepara la merce. -5. **Conferma**. +Per tutto ciò che non passa da un documento di vendita o acquisto (rettifiche, omaggi, autoconsumi, conto visione, +trasferimenti) usa **Magazzino → Movimenti** e crea un **Movimento di magazzino**: è un documento come gli altri +(vedi [Vendite](Vendite) per la maschera), con in più la **causale** e il **deposito**. -Un trasferimento genera **due movimenti collegati** (scarico dall'origine e carico nella destinazione) nella stessa -transazione. Finché il movimento è in bozza la merce dell'origine risulta **impegnata**. +1. Scegli la **causale**: decide se il movimento carica, scarica o trasferisce. +2. Indica il **deposito**; per un trasferimento anche il **deposito di destinazione**, diverso dall'origine. +3. Inserisci le righe con articolo e quantità; nei carichi il prezzo è il costo unitario. +4. **Conferma**: il magazzino si aggiorna. Un trasferimento scarica l'origine e carica la destinazione al costo medio, + senza cambiare il valore complessivo. + +Un movimento confermato si può annullare: i suoi movimenti vengono tolti e le giacenze ricalcolate. ## Inventario fisico -![038 · Inventario fisico con conteggi e rettifiche](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/038-inventario-fisico.png) -*Mockup 038 — inventario guidato in cinque passi, griglia con giacenza teorica, contato, differenza, valore e rettifica (anteprima ridotta).* +![Khaemhat 0.6.0 · inventario fisico in conteggio](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-inventario.png) -L'inventario è una procedura guidata: +L'inventario confronta la merce contata con la **giacenza contabile** e trasforma le differenze in rettifiche. -1. **Preparazione**: scegli il **deposito**, la **data** e il criterio di **valorizzazione** (es. costo medio); - l'opzione **Blocca movimenti durante il conteggio** congela le giacenze del deposito. -2. **Conteggio**: **Stampa liste di conteggio** (anche per ubicazione e squadra) e inserisci i quantitativi contati - nella griglia oppure **Importa conteggi CSV**. -3. **Verifica differenze**: la griglia confronta **giacenza teorica** e **contato** e mostra differenza e valore; - il filtro *Solo differenze e da contare* aiuta a chiudere il lavoro. -4. **Rettifiche**: **Genera rettifiche** crea i movimenti di carico o scarico per allineare la giacenza al contato. -5. **Chiusura**: sblocca il deposito. +1. **Apertura**: in **Magazzino → Inventario** scegli il **deposito**, la **data del conteggio**, se vuoi una + **categoria** e una descrizione, poi **Apri inventario**. Khaemhat fotografa la giacenza contabile di ogni articolo + gestito a magazzino a quella data. +2. **Conteggio**: scrivi le quantità contate nella colonna *Contato* e premi **Salva conteggi**, oppure **Importa + conteggi** da un file CSV o di testo del lettore di codici a barre: una riga per articolo con *codice articolo* e + *quantità*, separati da punto e virgola, tabulazione o virgola (con la virgola la quantità usa il punto decimale). + Una riga di intestazione viene saltata; i codici non in lista sono segnalati. +3. **Verifica differenze**: il filtro **Mostra** (*Tutti*, *Da contare*, *Con differenze*) aiuta a chiudere il + lavoro; le righe con differenza sono evidenziate e la striscia in alto riassume articoli contati, differenze e + valore delle differenze. +4. **Registrazione**: **Registra rettifiche** crea alla data del conteggio un movimento `INVP` per le eccedenze e uno + `INVN` per gli ammanchi, e chiude l'inventario. Gli articoli **non contati restano come sono**. + +**Annulla inventario** lo chiude senza muovere il magazzino; i conteggi restano consultabili. I movimenti successivi +alla data del conteggio non disturbano: le rettifiche sono alla data del conteggio e la giacenza di oggi tiene conto +di entrambi. ## Proposta di riordino -![039 · Proposta di riordino fornitori dal sottoscorta](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/039-proposta-di-riordino.png) -*Mockup 039 — proposta di riordino: indicatori, criterio di calcolo, quantità proposta modificabile e fornitore per riga (anteprima ridotta).* +![Khaemhat 0.6.0 · proposta di riordino](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-riordino.png) -La proposta elenca gli articoli sotto il punto di riordino con giacenza, impegnato, ordinato, disponibile, scorta -minima, punto e **lotto** di riordino, **quantità proposta** (modificabile), **fornitore** abituale, lead time, -prezzo e valore. In alto gli indicatori: articoli sotto riordino, proposte, valore, fornitori coinvolti, articoli -già coperti da ordini. +La proposta elenca gli articoli il cui **disponibile più ordinato** non copre più il **punto di riordino** (o, se manca, +la **scorta minima**). Per ogni articolo propone: -1. Scegli **deposito**, **fornitore** (o tutti) e il **criterio di calcolo** (es. *disponibile + ordinato < punto - di riordino*, con o senza l'impegnato). -2. **Ricalcola**, controlla e correggi le quantità proposte, togli la spunta alle righe da non ordinare. -3. **Genera ordini fornitore**: Khaemhat crea **un ordine in bozza per fornitore** (vedi [Acquisti](Acquisti)). +- la **quantità**: il **lotto di riordino** dell'articolo se c'è, altrimenti quanto riporta al punto di riordino (o + alla scorta minima); mai meno del **minimo d'ordine** del fornitore; +- il **fornitore abituale** (il preferito nella scheda articolo, *Fornitori*) con il suo prezzo e la **data di arrivo + prevista** dal lead time. -Il mockup indica come fabbisogno il maggiore tra il lotto e la differenza fra punto di riordino e disponibile più -ordinato; la formula definitiva (compresi gli arrotondamenti al lotto) sarà fissata in sviluppo. La proposta può -anche essere eseguita da una procedura pianificata o alimentata da una regola di automazione (evento *articolo sotto -il punto di riordino*, vedi [Automazioni](Automazioni)). +Correggi le quantità, cambia il fornitore di una riga o togli la spunta alle righe da non ordinare; **Ricalcola** +rilegge le giacenze. **Genera ordini fornitore** crea **un ordine in bozza per fornitore** con prezzi e condizioni del +fornitore: controllali e confermali da **Acquisti → Ordini fornitori** (vedi [Acquisti](Acquisti)). Le righe senza +fornitore non vengono ordinate. ## Costo medio e valorizzazione -- Il criterio di valorizzazione è il **costo medio ponderato**: a ogni carico il nuovo costo medio è - (valore della giacenza esistente + valore del carico) / (giacenza esistente + quantità caricata). FIFO e LIFO sono - predisposti ma non attivi. -- Il **valore** di una giacenza è quantità x costo medio. -- La **valorizzazione a data** ricostruisce quantità e valore a una data passata (ad esempio al 31 dicembre). -- Le **rimanenze finali** valorizzate alimentano la chiusura dell'esercizio e il **libro inventari** (vedi - [Contabilità](Contabilita)); sono disponibili le **scritture ausiliarie di magazzino** e l'**analisi ABC**. +![Khaemhat 0.6.0 · valorizzazione con classi ABC](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/magazzino-valorizzazione.png) + +- Il criterio è il **costo medio ponderato** per articolo, su tutti i depositi: a ogni carico con valore il nuovo + costo medio è (valore della giacenza + valore del carico) / (giacenza + quantità caricata). Scarichi, trasferimenti + e conto visione escono al costo medio del momento e non lo cambiano. +- La scheda articolo mostra **costo medio** e **ultimo costo** calcolati dai movimenti. +- La **valorizzazione** (pulsante nelle giacenze) calcola quantità e valore **a una data** qualsiasi, anche passata, + con il criterio scelto: *costo medio ponderato*, *ultimo costo* o *costo standard*. Divide gli articoli in **classi + ABC**: A gli articoli che fanno l'80% del valore, B fino al 95%, C il resto. +- FIFO e LIFO sono previsti con la gestione a lotti; le rimanenze alimenteranno la chiusura dell'esercizio e il libro + inventari con la [Contabilità](Contabilita) (M7). ## Ricostruzione -Se le giacenze risultassero non allineate (ad esempio dopo un ripristino o un import), la **ricostruzione** ricalcola -giacenze, impegnato, ordinato e costi medi ripercorrendo tutti i movimenti. È una procedura eseguibile a mano o da -attività programmata e non modifica i documenti. Vedi [Automazioni](Automazioni) e -[Attività programmate](Attivita-programmate). +Se le giacenze sembrano non tornare (dopo un ripristino, un import diretto nel database, un cambio di causale su un +tipo documento), **Ricostruisci** nelle giacenze riscrive tutti i movimenti dai documenti in vigore, dal più vecchio, +e ricalcola giacenze, impegnato, ordinato e costi. I documenti non cambiano e i dati restano consultabili durante il +lavoro, che mostra l'avanzamento. Richiede `inventory.entry.post`. -## Stati dei movimenti +La stessa ricostruzione gira ogni **domenica alle 2:15** come attività di sistema *Ricostruzione del magazzino* (vedi +[Attività programmate](Attivita-programmate)), su tutte le aziende attive. -| Stato | Effetto | -|---|---| -| **Bozza** | nessun effetto sulla giacenza (nei trasferimenti l'origine è impegnata) | -| **Confermato** | giacenze aggiornate; righe non più modificabili | -| **Annullato** | movimenti stornati | +## Esistenze iniziali + +Per partire con le giacenze di un altro gestionale importa il tracciato **Giacenze iniziali** da +[Import ed export](Import-Export): articolo, deposito, quantità e costo unitario. Khaemhat crea e conferma un +movimento con causale `APE` per deposito, alla data dell'import. ## Permessi e licenza -Il magazzino è nel modulo **CORE**. Confermare un movimento richiede `inventory.entry.post`; vedere costi e valori -richiede `items.cost.read`. +Il magazzino è nel modulo **CORE**. Vedere giacenze e movimenti richiede `inventory.stock.read`; scrivere movimenti +e conteggi `inventory.entry.write`; confermare i movimenti, registrare le rettifiche e ricostruire +`inventory.entry.post`. Costi, valori e valorizzazione sono visibili solo con `items.cost.read`. ## Domande frequenti - **Il disponibile è negativo.** Gli ordini clienti confermati impegnano più merce di quella in giacenza: ordina al fornitore o rivedi le consegne. -- **Il costo medio è cambiato dopo un carico.** È il comportamento previsto del costo medio ponderato; il messaggio - sul DDT di carico indica il vecchio e il nuovo valore. -- **Durante l'inventario non riesco a scaricare merce dal deposito.** È attivo il blocco dei movimenti: termina la - procedura o disattiva il blocco. +- **La giacenza è negativa.** È stato confermato uno scarico senza merce a sufficienza (Khaemhat non lo blocca, per + non fermare le consegne): registra il carico mancante o fai un inventario. +- **Il costo medio è cambiato dopo una fattura fornitore.** Il prezzo fatturato era diverso da quello del DDT di + carico: il costo del carico viene corretto con il prezzo della fattura. +- **Un articolo non compare nelle giacenze.** Non ha movimenti: spunta *Anche gli articoli senza giacenza*. Se non + compare comunque, nella scheda non è *gestito a magazzino* o non è un bene. +- **L'articolo non è nella proposta di riordino.** Non ha punto di riordino né scorta minima, oppure l'ordinato già + lo copre. ## Pagine correlate [Articoli e listini](Articoli-e-listini) · [Acquisti](Acquisti) · [Vendite](Vendite) · -[Tabelle azienda](Tabelle-azienda) · [Report](Report) · [Contabilità](Contabilita) · [Automazioni](Automazioni) +[Tabelle azienda](Tabelle-azienda) · [Import ed export](Import-Export) · [Dashboard](Dashboard) · +[Attività programmate](Attivita-programmate) diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index dc2906b..ee677f5 100644 --- a/docs/wiki/Roadmap.md +++ b/docs/wiki/Roadmap.md @@ -13,7 +13,7 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo quando verrà deciso esplicitamente. -**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0). **Prossima:** M6. +**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0), M5 (0.5.0), M6 (0.6.0). **Prossima:** M7. | # | Milestone | Contenuto principale | Versione | |---|---|---|---| diff --git a/docs/wiki/Vendite.md b/docs/wiki/Vendite.md index 2c65130..88c1a20 100644 --- a/docs/wiki/Vendite.md +++ b/docs/wiki/Vendite.md @@ -9,8 +9,9 @@ accompagnatorie, differite, di acconto, parcelle), **note di credito e di debito e si inviano per e-mail. > **In questa versione** i documenti hanno numeri, totali, castelletto IVA, bollo, ritenute, scadenze, collegamenti -> riga per riga, stampa ed e-mail. Arrivano più avanti: lo **scarico di magazzino** e l'impegno (M6, con il -> magazzino), la **registrazione contabile** (M7), le **partite** e il controllo del fido (M8), il **file XML** per lo +> riga per riga, stampa ed e-mail. Dalla 0.6 i documenti **muovono il magazzino** (DDT e fatture +> accompagnatorie scaricano, gli ordini impegnano: vedi [Magazzino](Magazzino)). Arrivano più avanti: la +> **registrazione contabile** (M7), le **partite** e il controllo del fido (M8), il **file XML** per lo > SDI (M9) e il collegamento alle opportunità del **CRM** (M11). I pulsanti di queste funzioni compaiono quando la > funzione c'è. @@ -148,8 +149,8 @@ e CUP, riportati nella stampa. Il DDT accompagna la merce: si compila la scheda *Trasporto* e si stampa con gli spazi per le firme. Un DDT confermato non ancora fatturato compare nella **fatturazione differita**; un DDT fatturato risulta *Evaso*. Finché non è -fatturato le righe si possono ancora correggere; **Annulla documento** lo annulla con un motivo. Lo scarico del -magazzino arriva con M6. +fatturato le righe si possono ancora correggere; **Annulla documento** lo annulla con un motivo. Alla conferma il DDT +**scarica il magazzino** (causale `SCA`); la fattura differita che lo fattura non scarica di nuovo. ## Fatture diff --git a/docs/wiki/img/acquisti-autofatture-in-attesa.png b/docs/wiki/img/acquisti-autofatture-in-attesa.png new file mode 100644 index 0000000..fda7d79 Binary files /dev/null and b/docs/wiki/img/acquisti-autofatture-in-attesa.png differ diff --git a/docs/wiki/img/acquisti-fattura-autofattura.png b/docs/wiki/img/acquisti-fattura-autofattura.png new file mode 100644 index 0000000..0fd28a8 Binary files /dev/null and b/docs/wiki/img/acquisti-fattura-autofattura.png differ diff --git a/docs/wiki/img/acquisti-fattura-differenze.png b/docs/wiki/img/acquisti-fattura-differenze.png new file mode 100644 index 0000000..5b49225 Binary files /dev/null and b/docs/wiki/img/acquisti-fattura-differenze.png differ diff --git a/docs/wiki/img/acquisti-importa-fatture.png b/docs/wiki/img/acquisti-importa-fatture.png new file mode 100644 index 0000000..7aaf16e Binary files /dev/null and b/docs/wiki/img/acquisti-importa-fatture.png differ diff --git a/docs/wiki/img/acquisti-ricevimento.png b/docs/wiki/img/acquisti-ricevimento.png new file mode 100644 index 0000000..47a3f99 Binary files /dev/null and b/docs/wiki/img/acquisti-ricevimento.png differ diff --git a/docs/wiki/img/magazzino-giacenze.png b/docs/wiki/img/magazzino-giacenze.png new file mode 100644 index 0000000..b592ba2 Binary files /dev/null and b/docs/wiki/img/magazzino-giacenze.png differ diff --git a/docs/wiki/img/magazzino-inventario.png b/docs/wiki/img/magazzino-inventario.png new file mode 100644 index 0000000..3f3a1f8 Binary files /dev/null and b/docs/wiki/img/magazzino-inventario.png differ diff --git a/docs/wiki/img/magazzino-movimenti-articolo.png b/docs/wiki/img/magazzino-movimenti-articolo.png new file mode 100644 index 0000000..03e2cd3 Binary files /dev/null and b/docs/wiki/img/magazzino-movimenti-articolo.png differ diff --git a/docs/wiki/img/magazzino-riordino.png b/docs/wiki/img/magazzino-riordino.png new file mode 100644 index 0000000..43a10d3 Binary files /dev/null and b/docs/wiki/img/magazzino-riordino.png differ diff --git a/docs/wiki/img/magazzino-valorizzazione.png b/docs/wiki/img/magazzino-valorizzazione.png new file mode 100644 index 0000000..983c4ed Binary files /dev/null and b/docs/wiki/img/magazzino-valorizzazione.png differ diff --git a/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs b/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs index af7b74c..a0d7f63 100644 --- a/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs +++ b/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs @@ -105,7 +105,7 @@ public static class WidgetCatalog new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"), new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core), new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core), - new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"), + new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read"), new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"), new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"), new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true), diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index a13a8c6..755b410 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -1,4 +1,5 @@ using Khaemhat.Application.Audit; +using Khaemhat.Application.Inventory; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Documents; @@ -89,6 +90,15 @@ public static class DocumentErrors /// Error: a line of an invoice without its VAT code. public const string LineTaxRequired = "document.line.tax-required"; + + /// A supplier invoice needs the number and date the supplier gave it. + public const string SupplierNumberRequired = "document.purchase.number-required"; + + /// The same supplier already has a document of the kind with that number in that year. + public const string SupplierDuplicate = "document.purchase.duplicate"; + + /// The VAT date comes before the date of the supplier document. + public const string VatDateBefore = "document.purchase.vat-date-before"; } /// @@ -240,6 +250,7 @@ public sealed partial class DocumentEngine } var errors = Check(definition, record, before); + await CheckSupplierDocumentAsync(uow, record, confirming: false, errors, cancellationToken).ConfigureAwait(false); if (errors.Count > 0) { throw new ValidationFailedException(errors); @@ -257,6 +268,7 @@ public sealed partial class DocumentEngine if (before is not null && DocumentStateMachine.IsInForce(header.Status)) { await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false); + await InventoryPoster.SyncAsync(uow, record.Family, id, cancellationToken).ConfigureAwait(false); } await uow.CommitAsync(cancellationToken).ConfigureAwait(false); @@ -300,6 +312,8 @@ public sealed partial class DocumentEngine errors.Add("Lines:" + DocumentErrors.LinesRequired); } + await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false); + if (definition.Behavior.Has(DocumentEffects.Ledger)) { // A document that goes to the VAT registers needs the VAT of every line with an amount. @@ -329,12 +343,20 @@ public sealed partial class DocumentEngine } header.Year = header.DocumentDate.Year; + if (IsRegistered(header.Kind)) + { + // A supplier invoice takes its protocol from the numbering of the purchase register (§11.5). + header.VatProtocol = header.Number; + header.VatDate ??= header.DocumentDate; + } + header.Status = next; header.ConfirmedAt = _clock.GetUtcNow().UtcDateTime; header.ConfirmedBy = actor.UserName; await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false); await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false); await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false); + await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false); await uow.CommitAsync(cancellationToken).ConfigureAwait(false); LogConfirmed(_logger, header.Kind, header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), header.Status, company, actor.UserName); } @@ -679,6 +701,8 @@ public sealed partial class DocumentEngine await after(uow, record, actor.UserName, cancellationToken).ConfigureAwait(false); } + // A cancelled delivery note gives its stock back; a closed or reopened order its open quantities. + await InventoryPoster.SyncAsync(uow, family, id, cancellationToken).ConfigureAwait(false); await uow.CommitAsync(cancellationToken).ConfigureAwait(false); LogChanged(_logger, record.Header.Kind, record.Header.DocumentNumber ?? id.ToString(System.Globalization.CultureInfo.InvariantCulture), action, next, company, actor.UserName); } @@ -834,6 +858,52 @@ public sealed partial class DocumentEngine header.Revision = 0; } + // Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date. + private static bool IsRegistered(DocumentKind kind) => kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote; + + // The rules of a supplier document (§11.5): its own number and date, the VAT date not before it, no duplicate of + // the same supplier, kind, number and year among the documents in force or in draft. + private static async Task CheckSupplierDocumentAsync(IUnitOfWork uow, DocumentRecord record, bool confirming, List errors, CancellationToken cancellationToken) + { + var header = record.Header; + if (!IsRegistered(header.Kind)) + { + return; + } + + var number = header.ExternalReference?.Trim(); + if (confirming && string.IsNullOrEmpty(number)) + { + errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierNumberRequired); + } + + if (confirming && header.ExternalDate is null) + { + errors.Add(nameof(DocumentHeader.ExternalDate) + ":" + DocumentErrors.SupplierNumberRequired); + } + + if (header.VatDate is { } vatDate && header.ExternalDate is { } supplierDate && vatDate < supplierDate) + { + errors.Add(nameof(DocumentHeader.VatDate) + ":" + DocumentErrors.VatDateBefore); + } + + if (string.IsNullOrEmpty(number) || header.PartyId is not { } party) + { + return; + } + + var year = (header.ExternalDate ?? header.DocumentDate).Year; + var kind = header.Kind; + var id = header.Id; + var others = (await uow.Repository().ListAsync( + Query.For().Where(d => d.PartyId == party && d.Kind == kind && d.ExternalReference == number && d.Id != id && d.Status != DocumentStatus.Cancelled), + cancellationToken).ConfigureAwait(false)).Items; + if (others.Any(d => (d.ExternalDate ?? d.DocumentDate).Year == year)) + { + errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierDuplicate); + } + } + private static string Company(Actor actor, string companyCode) { ArgumentNullException.ThrowIfNull(actor); diff --git a/src/Khaemhat.Application/Documents/DocumentStores.cs b/src/Khaemhat.Application/Documents/DocumentStores.cs index aa55ea5..3f6a94c 100644 --- a/src/Khaemhat.Application/Documents/DocumentStores.cs +++ b/src/Khaemhat.Application/Documents/DocumentStores.cs @@ -40,6 +40,12 @@ internal interface IDocumentStore /// The lines. Task> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken); + /// Reads the headers of the documents in force (neither drafts nor cancelled). + /// The unit of work. + /// Cancellation. + /// The headers. + Task> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken); + /// Reads a line. /// The unit of work. /// The line. @@ -136,6 +142,11 @@ internal sealed class DocumentStore(DocumentFamily family, strin public async Task GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) => await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + /// + public async Task> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken) => + [.. (await uow.Repository().ListAsync( + Query.For().Where(h => h.Status != DocumentStatus.Draft && h.Status != DocumentStatus.Cancelled), cancellationToken).ConfigureAwait(false)).Items]; + /// public async Task> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken) { diff --git a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs index 108a6b3..d66782f 100644 --- a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs +++ b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs @@ -2,10 +2,6 @@ using Khaemhat.Application.Modules; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Accounting; -using Khaemhat.Core.Items; -using Khaemhat.Core.Tables; -using Khaemhat.Data; -using Khaemhat.Data.Querying; namespace Khaemhat.Application.ImportExport; @@ -232,101 +228,3 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => Task.FromResult>>([]); } - -/// -/// The opening stock (giacenze-iniziali): item, warehouse, quantity and unit cost. Until the stock entries exist -/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts. -/// -/// Opens the company databases. -/// Checks the permission. -public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget -{ - private static readonly ImportField[] StockFields = - [ - new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), - new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]), - new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]), - new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]), - ]; - - /// - public string Key => "giacenze-iniziali"; - - /// - public string ModuleCode => ModuleCodes.Core; - - /// - public string Permission => "inventory.entry.write"; - - /// - public string ExportPermission => "inventory.stock.read"; - - /// - public bool CanApply => false; - - /// - public bool CanExport => false; - - /// - public IReadOnlyList Fields => StockFields; - - /// - public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(context); - ArgumentNullException.ThrowIfNull(rows); - var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); - await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); - var items = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; - var codes = new CodeIndex(items.Select(i => (i.Code, i.Id))); - var byId = items.ToDictionary(i => i.Id); - var warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); - var seen = new HashSet<(long, long)>(); - var results = new List(rows.Count); - foreach (var row in rows) - { - var messages = new List(); - var cells = new CellReader(row, messages); - messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); - var item = cells.Code("articolo", codes) is { } id ? byId[id] : null; - var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId); - if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked)) - { - messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code)); - } - - if (item is not null && warehouse is null && !cells.Has("deposito")) - { - messages.Add(new("deposito", ImportErrors.Required)); - } - - if (cells.Number("quantita") is <= 0) - { - messages.Add(new("quantita", ImportErrors.Positive)); - } - - if (cells.Number("costo_unitario") is < 0) - { - messages.Add(new("costo_unitario", Items.ItemService.NotNegative)); - } - - var label = row["articolo"] ?? string.Empty; - if (item is not null && warehouse is { } w && !seen.Add((item.Id, w))) - { - messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); - } - - results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages)); - } - - return results; - } - - /// - public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => - throw new InvalidOperationException(ImportErrors.CheckOnly); - - /// - public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => - Task.FromResult>>([]); -} diff --git a/src/Khaemhat.Application/ImportExport/OpeningStockImportTarget.cs b/src/Khaemhat.Application/ImportExport/OpeningStockImportTarget.cs new file mode 100644 index 0000000..c10bff1 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/OpeningStockImportTarget.cs @@ -0,0 +1,191 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The opening stock (giacenze-iniziali, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted +/// become one warehouse movement per warehouse with the reason APE (opening stock), confirmed at the day of the +/// import: the stock and the average cost start from there. +/// +/// Opens the company databases. +/// Checks the permission. +/// Writes the movements. +/// The day of the movements. +public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget +{ + /// The reason of the opening stock. + public const string OpeningReason = "APE"; + + /// Error: the reason APE is missing. + public const string ReasonMissing = "import.stock.reason-missing"; + + private static readonly ImportField[] StockFields = + [ + new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), + new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]), + new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]), + new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]), + ]; + + /// + public string Key => "giacenze-iniziali"; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public string Permission => "inventory.entry.write"; + + /// + public string ExportPermission => "inventory.stock.read"; + + /// + public bool CanApply => true; + + /// + public bool CanExport => false; + + /// + public IReadOnlyList Fields => StockFields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + [.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)]; + + /// + public async Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var read = await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + long? reason; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + reason = (await uow.Repository().FindAsync(Query.For().Where(r => r.Code == OpeningReason), cancellationToken) + .ConfigureAwait(false))?.Id; + } + + var results = read.Select(r => r.Result).ToArray(); + var good = read.Select((r, i) => (Row: r, Index: i)).Where(x => x.Row.Result.Action == ImportAction.Create && x.Row.Stock is not null).ToList(); + if (reason is null) + { + foreach (var (_, index) in good) + { + results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, new ImportMessage("articolo", ReasonMissing)] }; + } + + return results; + } + + var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime); + foreach (var group in good.GroupBy(x => x.Row.Stock!.Value.WarehouseId)) + { + var movement = await engine.NewAsync(context.Actor, company, "MM", cancellationToken).ConfigureAwait(false); + movement.Header.DocumentDate = today; + movement.Header.WarehouseId = group.Key; + movement.Header.InventoryReasonId = reason; + foreach (var (row, _) in group) + { + var stock = row.Stock!.Value; + movement.Lines.Add(new InventoryDocumentLine + { + Kind = DocumentLineKind.Item, + ItemId = stock.Item.Id, + Description = stock.Item.Description, + UnitOfMeasureId = stock.Item.UnitOfMeasureId, + Quantity = stock.Quantity, + Price = stock.Cost, + WarehouseId = group.Key, + }); + } + + try + { + var saved = await engine.SaveAsync(context.Actor, company, movement, cancellationToken).ConfigureAwait(false); + await engine.ConfirmAsync(context.Actor, company, saved.Family, saved.Header.Id, cancellationToken).ConfigureAwait(false); + } + catch (ValidationFailedException ex) + { + var message = new ImportMessage("articolo", ex.Errors.Count > 0 ? ex.Errors[0].Split(':', 2)[^1] : ImportErrors.Required); + foreach (var (_, index) in group) + { + results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, message] }; + } + } + } + + return results; + } + + /// + public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => + Task.FromResult>>([]); + + private async Task> ReadAsync( + ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var codes = new CodeIndex(items.Select(i => (i.Code, i.Id))); + var byId = items.ToDictionary(i => i.Id); + var warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var fallback = (await uow.Repository().ListAsync(Query.For().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items + .OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id; + var seen = new HashSet<(long, long)>(); + var results = new List<(ImportRowResult, (Item, long, decimal, decimal)?)>(rows.Count); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + var item = cells.Code("articolo", codes) is { } id ? byId[id] : null; + var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId ?? fallback); + if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked)) + { + messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code)); + } + + if (item is not null && warehouse is null && !cells.Has("deposito")) + { + messages.Add(new("deposito", ImportErrors.Required)); + } + + var quantity = cells.Number("quantita"); + if (quantity is <= 0) + { + messages.Add(new("quantita", ImportErrors.Positive)); + } + + var cost = cells.Number("costo_unitario"); + if (cost is < 0) + { + messages.Add(new("costo_unitario", Items.ItemService.NotNegative)); + } + + var label = row["articolo"] ?? string.Empty; + if (item is not null && warehouse is { } w && !seen.Add((item.Id, w))) + { + messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); + } + + var failed = messages.Any(m => !m.IsWarning); + (Item, long, decimal, decimal)? stock = !failed && item is not null && warehouse is { } where && quantity is { } q + ? (item, where, q, cost ?? item.AverageCost ?? item.StandardCost ?? item.LastCost ?? 0m) + : null; + results.Add((new ImportRowResult(row.Line, label, failed ? ImportAction.Skip : ImportAction.Create, messages), stock)); + } + + return results; + } +} diff --git a/src/Khaemhat.Application/Inventory/InventoryPoster.cs b/src/Khaemhat.Application/Inventory/InventoryPoster.cs new file mode 100644 index 0000000..db0a381 --- /dev/null +++ b/src/Khaemhat.Application/Inventory/InventoryPoster.cs @@ -0,0 +1,553 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Inventory; + +/// +/// Posts the documents to the warehouse (SPEC §11.6, ADR 0035) inside the transaction of the document engine: a +/// confirmed document that moves the stock writes one movement per stocked line; a cancelled one loses it. After every +/// change the history of the items touched runs again through the weighted average and gives the balances of each +/// warehouse, the committed and ordered quantities of the open orders and the costs on the item card. +/// +public static class InventoryPoster +{ + /// A transfer needs a destination different from the origin. + public const string TransferDestination = "document.transfer.destination"; + + /// Writes again the movements of a document from its current state and refreshes its items. + /// The unit of work of the company, in a transaction. + /// The family of the document. + /// The document. + /// Cancellation. + /// A task. + public static async Task SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var items = new HashSet(); + await RemoveAsync(uow, family, documentId, items, cancellationToken).ConfigureAwait(false); + var header = await HeaderAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false); + if (header is null) + { + await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false); + return; + } + + var lines = await LinesAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false); + foreach (var line in lines.Where(l => l.ItemId is not null)) + { + // Orders hold committed and ordered quantities; every state change of theirs moves the balances. + items.Add(line.ItemId!.Value); + } + + if (DocumentStateMachine.IsInForce(header.Status) && StockEffectMatrix.MovesStock(header.Kind)) + { + await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false); + } + + await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false); + } + + /// + /// Rebuilds the warehouse from the documents (SPEC §11.6, ricostruzione): removes every movement, posts + /// again every document in force that moves the stock, oldest first and the delivery notes before the invoices of + /// the same day, then runs the history of every item. + /// + /// The unit of work of the company, in a transaction. + /// Receives the documents posted and the total, then the items and their total. + /// Cancellation. + /// The documents posted and the items computed. + public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress? progress = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entry_lines"), cancellationToken).ConfigureAwait(false); + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entries"), cancellationToken).ConfigureAwait(false); + var documents = new List<(DocumentFamily Family, DocumentHeader Header)>(); + foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument }) + { + foreach (var header in await Documents.DocumentStores.Of(family).InForceAsync(uow, cancellationToken).ConfigureAwait(false)) + { + if (StockEffectMatrix.MovesStock(header.Kind)) + { + documents.Add((family, header)); + } + } + } + + // Delivery notes and receipts first: their invoices then find the goods already moved. + var ordered = documents + .OrderBy(d => d.Header.DocumentDate) + .ThenBy(d => d.Header.Kind is DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote or DocumentKind.InventoryEntry ? 0 : 1) + .ThenBy(d => d.Header.ConfirmedAt) + .ThenBy(d => d.Header.Id) + .ToList(); + var items = new HashSet(); + for (var i = 0; i < ordered.Count; i++) + { + var (family, header) = ordered[i]; + var lines = await LinesAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false); + await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false); + progress?.Report(new RebuildProgress(RebuildPhase.Documents, i + 1, ordered.Count)); + } + + // Every stocked item, also those with only orders or with no movement left. + var all = (await uow.Repository().ListAsync(Query.For().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id); + var balanced = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(b => b.ItemId); + var ids = items.Concat(all).Concat(balanced).Distinct().ToList(); + for (var i = 0; i < ids.Count; i += 50) + { + await RecomputeAsync(uow, ids.Skip(i).Take(50), cancellationToken).ConfigureAwait(false); + progress?.Report(new RebuildProgress(RebuildPhase.Items, Math.Min(i + 50, ids.Count), ids.Count)); + } + + return (ordered.Count, ids.Count); + } + + /// + /// Runs again the history of items: the cost of every movement, the balances of each warehouse, the committed and + /// ordered quantities, the average and last cost on the item card. + /// + /// The unit of work of the company, in a transaction. + /// The items. + /// Cancellation. + /// A task. + public static async Task RecomputeAsync(IUnitOfWork uow, IEnumerable itemIds, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + ArgumentNullException.ThrowIfNull(itemIds); + var ids = itemIds.Distinct().ToList(); + if (ids.Count == 0) + { + return; + } + + var committed = await OpenQuantitiesAsync(uow, ids, cancellationToken).ConfigureAwait(false); + var ordered = await OpenQuantitiesAsync(uow, ids, cancellationToken).ConfigureAwait(false); + var defaultWarehouse = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false); + foreach (var itemId in ids) + { + await RecomputeItemAsync(uow, itemId, committed, ordered, defaultWarehouse, cancellationToken).ConfigureAwait(false); + } + } + + /// The default warehouse of the company: the one marked as such, or the first. + /// The unit of work. + /// Cancellation. + /// The warehouse, if any. + public static async Task DefaultWarehouseAsync(IUnitOfWork uow, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(uow); + var warehouses = uow.Repository(); + var marked = await warehouses.FindAsync(Query.For().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false); + return marked?.Id ?? (await warehouses.FindAsync(Query.For().Where(w => !w.Disabled).OrderBy(w => w.Code), cancellationToken).ConfigureAwait(false))?.Id; + } + + /// The quantity of a line in the base unit of its item. + /// The quantity on the line. + /// The unit of the line. + /// The item. + /// The alternative units of the item. + /// The quantity in the base unit. + public static decimal ToBase(decimal quantity, long? lineUnit, Item item, IEnumerable units) + { + ArgumentNullException.ThrowIfNull(item); + ArgumentNullException.ThrowIfNull(units); + if (lineUnit is null || lineUnit == item.UnitOfMeasureId) + { + return quantity; + } + + var unit = units.FirstOrDefault(u => u.ItemId == item.Id && u.UnitOfMeasureId == lineUnit); + return unit is null || unit.Factor <= 0m ? quantity : quantity * unit.Factor; + } + + private static async Task RemoveAsync(IUnitOfWork uow, DocumentFamily family, long documentId, HashSet items, CancellationToken cancellationToken) + { + var entries = uow.Repository(); + var lines = uow.Repository(); + foreach (var entry in (await entries.ListAsync(Query.For().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId), cancellationToken) + .ConfigureAwait(false)).Items) + { + foreach (var line in (await lines.ListAsync(Query.For().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items) + { + items.Add(line.ItemId); + await lines.DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false); + } + + await entries.DeleteAsync(entry.Id, cancellationToken).ConfigureAwait(false); + } + } + + private static async Task PostAsync( + IUnitOfWork uow, DocumentFamily family, DocumentHeader header, IReadOnlyList lines, HashSet items, CancellationToken cancellationToken) + { + if (header.InventoryReasonId is not { } reasonId + || await uow.Repository().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) is not { } reason) + { + return; + } + + // A line that comes from a document that already moved its goods the same way (the invoice of a delivery note) + // does not move them again; a credit note of an invoice moves them back. + var sign = reason.IsTransfer ? 0 : reason.Effect switch { StockEffect.Load => 1, StockEffect.Unload => -1, _ => 0 }; + var stockLines = await StockLinesAsync(uow, header, lines, sign, cancellationToken).ConfigureAwait(false); + IReadOnlyList movements; + try + { + movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines); + } + catch (InvalidOperationException) + { + throw new ValidationFailedException([nameof(DocumentHeader.ToWarehouseId) + ":" + TransferDestination]); + } + if (movements.Count == 0) + { + return; + } + + var entry = new InventoryEntry + { + EntryDate = header.DocumentDate, + SourceFamily = family, + SourceDocumentId = header.Id, + SourceKind = header.Kind, + SourceNumber = header.DocumentNumber, + InventoryReasonId = reason.Id, + PartyId = header.PartyId, + IsDemo = header.IsDemo, + }; + await uow.Repository().InsertAsync(entry, cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var order = 0; + foreach (var m in movements) + { + items.Add(m.ItemId); + await repository.InsertAsync( + new InventoryEntryLine + { + EntryId = entry.Id, + EntryDate = entry.EntryDate, + ItemId = m.ItemId, + WarehouseId = m.WarehouseId, + Quantity = m.Quantity, + Valued = m.Valued, + UnitCost = m.UnitCost, + Value = StockCostCalculator.Value(m.Quantity, m.UnitCost), + SourceLineId = m.SourceLineId, + SortOrder = ++order, + }, + cancellationToken).ConfigureAwait(false); + } + } + + // The stocked lines of a document in the base unit, with their warehouse and cost; the lines that come from a + // document that already moved the stock (the invoice of a delivery note) are left out. + private static async Task> StockLinesAsync( + IUnitOfWork uow, DocumentHeader header, IReadOnlyList lines, int sign, CancellationToken cancellationToken) + { + var result = new List(); + var itemIds = lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null).Select(l => l.ItemId).Distinct().ToList(); + if (itemIds.Count == 0) + { + return result; + } + + var catalog = (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(i => i.Id); + var ids = catalog.Keys.ToList(); + var units = (await uow.Repository().ListAsync(Query.For().Where(u => ids.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items; + var fallback = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false); + var moved = new Dictionary<(DocumentFamily, long), Dictionary>(); + foreach (var line in lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null && l.Quantity != 0m)) + { + if (!catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked || item.Kind != ItemKind.Goods) + { + continue; + } + + if (sign != 0 && line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId + && await MovedSignAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false) == sign) + { + continue; + } + + var warehouse = line.WarehouseId ?? header.WarehouseId ?? item.WarehouseId ?? fallback; + if (warehouse is null) + { + continue; + } + + var quantity = ToBase(Math.Abs(line.Quantity), line.UnitOfMeasureId, item, units); + result.Add(new StockLineInput(line.Id, item.Id, quantity, warehouse.Value, UnitCost(header, line, quantity))); + } + + return result; + } + + // The cost per base unit in euro of a line: its taxable amount over the quantity, at the exchange rate of the document. + private static decimal? UnitCost(DocumentHeader header, DocumentLine line, decimal baseQuantity) + { + if (baseQuantity == 0m || line.TaxableAmount == 0m) + { + return null; + } + + var amount = Math.Abs(line.TaxableAmount); + if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m) + { + amount /= header.ExchangeRate; + } + + return Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero); + } + + // How a line of another document moved the stock: 1 loaded, -1 unloaded, 0 not at all. + private static async Task MovedSignAsync( + IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary> moved, CancellationToken cancellationToken) + { + var source = await StoreLineAsync(uow, sourceFamily, sourceLineId, cancellationToken).ConfigureAwait(false); + if (source is null) + { + return 0; + } + + var key = (sourceFamily, source.DocumentId); + if (!moved.TryGetValue(key, out var lines)) + { + lines = []; + var entries = (await uow.Repository() + .ListAsync(Query.For().Where(e => e.SourceFamily == sourceFamily && e.SourceDocumentId == source.DocumentId), cancellationToken).ConfigureAwait(false)).Items; + foreach (var entry in entries) + { + foreach (var line in (await uow.Repository() + .ListAsync(Query.For().Where(l => l.EntryId == entry.Id), cancellationToken).ConfigureAwait(false)).Items) + { + if (line.SourceLineId is { } id) + { + lines[id] = Math.Sign(line.Quantity); + } + } + } + + moved[key] = lines; + } + + return lines.GetValueOrDefault(sourceLineId); + } + + private static async Task RecomputeItemAsync( + IUnitOfWork uow, long itemId, IReadOnlyDictionary<(long, long?), decimal> committed, IReadOnlyDictionary<(long, long?), decimal> ordered, long? defaultWarehouse, + CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(itemId, cancellationToken).ConfigureAwait(false) is not { } item) + { + return; + } + + var repository = uow.Repository(); + var lines = (await repository.ListAsync( + Query.For().Where(l => l.ItemId == itemId).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken) + .ConfigureAwait(false)).Items; + var invoiced = await InvoicedCostsAsync(uow, lines, cancellationToken).ConfigureAwait(false); + var history = StockCostCalculator.Run( + lines.Select(l => new CostedMovement( + l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued || invoiced.ContainsKey(l.Id), invoiced.TryGetValue(l.Id, out var cost) ? cost : l.UnitCost)), + item.StandardCost ?? 0m); + foreach (var line in lines) + { + var unitCost = history.UnitCosts[line.Id]; + var value = StockCostCalculator.Value(line.Quantity, unitCost); + if (line.UnitCost != unitCost || line.Value != value) + { + line.UnitCost = unitCost; + line.Value = value; + await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + } + + await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM item_balances WHERE item_id = {itemId}"), cancellationToken).ConfigureAwait(false); + var warehouses = history.Warehouses.Keys + .Concat(committed.Keys.Concat(ordered.Keys).Where(k => k.Item1 == itemId).Select(k => k.Item2 ?? item.WarehouseId ?? defaultWarehouse).OfType()) + .Distinct(); + var balances = uow.Repository(); + foreach (var warehouseId in warehouses) + { + var stock = history.Warehouses.GetValueOrDefault(warehouseId) ?? new WarehouseStock(0m, null, null); + await balances.InsertAsync( + new ItemBalance + { + ItemId = itemId, + WarehouseId = warehouseId, + OnHand = stock.OnHand, + Committed = Open(committed, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse), + Ordered = Open(ordered, itemId, warehouseId, item.WarehouseId ?? defaultWarehouse), + AverageCost = history.AverageCost, + Value = StockCostCalculator.Value(stock.OnHand, history.AverageCost), + LastCost = history.LastCost, + LastLoadDate = stock.LastLoad, + LastUnloadDate = stock.LastUnload, + }, + cancellationToken).ConfigureAwait(false); + } + + // Only the costs: the card keeps its version, so whoever is editing it does not collide with a posting. + decimal? average = lines.Count == 0 ? item.AverageCost : history.AverageCost; + var last = history.LastCost ?? item.LastCost; + if (average != item.AverageCost || last != item.LastCost) + { + await uow.ExecuteAsync(SqlFragment.Of($"UPDATE items SET average_cost = {average}, last_cost = {last} WHERE id = {itemId}"), cancellationToken).ConfigureAwait(false); + } + } + + // The quantity still open of an item in a warehouse; the lines without a warehouse count in the usual one. + private static decimal Open(IReadOnlyDictionary<(long, long?), decimal> open, long itemId, long warehouseId, long? usual) + { + var total = open.GetValueOrDefault((itemId, warehouseId)); + if (usual == warehouseId) + { + total += open.GetValueOrDefault((itemId, null)); + } + + return total; + } + + // The cost a supplier invoice gives to the loads of the delivery notes it invoices (the difference of price, §11.5). + private static async Task> InvoicedCostsAsync(IUnitOfWork uow, IReadOnlyList lines, CancellationToken cancellationToken) + { + var result = new Dictionary(); + var loads = lines.Where(l => l.Quantity > 0m && l.SourceLineId is not null).ToList(); + if (loads.Count == 0) + { + return result; + } + + var entryIds = loads.Select(l => l.EntryId).Distinct().ToList(); + var receipts = (await uow.Repository() + .ListAsync(Query.For().Where(e => entryIds.Contains(e.Id) && e.SourceKind == DocumentKind.PurchaseDeliveryNote), cancellationToken).ConfigureAwait(false)) + .Items.Select(e => e.Id).ToHashSet(); + var receiptLines = loads.Where(l => receipts.Contains(l.EntryId)).ToList(); + if (receiptLines.Count == 0) + { + return result; + } + + var sourceIds = receiptLines.Select(l => l.SourceLineId!.Value).Distinct().ToList(); + var links = (await uow.Repository().ListAsync( + Query.For().Where(k => k.SourceFamily == DocumentFamily.PurchaseDocument && k.TargetFamily == DocumentFamily.PurchaseDocument && sourceIds.Contains(k.SourceLineId)), + cancellationToken).ConfigureAwait(false)).Items; + foreach (var load in receiptLines) + { + decimal amount = 0m, quantity = 0m; + foreach (var link in links.Where(k => k.SourceLineId == load.SourceLineId)) + { + var target = await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, link.TargetLineId, cancellationToken).ConfigureAwait(false); + var header = target is null ? null : await HeaderAsync(uow, DocumentFamily.PurchaseDocument, target.DocumentId, cancellationToken).ConfigureAwait(false); + if (target is null || header is null || header.Kind != DocumentKind.PurchaseInvoice || !DocumentStateMachine.IsInForce(header.Status) || target.Quantity == 0m) + { + continue; + } + + var lineAmount = Math.Abs(target.TaxableAmount); + if (!string.Equals(header.CurrencyCode, "EUR", StringComparison.Ordinal) && header.ExchangeRate > 0m) + { + lineAmount /= header.ExchangeRate; + } + + // The invoice line in the unit of the delivery note: its share of the load is the linked quantity. + var share = Math.Abs(link.Quantity / target.Quantity); + amount += lineAmount * share; + quantity += Math.Abs(link.Quantity); + } + + var source = quantity == 0m ? null : await StoreLineAsync(uow, DocumentFamily.PurchaseDocument, load.SourceLineId!.Value, cancellationToken).ConfigureAwait(false); + if (source is null || source.Quantity == 0m) + { + continue; + } + + // The load is in the base unit; the invoiced part of the delivery line is quantity / source.Quantity of it. + var baseQuantity = load.Quantity * (quantity / Math.Abs(source.Quantity)); + if (baseQuantity > 0m && amount > 0m) + { + result[load.Id] = Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero); + } + } + + return result; + } + + // The quantities still to deliver of the open orders of a family, by item and warehouse of the line. + private static async Task> OpenQuantitiesAsync(IUnitOfWork uow, List itemIds, CancellationToken cancellationToken) + where THeader : DocumentHeader, new() + where TLine : DocumentLine, new() + { + var result = new Dictionary<(long, long?), decimal>(); + var ids = itemIds.Select(i => (long?)i).ToList(); + var lines = (await uow.Repository().ListAsync( + Query.For().Where(l => ids.Contains(l.ItemId) && !l.FulfillmentClosed), cancellationToken).ConfigureAwait(false)).Items; + if (lines.Count == 0) + { + return result; + } + + var documentIds = lines.Select(l => l.DocumentId).Distinct().ToList(); + var open = (await uow.Repository().ListAsync( + Query.For().Where(h => documentIds.Contains(h.Id) && (h.Status == DocumentStatus.Confirmed || h.Status == DocumentStatus.PartiallyFulfilled)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(h => h.Id); + if (open.Count == 0) + { + return result; + } + + var catalog = (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(i => i.Id); + var units = (await uow.Repository().ListAsync(Query.For().Where(u => itemIds.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items; + foreach (var line in lines) + { + if (!open.TryGetValue(line.DocumentId, out var header) || !catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked) + { + continue; + } + + var residual = line.Quantity - line.FulfilledQuantity; + if (residual <= 0m) + { + continue; + } + + var key = (item.Id, line.WarehouseId ?? header.WarehouseId); + result[key] = result.GetValueOrDefault(key) + ToBase(residual, line.UnitOfMeasureId, item, units); + } + + return result; + } + + private static Task HeaderAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) => + Documents.DocumentStores.Of(family).GetAsync(uow, id, cancellationToken); + + private static Task> LinesAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) => + Documents.DocumentStores.Of(family).LinesAsync(uow, id, cancellationToken); + + private static Task StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) => + Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken); +} + +/// The step of a rebuild. +public enum RebuildPhase +{ + /// Posting the documents. + Documents = 0, + + /// Computing the items. + Items = 1, +} + +/// How far a rebuild is. +/// The step. +/// How many done. +/// How many in all. +public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total); diff --git a/src/Khaemhat.Application/Inventory/InventoryRebuildJob.cs b/src/Khaemhat.Application/Inventory/InventoryRebuildJob.cs new file mode 100644 index 0000000..ffc2537 --- /dev/null +++ b/src/Khaemhat.Application/Inventory/InventoryRebuildJob.cs @@ -0,0 +1,42 @@ +using System.Globalization; +using Khaemhat.Application.Jobs; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Companies; + +namespace Khaemhat.Application.Inventory; + +/// +/// Rebuilds the warehouse of every active company from its documents, once a week at night (SPEC §11.6): a safety net +/// that brings balances and costs back in line after imports or corrections made outside the screens. +/// +/// The units of work. +/// The companies. +public sealed class InventoryRebuildJob(IUnitOfWorkFactory factory, ICompanyRegistry companies) : IScheduledJob +{ + /// The job type. + public const string JobType = "inventory.rebuild"; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + int documents = 0, items = 0, done = 0; + foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status is CompanyStatus.Disabled) + { + continue; + } + + var (d, i) = await InventoryService.RebuildCompanyAsync(factory, company.Code, null, cancellationToken).ConfigureAwait(false); + documents += d; + items += i; + done++; + } + + return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {documents} documenti, {items} articoli ricalcolati."); + } +} diff --git a/src/Khaemhat.Application/Inventory/InventoryService.cs b/src/Khaemhat.Application/Inventory/InventoryService.cs new file mode 100644 index 0000000..dae909c --- /dev/null +++ b/src/Khaemhat.Application/Inventory/InventoryService.cs @@ -0,0 +1,422 @@ +using Khaemhat.Application.Items; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Inventory; + +/// What the stock screen asks (mockup 036). +public sealed record StockFilter +{ + /// Code, description or brand. + public string? Search { get; init; } + + /// One warehouse, or all together. + public long? WarehouseId { get; init; } + + /// One category. + public long? CategoryId { get; init; } + + /// Only the items under their minimum stock or reorder point. + public bool UnderstockOnly { get; init; } + + /// Also the items with nothing on hand, committed or ordered. + public bool IncludeEmpty { get; init; } +} + +/// The state of an item under its thresholds. +public enum StockLevel +{ + /// Enough. + Ok = 0, + + /// The available quantity reached the reorder point. + Reorder = 1, + + /// The available quantity is under the minimum stock. + Understock = 2, + + /// Nothing left, or less than nothing. + Out = 3, +} + +/// A row of the stock screen: an item in one warehouse or in all. +/// The item. +/// Its code. +/// Its description. +/// Its category. +/// Its base unit. +/// On hand. +/// Committed to customers. +/// Ordered from suppliers. +/// On hand less committed. +/// The minimum stock. +/// The reorder point. +/// The weighted average cost (none without the permission on costs). +/// The value at the average (none without the permission). +/// The last load. +/// The last unload. +/// The state under the thresholds. +public sealed record StockRow( + long ItemId, string Code, string Description, long? CategoryId, long? UnitOfMeasureId, decimal OnHand, decimal Committed, decimal Ordered, decimal Available, + decimal? MinimumStock, decimal? ReorderPoint, decimal? AverageCost, decimal? Value, DateOnly? LastLoad, DateOnly? LastUnload, StockLevel Level); + +/// A movement of an item, with the balance after it. +/// The movement. +/// The date. +/// The family of the document. +/// The document. +/// Its kind. +/// Its number. +/// The warehouse reason. +/// The customer or supplier. +/// The warehouse. +/// Positive loads, negative unloads. +/// The cost (none without the permission). +/// The value (none without the permission). +/// The balance after the movement, in the warehouses shown. +public sealed record MovementRow( + long Id, DateOnly Date, DocumentFamily? Family, long? DocumentId, DocumentKind? Kind, string? Number, string? ReasonCode, string? PartyName, long WarehouseId, + decimal Quantity, decimal? UnitCost, decimal? Value, decimal Balance); + +/// The value of an item at a date (closing stock, libro inventari). +/// The item. +/// Its code. +/// Its description. +/// On hand at the date. +/// The cost of the method. +/// Quantity times cost. +/// A (the first 80% of the value), B (up to 95%) or C. +public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass); + +/// +/// The warehouse as people read it (SPEC §11.6, mockups 036-037): stock and availability, the movements of an item, +/// the value at a date. The balances are kept by ; this service only reads them. +/// +/// Permission inventory.stock.read, movements inventory.entry.read; costs only with items.cost.read. +public sealed class InventoryService +{ + /// Permission to read the stock. + public const string StockPermission = "inventory.stock.read"; + + /// Permission to read the movements. + public const string EntryReadPermission = "inventory.entry.read"; + + /// Permission to post movements, stock takes and the rebuild. + public const string PostPermission = "inventory.entry.post"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + + /// Creates the service. + /// The units of work. + /// The permissions. + public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + _factory = factory; + _permissions = permissions; + } + + /// The stock of the items, in a warehouse or in all. + /// Who reads. + /// The company. + /// What to show. + /// Cancellation. + /// The rows, by code. + public async Task> StockAsync(Actor actor, string companyCode, StockFilter filter, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(filter); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false); + var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled); + if (filter.CategoryId is { } category) + { + query = query.Where(i => i.CategoryId == category); + } + + if (filter.Search?.Trim() is { Length: > 0 } text) + { + query = query.Where(i => i.Code.Contains(text) || i.Description.Contains(text) || (i.Brand != null && i.Brand.Contains(text))); + } + + var items = (await uow.Repository().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items; + var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false); + var rows = new List(); + foreach (var item in items) + { + var mine = balances.GetValueOrDefault(item.Id) ?? []; + var row = RowOf(item, mine, costs); + if (!filter.IncludeEmpty && mine.Count == 0) + { + // No movement and no order: shown only when asked, or when it has a minimum to keep. + if (row.Level == StockLevel.Ok) + { + continue; + } + } + + if (filter.UnderstockOnly && row.Level == StockLevel.Ok) + { + continue; + } + + rows.Add(row); + } + + return rows; + } + + /// The balances of an item in each warehouse. + /// Who reads. + /// The company. + /// The item. + /// Cancellation. + /// The balances, costs hidden without the permission. + public async Task> BalancesAsync(Actor actor, string companyCode, long itemId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false); + var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var rows = (await uow.Repository().ListAsync(Query.For().Where(b => b.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items; + if (!costs) + { + foreach (var row in rows) + { + row.AverageCost = 0m; + row.Value = 0m; + row.LastCost = null; + } + } + + return rows; + } + + /// The movements of an item in a period, with the running balance (mockup 036, dialog of the item). + /// Who reads. + /// The company. + /// The item. + /// One warehouse, or all. + /// The first day, or the beginning. + /// The last day, or today. + /// Cancellation. + /// The movements, oldest first; the balance starts from what was on hand before . + public async Task> MovementsAsync( + Actor actor, string companyCode, long itemId, long? warehouseId, DateOnly? from, DateOnly? to, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EntryReadPermission, cancellationToken).ConfigureAwait(false); + var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var query = Query.For().Where(l => l.ItemId == itemId); + if (warehouseId is { } warehouse) + { + query = query.Where(l => l.WarehouseId == warehouse); + } + + var lines = (await uow.Repository().ListAsync(query.OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken) + .ConfigureAwait(false)).Items; + var entryIds = lines.Select(l => l.EntryId).Distinct().ToList(); + var entries = entryIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(e => entryIds.Contains(e.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(e => e.Id); + var reasons = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id, r => r.Code); + var partyIds = entries.Values.Where(e => e.PartyId is not null).Select(e => e.PartyId!.Value).Distinct().ToList(); + var parties = partyIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(p => partyIds.Contains(p.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name); + var result = new List(); + var balance = 0m; + foreach (var line in lines) + { + balance += line.Quantity; + if ((from is { } first && line.EntryDate < first) || (to is { } last && line.EntryDate > last)) + { + continue; + } + + var entry = entries.GetValueOrDefault(line.EntryId); + result.Add(new MovementRow( + line.Id, line.EntryDate, entry?.SourceFamily, entry?.SourceDocumentId, entry?.SourceKind, entry?.SourceNumber, + entry?.InventoryReasonId is { } r ? reasons.GetValueOrDefault(r) : null, + entry?.PartyId is { } p ? parties.GetValueOrDefault(p) : null, + line.WarehouseId, line.Quantity, costs ? line.UnitCost : null, costs ? line.Value : null, balance)); + } + + return result; + } + + /// + /// The value of the stock at a date (closing stock, libro inventari): the history of each item up to that day, + /// valued with a method, with its ABC class by value. + /// + /// Who reads: needs the permission on costs too. + /// The company. + /// The day. + /// One warehouse, or all. + /// The cost used. + /// Cancellation. + /// The items with something on hand, by value. + public async Task> ValuationAsync( + Actor actor, string companyCode, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false); + await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var lines = (await uow.Repository().ListAsync( + Query.For().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken) + .ConfigureAwait(false)).Items; + var itemIds = lines.Select(l => l.ItemId).Distinct().ToList(); + var items = itemIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(i => i.Id); + var rows = new List(); + foreach (var group in lines.GroupBy(l => l.ItemId)) + { + if (!items.TryGetValue(group.Key, out var item)) + { + continue; + } + + // The costs written on the movements are those of the last run: the history up to the day gives the average then. + var history = StockCostCalculator.Run(group.Select(l => new CostedMovement(l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued, l.Valued ? l.UnitCost : 0m)), item.StandardCost ?? 0m); + var quantity = warehouseId is { } w ? history.Warehouses.GetValueOrDefault(w)?.OnHand ?? 0m : history.OnHand; + if (quantity == 0m) + { + continue; + } + + var cost = method switch + { + StockValuationMethod.LastCost => history.LastCost ?? history.AverageCost, + StockValuationMethod.StandardCost => item.StandardCost ?? history.AverageCost, + _ => history.AverageCost, + }; + rows.Add(new ValuationRow(item.Id, item.Code, item.Description, quantity, cost, StockCostCalculator.Value(quantity, cost), 'C')); + } + + return Classify(rows); + } + + /// The items under their thresholds, the most urgent first (dashboard widget and reorder). + /// Who reads. + /// The company. + /// How many. + /// Cancellation. + /// The rows. + public async Task> UnderstockAsync(Actor actor, string companyCode, int limit = 10, CancellationToken cancellationToken = default) + { + var rows = await StockAsync(actor, companyCode, new StockFilter { UnderstockOnly = true }, cancellationToken).ConfigureAwait(false); + return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)]; + } + + /// + /// Rebuilds the warehouse of the company from its documents (SPEC §11.6): every movement is written again and every + /// item computed again, in one transaction. + /// + /// Who rebuilds: needs inventory.entry.post. + /// The company. + /// How far it is. + /// Cancellation. + /// The documents posted and the items computed. + public async Task<(int Documents, int Items)> RebuildAsync(Actor actor, string companyCode, IProgress? progress = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PostPermission, cancellationToken).ConfigureAwait(false); + return await RebuildCompanyAsync(_factory, company, progress, cancellationToken).ConfigureAwait(false); + } + + /// Rebuilds the warehouse of a company, without checks (the scheduled job). + /// The units of work. + /// The company. + /// How far it is. + /// Cancellation. + /// The documents posted and the items computed. + internal static async Task<(int Documents, int Items)> RebuildCompanyAsync( + IUnitOfWorkFactory factory, string company, IProgress? progress, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var result = await InventoryPoster.RebuildAsync(uow, progress, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return result; + } + + /// + /// The level of an item: out when nothing is available (or less than nothing), under stock below the minimum, + /// to reorder when what is available and on order no longer covers the reorder point. + /// + /// On hand less committed. + /// Ordered from suppliers. + /// The minimum stock. + /// The reorder point. + /// The level. + public static StockLevel LevelOf(decimal available, decimal ordered, decimal? minimum, decimal? reorderPoint) + { + var watched = minimum is not null || reorderPoint is not null; + if (available < 0m || (watched && available <= 0m)) + { + return StockLevel.Out; + } + + if (minimum is { } min && available < min) + { + return StockLevel.Understock; + } + + return reorderPoint is { } point && available + ordered <= point ? StockLevel.Reorder : StockLevel.Ok; + } + + /// Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest. + /// The rows. + /// The rows by value, with their class. + public static IReadOnlyList Classify(IEnumerable rows) + { + ArgumentNullException.ThrowIfNull(rows); + var sorted = rows.OrderByDescending(r => r.Value).ThenBy(r => r.Code, StringComparer.Ordinal).ToList(); + var total = sorted.Where(r => r.Value > 0m).Sum(r => r.Value); + var running = 0m; + var result = new List(sorted.Count); + foreach (var row in sorted) + { + // The class of an item is where its value starts: the first item is always A. + var share = total <= 0m ? 1m : running / total; + running += Math.Max(row.Value, 0m); + result.Add(row with { AbcClass = share < 0.80m ? 'A' : share < 0.95m ? 'B' : 'C' }); + } + + return result; + } + + internal static StockRow RowOf(Item item, IReadOnlyList balances, bool costs) + { + var onHand = balances.Sum(b => b.OnHand); + var committed = balances.Sum(b => b.Committed); + var ordered = balances.Sum(b => b.Ordered); + var available = onHand - committed; + var average = balances.Count > 0 ? balances[0].AverageCost : item.AverageCost ?? 0m; + return new StockRow( + item.Id, item.Code, item.Description, item.CategoryId, item.UnitOfMeasureId, onHand, committed, ordered, available, item.MinimumStock, item.ReorderPoint, + costs ? average : null, costs ? balances.Sum(b => b.Value) : null, + balances.Max(b => b.LastLoadDate), balances.Max(b => b.LastUnloadDate), + LevelOf(available, ordered, item.MinimumStock, item.ReorderPoint)); + } + + internal static async Task>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken) + { + var query = Query.For(); + if (warehouseId is { } warehouse) + { + query = query.Where(b => b.WarehouseId == warehouse); + } + + return (await uow.Repository().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items + .GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList()); + } + + private async Task CostsAsync(Actor actor, CancellationToken cancellationToken) => + (await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed; +} diff --git a/src/Khaemhat.Application/Inventory/ReorderService.cs b/src/Khaemhat.Application/Inventory/ReorderService.cs new file mode 100644 index 0000000..e395470 --- /dev/null +++ b/src/Khaemhat.Application/Inventory/ReorderService.cs @@ -0,0 +1,183 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Inventory; + +/// An item to reorder (mockup 039). +/// The item. +/// Its code. +/// Its description. +/// Its unit. +/// On hand less committed. +/// Already ordered. +/// The minimum stock. +/// The reorder point. +/// The quantity proposed. +/// The usual supplier, if any. +/// Its name. +/// Its price. +/// When it would arrive, from the lead time. +public sealed record ReorderProposal( + long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal Available, decimal Ordered, decimal? MinimumStock, decimal? ReorderPoint, + decimal Quantity, long? SupplierId, string? SupplierName, decimal? Price, DateOnly? ExpectedDate); + +/// A proposal the user accepts, perhaps with another quantity or supplier. +/// The item. +/// The supplier. +/// The quantity. +public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity); + +/// +/// The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the +/// reorder point (or the minimum stock), with the quantity to order (the lot, or what brings back to the threshold, at +/// least the minimum of the supplier) and the usual supplier; accepted, the proposals become draft supplier orders, +/// one per supplier. +/// +public sealed class ReorderService +{ + /// Error: a chosen line without a supplier or a quantity. + public const string ChoiceInvalid = "inventory.reorder.choice-invalid"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly DocumentEngine _engine; + private readonly DocumentEditor _editor; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The document engine. + /// The editor (prices and terms of the supplier). + /// The clock. + public ReorderService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, DocumentEditor editor, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _engine = engine; + _editor = editor; + _clock = clock; + } + + /// The items to reorder, by supplier and code. + /// Who reads. + /// The company. + /// Cancellation. + /// The proposals. + public async Task> ProposalsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.StockPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = (await uow.Repository().ListAsync( + Query.For().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled && (i.MinimumStock != null || i.ReorderPoint != null)).OrderBy(i => i.Code), cancellationToken) + .ConfigureAwait(false)).Items; + if (items.Count == 0) + { + return []; + } + + var balances = await InventoryService.BalancesByItemAsync(uow, null, cancellationToken).ConfigureAwait(false); + var ids = items.Select(i => i.Id).ToList(); + var suppliers = (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.ItemId)), cancellationToken) + .ConfigureAwait(false)).Items.GroupBy(s => s.ItemId).ToDictionary(g => g.Key, g => g.OrderByDescending(s => s.IsDefault).ThenBy(s => s.Id).First()); + var partyIds = suppliers.Values.Select(s => s.PartyId).Distinct().ToList(); + var names = partyIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(p => partyIds.Contains(p.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + var result = new List(); + foreach (var item in items) + { + var mine = balances.GetValueOrDefault(item.Id) ?? []; + var available = mine.Sum(b => b.OnHand - b.Committed); + var ordered = mine.Sum(b => b.Ordered); + var supplier = suppliers.GetValueOrDefault(item.Id); + var quantity = Quantity(available + ordered, item.MinimumStock, item.ReorderPoint, item.ReorderLot, supplier?.MinimumQuantity); + if (quantity <= 0m) + { + continue; + } + + result.Add(new ReorderProposal( + item.Id, item.Code, item.Description, item.UnitOfMeasureId, available, ordered, item.MinimumStock, item.ReorderPoint, quantity, + supplier?.PartyId, supplier is null ? null : names.GetValueOrDefault(supplier.PartyId), supplier?.Price ?? item.LastCost, + supplier?.LeadTimeDays is { } days ? today.AddDays(days) : null)); + } + + return [.. result.OrderBy(r => r.SupplierName is null).ThenBy(r => r.SupplierName, StringComparer.CurrentCulture).ThenBy(r => r.Code, StringComparer.Ordinal)]; + } + + /// + /// The quantity to order: nothing while what is available and ordered covers the reorder point (or the minimum); + /// otherwise the lot of the item, or what brings back to the higher of the two thresholds, at least the minimum + /// quantity of the supplier. + /// + /// Available plus ordered. + /// The minimum stock. + /// The reorder point. + /// The reorder lot. + /// The minimum of the supplier. + /// The quantity. + public static decimal Quantity(decimal cover, decimal? minimum, decimal? reorderPoint, decimal? lot, decimal? supplierMinimum) + { + var threshold = reorderPoint ?? minimum; + if (threshold is not { } point || cover > point || (reorderPoint is null && cover >= point)) + { + return 0m; + } + + var target = Math.Max(minimum ?? 0m, reorderPoint ?? 0m); + var quantity = lot is > 0m ? lot.Value : Math.Max(target - cover, 0m); + if (lot is > 0m && cover + quantity < target) + { + // One lot is not enough: as many lots as it takes. + quantity = Math.Ceiling((target - cover) / lot.Value) * lot.Value; + } + + return Math.Max(quantity, supplierMinimum ?? 0m); + } + + /// Creates the draft supplier orders of the chosen proposals, one per supplier. + /// Who orders: needs purchases.order.write. + /// The company. + /// The proposals accepted. + /// Cancellation. + /// The orders, saved as drafts. + public async Task> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList choices, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(choices); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "purchases.order.write", cancellationToken).ConfigureAwait(false); + if (choices.Any(c => c.Quantity <= 0m || c.SupplierId <= 0)) + { + throw new ValidationFailedException([":" + ChoiceInvalid]); + } + + var result = new List(); + foreach (var group in choices.GroupBy(c => c.SupplierId)) + { + var order = await _engine.NewAsync(actor, company, "OF", cancellationToken).ConfigureAwait(false); + await _editor.ApplyPartyAsync(actor, company, order, group.Key, cancellationToken).ConfigureAwait(false); + foreach (var choice in group) + { + var line = new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = choice.ItemId, Quantity = choice.Quantity }; + order.Lines.Add(line); + await _editor.FillLineAsync(actor, company, order, line, choice.ItemId, cancellationToken).ConfigureAwait(false); + line.Quantity = choice.Quantity; + } + + result.Add(await _engine.SaveAsync(actor, company, order, cancellationToken).ConfigureAwait(false)); + } + + return result; + } +} diff --git a/src/Khaemhat.Application/Inventory/StockTakeService.cs b/src/Khaemhat.Application/Inventory/StockTakeService.cs new file mode 100644 index 0000000..e58b5bc --- /dev/null +++ b/src/Khaemhat.Application/Inventory/StockTakeService.cs @@ -0,0 +1,405 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Inventory; + +/// A line of a stock take with its item. +/// The line. +/// The code of the item. +/// Its description. +/// Its base unit. +public sealed record StockTakeLineView(StockTakeLine Line, string Code, string Description, long? UnitOfMeasureId); + +/// A stock take with its lines. +/// The stock take. +/// Its lines, by code. +public sealed record StockTakeView(StockTake Take, IReadOnlyList Lines) +{ + /// How many lines are counted. + public int Counted => Lines.Count(l => l.Line.CountedQuantity is not null); + + /// The value of the differences at the cost of the lines. + public decimal DifferenceValue => Lines.Sum(l => StockCostCalculator.Value(l.Line.Difference, l.Line.UnitCost)); +} + +/// What the import of the counts found. +/// The lines counted. +/// The codes not on the list, with their row. +public sealed record StockCountImport(int Applied, IReadOnlyList Unknown); + +/// +/// The physical inventory (SPEC §11.6, mockup 038): a list of the items of a warehouse with what the books say at the +/// date, the counts typed or read from a file, and the posting that writes the differences as two warehouse movements +/// (gains with reason INVP, losses with INVN) through the document engine. +/// +/// Permissions inventory.entry.read, write (lists and counts) and post. +public sealed class StockTakeService +{ + /// Error: the stock take is no longer open. + public const string NotOpen = "inventory.stock-take.not-open"; + + /// Error: nothing is counted. + public const string NothingCounted = "inventory.stock-take.nothing-counted"; + + /// Error: a counted quantity below zero. + public const string NegativeCount = "inventory.stock-take.negative"; + + /// Error: the reasons of the adjustments are missing from the base tables. + public const string ReasonMissing = "inventory.stock-take.reason-missing"; + + /// The reason of the gains. + public const string GainReason = "INVP"; + + /// The reason of the losses. + public const string LossReason = "INVN"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly DocumentEngine _engine; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The document engine, for the adjustments. + /// The clock. + public StockTakeService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _engine = engine; + _clock = clock; + } + + /// The stock takes, the latest first. + /// Who reads. + /// The company. + /// Cancellation. + /// The stock takes. + public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync(Query.For().OrderByDescending(t => t.TakeDate).OrderByDescending(t => t.Id), cancellationToken) + .ConfigureAwait(false)).Items; + } + + /// A stock take with its lines. + /// Who reads. + /// The company. + /// The stock take. + /// Cancellation. + /// The stock take, or none. + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Opens a stock take: the stocked goods of the warehouse (of a category, if given) with the quantity the books + /// give at the date and the average cost. + /// + /// Who opens it. + /// The company. + /// The warehouse. + /// The day of the count. + /// Only a category. + /// A description; the warehouse and date when empty. + /// Cancellation. + /// The new stock take. + public async Task CreateAsync( + Actor actor, string companyCode, long warehouseId, DateOnly date, long? categoryId, string? description, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var warehouse = await uow.Repository().GetAsync(warehouseId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([nameof(StockTake.WarehouseId) + ":" + "inventory.warehouse.missing"]); + var query = Query.For().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled); + if (categoryId is { } category) + { + query = query.Where(i => i.CategoryId == category); + } + + var items = (await uow.Repository().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items; + var book = await BookAsync(uow, warehouseId, date, cancellationToken).ConfigureAwait(false); + var balances = (await uow.Repository().ListAsync(Query.For().Where(b => b.WarehouseId == warehouseId), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(b => b.ItemId); + var take = new StockTake + { + TakeDate = date, + WarehouseId = warehouseId, + CategoryId = categoryId, + Description = string.IsNullOrWhiteSpace(description) + ? "Inventario " + warehouse.Code + " al " + date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + : description.Trim()[..Math.Min(description.Trim().Length, 100)], + Status = StockTakeStatus.Open, + }; + await uow.Repository().InsertAsync(take, cancellationToken).ConfigureAwait(false); + var lines = uow.Repository(); + var order = 0; + foreach (var item in items) + { + await lines.InsertAsync( + new StockTakeLine + { + StockTakeId = take.Id, + ItemId = item.Id, + BookQuantity = book.GetValueOrDefault(item.Id), + UnitCost = balances.TryGetValue(item.Id, out var balance) ? balance.AverageCost : item.AverageCost ?? item.StandardCost ?? 0m, + SortOrder = ++order, + }, + cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return (await ViewAsync(uow, take.Id, cancellationToken).ConfigureAwait(false))!; + } + + /// Writes the counts typed on the list; an empty count means not counted yet. + /// Who counts. + /// The company. + /// The stock take. + /// The counted quantity of each line, by line. + /// Cancellation. + /// The stock take. + public async Task SaveCountsAsync( + Actor actor, string companyCode, long id, IReadOnlyDictionary counts, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(counts); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false); + if (counts.Values.Any(v => v < 0m)) + { + throw new ValidationFailedException(["CountedQuantity:" + NegativeCount]); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + foreach (var line in (await repository.ListAsync(Query.For().Where(l => l.StockTakeId == id), cancellationToken).ConfigureAwait(false)).Items) + { + if (counts.TryGetValue(line.Id, out var counted) && counted != line.CountedQuantity) + { + line.CountedQuantity = counted; + await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false); + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!; + } + + /// + /// Reads the counts from a text file (from a barcode reader or a spreadsheet): one row per item, the code and the + /// quantity separated by semicolon, tab or comma; a header and empty rows are skipped; the same code twice adds up. + /// + /// Who counts. + /// The company. + /// The stock take. + /// The file. + /// Cancellation. + /// How many lines were counted and the codes not on the list. + public async Task ImportCountsAsync(Actor actor, string companyCode, long id, Stream content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen); + var byCode = view.Lines.ToDictionary(l => l.Code, l => l.Line.Id, StringComparer.OrdinalIgnoreCase); + var counts = new Dictionary(); + var unknown = new List(); + using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + var row = 0; + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } text) + { + row++; + if (ParseCount(text) is not { } parsed) + { + continue; + } + + var (code, quantity) = parsed; + + if (byCode.TryGetValue(code, out var lineId)) + { + counts[lineId] = (counts.GetValueOrDefault(lineId) ?? 0m) + quantity; + } + else + { + unknown.Add(row.ToString(CultureInfo.InvariantCulture) + ": " + code); + } + } + + if (counts.Count > 0) + { + await SaveCountsAsync(actor, companyCode, id, counts, cancellationToken).ConfigureAwait(false); + } + + return new StockCountImport(counts.Count, unknown); + } + + /// + /// Posts a stock take: the counted lines that differ from the books become a movement of gains (INVP, at the cost + /// of the line) and one of losses (INVN), confirmed at the date of the count. The lines not counted are left as + /// they are. + /// + /// Who posts: needs inventory.entry.post. + /// The company. + /// The stock take. + /// Cancellation. + /// The stock take as posted. + public async Task PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.PostPermission, cancellationToken).ConfigureAwait(false); + StockTakeView view; + long? gainReason, lossReason; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false); + view = (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!; + var reasons = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + gainReason = reasons.FirstOrDefault(r => r.Code == GainReason)?.Id; + lossReason = reasons.FirstOrDefault(r => r.Code == LossReason)?.Id; + } + + if (view.Counted == 0) + { + throw new ValidationFailedException([":" + NothingCounted]); + } + + if (gainReason is null || lossReason is null) + { + throw new ValidationFailedException([":" + ReasonMissing]); + } + + var take = view.Take; + var gains = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference > 0m).ToList(); + var losses = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference < 0m).ToList(); + take.AdjustmentDocumentId = await AdjustAsync(actor, company, take, gainReason.Value, gains, cancellationToken).ConfigureAwait(false); + take.LossDocumentId = await AdjustAsync(actor, company, take, lossReason.Value, losses, cancellationToken).ConfigureAwait(false); + take.Status = StockTakeStatus.Posted; + take.PostedAt = _clock.GetUtcNow().UtcDateTime; + take.PostedBy = actor.UserName; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.Repository().UpdateAsync(take, cancellationToken).ConfigureAwait(false); + return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!; + } + } + + /// Cancels an open stock take; its counts stay for the record. + /// Who cancels. + /// The company. + /// The stock take. + /// Cancellation. + /// A task. + public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var take = await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false); + take.Status = StockTakeStatus.Cancelled; + await uow.Repository().UpdateAsync(take, cancellationToken).ConfigureAwait(false); + } + + /// A code and a quantity from a row of a count file, or none for a header or an empty row. + /// The row. + /// The code and the quantity. + public static (string Code, decimal Quantity)? ParseCount(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + + var separator = text.Contains(';', StringComparison.Ordinal) ? ';' : text.Contains('\t', StringComparison.Ordinal) ? '\t' : ','; + var parts = text.Split(separator, StringSplitOptions.TrimEntries); + if (parts.Length < 2 || parts[0].Length == 0) + { + return null; + } + + var number = parts[1].Trim('"'); + + // With a comma as separator the quantity is in the invariant form; otherwise the Italian one is accepted too. + var parsed = separator == ',' + ? decimal.TryParse(number, NumberStyles.Number, CultureInfo.InvariantCulture, out var value) + : decimal.TryParse(number.Replace(".", string.Empty, StringComparison.Ordinal), NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"), out value); + return parsed && value >= 0m ? (parts[0].Trim('"'), value) : null; + } + + // The quantity of each item in a warehouse at the end of a day. + internal static async Task> BookAsync(IUnitOfWork uow, long warehouseId, DateOnly date, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync( + Query.For().Where(l => l.WarehouseId == warehouseId && l.EntryDate <= date), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(l => l.ItemId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity)); + + private async Task AdjustAsync( + Actor actor, string company, StockTake take, long reasonId, List lines, CancellationToken cancellationToken) + { + if (lines.Count == 0) + { + return null; + } + + var entry = await _engine.NewAsync(actor, company, "MM", cancellationToken).ConfigureAwait(false); + entry.Header.DocumentDate = take.TakeDate; + entry.Header.InventoryReasonId = reasonId; + entry.Header.WarehouseId = take.WarehouseId; + entry.Header.ExternalReference = take.Description.Length > 40 ? take.Description[..40] : take.Description; + entry.Header.IsDemo = take.IsDemo; + foreach (var line in lines) + { + entry.Lines.Add(new InventoryDocumentLine + { + Kind = DocumentLineKind.Item, + ItemId = line.Line.ItemId, + Description = line.Description, + UnitOfMeasureId = line.UnitOfMeasureId, + Quantity = Math.Abs(line.Line.Difference), + Price = line.Line.UnitCost, + WarehouseId = take.WarehouseId, + }); + } + + entry = await _engine.SaveAsync(actor, company, entry, cancellationToken).ConfigureAwait(false); + return (await _engine.ConfirmAsync(actor, company, DocumentFamily.InventoryDocument, entry.Header.Id, cancellationToken).ConfigureAwait(false)).Header.Id; + } + + private static async Task OpenTakeAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + var take = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen); + return take.Status == StockTakeStatus.Open ? take : throw new ValidationFailedException([":" + NotOpen]); + } + + private static async Task ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } take) + { + return null; + } + + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => l.StockTakeId == id).OrderBy(l => l.SortOrder), cancellationToken) + .ConfigureAwait(false)).Items; + var ids = lines.Select(l => l.ItemId).Distinct().ToList(); + var items = ids.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false)) + .Items.ToDictionary(i => i.Id); + return new StockTakeView(take, [.. lines.Select(l => items.TryGetValue(l.ItemId, out var item) + ? new StockTakeLineView(l, item.Code, item.Description, item.UnitOfMeasureId) + : new StockTakeLineView(l, "?", string.Empty, null))]); + } +} diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index ab6a824..f4ef55c 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -50,7 +50,7 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy /// public sealed class JobScheduler { - /// The system tasks (M2, attachments trash from M3, ECB rates from M4). + /// The system tasks (M2, attachments trash from M3, ECB rates from M4, warehouse rebuild from M6). public static readonly IReadOnlyList SystemTasks = [ new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300), @@ -58,6 +58,7 @@ public sealed class JobScheduler new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800), new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800), new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true), + new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600), ]; private readonly IUnitOfWorkFactory _factory; diff --git a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs new file mode 100644 index 0000000..19bff2a --- /dev/null +++ b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs @@ -0,0 +1,522 @@ +using System.IO.Compression; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Files; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Files; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Tax; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Purchases; + +/// An invoice found in a received file, as the import screen shows it before registering (mockup 034). +/// The file (inside a ZIP, its entry). +/// The file as read. +/// The invoice (a file may hold several). +/// The purchase document type that registers it, or none. +/// The supplier already in the archive, by VAT number or tax code. +/// Whether the supplier already has a document with this number in this year. +/// Taxable plus tax of the summary, plus rounding: what the total should be. +/// What stops or warns (resource codes). +public sealed record IncomingCandidate( + string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal, + IReadOnlyList Problems) +{ + /// Whether it can be registered. + public bool CanImport => DocumentTypeCode is not null && !Duplicate; + + /// The total in the file, or the computed one. + public decimal Total => Invoice.Total ?? ComputedTotal; +} + +/// A file that could not be read. +/// The file. +/// Why (resource code). +public sealed record IncomingRejected(string FileName, string Error); + +/// What the files hold. +/// The invoices found. +/// The files not read. +public sealed record IncomingReading(IReadOnlyList Invoices, IReadOnlyList Rejected); + +/// An invoice registered, or why not. +/// The invoice. +/// The draft document. +/// Whether the supplier was added to the archive. +/// Why it was not registered (resource code). +/// What to check on the draft (resource codes). +public sealed record IncomingImported(IncomingCandidate Candidate, DocumentRecord? Record, bool SupplierCreated, string? Error, IReadOnlyList Warnings); + +/// +/// The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files are read by the fiscal pack; +/// each invoice finds its supplier by VAT number or tax code (or adds it), its items by the supplier code, bar code or +/// code, its tax codes by rate and nature; it becomes a draft supplier invoice or credit note with the file attached, to +/// check and confirm. Duplicates (same supplier, number and year) are refused; a total that does not match the lines is +/// reported. +/// +public sealed class PurchaseInvoiceImportService +{ + /// The largest file accepted, ZIP included. + public const int MaxFileSize = 50 * 1024 * 1024; + + /// Problem: the type of the invoice is not a purchase (a self-invoice). + public const string UnsupportedType = "purchase.import.unsupported-type"; + + /// Problem: already registered. + public const string DuplicateProblem = "purchase.import.duplicate"; + + /// Warning: the total in the file differs from the lines. + public const string TotalMismatch = "purchase.import.total-mismatch"; + + /// Warning: the signature of the file could not be verified. + public const string SignatureNotVerified = "purchase.import.signature"; + + /// Warning: the discounts of the whole document are not carried to the lines. + public const string DocumentDiscount = "purchase.import.document-discount"; + + /// Error: no tax code of the company has the rate and nature of a line. + public const string TaxCodeMissing = "purchase.import.tax-code"; + + /// Error: the archive is empty of invoices. + public const string EmptyArchive = "purchase.import.empty"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly DocumentEngine _engine; + private readonly DocumentEditor _editor; + private readonly PartyService _parties; + private readonly AttachmentService _attachments; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The document engine. + /// The editor (terms of the supplier). + /// The parties (new suppliers). + /// The attachments (the file). + /// The clock. + public PurchaseInvoiceImportService( + IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, DocumentEditor editor, PartyService parties, + AttachmentService attachments, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(parties); + ArgumentNullException.ThrowIfNull(attachments); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _engine = engine; + _editor = editor; + _parties = parties; + _attachments = attachments; + _clock = clock; + } + + /// Reads files: each XML or P7M, and those inside a ZIP. + /// Who imports: needs purchases.invoice.write. + /// The company. + /// The files, by name. + /// Cancellation. + /// The invoices found and the files not read. + public async Task ReadAsync( + Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(files); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false); + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var reader = pack.GetFeature(); + var rules = pack.GetFeature(); + var found = new List<(string Name, IncomingInvoiceFile File)>(); + var rejected = new List(); + foreach (var (name, content) in Expand(files, rejected)) + { + if (reader is null || !reader.CanRead(name, content)) + { + rejected.Add(new(name, IncomingInvoiceErrors.NotReadable)); + continue; + } + + try + { + found.Add((name, reader.Read(name, content))); + } + catch (IncomingInvoiceException ex) + { + rejected.Add(new(name, ex.Code)); + } + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var result = new List(); + foreach (var (name, file) in found) + { + var supplierId = await FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false); + foreach (var invoice in file.Invoices) + { + var problems = new List(); + var typeCode = rules?.DocumentTypeCode(invoice.DocumentType); + if (typeCode is null) + { + problems.Add(UnsupportedType); + } + + var duplicate = supplierId is { } supplier && await IsDuplicateAsync(uow, supplier, invoice, cancellationToken).ConfigureAwait(false); + if (duplicate) + { + problems.Add(DuplicateProblem); + } + + var computed = invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) + (invoice.Rounding ?? 0m); + if (invoice.Total is { } total && Math.Abs(total - computed) > 0.01m && invoice.Discounts.Count == 0) + { + problems.Add(TotalMismatch); + } + + if (invoice.Discounts.Count > 0) + { + problems.Add(DocumentDiscount); + } + + if (file.Signature is { Verified: false }) + { + problems.Add(SignatureNotVerified); + } + + result.Add(new IncomingCandidate(name, file, invoice, typeCode, supplierId, duplicate, computed, problems)); + } + } + + if (result.Count == 0 && rejected.Count == 0) + { + rejected.Add(new(files.Count == 1 ? files[0].FileName : string.Empty, EmptyArchive)); + } + + return new IncomingReading([.. result.OrderBy(c => c.Invoice.Date).ThenBy(c => c.File.Supplier.DisplayName, StringComparer.CurrentCulture)], rejected); + } + + /// + /// Registers the invoices as drafts: the supplier is found or added, each line takes its item and tax code, the + /// file is attached. One invoice that fails does not stop the others. + /// + /// Who imports. + /// The company. + /// The invoices to register. + /// Cancellation. + /// What happened to each. + public async Task> ImportAsync( + Actor actor, string companyCode, IReadOnlyList candidates, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(candidates); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + var created = new Dictionary(StringComparer.OrdinalIgnoreCase); + var result = new List(); + foreach (var candidate in candidates) + { + if (candidate.DocumentTypeCode is not { } typeCode) + { + result.Add(new(candidate, null, false, UnsupportedType, [])); + continue; + } + + var supplierCreated = false; + try + { + long supplierId; + var key = KeyOf(candidate.File.Supplier); + if (candidate.SupplierId is { } known) + { + supplierId = known; + } + else if (key.Length > 0 && created.TryGetValue(key, out var made)) + { + supplierId = made; + } + else + { + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + supplierId = await FindSupplierAsync(uow, candidate.File.Supplier, cancellationToken).ConfigureAwait(false) ?? 0; + } + + if (supplierId == 0) + { + supplierId = await CreateSupplierAsync(actor, company, candidate.File.Supplier, cancellationToken).ConfigureAwait(false); + supplierCreated = true; + } + + if (key.Length > 0) + { + created[key] = supplierId; + } + } + + var (record, warnings) = await DraftAsync(actor, company, candidate, typeCode, supplierId, today, cancellationToken).ConfigureAwait(false); + result.Add(new(candidate, record, supplierCreated, null, warnings)); + } + catch (ValidationFailedException ex) + { + result.Add(new(candidate, null, supplierCreated, (ex.Errors.Count > 0 ? ex.Errors[0] : null)?.Split(':', 2)[^1] ?? IncomingInvoiceErrors.Invalid, [])); + } + } + + return result; + } + + // ZIP archives are opened (one level, entries .xml and .p7m); other files pass as they are. + private static List<(string Name, byte[] Content)> Expand(IReadOnlyList<(string FileName, byte[] Content)> files, List rejected) + { + var result = new List<(string, byte[])>(); + foreach (var (name, content) in files) + { + if (content.Length > MaxFileSize) + { + rejected.Add(new(name, IncomingInvoiceErrors.NotReadable)); + continue; + } + + if (content.Length < 4 || content[0] != (byte)'P' || content[1] != (byte)'K') + { + result.Add((name, content)); + continue; + } + + try + { + using var archive = new ZipArchive(new MemoryStream(content, writable: false), ZipArchiveMode.Read); + long total = 0; + foreach (var entry in archive.Entries.Where(e => e.Length > 0 && !e.FullName.EndsWith('/'))) + { + var entryName = Path.GetFileName(entry.FullName); + if (!entryName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && !entryName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + total += entry.Length; + if (entry.Length > MaxFileSize || total > 4L * MaxFileSize) + { + rejected.Add(new(entryName, IncomingInvoiceErrors.NotReadable)); + continue; + } + + using var stream = entry.Open(); + using var buffer = new MemoryStream(); + stream.CopyTo(buffer); + result.Add((entryName, buffer.ToArray())); + } + } + catch (InvalidDataException) + { + rejected.Add(new(name, IncomingInvoiceErrors.NotReadable)); + } + } + + return result; + } + + private static string KeyOf(IncomingParty party) => + (party.VatNumber is { Length: > 0 } vat ? (party.CountryCode ?? "IT") + vat : party.TaxCode ?? string.Empty).ToUpperInvariant(); + + // The VAT number as the archive keeps it: digits only for Italy, with the country prefix abroad. + private static string? VatOf(IncomingParty party) => + party.VatNumber is not { Length: > 0 } vat ? null + : party.CountryCode is null or "IT" ? vat + : vat.StartsWith(party.CountryCode, StringComparison.OrdinalIgnoreCase) ? vat : party.CountryCode + vat; + + private static async Task FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken) + { + var parties = uow.Repository(); + if (VatOf(party) is { } vat) + { + var bare = party.VatNumber!; + var byVat = (await parties.ListAsync(Query.For().Where(p => p.VatNumber == vat || p.VatNumber == bare), cancellationToken).ConfigureAwait(false)).Items; + if (Pick(byVat) is { } found) + { + return found; + } + } + + if (party.TaxCode is { Length: > 0 } taxCode) + { + var byTaxCode = (await parties.ListAsync(Query.For().Where(p => p.TaxCode == taxCode), cancellationToken).ConfigureAwait(false)).Items; + return Pick(byTaxCode); + } + + return null; + + // A supplier first, then a customer that is also a supplier, then any party; the enabled ones first. + static long? Pick(IReadOnlyList parties) => parties + .OrderBy(p => p.Disabled).ThenBy(p => p.Kind == PartyKind.Supplier ? 0 : p.IsSupplier ? 1 : 2).ThenBy(p => p.Id).FirstOrDefault()?.Id; + } + + private static async Task IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken) + { + var number = invoice.Number.Trim(); + var from = new DateOnly(invoice.Date.Year, 1, 1); + var to = new DateOnly(invoice.Date.Year, 12, 31); + return await uow.Repository().CountAsync( + Query.For().Where(d => d.PartyId == supplierId && d.ExternalReference == number && d.ExternalDate >= from && d.ExternalDate <= to + && d.Status != DocumentStatus.Cancelled + && (d.Kind == DocumentKind.PurchaseInvoice || d.Kind == DocumentKind.PurchaseCreditNote)), + cancellationToken).ConfigureAwait(false) > 0; + } + + private async Task CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken) + { + var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false); + var p = record.Party; + var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant(); + bool inEu; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + inEu = (await uow.Repository().FindAsync(Query.For().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false; + } + + p.CountryCode = country; + p.SubjectType = country == "IT" + ? (party.Name is null && party.VatNumber is null ? SubjectType.Person : SubjectType.Company) + : inEu ? SubjectType.EuCompany : SubjectType.NonEuCompany; + p.Name = Limit(party.DisplayName, 200) ?? string.Empty; + p.FirstName = p.SubjectType == SubjectType.Person ? Limit(party.FirstName, 100) : null; + p.LastName = p.SubjectType == SubjectType.Person ? Limit(party.LastName, 100) : null; + p.VatNumber = VatOf(party); + p.TaxCode = Limit(party.TaxCode, 16); + p.Address = Limit(party.Address, 200); + p.StreetNumber = Limit(party.StreetNumber, 20); + p.PostalCode = Limit(party.PostalCode, 10); + p.City = Limit(party.City, 100); + p.Province = country == "IT" ? Limit(party.Province, 2) : null; + p.Email = Limit(party.Email, 200); + p.Phone = Limit(party.Phone, 40); + p.Rea = party.ReaOffice is null || party.ReaNumber is null ? null : Limit(party.ReaOffice + "-" + party.ReaNumber, 30); + return (await _parties.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false)).Party.Id; + } + + private static string? Limit(string? text, int length) => + string.IsNullOrWhiteSpace(text) ? null : text.Trim() is var trimmed && trimmed.Length > length ? trimmed[..length] : text.Trim(); + + private async Task<(DocumentRecord Record, IReadOnlyList Warnings)> DraftAsync( + Actor actor, string company, IncomingCandidate candidate, string typeCode, long supplierId, DateOnly today, CancellationToken cancellationToken) + { + var invoice = candidate.Invoice; + var record = await _engine.NewAsync(actor, company, typeCode, cancellationToken).ConfigureAwait(false); + await _editor.ApplyPartyAsync(actor, company, record, supplierId, cancellationToken).ConfigureAwait(false); + var header = record.Header; + header.DocumentDate = invoice.Date > today ? invoice.Date : today; + header.ExternalReference = Limit(invoice.Number, 50); + header.ExternalDate = invoice.Date; + if (invoice.Causals.Count > 0) + { + header.Notes = Limit(string.Join(Environment.NewLine, invoice.Causals), 2000); + } + + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + var taxes = (await uow.Repository().ListAsync(Query.For().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items; + var codes = invoice.Lines.SelectMany(l => l.Codes).Select(c => c.Value.Trim()).Where(v => v.Length > 0).Distinct(StringComparer.Ordinal).ToList(); + var bySupplierCode = codes.Count == 0 ? [] : (await uow.Repository().ListAsync( + Query.For().Where(s => s.PartyId == supplierId && codes.Contains(s.SupplierCode!)), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(s => s.SupplierCode!, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal); + var byBarcode = codes.Count == 0 ? [] : (await uow.Repository().ListAsync( + Query.For().Where(b => codes.Contains(b.Code)), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(b => b.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal); + var byCode = codes.Count == 0 ? [] : (await uow.Repository().ListAsync( + Query.For().Where(i => codes.Contains(i.Code)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Code, StringComparer.Ordinal); + var itemIds = bySupplierCode.Values.Concat(byBarcode.Values).Distinct().ToList(); + var items = itemIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(i => i.Id); + foreach (var item in byCode.Values) + { + items.TryAdd(item.Id, item); + } + + var credit = record.Header.Kind == DocumentKind.PurchaseCreditNote; + foreach (var source in invoice.Lines.OrderBy(l => l.Number)) + { + var line = new PurchaseDocumentLine(); + line.Kind = DocumentLineKind.Free; + line.Description = Limit(source.Description, 1000) ?? "-"; + line.TaxCodeId = TaxCodeOf(taxes, source.TaxRate, source.Nature) + ?? throw new ValidationFailedException([":" + TaxCodeMissing]); + var quantity = source.Quantity is { } q && q != 0m ? q : 1m; + var price = source.UnitPrice; + var discounts = source.Discounts; + if (discounts.Count > 0 && discounts.All(d => d.Percent is > 0m and <= 100m && !d.IsSurcharge)) + { + line.DiscountFormula = string.Join('+', discounts.Select(d => d.Percent!.Value.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture))); + } + else if (discounts.Count > 0 || (source.Quantity is null && source.TotalPrice != source.UnitPrice)) + { + // Amounts or surcharges: the net price keeps the total of the line. + price = Math.Round(source.TotalPrice / quantity, 6); + } + + line.Quantity = credit ? Math.Abs(quantity) : quantity; + line.Price = credit && quantity < 0m ? -price : price; + if (ItemOf(source, bySupplierCode, byBarcode, byCode) is { } itemId && items.TryGetValue(itemId, out var item) && !item.Disabled) + { + line.Kind = DocumentLineKind.Item; + line.ItemId = item.Id; + line.UnitOfMeasureId = item.UnitOfMeasureId; + } + + record.Lines.Add(line); + } + } + + var saved = await _engine.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false); + await _attachments.AddAsync( + actor, company, DocumentPrintService.EntityOf(saved.Family), saved.Header.Id, new AttachmentFile(AttachmentKind.EInvoice, candidate.File.FileName, null), + (stream, ct) => stream.WriteAsync(candidate.File.Xml, ct).AsTask(), cancellationToken).ConfigureAwait(false); + var warnings = candidate.Problems.Where(p => p is TotalMismatch or SignatureNotVerified or DocumentDiscount).ToList(); + if (invoice.Total is { } total && Math.Abs(total - saved.Header.TotalAmount) > 0.01m && !warnings.Contains(TotalMismatch)) + { + warnings.Add(TotalMismatch); + } + + return (saved, warnings); + } + + private static long? ItemOf(IncomingLine line, Dictionary bySupplierCode, Dictionary byBarcode, Dictionary byCode) + { + foreach (var code in line.Codes.Select(c => c.Value.Trim())) + { + if (bySupplierCode.TryGetValue(code, out var id) || byBarcode.TryGetValue(code, out id)) + { + return id; + } + } + + return line.Codes.Select(c => c.Value.Trim()).FirstOrDefault(byCode.ContainsKey) is { } own ? byCode[own].Id : null; + } + + // The tax code with the rate and nature of the line: the exact nature first, then the family of the nature (N3 for + // N3.2), then for an ordinary rate the ordinary codes before the others. + private static long? TaxCodeOf(IReadOnlyList taxes, decimal rate, string? nature) + { + var withRate = taxes.Where(t => t.Rate == rate).OrderBy(t => t.ValidTo is not null).ThenBy(t => t.Code, StringComparer.Ordinal).ToList(); + if (nature is null) + { + return (withRate.FirstOrDefault(t => t.Nature is null && t.Kind == TaxCodeKind.Taxable) ?? withRate.FirstOrDefault(t => t.Nature is null))?.Id; + } + + return (withRate.FirstOrDefault(t => string.Equals(t.Nature, nature, StringComparison.OrdinalIgnoreCase)) + ?? withRate.FirstOrDefault(t => t.Nature is not null && t.Nature.StartsWith(nature.Split('.')[0], StringComparison.OrdinalIgnoreCase)))?.Id; + } +} diff --git a/src/Khaemhat.Application/Purchases/PurchaseService.cs b/src/Khaemhat.Application/Purchases/PurchaseService.cs new file mode 100644 index 0000000..8d6fde2 --- /dev/null +++ b/src/Khaemhat.Application/Purchases/PurchaseService.cs @@ -0,0 +1,267 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Purchases; + +/// A line of a supplier invoice whose price differs from the order or receipt it comes from (§11.5). +/// The line of the invoice. +/// Its description. +/// The kind of the document it comes from. +/// Its number. +/// The net unit price there. +/// The net unit price on the invoice. +/// The quantity of the invoice line. +public sealed record PriceDifference( + int LineNumber, string Description, DocumentKind SourceKind, string? SourceNumber, decimal SourcePrice, decimal InvoicePrice, decimal Quantity) +{ + /// The difference on the whole line: positive when the invoice costs more. + public decimal Amount => Math.Round((InvoicePrice - SourcePrice) * Quantity, 2, MidpointRounding.AwayFromZero); +} + +/// A supplier invoice that waits for its self-invoice (mockup 035). +/// The invoice. +/// The self-invoice it needs and by when. +public sealed record PendingSelfInvoice(DocumentRow Invoice, SelfInvoiceAdvice Advice); + +/// +/// The rules of purchases beyond the document engine (SPEC §11.5): price differences against orders and receipts, +/// the self-invoice a supplier invoice needs (reverse charge, purchases from abroad) and its draft. +/// +/// Permissions purchases.invoice.read and write. +public sealed class PurchaseService +{ + /// Permission to read supplier invoices. + public const string ReadPermission = "purchases.invoice.read"; + + /// Permission to register supplier invoices and self-invoices. + public const string WritePermission = "purchases.invoice.write"; + + /// The supplier invoice does not need a self-invoice. + public const string SelfInvoiceNotNeeded = "purchase.self-invoice.not-needed"; + + private readonly DocumentEngine _engine; + private readonly DocumentCopyService _copies; + private readonly DocumentEditor _editor; + private readonly CompanyFiscalContext _packs; + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + + /// Creates the service. + /// The document engine. + /// Copies and transformations. + /// The editor (radars). + /// The fiscal pack of each company. + /// The units of work. + /// The permissions. + public PurchaseService( + DocumentEngine engine, DocumentCopyService copies, DocumentEditor editor, CompanyFiscalContext packs, IUnitOfWorkFactory factory, PermissionService permissions) + { + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(copies); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + _engine = engine; + _copies = copies; + _editor = editor; + _packs = packs; + _factory = factory; + _permissions = permissions; + } + + /// The lines of a supplier invoice whose net price differs from their order or receipt. + /// Who reads. + /// The company. + /// The invoice, as on screen. + /// Cancellation. + /// The differences. + public async Task> PriceDifferencesAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var result = new List(); + if (record.Header.Kind is not (DocumentKind.PurchaseInvoice or DocumentKind.PurchaseDeliveryNote)) + { + return result; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var headers = new Dictionary<(DocumentFamily, long), DocumentHeader?>(); + for (var i = 0; i < record.Lines.Count; i++) + { + var line = record.Lines[i]; + if (line.SourceFamily is not { } family || line.SourceLineId is not { } sourceId || line.Quantity == 0m) + { + continue; + } + + var source = await DocumentStores.Of(family).GetLineAsync(uow, sourceId, cancellationToken).ConfigureAwait(false); + if (source is null || source.Quantity == 0m) + { + continue; + } + + if (!headers.TryGetValue((family, source.DocumentId), out var header)) + { + header = await DocumentStores.Of(family).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false); + headers[(family, source.DocumentId)] = header; + } + + if (header is null) + { + continue; + } + + var before = Math.Round(source.TaxableAmount / source.Quantity, 4, MidpointRounding.AwayFromZero); + var now = Math.Round(line.TaxableAmount / line.Quantity, 4, MidpointRounding.AwayFromZero); + if (before != now) + { + result.Add(new PriceDifference(i + 1, line.Description, header.Kind, header.DocumentNumber ?? header.ExternalReference, before, now, line.Quantity)); + } + } + + return result; + } + + /// The self-invoice a supplier invoice needs, if any (reverse charge, purchase from abroad). + /// Who reads. + /// The company. + /// The invoice. + /// Cancellation. + /// The advice, or . + public async Task AdviseAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + if (record.Header.Kind != DocumentKind.PurchaseInvoice || record.Header.PartyId is null) + { + return null; + } + + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + if (rules is null) + { + return null; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false); + } + + /// + /// The confirmed supplier invoices that need a self-invoice and have none yet, the nearest deadline first. + /// + /// Who reads. + /// The company. + /// Cancellation. + /// The invoices with their advice. + public async Task> PendingSelfInvoicesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + if (rules is null) + { + return []; + } + + var rows = await _editor.ListAsync(actor, company, DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseInvoice], new Querying.ListQuery { Limit = 500 }, cancellationToken) + .ConfigureAwait(false); + var result = new List(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var integrated = (await uow.Repository().ListAsync( + Query.For().Where(l => l.SourceFamily == DocumentFamily.PurchaseDocument && l.TargetFamily == DocumentFamily.SaleDocument), cancellationToken) + .ConfigureAwait(false)).Items.Select(l => l.SourceDocumentId).ToHashSet(); + foreach (var row in rows.Items.Where(r => DocumentStateMachine.IsInForce(r.Status) && !integrated.Contains(r.Id))) + { + var record = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, row.Id, cancellationToken).ConfigureAwait(false); + if (record is not null && await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false) is { } advice) + { + result.Add(new PendingSelfInvoice(row, advice)); + } + } + + return [.. result.OrderBy(p => p.Advice.Deadline).ThenBy(p => p.Invoice.Date)]; + } + + /// + /// The draft self-invoice of a supplier invoice: its lines with the ordinary VAT code where the supplier wrote a + /// nature, the supplier's number and date as the related invoice, today as date. + /// + /// Who creates. + /// The company. + /// The supplier invoice. + /// The type, such as AF17; the advised one when empty. + /// Cancellation. + /// The draft, saved. + /// No type was given and none is advised. + public async Task CreateSelfInvoiceAsync(Actor actor, string companyCode, long purchaseInvoiceId, string? typeCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var invoice = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + var code = typeCode; + if (string.IsNullOrWhiteSpace(code)) + { + await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + code = (await AdviseAsync(read, rules, invoice, cancellationToken).ConfigureAwait(false))?.DocumentTypeCode + ?? throw new ValidationFailedException([":" + SelfInvoiceNotNeeded]); + } + + var draft = await _copies.CopyAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, code, null, cancellationToken).ConfigureAwait(false); + var header = draft.Header; + header.RelatedDocumentId = invoice.Header.Id; + header.RelatedNumber = invoice.Header.ExternalReference; + header.RelatedDate = invoice.Header.ExternalDate; + header.ExternalReference = null; + header.ExternalDate = null; + header.InventoryReasonId = null; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + var taxes = (await uow.Repository().ListAsync(Query.For().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items; + var ordinary = taxes.FirstOrDefault(t => t.Code == rules.OrdinaryTaxCode)?.Id; + foreach (var line in draft.Lines) + { + // The supplier invoiced without VAT (a nature): the integration applies the rate. + if (line.TaxCodeId is { } id && taxes.FirstOrDefault(t => t.Id == id) is { Nature: not null } && ordinary is not null) + { + line.TaxCodeId = ordinary; + } + } + } + + return await _engine.SaveAsync(actor, company, draft, cancellationToken).ConfigureAwait(false); + } + + private static async Task AdviseAsync(IUnitOfWork uow, ISelfInvoiceRules rules, DocumentRecord record, CancellationToken cancellationToken) + { + if (record.Header.PartyId is not { } partyId || await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { } party) + { + return null; + } + + var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant(); + var inEu = (await uow.Repository().FindAsync(Query.For().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false; + var taxIds = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).Distinct().ToList(); + var natures = taxIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(t => taxIds.Contains(t.Id)), cancellationToken) + .ConfigureAwait(false)).Items.Where(t => t.Nature is not null).Select(t => t.Nature!).Distinct().ToList(); + var itemIds = record.Lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList(); + var kinds = itemIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(i => i.Id, i => i.Kind); + + // Goods when the item lines of goods weigh more than the rest; free lines count as services. + var goods = record.Lines.Where(l => l.ItemId is { } id && kinds.GetValueOrDefault(id) == ItemKind.Goods).Sum(l => Math.Abs(l.TaxableAmount)); + var other = record.Lines.Where(l => l.Kind != DocumentLineKind.Description).Sum(l => Math.Abs(l.TaxableAmount)) - goods; + var received = record.Header.VatDate ?? record.Header.DocumentDate; + return rules.Advise(new SelfInvoiceCase(country, inEu && country != "IT", goods > other, natures, received)); + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs new file mode 100644 index 0000000..8f4edbd --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs @@ -0,0 +1,260 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Seeding; + +/// +/// The purchases and the warehouse of the demo company (SPEC §14, issue #61), made through the document engine like a +/// user makes them: the opening stock on the first of January, supplier orders received in full and in part, the +/// supplier invoice of a receipt with a price that differs from the order, a professional's invoice, an invoice from a +/// German supplier still waiting for its self-invoice, and a stock take being counted. Some items start low, so that the +/// sales bring them under their minimum and the reorder proposal has something to propose. Runs only when the demo data +/// are asked and the company has no purchase documents yet; every document is marked as demo. +/// +/// The document engine. +/// The document editor (supplier terms, item costs). +/// The transformations between documents. +/// The stock takes. +/// The units of work. +/// The clock. +public sealed class DemoPurchasesSeeder( + DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, StockTakeService stockTakes, IUnitOfWorkFactory factory, TimeProvider clock) + : ICompanySeeder +{ + private static readonly Actor Seed = Actor.System; + + private DocumentEngine Engine { get; } = engine; + + private DocumentEditor Editor { get; } = editor; + + private DocumentCopyService Copies { get; } = copies; + + private StockTakeService StockTakes { get; } = stockTakes; + + /// + public int Order => 30; + + /// + public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + if (!context.Demo) + { + return; + } + + var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false); + if (data is null) + { + return; + } + + var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + var run = new Run(this, companyCode, data, today, cancellationToken); + await run.ExecuteAsync().ConfigureAwait(false); + } + + // The suppliers, goods and reasons the documents use; null when the company already has purchases or lacks them. + private async Task ReadAsync(string companyCode, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return null; + } + + var parties = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal); + var goods = (await uow.Repository().ListAsync(Query.For().Where(i => i.IsDemo && i.Kind == ItemKind.Goods && i.Stocked), cancellationToken) + .ConfigureAwait(false)).Items.OrderBy(i => i.Id).ToList(); + var goodIds = goods.Select(g => g.Id).ToList(); + var suppliers = (await uow.Repository().ListAsync(Query.For().Where(s => goodIds.Contains(s.ItemId)), cancellationToken) + .ConfigureAwait(false)).Items.GroupBy(s => s.PartyId).ToDictionary(g => g.Key, g => (IReadOnlyList)[.. g.Select(s => s.ItemId).Distinct()]); + var reasons = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(r => r.Code, r => r.Id, StringComparer.Ordinal); + var taxes = (await uow.Repository().ListAsync(Query.For().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items; + var warehouse = (await uow.Repository().ListAsync(Query.For().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items + .OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id; + string[] names = ["Metalli Nord S.p.A.", "Plastica Sud S.r.l.", "Studio Rag. Neri Paola", "Elektro Werke Süd GmbH"]; + var ordinary = taxes.FirstOrDefault(t => t.Code == "22")?.Id; + var intraEu = taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N3.2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault() + ?? taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault(); + if (goods.Count < 12 || !names.All(parties.ContainsKey) || !reasons.TryGetValue("APE", out var opening) || warehouse is null || ordinary is null || intraEu is null) + { + return null; + } + + return new DemoData(parties, goods, suppliers, opening, warehouse.Value, ordinary.Value, intraEu.Value); + } + + private sealed record DemoData( + IReadOnlyDictionary Parties, IReadOnlyList Goods, IReadOnlyDictionary> ItemsBySupplier, long OpeningReason, + long Warehouse, long Ordinary, long IntraEu); + + // One seeding, with its company and dates. + private sealed class Run(DemoPurchasesSeeder owner, string company, DemoData data, DateOnly today, CancellationToken cancellationToken) + { + private long Party(string name) => data.Parties[name]; + + // A date some months before today, kept between the first of January and today (as the sales do). + private DateOnly D(int monthsBack, int day) + { + var month = today.AddMonths(-monthsBack); + var date = new DateOnly(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month))); + var first = new DateOnly(today.Year, 1, 1); + return date < first ? first : date > today ? today : date; + } + + // The goods a supplier sells, else the first goods. + private List GoodsOf(string supplier, int count) + { + var ids = data.ItemsBySupplier.GetValueOrDefault(Party(supplier)) ?? []; + var own = data.Goods.Where(g => ids.Contains(g.Id)).Take(count).ToList(); + return own.Count >= count ? own : [.. own, .. data.Goods.Where(g => !own.Contains(g)).Take(count - own.Count)]; + } + + public async Task ExecuteAsync() + { + await OpeningAsync().ConfigureAwait(false); + + // Metalli Nord: an order received in full, invoiced at a higher price on one line. + var metals = GoodsOf("Metalli Nord S.p.A.", 3); + var o1 = await OrderAsync("Metalli Nord S.p.A.", D(4, 5), [(metals[0], 30m), (metals[1], 20m), (metals[2], 50m)], "Riordino trimestrale").ConfigureAwait(false); + var r1 = await ReceiveAsync(o1, D(4, 15), "DDT 1184", null).ConfigureAwait(false); + var f1 = await CopyAsync(r1, "FF", D(4, 30)).ConfigureAwait(false); + var dearer = f1.Lines.First(l => l.Kind == DocumentLineKind.Item); + dearer.Price = Math.Round(dearer.Price * 1.04m, 2); + f1.Header.ExternalReference = "MN/2026/0311"; + f1.Header.ExternalDate = D(4, 28); + await ConfirmAsync(await SaveAsync(f1).ConfigureAwait(false)).ConfigureAwait(false); + + // Plastica Sud: an order received in part; the rest is still on its way. + var plastics = GoodsOf("Plastica Sud S.r.l.", 3); + var o2 = await OrderAsync("Plastica Sud S.r.l.", D(2, 3), [(plastics[0], 40m), (plastics[1], 60m), (plastics[2], 25m)], null).ConfigureAwait(false); + await ReceiveAsync(o2, D(1, 10), "Bolla 552", [o2.Lines[0].Id, o2.Lines[1].Id]).ConfigureAwait(false); + + // The accountant's fees, with withholding tax. + await InvoiceAsync("Studio Rag. Neri Paola", D(1, 28), "12/2026", D(1, 27), "Tenuta contabilità e dichiarativi", 450m, data.Ordinary).ConfigureAwait(false); + + // Goods from Germany: no Italian VAT on the invoice, the self-invoice is still to issue. + var german = data.Goods[^1]; + await InvoiceAsync("Elektro Werke Süd GmbH", D(0, 3), "RE-2026-08841", D(0, 1), german.Description, 1280m, data.IntraEu, german).ConfigureAwait(false); + + // A stock take being counted: half of the list, two items differ from the books. + var take = await owner.StockTakes.CreateAsync(Seed, company, data.Warehouse, today, null, null, cancellationToken).ConfigureAwait(false); + var counts = new Dictionary(); + foreach (var (line, index) in take.Lines.Take(Math.Min(12, take.Lines.Count)).Select((l, i) => (l, i))) + { + counts[line.Line.Id] = Math.Max(0m, line.Line.BookQuantity + index switch { 2 => -2m, 7 => 1m, _ => 0m }); + } + + await owner.StockTakes.SaveCountsAsync(Seed, company, take.Take.Id, counts, cancellationToken).ConfigureAwait(false); + } + + // The opening stock: plenty of most goods, little of one in five, so that the year's sales bring them under. + private async Task OpeningAsync() + { + var movement = await owner.Engine.NewAsync(Seed, company, "MM", cancellationToken).ConfigureAwait(false); + movement.Header.IsDemo = true; + movement.Header.DocumentDate = new DateOnly(today.Year, 1, 1); + movement.Header.WarehouseId = data.Warehouse; + movement.Header.InventoryReasonId = data.OpeningReason; + movement.Header.Notes = "Esistenze iniziali dall'inventario di fine anno."; + foreach (var (item, index) in data.Goods.Select((g, i) => (g, i))) + { + var bulk = item.ReorderPoint is null; + movement.Lines.Add(new InventoryDocumentLine + { + Kind = DocumentLineKind.Item, + ItemId = item.Id, + Description = item.Description, + UnitOfMeasureId = item.UnitOfMeasureId, + Quantity = index % 5 == 0 ? (bulk ? 30m : 6m) : bulk ? 400m : 60m, + Price = item.StandardCost ?? 0m, + WarehouseId = data.Warehouse, + }); + } + + await ConfirmAsync(await SaveAsync(movement).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task OrderAsync(string supplier, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, string? notes) + { + var order = await owner.Engine.NewAsync(Seed, company, "OF", cancellationToken).ConfigureAwait(false); + order.Header.IsDemo = true; + order.Header.DocumentDate = date; + order.Header.Notes = notes; + await owner.Editor.ApplyPartyAsync(Seed, company, order, Party(supplier), cancellationToken).ConfigureAwait(false); + foreach (var (item, quantity) in lines) + { + var line = new PurchaseOrderLine { Quantity = quantity }; + await owner.Editor.FillLineAsync(Seed, company, order, line, item.Id, cancellationToken).ConfigureAwait(false); + line.Quantity = quantity; + order.Lines.Add(line); + } + + return await ConfirmAsync(await SaveAsync(order).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task ReceiveAsync(DocumentRecord order, DateOnly date, string reference, IReadOnlyCollection? lines) + { + var receipt = await CopyAsync(order, "DDTF", date, lines).ConfigureAwait(false); + receipt.Header.ExternalReference = reference; + receipt.Header.ExternalDate = date; + return await ConfirmAsync(await SaveAsync(receipt).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task InvoiceAsync(string supplier, DateOnly date, string number, DateOnly numberDate, string description, decimal amount, long taxCode, Item? item = null) + { + var invoice = await owner.Engine.NewAsync(Seed, company, "FF", cancellationToken).ConfigureAwait(false); + invoice.Header.IsDemo = true; + invoice.Header.DocumentDate = date; + invoice.Header.ExternalReference = number; + invoice.Header.ExternalDate = numberDate; + await owner.Editor.ApplyPartyAsync(Seed, company, invoice, Party(supplier), cancellationToken).ConfigureAwait(false); + var line = new PurchaseDocumentLine { Quantity = 1m }; + if (item is not null) + { + await owner.Editor.FillLineAsync(Seed, company, invoice, line, item.Id, cancellationToken).ConfigureAwait(false); + line.Quantity = 10m; + line.Price = Math.Round(amount / 10m, 2); + } + else + { + line.Kind = DocumentLineKind.Free; + line.Description = description; + line.Price = amount; + } + + line.TaxCodeId = taxCode; + invoice.Lines.Add(line); + await ConfirmAsync(await SaveAsync(invoice).ConfigureAwait(false)).ConfigureAwait(false); + } + + private async Task CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection? lines = null) + { + var copy = await owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken).ConfigureAwait(false); + copy.Header.IsDemo = true; + return copy; + } + + private Task SaveAsync(DocumentRecord record) + { + record.Header.IsDemo = true; + return owner.Engine.SaveAsync(Seed, company, record, cancellationToken); + } + + private Task ConfirmAsync(DocumentRecord record) => + owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken); + } +} diff --git a/src/Khaemhat.Core/Documents/Documents.cs b/src/Khaemhat.Core/Documents/Documents.cs index cf8cbc9..749b7aa 100644 --- a/src/Khaemhat.Core/Documents/Documents.cs +++ b/src/Khaemhat.Core/Documents/Documents.cs @@ -73,6 +73,9 @@ public abstract class DocumentHeader : Entity, IDemoMarkable /// The warehouse. public long? WarehouseId { get; set; } + /// The destination warehouse of a transfer. + public long? ToWarehouseId { get; set; } + /// The warehouse reason. public long? InventoryReasonId { get; set; } @@ -220,9 +223,15 @@ public abstract class DocumentHeader : Entity, IDemoMarkable /// The ledger entry, once posted (M7). public long? GlEntryId { get; set; } - /// The VAT protocol of a supplier invoice. + /// The VAT protocol of a supplier invoice: its progressive number in the purchase register of the year. public long? VatProtocol { get; set; } + /// + /// The date the VAT of a supplier invoice counts from (competenza IVA): the registration date by default, an + /// earlier one when the invoice is received late but deducted in its period. + /// + public DateOnly? VatDate { get; set; } + /// When the document was confirmed or issued. public DateTime? ConfirmedAt { get; set; } diff --git a/src/Khaemhat.Core/Inventory/Inventory.cs b/src/Khaemhat.Core/Inventory/Inventory.cs new file mode 100644 index 0000000..c014963 --- /dev/null +++ b/src/Khaemhat.Core/Inventory/Inventory.cs @@ -0,0 +1,209 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Inventory; + +/// +/// A posting to the stock (SPEC §11.6, ADR 0035, inventory_entries): the movements one confirmed document wrote. +/// Cancelling the document removes its entry; the balances are then computed again from the movements left. +/// +public sealed class InventoryEntry : Entity, IDemoMarkable +{ + /// The date of the movements: the date of the document. + public DateOnly EntryDate { get; set; } + + /// The family of the document that posted it. + public DocumentFamily? SourceFamily { get; set; } + + /// The document that posted it. + public long? SourceDocumentId { get; set; } + + /// The kind of that document. + public DocumentKind? SourceKind { get; set; } + + /// The number of that document, as printed. + public string? SourceNumber { get; set; } + + /// The warehouse reason. + public long? InventoryReasonId { get; set; } + + /// The customer or supplier of the document. + public long? PartyId { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// +/// A movement of one item in one warehouse (inventory_entry_lines), in the base unit of the item: positive +/// loads, negative unloads. A transfer writes two lines. +/// +public sealed class InventoryEntryLine : Entity +{ + /// The entry. + public long EntryId { get; set; } + + /// The date, as the entry (kept here to read the history of an item without joins). + public DateOnly EntryDate { get; set; } + + /// The item. + public long ItemId { get; set; } + + /// The warehouse. + public long WarehouseId { get; set; } + + /// The quantity in the base unit: positive for loads, negative for unloads. + public decimal Quantity { get; set; } + + /// + /// The cost comes from the document (purchases, opening stock, adjustments with a cost) and moves the average; when + /// false the line is valued at the average of its moment (sales, returns, transfers). + /// + public bool Valued { get; set; } + + /// The unit cost in euro. + public decimal UnitCost { get; set; } + + /// The value of the movement in euro, with the sign of the quantity. + public decimal Value { get; set; } + + /// The document line that wrote it. + public long? SourceLineId { get; set; } + + /// The order of the lines in the entry. + public int SortOrder { get; set; } +} + +/// +/// What an item has in a warehouse (item_balances), kept in step with the movements and the open orders: +/// on hand, committed to customers, ordered from suppliers, average cost and value. +/// +public sealed class ItemBalance : Entity +{ + /// The item. + public long ItemId { get; set; } + + /// The warehouse. + public long WarehouseId { get; set; } + + /// The quantity on hand. + public decimal OnHand { get; set; } + + /// The quantity in the confirmed customer orders still to deliver. + public decimal Committed { get; set; } + + /// The quantity in the confirmed supplier orders still to receive. + public decimal Ordered { get; set; } + + /// The quantity sent towards this warehouse and not yet arrived (transfers are immediate: kept for later). + public decimal InTransit { get; set; } + + /// The weighted average cost of the item. + public decimal AverageCost { get; set; } + + /// The value of the quantity on hand at the average cost. + public decimal Value { get; set; } + + /// The last purchase cost. + public decimal? LastCost { get; set; } + + /// The date of the last load. + public DateOnly? LastLoadDate { get; set; } + + /// The date of the last unload. + public DateOnly? LastUnloadDate { get; set; } + + /// What can be promised: on hand less committed. + public decimal Available => OnHand - Committed; +} + +/// The state of a physical inventory. +public enum StockTakeStatus +{ + /// Counting: the quantities can be entered. + Open = 0, + + /// Posted: the differences became adjustments. + Posted = 1, + + /// Abandoned. + Cancelled = 2, +} + +/// A physical inventory of a warehouse (SPEC §11.6, mockup 038, stock_takes). +public sealed class StockTake : Entity, IDemoMarkable +{ + /// The date the count refers to: the book quantities are those of the evening of that day. + public DateOnly TakeDate { get; set; } + + /// The warehouse counted. + public long WarehouseId { get; set; } + + /// A description, such as Inventario di fine anno. + public string Description { get; set; } = string.Empty; + + /// The item category counted; every stocked item when empty. + public long? CategoryId { get; set; } + + /// The state. + public StockTakeStatus Status { get; set; } + + /// The warehouse entry that loads what was found more than the books, once posted. + public long? AdjustmentDocumentId { get; set; } + + /// The warehouse entry that unloads what was found less than the books, once posted. + public long? LossDocumentId { get; set; } + + /// When it was posted. + public DateTime? PostedAt { get; set; } + + /// Who posted it. + public string? PostedBy { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A line of a physical inventory (stock_take_lines). +public sealed class StockTakeLine : Entity +{ + /// The inventory. + public long StockTakeId { get; set; } + + /// The item. + public long ItemId { get; set; } + + /// The quantity the books say at the date of the count. + public decimal BookQuantity { get; set; } + + /// The quantity counted; empty until counted. + public decimal? CountedQuantity { get; set; } + + /// The unit cost used for the adjustment: the average cost at the date. + public decimal UnitCost { get; set; } + + /// Notes of the counter. + public string? Notes { get; set; } + + /// The order on the list (by item code). + public int SortOrder { get; set; } + + /// The difference to adjust: counted less book, zero while not counted. + public decimal Difference => CountedQuantity is { } counted ? counted - BookQuantity : 0m; +} + +/// How the stock is valued at a date (SPEC §11.6). +public enum StockValuationMethod +{ + /// Weighted average cost, moved by every purchase (the one the balances keep). + WeightedAverage = 0, + + /// The last purchase cost. + LastCost = 1, + + /// The standard cost of the item. + StandardCost = 2, +} diff --git a/src/Khaemhat.Core/Inventory/StockCostCalculator.cs b/src/Khaemhat.Core/Inventory/StockCostCalculator.cs new file mode 100644 index 0000000..0499559 --- /dev/null +++ b/src/Khaemhat.Core/Inventory/StockCostCalculator.cs @@ -0,0 +1,85 @@ +namespace Khaemhat.Core.Inventory; + +/// A movement of one item, in the order of the history. +/// The movement. +/// The date. +/// The warehouse. +/// Positive loads, negative unloads, in the base unit. +/// The cost comes from the document. +/// The cost of a valued movement. +public sealed record CostedMovement(long Id, DateOnly Date, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost); + +/// What one warehouse holds after the history. +/// The quantity on hand. +/// The date of the last load. +/// The date of the last unload. +public sealed record WarehouseStock(decimal OnHand, DateOnly? LastLoad, DateOnly? LastUnload); + +/// The history of an item run through the weighted average. +/// The unit cost of each movement: its own when valued, the average of its moment otherwise. +/// What each warehouse holds. +/// The average cost at the end. +/// The cost of the last valued load. +/// The quantity on hand in every warehouse together. +public sealed record CostedHistory( + IReadOnlyDictionary UnitCosts, IReadOnlyDictionary Warehouses, decimal AverageCost, decimal? LastCost, decimal OnHand); + +/// +/// The weighted average cost of an item over its movements (SPEC §11.6, ADR 0035): every valued load (purchase, +/// opening stock, adjustment with a cost) moves the average of the item across its warehouses; every other movement is +/// valued at the average of its moment. When the stock was zero or below, the next valued load sets the average. +/// +public static class StockCostCalculator +{ + /// The decimals of unit costs. + public const int CostDecimals = 4; + + /// Runs the history of an item. + /// The movements, in date and posting order. + /// The cost used before the first valued load (the standard cost of the item, or zero). + /// The costs and the stock. + public static CostedHistory Run(IEnumerable movements, decimal initialCost = 0m) + { + ArgumentNullException.ThrowIfNull(movements); + var costs = new Dictionary(); + var warehouses = new Dictionary(); + var total = 0m; + var average = initialCost; + decimal? last = null; + foreach (var m in movements) + { + decimal cost; + if (m.Valued && m.Quantity > 0m) + { + cost = m.UnitCost; + var after = total + m.Quantity; + average = total <= 0m || after <= 0m ? cost : Math.Round(((total * average) + (m.Quantity * cost)) / after, CostDecimals, MidpointRounding.AwayFromZero); + last = cost; + } + else + { + cost = average; + } + + costs[m.Id] = cost; + total += m.Quantity; + var stock = warehouses.TryGetValue(m.WarehouseId, out var s) ? s : new WarehouseStock(0m, null, null); + warehouses[m.WarehouseId] = stock with + { + OnHand = stock.OnHand + m.Quantity, + LastLoad = m.Quantity > 0m ? Later(stock.LastLoad, m.Date) : stock.LastLoad, + LastUnload = m.Quantity < 0m ? Later(stock.LastUnload, m.Date) : stock.LastUnload, + }; + } + + return new CostedHistory(costs, warehouses, average, last, total); + } + + /// The value of a quantity at a unit cost, in euro to the cent. + /// The quantity. + /// The unit cost. + /// The value. + public static decimal Value(decimal quantity, decimal unitCost) => Math.Round(quantity * unitCost, 2, MidpointRounding.AwayFromZero); + + private static DateOnly Later(DateOnly? a, DateOnly b) => a is { } x && x > b ? x : b; +} diff --git a/src/Khaemhat.Core/Inventory/StockEffectMatrix.cs b/src/Khaemhat.Core/Inventory/StockEffectMatrix.cs new file mode 100644 index 0000000..8f6f2ff --- /dev/null +++ b/src/Khaemhat.Core/Inventory/StockEffectMatrix.cs @@ -0,0 +1,122 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tables; + +namespace Khaemhat.Core.Inventory; + +/// A document line as the stock sees it: an item, a quantity in its base unit, a warehouse, a cost. +/// The document line. +/// The item. +/// The quantity in the base unit of the item (positive). +/// The warehouse of the line. +/// The cost per base unit in euro written on the document, if any. +public sealed record StockLineInput(long LineId, long ItemId, decimal Quantity, long WarehouseId, decimal? UnitCost); + +/// A movement to write: one item, one warehouse, a signed quantity. +/// The document line. +/// The item. +/// The warehouse. +/// Positive loads, negative unloads. +/// The cost comes from the document and moves the average. +/// The cost of a valued movement; zero for the others (valued at the average). +public sealed record StockMovement(long? SourceLineId, long ItemId, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost); + +/// What the warehouse reason of a document does. +/// Load, unload or nothing on the quantity. +/// Purchases and sales move the value; transfers and goods on approval only quantities. +/// A transfer between two warehouses. +public sealed record StockReason(StockEffect Effect, bool AffectsValue, bool IsTransfer) +{ + /// The reason of a row of inventory_reasons. + /// The row. + /// The reason. + public static StockReason Of(InventoryReason reason) + { + ArgumentNullException.ThrowIfNull(reason); + return new StockReason(reason.Effect, reason.AffectsValue, reason.IsTransfer); + } +} + +/// +/// Which documents move the stock and how (SPEC §11.6, ADR 0035): the warehouse reason of the document decides load, +/// unload or transfer; the kind decides whether the reason counts at all and whether the cost on the lines is a +/// purchase cost that moves the average. Orders do not move the stock: their residuals are the committed and ordered +/// quantities. +/// +public static class StockEffectMatrix +{ + private static readonly HashSet Moving = + [ + DocumentKind.DeliveryNote, DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, + DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice, + DocumentKind.PurchaseCreditNote, DocumentKind.InventoryEntry, + ]; + + // The kinds whose costs are purchase costs: they move the average when the reason loads with value. + private static readonly HashSet Costing = + [DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice, DocumentKind.InventoryEntry]; + + /// Whether documents of a kind move the stock when their reason says so. + /// The kind. + /// Whether they do. + public static bool MovesStock(DocumentKind kind) => Moving.Contains(kind); + + /// Whether the open lines of a kind are committed to customers. + /// The kind. + /// Whether they are. + public static bool Commits(DocumentKind kind) => kind == DocumentKind.SalesOrder; + + /// Whether the open lines of a kind are ordered from suppliers. + /// The kind. + /// Whether they are. + public static bool Orders(DocumentKind kind) => kind == DocumentKind.PurchaseOrder; + + /// Whether a document in a state still holds quantities committed or ordered. + /// The state. + /// Whether it is open. + public static bool IsOpenOrder(DocumentStatus status) => status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled; + + /// The movements of a document. + /// The kind of the document. + /// Its warehouse reason. + /// The destination of a transfer. + /// The stocked lines. + /// The movements; none when the kind or the reason does not move the stock. + /// A transfer without a destination different from the origin. + public static IReadOnlyList Movements(DocumentKind kind, StockReason? reason, long? toWarehouseId, IEnumerable lines) + { + ArgumentNullException.ThrowIfNull(lines); + if (reason is null || !MovesStock(kind)) + { + return []; + } + + var result = new List(); + foreach (var line in lines.Where(l => l.Quantity != 0m)) + { + if (reason.IsTransfer) + { + if (toWarehouseId is not { } to || to == line.WarehouseId) + { + throw new InvalidOperationException("A transfer needs a destination warehouse different from the origin."); + } + + result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, -line.Quantity, false, 0m)); + result.Add(new StockMovement(line.LineId, line.ItemId, to, line.Quantity, false, 0m)); + continue; + } + + switch (reason.Effect) + { + case StockEffect.Load: + var valued = reason.AffectsValue && Costing.Contains(kind) && line.UnitCost is > 0m; + result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, line.Quantity, valued, valued ? line.UnitCost!.Value : 0m)); + break; + case StockEffect.Unload: + result.Add(new StockMovement(line.LineId, line.ItemId, line.WarehouseId, -line.Quantity, false, 0m)); + break; + } + } + + return result; + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/InventoryMaps.cs b/src/Khaemhat.Data/CompanyDatabase/InventoryMaps.cs new file mode 100644 index 0000000..20ada1d --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/InventoryMaps.cs @@ -0,0 +1,52 @@ +using Khaemhat.Core.Inventory; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to inventory_entries. +public sealed class InventoryEntryMap : EntityMap +{ + /// Creates the map. + public InventoryEntryMap() + { + ToTable("inventory_entries"); + Map(x => x.SourceNumber).MaxLength(30); + } +} + +/// Map of to inventory_entry_lines. +public sealed class InventoryEntryLineMap : EntityMap +{ + /// Creates the map. + public InventoryEntryLineMap() => ToTable("inventory_entry_lines"); +} + +/// Map of to item_balances. +public sealed class ItemBalanceMap : EntityMap +{ + /// Creates the map. + public ItemBalanceMap() => ToTable("item_balances"); +} + +/// Map of to stock_takes. +public sealed class StockTakeMap : EntityMap +{ + /// Creates the map. + public StockTakeMap() + { + ToTable("stock_takes"); + Map(x => x.Description).MaxLength(100); + Map(x => x.PostedBy).MaxLength(100); + } +} + +/// Map of to stock_take_lines. +public sealed class StockTakeLineMap : EntityMap +{ + /// Creates the map. + public StockTakeLineMap() + { + ToTable("stock_take_lines"); + Map(x => x.Notes).MaxLength(200); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs new file mode 100644 index 0000000..c9952b8 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_001_CreateInventory.cs @@ -0,0 +1,136 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// The warehouse (SPEC §11.6, ADR 0035, issues #59 and #60): the movements posted by the documents, the balance of +/// each item in each warehouse, the physical inventories; on the documents the destination of a transfer and the VAT +/// date of a supplier invoice (#56). Immediate invoices unload, supplier invoices load and supplier credit notes give +/// back, like the delivery notes: the reason of the document type decides it and can be removed. +/// +[Migration(20261113_001, "create_inventory")] +public sealed class M20261113_001_CreateInventory : IMigration +{ + private static readonly string[] Headers = + ["sale_quotations", "sale_orders", "sale_documents", "purchase_orders", "purchase_documents", "inventory_documents"]; + + // The reasons given to the document types of the base tables that had none (ItalianBaseTables has them from now on). + private static readonly (string Type, string Reason)[] Reasons = [("FI", "SCA"), ("FF", "CAR"), ("NCF", "RESF")]; + + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + foreach (var table in Headers) + { + schema.AlterTable(table, t => + { + t.Int64("to_warehouse_id"); + t.Date("vat_date"); + }); + } + + foreach (var (type, reason) in Reasons) + { + schema.Sql(_ => "UPDATE document_types SET inventory_reason_id = (SELECT r.id FROM inventory_reasons r WHERE r.code = '" + reason + + "') WHERE code = '" + type + "' AND inventory_reason_id IS NULL"); + } + + schema.CreateTable("inventory_entries", t => + { + t.Id(); + t.Date("entry_date").NotNull(); + t.String("source_family", 40); + t.Int64("source_document_id"); + t.String("source_kind", 40); + t.String("source_number", 30); + t.Int64("inventory_reason_id"); + t.Int64("party_id"); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_inventory_entries_source", "source_family", "source_document_id"); + t.Index("ix_inventory_entries_date", "entry_date"); + t.ForeignKey("fk_inventory_entries_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict); + }); + + schema.CreateTable("inventory_entry_lines", t => + { + t.Id(); + t.Int64("entry_id").NotNull(); + t.Date("entry_date").NotNull(); + t.Int64("item_id").NotNull(); + t.Int64("warehouse_id").NotNull(); + t.Decimal("quantity").NotNull(); + t.Bool("valued").NotNull().Default(false); + t.Decimal("unit_cost").NotNull().Default(0m); + t.Decimal("value").NotNull().Default(0m); + t.Int64("source_line_id"); + t.Int32("sort_order").NotNull().Default(0); + t.AuditColumns(); + t.Index("ix_inventory_entry_lines_entry", "entry_id"); + t.Index("ix_inventory_entry_lines_item", "item_id", "entry_date"); + t.Index("ix_inventory_entry_lines_warehouse", "warehouse_id", "item_id"); + t.ForeignKey("fk_inventory_entry_lines_entry", "entry_id", "inventory_entries", ReferentialAction.Cascade); + t.ForeignKey("fk_inventory_entry_lines_item", "item_id", "items", ReferentialAction.Restrict); + t.ForeignKey("fk_inventory_entry_lines_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + }); + + schema.CreateTable("item_balances", t => + { + t.Id(); + t.Int64("item_id").NotNull(); + t.Int64("warehouse_id").NotNull(); + t.Decimal("on_hand").NotNull().Default(0m); + t.Decimal("committed").NotNull().Default(0m); + t.Decimal("ordered").NotNull().Default(0m); + t.Decimal("in_transit").NotNull().Default(0m); + t.Decimal("average_cost").NotNull().Default(0m); + t.Decimal("value").NotNull().Default(0m); + t.Decimal("last_cost"); + t.Date("last_load_date"); + t.Date("last_unload_date"); + t.AuditColumns(); + t.Unique("ux_item_balances_item_warehouse", "item_id", "warehouse_id"); + t.Index("ix_item_balances_warehouse", "warehouse_id"); + t.ForeignKey("fk_item_balances_item", "item_id", "items", ReferentialAction.Cascade); + t.ForeignKey("fk_item_balances_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + }); + + schema.CreateTable("stock_takes", t => + { + t.Id(); + t.Date("take_date").NotNull(); + t.Int64("warehouse_id").NotNull(); + t.String("description", 100).NotNull(); + t.Int64("category_id"); + t.String("status", 40).NotNull(); + t.Int64("adjustment_document_id"); + t.Int64("loss_document_id"); + t.DateTimeUtc("posted_at"); + t.String("posted_by", 100); + t.Text("notes"); + t.DemoColumn(); + t.AuditColumns(); + t.Index("ix_stock_takes_date", "take_date"); + t.ForeignKey("fk_stock_takes_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + t.ForeignKey("fk_stock_takes_category", "category_id", "item_categories", ReferentialAction.Restrict); + }); + + schema.CreateTable("stock_take_lines", t => + { + t.Id(); + t.Int64("stock_take_id").NotNull(); + t.Int64("item_id").NotNull(); + t.Decimal("book_quantity").NotNull().Default(0m); + t.Decimal("counted_quantity"); + t.Decimal("unit_cost").NotNull().Default(0m); + t.String("notes", 200); + t.Int32("sort_order").NotNull().Default(0); + t.AuditColumns(); + t.Unique("ux_stock_take_lines_item", "stock_take_id", "item_id"); + t.ForeignKey("fk_stock_take_lines_take", "stock_take_id", "stock_takes", ReferentialAction.Cascade); + t.ForeignKey("fk_stock_take_lines_item", "item_id", "items", ReferentialAction.Restrict); + }); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs index 727d475..b9bb46c 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Features.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -273,3 +273,41 @@ public interface IPlaceDirectory /// The municipalities. IReadOnlyList Municipalities { get; } } + +/// What a received invoice tells about the self-invoice it may need. +/// The country of the supplier (ISO 3166-1 alpha-2). +/// The supplier is in another member state of the European Union. +/// The invoice is mostly for goods (otherwise services). +/// The VAT natures of its lines (codes of the country's e-invoice format), if any. +/// The day it was received or registered. +public sealed record SelfInvoiceCase(string SupplierCountry, bool SupplierInEu, bool Goods, IReadOnlyCollection Natures, DateOnly Received); + +/// The self-invoice a received invoice needs. +/// The document type of the base tables, such as AF17. +/// Why, in the language of the users. +/// The last day to issue it. +public sealed record SelfInvoiceAdvice(string DocumentTypeCode, string Reason, DateOnly Deadline); + +/// +/// The country's rules of self-invoices and integrations (Italy: TD16-TD29 under reverse charge, purchases from abroad, +/// regularisations): which type a received invoice needs, by when, and the VAT code that integrates it. +/// +public interface ISelfInvoiceRules +{ + /// The document types of self-invoices, in the order of the menu. + IReadOnlyList DocumentTypeCodes { get; } + + /// The VAT code (of the base tables) of the ordinary rate, proposed on the lines of an integration. + string OrdinaryTaxCode { get; } + + /// The self-invoice a received invoice needs, if any. + /// The invoice. + /// The advice, or when none is needed. + SelfInvoiceAdvice? Advise(SelfInvoiceCase input); + + /// The last day to issue a self-invoice of a type for an invoice received on a day. + /// The type. + /// The day the invoice was received (or the operation took place). + /// The deadline. + DateOnly Deadline(string documentTypeCode, DateOnly received); +} diff --git a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs new file mode 100644 index 0000000..6949382 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs @@ -0,0 +1,281 @@ +namespace Khaemhat.Fiscal.Abstractions; + +// The supplier invoices received as files of the country's e-invoice format (Italy: FatturaPA, also signed .p7m). +// The records keep the file as it is, with the codes of the format; the import service maps them to documents. + +/// +/// Reads the e-invoice files received from suppliers: an optional feature of a country pack, like +/// . The reader only reads: it never contacts a service and never resolves external +/// references. +/// +public interface IIncomingInvoiceReader +{ + /// + /// Whether the file looks like one the reader understands (Italy: .xml, .p7m in DER or as base64 + /// text). The content is sniffed, not only the name. + /// + /// The name of the file, extension included. + /// The content, or at least its first bytes. + /// when is worth trying. + bool CanRead(string fileName, ReadOnlySpan content); + + /// Reads a file. + /// The name of the file, extension included. + /// The whole content. + /// The file with its invoices. + /// The file is not readable, not an invoice, or misses mandatory data; + /// is one of . + IncomingInvoiceFile Read(string fileName, byte[] content); +} + +/// A received e-invoice file that cannot be read; is one of . +public sealed class IncomingInvoiceException : Exception +{ + /// Creates the exception. + public IncomingInvoiceException() + : this(IncomingInvoiceErrors.NotReadable, "The file is not readable.") + { + } + + /// Creates the exception. + /// What went wrong. + public IncomingInvoiceException(string message) + : this(IncomingInvoiceErrors.NotReadable, message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public IncomingInvoiceException(string message, Exception innerException) + : this(IncomingInvoiceErrors.NotReadable, message, innerException) + { + } + + /// Creates the exception with a code. + /// One of . + /// What went wrong. + public IncomingInvoiceException(string code, string message) + : base(message) => Code = code; + + /// Creates the exception with a code and its cause. + /// One of . + /// What went wrong. + /// The cause. + public IncomingInvoiceException(string code, string message, Exception? innerException) + : base(message, innerException) => Code = code; + + /// The text code of the error, one of . + public string Code { get; } +} + +/// The codes of . +public static class IncomingInvoiceErrors +{ + /// Neither XML nor a signed envelope: garbage, an empty file, a truncated download. + public const string NotReadable = "incoming.not-readable"; + + /// A well-formed XML document that is not an e-invoice. + public const string NotInvoice = "incoming.not-invoice"; + + /// A signed envelope whose content cannot be extracted. + public const string SignatureBroken = "incoming.signature-broken"; + + /// An e-invoice that misses mandatory data (date, number, document type...). + public const string Invalid = "incoming.invalid"; +} + +/// A received e-invoice file: the transmission header, the two parties and one or more invoices. +/// The name of the file as received. +/// The transmission format (Italy: FPR12, FPA12, FSM10). +/// The progressive number of the transmission given by the sender. +/// The recipient code of the transmission. +/// The supplier who issued the invoices. +/// The customer the invoices are addressed to (normally the company). +/// The invoices, one per body of the file (a batch has more than one). +/// The signature of the envelope, or for an unsigned file. +/// The XML of the invoice, taken out of the envelope when the file was signed. +public sealed record IncomingInvoiceFile( + string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode, + IncomingParty Supplier, IncomingParty Customer, IReadOnlyList Invoices, + IncomingSignature? Signature, byte[] Xml); + +/// +/// The signature of a signed file. says only that the content is intact and signed by the key +/// of the embedded certificate: the trust chain and the revocation of the certificate are not checked, because no +/// trusted list is available offline. +/// +/// Whether the digest and the signature match the content. +/// The name of the signer, from the certificate. +/// The tax code of the signer, when the certificate carries it. +/// The signing time declared by the signer, if any (not a trusted timestamp). +/// The start of validity of the certificate. +/// The end of validity of the certificate. +/// Why the signature is not verified, or . +public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt, + DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem); + +/// A party of the invoice (supplier or customer) as written in the file. +/// The country of the VAT number. +/// The VAT number without the country prefix. +/// The tax code. +/// The company name, when the party is a company. +/// The first name, when the party is a person. +/// The last name, when the party is a person. +/// The street of the registered office. +/// The street number. +/// The postal code. +/// The city. +/// The province. +/// The country of the registered office. +/// The tax regime (supplier only). +/// The e-mail address (supplier only). +/// The phone number (supplier only). +/// The office of the companies register. +/// The number in the companies register. +public sealed record IncomingParty( + string? CountryCode, string? VatNumber, string? TaxCode, string? Name, string? FirstName, string? LastName, + string? Address, string? StreetNumber, string? PostalCode, string? City, string? Province, string? Country, + string? TaxRegime, string? Email, string? Phone, string? ReaOffice, string? ReaNumber) +{ + /// The company name, or first and last name of a person. + public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s))); +} + +/// An invoice of the file (one body). +/// The document type (Italy: TD01, TD04...). +/// The currency code. +/// The date of the document. +/// The number of the document. +/// The total amount declared by the supplier, if any. +/// The rounding on the total, if any. +/// The free-text causals. +/// Whether the document is issued under the rule that allows several documents with the same +/// number in a year (Italy: art. 73 DPR 633/72). +/// The withholding taxes. +/// The stamp duty, if any. +/// The social security contributions. +/// The discounts and surcharges on the whole document. +/// The purchase orders referred to. +/// The contracts referred to. +/// The invoices referred to (the invoice a credit note corrects). +/// The delivery notes referred to. +/// The lines. +/// The tax summary, one row per rate or nature. +/// The payment installments. +/// The attached files. +public sealed record IncomingInvoice( + string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding, + IReadOnlyList Causals, bool Art73, + IReadOnlyList Withholdings, IncomingStampDuty? StampDuty, + IReadOnlyList SocialSecurity, IReadOnlyList Discounts, + IReadOnlyList Orders, IReadOnlyList Contracts, + IReadOnlyList RelatedInvoices, IReadOnlyList DeliveryNotes, + IReadOnlyList Lines, IReadOnlyList TaxSummary, + IReadOnlyList Payments, IReadOnlyList Attachments); + +/// A line of an invoice. +/// The line number. +/// The item codes (type and value). +/// The description. +/// The quantity, if given. +/// The unit of measure, if given. +/// The unit price. +/// The total of the line, net of tax. +/// The tax rate in percent (zero with a nature). +/// The reason of a zero rate (Italy: N2.2...). +/// The discounts and surcharges of the line. +/// Whether the line is subject to withholding tax. +/// The kind of line (Italy: SC discount, PR premium, AB rebate, +/// AC ancillary cost). +/// The start of the period the line refers to. +/// The end of the period the line refers to. +/// The administrative reference (cost centre, internal code). +public sealed record IncomingLine( + int Number, IReadOnlyList Codes, string Description, decimal? Quantity, string? Unit, + decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList Discounts, + bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference); + +/// A code of the item of a line. +/// The kind of code (EAN, SKU, the supplier's code...). +/// The code. +public sealed record IncomingItemCode(string Type, string Value); + +/// A discount or surcharge. +/// Whether it is a surcharge (Italy: MG) instead of a discount (SC). +/// The percentage, if given. +/// The amount, if given. +public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount); + +/// A row of the tax summary. +/// The tax rate in percent. +/// The reason of a zero rate. +/// The taxable amount. +/// The tax. +/// When the tax is due (Italy: I immediate, D deferred, S split payment). +/// The law that justifies the nature. +/// Ancillary expenses, if any. +/// The rounding, if any. +public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility, + string? LegalReference, decimal? ExpensesAmount, decimal? Rounding); + +/// A payment installment. +/// The payment conditions (Italy: TP01 installments, TP02 full, TP03 advance). +/// The payment method (Italy: MP05 bank transfer...). +/// The due date, if given. +/// The amount. +/// The IBAN to pay to, if given. +/// The BIC, if given. +/// The beneficiary, if different from the supplier. +public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount, + string? Iban, string? Bic, string? Beneficiary); + +/// A reference to another document (order, contract, invoice, delivery note). +/// The number of the document. +/// The date of the document. +/// The lines of the invoice the reference applies to; empty when it applies to all. +/// The tender code, if any (public administration). +/// The project code, if any (public administration). +public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList LineNumbers, string? Cig, string? Cup); + +/// A withholding tax. +/// The kind of withholding (Italy: RT01...). +/// The amount withheld. +/// The rate in percent. +/// The payment reason (Italy: A...), if given. +public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason); + +/// The stamp duty of an invoice. +/// Whether it is paid virtually by the issuer. +/// The amount. +public sealed record IncomingStampDuty(bool Virtual, decimal Amount); + +/// A social security contribution added to the invoice. +/// The fund (Italy: TC01...). +/// The rate of the contribution in percent. +/// The amount of the contribution. +/// The amount the contribution is computed on, if given. +/// The tax rate applied to the contribution. +/// Whether the contribution is subject to withholding tax. +/// The reason of a zero tax rate. +public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate, + bool Withheld, string? Nature); + +/// A file attached to the invoice. +/// The name of the attachment. +/// The format declared by the supplier (such as PDF), if any. +/// The description, if any. +/// The decoded content. +public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content); + +/// +/// How a received e-invoice becomes a document of the company: which document type registers each type of the format +/// (Italy: TD01 and the like as supplier invoice FF, TD04 and TD08 as supplier credit note NCF). +/// +public interface IIncomingInvoiceRules +{ + /// The code of the document type that registers an invoice of this type of the format. + /// The type in the file (TD01...). + /// The document type code, or none when the type is not registered as a purchase (a self-invoice). + string? DocumentTypeCode(string formatType); +} diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs new file mode 100644 index 0000000..9775730 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs @@ -0,0 +1,517 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Reads the FatturaPA files received from suppliers (SPEC §11.9, issue #57): ordinary invoices v1.2.x +/// (FPR12, FPA12), simplified invoices (FSM10), plain .xml or signed CAdES .p7m +/// (binary or base64 text, also nested). +/// +/// +/// Elements are matched by local name, whatever the namespace or prefix (p:, ns2:, none). The XML +/// is read with DTDs prohibited and no resolver, so nothing external is ever loaded. A UTF-8 byte order mark, a +/// missing XML declaration, an ISO-8859-1 or windows-1252 declaration and leading whitespace are tolerated. +/// Amounts use the invariant culture (. separator) and dates yyyy-MM-dd. The reader does not +/// validate the file against the XSD nor recompute totals: it reports what the supplier wrote and rejects only files +/// without the data an import cannot do without (document type, date, number, prices and rates of the lines, the +/// rows of the tax summary, the amounts of withholdings and payments). A missing Divisa is read as +/// EUR; an attachment whose content is not valid base64 is kept with an empty content. +/// For signed files the signature is checked for integrity only (see ): no trust chain +/// and no revocation check. +/// Simplified invoices (FSM10): each DatiBeniServizi becomes a line with no quantity whose unit and +/// total price are Importo minus the tax, because there Importo includes the tax. The tax is +/// DatiIVA/Imposta or, when only the rate is given, the tax included in Importo at that rate; the rate is +/// DatiIVA/Aliquota or, when only the tax is given, derived from it. The tax summary groups the lines by rate and +/// nature, the total is the sum of Importo and DatiFatturaRettificata becomes the related invoice. +/// +public sealed class FatturaPaReader : IIncomingInvoiceReader +{ + /// The largest file read, as for signed envelopes (50 MB). + public const int MaxSize = CmsSignedData.MaxSize; + + /// + public bool CanRead(string fileName, ReadOnlySpan content) => + !content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content)); + + /// + public IncomingInvoiceFile Read(string fileName, byte[] content) + { + ArgumentNullException.ThrowIfNull(fileName); + ArgumentNullException.ThrowIfNull(content); + if (content.Length == 0) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is empty."); + } + + if (content.Length > MaxSize) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, $"The file is larger than {MaxSize / (1024 * 1024)} MB."); + } + + IncomingSignature? signature = null; + var xml = content; + if (!LooksLikeXml(content) && CmsSignedData.LooksLikeCms(content)) + { + CmsContent envelope; + try + { + envelope = CmsSignedData.Read(content); + } + catch (CmsFormatException ex) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.SignatureBroken, "The content of the signed file cannot be extracted: " + ex.Message, ex); + } + + xml = envelope.Content; + var signer = envelope.Signer; + signature = new IncomingSignature( + envelope.Verified, signer?.Name, signer?.TaxCode, signer?.SigningTime, + signer?.CertificateNotBefore, signer?.CertificateNotAfter, envelope.Problem); + } + + if (!LooksLikeXml(xml)) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is neither XML nor a signed envelope."); + } + + var root = Parse(xml).Root + ?? throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML has no root element."); + return root.Name.LocalName switch + { + "FatturaElettronica" => ReadOrdinary(fileName, root, signature, xml), + "FatturaElettronicaSemplificata" => ReadSimplified(fileName, root, signature, xml), + _ => throw new IncomingInvoiceException(IncomingInvoiceErrors.NotInvoice, $"The XML is a '{root.Name.LocalName}', not an electronic invoice."), + }; + } + + // --- XML ------------------------------------------------------------------------------------------------------- + + private static bool LooksLikeXml(ReadOnlySpan content) + { + if (content.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + content = content[3..]; + } + else if (content.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || content.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + { + return true; + } + + var trimmed = content.TrimStart((ReadOnlySpan)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']); + return !trimmed.IsEmpty && trimmed[0] == (byte)'<'; + } + + private static XDocument Parse(byte[] xml) + { + var text = Decode(xml).TrimStart('', ' ', '\t', '\r', '\n'); + var settings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + }; + try + { + using var reader = XmlReader.Create(new StringReader(text), settings); + return XDocument.Load(reader); + } + catch (XmlException ex) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML is not well formed: " + ex.Message, ex); + } + } + + // The text is decoded here, then read from a string: the encoding of the declaration is honoured without the + // reader having to know code pages (windows-1252 is common in files written by older programs). + private static string Decode(byte[] xml) + { + if (xml.AsSpan().StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + return new UTF8Encoding(false).GetString(xml, 3, xml.Length - 3); + } + + if (xml.AsSpan().StartsWith((ReadOnlySpan)[0xFF, 0xFE])) + { + return Encoding.Unicode.GetString(xml, 2, xml.Length - 2); + } + + if (xml.AsSpan().StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + { + return Encoding.BigEndianUnicode.GetString(xml, 2, xml.Length - 2); + } + + return EncodingOfDeclaration(xml).GetString(xml); + } + + private static Encoding EncodingOfDeclaration(byte[] xml) + { + var head = Encoding.ASCII.GetString(xml, 0, Math.Min(xml.Length, 256)); + var start = head.IndexOf("", start, StringComparison.Ordinal); + if (end < 0) + { + return new UTF8Encoding(false); + } + + var declaration = head[start..end]; + var at = declaration.IndexOf("encoding", StringComparison.OrdinalIgnoreCase); + if (at < 0) + { + return new UTF8Encoding(false); + } + + var quote = declaration.IndexOfAny(['"', '\''], at); + var close = quote < 0 ? -1 : declaration.IndexOf(declaration[quote], quote + 1); + if (close < 0) + { + return new UTF8Encoding(false); + } + + var name = declaration[(quote + 1)..close].Trim().ToUpperInvariant(); + return name switch + { + "UTF-8" or "UTF8" => new UTF8Encoding(false), + "ISO-8859-1" or "LATIN1" or "ISO8859-1" => Encoding.Latin1, + "WINDOWS-1252" or "CP1252" => CodePage(1252), + "ISO-8859-15" => CodePage(28605), + _ => new UTF8Encoding(false), + }; + } + + private static Encoding CodePage(int codePage) => + CodePagesEncodingProvider.Instance.GetEncoding(codePage) ?? Encoding.Latin1; + + // --- Ordinary invoice -------------------------------------------------------------------------------------------- + + private static IncomingInvoiceFile ReadOrdinary(string fileName, XElement root, IncomingSignature? signature, byte[] xml) + { + var header = El(root, "FatturaElettronicaHeader") + ?? throw Invalid("The invoice has no FatturaElettronicaHeader."); + var transmission = El(header, "DatiTrasmissione"); + var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore."); + var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente."); + var bodies = Els(root, "FatturaElettronicaBody").ToList(); + if (bodies.Count == 0) + { + throw Invalid("The invoice has no FatturaElettronicaBody."); + } + + return new IncomingInvoiceFile( + fileName, + Text(transmission, "FormatoTrasmissione"), + Text(transmission, "ProgressivoInvio"), + Text(transmission, "CodiceDestinatario"), + ReadParty(supplier), + ReadParty(customer), + bodies.Select(ReadBody).ToList(), + signature, + xml); + } + + private static IncomingParty ReadParty(XElement party) + { + var personal = El(party, "DatiAnagrafici"); + var identifiers = El(party, "IdentificativiFiscali"); + var others = El(party, "AltriDatiIdentificativi"); + var vat = El(personal, "IdFiscaleIVA") ?? El(identifiers, "IdFiscaleIVA") ?? El(party, "IdFiscaleIVA"); + var names = El(personal, "Anagrafica") ?? others ?? party; + var office = El(party, "Sede") ?? El(others, "Sede"); + var register = El(party, "IscrizioneREA"); + var contacts = El(party, "Contatti"); + return new IncomingParty( + Text(vat, "IdPaese"), + Text(vat, "IdCodice"), + Text(personal, "CodiceFiscale") ?? Text(identifiers, "CodiceFiscale") ?? Text(party, "CodiceFiscale"), + Text(names, "Denominazione"), + Text(names, "Nome"), + Text(names, "Cognome"), + Text(office, "Indirizzo"), + Text(office, "NumeroCivico"), + Text(office, "CAP"), + Text(office, "Comune"), + Text(office, "Provincia"), + Text(office, "Nazione"), + Text(personal, "RegimeFiscale") ?? Text(party, "RegimeFiscale"), + Text(contacts, "Email"), + Text(contacts, "Telefono"), + Text(register, "Ufficio"), + Text(register, "NumeroREA")); + } + + private static IncomingInvoice ReadBody(XElement body, int index) + { + var general = El(body, "DatiGenerali"); + var document = El(general, "DatiGeneraliDocumento") + ?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento."); + var goods = El(body, "DatiBeniServizi"); + var stamp = El(document, "DatiBollo"); + + return new IncomingInvoice( + Required(document, "TipoDocumento", index), + Text(document, "Divisa") ?? "EUR", + RequiredDate(document, "Data", index), + Required(document, "Numero", index), + OptionalDecimal(document, "ImportoTotaleDocumento"), + OptionalDecimal(document, "Arrotondamento"), + Els(document, "Causale").Select(c => c.Value.Trim()).Where(c => c.Length > 0).ToList(), + Flag(document, "Art73"), + Els(document, "DatiRitenuta").Select(w => new IncomingWithholding( + Required(w, "TipoRitenuta", index), + RequiredDecimal(w, "ImportoRitenuta", index), + RequiredDecimal(w, "AliquotaRitenuta", index), + Text(w, "CausalePagamento"))).ToList(), + stamp is null ? null : new IncomingStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m), + Els(document, "DatiCassaPrevidenziale").Select(s => new IncomingSocialSecurity( + Required(s, "TipoCassa", index), + RequiredDecimal(s, "AlCassa", index), + RequiredDecimal(s, "ImportoContributoCassa", index), + OptionalDecimal(s, "ImponibileCassa"), + RequiredDecimal(s, "AliquotaIVA", index), + Flag(s, "Ritenuta"), + Text(s, "Natura"))).ToList(), + ReadDiscounts(document), + ReadReferences(general, "DatiOrdineAcquisto"), + ReadReferences(general, "DatiContratto"), + ReadReferences(general, "DatiFattureCollegate"), + Els(general, "DatiDDT").Select(d => new IncomingReference( + Text(d, "NumeroDDT"), OptionalDate(d, "DataDDT"), LineNumbers(d), null, null)).ToList(), + Els(goods, "DettaglioLinee").Select((l, i) => ReadLine(l, i, index)).ToList(), + Els(goods, "DatiRiepilogo").Select(r => new IncomingTaxSummary( + RequiredDecimal(r, "AliquotaIVA", index), + Text(r, "Natura"), + RequiredDecimal(r, "ImponibileImporto", index), + RequiredDecimal(r, "Imposta", index), + Text(r, "EsigibilitaIVA"), + Text(r, "RiferimentoNormativo"), + OptionalDecimal(r, "SpeseAccessorie"), + OptionalDecimal(r, "Arrotondamento"))).ToList(), + ReadPayments(body, index), + ReadAttachments(body)); + } + + private static IncomingLine ReadLine(XElement line, int position, int index) => new( + OptionalInt(line, "NumeroLinea") ?? position + 1, + Els(line, "CodiceArticolo") + .Select(c => new IncomingItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty)) + .Where(c => c.Value.Length > 0) + .ToList(), + Text(line, "Descrizione") ?? string.Empty, + OptionalDecimal(line, "Quantita"), + Text(line, "UnitaMisura"), + RequiredDecimal(line, "PrezzoUnitario", index), + RequiredDecimal(line, "PrezzoTotale", index), + RequiredDecimal(line, "AliquotaIVA", index), + Text(line, "Natura"), + ReadDiscounts(line), + Flag(line, "Ritenuta"), + Text(line, "TipoCessionePrestazione"), + OptionalDate(line, "DataInizioPeriodo"), + OptionalDate(line, "DataFinePeriodo"), + Text(line, "RiferimentoAmministrazione")); + + private static List ReadDiscounts(XElement? parent) => + Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount( + string.Equals(Text(d, "Tipo"), "MG", StringComparison.OrdinalIgnoreCase), + OptionalDecimal(d, "Percentuale"), + OptionalDecimal(d, "Importo"))).ToList(); + + private static List ReadReferences(XElement? general, string name) => + Els(general, name).Select(r => new IncomingReference( + Text(r, "IdDocumento"), OptionalDate(r, "Data"), LineNumbers(r), Text(r, "CodiceCIG"), Text(r, "CodiceCUP"))).ToList(); + + private static List LineNumbers(XElement reference) => + Els(reference, "RiferimentoNumeroLinea") + .Select(n => int.TryParse(n.Value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : 0) + .Where(n => n > 0) + .ToList(); + + private static List ReadPayments(XElement body, int index) => + Els(body, "DatiPagamento").SelectMany(p => + { + var conditions = Text(p, "CondizioniPagamento"); + return Els(p, "DettaglioPagamento").Select(d => new IncomingPayment( + conditions, + Text(d, "ModalitaPagamento"), + OptionalDate(d, "DataScadenzaPagamento"), + RequiredDecimal(d, "ImportoPagamento", index), + Text(d, "IBAN"), + Text(d, "BIC"), + Text(d, "Beneficiario"))); + }).ToList(); + + private static List ReadAttachments(XElement body) => + Els(body, "Allegati").Select(a => new IncomingAttachment( + Text(a, "NomeAttachment") ?? "allegato", + Text(a, "FormatoAttachment"), + Text(a, "DescrizioneAttachment"), + DecodeAttachment(El(a, "Attachment")?.Value))).ToList(); + + private static byte[] DecodeAttachment(string? base64) + { + if (string.IsNullOrWhiteSpace(base64)) + { + return []; + } + + var compact = new StringBuilder(base64.Length); + foreach (var c in base64) + { + if (!char.IsWhiteSpace(c)) + { + compact.Append(c); + } + } + + var text = compact.ToString(); + var buffer = new byte[text.Length / 4 * 3 + 3]; + return Convert.TryFromBase64String(text, buffer, out var written) ? buffer[..written] : []; + } + + // --- Simplified invoice ------------------------------------------------------------------------------------------ + + private static IncomingInvoiceFile ReadSimplified(string fileName, XElement root, IncomingSignature? signature, byte[] xml) + { + var header = El(root, "FatturaElettronicaHeader") + ?? throw Invalid("The invoice has no FatturaElettronicaHeader."); + var transmission = El(header, "DatiTrasmissione"); + var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore."); + var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente."); + var bodies = Els(root, "FatturaElettronicaBody").ToList(); + if (bodies.Count == 0) + { + throw Invalid("The invoice has no FatturaElettronicaBody."); + } + + return new IncomingInvoiceFile( + fileName, + Text(transmission, "FormatoTrasmissione"), + Text(transmission, "ProgressivoInvio"), + Text(transmission, "CodiceDestinatario"), + ReadParty(supplier), + ReadParty(customer), + bodies.Select(ReadSimplifiedBody).ToList(), + signature, + xml); + } + + private static IncomingInvoice ReadSimplifiedBody(XElement body, int index) + { + var general = El(body, "DatiGenerali"); + var document = El(general, "DatiGeneraliDocumento") + ?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento."); + var lines = Els(body, "DatiBeniServizi").Select((l, i) => ReadSimplifiedLine(l, i, index)).ToList(); + var gross = Els(body, "DatiBeniServizi").Sum(l => RequiredDecimal(l, "Importo", index)); + var summary = lines + .GroupBy(l => (l.TaxRate, l.Nature)) + .Select(g => new IncomingTaxSummary( + g.Key.TaxRate, g.Key.Nature, g.Sum(l => l.TotalPrice), g.Sum(l => l.Tax), null, + g.Select(l => l.LegalReference).FirstOrDefault(r => r is not null), null, null)) + .ToList(); + var corrected = Els(general, "DatiFatturaRettificata") + .Select(r => new IncomingReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null)) + .ToList(); + + return new IncomingInvoice( + Required(document, "TipoDocumento", index), + Text(document, "Divisa") ?? "EUR", + RequiredDate(document, "Data", index), + Required(document, "Numero", index), + gross, + null, + [], + false, + [], + Flag(document, "BolloVirtuale") ? new IncomingStampDuty(true, 0m) : null, + [], + [], + [], + [], + corrected, + [], + lines.Select(l => l.Line).ToList(), + summary, + [], + ReadAttachments(body)); + } + + private static SimplifiedLine ReadSimplifiedLine(XElement line, int position, int index) + { + var gross = RequiredDecimal(line, "Importo", index); + var vat = El(line, "DatiIVA"); + var tax = OptionalDecimal(vat, "Imposta"); + var rate = OptionalDecimal(vat, "Aliquota"); + tax ??= rate is { } r && r != 0m ? Math.Round(gross * r / (100m + r), 2, MidpointRounding.AwayFromZero) : 0m; + var net = gross - tax.Value; + rate ??= net != 0m ? Math.Round(tax.Value / net * 100m, 2, MidpointRounding.AwayFromZero) : 0m; + var nature = Text(line, "Natura"); + return new SimplifiedLine( + new IncomingLine(position + 1, [], Text(line, "Descrizione") ?? string.Empty, null, null, net, net, rate.Value, nature, + [], false, null, null, null, null), + tax.Value, + Text(line, "RiferimentoNormativo")); + } + + private sealed record SimplifiedLine(IncomingLine Line, decimal Tax, string? LegalReference) + { + public decimal TaxRate => Line.TaxRate; + + public string? Nature => Line.Nature; + + public decimal TotalPrice => Line.TotalPrice; + } + + // --- Helpers ----------------------------------------------------------------------------------------------------- + + private static XElement? El(XElement? parent, string localName) => + parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName); + + private static IEnumerable Els(XElement? parent, string localName) => + parent is null ? [] : parent.Elements().Where(e => e.Name.LocalName == localName); + + private static string? Text(XElement? parent, string localName) + { + var value = El(parent, localName)?.Value.Trim(); + return string.IsNullOrEmpty(value) ? null : value; + } + + private static bool Flag(XElement? parent, string localName) => + string.Equals(Text(parent, localName), "SI", StringComparison.OrdinalIgnoreCase); + + private static string Required(XElement parent, string localName, int index) => + Text(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing."); + + private static decimal? OptionalDecimal(XElement? parent, string localName) => + Text(parent, localName) is { } text && decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value) + ? value + : null; + + private static decimal RequiredDecimal(XElement parent, string localName, int index) => + OptionalDecimal(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a number."); + + private static int? OptionalInt(XElement parent, string localName) => + Text(parent, localName) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null; + + private static DateOnly? OptionalDate(XElement? parent, string localName) + { + var text = Text(parent, localName); + if (text is null) + { + return null; + } + + // xs:date may carry a time zone (2026-03-15+01:00): the day is what counts. + var day = text.Length > 10 ? text[..10] : text; + return DateOnly.TryParseExact(day, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) ? date : null; + } + + private static DateOnly RequiredDate(XElement parent, string localName, int index) => + OptionalDate(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a date."); + + private static IncomingInvoiceException Invalid(string message) => new(IncomingInvoiceErrors.Invalid, message); +} diff --git a/src/Khaemhat.Fiscal.Italy/IncomingInvoiceRulesIt.cs b/src/Khaemhat.Fiscal.Italy/IncomingInvoiceRulesIt.cs new file mode 100644 index 0000000..b82fb56 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/IncomingInvoiceRulesIt.cs @@ -0,0 +1,22 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The types of a received FatturaPA and the purchase document that registers them: invoices, deposits, fee notes, +/// debit notes and deferred invoices (TD01, TD02, TD03, TD05, TD06, TD24, TD25, TD26, TD27) as supplier invoice FF, +/// credit notes (TD04, TD08) as supplier credit note NCF. The self-invoice types TD16-TD23, TD28 and TD29 are issued by +/// the company itself and are not purchases. +/// +public sealed class IncomingInvoiceRulesIt : IIncomingInvoiceRules +{ + private static readonly HashSet Invoices = new(StringComparer.Ordinal) { "TD01", "TD02", "TD03", "TD05", "TD06", "TD24", "TD25", "TD26", "TD27" }; + private static readonly HashSet CreditNotes = new(StringComparer.Ordinal) { "TD04", "TD08" }; + + /// + public string? DocumentTypeCode(string formatType) + { + var type = formatType?.Trim().ToUpperInvariant() ?? string.Empty; + return Invoices.Contains(type) ? "FF" : CreditNotes.Contains(type) ? "NCF" : null; + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs index e015538..9f9c379 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs @@ -50,7 +50,7 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null, DocumentKind.Quotation), new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null, DocumentKind.SalesOrder), new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null, DocumentKind.DeliveryNote), - new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01", DocumentKind.ImmediateInvoice), + new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.ImmediateInvoice), new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.AccompanyingInvoice), new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24", DocumentKind.DeferredInvoice), new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02", DocumentKind.DownPaymentInvoice), @@ -62,10 +62,16 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17", DocumentKind.SelfInvoice), new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18", DocumentKind.SelfInvoice), new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19", DocumentKind.SelfInvoice), + new("AF20", "Autofattura per regolarizzazione", NumeratorKind.SalesInvoice, "AUT", null, "TD20", DocumentKind.SelfInvoice), + new("AF21", "Autofattura per splafonamento", NumeratorKind.SalesInvoice, "AUT", null, "TD21", DocumentKind.SelfInvoice), + new("AF22", "Estrazione beni da deposito IVA", NumeratorKind.SalesInvoice, "AUT", null, "TD22", DocumentKind.SelfInvoice), + new("AF23", "Estrazione beni da deposito IVA con versamento", NumeratorKind.SalesInvoice, "AUT", null, "TD23", DocumentKind.SelfInvoice), + new("AF28", "Acquisti da San Marino con IVA", NumeratorKind.SalesInvoice, "AUT", null, "TD28", DocumentKind.SelfInvoice), + new("AF29", "Comunicazione per omessa o irregolare fatturazione", NumeratorKind.SalesInvoice, "AUT", null, "TD29", DocumentKind.SelfInvoice), new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null, DocumentKind.PurchaseOrder), new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null, DocumentKind.PurchaseDeliveryNote), - new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseInvoice), - new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseCreditNote), + new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", "CAR", null, DocumentKind.PurchaseInvoice), + new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", "RESF", null, DocumentKind.PurchaseCreditNote), new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null, DocumentKind.InventoryEntry), ]; } diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index ab9137c..4289fa3 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -15,6 +15,9 @@ public sealed class ItalyFiscalPack : FiscalPackBase public ItalyFiscalPack() { AddFeature(new FatturaPaFormat()); + AddFeature(new FatturaPaReader()); + AddFeature(new IncomingInvoiceRulesIt()); + AddFeature(new SelfInvoiceRulesIt()); AddFeature(new WithholdingRulesIt()); AddFeature(new FixedAssetRulesIt()); AddFeature(new F24Exporter()); diff --git a/src/Khaemhat.Fiscal.Italy/SelfInvoiceRulesIt.cs b/src/Khaemhat.Fiscal.Italy/SelfInvoiceRulesIt.cs new file mode 100644 index 0000000..2807dfa --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/SelfInvoiceRulesIt.cs @@ -0,0 +1,59 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Italian self-invoices and integrations (provvedimento AdE 99922/2020, specifiche FatturaPA 1.9): TD16 integrates a +/// domestic reverse charge (natures N6.x), TD17 the purchase of services from abroad, TD18 of goods from another member +/// state, TD19 of goods located in Italy from a non-resident (art. 17 c.2). Integrations go to the exchange system by +/// the 15th of the month after the receipt; regularisations (TD20) and communications (TD29) within 90 days. +/// +public sealed class SelfInvoiceRulesIt : ISelfInvoiceRules +{ + /// + public IReadOnlyList DocumentTypeCodes { get; } = ["AF16", "AF17", "AF18", "AF19", "AF20", "AF21", "AF22", "AF23", "AF28", "AF29"]; + + /// + public string OrdinaryTaxCode => "22"; + + /// + public SelfInvoiceAdvice? Advise(SelfInvoiceCase input) + { + ArgumentNullException.ThrowIfNull(input); + var domestic = string.Equals(input.SupplierCountry, "IT", StringComparison.OrdinalIgnoreCase); + if (domestic) + { + if (input.Natures.Any(n => n.StartsWith("N6", StringComparison.Ordinal))) + { + return Advice("AF16", "Inversione contabile interna (art. 17 c.6 e 74 c.7-8 DPR 633/72): integrazione della fattura del fornitore.", input.Received); + } + + return null; + } + + if (string.Equals(input.SupplierCountry, "SM", StringComparison.OrdinalIgnoreCase)) + { + return input.Natures.Count == 0 + ? Advice("AF28", "Acquisto da San Marino con IVA addebitata in fattura.", input.Received) + : null; + } + + if (!input.Goods) + { + return Advice("AF17", "Acquisto di servizi da un fornitore estero (art. 17 c.2 e 7-ter DPR 633/72).", input.Received); + } + + return input.SupplierInEu + ? Advice("AF18", "Acquisto intracomunitario di beni (art. 46-47 DL 331/93).", input.Received) + : Advice("AF19", "Acquisto di beni già in Italia da un soggetto non residente (art. 17 c.2 DPR 633/72).", input.Received); + } + + /// + public DateOnly Deadline(string documentTypeCode, DateOnly received) => documentTypeCode switch + { + "AF20" or "AF29" => received.AddDays(90), + _ => new DateOnly(received.Year, received.Month, 15).AddMonths(1), + }; + + private SelfInvoiceAdvice Advice(string code, string reason, DateOnly received) => new(code, reason, Deadline(code, received)); +} diff --git a/src/Khaemhat.Infrastructure/Security/CmsSignedData.cs b/src/Khaemhat.Infrastructure/Security/CmsSignedData.cs new file mode 100644 index 0000000..aed701b --- /dev/null +++ b/src/Khaemhat.Infrastructure/Security/CmsSignedData.cs @@ -0,0 +1,756 @@ +using System.Buffers.Text; +using System.Formats.Asn1; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Khaemhat.Infrastructure.Security; + +/// A structure that is not a readable CMS SignedData, or whose content cannot be extracted. +public sealed class CmsFormatException : Exception +{ + /// Creates the exception. + public CmsFormatException() + : base("Not a CMS SignedData structure.") + { + } + + /// Creates the exception. + /// What went wrong. + public CmsFormatException(string message) + : base(message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public CmsFormatException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// A signer of a CMS SignedData with what its certificate says and the result of the check. +/// The name of the signer: common name, else given name and surname, else organization, else +/// serial number of the subject. +/// The tax code of the signer, from the subject's SERIALNUMBER (OID 2.5.4.5) without +/// the TINIT- or IT: prefix, when present. +/// The subject of the certificate, or when it was not found. +/// The issuer of the certificate, or when it was not found. +/// The start of validity of the certificate. +/// The end of validity of the certificate. +/// The signingTime signed attribute: what the signer's clock said, not a trusted timestamp. +/// Whether the digest of the content and the signature match. +/// Why the signature is not verified, or . +/// The DER of the signer certificate, or when it was not found. +public sealed record CmsSigner( + string? Name, string? TaxCode, string? Subject, string? Issuer, + DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, DateTimeOffset? SigningTime, + bool Verified, string? Problem, byte[]? Certificate); + +/// The content of one or more nested CMS SignedData envelopes and their signers. +/// The content of the innermost envelope. +/// The signers, outermost envelope first. +/// How many envelopes were opened (two for .xml.p7m.p7m). +public sealed record CmsContent(byte[] Content, IReadOnlyList Signers, int Layers) +{ + /// Whether there is at least one signer and every signer of every envelope is verified. + public bool Verified => Signers.Count > 0 && Signers.All(s => s.Verified); + + /// The first problem found, or when . + public string? Problem => Signers.Count == 0 ? "The envelope has no signer." : Signers.FirstOrDefault(s => s.Problem is not null)?.Problem; + + /// The signer of the outermost envelope, or when there is none. + public CmsSigner? Signer => Signers.Count > 0 ? Signers[0] : null; +} + +/// +/// A minimal reader of CMS SignedData (RFC 5652, PKCS #7), the envelope of CAdES signed files such as .p7m, +/// written on System.Formats.Asn1 because System.Security.Cryptography.Pkcs is a separate package +/// (SPEC §1.2). +/// +/// +/// It accepts DER and BER (indefinite lengths, content split in constructed chunks), the base64 text of the +/// binary with or without line breaks and -----BEGIN armour, and nested envelopes (.p7m.p7m), opened +/// until the content is no longer CMS. +/// It checks integrity only: the messageDigest attribute against the content (SHA-1, SHA-256, SHA-384, +/// SHA-512) and the signature with the public key of the embedded signer certificate (RSA PKCS #1 v1.5, RSA-PSS with +/// the salt as long as the hash, ECDSA). It does not check the trust chain, the qualified status of the +/// certificate or its revocation, because no trusted list is available offline; it never follows external +/// references. A broken signature still returns the content, with false and the +/// problem; only unreadable structures throw . Detached signatures (no content) are +/// not supported. +/// +public static class CmsSignedData +{ + /// The largest envelope read, 50 MB. + public const int MaxSize = 50 * 1024 * 1024; + + /// The most nested envelopes opened. + public const int MaxLayers = 8; + + private const string SignedDataOid = "1.2.840.113549.1.7.2"; + private const string ContentTypeAttributeOid = "1.2.840.113549.1.9.3"; + private const string MessageDigestAttributeOid = "1.2.840.113549.1.9.4"; + private const string SigningTimeAttributeOid = "1.2.840.113549.1.9.5"; + private const string RsaEncryptionOid = "1.2.840.113549.1.1.1"; + private const string RsaPssOid = "1.2.840.113549.1.1.10"; + private const string EcPublicKeyOid = "1.2.840.10045.2.1"; + + // DER of OBJECT IDENTIFIER 1.2.840.113549.1.7.2 (signedData): what follows the header of the outer SEQUENCE. + private static readonly byte[] SignedDataOidDer = [0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02]; + + private static readonly Asn1Tag Context0 = new(TagClass.ContextSpecific, 0); + private static readonly Asn1Tag Context0Constructed = new(TagClass.ContextSpecific, 0, isConstructed: true); + private static readonly Asn1Tag Context1 = new(TagClass.ContextSpecific, 1); + + /// Whether the bytes look like a CMS SignedData, in binary or as base64 text. Only the start is looked at. + /// The content, or at least its first hundred bytes. + /// when is worth trying. + public static bool LooksLikeCms(ReadOnlySpan data) + { + if (LooksLikeBinaryCms(data)) + { + return true; + } + + // Base64 text: decode the first characters and look again. + Span chars = stackalloc byte[96]; + var count = 0; + foreach (var b in SkipArmour(SkipBom(data))) + { + if (IsBase64Whitespace(b)) + { + continue; + } + + if (!IsBase64Char(b)) + { + break; + } + + chars[count++] = b; + if (count == chars.Length) + { + break; + } + } + + count -= count % 4; + if (count < 24) + { + return false; + } + + Span decoded = stackalloc byte[72]; + var status = Base64.DecodeFromUtf8(chars[..count], decoded, out _, out var written, isFinalBlock: false); + return status is System.Buffers.OperationStatus.Done or System.Buffers.OperationStatus.NeedMoreData + && LooksLikeBinaryCms(decoded[..written]); + } + + /// + /// Opens a CMS SignedData and every envelope nested inside it, and checks the signatures. Accepts DER, BER and + /// base64 text (see the remarks of the class). + /// + /// The envelope. + /// The content of the innermost envelope and the signers. + /// The data is not a CMS SignedData, is too large, nests too deep, has no + /// content, or cannot be decoded. + public static CmsContent Read(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + var current = data; + var signers = new List(); + var layers = 0; + while (true) + { + if (current.Length > MaxSize) + { + throw new CmsFormatException($"The envelope is larger than {MaxSize / (1024 * 1024)} MB."); + } + + var binary = ToBinary(current); + if (binary is null) + { + if (layers == 0) + { + throw new CmsFormatException("Not a CMS SignedData structure."); + } + + return new CmsContent(current, signers, layers); + } + + if (++layers > MaxLayers) + { + throw new CmsFormatException($"More than {MaxLayers} nested envelopes."); + } + + current = ReadLayer(binary, signers); + } + } + + /// + /// Decodes the base64 text form of a binary structure: whitespace and line breaks are skipped, -----BEGIN + /// and -----END lines dropped, a UTF-8 byte order mark ignored. + /// + /// The text, as bytes. + /// The decoded bytes, or when the text is not base64. + public static byte[]? DecodeBase64Text(ReadOnlySpan text) + { + var body = SkipBom(text); + var filtered = new byte[body.Length]; + var count = 0; + var lineStart = true; + var skippingLine = false; + foreach (var b in body) + { + if (b is (byte)'\n' or (byte)'\r') + { + lineStart = true; + skippingLine = false; + continue; + } + + if (lineStart && b == (byte)'-') + { + skippingLine = true; + } + + lineStart = false; + if (skippingLine || IsBase64Whitespace(b)) + { + continue; + } + + if (!IsBase64Char(b) && b != (byte)'=') + { + return null; + } + + filtered[count++] = b; + } + + if (count == 0 || count % 4 != 0) + { + return null; + } + + var output = new byte[Base64.GetMaxDecodedFromUtf8Length(count)]; + var status = Base64.DecodeFromUtf8(filtered.AsSpan(0, count), output, out _, out var written); + return status == System.Buffers.OperationStatus.Done ? output[..written] : null; + } + + private static byte[]? ToBinary(byte[] data) + { + if (LooksLikeBinaryCms(data)) + { + return data; + } + + if (!LooksLikeCms(data)) + { + return null; + } + + var decoded = DecodeBase64Text(data); + return decoded is not null && LooksLikeBinaryCms(decoded) ? decoded : null; + } + + private static bool LooksLikeBinaryCms(ReadOnlySpan data) + { + if (data.Length < 2 || data[0] != 0x30) + { + return false; + } + + int header; + if (data[1] <= 0x80) + { + header = 2; + } + else + { + var lengthBytes = data[1] & 0x7F; + if (lengthBytes > 4) + { + return false; + } + + header = 2 + lengthBytes; + } + + return data.Length >= header + SignedDataOidDer.Length && data.Slice(header, SignedDataOidDer.Length).SequenceEqual(SignedDataOidDer); + } + + private static byte[] ReadLayer(byte[] data, List signers) + { + try + { + var outer = new AsnReader(data, AsnEncodingRules.BER); + var contentInfo = outer.ReadSequence(); + if (contentInfo.ReadObjectIdentifier() != SignedDataOid) + { + throw new CmsFormatException("The envelope is not SignedData."); + } + + var signedData = contentInfo.ReadSequence(Context0Constructed).ReadSequence(); + signedData.ReadInteger(); + signedData.ReadSetOf(skipSortOrderValidation: true); + + var encapsulated = signedData.ReadSequence(); + encapsulated.ReadObjectIdentifier(); + if (!encapsulated.HasData) + { + throw new CmsFormatException("The signature is detached: the envelope has no content."); + } + + var content = encapsulated.ReadSequence(Context0Constructed).ReadOctetString(); + + var certificates = new List(); + if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context0)) + { + var set = signedData.ReadSetOf(skipSortOrderValidation: true, Context0); + while (set.HasData) + { + var tag = set.PeekTag(); + var encoded = set.ReadEncodedValue(); + if (tag.HasSameClassAndValue(Asn1Tag.Sequence)) + { + certificates.Add(encoded.ToArray()); + } + } + } + + if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context1)) + { + signedData.ReadEncodedValue(); + } + + var signerInfos = signedData.ReadSetOf(skipSortOrderValidation: true); + var found = 0; + while (signerInfos.HasData) + { + signers.Add(ReadSigner(signerInfos.ReadSequence(), content, certificates)); + found++; + } + + if (found == 0) + { + signers.Add(new CmsSigner(null, null, null, null, null, null, null, false, "The envelope has no signer.", null)); + } + + return content; + } + catch (AsnContentException ex) + { + throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex); + } + catch (CryptographicException ex) + { + throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex); + } + } + + private static CmsSigner ReadSigner(AsnReader signerInfo, byte[] content, List certificates) + { + signerInfo.ReadInteger(); + byte[]? issuer = null; + byte[]? serial = null; + byte[]? keyIdentifier = null; + if (signerInfo.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence)) + { + var issuerAndSerial = signerInfo.ReadSequence(); + issuer = issuerAndSerial.ReadEncodedValue().ToArray(); + serial = issuerAndSerial.ReadIntegerBytes().ToArray(); + } + else + { + keyIdentifier = signerInfo.ReadOctetString(Context0); + } + + var (digestOid, _) = ReadAlgorithm(signerInfo); + byte[]? signedAttributes = null; + if (signerInfo.PeekTag().HasSameClassAndValue(Context0)) + { + signedAttributes = signerInfo.ReadEncodedValue().ToArray(); + } + + var (signatureOid, signatureParameters) = ReadAlgorithm(signerInfo); + var signature = signerInfo.ReadOctetString(); + + DateTimeOffset? signingTime = null; + byte[]? messageDigest = null; + if (signedAttributes is not null) + { + ReadAttributes(signedAttributes, out messageDigest, out signingTime); + } + + using var certificate = FindCertificate(certificates, issuer, serial, keyIdentifier); + var problem = Verify(certificate, content, digestOid, signedAttributes, messageDigest, signatureOid, signatureParameters, signature); + return Describe(certificate, signingTime, problem); + } + + private static (string Oid, byte[]? Parameters) ReadAlgorithm(AsnReader reader) + { + var algorithm = reader.ReadSequence(); + var oid = algorithm.ReadObjectIdentifier(); + var parameters = algorithm.HasData ? algorithm.ReadEncodedValue().ToArray() : null; + return (oid, parameters); + } + + private static void ReadAttributes(byte[] signedAttributes, out byte[]? messageDigest, out DateTimeOffset? signingTime) + { + messageDigest = null; + signingTime = null; + var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0); + while (set.HasData) + { + var attribute = set.ReadSequence(); + var type = attribute.ReadObjectIdentifier(); + var values = attribute.ReadSetOf(skipSortOrderValidation: true); + if (!values.HasData) + { + continue; + } + + switch (type) + { + case MessageDigestAttributeOid: + messageDigest = values.ReadOctetString(); + break; + case SigningTimeAttributeOid: + signingTime = values.PeekTag().HasSameClassAndValue(Asn1Tag.UtcTime) ? values.ReadUtcTime() : values.ReadGeneralizedTime(); + break; + case ContentTypeAttributeOid: + default: + break; + } + } + } + + private static X509Certificate2? FindCertificate(List certificates, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier) + { + foreach (var der in certificates) + { + X509Certificate2 certificate; + try + { + certificate = X509CertificateLoader.LoadCertificate(der); + } + catch (CryptographicException) + { + continue; + } + + if (Matches(certificate, issuer, serial, keyIdentifier)) + { + return certificate; + } + + certificate.Dispose(); + } + + return null; + } + + private static bool Matches(X509Certificate2 certificate, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier) + { + if (issuer is not null && serial is not null) + { + return certificate.IssuerName.RawData.AsSpan().SequenceEqual(issuer) + && certificate.SerialNumberBytes.Span.SequenceEqual(serial); + } + + return keyIdentifier is not null + && certificate.Extensions.OfType().FirstOrDefault() is { } extension + && extension.SubjectKeyIdentifierBytes.Span.SequenceEqual(keyIdentifier); + } + + private static string? Verify( + X509Certificate2? certificate, byte[] content, string digestOid, byte[]? signedAttributes, byte[]? messageDigest, + string signatureOid, byte[]? signatureParameters, byte[] signature) + { + if (certificate is null) + { + return "The signer certificate is not in the envelope."; + } + + if (HashOf(digestOid) is not { } digest) + { + return $"Unsupported digest algorithm {digestOid}."; + } + + List signedForms; + if (signedAttributes is null) + { + signedForms = [content]; + } + else + { + if (messageDigest is null) + { + return "The signed attributes have no message digest."; + } + + if (!CryptographicOperations.FixedTimeEquals(CryptographicOperations.HashData(digest, content), messageDigest)) + { + return "The content does not match the signed digest: it was changed after signing."; + } + + signedForms = SignedAttributesAsSet(signedAttributes); + } + + try + { + foreach (var signed in signedForms) + { + var result = VerifySignature(certificate, signed, digest, signatureOid, signatureParameters, signature); + if (result is null) + { + return null; + } + + if (result.Length > 0) + { + return result; + } + } + } + catch (CryptographicException ex) + { + return "The signature cannot be checked: " + ex.Message; + } + + return "The signature does not match the signer certificate."; + } + + // The signature covers the DER of the attributes as a SET (tag 0x31), not the [0] implicit tag of the file. The + // bytes of the file are tried first (they are DER in every well-formed signature); a DER re-encoding after. + private static List SignedAttributesAsSet(byte[] signedAttributes) + { + var forms = new List(); + if (signedAttributes.Length > 1 && signedAttributes[1] != 0x80) + { + var asSet = (byte[])signedAttributes.Clone(); + asSet[0] = 0x31; + forms.Add(asSet); + } + + try + { + var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0); + var writer = new AsnWriter(AsnEncodingRules.DER); + using (writer.PushSetOf()) + { + while (set.HasData) + { + writer.WriteEncodedValue(set.ReadEncodedValue().Span); + } + } + + var der = writer.Encode(); + if (!forms.Exists(f => f.AsSpan().SequenceEqual(der))) + { + forms.Add(der); + } + } + catch (ArgumentException) + { + // Attributes that are not DER inside cannot be re-encoded; the bytes of the file are all there is. + } + catch (AsnContentException) + { + // Same as above. + } + + return forms; + } + + // Null when verified, an empty string when the signature does not match, a message for an unsupported algorithm. + private static string? VerifySignature( + X509Certificate2 certificate, byte[] signed, HashAlgorithmName digest, string signatureOid, byte[]? signatureParameters, byte[] signature) + { + switch (signatureOid) + { + case RsaPssOid: + { + using var rsa = certificate.GetRSAPublicKey(); + if (rsa is null) + { + return "The signer certificate has no RSA key."; + } + + var pssHash = PssHash(signatureParameters) ?? digest; + return rsa.VerifyData(signed, signature, pssHash, RSASignaturePadding.Pss) ? null : string.Empty; + } + + case EcPublicKeyOid: + case "1.2.840.10045.4.1": + case "1.2.840.10045.4.3.2": + case "1.2.840.10045.4.3.3": + case "1.2.840.10045.4.3.4": + { + using var ecdsa = certificate.GetECDsaPublicKey(); + if (ecdsa is null) + { + return "The signer certificate has no ECDSA key."; + } + + var hash = signatureOid == EcPublicKeyOid ? digest : HashOfSignature(signatureOid) ?? digest; + return ecdsa.VerifyData(signed, signature, hash, DSASignatureFormat.Rfc3279DerSequence) ? null : string.Empty; + } + + case RsaEncryptionOid: + case "1.2.840.113549.1.1.5": + case "1.2.840.113549.1.1.11": + case "1.2.840.113549.1.1.12": + case "1.2.840.113549.1.1.13": + { + using var rsa = certificate.GetRSAPublicKey(); + if (rsa is null) + { + return "The signer certificate has no RSA key."; + } + + var hash = signatureOid == RsaEncryptionOid ? digest : HashOfSignature(signatureOid) ?? digest; + return rsa.VerifyData(signed, signature, hash, RSASignaturePadding.Pkcs1) ? null : string.Empty; + } + + default: + return $"Unsupported signature algorithm {signatureOid}."; + } + } + + private static HashAlgorithmName? HashOf(string digestOid) => digestOid switch + { + "1.3.14.3.2.26" => HashAlgorithmName.SHA1, + "2.16.840.1.101.3.4.2.1" => HashAlgorithmName.SHA256, + "2.16.840.1.101.3.4.2.2" => HashAlgorithmName.SHA384, + "2.16.840.1.101.3.4.2.3" => HashAlgorithmName.SHA512, + _ => null, + }; + + private static HashAlgorithmName? HashOfSignature(string signatureOid) => signatureOid switch + { + "1.2.840.113549.1.1.5" or "1.2.840.10045.4.1" => HashAlgorithmName.SHA1, + "1.2.840.113549.1.1.11" or "1.2.840.10045.4.3.2" => HashAlgorithmName.SHA256, + "1.2.840.113549.1.1.12" or "1.2.840.10045.4.3.3" => HashAlgorithmName.SHA384, + "1.2.840.113549.1.1.13" or "1.2.840.10045.4.3.4" => HashAlgorithmName.SHA512, + _ => null, + }; + + // RSASSA-PSS-params: hashAlgorithm [0] (default SHA-1), maskGenAlgorithm [1], saltLength [2], trailerField [3]. + private static HashAlgorithmName? PssHash(byte[]? parameters) + { + if (parameters is null) + { + return null; + } + + var sequence = new AsnReader(parameters, AsnEncodingRules.BER).ReadSequence(); + if (!sequence.HasData || !sequence.PeekTag().HasSameClassAndValue(Context0)) + { + return HashAlgorithmName.SHA1; + } + + var (oid, _) = ReadAlgorithm(sequence.ReadSequence(Context0Constructed)); + return HashOf(oid); + } + + private static CmsSigner Describe(X509Certificate2? certificate, DateTimeOffset? signingTime, string? problem) + { + if (certificate is null) + { + return new CmsSigner(null, null, null, null, null, null, signingTime, false, problem, null); + } + + string? commonName = null, givenName = null, surname = null, organization = null, serialNumber = null; + foreach (var rdn in certificate.SubjectName.EnumerateRelativeDistinguishedNames()) + { + if (rdn.HasMultipleElements) + { + continue; + } + + var value = rdn.GetSingleElementValue(); + switch (rdn.GetSingleElementType().Value) + { + case "2.5.4.3": + commonName ??= value; + break; + case "2.5.4.42": + givenName ??= value; + break; + case "2.5.4.4": + surname ??= value; + break; + case "2.5.4.10": + organization ??= value; + break; + case "2.5.4.5": + serialNumber ??= value; + break; + default: + break; + } + } + + var personName = string.Join(' ', new[] { givenName, surname }.Where(s => !string.IsNullOrWhiteSpace(s))); + var name = NullIfBlank(commonName) ?? NullIfBlank(personName) ?? NullIfBlank(organization) ?? NullIfBlank(serialNumber); + return new CmsSigner( + name, + TaxCodeOf(serialNumber), + certificate.Subject, + certificate.Issuer, + new DateTimeOffset(certificate.NotBefore.ToUniversalTime(), TimeSpan.Zero), + new DateTimeOffset(certificate.NotAfter.ToUniversalTime(), TimeSpan.Zero), + signingTime, + problem is null, + problem, + certificate.RawData); + } + + // ETSI EN 319 412-1: SERIALNUMBER = TINIT-; older Italian certificates use IT:. + private static string? TaxCodeOf(string? serialNumber) + { + if (string.IsNullOrWhiteSpace(serialNumber)) + { + return null; + } + + var value = serialNumber.Trim(); + if (value.StartsWith("TINIT-", StringComparison.OrdinalIgnoreCase)) + { + return NullIfBlank(value["TINIT-".Length..].Trim()); + } + + if (value.StartsWith("IT:", StringComparison.OrdinalIgnoreCase)) + { + return NullIfBlank(value["IT:".Length..].Trim()); + } + + return value.Length is 11 or 16 && value.All(char.IsAsciiLetterOrDigit) ? value.ToUpperInvariant() : null; + } + + private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value; + + private static ReadOnlySpan SkipBom(ReadOnlySpan data) => + data.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF]) ? data[3..] : data; + + private static ReadOnlySpan SkipArmour(ReadOnlySpan data) + { + var trimmed = data.TrimStart((ReadOnlySpan)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']); + if (!trimmed.StartsWith("-----"u8)) + { + return trimmed; + } + + var end = trimmed.IndexOf((byte)'\n'); + return end < 0 ? [] : trimmed[(end + 1)..]; + } + + private static bool IsBase64Char(byte b) => + b is (>= (byte)'A' and <= (byte)'Z') or (>= (byte)'a' and <= (byte)'z') or (>= (byte)'0' and <= (byte)'9') or (byte)'+' or (byte)'/'; + + private static bool IsBase64Whitespace(byte b) => b is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n'; +} diff --git a/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor b/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor index 56f417d..f416e84 100644 --- a/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor +++ b/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor @@ -19,6 +19,9 @@ case WidgetIds.SystemStatus: break; + case WidgetIds.Understock: + + break; default: break; diff --git a/src/Khaemhat.Web/Components/Dashboard/UnderstockWidget.razor b/src/Khaemhat.Web/Components/Dashboard/UnderstockWidget.razor new file mode 100644 index 0000000..92b0ccc --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/UnderstockWidget.razor @@ -0,0 +1,74 @@ +@using Khaemhat.Application.Inventory +@inject ShellSession Session +@inject InventoryService Inventory + +@* Sottoscorta (SPEC §10.3, §11.6): the items under their minimum stock or reorder point, the most urgent first, with a + link to the reorder proposal. *@ + + + @if (_rows is { Count: > 0 }) + { + @T.Number(_rows.Count) + } + + + @if (_failed) + { +

@T["Dashboard.Feed.Error"]

+ } + else if (_rows is null) + { +

@T["Dashboard.Feed.Loading"]

+ } + else if (_rows.Count == 0) + { +

@T["Dashboard.Widgets.Understock.Empty"]

+ } + else + { + + + } +
+
+ +@code { + private IReadOnlyList? _rows; + private bool _failed; + + /// The widget. + [Parameter, EditorRequired] + public WidgetDefinition Definition { get; set; } = default!; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !Session.Permissions.Allows(InventoryService.StockPermission)) + { + _rows = []; + return; + } + + try + { + _rows = await Inventory.UnderstockAsync(actor, company, 8); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _failed = true; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs index 57ac76f..052d287 100644 --- a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs @@ -46,7 +46,7 @@ public partial class ImportExportPage private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null; - private string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6"; + private static string CheckOnlyMilestone => "M7"; private IReadOnlyList> TargetChoices => [.. Targets.Select(t => new KhOption(t.Key, TargetName(t.Key)))]; diff --git a/src/Khaemhat.Web/Components/Pages/Inventory/ReorderPage.razor b/src/Khaemhat.Web/Components/Pages/Inventory/ReorderPage.razor new file mode 100644 index 0000000..7698ff3 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Inventory/ReorderPage.razor @@ -0,0 +1,247 @@ +@page "/magazzino/riordino" +@attribute [Authorize] +@using Khaemhat.Application.Documents +@using Khaemhat.Application.Inventory +@using Khaemhat.Application.Items +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Documents +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject ReorderService Reorder +@inject PartyService Parties +@inject TableService Tables +@inject ToastService Toasts + +@* The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the + reorder point or the minimum stock, with the quantity to order and the usual supplier; the lines chosen, perhaps with + another quantity or supplier, become draft supplier orders, one per supplier. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(InventoryService.StockPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + @if (_orders.Count > 0) + { +
+ + + @T.Format("Inventory.Reorder.Created", _orders.Count) + @foreach (var order in _orders) + { + @order.Supplier + } + +
+ } + + + + @T.Format("Inventory.Reorder.Selected", Chosen.Count(), T.Money(ChosenValue)) + + @if (CanOrder) + { + + } + + + @if (_lines.Count == 0) + { +

@T["Inventory.Reorder.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + + + + @foreach (var line in _lines) + { + var row = line.Proposal; + + + + + + + + + + + + + + + } + +
@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Items.Radar.Unit"]@T["Inventory.Stock.Available"]@T["Inventory.Stock.OrderedColumn"]@T["Inventory.Stock.Minimum"]@T["Inventory.Stock.ReorderPoint"]@T["Inventory.Reorder.Quantity"]@T["Purchases.Fields.Supplier"]@T["Inventory.Reorder.Price"]@T["Inventory.Reorder.Expected"]
@row.Code@row.Description@PartyScreens.Describe(_lookups.Units, row.UnitOfMeasureId)@Qty(row.Available)@Qty(row.Ordered)@(row.MinimumStock is { } m ? Qty(m) : null)@(row.ReorderPoint is { } p ? Qty(p) : null) + + + + @(row.Price is { } price ? T.Money(price) : null)@(row.ExpectedDate is { } date ? T.Date(date) : null)
+
+ } +
+
+

@T["Inventory.Reorder.Hint"]

+} + +@code { + private List _lines = []; + private List<(DocumentRecord Record, string Supplier)> _orders = []; + private ItemLookups _lookups = ItemLookups.Empty; + private bool _loaded; + private bool _busy; + + private bool CanOrder => Session.Permissions.Allows("purchases.order.write"); + + private IEnumerable Chosen => _lines.Where(l => l.Chosen && l.Supplier is not null && l.Quantity > 0m); + + private decimal ChosenValue => Chosen.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2)); + + private IReadOnlyList Stats => + [ + new(T["Inventory.Reorder.Items"], T.Number(_lines.Count), _lines.Count > 0 ? KhTone.Warning : KhTone.Ok), + new(T["Inventory.Reorder.Suppliers"], T.Number(_lines.Where(l => l.Supplier is not null).Select(l => l.Supplier!.Id).Distinct().Count())), + new(T["Inventory.Reorder.Value"], T.Money(_lines.Sum(l => Math.Round(l.Quantity * (l.Proposal.Price ?? 0m), 2)))), + new(T["Inventory.Reorder.WithoutSupplier"], T.Number(_lines.Count(l => l.Supplier is null)), _lines.Any(l => l.Supplier is null) ? KhTone.Warning : KhTone.Neutral), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.StockPermission)) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + await LoadAsync(); + } + + _loaded = true; + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + var proposals = await Reorder.ProposalsAsync(actor, company); + var supplierIds = proposals.Where(p => p.SupplierId is not null).Select(p => p.SupplierId!.Value).Distinct().ToList(); + var suppliers = Session.Permissions.Allows(PartyService.ReadPermission) + ? (await Parties.RowsAsync(actor, company, supplierIds)).ToDictionary(r => r.Id) + : []; + + _lines = [.. proposals.Select(p => new Line(p) + { + Quantity = p.Quantity, + Supplier = p.SupplierId is { } s ? suppliers.GetValueOrDefault(s) : null, + Chosen = p.SupplierId is not null, + })]; + } + + private async Task> SearchAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken) + : []; + + private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); + + private void SetQuantity(Line line, string? text) + { + if (decimal.TryParse((text ?? string.Empty).Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value) + && value >= 0m) + { + line.Quantity = value; + } + } + + private void ToggleAll(ChangeEventArgs e) + { + foreach (var line in _lines) + { + line.Chosen = e.Value is true; + } + } + + private async Task CreateAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (_lines.Any(l => l.Chosen && l.Supplier is null)) + { + Toasts.Show(ToastKind.Warning, T["Inventory.Reorder.MissingSupplier"]); + } + + _busy = true; + try + { + var names = Chosen.Select(l => l.Supplier!).DistinctBy(r => r.Id).ToDictionary(r => r.Id, r => r.Name); + var orders = await Reorder.CreateOrdersAsync(actor, company, [.. Chosen.Select(l => new ReorderChoice(l.Proposal.ItemId, l.Supplier!.Id, l.Quantity))]); + _orders = [.. orders.Select(o => (o, names.GetValueOrDefault(o.Header.PartyId ?? 0) ?? string.Empty))]; + Toasts.Show(ToastKind.Success, T.Format("Inventory.Reorder.Created", _orders.Count)); + await LoadAsync(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); + } + finally + { + _busy = false; + } + } + + private sealed class Line(ReorderProposal proposal) + { + public ReorderProposal Proposal { get; } = proposal; + + public decimal Quantity { get; set; } + + public PartyRow? Supplier { get; set; } + + public bool Chosen { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Inventory/StockPage.razor b/src/Khaemhat.Web/Components/Pages/Inventory/StockPage.razor new file mode 100644 index 0000000..673e392 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Inventory/StockPage.razor @@ -0,0 +1,450 @@ +@page "/magazzino/giacenze" +@attribute [Authorize] +@using Khaemhat.Application.Inventory +@using Khaemhat.Application.Items +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Inventory +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@inject ShellSession Session +@inject InventoryService Inventory +@inject ItemService Items +@inject TableService Tables +@inject ToastService Toasts +@inject DialogService Dialogs +@inject TimeProvider Clock + +@* Stock and availability (SPEC §11.6, mockup 036): every stocked item with on hand, committed, ordered and available, + its thresholds and, for who may see costs, the average cost and the value; the state under the thresholds. One + warehouse or all together. The movements of an item with their running balance; the value at a date with the ABC + classes; the rebuild of the warehouse from its documents. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(InventoryService.StockPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + + + + + + + @T["Shell.Menu.Inventory.Reorder"] + @T["Shell.Menu.Inventory.StockTake"] + @if (_costs) + { + + } + @if (Session.Permissions.Allows(InventoryService.PostPermission)) + { + + } + + + + @if (_rebuild is { } progress) + { +
+ + @T.Format("Inventory.Rebuild.Progress", T["Inventory.Rebuild.Phases." + progress.Phase], T.Number(progress.Done), T.Number(progress.Total)) +
+ } + + + + @if (_balances is { Count: > 1 }) + { + + } + @if (_movements is null) + { +

@T["Common.Loading"]

+ } + else if (_movements.Count == 0) + { +

@T["Inventory.Movements.None"]

+ } + else + { +
+ + + + + + + + + + @if (_costs) + { + + } + + + + + @foreach (var move in _movements) + { + + + + + + + + @if (_costs) + { + + } + + + } + +
@T["Inventory.Movements.Date"]@T["Inventory.Movements.Document"]@T["Inventory.Fields.Reason"]@T["Inventory.Movements.Party"]@T["Inventory.Fields.Warehouse"]@T["Inventory.Movements.Quantity"]@T["Inventory.Movements.UnitCost"]@T["Inventory.Movements.Balance"]
@T.Date(move.Date) + @if (move.Kind is { } kind && move.DocumentId is { } document) + { + @T["Sales.Kinds." + kind] @move.Number + } + @move.ReasonCode@move.PartyName@PartyScreens.Describe(_warehouses, move.WarehouseId)@Qty(move.Quantity)@Cost(move.UnitCost)@Qty(move.Balance)
+
+ } +
+ +
+ + + + + + +
+ +
+
+ @if (_valuation is { } rows) + { + +
+ + + + + + + + + + + + + @foreach (var row in rows) + { + + + + + + + + + } + +
@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Inventory.Movements.Quantity"]@T["Inventory.Movements.UnitCost"]@T["Inventory.Stock.Value"]@T["Inventory.Valuation.Class"]
@row.Code@row.Description@Qty(row.Quantity)@T.Money(row.UnitCost)@T.Money(row.Value)@row.AbcClass
+
+ } +

@T["Inventory.Valuation.Hint"]

+
+
+ +
+
+} + +@code { + private static readonly ListFields Fields = new ListFields() + .Add("code", r => r.Code, searchable: true) + .Add("description", r => r.Description, searchable: true) + .Add("category", r => r.CategoryId) + .Add("unit", r => r.UnitOfMeasureId) + .Add("onHand", r => r.OnHand) + .Add("committed", r => r.Committed) + .Add("ordered", r => r.Ordered) + .Add("available", r => r.Available) + .Add("minimum", r => r.MinimumStock) + .Add("reorderPoint", r => r.ReorderPoint) + .Add("averageCost", r => r.AverageCost) + .Add("value", r => r.Value, total: true) + .Add("lastLoad", r => r.LastLoad) + .Add("lastUnload", r => r.LastUnload) + .Add("level", r => r.Level) + .OrderByDefault(new ListSort("code")); + + private InMemoryListSource _source = new([], Fields); + private IReadOnlyList _rows = []; + private ItemLookups _lookups = ItemLookups.Empty; + private IReadOnlyList> _warehouses = []; + private KhRadar? _radar; + private long? _warehouse; + private bool _includeEmpty; + private bool _costs; + private bool _loaded; + private bool _busy; + private RebuildProgress? _rebuild; + + private StockRow? _item; + private IReadOnlyList? _movements; + private IReadOnlyList? _balances; + + private bool _valuationOpen; + private DateOnly? _valuationDate; + private StockValuationMethod _method = StockValuationMethod.WeightedAverage; + private IReadOnlyList? _valuation; + + /// An item to open at once, from the dashboard. + [SupplyParameterFromQuery(Name = "articolo")] + public long? ItemId { get; set; } + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + private IReadOnlyList Stats => + [ + new(T["Inventory.Stock.Items"], T.Number(_rows.Count(r => r.OnHand != 0m))), + new(T["Inventory.Stock.Understock"], T.Number(_rows.Count(r => r.Level is StockLevel.Understock or StockLevel.Reorder)), + _rows.Any(r => r.Level is StockLevel.Understock or StockLevel.Reorder) ? KhTone.Warning : KhTone.Neutral), + new(T["Inventory.Stock.Out"], T.Number(_rows.Count(r => r.Level == StockLevel.Out)), _rows.Any(r => r.Level == StockLevel.Out) ? KhTone.Error : KhTone.Neutral), + new(T["Inventory.Stock.Ordered"], T.Number(_rows.Count(r => r.Ordered > 0m))), + .. _costs ? [new KhStat(T["Inventory.Stock.TotalValue"], T.Money(_rows.Sum(r => r.Value ?? 0m)))] : Array.Empty(), + ]; + + private IReadOnlyList BalanceStats => _balances is null ? [] : + [.. _balances.Select(b => new KhStat(PartyScreens.Describe(_warehouses, b.WarehouseId) ?? string.Empty, Qty(b.OnHand)))]; + + private IReadOnlyList ValuationStats => _valuation is null ? [] : + [ + new(T["Inventory.Stock.Items"], T.Number(_valuation.Count)), + new(T["Inventory.Stock.TotalValue"], T.Money(_valuation.Sum(r => r.Value))), + new(T["Inventory.Valuation.ClassA"], T.Number(_valuation.Count(r => r.AbcClass == 'A'))), + new(T["Inventory.Valuation.ClassB"], T.Number(_valuation.Count(r => r.AbcClass == 'B'))), + new(T["Inventory.Valuation.ClassC"], T.Number(_valuation.Count(r => r.AbcClass == 'C'))), + ]; + + private IReadOnlyList> Methods => + [ + new(nameof(StockValuationMethod.WeightedAverage), T["Inventory.Valuation.Methods.WeightedAverage"]), + new(nameof(StockValuationMethod.LastCost), T["Inventory.Valuation.Methods.LastCost"]), + new(nameof(StockValuationMethod.StandardCost), T["Inventory.Valuation.Methods.StandardCost"]), + ]; + + private string MovementsTitle => _item is { } item ? item.Code + " · " + item.Description : T["Inventory.Movements.Title"]; + + private IReadOnlyList> Columns => + [ + new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "120px" }, + new("description", T["Items.Fields.Description"], r => r.Description), + new("category", T["Items.Radar.Category"], r => PartyScreens.Describe(_lookups.Categories, r.CategoryId)) { Width = "110px" }, + new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "50px" }, + new("onHand", T["Inventory.Stock.OnHand"], r => r.OnHand) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, + new("committed", T["Inventory.Stock.Committed"], r => r.Committed) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, + new("ordered", T["Inventory.Stock.OrderedColumn"], r => r.Ordered) { Kind = KhColumnKind.Number, Decimals = 2, Width = "90px" }, + new("available", T["Inventory.Stock.Available"], r => r.Available) + { + Kind = KhColumnKind.Number, Decimals = 2, Width = "90px", CellClass = r => r.Available < 0m ? "err" : null, + }, + new("minimum", T["Inventory.Stock.Minimum"], r => r.MinimumStock) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px" }, + new("reorderPoint", T["Inventory.Stock.ReorderPoint"], r => r.ReorderPoint) { Kind = KhColumnKind.Number, Decimals = 2, Width = "80px", Visible = false }, + new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "100px", Visible = _costs, Export = _costs }, + new("value", T["Inventory.Stock.Value"], r => r.Value) { Kind = KhColumnKind.Money, Width = "110px", Visible = _costs, Export = _costs, Total = _costs }, + new("lastLoad", T["Inventory.Stock.LastLoad"], r => r.LastLoad) { Kind = KhColumnKind.Date, Width = "95px", Visible = false }, + new("lastUnload", T["Inventory.Stock.LastUnload"], r => r.LastUnload) { Kind = KhColumnKind.Date, Width = "95px", Visible = false }, + new("level", T["Items.Radar.State"], r => T["Inventory.Levels." + r.Level]) + { + Width = "120px", + Template = r => @@T["Inventory.Levels." + r.Level], + }, + ]; + + private IReadOnlyList QuickFilters => + [ + new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]), + new("level", T["Items.Radar.State"], + [ + new(string.Empty, T["Items.Radar.All"]), + .. Enum.GetValues().Select(l => new KhOption(l.ToString(), T["Inventory.Levels." + l])), + ]), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.StockPermission)) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + _warehouses = [.. (await Tables.ActiveAsync(actor, company)).Select(w => new KhOption(PartyScreens.Text(w.Id)!, w.Code + " · " + w.Description))]; + _costs = await Items.CanSeeCostsAsync(actor, company); + _valuationDate = Today; + await LoadAsync(); + if (ItemId is { } id && _rows.FirstOrDefault(r => r.ItemId == id) is { } row) + { + await OpenMovementsAsync(row); + } + } + + _loaded = true; + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _rows = await Inventory.StockAsync(actor, company, new StockFilter { WarehouseId = _warehouse, IncludeEmpty = _includeEmpty }); + _source = new InMemoryListSource(_rows, Fields); + } + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => _source.QueryAsync(query, cancellationToken); + + private async Task ReloadAsync() + { + await LoadAsync(); + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + + private async Task SetWarehouseAsync(string? value) + { + _warehouse = PartyScreens.Id(value); + await ReloadAsync(); + } + + private async Task SetIncludeEmptyAsync(bool value) + { + _includeEmpty = value; + await ReloadAsync(); + } + + private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); + + private string Cost(decimal? value) => value is { } cost ? T.Money(cost) : string.Empty; + + private static KhTone ToneOf(StockLevel level) => level switch + { + StockLevel.Out => KhTone.Error, + StockLevel.Understock => KhTone.Warning, + StockLevel.Reorder => KhTone.Info, + _ => KhTone.Ok, + }; + + private static string? RowClassOf(StockRow row) => row.Level is StockLevel.Out or StockLevel.Understock ? "hl" : null; + + private async Task OpenMovementsAsync(StockRow row) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _item = row; + _movements = null; + _balances = null; + if (!Session.Permissions.Allows(InventoryService.EntryReadPermission)) + { + _movements = []; + return; + } + + _balances = await Inventory.BalancesAsync(actor, company, row.ItemId); + _movements = await Inventory.MovementsAsync(actor, company, row.ItemId, _warehouse, null, null); + } + + private void OpenValuation() + { + _valuation = null; + _valuationOpen = true; + } + + private void SetMethod(string? value) => + _method = Enum.TryParse(value, out var method) ? method : StockValuationMethod.WeightedAverage; + + private async Task ValueAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _valuationDate is not { } date) + { + return; + } + + _busy = true; + try + { + _valuation = await Inventory.ValuationAsync(actor, company, date, _warehouse, _method); + } + finally + { + _busy = false; + } + } + + private async Task RebuildAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(T["Inventory.Rebuild.Title"], T["Inventory.Rebuild.Text"], T["Inventory.Rebuild.Action"], T["Common.Cancel"]))) + { + return; + } + + _busy = true; + var progress = new Progress(p => + { + _rebuild = p; + _ = InvokeAsync(StateHasChanged); + }); + try + { + var (documents, items) = await Task.Run(() => Inventory.RebuildAsync(actor, company, progress)); + Toasts.Show(ToastKind.Success, T.Format("Inventory.Rebuild.Done", T.Number(documents), T.Number(items))); + await ReloadAsync(); + } + finally + { + _busy = false; + _rebuild = null; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor b/src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor new file mode 100644 index 0000000..6dc7b1b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Inventory/StockTakePage.razor @@ -0,0 +1,524 @@ +@page "/magazzino/inventario" +@page "/magazzino/inventario/{Id:long}" +@attribute [Authorize] +@using Khaemhat.Application.Documents +@using Khaemhat.Application.Inventory +@using Khaemhat.Application.Items +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Documents +@using Khaemhat.Core.Inventory +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject StockTakeService StockTakes +@inject ItemService Items +@inject TableService Tables +@inject ToastService Toasts +@inject DialogService Dialogs +@inject NavigationManager Navigation +@inject TimeProvider Clock + +@* The physical stock take (SPEC §11.6, mockup 038): opened on a warehouse at a date (and perhaps a category), it freezes + the book quantity and cost of each item; the counts are typed on the list or read from a scanner file; posting turns + the differences into gain and loss movements at the date of the count. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(InventoryService.EntryReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (Id is null) +{ +
+
+ + @if (CanWrite) + { + + + + + +
+ +
+
+ } +

@T["Inventory.StockTake.Hint"]

+
+
+
+ + @if (_takes.Count == 0) + { +

@T["Inventory.StockTake.None"]

+ } + else + { +
+ + + + + + + + + + + @foreach (var take in _takes) + { + + + + + + + } + +
@T["Inventory.StockTake.Date"]@T["Inventory.StockTake.Description"]@T["Inventory.Fields.Warehouse"]@T["Items.Radar.State"]
@T.Date(take.TakeDate)@take.Description@PartyScreens.Describe(_warehouses, take.WarehouseId)@T["Inventory.StockTake.States." + take.Status]
+
+ } +
+
+
+} +else if (_view is null) +{ +

@T["Inventory.StockTake.Missing"]

@T["Inventory.StockTake.List"]

+} +else +{ + var take = _view.Take; +
+
+ + +
+
@T["Inventory.Fields.Warehouse"]
@PartyScreens.Describe(_warehouses, take.WarehouseId)
+
@T["Inventory.StockTake.Date"]
@T.Date(take.TakeDate)
+
@T["Items.Radar.Category"]
@(PartyScreens.Describe(_lookups.Categories, take.CategoryId) ?? T["Inventory.StockTake.AllCategories"])
+
@T["Items.Radar.State"]
@T["Inventory.StockTake.States." + take.Status]
+ @if (take.Status == StockTakeStatus.Posted) + { +
@T["Inventory.StockTake.Movements"]
+
+ @if (take.AdjustmentDocumentId is { } gain) + { + @StockTakeService.GainReason + } + @if (take.LossDocumentId is { } loss) + { + @StockTakeService.LossReason + } +
+ } +
+ @if (IsOpen && CanWrite) + { +
+ +
+ } +
+
+
+ + + +
+ + + @if (IsOpen && CanWrite) + { + + + @if (Session.Permissions.Allows(InventoryService.PostPermission)) + { + + } + } +
+
+ + + + + + + + + + @if (_costs) + { + + + } + + + + + @foreach (var line in Shown) + { + var id = line.Line.Id; + var counted = CountOf(line); + var difference = counted is { } c ? c - line.Line.BookQuantity : 0m; + + + + + + + + @if (_costs) + { + + + } + + + } + +
@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Items.Radar.Unit"]@T["Inventory.StockTake.Book"]@T["Inventory.StockTake.Counted"]@T["Inventory.StockTake.Difference"]@T["Inventory.Movements.UnitCost"]@T["Inventory.StockTake.DifferenceValue"]@T["Items.Radar.State"]
@line.Code@line.Description@PartyScreens.Describe(_lookups.Units, line.UnitOfMeasureId)@Qty(line.Line.BookQuantity) + @if (IsOpen && CanWrite) + { + + } + else + { + @(counted is { } v ? Qty(v) : "—") + } + 0m ? "ok" : null)">@(counted is null ? null : Qty(difference))@T.Money(line.Line.UnitCost)@(counted is null ? null : T.Money(Math.Round(difference * line.Line.UnitCost, 2))) + @if (counted is null) + { + @T["Inventory.StockTake.ToCount"] + } + else if (difference == 0m) + { + @T["Inventory.StockTake.Matches"] + } + else + { + @T["Inventory.StockTake.Differs"] + } +
+
+
+
+
+
+} + +@code { + private readonly KhValidation _validation = new(); + private readonly Dictionary _counts = []; + private IReadOnlyList _takes = []; + private IReadOnlyList> _warehouses = []; + private ItemLookups _lookups = ItemLookups.Empty; + private StockTakeView? _view; + private long? _warehouse; + private long? _category; + private DateOnly? _date; + private string? _description; + private string? _search; + private string _show = string.Empty; + private bool _costs; + private bool _loaded; + private bool _busy; + + /// The stock take shown, or none for the list. + [Parameter] + public long? Id { get; set; } + + private string Title => _view?.Take.Description is { } description && Id is not null ? description : T["Inventory.StockTake.Title"]; + + private bool CanWrite => Session.Permissions.Allows("inventory.entry.write"); + + private bool IsOpen => _view?.Take.Status == StockTakeStatus.Open; + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + private IReadOnlyList Steps => + [ + new(T["Inventory.StockTake.Steps.Open"], T["Inventory.StockTake.Steps.OpenDetail"]), + new(T["Inventory.StockTake.Steps.Count"], T["Inventory.StockTake.Steps.CountDetail"]), + new(T["Inventory.StockTake.Steps.Check"], T["Inventory.StockTake.Steps.CheckDetail"]), + new(T["Inventory.StockTake.Steps.Post"], T["Inventory.StockTake.Steps.PostDetail"]), + ]; + + private int Step => _view is null ? 0 : _view.Take.Status != StockTakeStatus.Open ? 4 : Counted == 0 ? 1 : Counted < _view.Lines.Count ? 1 : 2; + + private int Counted => _view?.Lines.Count(l => CountOf(l) is not null) ?? 0; + + private IReadOnlyList Stats + { + get + { + if (_view is null) + { + return []; + } + + var counted = _view.Lines.Where(l => CountOf(l) is not null).ToList(); + var differences = counted.Where(l => CountOf(l) != l.Line.BookQuantity).ToList(); + var value = differences.Sum(l => Math.Round((CountOf(l)!.Value - l.Line.BookQuantity) * l.Line.UnitCost, 2)); + return + [ + new(T["Inventory.StockTake.Items"], T.Number(_view.Lines.Count)), + new(T["Inventory.StockTake.CountedItems"], T.Number(counted.Count), counted.Count == _view.Lines.Count ? KhTone.Ok : KhTone.Neutral), + new(T["Inventory.StockTake.Differences"], T.Number(differences.Count), differences.Count > 0 ? KhTone.Warning : KhTone.Neutral), + .. _costs ? [new KhStat(T["Inventory.StockTake.DifferenceValue"], T.Money(value), value < 0m ? KhTone.Error : KhTone.Neutral)] : Array.Empty(), + ]; + } + } + + private IEnumerable Shown => (_view?.Lines ?? []).Where(l => + (string.IsNullOrWhiteSpace(_search) + || l.Code.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase) + || l.Description.Contains(_search.Trim(), StringComparison.OrdinalIgnoreCase)) + && _show switch + { + "todo" => CountOf(l) is null, + "diff" => CountOf(l) is { } c && c != l.Line.BookQuantity, + _ => true, + }); + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(InventoryService.EntryReadPermission)) + { + if (!_loaded) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + _warehouses = [.. (await Tables.ActiveAsync(actor, company)).Select(w => new KhOption(PartyScreens.Text(w.Id)!, w.Code + " · " + w.Description))]; + _warehouse = await DefaultWarehouseAsync(actor, company); + _costs = await Items.CanSeeCostsAsync(actor, company); + _date = Today; + } + + _counts.Clear(); + if (Id is { } id) + { + _view = await StockTakes.GetAsync(actor, company, id); + } + else + { + _view = null; + _takes = await StockTakes.ListAsync(actor, company); + } + } + + _loaded = true; + } + + private async Task DefaultWarehouseAsync(Actor actor, string company) => + (await Tables.ActiveAsync(actor, company)).OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id; + + private decimal? CountOf(StockTakeLineView line) => _counts.TryGetValue(line.Line.Id, out var count) ? count : line.Line.CountedQuantity; + + private string Qty(decimal value) => value.ToString("#,##0.###", T.Culture); + + private static KhTone ToneOf(StockTakeStatus status) => status switch + { + StockTakeStatus.Posted => KhTone.Ok, + StockTakeStatus.Cancelled => KhTone.Neutral, + _ => KhTone.Info, + }; + + private void SetCount(long lineId, string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + _counts[lineId] = null; + return; + } + + if (decimal.TryParse(text.Replace(".", string.Empty, StringComparison.Ordinal), System.Globalization.NumberStyles.Number, T.Culture, out var value) && value >= 0m) + { + _counts[lineId] = value; + } + else + { + Toasts.Show(ToastKind.Error, T["inventory.stock-take.negative"]); + } + } + + private async Task CreateAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _warehouse is not { } warehouse || _date is not { } date) + { + return; + } + + _busy = true; + try + { + var view = await StockTakes.CreateAsync(actor, company, warehouse, date, _category, _description); + Toasts.Show(ToastKind.Success, T.Format("Inventory.StockTake.Opened", view.Lines.Count)); + Navigation.NavigateTo("magazzino/inventario/" + view.Take.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + finally + { + _busy = false; + } + } + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id || _counts.Count == 0) + { + return; + } + + _busy = true; + try + { + _view = await StockTakes.SaveCountsAsync(actor, company, id, _counts); + _counts.Clear(); + Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Saved"]); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + finally + { + _busy = false; + } + } + + private async Task ImportAsync(InputFileChangeEventArgs e) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) + { + return; + } + + _busy = true; + try + { + if (_counts.Count > 0) + { + await StockTakes.SaveCountsAsync(actor, company, id, _counts); + _counts.Clear(); + } + + using var buffer = new MemoryStream(); + await using (var stream = e.File.OpenReadStream(5 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + buffer.Position = 0; + var result = await StockTakes.ImportCountsAsync(actor, company, id, buffer); + _view = await StockTakes.GetAsync(actor, company, id); + Toasts.Show(result.Unknown.Count == 0 ? ToastKind.Success : ToastKind.Warning, + T.Format("Inventory.StockTake.Imported", result.Applied, result.Unknown.Count) + (result.Unknown.Count == 0 ? string.Empty : " " + string.Join(", ", result.Unknown.Take(5)))); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + catch (IOException) + { + Toasts.Show(ToastKind.Error, T["Inventory.StockTake.FileTooLarge"]); + } + finally + { + _busy = false; + } + } + + private async Task PostAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.PostTitle"], T["Inventory.StockTake.PostText"], T["Inventory.StockTake.Post"], T["Common.Cancel"]))) + { + return; + } + + _busy = true; + try + { + if (_counts.Count > 0) + { + await StockTakes.SaveCountsAsync(actor, company, id, _counts); + _counts.Clear(); + } + + _view = await StockTakes.PostAsync(actor, company, id); + Toasts.Show(ToastKind.Success, T["Inventory.StockTake.Posted"]); + } + catch (ValidationFailedException ex) + { + ShowErrors(ex); + } + catch (InvalidDocumentActionException) + { + Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]); + } + finally + { + _busy = false; + } + } + + private async Task CancelAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Id is not { } id) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(T["Inventory.StockTake.CancelTitle"], T["Inventory.StockTake.CancelText"], T["Inventory.StockTake.Cancel"], T["Common.Back"], Danger: true))) + { + return; + } + + await StockTakes.CancelAsync(actor, company, id); + _view = await StockTakes.GetAsync(actor, company, id); + } + + private void ShowErrors(ValidationFailedException ex) => + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); +} diff --git a/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor new file mode 100644 index 0000000..3196542 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor @@ -0,0 +1,384 @@ +@page "/acquisti/importa-fatture" +@attribute [Authorize] +@using Khaemhat.Application.Purchases +@using Khaemhat.Fiscal.Abstractions +@using Khaemhat.Web.Documents +@inject ShellSession Session +@inject PurchaseInvoiceImportService Import +@inject ToastService Toasts + +@* The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files; each invoice shows its + supplier (known or to add), number, date, total and what to check; the chosen ones become draft supplier invoices or + credit notes with the file attached. The invoice can be read as a page before registering it. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Inventory.NoCompany"]

+} +else if (!Session.Permissions.Allows(PurchaseService.WritePermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ +
+
+ + +
+
+ + + @T["Purchases.Import.FilesHint"] +
+
+
+
+
+ @if (_results.Count > 0) + { + +
+ + + + + + + + + + + @foreach (var result in _results) + { + + + + @if (result.Record is { } record) + { + + + } + else + { + + } + + } + +
@T["Purchases.Fields.Supplier"]@T["Purchases.Fields.SupplierNumber"]@T["Purchases.Import.Draft"]@T["Purchases.Import.Check"]
+ @result.Candidate.File.Supplier.DisplayName + @if (result.SupplierCreated) + { + @T["Purchases.Import.NewSupplier"] + } + @result.Candidate.Invoice.Number@T["Sales.Kinds." + record.Header.Kind] · @T.Money(record.Header.TotalAmount)@string.Join(" ", result.Warnings.Select(w => T[w])) @(T.Contains(result.Error ?? string.Empty) ? T[result.Error!] : result.Error)
+
+
+ @T["Sales.Sections.PurchaseInvoices.Title"] + +
+
+ } + else + { + @if (_rejected.Count > 0) + { + + } + + + @T.Format("Purchases.Import.Selected", _selected.Count, T.Money(SelectedTotal)) + + + + @if (_invoices.Count == 0) + { +

@T["Purchases.Import.Start"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @for (var i = 0; i < _invoices.Count; i++) + { + var index = i; + var invoice = _invoices[i]; + + + + + + + + + + + + } + +
@T["Purchases.Fields.Supplier"]@T["Purchases.Import.VatNumber"]@T["Purchases.Import.Type"]@T["Purchases.Fields.SupplierNumber"]@T["Purchases.Fields.SupplierDate"]@T["Sales.Totals.Total"]@T["Purchases.Import.Check"]@T["Purchases.Import.View"]
+ + + @invoice.File.Supplier.DisplayName + @if (invoice.SupplierId is null) + { + @T["Purchases.Import.NewSupplier"] + } + @(invoice.File.Supplier.CountryCode)@invoice.File.Supplier.VatNumber@invoice.Invoice.DocumentType @(invoice.DocumentTypeCode is { } code ? "→ " + code : null)@invoice.Invoice.Number@T.Date(invoice.Invoice.Date)@T.Money(invoice.Total) + @if (invoice.Problems.Count == 0) + { + @T["Purchases.Import.Ready"] + } + @foreach (var problem in invoice.Problems) + { + @T[problem + ".short"] + } +
+
+ } +
+
+ } +
+
+ + + + @if (_shown is { } shown) + { + var supplier = shown.File.Supplier; + var invoice = shown.Invoice; +
+
+
@T["Purchases.Fields.Supplier"]
+
@supplier.DisplayName
@supplier.Address @supplier.StreetNumber, @supplier.PostalCode @supplier.City @(supplier.Province is null ? null : "(" + supplier.Province + ")")
+
@T["Purchases.Import.VatNumber"]
@supplier.CountryCode@supplier.VatNumber @(supplier.TaxCode is null ? null : " · " + supplier.TaxCode)
+
@T["Purchases.Import.Type"]
@invoice.DocumentType · @invoice.Currency
+
@T["Purchases.Fields.SupplierNumber"]
@invoice.Number · @T.Date(invoice.Date)
+ @if (invoice.Causals.Count > 0) + { +
@T["Purchases.Import.Causal"]
@string.Join(" ", invoice.Causals)
+ } + @if (shown.File.Signature is { } signature) + { +
@T["Purchases.Import.Signature"]
+
+ @T[signature.Verified ? "Purchases.Import.SignatureOk" : "Purchases.Import.SignatureKo"] + @signature.Signer +
+ } +
+
+ + + + + + + + + + + + + + @foreach (var line in invoice.Lines) + { + + + + + + + + + + } + +
#@T["Items.Fields.Code"]@T["Items.Fields.Description"]@T["Inventory.Movements.Quantity"]@T["Inventory.Reorder.Price"]@T["Sales.Totals.Taxable"]@T["Purchases.Import.Rate"]
@line.Number@string.Join(" ", line.Codes.Select(c => c.Value))@line.Description@(line.Quantity is { } q ? q.ToString("#,##0.###", T.Culture) + " " + line.Unit : null)@T.Money(line.UnitPrice)@T.Money(line.TotalPrice)@(line.Nature ?? line.TaxRate.ToString("0.##", T.Culture) + "%")
+
+ + @if (invoice.Payments.Count > 0) + { +
    + @foreach (var payment in invoice.Payments) + { +
  • @T["Purchases.Import.Payment"] @(payment.DueDate is { } due ? T.Date(due) : null) · @T.Money(payment.Amount) @(payment.Iban is null ? null : " · " + payment.Iban)
  • + } +
+ } +
+ } +
+
+ +
+
+} + +@code { + private readonly HashSet _selected = []; + private List _invoices = []; + private List _rejected = []; + private List _results = []; + private IncomingCandidate? _shown; + private bool _loaded; + private bool _busy; + private int _step; + + private IReadOnlyList Steps => + [ + new(T["Purchases.Import.Steps.Load"], T["Purchases.Import.Steps.LoadDetail"]), + new(T["Purchases.Import.Steps.Check"], T["Purchases.Import.Steps.CheckDetail"]), + new(T["Purchases.Import.Steps.Register"], T["Purchases.Import.Steps.RegisterDetail"]), + ]; + + private IEnumerable Importable => Enumerable.Range(0, _invoices.Count).Where(i => _invoices[i].CanImport); + + private decimal SelectedTotal => _selected.Sum(i => _invoices[i].Total); + + private string ShownTitle => _shown is { } shown ? shown.File.Supplier.DisplayName + " · " + shown.Invoice.Number : T["Purchases.Import.View"]; + + private IReadOnlyList SummaryOf(IncomingInvoice invoice) => + [ + new(T["Sales.Totals.Taxable"], T.Money(invoice.TaxSummary.Sum(t => t.Taxable))), + new(T["Sales.Totals.Tax"], T.Money(invoice.TaxSummary.Sum(t => t.Tax))), + new(T["Sales.Totals.Total"], T.Money(invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax))), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } + + private async Task ReadAsync(InputFileChangeEventArgs e) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var files = new List<(string, byte[])>(); + foreach (var file in e.GetMultipleFiles(200)) + { + using var buffer = new MemoryStream(); + await using (var stream = file.OpenReadStream(PurchaseInvoiceImportService.MaxFileSize)) + { + await stream.CopyToAsync(buffer); + } + + files.Add((file.Name, buffer.ToArray())); + } + + var reading = await Import.ReadAsync(actor, company, files); + _invoices = [.. reading.Invoices]; + _rejected = [.. reading.Rejected]; + _results.Clear(); + _selected.Clear(); + _selected.UnionWith(Importable); + _step = _invoices.Count > 0 ? 1 : 0; + } + catch (IOException) + { + Toasts.Show(ToastKind.Error, T["Purchases.Import.TooLarge"]); + } + finally + { + _busy = false; + } + } + + private void Toggle(int index, bool on) + { + if (on) + { + _selected.Add(index); + } + else + { + _selected.Remove(index); + } + } + + private void ToggleAll(ChangeEventArgs e) + { + _selected.Clear(); + if (e.Value is true) + { + _selected.UnionWith(Importable); + } + } + + private async Task ImportAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + _results = [.. await Import.ImportAsync(actor, company, [.. _selected.Order().Select(i => _invoices[i])])]; + _step = 2; + var made = _results.Count(r => r.Record is not null); + Toasts.Show(made == _results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("Purchases.Import.Done", made, _results.Count)); + } + finally + { + _busy = false; + } + } + + private void Restart() + { + _results.Clear(); + _invoices.Clear(); + _rejected.Clear(); + _selected.Clear(); + _step = 0; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor index cf5330b..24c398b 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor @@ -1,7 +1,12 @@ @page "/vendite/{Segment}/nuovo" @page "/vendite/{Segment}/{Id:long}" +@page "/acquisti/{Segment}/nuovo" +@page "/acquisti/{Segment}/{Id:long}" +@page "/magazzino/{Segment}/nuovo" +@page "/magazzino/{Segment}/{Id:long}" @attribute [Authorize] @inherits DocumentPage +@using Khaemhat.Application.Purchases @using Khaemhat.Application.Audit @using Khaemhat.Application.Documents @using Khaemhat.Application.Items @@ -11,8 +16,9 @@ @using Khaemhat.Web.Documents @using Khaemhat.Web.Parties -@* The record of a sales document (SPEC §11.3, mockups 020-022 and 026-029): quotation, order, delivery note, invoice of - every kind, pro forma, credit and debit note. Righe first with the VAT summary, due dates and totals underneath, then +@* The record of a document (SPEC §11.3-§11.6, mockups 020-022, 026-029, 031-033, 035, 037): quotation, order, delivery + note, invoice of every kind, pro forma, credit and debit note; supplier order, receipt, supplier invoice and credit + note with protocol and VAT date, self-invoice; warehouse movement with reason and warehouses. Righe first with the VAT summary, due dates and totals underneath, then Testata, Trasporto for the documents that move goods, Totali, Scadenze, Note, Allegati, Collegamenti, Storico. The totals are computed while typing with the code of the save; the actions follow the state machine of the engine. *@ @@ -46,8 +52,8 @@ else var h = Record.Header; - @T["Sales.Fields.DocumentDate"] @T.Date(h.DocumentDate) @@ -104,7 +110,29 @@ else @switch (ActiveTab) { case TabIds.Lines: - @if (h.PartyId is null && !IsReadOnly) + @if (_differences.Count > 0) + { +
+ @(_differences.Count == 1 ? T.Format("Purchases.PriceDifferences.SummaryOne", T.Money(_differences[0].Amount)) : T.Format("Purchases.PriceDifferences.Summary", _differences.Count, T.Money(_differences.Sum(d => d.Amount)))) + @foreach (var difference in _differences.Take(5)) + { +
@T.Format("Purchases.PriceDifferences.Line", difference.LineNumber, difference.Description, difference.SourceNumber ?? string.Empty, + T.Money(difference.SourcePrice), T.Money(difference.InvoicePrice)) + } +
+
+ } + @if (_selfAdvice is { } advice) + { +
+ @T.Format("Purchases.SelfInvoices.Advice", advice.DocumentTypeCode, Sentence(advice.Reason), T.Date(advice.Deadline)) + @if (Session.Permissions.Allows(PurchaseService.WritePermission) && DocumentStateMachine.IsInForce(h.Status)) + { + + } +
+ } + @if (h.PartyId is null && !IsReadOnly && !IsInternal) {
@T["Sales.Hints.PartyFirst"]
@@ -143,9 +171,17 @@ else { } - - + + + @if (IsRegistered) + { + + + } @if (IsNote) { } + @if (IsInternal) + { + + + + @if (IsTransfer) + { + + } +

@T["Inventory.Hints.Movement"]

+
+ } + else + { - - + @if (!IsPurchase) + { + + } @if (h.PartyId is not null) @@ -203,6 +259,7 @@ else

@T["Sales.Hints.Withholding"]

} + } break; @@ -297,11 +354,11 @@ else @if (SalesScreens.RecordUrl(link.Kind, link.Id) is { } url) { - @(link.DocumentNumber ?? T["Sales.DraftNumber"]) + @SalesScreens.Number(T, link.DocumentNumber, link.Status) } else { - @(link.DocumentNumber ?? T["Sales.DraftNumber"]) + @SalesScreens.Number(T, link.DocumentNumber, link.Status) } @T.Date(link.Date) diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs index e52d490..2d2e1b3 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs @@ -5,12 +5,14 @@ using Khaemhat.Application.Files; using Khaemhat.Application.Items; using Khaemhat.Application.Localization; using Khaemhat.Application.Parties; +using Khaemhat.Application.Purchases; using Khaemhat.Application.Querying; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Common; using Khaemhat.Core.Documents; using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; using Khaemhat.Web.Components.Ui; using Khaemhat.Web.Documents; using Khaemhat.Web.Parties; @@ -34,6 +36,8 @@ public sealed partial class SalesDocumentPage private PartyRow? _party; private IReadOnlyList _actions = []; private IReadOnlyList _links = []; + private IReadOnlyList _differences = []; + private SelfInvoiceAdvice? _selfAdvice; private IReadOnlyList _history = []; private int _attachments; private bool _loaded; @@ -100,6 +104,9 @@ public sealed partial class SalesDocumentPage [Inject] private TimeProvider Clock { get; set; } = default!; + [Inject] + private PurchaseService Purchases { get; set; } = default!; + private DocumentHeader H => Record!.Header; private DocumentBehavior Behavior => DocumentBehaviors.Of(Record!.Header.Kind); @@ -108,9 +115,12 @@ public sealed partial class SalesDocumentPage private string PageTitle => Record is null || _definition is null ? T["Shell.Menu.Sales"] - : _definition.Type.Description + " " + (Record.Header.DocumentNumber ?? T["Sales.DraftNumber"]); + : _definition.Type.Description + " " + SalesScreens.Number(T, Record.Header.DocumentNumber, Record.Header.Status); - private bool IsInvoice => Record is not null && (Behavior.Lifecycle == DocumentLifecycle.Invoice || H.Kind == DocumentKind.ProForma); + private bool IsInvoice => Record is not null && (Behavior.Lifecycle == DocumentLifecycle.Invoice || H.Kind == DocumentKind.ProForma || IsRegistered); + + // A movement between two warehouses: its reason is a transfer. + private bool IsTransfer => Record is not null && H.InventoryReasonId is { } reason && _lookups.TransferReasons.Contains(reason); private bool IsNote => Record is not null && H.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote; @@ -119,7 +129,17 @@ public sealed partial class SalesDocumentPage private bool CanWrite => Record is not null && Session.Permissions.Allows(Behavior.WritePermission); // The entity of the attachments, such as sales.saledocument. - private string AttachmentEntity => "sales." + Record!.Header.GetType().Name.ToLowerInvariant(); + private string AttachmentEntity => DocumentPrintService.EntityOf(Record!.Family); + + // Customers for sales, suppliers for purchases and self-invoices. + private PartyArchive Archive => _section?.Direction == DocumentDirection.Purchase ? PartyArchive.Suppliers : PartyArchive.Customers; + + private bool IsPurchase => _section?.Direction == DocumentDirection.Purchase; + + private bool IsInternal => _section?.Direction == DocumentDirection.Internal; + + // A supplier invoice or credit note: registered with a protocol and a VAT date. + private bool IsRegistered => Record is not null && H.Kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote; /// public override bool IsReadOnly => Record is null || !CanWrite || !(IsNew || _actions.Contains(DocumentAction.Edit)); @@ -154,7 +174,7 @@ public sealed partial class SalesDocumentPage TabOf(TabIds.Lines, "list", "Ui.Record.Tabs.Lines", Record.Lines.Count), TabOf(TabIds.Header, "file", "Ui.Record.Tabs.Header"), }; - if (Behavior.Has(DocumentEffects.Inventory)) + if (Behavior.Has(DocumentEffects.Inventory) && !IsInternal) { tabs.Add(TabOf(SalesScreens.TransportTab, "truck", "Sales.Tabs.Transport")); } @@ -214,7 +234,7 @@ public sealed partial class SalesDocumentPage return; } - _section = SalesScreens.Find(Segment); + _section = SalesScreens.Find(SalesScreens.AreaOf(Navigation.ToBaseRelativePath(Navigation.Uri)), Segment); if (!_loaded) { _lookups = await DocumentLookups.ReadAsync(Tables, actor, company); @@ -302,16 +322,56 @@ public sealed partial class SalesDocumentPage _links = []; _history = []; _attachments = 0; + _differences = []; + _selfAdvice = null; return; } _links = await Editor.LinksAsync(actor, company, Record); + await LoadPurchaseChecksAsync(actor, company); _history = await Audit.HistoryAsync(actor, company, Record.Header.GetType().Name, Record.Header.Id.ToString(CultureInfo.InvariantCulture), Behavior.ReadPermission); _attachments = Session.Permissions.Allows(AttachmentService.ReadPermission) ? await Attachments.CountAsync(actor, company, AttachmentEntity, Record.Header.Id) : 0; } + // A supplier invoice: the prices that differ from its order or receipt, and the self-invoice it needs. + // A reason ends with one full stop, whether the fiscal pack wrote it or not. + private static string Sentence(string text) => text.EndsWith('.') ? text : text + "."; + + private async Task LoadPurchaseChecksAsync(Actor actor, string company) + { + _differences = []; + _selfAdvice = null; + if (Record is null || H.Kind != DocumentKind.PurchaseInvoice || !Session.Permissions.Allows(PurchaseService.ReadPermission)) + { + return; + } + + _differences = await Purchases.PriceDifferencesAsync(actor, company, Record); + _selfAdvice = _links.Any(l => l.Kind == DocumentKind.SelfInvoice && l.Status != DocumentStatus.Cancelled) + ? null + : await Purchases.AdviseAsync(actor, company, Record); + } + + private async Task CreateSelfInvoiceAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Record is null || _selfAdvice is not { } advice) + { + return; + } + + try + { + var self = await Purchases.CreateSelfInvoiceAsync(actor, company, H.Id, advice.DocumentTypeCode); + Navigation.NavigateTo(SalesScreens.RecordUrl(self.Header.Kind, self.Header.Id)!); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); + } + } + // ---- Head ------------------------------------------------------------------------------------------------------- private IReadOnlyList PartyLines @@ -847,10 +907,10 @@ public sealed partial class SalesDocumentPage private async Task> SearchPartiesAsync(string text, CancellationToken cancellationToken) => Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) - ? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken) + ? await Parties.SearchAsync(actor, company, Archive, text, cancellationToken) : []; - private void OpenParty(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, row.Id)); + private void OpenParty(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(Archive, row.Id)); private void Change(Action change) { @@ -1100,11 +1160,14 @@ public sealed partial class SalesDocumentPage // An order-like document gives what is left to fulfil; an issued invoice gives its notes. var open = H.Status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled; var issued = Behavior.Lifecycle == DocumentLifecycle.Invoice && DocumentStateMachine.IsInForce(H.Status); + + // A registered supplier invoice gives its credit notes and self-invoices. + var registered = IsRegistered && DocumentStateMachine.IsInForce(H.Status); var preferred = SalesScreens.Sections.SelectMany(s => s.NewTypes).ToList(); return _definitions - .Where(d => d.Behavior.Direction == DocumentDirection.Sale && d.Behavior.Fulfils(H.Kind) && preferred.Contains(d.Code) + .Where(d => d.Behavior.Direction == Behavior.Direction && d.Behavior.Fulfils(H.Kind) && preferred.Contains(d.Code) && Session.Permissions.Allows(d.Behavior.WritePermission) - && (d.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote ? issued : open)) + && (d.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote or DocumentKind.PurchaseCreditNote or DocumentKind.SelfInvoice ? issued || registered : open)) .OrderBy(d => Preference(H.Kind, d.Kind)) .ThenBy(d => preferred.IndexOf(d.Code)); } @@ -1117,6 +1180,9 @@ public sealed partial class SalesDocumentPage (DocumentKind.DeliveryNote, DocumentKind.DeferredInvoice) => 0, (DocumentKind.ProForma, DocumentKind.ImmediateInvoice) => 0, (_, DocumentKind.CreditNote) => 0, + (DocumentKind.PurchaseOrder, DocumentKind.PurchaseDeliveryNote) => 0, + (DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice) => 0, + (_, DocumentKind.PurchaseCreditNote) => 0, _ => 1, }; diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor index 1d436bc..54381f8 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor @@ -1,4 +1,6 @@ @page "/vendite/{Segment}" +@page "/acquisti/{Segment}" +@page "/magazzino/{Segment}" @attribute [Authorize] @using Khaemhat.Application.Documents @using Khaemhat.Core.Documents @@ -9,9 +11,10 @@ @inject NavigationManager Navigation @inject TimeProvider Clock -@* The radar of a kind of sales documents (SPEC §11.3): quotations, orders, delivery notes, invoices (with pro forma - and fees), credit and debit notes. Search on number, reference and customer; filters for state, type and year; - totals of the page. Enter or double click opens the document. *@ +@* The radar of a kind of documents (SPEC §11.3-§11.6): quotations, orders, delivery notes, invoices (with pro forma + and fees), credit and debit notes; supplier orders, receipts, supplier invoices, self-invoices; warehouse + movements. Search on number, reference and party; filters for state, type and year; totals of the page. Enter or + double click opens the document. *@ @if (!_loaded) @@ -36,7 +39,11 @@ else if (!CanRead) } else { - + } + @@ -44,10 +51,14 @@ else { } - @if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write")) + @if (_section.Area == SalesScreens.BasePath && _section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write")) { @T["Sales.Deferred.Title"] } + @if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "fatture" && Session.Permissions.Allows("purchases.invoice.write")) + { + @T["Shell.Menu.Purchases.Import"] + } @@ -79,6 +90,8 @@ else private string Title => _section is null ? T["Shell.Menu.Sales"] : T["Sales.Sections." + _section.Key + ".Title"]; + private bool Internal => _section?.Direction == DocumentDirection.Internal; + private bool CanRead => _section is not null && Session.Permissions.Allows(DocumentBehaviors.Of(_section.Kinds[0]).ReadPermission); private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); @@ -90,15 +103,15 @@ else private IReadOnlyList> Columns => [ - new("number", T["Sales.Fields.DocumentNumber"], r => r.DocumentNumber ?? T["Sales.DraftNumber"]) { Kind = KhColumnKind.Code, Width = "130px" }, + new("number", T[_section?.Kinds.Contains(DocumentKind.PurchaseInvoice) == true ? "Purchases.Fields.Protocol" : "Sales.Fields.DocumentNumber"], r => SalesScreens.Number(T, r.DocumentNumber, r.Status)) { Kind = KhColumnKind.Code, Width = "130px" }, new("date", T["Sales.Fields.DocumentDate"], r => r.Date) { Kind = KhColumnKind.Date, Width = "100px" }, new("type", T["Sales.Radar.Kind"], r => SalesScreens.KindName(T, r.Kind)) { Width = "150px", Sortable = false, Visible = _section?.Kinds.Count > 1 }, - new("party", T["Sales.Fields.PartyId"], r => r.PartyName) { Sortable = false }, - new("reference", T["Sales.Fields.ExternalReference"], r => r.Reference) { Width = "140px" }, + new("party", T[SalesScreens.PartyLabel(_section?.Direction ?? DocumentDirection.Sale)], r => r.PartyName) { Sortable = false, Visible = !Internal }, + new("reference", T[_section?.Direction == DocumentDirection.Purchase ? "Purchases.Fields.SupplierNumber" : "Sales.Fields.ExternalReference"], r => r.Reference) { Width = "140px" }, new("validUntil", T["Sales.Fields.ValidUntil"], r => r.ValidUntil) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment == "preventivi" }, - new("delivery", T["Sales.Fields.DeliveryDate"], r => r.DeliveryDate) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment is "ordini" or "ddt" }, - new("taxable", T["Sales.Totals.Taxable"], r => r.Taxable) { Kind = KhColumnKind.Money, Width = "120px" }, - new("total", T["Sales.Totals.Total"], r => r.Total) { Kind = KhColumnKind.Money, Width = "120px" }, + new("delivery", T["Sales.Fields.DeliveryDate"], r => r.DeliveryDate) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment is "ordini" or "ddt" or "ricevimenti" }, + new("taxable", T["Sales.Totals.Taxable"], r => r.Taxable) { Kind = KhColumnKind.Money, Width = "120px", Visible = !Internal }, + new("total", T["Sales.Totals.Total"], r => r.Total) { Kind = KhColumnKind.Money, Width = "120px", Visible = !Internal }, new("status", T["Sales.Radar.State"], r => StateOf(r).Text) { Width = "130px", @@ -136,7 +149,7 @@ else protected override async Task OnParametersSetAsync() { await Session.EnsureLoadedAsync(); - _section = SalesScreens.Find(Segment); + _section = SalesScreens.Find(SalesScreens.AreaOf(Navigation.ToBaseRelativePath(Navigation.Uri)), Segment); if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company) { _definitions = await Engine.DefinitionsAsync(actor, company); diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor index d6c7b9d..06af393 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor @@ -1,4 +1,6 @@ @page "/vendite/{Segment}/{Id:long}/stampa" +@page "/acquisti/{Segment}/{Id:long}/stampa" +@page "/magazzino/{Segment}/{Id:long}/stampa" @attribute [Authorize] @using Khaemhat.Application.Documents @using Khaemhat.Application.Security @@ -9,6 +11,7 @@ @inject DocumentEngine Engine @inject FileGenerationService Generation @inject ToastService Toasts +@inject NavigationManager Navigation @* The print preview of a sales document (SPEC §9.4, issue #52, mockup 025): the A4 sheet in HTML from the same model as the PDF, with Stampa (the print of the browser), the PDF made by Khaemhat and "Salva come allegato", which keeps @@ -172,13 +175,13 @@ else private string Heading => _model is null ? T["Sales.Print.Title"] : T.Format("Sales.Print.Heading", _model.Title, _model.Number); - private string BackUrl => _section is null ? SalesScreens.BasePath : SalesScreens.BasePath + "/" + _section.Segment + "/" + Id.ToString(T.Culture); + private string BackUrl => _section is null ? SalesScreens.BasePath : SalesScreens.RadarUrl(_section) + "/" + Id.ToString(T.Culture); /// protected override async Task OnParametersSetAsync() { await Session.EnsureLoadedAsync(); - _section = SalesScreens.Find(Segment); + _section = SalesScreens.Find(SalesScreens.AreaOf(Navigation.ToBaseRelativePath(Navigation.Uri)), Segment); if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) { _missing = true; diff --git a/src/Khaemhat.Web/Components/Purchases/PendingSelfInvoicesPanel.razor b/src/Khaemhat.Web/Components/Purchases/PendingSelfInvoicesPanel.razor new file mode 100644 index 0000000..637600e --- /dev/null +++ b/src/Khaemhat.Web/Components/Purchases/PendingSelfInvoicesPanel.razor @@ -0,0 +1,98 @@ +@using Khaemhat.Application.Purchases +@using Khaemhat.Application.Security +@using Khaemhat.Web.Documents +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject PurchaseService Purchases +@inject ToastService Toasts +@inject NavigationManager Navigation +@inject TimeProvider Clock + +@* The supplier invoices still waiting for their self-invoice (SPEC §11.5, mockup 035): reverse charge from Italian + suppliers, services and goods from abroad, San Marino; the type to issue, why, and the deadline. One click creates + the self-invoice as a draft. *@ +@if (_pending is { Count: > 0 } pending) +{ + + @T.Number(pending.Count) + +
+ + + + + + + + + + + + + + @foreach (var item in pending) + { + var row = item.Invoice; + + + + + + + + + + } + +
@T["Purchases.SelfInvoices.Invoice"]@T["Purchases.Fields.Supplier"]@T["Sales.Totals.Taxable"]@T["Purchases.SelfInvoices.Type"]@T["Purchases.SelfInvoices.Reason"]@T["Purchases.SelfInvoices.Deadline"]@T["Purchases.SelfInvoices.Create"]
@row.DocumentNumber · @T.Date(row.Date)@row.PartyName@T.Money(row.Taxable)@item.Advice.DocumentTypeCode@item.Advice.Reason@T.Date(item.Advice.Deadline) + @if (CanWrite) + { + + } +
+
+
+
+} + +@code { + private IReadOnlyList? _pending; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(PurchaseService.WritePermission); + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PurchaseService.ReadPermission)) + { + _pending = await Purchases.PendingSelfInvoicesAsync(actor, company); + } + } + + private async Task CreateAsync(PendingSelfInvoice item) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var self = await Purchases.CreateSelfInvoiceAsync(actor, company, item.Invoice.Id, item.Advice.DocumentTypeCode); + Navigation.NavigateTo(SalesScreens.RecordUrl(self.Header.Kind, self.Header.Id)!); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Documents/DocumentLookups.cs b/src/Khaemhat.Web/Documents/DocumentLookups.cs index 33244b9..eb00d81 100644 --- a/src/Khaemhat.Web/Documents/DocumentLookups.cs +++ b/src/Khaemhat.Web/Documents/DocumentLookups.cs @@ -33,6 +33,12 @@ public sealed class DocumentLookups /// Warehouses. public IReadOnlyList> Warehouses { get; private init; } = []; + /// Warehouse reasons (causali di magazzino). + public IReadOnlyList> InventoryReasons { get; private init; } = []; + + /// The ids of the reasons that move goods between two warehouses. + public IReadOnlySet TransferReasons { get; private init; } = new HashSet(); + /// Carriers. public IReadOnlyList> Carriers { get; private init; } = []; @@ -68,6 +74,8 @@ public sealed class DocumentLookups Salespeople = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), BankAccounts = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), Warehouses = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + InventoryReasons = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + TransferReasons = (await tables.ActiveAsync(actor, company, cancellationToken).ConfigureAwait(false)).Where(r => r.IsTransfer).Select(r => r.Id).ToHashSet(), Carriers = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), ShippingTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), TransportReasons = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), diff --git a/src/Khaemhat.Web/Documents/SalesScreens.cs b/src/Khaemhat.Web/Documents/SalesScreens.cs index 6f05be7..5c1ee73 100644 --- a/src/Khaemhat.Web/Documents/SalesScreens.cs +++ b/src/Khaemhat.Web/Documents/SalesScreens.cs @@ -5,24 +5,37 @@ using Khaemhat.Web.Ui; namespace Khaemhat.Web.Documents; -/// A radar of the sales menu and the document types it holds. +/// A radar of the documents menus (sales, purchases, warehouse) and the document types it holds. /// The path segment, such as fatture. /// The family of the documents. /// The kinds shown. /// The document types a user can create from the radar, the first being the usual one. /// The icon. /// The key of the texts under Sales.Sections. -public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList Kinds, IReadOnlyList NewTypes, string Icon, string Key); +/// The menu area, such as vendite or acquisti. +public sealed record SalesSection( + string Segment, DocumentFamily Family, IReadOnlyList Kinds, IReadOnlyList NewTypes, string Icon, string Key, string Area = SalesScreens.BasePath) +{ + /// Whose documents: customers, suppliers or nobody. + public DocumentDirection Direction => DocumentBehaviors.Of(Kinds[0]).Direction; +} /// -/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under -/// /vendite, the record of a document under it, and the deferred invoicing. +/// Addresses and labels of the document screens (SPEC §11.3-§11.6, mockups 020-037): one radar per menu entry under +/// /vendite, /acquisti and /magazzino, the record of a document under it, and the deferred +/// invoicing. The screens are the same for every area; the labels follow the direction (customer or supplier). /// public static class SalesScreens { - /// The menu area. + /// The sales area. public const string BasePath = "vendite"; + /// The purchases area. + public const string PurchasesPath = "acquisti"; + + /// The warehouse area. + public const string InventoryPath = "magazzino"; + /// The deferred invoicing of the delivery notes. public const string DeferredInvoicingUrl = BasePath + "/fatturazione-differita"; @@ -39,12 +52,40 @@ public static class SalesScreens [DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.Fee, DocumentKind.ProForma], ["FI", "FA", "FD", "FACC", "PAR", "PF"], "euro", "Invoices"), new("note-credito", DocumentFamily.SaleDocument, [DocumentKind.CreditNote, DocumentKind.DebitNote], ["NC", "ND"], "undo", "CreditNotes"), + new("ordini", DocumentFamily.PurchaseOrder, [DocumentKind.PurchaseOrder], ["OF"], "file-check", "PurchaseOrders", PurchasesPath), + new("ricevimenti", DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseDeliveryNote], ["DDTF"], "truck", "Receipts", PurchasesPath), + new("fatture", DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseInvoice, DocumentKind.PurchaseCreditNote], ["FF", "NCF"], "euro", "PurchaseInvoices", PurchasesPath), + new("autofatture", DocumentFamily.SaleDocument, [DocumentKind.SelfInvoice], + ["AF16", "AF17", "AF18", "AF19", "AF20", "AF21", "AF22", "AF23", "AF28", "AF29"], "refresh", "SelfInvoices", PurchasesPath), + new("movimenti", DocumentFamily.InventoryDocument, [DocumentKind.InventoryEntry], ["MM"], "layers", "Movements", InventoryPath), ]; - /// The radar of a path segment. + /// The sales radar of a path segment. /// The segment. /// The radar, or . - public static SalesSection? Find(string? segment) => Sections.FirstOrDefault(s => string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase)); + public static SalesSection? Find(string? segment) => Find(BasePath, segment); + + /// The radar of an area and a path segment. + /// The area, such as acquisti. + /// The segment. + /// The radar, or . + public static SalesSection? Find(string? area, string? segment) => + Sections.FirstOrDefault(s => string.Equals(s.Area, area, StringComparison.OrdinalIgnoreCase) && string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase)); + + /// The area of a relative address: its first segment. + /// The address relative to the base, such as acquisti/fatture/3. + /// The area. + public static string AreaOf(string? relativePath) + { + var path = relativePath ?? string.Empty; + var end = path.IndexOfAny(['/', '?', '#']); + return end < 0 ? path : path[..end]; + } + + /// The key of the label of the party for a direction: customer, supplier. + /// The direction. + /// The key of the text. + public static string PartyLabel(DocumentDirection direction) => direction == DocumentDirection.Purchase ? "Purchases.Fields.Supplier" : "Sales.Fields.PartyId"; /// The radar that holds a kind of document. /// The kind. @@ -57,7 +98,7 @@ public static class SalesScreens public static string RadarUrl(SalesSection section) { ArgumentNullException.ThrowIfNull(section); - return BasePath + "/" + section.Segment; + return section.Area + "/" + section.Segment; } /// The address of a document. @@ -93,6 +134,20 @@ public static class SalesScreens return texts["Sales.Kinds." + kind]; } + /// + /// The number shown for a document: its own number, else "Bozza" for a draft and "Senza numero" for a confirmed + /// document of a type without numerator (a supplier delivery note, which keeps the supplier's number). + /// + /// The texts. + /// The document number. + /// The state. + /// The text. + public static string Number(ITexts texts, string? number, DocumentStatus status) + { + ArgumentNullException.ThrowIfNull(texts); + return number ?? texts[status == DocumentStatus.Draft ? "Sales.DraftNumber" : "Sales.NoNumber"]; + } + /// The label and tone of a state; a quotation shows its outcome (accepted, refused, expired). /// The texts. /// The kind. diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 142c091..2e19bf2 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -146,6 +146,12 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); // The document engine (ADR 0032): one engine, the copies, a typed service per family. @@ -178,6 +184,8 @@ internal static class KhaemhatServices services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index 0972cd0..bc58caf 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -132,6 +132,7 @@ public static class SeedCommand // The demo documents go through the document engine, after the masters they use. await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); + await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json index ea07685..b09b36b 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json +++ b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json @@ -125,7 +125,10 @@ }, "Understock": { "Title": "Sottoscorta", - "Description": "Gli articoli sotto la scorta minima." + "Description": "Gli articoli sotto la scorta minima o il punto di riordino.", + "Empty": "Nessun articolo sotto scorta.", + "Line": "Disponibile {0}, scorta {1}", + "Reorder": "Apri la proposta di riordino" }, "Pipeline": { "Title": "Pipeline CRM", diff --git a/src/Khaemhat.Web/Resources/it-IT/Documents.json b/src/Khaemhat.Web/Resources/it-IT/Documents.json index 6ac2981..80d7388 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Documents.json +++ b/src/Khaemhat.Web/Resources/it-IT/Documents.json @@ -41,6 +41,14 @@ "reason-required": "Per annullare una fattura indica il motivo.", "has-followers": "Altri documenti evadono questo: annulla prima quelli." }, + "purchase": { + "number-required": "Indica il numero e la data che il fornitore ha scritto sul documento.", + "duplicate": "Questo fornitore ha già un documento con lo stesso numero nello stesso anno: controlla di non registrarlo due volte.", + "vat-date-before": "La data di registrazione IVA non può precedere la data del documento del fornitore." + }, + "transfer": { + "destination": "Per un trasferimento indica il deposito d'arrivo, diverso da quello di partenza." + }, "copy": { "direction": "Si trasforma solo in un documento della stessa direzione (vendita o acquisto).", "nothing-left": "Non c'è più nulla da evadere.", diff --git a/src/Khaemhat.Web/Resources/it-IT/ImportExport.json b/src/Khaemhat.Web/Resources/it-IT/ImportExport.json index d1f53ad..fae9415 100644 --- a/src/Khaemhat.Web/Resources/it-IT/ImportExport.json +++ b/src/Khaemhat.Web/Resources/it-IT/ImportExport.json @@ -220,7 +220,7 @@ "target": "Indica il listino oppure il cliente, non entrambi." }, "stock": { - "not-stocked": "L'articolo {0} non è merce gestita a magazzino." + "reason-missing": "Manca la causale di magazzino APE (esistenza iniziale): aggiornala da Tabelle azienda, Aggiorna tabelle di base." }, "write": { "failed": "Riga non scritta: il dato è cambiato nel frattempo o una regola l'ha rifiutata." diff --git a/src/Khaemhat.Web/Resources/it-IT/Inventory.json b/src/Khaemhat.Web/Resources/it-IT/Inventory.json new file mode 100644 index 0000000..48ccf2a --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Inventory.json @@ -0,0 +1,174 @@ +{ + "Inventory": { + "NoReason": "Senza causale", + "Groups": { + "Movement": "Movimento" + }, + "Fields": { + "Reason": "Causale", + "Warehouse": "Deposito", + "FromWarehouse": "Dal deposito", + "ToWarehouse": "Al deposito" + }, + "Hints": { + "Movement": "La causale decide se il movimento carica, scarica o trasferisce; senza deposito vale quello dell’articolo." + }, + "NoCompany": "Scegli un'azienda per lavorare sul magazzino.", + "Levels": { + "Ok": "Disponibile", + "Reorder": "Da riordinare", + "Understock": "Sottoscorta", + "Out": "Esaurito" + }, + "Stock": { + "Title": "Giacenze e disponibilità", + "Search": "Cerca per codice o descrizione", + "AllWarehouses": "Tutti i depositi", + "IncludeEmpty": "Anche gli articoli senza giacenza", + "Items": "Articoli in giacenza", + "Understock": "Sottoscorta", + "Out": "Esauriti", + "Ordered": "Articoli in arrivo", + "TotalValue": "Valore di magazzino", + "OnHand": "Giacenza", + "Committed": "Impegnato", + "OrderedColumn": "Ordinato", + "Available": "Disponibile", + "Minimum": "Scorta min.", + "ReorderPoint": "Punto riordino", + "Value": "Valore", + "LastLoad": "Ultimo carico", + "LastUnload": "Ultimo scarico" + }, + "Movements": { + "Title": "Movimenti dell'articolo", + "ByWarehouse": "Giacenza per deposito", + "None": "Nessun movimento per questo articolo.", + "Date": "Data", + "Document": "Documento", + "Party": "Cliente o fornitore", + "Quantity": "Quantità", + "UnitCost": "Costo unitario", + "Balance": "Saldo", + "OpenItem": "Apri l'articolo" + }, + "Valuation": { + "Title": "Valorizzazione", + "Date": "Alla data", + "Method": "Criterio", + "Compute": "Calcola", + "Class": "Classe ABC", + "ClassA": "Classe A", + "ClassB": "Classe B", + "ClassC": "Classe C", + "Methods": { + "WeightedAverage": "Costo medio ponderato", + "LastCost": "Ultimo costo", + "StandardCost": "Costo standard" + }, + "Hint": "Classe A: gli articoli che fanno l'80% del valore; B fino al 95%; C il resto. FIFO e LIFO arriveranno con la contabilità di magazzino a lotti." + }, + "Rebuild": { + "Action": "Ricostruisci", + "Title": "Ricostruire il magazzino?", + "Text": "Tutti i movimenti vengono riscritti dai documenti in vigore e costi e giacenze ricalcolati. Su molti documenti può richiedere qualche minuto; i dati restano consultabili.", + "Progress": "Ricostruzione in corso: {0} {1} di {2}", + "Phases": { + "Documents": "documenti", + "Items": "articoli" + }, + "Done": "Magazzino ricostruito: {0} documenti, {1} articoli ricalcolati." + }, + "StockTake": { + "Title": "Inventario fisico", + "New": "Nuovo inventario", + "Open": "Apri inventario", + "Opened": "Inventario aperto con {0} articoli da contare.", + "Date": "Data del conteggio", + "Description": "Descrizione", + "DescriptionHint": "Vuota: deposito e data.", + "AllCategories": "Tutte le categorie", + "Hint": "L'inventario fotografa la giacenza contabile del deposito alla data scelta. Conta gli articoli, scrivi le quantità o importa il file del lettore, poi registra: le differenze diventano movimenti di rettifica INVP e INVN alla data del conteggio.", + "List": "Inventari", + "None": "Nessun inventario ancora.", + "Missing": "Questo inventario non esiste più.", + "Procedure": "Procedura", + "Movements": "Rettifiche", + "Lines": "Articoli da contare", + "Show": "Mostra", + "ShowAll": "Tutti", + "ShowToCount": "Da contare", + "ShowDifferences": "Con differenze", + "Import": "Importa conteggi", + "Save": "Salva conteggi", + "Saved": "Conteggi salvati.", + "Imported": "{0} articoli contati dal file, {1} codici non in lista.", + "FileTooLarge": "Il file è troppo grande: al massimo 5 MB.", + "Post": "Registra rettifiche", + "PostTitle": "Registrare l'inventario?", + "PostText": "Le differenze contate diventano movimenti di magazzino alla data del conteggio e l'inventario si chiude. Gli articoli non contati restano come sono.", + "Posted": "Inventario registrato.", + "Cancel": "Annulla inventario", + "CancelTitle": "Annullare l'inventario?", + "CancelText": "L'inventario si chiude senza muovere il magazzino; i conteggi restano consultabili.", + "Book": "Contabile", + "Counted": "Contato", + "Difference": "Differenza", + "DifferenceValue": "Valore differenze", + "ToCount": "Da contare", + "Matches": "Corrisponde", + "Differs": "Differenza", + "Items": "Articoli", + "CountedItems": "Contati", + "Differences": "Con differenze", + "States": { + "Open": "Aperto", + "Posted": "Registrato", + "Cancelled": "Annullato" + }, + "Steps": { + "Open": "Apertura", + "OpenDetail": "Deposito, data e categoria: giacenza contabile congelata.", + "Count": "Conteggio", + "CountDetail": "Quantità scritte o importate dal lettore.", + "Check": "Verifica differenze", + "CheckDetail": "Controlla gli scostamenti e il loro valore.", + "Post": "Registrazione", + "PostDetail": "Movimenti INVP e INVN alla data del conteggio." + } + }, + "Reorder": { + "Title": "Proposta di riordino", + "Lines": "Articoli da riordinare", + "None": "Nessun articolo da riordinare: le disponibilità coprono scorte minime e punti di riordino.", + "Selected": "{0} righe scelte, {1}", + "Refresh": "Ricalcola", + "Create": "Genera ordini fornitore", + "Created": "Ordini fornitore creati in bozza: {0}.", + "Quantity": "Da ordinare", + "Price": "Prezzo", + "Expected": "Arrivo previsto", + "ChooseSupplier": "Scegli il fornitore", + "MissingSupplier": "Le righe senza fornitore non vengono ordinate.", + "Items": "Articoli sotto il punto di riordino", + "Suppliers": "Fornitori coinvolti", + "Value": "Valore stimato", + "WithoutSupplier": "Senza fornitore", + "Hint": "La quantità proposta è il lotto di riordino dell'articolo, oppure quanto riporta al punto di riordino o alla scorta minima, almeno il minimo d'ordine del fornitore. Gli ordini nascono in bozza: controllali e confermali da Acquisti, Ordini fornitore." + } + }, + "inventory": { + "stock-take": { + "not-open": "L'inventario è già stato registrato o annullato: non si può più modificare.", + "nothing-counted": "Non hai contato nessun articolo: inserisci almeno una quantità prima di registrare.", + "negative": "Una quantità contata non può essere negativa.", + "reason-missing": "Mancano le causali di rettifica inventariale INVP e INVN: aggiornale da Tabelle azienda, Aggiorna tabelle di base." + }, + "warehouse": { + "missing": "Il deposito non esiste più." + }, + "reorder": { + "choice-invalid": "Ogni riga da ordinare deve avere un fornitore e una quantità maggiore di zero." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Purchases.json b/src/Khaemhat.Web/Resources/it-IT/Purchases.json new file mode 100644 index 0000000..4689ab9 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Purchases.json @@ -0,0 +1,92 @@ +{ + "Purchases": { + "Fields": { + "Supplier": "Fornitore", + "SupplierNumber": "N. documento fornitore", + "SupplierDate": "Data documento fornitore", + "Protocol": "Protocollo", + "VatDate": "Data registrazione IVA" + }, + "Hints": { + "SupplierNumber": "Il numero scritto dal fornitore sulla sua fattura o sul DDT.", + "VatDate": "Il mese in cui l’IVA entra in detrazione; vuota, vale la data di registrazione." + }, + "Import": { + "Title": "Importa fatture passive", + "Procedure": "Procedura", + "Files": "File da importare", + "FilesHint": "XML FatturaPA, file firmati .p7m o archivi ZIP che li contengono; anche più file insieme.", + "Invoices": "Fatture nei file", + "Start": "Carica i file ricevuti dallo SDI o dal tuo intermediario: le fatture appaiono qui per il controllo.", + "Selected": "{0} fatture scelte, {1}", + "Register": "Registra in bozza", + "Results": "Fatture registrate", + "Draft": "Documento in bozza", + "Check": "Da controllare", + "NewSupplier": "Nuovo fornitore", + "VatNumber": "Partita IVA", + "Type": "Tipo", + "Ready": "Pronta", + "View": "Leggi", + "Causal": "Causale", + "Signature": "Firma", + "SignatureOk": "Firma verificata", + "SignatureKo": "Firma non verificata", + "Lines": "Righe della fattura", + "Rate": "IVA", + "Summary": "Riepilogo", + "Payment": "Pagamento", + "Rejected": "{0} file non letti", + "Done": "Registrate {0} fatture su {1}: controllale e confermale per protocollarle.", + "Again": "Importa altri file", + "TooLarge": "Un file supera la dimensione massima di 50 MB.", + "Steps": { + "Load": "Caricamento", + "LoadDetail": "XML, P7M o ZIP.", + "Check": "Controllo", + "CheckDetail": "Fornitore, duplicati e totali.", + "Register": "Registrazione", + "RegisterDetail": "Fatture in bozza con il file allegato." + } + }, + "SelfInvoices": { + "Pending": "Integrazioni da emettere", + "Invoice": "Fattura fornitore", + "Type": "Tipo", + "Reason": "Motivo", + "Deadline": "Entro il", + "Create": "Crea autofattura", + "Advice": "Serve un'autofattura {0}: {1} Da emettere entro il {2}." + }, + "PriceDifferences": { + "Summary": "{0} righe hanno un prezzo diverso dall'ordine o dal ricevimento: differenza totale {1}.", + "SummaryOne": "Una riga ha un prezzo diverso dall'ordine o dal ricevimento: differenza {0}.", + "Line": "Riga {0}, {1}: {2} a {3}, in fattura {4}." + } + }, + "purchase": { + "self-invoice": { + "not-needed": "Per questa fattura non serve un'autofattura: il fornitore applica già l'IVA italiana." + }, + "import": { + "unsupported-type": "Questo tipo di documento non è un acquisto da registrare (per esempio un'autofattura emessa dall'azienda).", + "duplicate": "Fattura già registrata: lo stesso fornitore ha un documento con questo numero nello stesso anno.", + "total-mismatch": "Il totale indicato nel file non corrisponde alle righe: controlla la bozza prima di confermarla.", + "signature": "La firma del file non è stata verificata: controlla la provenienza.", + "document-discount": "Il file contiene sconti o maggiorazioni sul totale: riportali a mano nella bozza.", + "tax-code": "Nessun codice IVA dell'azienda ha l'aliquota o la natura di una riga: aggiungilo in Tabelle azienda, Codici IVA.", + "empty": "Nei file non ci sono fatture elettroniche.", + "unsupported-type.short": "Non è un acquisto", + "duplicate.short": "Già registrata", + "total-mismatch.short": "Totale diverso", + "signature.short": "Firma non verificata", + "document-discount.short": "Sconto sul totale" + } + }, + "incoming": { + "not-readable": "Il file non è una fattura elettronica leggibile: carica un XML FatturaPA, un file firmato .p7m o uno ZIP che li contiene.", + "not-invoice": "Il file XML non è una FatturaPA.", + "signature-broken": "La firma del file .p7m non è valida: il contenuto potrebbe essere stato alterato.", + "invalid": "La fattura elettronica non è conforme al tracciato FatturaPA." + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Sales.json b/src/Khaemhat.Web/Resources/it-IT/Sales.json index 1c01d68..4698eab 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Sales.json +++ b/src/Khaemhat.Web/Resources/it-IT/Sales.json @@ -4,6 +4,7 @@ "NotFound": "Documento non trovato", "BackToList": "Torna all'elenco", "DraftNumber": "Bozza", + "NoNumber": "Senza numero", "NumberOnConfirm": "Assegnato alla conferma", "NoParty": "Cliente da scegliere", "Demo": "Dato dimostrativo", @@ -13,7 +14,12 @@ "Orders": { "Title": "Ordini clienti", "New": "Nuovo ordine" }, "DeliveryNotes": { "Title": "Documenti di trasporto", "New": "Nuovo DDT" }, "Invoices": { "Title": "Fatture di vendita", "New": "Nuova fattura" }, - "CreditNotes": { "Title": "Note di credito e di debito", "New": "Nuova nota" } + "CreditNotes": { "Title": "Note di credito e di debito", "New": "Nuova nota" }, + "PurchaseOrders": { "Title": "Ordini fornitori", "New": "Nuovo ordine fornitore" }, + "Receipts": { "Title": "Ricevimenti merce", "New": "Nuovo ricevimento" }, + "PurchaseInvoices": { "Title": "Fatture passive", "New": "Registra fattura" }, + "SelfInvoices": { "Title": "Autofatture e integrazioni", "New": "Nuova autofattura" }, + "Movements": { "Title": "Movimenti di magazzino", "New": "Nuovo movimento" } }, "Kinds": { "Quotation": "Preventivo", @@ -173,7 +179,13 @@ "CreditNote": "TD04, storna in tutto o in parte una fattura.", "DebitNote": "TD05, aggiunge importi a una fattura.", "Fee": "TD06, per i professionisti, con ritenuta e cassa.", - "ProForma": "Non fiscale: anticipa la fattura al cliente." + "ProForma": "Non fiscale: anticipa la fattura al cliente.", + "SelfInvoice": "TD16-TD29: integra la fattura del fornitore o regolarizza un acquisto.", + "PurchaseOrder": "Ordine al fornitore: la merce ordinata entra nelle disponibilità.", + "PurchaseDeliveryNote": "Carica il magazzino al costo della riga, dall’ordine o libero.", + "PurchaseInvoice": "Registrata con protocollo e data IVA; carica la merce non ricevuta con DDT.", + "PurchaseCreditNote": "Storna una fattura del fornitore; restituisce la merce resa.", + "InventoryEntry": "Carico, scarico o trasferimento manuale con la sua causale." } }, "Lines": { diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index c52ec32..9948edc 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -74,7 +74,9 @@ "_": "Acquisti", "Orders": "Ordini fornitori", "Receipts": "Ricevimenti merce", - "Invoices": "Fatture passive" + "Invoices": "Fatture passive", + "Import": "Importa fatture", + "SelfInvoices": "Autofatture" }, "Inventory": { "_": "Magazzino", diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 4c5b190..aaa2319 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -63,9 +63,10 @@ public static class MenuCatalog Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", null, ("Shell.Menu.Sales.Quotes", "preventivi"), ("Shell.Menu.Sales.Orders", "ordini"), ("Shell.Menu.Sales.DeliveryNotes", "ddt"), ("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito"), ("Shell.Menu.Sales.DeferredInvoicing", "fatturazione-differita")), - Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", "M6", - ("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture")), - Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", "M6", + Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", null, + ("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture"), + ("Shell.Menu.Purchases.Import", "importa-fatture"), ("Shell.Menu.Purchases.SelfInvoices", "autofatture")), + Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", null, ("Shell.Menu.Inventory.Stock", "giacenze"), ("Shell.Menu.Inventory.Entries", "movimenti"), ("Shell.Menu.Inventory.StockTake", "inventario"), ("Shell.Menu.Inventory.Reorder", "riordino")), Area("Shell.Menu.Ledger", "book", "/contabilita", ModuleCodes.Accounting, "ledger.entry.read", "M7", diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 469eb44..64c1bf0 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -159,6 +159,8 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } .kh-tone { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--kh-text-3); } .kh-tone.ok { background: var(--kh-ok); } .kh-tone.info { background: var(--kh-info, var(--kh-accent)); } .kh-tone.warn { background: var(--kh-warn); } .kh-tone.err { background: var(--kh-err); } +.kh-wfoot { padding: 8px 12px; border-top: 1px solid var(--kh-border); font-size: 12.5px; } +.kh-wfoot a { display: inline-flex; align-items: center; gap: 6px; } .kh-status .li { padding: 7px 12px; } .kh-status .li .s { text-align: right; } .chk-row input[type="checkbox"] { margin: 0; accent-color: var(--kh-accent); } @@ -403,3 +405,20 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } /* The message of "Invia per e-mail" (issue #52): room for the whole text proposed by the template. */ .kh-mail-form textarea.in { min-height: 190px; } + +/* Warehouse (M6): filters above a radar, count boxes, file picker as a button, grids inside dialogs. */ +.kh-pagefilters { margin: 10px 0 4px; } +.kh-searchbox { width: 220px; } +.kh-taketools { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--kh-border); } +.kh-taketools .in { width: auto; } +.kh-taketools .kh-searchbox { flex: 1 1 200px; max-width: 320px; } +.kh-scrollx { overflow-x: auto; } +.in.kh-countbox { width: 96px; height: 26px; text-align: right; } +.kh-filebtn { position: relative; overflow: hidden; cursor: pointer; } +.kh-filebtn input[type=file] { position: absolute; inset: 0; opacity: 0; cursor: pointer; } +.kh-dialoggrid { max-height: 52vh; overflow: auto; margin-top: 10px; } +.kh-dialoggrid .mono { font-family: var(--kh-mono); font-size: 12px; } +.kh-cellpick { min-width: 220px; } +.kh-cellpick .f > label:empty { display: none; } +.kh-plainlist { margin: 4px 0 0; padding-left: 18px; } +.kh-pendingself { margin-bottom: 12px; } diff --git a/tests/Khaemhat.Core.Tests/Inventory/StockRulesTests.cs b/tests/Khaemhat.Core.Tests/Inventory/StockRulesTests.cs new file mode 100644 index 0000000..0b5b77e --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Inventory/StockRulesTests.cs @@ -0,0 +1,104 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Tables; + +namespace Khaemhat.Core.Tests.Inventory; + +/// Which documents move the stock and how the weighted average values it (issue #59, ADR 0035). +[TestClass] +public sealed class StockRulesTests +{ + private static readonly StockReason Load = new(StockEffect.Load, AffectsValue: true, IsTransfer: false); + private static readonly StockReason Unload = new(StockEffect.Unload, AffectsValue: true, IsTransfer: false); + private static readonly StockReason Transfer = new(StockEffect.None, AffectsValue: false, IsTransfer: true); + + [TestMethod] + public void Movements_FollowTheReason_AndOnlyPurchasesCarryTheirCost() + { + var line = new StockLineInput(7, 100, 5m, 1, 12.5m); + + var receipt = StockEffectMatrix.Movements(DocumentKind.PurchaseDeliveryNote, Load, null, [line]).Single(); + Assert.AreEqual(5m, receipt.Quantity); + Assert.IsTrue(receipt.Valued); + Assert.AreEqual(12.5m, receipt.UnitCost); + + var delivery = StockEffectMatrix.Movements(DocumentKind.DeliveryNote, Unload, null, [line]).Single(); + Assert.AreEqual(-5m, delivery.Quantity); + Assert.IsFalse(delivery.Valued, "A sale is valued at the average, not at its price."); + + // A customer return loads, at the average. + var back = StockEffectMatrix.Movements(DocumentKind.CreditNote, Load, null, [line]).Single(); + Assert.AreEqual(5m, back.Quantity); + Assert.IsFalse(back.Valued); + + // Orders and quotations never move the stock; without a reason nothing moves. + Assert.IsEmpty(StockEffectMatrix.Movements(DocumentKind.PurchaseOrder, Load, null, [line])); + Assert.IsEmpty(StockEffectMatrix.Movements(DocumentKind.Quotation, Unload, null, [line])); + Assert.IsEmpty(StockEffectMatrix.Movements(DocumentKind.ImmediateInvoice, null, null, [line])); + Assert.IsTrue(StockEffectMatrix.Commits(DocumentKind.SalesOrder)); + Assert.IsTrue(StockEffectMatrix.Orders(DocumentKind.PurchaseOrder)); + Assert.IsTrue(StockEffectMatrix.IsOpenOrder(DocumentStatus.PartiallyFulfilled)); + Assert.IsFalse(StockEffectMatrix.IsOpenOrder(DocumentStatus.Closed)); + } + + [TestMethod] + public void Transfer_UnloadsTheOriginAndLoadsTheDestination_WithoutValue() + { + var moves = StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, 2, [new StockLineInput(1, 100, 3m, 1, 10m)]); + Assert.HasCount(2, moves); + Assert.AreEqual((1L, -3m), (moves[0].WarehouseId, moves[0].Quantity)); + Assert.AreEqual((2L, 3m), (moves[1].WarehouseId, moves[1].Quantity)); + Assert.IsFalse(moves.Any(m => m.Valued)); + + Assert.ThrowsExactly(() => StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, null, [new StockLineInput(1, 100, 3m, 1, null)])); + Assert.ThrowsExactly(() => StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, 1, [new StockLineInput(1, 100, 3m, 1, null)])); + } + + [TestMethod] + public void WeightedAverage_MovesWithEveryValuedLoad_AndValuesTheRestAtItsMoment() + { + var day = new DateOnly(2026, 3, 1); + var history = StockCostCalculator.Run( + [ + new CostedMovement(1, day, 1, 10m, true, 10m), + new CostedMovement(2, day.AddDays(1), 1, -4m, false, 0m), + new CostedMovement(3, day.AddDays(2), 2, 6m, true, 13m), + new CostedMovement(4, day.AddDays(3), 1, -2m, false, 0m), + ]); + + // 6 left at 10, then 6 more at 13: (60 + 78) / 12 = 11.5. + Assert.AreEqual(10m, history.UnitCosts[2]); + Assert.AreEqual(11.5m, history.UnitCosts[4]); + Assert.AreEqual(11.5m, history.AverageCost); + Assert.AreEqual(13m, history.LastCost); + Assert.AreEqual(10m, history.OnHand); + Assert.AreEqual(4m, history.Warehouses[1].OnHand); + Assert.AreEqual(6m, history.Warehouses[2].OnHand); + Assert.AreEqual(day.AddDays(3), history.Warehouses[1].LastUnload); + Assert.AreEqual(day, history.Warehouses[1].LastLoad); + Assert.AreEqual(-23m, StockCostCalculator.Value(-2m, 11.5m)); + } + + [TestMethod] + public void WeightedAverage_RestartsFromTheLoad_WhenTheStockWasNegative() + { + var day = new DateOnly(2026, 3, 1); + var history = StockCostCalculator.Run( + [ + new CostedMovement(1, day, 1, -3m, false, 0m), + new CostedMovement(2, day, 1, 5m, true, 8m), + ], + initialCost: 7m); + + Assert.AreEqual(7m, history.UnitCosts[1], "Before any purchase the standard cost values the unload."); + Assert.AreEqual(8m, history.AverageCost); + Assert.AreEqual(2m, history.OnHand); + } + + [TestMethod] + public void Reason_ComesFromTheRowOfTheTable() + { + var reason = StockReason.Of(new InventoryReason { Code = "TRA", Description = "Trasferimento", Effect = StockEffect.None, AffectsValue = false, IsTransfer = true }); + Assert.AreEqual(Transfer, reason); + } +} diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 69cc632..8e4321f 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -81,6 +81,7 @@ public sealed class MappingTests "sale_quotations", "sale_quotation_lines", "sale_orders", "sale_order_lines", "sale_documents", "sale_document_lines", "purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines", "document_links", "document_tax_summaries", "document_installments", + "inventory_entries", "inventory_entry_lines", "item_balances", "stock_takes", "stock_take_lines", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs new file mode 100644 index 0000000..96fc5f6 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs @@ -0,0 +1,586 @@ +using System.Text; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Tests.Security; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// +/// The reader of received FatturaPA files (issue #57). Every sample is written here with fictitious data: no file is +/// downloaded and the identifiers are not checked by the reader. +/// +[TestClass] +public sealed class FatturaPaReaderTests +{ + private const string FileName = "IT01234567890_00042.xml"; + private const string Namespace = "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2"; + + private static readonly FatturaPaReader Reader = new(); + + private const string Header = """ + + + IT01234567890 + 00042 + FPR12 + ABC1234 + + + + IT01234567890 + 01234567890 + Ferramenta Piemontese S.r.l. + RF01 + + + Via Roma1210121 + TorinoTOIT + + TO123456LN + 011 1234567amministrazione@ferramenta.example + + + + IT09876543210 + Officine Esempio S.p.A. + + Corso Milano20121MilanoMIIT + + + """; + + private const string OrdinaryBody = """ + + + + TD01 + EUR + 2026-03-15 + FT/2026/123 + SC2.00 + MG1.50 + 116.90 + Fornitura di marzo + Consegna in cantiere + + + 1 + 2 + ORD-77 + 2026-03-01 + J11B26000010001 + Z1234567AB + + + DDT-501 + 2026-03-10 + 1 + + + + + 1 + SKUB-M8-ZN + EAN8001234567895 + Bulloni M8 zincati + 100.00 + PZ + 0.500000 + SC10.00 + 45.00 + 22.00 + + + 2 + Manuale tecnico di carpenteria + 2.00 + 25.00 + 50.00 + 4.00 + + + 3 + AC + Contributo ambientale imballi + 2026-03-01 + 2026-03-31 + 10.00 + 10.00 + 0.00 + N2.2 + CC-12 + + + 22.0045.009.90I + + + 4.0050.002.00I + + + 0.00N2.210.000.00 + Non soggetto art. 15 DPR 633/72 + + + + TP01 + + MP05 + 2026-04-30 + 58.45 + IT60X0542811101000000123456 + + + Ferramenta Piemontese S.r.l. + MP05 + 2026-05-31 + 58.45 + IT60X0542811101000000123456 + BPMOIT22XXX + + + + """; + + private static string Prefixed(params string[] bodies) => + $"""{Header}{string.Concat(bodies)}"""; + + private static string Body(string type, string number, string date, string generalExtra = "", string documentExtra = "", string goods = "", string extra = "") => $""" + + + + {type}EUR{date}{number}{documentExtra} + {generalExtra} + + {(goods.Length > 0 ? goods : SimpleGoods)}{extra} + + """; + + private const string SimpleGoods = """ + 1Consulenza100.00100.0022.00 + 22.00100.0022.00I + """; + + private static IncomingInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml)); + + [TestMethod] + public void Read_OrdinaryInvoice_ReadsHeaderPartiesAndTransmission() + { + var file = Read(Prefixed(OrdinaryBody)); + + Assert.AreEqual(FileName, file.FileName); + Assert.AreEqual("FPR12", file.TransmissionFormat); + Assert.AreEqual("00042", file.ProgressiveNumber); + Assert.AreEqual("ABC1234", file.RecipientCode); + Assert.IsNull(file.Signature); + Assert.HasCount(1, file.Invoices); + + var supplier = file.Supplier; + Assert.AreEqual("IT", supplier.CountryCode); + Assert.AreEqual("01234567890", supplier.VatNumber); + Assert.AreEqual("01234567890", supplier.TaxCode); + Assert.AreEqual("Ferramenta Piemontese S.r.l.", supplier.DisplayName); + Assert.AreEqual("Via Roma", supplier.Address); + Assert.AreEqual("12", supplier.StreetNumber); + Assert.AreEqual("10121", supplier.PostalCode); + Assert.AreEqual("Torino", supplier.City); + Assert.AreEqual("TO", supplier.Province); + Assert.AreEqual("IT", supplier.Country); + Assert.AreEqual("RF01", supplier.TaxRegime); + Assert.AreEqual("amministrazione@ferramenta.example", supplier.Email); + Assert.AreEqual("011 1234567", supplier.Phone); + Assert.AreEqual("TO", supplier.ReaOffice); + Assert.AreEqual("123456", supplier.ReaNumber); + + Assert.AreEqual("09876543210", file.Customer.VatNumber); + Assert.AreEqual("Officine Esempio S.p.A.", file.Customer.Name); + Assert.AreEqual("Milano", file.Customer.City); + Assert.IsNull(file.Customer.TaxRegime); + } + + [TestMethod] + public void Read_OrdinaryInvoice_ReadsDocumentLinesSummaryAndPayments() + { + var invoice = Read(Prefixed(OrdinaryBody)).Invoices[0]; + + Assert.AreEqual("TD01", invoice.DocumentType); + Assert.AreEqual("EUR", invoice.Currency); + Assert.AreEqual(new DateOnly(2026, 3, 15), invoice.Date); + Assert.AreEqual("FT/2026/123", invoice.Number); + Assert.AreEqual(116.90m, invoice.Total); + Assert.IsNull(invoice.Rounding); + CollectionAssert.AreEqual(new[] { "Fornitura di marzo", "Consegna in cantiere" }, invoice.Causals.ToArray()); + Assert.IsFalse(invoice.Art73); + Assert.AreEqual(new IncomingDiscount(false, 2.00m, null), invoice.Discounts[0]); + Assert.AreEqual(new IncomingDiscount(true, null, 1.50m), invoice.Discounts[1]); + + Assert.HasCount(3, invoice.Lines); + var bolts = invoice.Lines[0]; + Assert.AreEqual(1, bolts.Number); + Assert.AreEqual(new IncomingItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]); + Assert.AreEqual(new IncomingItemCode("EAN", "8001234567895"), bolts.Codes[1]); + Assert.AreEqual("Bulloni M8 zincati", bolts.Description); + Assert.AreEqual(100m, bolts.Quantity); + Assert.AreEqual("PZ", bolts.Unit); + Assert.AreEqual(0.5m, bolts.UnitPrice); + Assert.AreEqual(45m, bolts.TotalPrice); + Assert.AreEqual(22m, bolts.TaxRate); + Assert.IsNull(bolts.Nature); + Assert.AreEqual(new IncomingDiscount(false, 10m, null), bolts.Discounts.Single()); + Assert.IsFalse(bolts.Withheld); + + Assert.AreEqual(4m, invoice.Lines[1].TaxRate); + var contribution = invoice.Lines[2]; + Assert.IsNull(contribution.Quantity); + Assert.AreEqual(0m, contribution.TaxRate); + Assert.AreEqual("N2.2", contribution.Nature); + Assert.AreEqual("AC", contribution.LineType); + Assert.AreEqual(new DateOnly(2026, 3, 1), contribution.PeriodStart); + Assert.AreEqual(new DateOnly(2026, 3, 31), contribution.PeriodEnd); + Assert.AreEqual("CC-12", contribution.AdministrativeReference); + + Assert.HasCount(3, invoice.TaxSummary); + Assert.AreEqual(new IncomingTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]); + Assert.AreEqual(4m, invoice.TaxSummary[1].Rate); + Assert.AreEqual("N2.2", invoice.TaxSummary[2].Nature); + Assert.AreEqual("Non soggetto art. 15 DPR 633/72", invoice.TaxSummary[2].LegalReference); + + Assert.HasCount(2, invoice.Payments); + Assert.AreEqual(new IncomingPayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]); + Assert.AreEqual("BPMOIT22XXX", invoice.Payments[1].Bic); + Assert.AreEqual("Ferramenta Piemontese S.r.l.", invoice.Payments[1].Beneficiary); + Assert.IsEmpty(invoice.Attachments); + } + + [TestMethod] + public void Read_OrdinaryInvoice_ReadsOrdersAndDeliveryNotes() + { + var invoice = Read(Prefixed(OrdinaryBody)).Invoices[0]; + + var order = invoice.Orders.Single(); + Assert.AreEqual("ORD-77", order.Id); + Assert.AreEqual(new DateOnly(2026, 3, 1), order.Date); + CollectionAssert.AreEqual(new[] { 1, 2 }, order.LineNumbers.ToArray()); + Assert.AreEqual("Z1234567AB", order.Cig); + Assert.AreEqual("J11B26000010001", order.Cup); + + var note = invoice.DeliveryNotes.Single(); + Assert.AreEqual("DDT-501", note.Id); + Assert.AreEqual(new DateOnly(2026, 3, 10), note.Date); + CollectionAssert.AreEqual(new[] { 1 }, note.LineNumbers.ToArray()); + Assert.IsEmpty(invoice.Contracts); + Assert.IsEmpty(invoice.RelatedInvoices); + } + + [TestMethod] + public void Read_CreditNote_ReadsTheRelatedInvoice() + { + var related = """ + FT/2026/1232026-03-15 + CTR-2026-01 + """; + var invoice = Read(Prefixed(Body("TD04", "NC/2026/7", "2026-03-20", generalExtra: related))).Invoices[0]; + + Assert.AreEqual("TD04", invoice.DocumentType); + Assert.AreEqual("NC/2026/7", invoice.Number); + var original = invoice.RelatedInvoices.Single(); + Assert.AreEqual("FT/2026/123", original.Id); + Assert.AreEqual(new DateOnly(2026, 3, 15), original.Date); + Assert.IsEmpty(original.LineNumbers); + Assert.AreEqual("CTR-2026-01", invoice.Contracts.Single().Id); + Assert.IsNull(invoice.Contracts[0].Date); + } + + [TestMethod] + public void Read_Batch_ReturnsOneInvoicePerBody() + { + var file = Read(Prefixed(Body("TD01", "101", "2026-02-01"), Body("TD01", "102", "2026-02-02"))); + + Assert.HasCount(2, file.Invoices); + Assert.AreEqual("101", file.Invoices[0].Number); + Assert.AreEqual("102", file.Invoices[1].Number); + Assert.AreEqual(new DateOnly(2026, 2, 2), file.Invoices[1].Date); + } + + [TestMethod] + public void Read_IgnoresNamespacesAndPrefixes_AndToleratesBomAndWhitespace() + { + var prefixed = Prefixed(OrdinaryBody); + var defaultNamespace = prefixed + .Replace("", StringComparison.Ordinal)..][2..]; + + byte[] withBom = [0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes("\r\n " + prefixed)]; + var variants = new List + { + Encoding.UTF8.GetBytes(prefixed), + Encoding.UTF8.GetBytes(defaultNamespace), + Encoding.UTF8.GetBytes(everyElementPrefixed), + withBom, + Encoding.UTF8.GetBytes("\n" + noDeclaration), + }; + + foreach (var bytes in variants) + { + Assert.IsTrue(Reader.CanRead(FileName, bytes)); + var file = Reader.Read(FileName, bytes); + Assert.AreEqual("Ferramenta Piemontese S.r.l.", file.Supplier.Name); + Assert.AreEqual("FT/2026/123", file.Invoices[0].Number); + Assert.HasCount(3, file.Invoices[0].Lines); + Assert.HasCount(2, file.Invoices[0].Payments); + } + } + + [TestMethod] + public void Read_Windows1252Declaration_DecodesTheText() + { + var goods = """ + 1Caffè in grani € 1 al kg10.0010.0010.00 + 10.0010.001.00 + """; + var xml = Prefixed(Body("TD01", "5", "2026-01-10", goods: goods)).Replace("encoding=\"UTF-8\"", "encoding=\"windows-1252\"", StringComparison.Ordinal); + var bytes = CodePagesEncodingProvider.Instance.GetEncoding(1252)!.GetBytes(xml); + + var line = Reader.Read(FileName, bytes).Invoices[0].Lines[0]; + + Assert.AreEqual("Caffè in grani € 1 al kg", line.Description); + } + + [TestMethod] + public void Read_WithholdingSocialSecurityAndVirtualStampDuty() + { + var document = """ + RT01208.0020.00A + SI2.00 + + TC014.0040.00 + 1000.0022.00SI + + 1270.88 + 0.01 + SI + """; + var goods = """ + 1Parere legale1000.001000.0022.00SI + 22.001040.00228.80I + """; + var xml = Prefixed(Body("TD06", "12/2026", "2026-04-02", documentExtra: document, goods: goods)) + .Replace("Ferramenta Piemontese S.r.l.", "GiuliaBianchi", StringComparison.Ordinal); + + var file = Read(xml); + var invoice = file.Invoices[0]; + + Assert.IsNull(file.Supplier.Name); + Assert.AreEqual("Giulia", file.Supplier.FirstName); + Assert.AreEqual("Bianchi", file.Supplier.LastName); + Assert.AreEqual("Giulia Bianchi", file.Supplier.DisplayName); + Assert.AreEqual(new IncomingWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single()); + Assert.AreEqual(new IncomingStampDuty(true, 2m), invoice.StampDuty); + Assert.AreEqual(new IncomingSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single()); + Assert.AreEqual(1270.88m, invoice.Total); + Assert.AreEqual(0.01m, invoice.Rounding); + Assert.IsTrue(invoice.Art73); + Assert.IsTrue(invoice.Lines[0].Withheld); + } + + [TestMethod] + public void Read_Attachment_IsDecoded() + { + var pdf = Encoding.ASCII.GetBytes("%PDF-1.4 copia di cortesia della fattura"); + var attachment = $""" + + FT_2026_5.pdf + PDF + Copia di cortesia + {Convert.ToBase64String(pdf, Base64FormattingOptions.InsertLineBreaks)} + + + """; + + var found = Read(Prefixed(Body("TD01", "5", "2026-01-10", extra: attachment))).Invoices[0].Attachments.Single(); + + Assert.AreEqual("FT_2026_5.pdf", found.Name); + Assert.AreEqual("PDF", found.Format); + Assert.AreEqual("Copia di cortesia", found.Description); + CollectionAssert.AreEqual(pdf, found.Content); + } + + [TestMethod] + public void Read_SimplifiedInvoice_MapsTheGrossAmountsToNetLines() + { + var xml = """ + + + + + IT01234567890 + S0001 + FSM10 + 0000000 + + + IT01234567890 + Bar Centrale di Rossi Mario + Piazza Castello10123TorinoTOIT + RF01 + + + IT09876543210 + + Officine Esempio S.p.A. + Corso Milano20121MilanoMIIT + + + + + + TD08EUR2026-05-04S/18 + S/122026-04-28Importo + + Pranzo di lavoro122.0022.00 + Quotidiani e riviste52.004.00 + Francobolli30.000.00N2.2 + + + """; + + var file = Read(xml); + var invoice = file.Invoices[0]; + + Assert.AreEqual("FSM10", file.TransmissionFormat); + Assert.AreEqual("Bar Centrale di Rossi Mario", file.Supplier.Name); + Assert.AreEqual("01234567890", file.Supplier.VatNumber); + Assert.AreEqual("RF01", file.Supplier.TaxRegime); + Assert.AreEqual("09876543210", file.Customer.VatNumber); + Assert.AreEqual("Officine Esempio S.p.A.", file.Customer.Name); + Assert.AreEqual("Milano", file.Customer.City); + + Assert.AreEqual("TD08", invoice.DocumentType); + Assert.AreEqual("S/18", invoice.Number); + Assert.AreEqual(204m, invoice.Total); + Assert.AreEqual("S/12", invoice.RelatedInvoices.Single().Id); + Assert.AreEqual(new DateOnly(2026, 4, 28), invoice.RelatedInvoices[0].Date); + + Assert.HasCount(3, invoice.Lines); + var lunch = invoice.Lines[0]; + Assert.IsNull(lunch.Quantity); + Assert.AreEqual(100m, lunch.UnitPrice); + Assert.AreEqual(100m, lunch.TotalPrice); + Assert.AreEqual(22m, lunch.TaxRate); + Assert.AreEqual(50m, invoice.Lines[1].TotalPrice); + Assert.AreEqual(4m, invoice.Lines[1].TaxRate); + Assert.AreEqual("N2.2", invoice.Lines[2].Nature); + Assert.AreEqual(0m, invoice.Lines[2].TaxRate); + Assert.AreEqual(30m, invoice.Lines[2].TotalPrice); + + Assert.HasCount(3, invoice.TaxSummary); + Assert.AreEqual(22m, invoice.TaxSummary.Single(s => s.Rate == 22m).Tax); + Assert.AreEqual(2m, invoice.TaxSummary.Single(s => s.Rate == 4m).Tax); + Assert.AreEqual(30m, invoice.TaxSummary.Single(s => s.Nature == "N2.2").Taxable); + } + + [TestMethod] + public void Read_SignedP7m_ReturnsTheInvoiceAndTheSignature() + { + var xml = Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody)); + var p7m = CmsTestSigner.Sign(xml, CmsTestSigner.Rsa, new CmsTestOptions { Ber = true }); + var base64 = Encoding.ASCII.GetBytes(Convert.ToBase64String(p7m, Base64FormattingOptions.InsertLineBreaks)); + + foreach (var content in new[] { p7m, base64 }) + { + Assert.IsTrue(Reader.CanRead(FileName + ".p7m", content)); + var file = Reader.Read(FileName + ".p7m", content); + + CollectionAssert.AreEqual(xml, file.Xml); + Assert.AreEqual("FT/2026/123", file.Invoices[0].Number); + var signature = file.Signature!; + Assert.IsTrue(signature.Verified, signature.Problem); + Assert.AreEqual("Mario Rossi", signature.Signer); + Assert.AreEqual("RSSMRA80A01H501U", signature.SignerTaxCode); + Assert.AreEqual(CmsTestSigner.SigningTime, signature.SignedAt); + Assert.AreEqual(new DateTimeOffset(2028, 1, 1, 0, 0, 0, TimeSpan.Zero), signature.CertificateNotAfter); + Assert.IsNull(signature.Problem); + } + } + + [TestMethod] + public void Read_TamperedP7m_StillReadsTheInvoice_NotVerified() + { + var xml = Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody)); + var tampered = Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody).Replace("116.90", "16.90", StringComparison.Ordinal)); + var p7m = CmsTestSigner.Sign(xml, CmsTestSigner.Rsa, new CmsTestOptions { TamperedContent = tampered }); + + var file = Reader.Read(FileName + ".p7m", p7m); + + Assert.AreEqual(16.90m, file.Invoices[0].Total); + Assert.IsFalse(file.Signature!.Verified); + Assert.IsNotNull(file.Signature.Problem); + } + + [TestMethod] + public void CanRead_SniffsTheContent() + { + Assert.IsTrue(Reader.CanRead("fattura.XML", Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody)))); + Assert.IsTrue(Reader.CanRead("senza-estensione", Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody)))); + Assert.IsFalse(Reader.CanRead("fattura.pdf", "%PDF-1.4"u8)); + Assert.IsFalse(Reader.CanRead("vuoto.xml", [])); + } + + [TestMethod] + public void Read_NotXml_IsNotReadable() + { + AssertError(IncomingInvoiceErrors.NotReadable, "%PDF-1.4 non è una fattura"u8.ToArray()); + AssertError(IncomingInvoiceErrors.NotReadable, []); + AssertError(IncomingInvoiceErrors.NotReadable, Encoding.UTF8.GetBytes("
")); + } + + [TestMethod] + public void Read_Dtd_IsRefused() + { + var xml = """]>&e;"""; + + AssertError(IncomingInvoiceErrors.NotReadable, Encoding.UTF8.GetBytes(xml)); + } + + [TestMethod] + public void Read_OtherXml_IsNotAnInvoice() => + AssertError(IncomingInvoiceErrors.NotInvoice, Encoding.UTF8.GetBytes("""1""")); + + [TestMethod] + public void Read_MissingMandatoryData_IsInvalid() + { + var noNumber = Prefixed(Body("TD01", "", "2026-01-10")); + var badDate = Prefixed(Body("TD01", "7", "10/01/2026")); + var noHeader = $"""{Body("TD01", "7", "2026-01-10")}"""; + var noBody = $"""{Header}"""; + + foreach (var xml in new[] { noNumber, badDate, noHeader, noBody }) + { + AssertError(IncomingInvoiceErrors.Invalid, Encoding.UTF8.GetBytes(xml)); + } + + var ex = Assert.ThrowsExactly(() => Read(noNumber)); + StringAssert.Contains(ex.Message, "Numero"); + } + + [TestMethod] + public void Read_BrokenEnvelope_IsSignatureBroken() + { + var p7m = CmsTestSigner.Sign(Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody)), CmsTestSigner.Rsa); + + AssertError(IncomingInvoiceErrors.SignatureBroken, p7m[..(p7m.Length / 2)]); + } + + [TestMethod] + public void Pack_DeliversTheReader() => + Assert.IsInstanceOfType(new ItalyFiscalPack().GetFeature()); + + private static void AssertError(string code, byte[] content) + { + var ex = Assert.ThrowsExactly(() => Reader.Read(FileName, content)); + Assert.AreEqual(code, ex.Code, ex.Message); + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj b/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj index ac3cce5..fb03430 100644 --- a/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj +++ b/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj @@ -8,4 +8,9 @@ + + + + + diff --git a/tests/Khaemhat.Infrastructure.Tests/Security/CmsSignedDataTests.cs b/tests/Khaemhat.Infrastructure.Tests/Security/CmsSignedDataTests.cs new file mode 100644 index 0000000..3bcd86b --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Security/CmsSignedDataTests.cs @@ -0,0 +1,167 @@ +using System.Text; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Infrastructure.Tests.Security; + +/// The reader of CMS SignedData envelopes (.p7m) used for received e-invoices (issue #57). +[TestClass] +public sealed class CmsSignedDataTests +{ + private static readonly byte[] Content = Encoding.UTF8.GetBytes("contenuto firmato"); + + [TestMethod] + public void Read_RsaSignature_ReturnsTheContentVerified_WithTheSigner() + { + var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa); + + var result = CmsSignedData.Read(envelope); + + CollectionAssert.AreEqual(Content, result.Content); + Assert.IsTrue(result.Verified, result.Problem); + Assert.IsNull(result.Problem); + Assert.AreEqual(1, result.Layers); + var signer = result.Signer!; + Assert.AreEqual("Mario Rossi", signer.Name); + Assert.AreEqual("RSSMRA80A01H501U", signer.TaxCode); + Assert.AreEqual(CmsTestSigner.SigningTime, signer.SigningTime); + Assert.AreEqual(new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), signer.CertificateNotBefore); + Assert.AreEqual(new DateTimeOffset(2028, 1, 1, 0, 0, 0, TimeSpan.Zero), signer.CertificateNotAfter); + CollectionAssert.AreEqual(CmsTestSigner.Rsa.RawData, signer.Certificate); + } + + [TestMethod] + public void Read_EcdsaSignature_BySubjectKeyIdentifier_IsVerified() + { + var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Ecdsa, new CmsTestOptions { BySubjectKeyIdentifier = true }); + + var result = CmsSignedData.Read(envelope); + + Assert.IsTrue(result.Verified, result.Problem); + Assert.AreEqual("RSSMRA80A01H501U", result.Signer!.TaxCode); + } + + [TestMethod] + public void Read_WithoutSignedAttributes_VerifiesTheSignatureOverTheContent() + { + var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { SignedAttributes = false }); + + var result = CmsSignedData.Read(envelope); + + Assert.IsTrue(result.Verified, result.Problem); + Assert.IsNull(result.Signer!.SigningTime); + } + + [TestMethod] + public void Read_TamperedContent_ReturnsItNotVerified_WithTheProblem() + { + var tampered = Encoding.UTF8.GetBytes("contenuto alterato"); + var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { TamperedContent = tampered }); + + var result = CmsSignedData.Read(envelope); + + CollectionAssert.AreEqual(tampered, result.Content); + Assert.IsFalse(result.Verified); + StringAssert.Contains(result.Problem, "changed after signing"); + Assert.AreEqual("Mario Rossi", result.Signer!.Name); + } + + [TestMethod] + public void Read_BrokenSignature_IsNotVerified() + { + var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { BreakSignature = true }); + + var result = CmsSignedData.Read(envelope); + + Assert.IsFalse(result.Verified); + StringAssert.Contains(result.Problem, "does not match"); + } + + [TestMethod] + public void Read_BerWithIndefiniteLengthsAndChunkedContent_IsVerified() + { + var large = Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat("Bulloni M8 zincati", 40))); + var envelope = CmsTestSigner.Sign(large, CmsTestSigner.Rsa, new CmsTestOptions { Ber = true }); + Assert.AreEqual(0x80, envelope[1], "The outer SEQUENCE must have an indefinite length."); + + var result = CmsSignedData.Read(envelope); + + CollectionAssert.AreEqual(large, result.Content); + Assert.IsTrue(result.Verified, result.Problem); + } + + [TestMethod] + public void Read_Base64TextForm_WithLineBreaksAndArmour_IsVerified() + { + var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa); + var plain = Encoding.ASCII.GetBytes(Convert.ToBase64String(envelope)); + var wrapped = Encoding.ASCII.GetBytes( + "-----BEGIN PKCS7-----\r\n" + Convert.ToBase64String(envelope, Base64FormattingOptions.InsertLineBreaks) + "\r\n-----END PKCS7-----\r\n"); + + Assert.IsTrue(CmsSignedData.LooksLikeCms(plain)); + Assert.IsTrue(CmsSignedData.LooksLikeCms(wrapped)); + foreach (var text in new[] { plain, wrapped }) + { + var result = CmsSignedData.Read(text); + CollectionAssert.AreEqual(Content, result.Content); + Assert.IsTrue(result.Verified, result.Problem); + } + } + + [TestMethod] + public void Read_NestedEnvelopes_AreOpenedUntilTheContent() + { + var inner = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa); + var outer = CmsTestSigner.Sign(inner, CmsTestSigner.Ecdsa, new CmsTestOptions { Ber = true }); + + var result = CmsSignedData.Read(outer); + + CollectionAssert.AreEqual(Content, result.Content); + Assert.AreEqual(2, result.Layers); + Assert.HasCount(2, result.Signers); + Assert.IsTrue(result.Verified, result.Problem); + } + + [TestMethod] + public void Read_NestedEnvelope_WithABrokenInnerSignature_IsNotVerified() + { + var inner = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { BreakSignature = true }); + var outer = CmsTestSigner.Sign(inner, CmsTestSigner.Rsa); + + var result = CmsSignedData.Read(outer); + + Assert.IsTrue(result.Signers[0].Verified); + Assert.IsFalse(result.Signers[1].Verified); + Assert.IsFalse(result.Verified); + Assert.IsNotNull(result.Problem); + } + + [TestMethod] + public void Read_Garbage_Throws() + { + Assert.ThrowsExactly(() => CmsSignedData.Read(Encoding.UTF8.GetBytes("questo non è un file firmato"))); + Assert.ThrowsExactly(() => CmsSignedData.Read([])); + Assert.ThrowsExactly(() => CmsSignedData.Read(Content)); + + // The right start and nothing after it. + var truncated = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa)[..40]; + Assert.IsTrue(CmsSignedData.LooksLikeCms(truncated)); + Assert.ThrowsExactly(() => CmsSignedData.Read(truncated)); + } + + [TestMethod] + public void LooksLikeCms_SniffsTheContent() + { + Assert.IsTrue(CmsSignedData.LooksLikeCms(CmsTestSigner.Sign(Content, CmsTestSigner.Rsa))); + Assert.IsTrue(CmsSignedData.LooksLikeCms(CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { Ber = true }))); + Assert.IsFalse(CmsSignedData.LooksLikeCms(Content)); + Assert.IsFalse(CmsSignedData.LooksLikeCms("QUJDRA=="u8)); + Assert.IsFalse(CmsSignedData.LooksLikeCms([])); + } + + [TestMethod] + public void DecodeBase64Text_RejectsWhatIsNotBase64() + { + Assert.IsNull(CmsSignedData.DecodeBase64Text("non è base64!"u8)); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, CmsSignedData.DecodeBase64Text("AQID\r\n"u8)); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs b/tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs new file mode 100644 index 0000000..8940eb4 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs @@ -0,0 +1,215 @@ +using System.Formats.Asn1; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Khaemhat.Infrastructure.Tests.Security; + +/// How builds the envelope. +internal sealed record CmsTestOptions +{ + /// BER with indefinite lengths and the content split in chunks, as many signing programs write. + public bool Ber { get; init; } + + /// Identify the signer by subject key identifier instead of issuer and serial number. + public bool BySubjectKeyIdentifier { get; init; } + + /// Whether to sign attributes (contentType, messageDigest, signingTime) or the content directly. + public bool SignedAttributes { get; init; } = true; + + /// Content put in the envelope instead of the signed one (to simulate tampering). + public byte[]? TamperedContent { get; init; } + + /// Flip a bit of the signature. + public bool BreakSignature { get; init; } +} + +/// +/// Builds CMS SignedData envelopes (CAdES .p7m) in the tests with and self-signed certificates: +/// no fixture is downloaded and no package is needed. Shared with the tests of the FatturaPA reader. +/// +internal static class CmsTestSigner +{ + public static readonly DateTimeOffset SigningTime = new(2026, 3, 15, 10, 30, 0, TimeSpan.Zero); + + private const string DataOid = "1.2.840.113549.1.7.1"; + private const string SignedDataOid = "1.2.840.113549.1.7.2"; + private const string Sha256Oid = "2.16.840.1.101.3.4.2.1"; + + private static readonly Lazy RsaCertificate = new(() => Create(ecdsa: false)); + private static readonly Lazy EcdsaCertificate = new(() => Create(ecdsa: true)); + + /// A self-signed RSA certificate of "Mario Rossi" with SERIALNUMBER=TINIT-RSSMRA80A01H501U. + public static X509Certificate2 Rsa => RsaCertificate.Value; + + /// A self-signed ECDSA P-256 certificate of the same person. + public static X509Certificate2 Ecdsa => EcdsaCertificate.Value; + + public static byte[] Sign(byte[] content, X509Certificate2 certificate, CmsTestOptions? options = null) + { + options ??= new CmsTestOptions(); + var isEcdsa = certificate.GetECDsaPrivateKey() is not null; + + byte[]? signedAttributes = null; + byte[] toSign = content; + if (options.SignedAttributes) + { + var writer = new AsnWriter(AsnEncodingRules.DER); + using (writer.PushSetOf()) + { + WriteAttribute(writer, "1.2.840.113549.1.9.3", w => w.WriteObjectIdentifier(DataOid)); + WriteAttribute(writer, "1.2.840.113549.1.9.4", w => w.WriteOctetString(SHA256.HashData(content))); + WriteAttribute(writer, "1.2.840.113549.1.9.5", w => w.WriteUtcTime(SigningTime)); + } + + toSign = writer.Encode(); + signedAttributes = (byte[])toSign.Clone(); + signedAttributes[0] = 0xA0; + } + + byte[] signature; + if (isEcdsa) + { + using var key = certificate.GetECDsaPrivateKey()!; + signature = key.SignData(toSign, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence); + } + else + { + using var key = certificate.GetRSAPrivateKey()!; + signature = key.SignData(toSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + } + + if (options.BreakSignature) + { + signature[^5] ^= 0x01; + } + + var signerInfo = new AsnWriter(AsnEncodingRules.DER); + using (signerInfo.PushSequence()) + { + if (options.BySubjectKeyIdentifier) + { + signerInfo.WriteInteger(3); + var ski = certificate.Extensions.OfType().Single(); + signerInfo.WriteOctetString(ski.SubjectKeyIdentifierBytes.Span, new Asn1Tag(TagClass.ContextSpecific, 0)); + } + else + { + signerInfo.WriteInteger(1); + using (signerInfo.PushSequence()) + { + signerInfo.WriteEncodedValue(certificate.IssuerName.RawData); + signerInfo.WriteInteger(certificate.SerialNumberBytes.Span); + } + } + + WriteAlgorithm(signerInfo, Sha256Oid, withNull: true); + if (signedAttributes is not null) + { + signerInfo.WriteEncodedValue(signedAttributes); + } + + WriteAlgorithm(signerInfo, isEcdsa ? "1.2.840.10045.4.3.2" : "1.2.840.113549.1.1.11", withNull: !isEcdsa); + signerInfo.WriteOctetString(signature); + } + + var version = Der(w => w.WriteInteger(1)); + var digestAlgorithms = Der(w => + { + using (w.PushSetOf()) + { + WriteAlgorithm(w, Sha256Oid, withNull: true); + } + }); + var certificates = Tlv(0xA0, certificate.RawData); + var signerInfos = Tlv(0x31, signerInfo.Encode()); + var signedDataOid = Der(w => w.WriteObjectIdentifier(SignedDataOid)); + var dataOid = Der(w => w.WriteObjectIdentifier(DataOid)); + var envelopeContent = options.TamperedContent ?? content; + + if (!options.Ber) + { + return Tlv(0x30, signedDataOid, Tlv(0xA0, Tlv(0x30, + version, digestAlgorithms, Tlv(0x30, dataOid, Tlv(0xA0, Tlv(0x04, envelopeContent))), certificates, signerInfos))); + } + + // BER: indefinite lengths everywhere around the content, which is a constructed OCTET STRING of small chunks. + var chunks = envelopeContent.Chunk(100).Select(c => Tlv(0x04, c)).ToArray(); + return Indefinite(0x30, signedDataOid, Indefinite(0xA0, Indefinite(0x30, + version, digestAlgorithms, Indefinite(0x30, dataOid, Indefinite(0xA0, Indefinite(0x24, chunks))), certificates, signerInfos))); + } + + private static X509Certificate2 Create(bool ecdsa) + { + var name = new X500DistinguishedNameBuilder(); + name.AddCountryOrRegion("IT"); + name.Add("2.5.4.42", "Mario"); + name.Add("2.5.4.4", "Rossi"); + name.Add("2.5.4.5", "TINIT-RSSMRA80A01H501U", UniversalTagNumber.PrintableString); + name.AddCommonName("Mario Rossi"); + var subject = name.Build(); + var notBefore = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero); + var notAfter = new DateTimeOffset(2028, 1, 1, 0, 0, 0, TimeSpan.Zero); + if (ecdsa) + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); + return request.CreateSelfSigned(notBefore, notAfter); + } + else + { + using var key = RSA.Create(2048); + var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); + return request.CreateSelfSigned(notBefore, notAfter); + } + } + + private static void WriteAttribute(AsnWriter writer, string oid, Action value) + { + using (writer.PushSequence()) + { + writer.WriteObjectIdentifier(oid); + using (writer.PushSetOf()) + { + value(writer); + } + } + } + + private static void WriteAlgorithm(AsnWriter writer, string oid, bool withNull) + { + using (writer.PushSequence()) + { + writer.WriteObjectIdentifier(oid); + if (withNull) + { + writer.WriteNull(); + } + } + } + + private static byte[] Der(Action write) + { + var writer = new AsnWriter(AsnEncodingRules.DER); + write(writer); + return writer.Encode(); + } + + private static byte[] Tlv(byte tag, params byte[][] children) + { + var body = children.SelectMany(c => c).ToArray(); + var length = body.Length; + byte[] lengthBytes = length switch + { + < 0x80 => [(byte)length], + <= 0xFF => [0x81, (byte)length], + <= 0xFFFF => [0x82, (byte)(length >> 8), (byte)length], + _ => [0x83, (byte)(length >> 16), (byte)(length >> 8), (byte)length], + }; + return [tag, .. lengthBytes, .. body]; + } + + private static byte[] Indefinite(byte tag, params byte[][] children) => + [tag, 0x80, .. children.SelectMany(c => c), 0x00, 0x00]; +} diff --git a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs index 6171280..392fff4 100644 --- a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs +++ b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs @@ -125,7 +125,7 @@ public sealed class DocumentEngineTests var year = DateTime.Now.Year; var definitions = await engine.DefinitionsAsync(Root, company); - Assert.HasCount(20, definitions, "Every seeded type has its kind."); + Assert.HasCount(26, definitions, "Every seeded type has its kind."); Assert.AreEqual(DocumentKind.DeferredInvoice, definitions.Single(d => d.Code == "FD").Kind); Assert.AreEqual(DocumentAction.Issue, definitions.Single(d => d.Code == "FI").ConfirmAction); await Assert.ThrowsExactlyAsync(() => sales.NewAsync(Root, company, "OC"), "An order is not a sale document."); diff --git a/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs index 9d97bdb..e1281b5 100644 --- a/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs +++ b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs @@ -152,7 +152,12 @@ public sealed class SalesFlowTests Assert.AreEqual("vendite/fatture/12", SalesScreens.RecordUrl(DocumentKind.Fee, 12)); Assert.AreEqual("vendite/note-credito/3", SalesScreens.RecordUrl(DocumentKind.DebitNote, 3)); Assert.AreEqual("vendite/ddt/nuovo?tipo=DDT", SalesScreens.NewUrl(SalesScreens.Find("ddt")!, "DDT")); - Assert.IsNull(SalesScreens.RecordUrl(DocumentKind.PurchaseInvoice, 1)); + Assert.AreEqual("acquisti/fatture/1", SalesScreens.RecordUrl(DocumentKind.PurchaseInvoice, 1)); + Assert.AreEqual("magazzino/movimenti/4", SalesScreens.RecordUrl(DocumentKind.InventoryEntry, 4)); + Assert.AreEqual(DocumentFamily.PurchaseDocument, SalesScreens.Find("acquisti", "fatture")!.Family); + Assert.IsNull(SalesScreens.Find("magazzino", "fatture")); + Assert.AreEqual("acquisti", SalesScreens.AreaOf("acquisti/fatture/3?x=1")); + Assert.AreEqual("Purchases.Fields.Supplier", SalesScreens.PartyLabel(SalesScreens.Find("acquisti", "autofatture")!.Direction)); // Each sales kind belongs to one radar only. var kinds = SalesScreens.Sections.SelectMany(s => s.Kinds).ToList(); diff --git a/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs b/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs index e97d3f5..ad513df 100644 --- a/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs +++ b/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs @@ -148,13 +148,14 @@ public sealed class ImportServiceTests } [TestMethod] - public async Task OpeningStock_IsOnlyChecked_UntilTheStockEntriesExist() + public async Task OpeningStock_LoadsTheWarehouse_WithAnOpeningMovement() { var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); await using (app) { var imports = app.Services.GetRequiredService(); var tables = app.Services.GetRequiredService(); + var stockService = app.Services.GetRequiredService(); await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" }); var items = Csv("codice;descrizione;categoria;tipo", "A-1;Valvola;VALV;merce", "S-1;Manodopera;VALV;servizio"); await imports.ImportAsync(Root, company, "articoli", items, ImportService.SuggestMapping(imports.Target("articoli"), items.Headers), new ImportOptions()); @@ -162,13 +163,16 @@ public sealed class ImportServiceTests var stock = Csv("articolo;deposito;quantita;costo_unitario", "A-1;;5;3,20", "S-1;;1;", "A-1;;0;", "B-9;;1;"); var mapping = ImportService.SuggestMapping(imports.Target("giacenze-iniziali"), stock.Headers); var preview = await imports.PreviewAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions()); - Assert.IsFalse(preview.CanApply); + Assert.IsTrue(preview.CanApply); Assert.AreEqual(ImportOutcome.Ok, preview.Rows[0].Outcome, string.Join("; ", preview.Rows[0].Messages.Select(m => m.Field + ":" + m.Code))); Assert.AreEqual(ImportErrors.NotStocked, preview.Rows[1].Messages.Single().Code); CollectionAssert.Contains(preview.Rows[2].Messages.Select(m => m.Code).ToList(), ImportErrors.Positive); Assert.AreEqual(ImportErrors.CodeUnknown, preview.Rows[3].Messages.Single().Code); - var refused = await Assert.ThrowsExactlyAsync(() => imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions())); - Assert.AreEqual(ImportErrors.CheckOnly, refused.Code); + + var report = await imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions()); + Assert.AreEqual(1, report.Created); + var row = (await stockService.StockAsync(Root, company, new Khaemhat.Application.Inventory.StockFilter())).Single(); + Assert.AreEqual((5m, 3.2m), (row.OnHand, row.AverageCost)); await app.StopAsync(); } } diff --git a/tests/Khaemhat.Web.Tests/Inventory/DemoPurchasesTests.cs b/tests/Khaemhat.Web.Tests/Inventory/DemoPurchasesTests.cs new file mode 100644 index 0000000..fd9f284 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/DemoPurchasesTests.cs @@ -0,0 +1,74 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Purchases; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Seeding; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Security; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Inventory; + +/// +/// The demo purchases and warehouse (SPEC §14, issue #61): the opening stock, the orders, the receipts and the invoices +/// made through the engine, a self-invoice still to issue, items under their minimum and a stock take being counted. +/// +[TestClass] +public sealed class DemoPurchasesTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task DemoSeed_MakesPurchasesAndStock_Once() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await app.Services.GetRequiredService().RunAsync(company, SeedKind.Demo); + var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); + await app.Services.GetRequiredService().SeedAsync(company, context); + var seeder = app.Services.GetRequiredService(); + await seeder.SeedAsync(company, context); + + var editor = app.Services.GetRequiredService(); + var all = await AllAsync(editor, company); + int Count(DocumentKind kind, DocumentStatus status) => all.Count(r => r.Kind == kind && r.Status == status); + Assert.AreEqual(1, Count(DocumentKind.PurchaseOrder, DocumentStatus.Fulfilled), "One order received in full."); + Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.PurchaseOrder && r.Status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled), + "One order still partly on its way."); + Assert.AreEqual(2, all.Count(r => r.Kind == DocumentKind.PurchaseDeliveryNote)); + Assert.AreEqual(3, all.Count(r => r.Kind == DocumentKind.PurchaseInvoice && r.Status != DocumentStatus.Draft)); + Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.InventoryEntry)); + Assert.IsTrue(all.All(r => r.Date.Year == DateTime.Now.Year && r.Date <= DateOnly.FromDateTime(DateTime.Now)), "Dates of this year, never in the future."); + + // The German invoice waits for its self-invoice; the stock has items under the minimum to reorder. + var pending = await app.Services.GetRequiredService().PendingSelfInvoicesAsync(Root, company); + Assert.HasCount(1, pending); + var inventory = app.Services.GetRequiredService(); + Assert.IsNotEmpty(await inventory.StockAsync(Root, company, new StockFilter())); + Assert.IsNotEmpty(await app.Services.GetRequiredService().ProposalsAsync(Root, company)); + var take = (await app.Services.GetRequiredService().ListAsync(Root, company)).Single(); + Assert.AreEqual(StockTakeStatus.Open, take.Status); + + // Run again, nothing changes. + await seeder.SeedAsync(company, context); + Assert.HasCount(all.Count, await AllAsync(editor, company)); + await app.StopAsync(); + } + } + + private static async Task> AllAsync(DocumentEditor editor, string company) + { + var all = new List(); + foreach (var family in new[] { DocumentFamily.PurchaseOrder, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument }) + { + all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues()], new ListQuery { Limit = 200 })).Items); + } + + return all; + } +} diff --git a/tests/Khaemhat.Web.Tests/Inventory/InventoryFlowTests.cs b/tests/Khaemhat.Web.Tests/Inventory/InventoryFlowTests.cs new file mode 100644 index 0000000..d07617f --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/InventoryFlowTests.cs @@ -0,0 +1,167 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Items; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Inventory; + +/// +/// The warehouse on a real instance (issue #59): receipts load at their cost, deliveries unload at the average, +/// cancelling gives the stock back, transfers move between warehouses, orders hold committed and ordered quantities. +/// +[TestClass] +public sealed class InventoryFlowTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task Documents_MoveTheStock_AndTheAverageCost() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var stock = app.Services.GetRequiredService(); + var tables = app.Services.GetRequiredService(); + var supplier = await PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897"); + var customer = await PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304"); + var item = await ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", minimum: 5m); + var day = new DateOnly(DateTime.Now.Year, 2, 1); + + // 10 pieces at 10 euro, then 10 at 13: the average is 11.5. + var first = await ReceiptAsync(engine, company, supplier, item, day, 10m, 10m); + await ReceiptAsync(engine, company, supplier, item, day.AddDays(1), 10m, 13m); + var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual(20m, row.OnHand); + Assert.AreEqual(11.5m, row.AverageCost); + Assert.AreEqual(230m, row.Value); + + // A delivery note unloads at the average. + var note = await engine.NewAsync(Root, company, "DDT"); + note.Header.PartyId = customer; + note.Header.DocumentDate = day.AddDays(2); + note.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola a sfera 1/2", Quantity = 16m, Price = 20m }); + note = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, (await engine.SaveAsync(Root, company, note)).Header.Id); + var moves = await stock.MovementsAsync(Root, company, item, null, null, null); + Assert.HasCount(3, moves); + Assert.AreEqual(-16m, moves[2].Quantity); + Assert.AreEqual(11.5m, moves[2].UnitCost); + Assert.AreEqual(4m, moves[2].Balance); + Assert.AreEqual(note.Header.DocumentNumber, moves[2].Number); + Assert.AreEqual("Rossi Impianti S.r.l.", moves[2].PartyName); + row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual(StockLevel.Understock, row.Level, "4 left, 5 the minimum."); + Assert.AreEqual(item, (await stock.UnderstockAsync(Root, company)).Single().ItemId); + + // Cancelling the first receipt re-runs the history: the average is that of the second. + await engine.CancelAsync(Root, company, DocumentFamily.PurchaseDocument, first.Header.Id, null); + row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual(-6m, row.OnHand); + Assert.AreEqual(13m, row.AverageCost); + Assert.AreEqual(StockLevel.Out, row.Level); + + // The value at a date before the cancelled history. + var valuation = await stock.ValuationAsync(Root, company, day.AddDays(1), null, StockValuationMethod.WeightedAverage); + Assert.AreEqual((10m, 13m, 130m, 'A'), (valuation.Single().Quantity, valuation[0].UnitCost, valuation[0].Value, valuation[0].AbcClass)); + + // A transfer moves the quantity, not the value. + var other = await tables.SaveAsync(Root, company, new Warehouse { Code = "FURG", Description = "Furgone" }); + var transfer = await engine.NewAsync(Root, company, "MM"); + transfer.Header.DocumentDate = day.AddDays(3); + transfer.Header.InventoryReasonId = (await tables.ActiveAsync(Root, company)).Single(r => r.Code == "TRA").Id; + transfer.Header.ToWarehouseId = other.Id; + transfer.Lines.Add(new InventoryDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola", Quantity = 2m }); + await engine.ConfirmAsync(Root, company, DocumentFamily.InventoryDocument, (await engine.SaveAsync(Root, company, transfer)).Header.Id); + var balances = await stock.BalancesAsync(Root, company, item); + Assert.AreEqual(2m, balances.Single(b => b.WarehouseId == other.Id).OnHand); + Assert.AreEqual(-8m, balances.Single(b => b.WarehouseId != other.Id).OnHand); + Assert.AreEqual(-6m, balances.Sum(b => b.OnHand)); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Orders_HoldCommittedAndOrderedQuantities_UntilTheyAreFulfilled() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var copies = app.Services.GetRequiredService(); + var stock = app.Services.GetRequiredService(); + var supplier = await PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897"); + var customer = await PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304"); + var item = await ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", minimum: null); + var day = new DateOnly(DateTime.Now.Year, 3, 1); + + var order = await engine.NewAsync(Root, company, "OC"); + order.Header.PartyId = customer; + order.Header.DocumentDate = day; + order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Tubo", Quantity = 50m, Price = 2m }); + order = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleOrder, (await engine.SaveAsync(Root, company, order)).Header.Id); + + var purchase = await engine.NewAsync(Root, company, "OF"); + purchase.Header.PartyId = supplier; + purchase.Header.DocumentDate = day; + purchase.Lines.Add(new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Tubo", Quantity = 100m, Price = 1m }); + purchase = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, (await engine.SaveAsync(Root, company, purchase)).Header.Id); + + var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual((0m, 50m, 100m, -50m), (row.OnHand, row.Committed, row.Ordered, row.Available)); + + // Receiving 60 of the order: 60 on hand, 40 still ordered. + var receipt = await copies.MergeAsync(Root, company, DocumentFamily.PurchaseOrder, [purchase.Header.Id], "DDTF", day.AddDays(5)); + receipt.Lines.Single(l => l.Kind == DocumentLineKind.Item).Quantity = 60m; + await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, (await engine.SaveAsync(Root, company, receipt)).Header.Id); + row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual((60m, 50m, 40m, 10m), (row.OnHand, row.Committed, row.Ordered, row.Available)); + Assert.AreEqual(1m, row.AverageCost, "The cost of the receipt comes from the order price."); + + // Closing the customer order frees what it committed. + await engine.CloseAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id); + row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual(0m, row.Committed); + await app.StopAsync(); + } + } + + internal static async Task ReceiptAsync(DocumentEngine engine, string company, long supplier, long item, DateOnly date, decimal quantity, decimal price) + { + var receipt = await engine.NewAsync(Root, company, "DDTF"); + receipt.Header.PartyId = supplier; + receipt.Header.DocumentDate = date; + receipt.Header.ExternalReference = "B" + date.DayNumber.ToString(System.Globalization.CultureInfo.InvariantCulture); + receipt.Lines.Add(new PurchaseDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Carico", Quantity = quantity, Price = price }); + receipt = await engine.SaveAsync(Root, company, receipt); + return await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, receipt.Header.Id); + } + + internal static async Task ItemAsync(WebApplication app, string company, string code, string description, decimal? minimum) + { + var items = app.Services.GetRequiredService(); + var record = await items.NewAsync(Root, company); + record.Item.Code = code; + record.Item.Description = description; + record.Item.MinimumStock = minimum; + return (await items.SaveAsync(Root, company, record)).Item.Id; + } + + internal static async Task PartyAsync(WebApplication app, string company, PartyKind kind, string name, string vatNumber) + { + var parties = app.Services.GetRequiredService(); + var record = await parties.NewAsync(Root, company, kind); + record.Party.Name = name; + record.Party.VatNumber = vatNumber; + return (await parties.SaveAsync(Root, company, record)).Party.Id; + } +} diff --git a/tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs b/tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs new file mode 100644 index 0000000..d5acc32 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs @@ -0,0 +1,148 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Purchases; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Fiscal.Italy; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Inventory; + +/// +/// The purchases on a real instance (issues #55, #56, #58): order, receipt and invoice with protocol and VAT date, +/// the duplicate check, the price differences, the cost of the receipt corrected by the invoice, the self-invoice. +/// +[TestClass] +public sealed class PurchaseFlowTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task Invoice_GetsItsProtocol_RefusesDuplicates_AndCorrectsTheCostOfTheReceipt() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var copies = app.Services.GetRequiredService(); + var purchases = app.Services.GetRequiredService(); + var stock = app.Services.GetRequiredService(); + var vat22 = (await app.Services.GetRequiredService().ActiveAsync(Root, company)).Single(t => t.Code == "22").Id; + var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897"); + var item = await InventoryFlowTests.ItemAsync(app, company, "RACC-20", "Raccordo 20 mm", null); + var day = new DateOnly(DateTime.Now.Year, 4, 1); + + var order = await engine.NewAsync(Root, company, "OF"); + order.Header.PartyId = supplier; + order.Header.DocumentDate = day; + order.Lines.Add(new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Raccordo", Quantity = 10m, Price = 2m, TaxCodeId = vat22 }); + order = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, (await engine.SaveAsync(Root, company, order)).Header.Id); + Assert.IsNotNull(order.Header.DocumentNumber, "Supplier orders are numbered."); + + var receipt = await copies.MergeAsync(Root, company, DocumentFamily.PurchaseOrder, [order.Header.Id], "DDTF", day.AddDays(3)); + receipt.Header.ExternalReference = "DDT 77"; + receipt = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, (await engine.SaveAsync(Root, company, receipt)).Header.Id); + Assert.AreEqual(2m, (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item).AverageCost); + + // The invoice of the receipt costs 2.50 a piece: the difference shows, and the receipt takes its cost. + var invoice = await copies.MergeAsync(Root, company, DocumentFamily.PurchaseDocument, [receipt.Header.Id], "FF", day.AddDays(10)); + var line = invoice.Lines.Single(l => l.Kind == DocumentLineKind.Item); + line.Price = 2.5m; + invoice = await engine.SaveAsync(Root, company, invoice); + var differences = await purchases.PriceDifferencesAsync(Root, company, invoice); + Assert.AreEqual((2m, 2.5m, 5m), (differences.Single().SourcePrice, differences[0].InvoicePrice, differences[0].Amount)); + + // Without the supplier's number and date the invoice is not registered. + invoice.Header.ExternalReference = null; + invoice = await engine.SaveAsync(Root, company, invoice); + var missing = await Assert.ThrowsExactlyAsync(() => engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, invoice.Header.Id)); + CollectionAssert.Contains(missing.Errors.ToArray(), "ExternalReference:" + DocumentErrors.SupplierNumberRequired); + + invoice.Header.ExternalReference = "125/A"; + invoice.Header.ExternalDate = day.AddDays(8); + invoice = await engine.SaveAsync(Root, company, invoice); + invoice = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, invoice.Header.Id); + Assert.AreEqual(1L, invoice.Header.VatProtocol); + Assert.AreEqual("1", invoice.Header.DocumentNumber); + Assert.AreEqual(day.AddDays(10), invoice.Header.VatDate, "The VAT date defaults to the registration."); + var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual(10m, row.OnHand, "The invoice of a receipt does not load again."); + Assert.AreEqual(2.5m, row.AverageCost, "The invoice corrects the cost of the receipt."); + + // The same number of the same supplier in the same year is refused. + var again = await engine.NewAsync(Root, company, "FF"); + again.Header.PartyId = supplier; + again.Header.ExternalReference = "125/A"; + again.Header.ExternalDate = day.AddDays(8); + again.Lines.Add(new PurchaseDocumentLine { Kind = DocumentLineKind.Free, Description = "Spese", Quantity = 1m, Price = 10m, TaxCodeId = vat22 }); + var duplicate = await Assert.ThrowsExactlyAsync(() => engine.SaveAsync(Root, company, again)); + CollectionAssert.Contains(duplicate.Errors.ToArray(), "ExternalReference:" + DocumentErrors.SupplierDuplicate); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task ForeignServices_NeedASelfInvoice_ByThe15thOfTheNextMonth() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var purchases = app.Services.GetRequiredService(); + var parties = app.Services.GetRequiredService(); + var taxes = await app.Services.GetRequiredService().ActiveAsync(Root, company); + var outside = taxes.First(t => t.Nature is not null && t.Nature.StartsWith("N2", StringComparison.Ordinal)).Id; + var record = await parties.NewAsync(Root, company, PartyKind.Supplier); + record.Party.Name = "Cloud Services GmbH"; + record.Party.SubjectType = SubjectType.EuCompany; + record.Party.CountryCode = "DE"; + record.Party.VatNumber = "DE123456789"; + var supplier = (await parties.SaveAsync(Root, company, record)).Party.Id; + var day = new DateOnly(DateTime.Now.Year, 5, 20); + + var invoice = await engine.NewAsync(Root, company, "FF"); + invoice.Header.PartyId = supplier; + invoice.Header.DocumentDate = day; + invoice.Header.ExternalReference = "INV-2026-0042"; + invoice.Header.ExternalDate = day.AddDays(-2); + invoice.Lines.Add(new PurchaseDocumentLine { Kind = DocumentLineKind.Free, Description = "Abbonamento software maggio", Quantity = 1m, Price = 100m, TaxCodeId = outside }); + invoice = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, (await engine.SaveAsync(Root, company, invoice)).Header.Id); + + var advice = await purchases.AdviseAsync(Root, company, invoice); + Assert.AreEqual("AF17", advice!.DocumentTypeCode); + Assert.AreEqual(new DateOnly(day.Year, 6, 15), advice.Deadline); + Assert.AreEqual(invoice.Header.Id, (await purchases.PendingSelfInvoicesAsync(Root, company)).Single().Invoice.Id); + + var self = await purchases.CreateSelfInvoiceAsync(Root, company, invoice.Header.Id, null); + Assert.AreEqual(DocumentKind.SelfInvoice, self.Header.Kind); + Assert.AreEqual("INV-2026-0042", self.Header.RelatedNumber); + Assert.AreEqual(taxes.Single(t => t.Code == "22").Id, self.Lines.Single().TaxCodeId, "The integration applies the ordinary rate."); + Assert.AreEqual(22m, self.Header.TaxAmount); + self = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, self.Header.Id); + Assert.IsNotNull(self.Header.DocumentNumber); + Assert.IsEmpty(await purchases.PendingSelfInvoicesAsync(Root, company), "An integrated invoice no longer waits."); + await app.StopAsync(); + } + } + + [TestMethod] + public void ItalianRules_ChooseTheTypeOfTheSelfInvoice() + { + var rules = new SelfInvoiceRulesIt(); + var day = new DateOnly(2026, 12, 3); + Assert.AreEqual("AF16", rules.Advise(new SelfInvoiceCase("IT", false, false, ["N6.3"], day))!.DocumentTypeCode); + Assert.IsNull(rules.Advise(new SelfInvoiceCase("IT", false, true, [], day))); + Assert.AreEqual("AF18", rules.Advise(new SelfInvoiceCase("FR", true, true, ["N3.2"], day))!.DocumentTypeCode); + Assert.AreEqual("AF19", rules.Advise(new SelfInvoiceCase("CH", false, true, [], day))!.DocumentTypeCode); + Assert.AreEqual("AF17", rules.Advise(new SelfInvoiceCase("US", false, false, [], day))!.DocumentTypeCode); + Assert.AreEqual(new DateOnly(2027, 1, 15), rules.Deadline("AF17", day)); + Assert.AreEqual(day.AddDays(90), rules.Deadline("AF20", day)); + } +} diff --git a/tests/Khaemhat.Web.Tests/Inventory/PurchaseImportTests.cs b/tests/Khaemhat.Web.Tests/Inventory/PurchaseImportTests.cs new file mode 100644 index 0000000..9ab6512 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/PurchaseImportTests.cs @@ -0,0 +1,170 @@ +using System.IO.Compression; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Files; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Purchases; +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Files; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Inventory; + +/// +/// The import of supplier e-invoices on a real instance (issue #57): the supplier is added from the file, the items found +/// by code, the tax codes by rate and nature; the draft keeps the file; the same invoice is not registered twice; a ZIP +/// holds several files. +/// +[TestClass] +public sealed class PurchaseImportTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + private static string Invoice(string type, string number, string date, string lines, string summary, string total) => $""" + + + + + IT01234567897 + 00042FPR120000000 + + + + IT01234567897 + Ferramenta Piemontese S.r.l. + RF01 + + Via Roma1210121TorinoTOIT + + + + IT02987654304 + Azienda di prova + + Corso Milano20121MilanoMIIT + + + + + + {type}EUR{date}{number} + {total}Fornitura di marzo + + + {lines}{summary} + + + """; + + private const string Lines = """ + + 1 + SKUVALV-01 + Valvola a sfera 1/210.00PZ4.000000 + SC10.00 + 36.0022.00 + + + 2Spese di trasporto15.0015.0022.00 + + """; + + private const string Summary = """ + 22.0051.0011.22I + """; + + [TestMethod] + public async Task Import_AddsTheSupplier_MatchesItemsAndTaxes_AndRefusesTheSameInvoiceTwice() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var import = app.Services.GetRequiredService(); + var engine = app.Services.GetRequiredService(); + var attachments = app.Services.GetRequiredService(); + var parties = app.Services.GetRequiredService(); + var item = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null); + var year = DateTime.Now.Year; + var xml = Encoding.UTF8.GetBytes(Invoice("TD01", "FT/123", $"{year}-03-15", Lines, Summary, "62.22")); + + var reading = await import.ReadAsync(Root, company, [("IT01234567897_00042.xml", xml)]); + Assert.IsEmpty(reading.Rejected); + var candidate = reading.Invoices.Single(); + Assert.AreEqual(("FF", null, false, 62.22m), (candidate.DocumentTypeCode, candidate.SupplierId, candidate.Duplicate, candidate.ComputedTotal)); + Assert.IsEmpty(candidate.Problems); + + var done = (await import.ImportAsync(Root, company, reading.Invoices)).Single(); + Assert.IsNull(done.Error); + Assert.IsTrue(done.SupplierCreated); + Assert.IsEmpty(done.Warnings); + var record = done.Record!; + Assert.AreEqual((DocumentKind.PurchaseInvoice, DocumentStatus.Draft, "FT/123", new DateOnly(year, 3, 15)), + (record.Header.Kind, record.Header.Status, record.Header.ExternalReference, record.Header.ExternalDate)); + Assert.AreEqual(62.22m, record.Header.TotalAmount); + var valve = record.Lines.Single(l => l.Kind == DocumentLineKind.Item); + Assert.AreEqual((item, 10m, 4m, "10"), (valve.ItemId!.Value, valve.Quantity, valve.Price, valve.DiscountFormula)); + Assert.AreEqual(DocumentLineKind.Free, record.Lines.Single(l => l.Description == "Spese di trasporto").Kind); + var supplier = (await parties.GetAsync(Root, company, record.Header.PartyId!.Value))!.Party; + Assert.AreEqual(("Ferramenta Piemontese S.r.l.", "01234567897", PartyKind.Supplier, "Torino", "TO"), + (supplier.Name, supplier.VatNumber, supplier.Kind, supplier.City, supplier.Province)); + var files = await attachments.ListAsync(Root, company, DocumentPrintService.EntityOf(DocumentFamily.PurchaseDocument), record.Header.Id); + Assert.AreEqual((AttachmentKind.EInvoice, "IT01234567897_00042.xml"), (files.Single().Kind, files[0].FileName)); + + // The same file again: the supplier is known and the invoice is a duplicate. + var again = (await import.ReadAsync(Root, company, [("IT01234567897_00042.xml", xml)])).Invoices.Single(); + Assert.AreEqual((supplier.Id, true, false), (again.SupplierId!.Value, again.Duplicate, again.CanImport)); + CollectionAssert.Contains(again.Problems.ToArray(), PurchaseInvoiceImportService.DuplicateProblem); + + // A ZIP with a credit note, a self-invoice the company sent itself and a stray file. + var credit = Encoding.UTF8.GetBytes(Invoice("TD04", "NC/7", $"{year}-03-20", Lines, Summary, "62.22")); + var self = Encoding.UTF8.GetBytes(Invoice("TD17", "AF/1", $"{year}-03-21", Lines, Summary, "62.22")); + using var zip = new MemoryStream(); + using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true)) + { + await Add(archive, "nc.xml", credit); + await Add(archive, "af.xml", self); + await Add(archive, "leggimi.txt", Encoding.UTF8.GetBytes("nothing")); + } + + var zipped = await import.ReadAsync(Root, company, [("marzo.zip", zip.ToArray()), ("rotto.xml", Encoding.UTF8.GetBytes(""))]); + Assert.AreEqual("rotto.xml", zipped.Rejected.Single().FileName); + Assert.HasCount(2, zipped.Invoices); + var note = zipped.Invoices.Single(i => i.Invoice.Number == "NC/7"); + Assert.AreEqual(("NCF", supplier.Id), (note.DocumentTypeCode, note.SupplierId!.Value)); + var unsupported = zipped.Invoices.Single(i => i.Invoice.Number == "AF/1"); + Assert.IsFalse(unsupported.CanImport); + CollectionAssert.Contains(unsupported.Problems.ToArray(), PurchaseInvoiceImportService.UnsupportedType); + + var results = await import.ImportAsync(Root, company, zipped.Invoices); + Assert.AreEqual(DocumentKind.PurchaseCreditNote, results.Single(r => r.Candidate == note).Record!.Header.Kind); + Assert.AreEqual(PurchaseInvoiceImportService.UnsupportedType, results.Single(r => r.Candidate == unsupported).Error); + + // Confirmed, the imported invoice takes its protocol like one typed. + var confirmed = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, record.Header.Id); + Assert.IsNotNull(confirmed.Header.VatProtocol); + await app.StopAsync(); + } + } + + [TestMethod] + public void ItalianRules_RegisterInvoicesAndCreditNotes() + { + var rules = new Khaemhat.Fiscal.Italy.IncomingInvoiceRulesIt(); + Assert.AreEqual("FF", rules.DocumentTypeCode("TD01")); + Assert.AreEqual("FF", rules.DocumentTypeCode("td24")); + Assert.AreEqual("NCF", rules.DocumentTypeCode("TD04")); + Assert.IsNull(rules.DocumentTypeCode("TD17")); + Assert.IsInstanceOfType(rules); + } + + private static async Task Add(ZipArchive archive, string name, byte[] content) + { + await using var stream = archive.CreateEntry(name).Open(); + await stream.WriteAsync(content); + } +} diff --git a/tests/Khaemhat.Web.Tests/Inventory/StockTakeAndReorderTests.cs b/tests/Khaemhat.Web.Tests/Inventory/StockTakeAndReorderTests.cs new file mode 100644 index 0000000..ffaf434 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/StockTakeAndReorderTests.cs @@ -0,0 +1,197 @@ +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Inventory; +using Khaemhat.Application.Items; +using Khaemhat.Application.Security; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Inventory; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Inventory; + +/// +/// The physical stock take, the reorder proposal and the rebuild of the warehouse on a real instance (issue #60). +/// +[TestClass] +public sealed class StockTakeAndReorderTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public async Task StockTake_PostsGainsAndLosses_AtTheDateOfTheCount() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var stock = app.Services.GetRequiredService(); + var takes = app.Services.GetRequiredService(); + var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897"); + var valve = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null); + var pipe = await InventoryFlowTests.ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", null); + var day = new DateOnly(DateTime.Now.Year, 6, 1); + await InventoryFlowTests.ReceiptAsync(engine, company, supplier, valve, day, 10m, 4m); + await InventoryFlowTests.ReceiptAsync(engine, company, supplier, pipe, day, 100m, 1.5m); + var warehouse = (await stock.BalancesAsync(Root, company, valve)).Single().WarehouseId; + + var take = await takes.CreateAsync(Root, company, warehouse, day.AddDays(1), null, null); + Assert.AreEqual(10m, take.Lines.Single(l => l.Code == "VALV-01").Line.BookQuantity); + Assert.AreEqual(4m, take.Lines.Single(l => l.Code == "VALV-01").Line.UnitCost); + + // Nothing counted, nothing to post. + var empty = await Assert.ThrowsExactlyAsync(() => takes.PostAsync(Root, company, take.Take.Id)); + CollectionAssert.Contains(empty.Errors.ToArray(), ":" + StockTakeService.NothingCounted); + + // The counts come from a reader file: 12 valves (2 more), 95 pipes (5 less), an unknown code. + using var file = new MemoryStream(Encoding.UTF8.GetBytes("Codice;Quantità\nVALV-01;12\nTUBO-16;90\nTUBO-16;5\nXX-99;1\n")); + var imported = await takes.ImportCountsAsync(Root, company, take.Take.Id, file); + Assert.AreEqual(2, imported.Applied); + Assert.AreEqual("5: XX-99", imported.Unknown.Single()); + take = (await takes.GetAsync(Root, company, take.Take.Id))!; + Assert.AreEqual(2, take.Counted); + Assert.AreEqual(2m * 4m - 5m * 1.5m, take.DifferenceValue); + + take = await takes.PostAsync(Root, company, take.Take.Id); + Assert.AreEqual(StockTakeStatus.Posted, take.Take.Status); + Assert.IsNotNull(take.Take.AdjustmentDocumentId); + Assert.IsNotNull(take.Take.LossDocumentId); + var rows = await stock.StockAsync(Root, company, new StockFilter()); + Assert.AreEqual(12m, rows.Single(r => r.ItemId == valve).OnHand); + Assert.AreEqual(95m, rows.Single(r => r.ItemId == pipe).OnHand); + var moves = await stock.MovementsAsync(Root, company, pipe, null, null, null); + Assert.AreEqual((-5m, day.AddDays(1)), (moves[^1].Quantity, moves[^1].Date)); + + // A posted take is closed. + var closed = await Assert.ThrowsExactlyAsync(() => takes.SaveCountsAsync(Root, company, take.Take.Id, new Dictionary())); + CollectionAssert.Contains(closed.Errors.ToArray(), ":" + StockTakeService.NotOpen); + await app.StopAsync(); + } + } + + [TestMethod] + public void CountRows_AcceptItalianAndInvariantNumbers() + { + Assert.AreEqual(("A-1", 1234.5m), StockTakeService.ParseCount("A-1;1.234,5")); + Assert.AreEqual(("A-1", 3m), StockTakeService.ParseCount("A-1\t3")); + Assert.AreEqual(("A-1", 2.5m), StockTakeService.ParseCount("\"A-1\",2.5")); + Assert.IsNull(StockTakeService.ParseCount("Codice;Quantità")); + Assert.IsNull(StockTakeService.ParseCount("A-1;-3")); + Assert.IsNull(StockTakeService.ParseCount(" ")); + } + + [TestMethod] + public void ReorderQuantity_UsesTheLotAndTheSupplierMinimum() + { + Assert.AreEqual(0m, ReorderService.Quantity(11m, 5m, 10m, null, null), "Covered above the reorder point."); + Assert.AreEqual(4m, ReorderService.Quantity(6m, 5m, 10m, null, null), "Back to the reorder point."); + Assert.AreEqual(25m, ReorderService.Quantity(6m, 5m, 10m, 25m, null), "One lot."); + Assert.AreEqual(30m, ReorderService.Quantity(-12m, 5m, 10m, 10m, null), "As many lots as it takes: 22 missing, three lots."); + Assert.AreEqual(50m, ReorderService.Quantity(6m, 5m, 10m, null, 50m), "At least the supplier minimum."); + Assert.AreEqual(0m, ReorderService.Quantity(5m, 5m, null, null, null), "At the minimum, without a reorder point."); + Assert.AreEqual(1m, ReorderService.Quantity(4m, 5m, null, null, null)); + Assert.AreEqual(0m, ReorderService.Quantity(-3m, null, null, null, null), "No thresholds, no proposal."); + } + + [TestMethod] + public async Task Reorder_ProposesTheItemsUnderTheirPoint_AndOrdersThemBySupplier() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var reorder = app.Services.GetRequiredService(); + var items = app.Services.GetRequiredService(); + var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897"); + var other = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Ferramenta Sud S.p.A.", "00743110157"); + var valve = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", 5m); + var record = await items.GetAsync(Root, company, valve); + record!.Item.ReorderPoint = 10m; + record.Item.ReorderLot = 24m; + record.Suppliers.Add(new ItemSupplier { PartyId = supplier, SupplierCode = "VS-12", Price = 3.8m, LeadTimeDays = 7, IsDefault = true }); + await items.SaveAsync(Root, company, record); + var pipe = await InventoryFlowTests.ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", 50m); + var plenty = await InventoryFlowTests.ItemAsync(app, company, "RACC-20", "Raccordo 20 mm", 5m); + var day = new DateOnly(DateTime.Now.Year, 7, 1); + await InventoryFlowTests.ReceiptAsync(engine, company, supplier, valve, day, 6m, 4m); + await InventoryFlowTests.ReceiptAsync(engine, company, supplier, plenty, day, 30m, 1m); + + var proposals = await reorder.ProposalsAsync(Root, company); + Assert.HasCount(2, proposals); + var first = proposals[0]; + Assert.AreEqual((valve, 24m, supplier, 3.8m), (first.ItemId, first.Quantity, first.SupplierId, first.Price)); + Assert.IsNotNull(first.ExpectedDate); + Assert.AreEqual((pipe, 50m), (proposals[1].ItemId, proposals[1].Quantity), "No supplier: last, to be chosen."); + Assert.IsNull(proposals[1].SupplierId); + + var invalid = await Assert.ThrowsExactlyAsync(() => reorder.CreateOrdersAsync(Root, company, [new ReorderChoice(pipe, 0, 50m)])); + CollectionAssert.Contains(invalid.Errors.ToArray(), ":" + ReorderService.ChoiceInvalid); + + var orders = await reorder.CreateOrdersAsync(Root, company, [new ReorderChoice(valve, supplier, 24m), new ReorderChoice(pipe, other, 60m)]); + Assert.HasCount(2, orders); + Assert.IsTrue(orders.All(o => o.Header.Kind == DocumentKind.PurchaseOrder && o.Header.Status == DocumentStatus.Draft)); + var valveLine = orders.Single(o => o.Header.PartyId == supplier).Lines.Single(l => l.Kind == DocumentLineKind.Item); + Assert.AreEqual((valve, 24m, 3.8m), (valveLine.ItemId, valveLine.Quantity, valveLine.Price)); + Assert.AreEqual(60m, orders.Single(o => o.Header.PartyId == other).Lines.Single(l => l.Kind == DocumentLineKind.Item).Quantity); + + // Confirmed, the order covers the valve: it is no longer proposed. + await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, orders.Single(o => o.Header.PartyId == supplier).Header.Id); + Assert.IsFalse((await reorder.ProposalsAsync(Root, company)).Any(p => p.ItemId == valve)); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Rebuild_WritesTheSameStockAgain_AndTheJobRunsForEveryCompany() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var engine = app.Services.GetRequiredService(); + var stock = app.Services.GetRequiredService(); + var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897"); + var customer = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304"); + var item = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null); + var day = new DateOnly(DateTime.Now.Year, 8, 1); + await InventoryFlowTests.ReceiptAsync(engine, company, supplier, item, day, 10m, 10m); + await InventoryFlowTests.ReceiptAsync(engine, company, supplier, item, day.AddDays(1), 10m, 13m); + var note = await engine.NewAsync(Root, company, "DDT"); + note.Header.PartyId = customer; + note.Header.DocumentDate = day.AddDays(2); + note.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola", Quantity = 4m, Price = 20m }); + await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, (await engine.SaveAsync(Root, company, note)).Header.Id); + var before = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + var movesBefore = await stock.MovementsAsync(Root, company, item, null, null, null); + + var phases = new List(); + var (documents, items) = await stock.RebuildAsync(Root, company, new SyncProgress(p => phases.Add(p.Phase))); + Assert.AreEqual(3, documents); + Assert.IsGreaterThanOrEqualTo(1, items); + CollectionAssert.Contains(phases, RebuildPhase.Documents); + CollectionAssert.Contains(phases, RebuildPhase.Items); + var after = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item); + Assert.AreEqual((before.OnHand, before.AverageCost, before.Value), (after.OnHand, after.AverageCost, after.Value)); + var movesAfter = await stock.MovementsAsync(Root, company, item, null, null, null); + CollectionAssert.AreEqual(movesBefore.Select(m => (m.Date, m.Quantity, m.UnitCost)).ToList(), movesAfter.Select(m => (m.Date, m.Quantity, m.UnitCost)).ToList()); + + // Without the right to post, no rebuild. + var reader = new Actor("lucia", UserLevel.Standard, null, 999, company); + await Assert.ThrowsExactlyAsync(() => stock.RebuildAsync(reader, company)); + + var job = app.Services.GetServices().Single(j => j.Type == InventoryRebuildJob.JobType); + var summary = await job.RunAsync(null!, CancellationToken.None); + StringAssert.Contains(summary, "3 documenti"); + Assert.AreEqual(after.OnHand, (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item).OnHand); + await app.StopAsync(); + } + } + + // Reports at once, unlike Progress which posts to the thread pool. + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(RebuildProgress value) => report(value); + } +}