Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f8cb57a08 | ||
|
|
4b759ee96e | ||
|
|
cd4cb85562 | ||
|
|
ced689b297 | ||
|
|
eb301fa570 | ||
|
|
f8b72f4d17 | ||
|
|
eeabb12f96 | ||
|
|
20b2421eea | ||
|
|
9a40adecfe | ||
|
|
2c56c0dff0 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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).
|
||||
@@ -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
|
||||
|
||||

|
||||
*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)).
|
||||

|
||||
|
||||
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*).
|
||||
|
||||

|
||||
*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.
|
||||

|
||||
|
||||
## Fatture di acquisto
|
||||
|
||||

|
||||
*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
|
||||

|
||||
|
||||

|
||||
*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)
|
||||
|
||||

|
||||
*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).*
|
||||

|
||||
|
||||
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):
|
||||

|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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). |
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||

|
||||
|
||||
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.
|
||||
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
|
||||
**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.
|
||||
|
||||

|
||||
|
||||
**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
|
||||
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
|
||||
**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
|
||||
|
||||

|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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à
|
||||
|
||||

|
||||
*Mockup 036 — striscia di indicatori (valore magazzino, articoli gestiti, sottoscorta, sotto riordino, in arrivo) e griglia giacenze con stato (anteprima ridotta).*
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
*Mockup 037 — trasferimento in bozza dal deposito SEDE al deposito furgone, con disponibilità all'origine e valore (anteprima ridotta).*
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
*Mockup 038 — inventario guidato in cinque passi, griglia con giacenza teorica, contato, differenza, valore e rettifica (anteprima ridotta).*
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
*Mockup 039 — proposta di riordino: indicatori, criterio di calcolo, quantità proposta modificabile e fornitore per riga (anteprima ridotta).*
|
||||

|
||||
|
||||
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**.
|
||||

|
||||
|
||||
- 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)
|
||||
@@ -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 |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 177 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 199 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 220 KiB |
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
/// <summary>Error: a line of an invoice without its VAT code.</summary>
|
||||
public const string LineTaxRequired = "document.line.tax-required";
|
||||
|
||||
/// <summary>A supplier invoice needs the number and date the supplier gave it.</summary>
|
||||
public const string SupplierNumberRequired = "document.purchase.number-required";
|
||||
|
||||
/// <summary>The same supplier already has a document of the kind with that number in that year.</summary>
|
||||
public const string SupplierDuplicate = "document.purchase.duplicate";
|
||||
|
||||
/// <summary>The VAT date comes before the date of the supplier document.</summary>
|
||||
public const string VatDateBefore = "document.purchase.vat-date-before";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<string> 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<PurchaseDocument, long>().ListAsync(
|
||||
Query.For<PurchaseDocument>().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);
|
||||
|
||||
@@ -40,6 +40,12 @@ internal interface IDocumentStore
|
||||
/// <returns>The lines.</returns>
|
||||
Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads the headers of the documents in force (neither drafts nor cancelled).</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The headers.</returns>
|
||||
Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads a line.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="id">The line.</param>
|
||||
@@ -136,6 +142,11 @@ internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, strin
|
||||
public async Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<THeader, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
[.. (await uow.Repository<THeader, long>().ListAsync(
|
||||
Query.For<THeader>().Where(h => h.Status != DocumentStatus.Draft && h.Status != DocumentStatus.Cancelled), cancellationToken).ConfigureAwait(false)).Items];
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -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<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The opening stock (<c>giacenze-iniziali</c>): 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.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
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"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "giacenze-iniziali";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => "inventory.entry.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "inventory.stock.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => StockFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> 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<Item, long>().ListAsync(Query.For<Item>(), 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<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var seen = new HashSet<(long, long)>();
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The opening stock (<c>giacenze-iniziali</c>, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted
|
||||
/// become one warehouse movement per warehouse with the reason <c>APE</c> (opening stock), confirmed at the day of the
|
||||
/// import: the stock and the average cost start from there.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
/// <param name="engine">Writes the movements.</param>
|
||||
/// <param name="clock">The day of the movements.</param>
|
||||
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget
|
||||
{
|
||||
/// <summary>The reason of the opening stock.</summary>
|
||||
public const string OpeningReason = "APE";
|
||||
|
||||
/// <summary>Error: the reason APE is missing.</summary>
|
||||
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"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "giacenze-iniziali";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => "inventory.entry.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "inventory.stock.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => StockFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
[.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)];
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> 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<InventoryReason, long>().FindAsync(Query.For<InventoryReason>().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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
|
||||
private async Task<List<(ImportRowResult Result, (Item Item, long WarehouseId, decimal Quantity, decimal Cost)? Stock)>> ReadAsync(
|
||||
ImportContext context, IReadOnlyList<ImportRow> 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<Item, long>().ListAsync(Query.For<Item>(), 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<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var fallback = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().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<ImportMessage>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class InventoryPoster
|
||||
{
|
||||
/// <summary>A transfer needs a destination different from the origin.</summary>
|
||||
public const string TransferDestination = "document.transfer.destination";
|
||||
|
||||
/// <summary>Writes again the movements of a document from its current state and refreshes its items.</summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="family">The family of the document.</param>
|
||||
/// <param name="documentId">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task SyncAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var items = new HashSet<long>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the warehouse from the documents (SPEC §11.6, <i>ricostruzione</i>): 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.
|
||||
/// </summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="progress">Receives the documents posted and the total, then the items and their total.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress<RebuildProgress>? 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<long>();
|
||||
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<Item, long>().ListAsync(Query.For<Item>().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id);
|
||||
var balanced = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>(), 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="itemIds">The items.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task RecomputeAsync(IUnitOfWork uow, IEnumerable<long> itemIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
ArgumentNullException.ThrowIfNull(itemIds);
|
||||
var ids = itemIds.Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var committed = await OpenQuantitiesAsync<SaleOrder, SaleOrderLine>(uow, ids, cancellationToken).ConfigureAwait(false);
|
||||
var ordered = await OpenQuantitiesAsync<PurchaseOrder, PurchaseOrderLine>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The default warehouse of the company: the one marked as such, or the first.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The warehouse, if any.</returns>
|
||||
public static async Task<long?> DefaultWarehouseAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var warehouses = uow.Repository<Warehouse, long>();
|
||||
var marked = await warehouses.FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
return marked?.Id ?? (await warehouses.FindAsync(Query.For<Warehouse>().Where(w => !w.Disabled).OrderBy(w => w.Code), cancellationToken).ConfigureAwait(false))?.Id;
|
||||
}
|
||||
|
||||
/// <summary>The quantity of a line in the base unit of its item.</summary>
|
||||
/// <param name="quantity">The quantity on the line.</param>
|
||||
/// <param name="lineUnit">The unit of the line.</param>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="units">The alternative units of the item.</param>
|
||||
/// <returns>The quantity in the base unit.</returns>
|
||||
public static decimal ToBase(decimal quantity, long? lineUnit, Item item, IEnumerable<ItemUnit> 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<long> items, CancellationToken cancellationToken)
|
||||
{
|
||||
var entries = uow.Repository<InventoryEntry, long>();
|
||||
var lines = uow.Repository<InventoryEntryLine, long>();
|
||||
foreach (var entry in (await entries.ListAsync(Query.For<InventoryEntry>().Where(e => e.SourceFamily == family && e.SourceDocumentId == documentId), cancellationToken)
|
||||
.ConfigureAwait(false)).Items)
|
||||
{
|
||||
foreach (var line in (await lines.ListAsync(Query.For<InventoryEntryLine>().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<DocumentLine> lines, HashSet<long> items, CancellationToken cancellationToken)
|
||||
{
|
||||
if (header.InventoryReasonId is not { } reasonId
|
||||
|| await uow.Repository<InventoryReason, long>().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<StockMovement> 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<InventoryEntry, long>().InsertAsync(entry, cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<InventoryEntryLine, long>();
|
||||
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<List<StockLineInput>> StockLinesAsync(
|
||||
IUnitOfWork uow, DocumentHeader header, IReadOnlyList<DocumentLine> lines, int sign, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new List<StockLineInput>();
|
||||
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<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(i => i.Id);
|
||||
var ids = catalog.Keys.ToList();
|
||||
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().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<long, int>>();
|
||||
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<int> MovedSignAsync(
|
||||
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary<long, int>> 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<InventoryEntry, long>()
|
||||
.ListAsync(Query.For<InventoryEntry>().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<InventoryEntryLine, long>()
|
||||
.ListAsync(Query.For<InventoryEntryLine>().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<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) is not { } item)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var repository = uow.Repository<InventoryEntryLine, long>();
|
||||
var lines = (await repository.ListAsync(
|
||||
Query.For<InventoryEntryLine>().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<long>())
|
||||
.Distinct();
|
||||
var balances = uow.Repository<ItemBalance, long>();
|
||||
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<Dictionary<long, decimal>> InvoicedCostsAsync(IUnitOfWork uow, IReadOnlyList<InventoryEntryLine> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new Dictionary<long, decimal>();
|
||||
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<InventoryEntry, long>()
|
||||
.ListAsync(Query.For<InventoryEntry>().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<DocumentLink, long>().ListAsync(
|
||||
Query.For<DocumentLink>().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<Dictionary<(long, long?), decimal>> OpenQuantitiesAsync<THeader, TLine>(IUnitOfWork uow, List<long> 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<TLine, long>().ListAsync(
|
||||
Query.For<TLine>().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<THeader, long>().ListAsync(
|
||||
Query.For<THeader>().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<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(i => i.Id);
|
||||
var units = (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().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<DocumentHeader?> HeaderAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
Documents.DocumentStores.Of(family).GetAsync(uow, id, cancellationToken);
|
||||
|
||||
private static Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
Documents.DocumentStores.Of(family).LinesAsync(uow, id, cancellationToken);
|
||||
|
||||
private static Task<DocumentLine?> StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The step of a rebuild.</summary>
|
||||
public enum RebuildPhase
|
||||
{
|
||||
/// <summary>Posting the documents.</summary>
|
||||
Documents = 0,
|
||||
|
||||
/// <summary>Computing the items.</summary>
|
||||
Items = 1,
|
||||
}
|
||||
|
||||
/// <summary>How far a rebuild is.</summary>
|
||||
/// <param name="Phase">The step.</param>
|
||||
/// <param name="Done">How many done.</param>
|
||||
/// <param name="Total">How many in all.</param>
|
||||
public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class InventoryRebuildJob(IUnitOfWorkFactory factory, ICompanyRegistry companies) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "inventory.rebuild";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> 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.");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>What the stock screen asks (mockup 036).</summary>
|
||||
public sealed record StockFilter
|
||||
{
|
||||
/// <summary>Code, description or brand.</summary>
|
||||
public string? Search { get; init; }
|
||||
|
||||
/// <summary>One warehouse, or all together.</summary>
|
||||
public long? WarehouseId { get; init; }
|
||||
|
||||
/// <summary>One category.</summary>
|
||||
public long? CategoryId { get; init; }
|
||||
|
||||
/// <summary>Only the items under their minimum stock or reorder point.</summary>
|
||||
public bool UnderstockOnly { get; init; }
|
||||
|
||||
/// <summary>Also the items with nothing on hand, committed or ordered.</summary>
|
||||
public bool IncludeEmpty { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The state of an item under its thresholds.</summary>
|
||||
public enum StockLevel
|
||||
{
|
||||
/// <summary>Enough.</summary>
|
||||
Ok = 0,
|
||||
|
||||
/// <summary>The available quantity reached the reorder point.</summary>
|
||||
Reorder = 1,
|
||||
|
||||
/// <summary>The available quantity is under the minimum stock.</summary>
|
||||
Understock = 2,
|
||||
|
||||
/// <summary>Nothing left, or less than nothing.</summary>
|
||||
Out = 3,
|
||||
}
|
||||
|
||||
/// <summary>A row of the stock screen: an item in one warehouse or in all.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="CategoryId">Its category.</param>
|
||||
/// <param name="UnitOfMeasureId">Its base unit.</param>
|
||||
/// <param name="OnHand">On hand.</param>
|
||||
/// <param name="Committed">Committed to customers.</param>
|
||||
/// <param name="Ordered">Ordered from suppliers.</param>
|
||||
/// <param name="Available">On hand less committed.</param>
|
||||
/// <param name="MinimumStock">The minimum stock.</param>
|
||||
/// <param name="ReorderPoint">The reorder point.</param>
|
||||
/// <param name="AverageCost">The weighted average cost (none without the permission on costs).</param>
|
||||
/// <param name="Value">The value at the average (none without the permission).</param>
|
||||
/// <param name="LastLoad">The last load.</param>
|
||||
/// <param name="LastUnload">The last unload.</param>
|
||||
/// <param name="Level">The state under the thresholds.</param>
|
||||
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);
|
||||
|
||||
/// <summary>A movement of an item, with the balance after it.</summary>
|
||||
/// <param name="Id">The movement.</param>
|
||||
/// <param name="Date">The date.</param>
|
||||
/// <param name="Family">The family of the document.</param>
|
||||
/// <param name="DocumentId">The document.</param>
|
||||
/// <param name="Kind">Its kind.</param>
|
||||
/// <param name="Number">Its number.</param>
|
||||
/// <param name="ReasonCode">The warehouse reason.</param>
|
||||
/// <param name="PartyName">The customer or supplier.</param>
|
||||
/// <param name="WarehouseId">The warehouse.</param>
|
||||
/// <param name="Quantity">Positive loads, negative unloads.</param>
|
||||
/// <param name="UnitCost">The cost (none without the permission).</param>
|
||||
/// <param name="Value">The value (none without the permission).</param>
|
||||
/// <param name="Balance">The balance after the movement, in the warehouses shown.</param>
|
||||
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);
|
||||
|
||||
/// <summary>The value of an item at a date (closing stock, libro inventari).</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="Quantity">On hand at the date.</param>
|
||||
/// <param name="UnitCost">The cost of the method.</param>
|
||||
/// <param name="Value">Quantity times cost.</param>
|
||||
/// <param name="AbcClass">A (the first 80% of the value), B (up to 95%) or C.</param>
|
||||
public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="InventoryPoster"/>; this service only reads them.
|
||||
/// </summary>
|
||||
/// <remarks>Permission <c>inventory.stock.read</c>, movements <c>inventory.entry.read</c>; costs only with <c>items.cost.read</c>.</remarks>
|
||||
public sealed class InventoryService
|
||||
{
|
||||
/// <summary>Permission to read the stock.</summary>
|
||||
public const string StockPermission = "inventory.stock.read";
|
||||
|
||||
/// <summary>Permission to read the movements.</summary>
|
||||
public const string EntryReadPermission = "inventory.entry.read";
|
||||
|
||||
/// <summary>Permission to post movements, stock takes and the rebuild.</summary>
|
||||
public const string PostPermission = "inventory.entry.post";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
}
|
||||
|
||||
/// <summary>The stock of the items, in a warehouse or in all.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="filter">What to show.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows, by code.</returns>
|
||||
public async Task<IReadOnlyList<StockRow>> 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<Item>().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<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false);
|
||||
var rows = new List<StockRow>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The balances of an item in each warehouse.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The balances, costs hidden without the permission.</returns>
|
||||
public async Task<IReadOnlyList<ItemBalance>> 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<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().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;
|
||||
}
|
||||
|
||||
/// <summary>The movements of an item in a period, with the running balance (mockup 036, dialog of the item).</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="warehouseId">One warehouse, or all.</param>
|
||||
/// <param name="from">The first day, or the beginning.</param>
|
||||
/// <param name="to">The last day, or today.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movements, oldest first; the balance starts from what was on hand before <paramref name="from"/>.</returns>
|
||||
public async Task<IReadOnlyList<MovementRow>> 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<InventoryEntryLine>().Where(l => l.ItemId == itemId);
|
||||
if (warehouseId is { } warehouse)
|
||||
{
|
||||
query = query.Where(l => l.WarehouseId == warehouse);
|
||||
}
|
||||
|
||||
var lines = (await uow.Repository<InventoryEntryLine, long>().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<InventoryEntry, long>().ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(e => e.Id);
|
||||
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), 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<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
|
||||
var result = new List<MovementRow>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who reads: needs the permission on costs too.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <param name="warehouseId">One warehouse, or all.</param>
|
||||
/// <param name="method">The cost used.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The items with something on hand, by value.</returns>
|
||||
public async Task<IReadOnlyList<ValuationRow>> 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<InventoryEntryLine, long>().ListAsync(
|
||||
Query.For<InventoryEntryLine>().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<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
|
||||
var rows = new List<ValuationRow>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The items under their thresholds, the most urgent first (dashboard widget and reorder).</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="limit">How many.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public async Task<IReadOnlyList<StockRow>> 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)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who rebuilds: needs <c>inventory.entry.post</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="progress">How far it is.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
public async Task<(int Documents, int Items)> RebuildAsync(Actor actor, string companyCode, IProgress<RebuildProgress>? 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);
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the warehouse of a company, without checks (the scheduled job).</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="progress">How far it is.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
internal static async Task<(int Documents, int Items)> RebuildCompanyAsync(
|
||||
IUnitOfWorkFactory factory, string company, IProgress<RebuildProgress>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="available">On hand less committed.</param>
|
||||
/// <param name="ordered">Ordered from suppliers.</param>
|
||||
/// <param name="minimum">The minimum stock.</param>
|
||||
/// <param name="reorderPoint">The reorder point.</param>
|
||||
/// <returns>The level.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest.</summary>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <returns>The rows by value, with their class.</returns>
|
||||
public static IReadOnlyList<ValuationRow> Classify(IEnumerable<ValuationRow> 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<ValuationRow>(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<ItemBalance> 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<Dictionary<long, List<ItemBalance>>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = Query.For<ItemBalance>();
|
||||
if (warehouseId is { } warehouse)
|
||||
{
|
||||
query = query.Where(b => b.WarehouseId == warehouse);
|
||||
}
|
||||
|
||||
return (await uow.Repository<ItemBalance, long>().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList());
|
||||
}
|
||||
|
||||
private async Task<bool> CostsAsync(Actor actor, CancellationToken cancellationToken) =>
|
||||
(await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>An item to reorder (mockup 039).</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="UnitOfMeasureId">Its unit.</param>
|
||||
/// <param name="Available">On hand less committed.</param>
|
||||
/// <param name="Ordered">Already ordered.</param>
|
||||
/// <param name="MinimumStock">The minimum stock.</param>
|
||||
/// <param name="ReorderPoint">The reorder point.</param>
|
||||
/// <param name="Quantity">The quantity proposed.</param>
|
||||
/// <param name="SupplierId">The usual supplier, if any.</param>
|
||||
/// <param name="SupplierName">Its name.</param>
|
||||
/// <param name="Price">Its price.</param>
|
||||
/// <param name="ExpectedDate">When it would arrive, from the lead time.</param>
|
||||
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);
|
||||
|
||||
/// <summary>A proposal the user accepts, perhaps with another quantity or supplier.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="SupplierId">The supplier.</param>
|
||||
/// <param name="Quantity">The quantity.</param>
|
||||
public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class ReorderService
|
||||
{
|
||||
/// <summary>Error: a chosen line without a supplier or a quantity.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The editor (prices and terms of the supplier).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The items to reorder, by supplier and code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The proposals.</returns>
|
||||
public async Task<IReadOnlyList<ReorderProposal>> 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<Item, long>().ListAsync(
|
||||
Query.For<Item>().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<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().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<Party, long>().ListAsync(Query.For<Party>().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<ReorderProposal>();
|
||||
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)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="cover">Available plus ordered.</param>
|
||||
/// <param name="minimum">The minimum stock.</param>
|
||||
/// <param name="reorderPoint">The reorder point.</param>
|
||||
/// <param name="lot">The reorder lot.</param>
|
||||
/// <param name="supplierMinimum">The minimum of the supplier.</param>
|
||||
/// <returns>The quantity.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Creates the draft supplier orders of the chosen proposals, one per supplier.</summary>
|
||||
/// <param name="actor">Who orders: needs <c>purchases.order.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="choices">The proposals accepted.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The orders, saved as drafts.</returns>
|
||||
public async Task<IReadOnlyList<DocumentRecord>> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList<ReorderChoice> 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<DocumentRecord>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A line of a stock take with its item.</summary>
|
||||
/// <param name="Line">The line.</param>
|
||||
/// <param name="Code">The code of the item.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="UnitOfMeasureId">Its base unit.</param>
|
||||
public sealed record StockTakeLineView(StockTakeLine Line, string Code, string Description, long? UnitOfMeasureId);
|
||||
|
||||
/// <summary>A stock take with its lines.</summary>
|
||||
/// <param name="Take">The stock take.</param>
|
||||
/// <param name="Lines">Its lines, by code.</param>
|
||||
public sealed record StockTakeView(StockTake Take, IReadOnlyList<StockTakeLineView> Lines)
|
||||
{
|
||||
/// <summary>How many lines are counted.</summary>
|
||||
public int Counted => Lines.Count(l => l.Line.CountedQuantity is not null);
|
||||
|
||||
/// <summary>The value of the differences at the cost of the lines.</summary>
|
||||
public decimal DifferenceValue => Lines.Sum(l => StockCostCalculator.Value(l.Line.Difference, l.Line.UnitCost));
|
||||
}
|
||||
|
||||
/// <summary>What the import of the counts found.</summary>
|
||||
/// <param name="Applied">The lines counted.</param>
|
||||
/// <param name="Unknown">The codes not on the list, with their row.</param>
|
||||
public sealed record StockCountImport(int Applied, IReadOnlyList<string> Unknown);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>inventory.entry.read</c>, <c>write</c> (lists and counts) and <c>post</c>.</remarks>
|
||||
public sealed class StockTakeService
|
||||
{
|
||||
/// <summary>Error: the stock take is no longer open.</summary>
|
||||
public const string NotOpen = "inventory.stock-take.not-open";
|
||||
|
||||
/// <summary>Error: nothing is counted.</summary>
|
||||
public const string NothingCounted = "inventory.stock-take.nothing-counted";
|
||||
|
||||
/// <summary>Error: a counted quantity below zero.</summary>
|
||||
public const string NegativeCount = "inventory.stock-take.negative";
|
||||
|
||||
/// <summary>Error: the reasons of the adjustments are missing from the base tables.</summary>
|
||||
public const string ReasonMissing = "inventory.stock-take.reason-missing";
|
||||
|
||||
/// <summary>The reason of the gains.</summary>
|
||||
public const string GainReason = "INVP";
|
||||
|
||||
/// <summary>The reason of the losses.</summary>
|
||||
public const string LossReason = "INVN";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly DocumentEngine _engine;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="engine">The document engine, for the adjustments.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The stock takes, the latest first.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock takes.</returns>
|
||||
public async Task<IReadOnlyList<StockTake>> 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<StockTake, long>().ListAsync(Query.For<StockTake>().OrderByDescending(t => t.TakeDate).OrderByDescending(t => t.Id), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>A stock take with its lines.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take, or none.</returns>
|
||||
public async Task<StockTakeView?> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who opens it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="warehouseId">The warehouse.</param>
|
||||
/// <param name="date">The day of the count.</param>
|
||||
/// <param name="categoryId">Only a category.</param>
|
||||
/// <param name="description">A description; the warehouse and date when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new stock take.</returns>
|
||||
public async Task<StockTakeView> 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<Warehouse, long>().GetAsync(warehouseId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException([nameof(StockTake.WarehouseId) + ":" + "inventory.warehouse.missing"]);
|
||||
var query = Query.For<Item>().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<Item, long>().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<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().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<StockTake, long>().InsertAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
var lines = uow.Repository<StockTakeLine, long>();
|
||||
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))!;
|
||||
}
|
||||
|
||||
/// <summary>Writes the counts typed on the list; an empty count means not counted yet.</summary>
|
||||
/// <param name="actor">Who counts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="counts">The counted quantity of each line, by line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take.</returns>
|
||||
public async Task<StockTakeView> SaveCountsAsync(
|
||||
Actor actor, string companyCode, long id, IReadOnlyDictionary<long, decimal?> 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<StockTakeLine, long>();
|
||||
foreach (var line in (await repository.ListAsync(Query.For<StockTakeLine>().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))!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who counts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="content">The file.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many lines were counted and the codes not on the list.</returns>
|
||||
public async Task<StockCountImport> 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<long, decimal?>();
|
||||
var unknown = new List<string>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who posts: needs <c>inventory.entry.post</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take as posted.</returns>
|
||||
public async Task<StockTakeView> 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<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), 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<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cancels an open stock take; its counts stay for the record.</summary>
|
||||
/// <param name="actor">Who cancels.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A code and a quantity from a row of a count file, or none for a header or an empty row.</summary>
|
||||
/// <param name="text">The row.</param>
|
||||
/// <returns>The code and the quantity.</returns>
|
||||
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<Dictionary<long, decimal>> BookAsync(IUnitOfWork uow, long warehouseId, DateOnly date, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<InventoryEntryLine, long>().ListAsync(
|
||||
Query.For<InventoryEntryLine>().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<long?> AdjustAsync(
|
||||
Actor actor, string company, StockTake take, long reasonId, List<StockTakeLineView> 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<StockTake> OpenTakeAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
var take = await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
|
||||
return take.Status == StockTakeStatus.Open ? take : throw new ValidationFailedException([":" + NotOpen]);
|
||||
}
|
||||
|
||||
private static async Task<StockTakeView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } take)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var lines = (await uow.Repository<StockTakeLine, long>().ListAsync(Query.For<StockTakeLine>().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<Item, long>().ListAsync(Query.For<Item>().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))]);
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
|
||||
/// </summary>
|
||||
public sealed class JobScheduler
|
||||
{
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4, warehouse rebuild from M6).</summary>
|
||||
public static readonly IReadOnlyList<SystemTaskDefinition> 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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>An invoice found in a received file, as the import screen shows it before registering (mockup 034).</summary>
|
||||
/// <param name="FileName">The file (inside a ZIP, its entry).</param>
|
||||
/// <param name="File">The file as read.</param>
|
||||
/// <param name="Invoice">The invoice (a file may hold several).</param>
|
||||
/// <param name="DocumentTypeCode">The purchase document type that registers it, or none.</param>
|
||||
/// <param name="SupplierId">The supplier already in the archive, by VAT number or tax code.</param>
|
||||
/// <param name="Duplicate">Whether the supplier already has a document with this number in this year.</param>
|
||||
/// <param name="ComputedTotal">Taxable plus tax of the summary, plus rounding: what the total should be.</param>
|
||||
/// <param name="Problems">What stops or warns (resource codes).</param>
|
||||
public sealed record IncomingCandidate(
|
||||
string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal,
|
||||
IReadOnlyList<string> Problems)
|
||||
{
|
||||
/// <summary>Whether it can be registered.</summary>
|
||||
public bool CanImport => DocumentTypeCode is not null && !Duplicate;
|
||||
|
||||
/// <summary>The total in the file, or the computed one.</summary>
|
||||
public decimal Total => Invoice.Total ?? ComputedTotal;
|
||||
}
|
||||
|
||||
/// <summary>A file that could not be read.</summary>
|
||||
/// <param name="FileName">The file.</param>
|
||||
/// <param name="Error">Why (resource code).</param>
|
||||
public sealed record IncomingRejected(string FileName, string Error);
|
||||
|
||||
/// <summary>What the files hold.</summary>
|
||||
/// <param name="Invoices">The invoices found.</param>
|
||||
/// <param name="Rejected">The files not read.</param>
|
||||
public sealed record IncomingReading(IReadOnlyList<IncomingCandidate> Invoices, IReadOnlyList<IncomingRejected> Rejected);
|
||||
|
||||
/// <summary>An invoice registered, or why not.</summary>
|
||||
/// <param name="Candidate">The invoice.</param>
|
||||
/// <param name="Record">The draft document.</param>
|
||||
/// <param name="SupplierCreated">Whether the supplier was added to the archive.</param>
|
||||
/// <param name="Error">Why it was not registered (resource code).</param>
|
||||
/// <param name="Warnings">What to check on the draft (resource codes).</param>
|
||||
public sealed record IncomingImported(IncomingCandidate Candidate, DocumentRecord? Record, bool SupplierCreated, string? Error, IReadOnlyList<string> Warnings);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class PurchaseInvoiceImportService
|
||||
{
|
||||
/// <summary>The largest file accepted, ZIP included.</summary>
|
||||
public const int MaxFileSize = 50 * 1024 * 1024;
|
||||
|
||||
/// <summary>Problem: the type of the invoice is not a purchase (a self-invoice).</summary>
|
||||
public const string UnsupportedType = "purchase.import.unsupported-type";
|
||||
|
||||
/// <summary>Problem: already registered.</summary>
|
||||
public const string DuplicateProblem = "purchase.import.duplicate";
|
||||
|
||||
/// <summary>Warning: the total in the file differs from the lines.</summary>
|
||||
public const string TotalMismatch = "purchase.import.total-mismatch";
|
||||
|
||||
/// <summary>Warning: the signature of the file could not be verified.</summary>
|
||||
public const string SignatureNotVerified = "purchase.import.signature";
|
||||
|
||||
/// <summary>Warning: the discounts of the whole document are not carried to the lines.</summary>
|
||||
public const string DocumentDiscount = "purchase.import.document-discount";
|
||||
|
||||
/// <summary>Error: no tax code of the company has the rate and nature of a line.</summary>
|
||||
public const string TaxCodeMissing = "purchase.import.tax-code";
|
||||
|
||||
/// <summary>Error: the archive is empty of invoices.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The editor (terms of the supplier).</param>
|
||||
/// <param name="parties">The parties (new suppliers).</param>
|
||||
/// <param name="attachments">The attachments (the file).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Reads files: each XML or P7M, and those inside a ZIP.</summary>
|
||||
/// <param name="actor">Who imports: needs <c>purchases.invoice.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="files">The files, by name.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The invoices found and the files not read.</returns>
|
||||
public async Task<IncomingReading> 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<IIncomingInvoiceReader>();
|
||||
var rules = pack.GetFeature<IIncomingInvoiceRules>();
|
||||
var found = new List<(string Name, IncomingInvoiceFile File)>();
|
||||
var rejected = new List<IncomingRejected>();
|
||||
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<IncomingCandidate>();
|
||||
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<string>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="candidates">The invoices to register.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened to each.</returns>
|
||||
public async Task<IReadOnlyList<IncomingImported>> ImportAsync(
|
||||
Actor actor, string companyCode, IReadOnlyList<IncomingCandidate> 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<string, long>(StringComparer.OrdinalIgnoreCase);
|
||||
var result = new List<IncomingImported>();
|
||||
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<IncomingRejected> 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<long?> FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken)
|
||||
{
|
||||
var parties = uow.Repository<Party, long>();
|
||||
if (VatOf(party) is { } vat)
|
||||
{
|
||||
var bare = party.VatNumber!;
|
||||
var byVat = (await parties.ListAsync(Query.For<Party>().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<Party>().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<Party> 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<bool> 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<PurchaseDocument, long>().CountAsync(
|
||||
Query.For<PurchaseDocument>().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<long> 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<Country, long>().FindAsync(Query.For<Country>().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<string> 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<TaxCode, long>().ListAsync(Query.For<TaxCode>().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<ItemSupplier, long>().ListAsync(
|
||||
Query.For<ItemSupplier>().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<ItemBarcode, long>().ListAsync(
|
||||
Query.For<ItemBarcode>().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<Item, long>().ListAsync(
|
||||
Query.For<Item>().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<Item, long>().ListAsync(Query.For<Item>().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<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> 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<TaxCode> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A line of a supplier invoice whose price differs from the order or receipt it comes from (§11.5).</summary>
|
||||
/// <param name="LineNumber">The line of the invoice.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="SourceKind">The kind of the document it comes from.</param>
|
||||
/// <param name="SourceNumber">Its number.</param>
|
||||
/// <param name="SourcePrice">The net unit price there.</param>
|
||||
/// <param name="InvoicePrice">The net unit price on the invoice.</param>
|
||||
/// <param name="Quantity">The quantity of the invoice line.</param>
|
||||
public sealed record PriceDifference(
|
||||
int LineNumber, string Description, DocumentKind SourceKind, string? SourceNumber, decimal SourcePrice, decimal InvoicePrice, decimal Quantity)
|
||||
{
|
||||
/// <summary>The difference on the whole line: positive when the invoice costs more.</summary>
|
||||
public decimal Amount => Math.Round((InvoicePrice - SourcePrice) * Quantity, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
/// <summary>A supplier invoice that waits for its self-invoice (mockup 035).</summary>
|
||||
/// <param name="Invoice">The invoice.</param>
|
||||
/// <param name="Advice">The self-invoice it needs and by when.</param>
|
||||
public sealed record PendingSelfInvoice(DocumentRow Invoice, SelfInvoiceAdvice Advice);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>purchases.invoice.read</c> and <c>write</c>.</remarks>
|
||||
public sealed class PurchaseService
|
||||
{
|
||||
/// <summary>Permission to read supplier invoices.</summary>
|
||||
public const string ReadPermission = "purchases.invoice.read";
|
||||
|
||||
/// <summary>Permission to register supplier invoices and self-invoices.</summary>
|
||||
public const string WritePermission = "purchases.invoice.write";
|
||||
|
||||
/// <summary>The supplier invoice does not need a self-invoice.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="copies">Copies and transformations.</param>
|
||||
/// <param name="editor">The editor (radars).</param>
|
||||
/// <param name="packs">The fiscal pack of each company.</param>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The lines of a supplier invoice whose net price differs from their order or receipt.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The invoice, as on screen.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The differences.</returns>
|
||||
public async Task<IReadOnlyList<PriceDifference>> 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<PriceDifference>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The self-invoice a supplier invoice needs, if any (reverse charge, purchase from abroad).</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The invoice.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The advice, or <see langword="null"/>.</returns>
|
||||
public async Task<SelfInvoiceAdvice?> 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<ISelfInvoiceRules>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The confirmed supplier invoices that need a self-invoice and have none yet, the nearest deadline first.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The invoices with their advice.</returns>
|
||||
public async Task<IReadOnlyList<PendingSelfInvoice>> 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<ISelfInvoiceRules>();
|
||||
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<PendingSelfInvoice>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var integrated = (await uow.Repository<DocumentLink, long>().ListAsync(
|
||||
Query.For<DocumentLink>().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)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who creates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="purchaseInvoiceId">The supplier invoice.</param>
|
||||
/// <param name="typeCode">The type, such as <c>AF17</c>; the advised one when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The draft, saved.</returns>
|
||||
/// <exception cref="ValidationFailedException">No type was given and none is advised.</exception>
|
||||
public async Task<DocumentRecord> 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<ISelfInvoiceRules>();
|
||||
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<TaxCode, long>().ListAsync(Query.For<TaxCode>().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<SelfInvoiceAdvice?> AdviseAsync(IUnitOfWork uow, ISelfInvoiceRules rules, DocumentRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
if (record.Header.PartyId is not { } partyId || await uow.Repository<Party, long>().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<Country, long>().FindAsync(Query.For<Country>().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<TaxCode, long>().ListAsync(Query.For<TaxCode>().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<Item, long>().ListAsync(Query.For<Item>().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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The document editor (supplier terms, item costs).</param>
|
||||
/// <param name="copies">The transformations between documents.</param>
|
||||
/// <param name="stockTakes">The stock takes.</param>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 30;
|
||||
|
||||
/// <inheritdoc />
|
||||
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<DemoData?> ReadAsync(string companyCode, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
if (await uow.Repository<PurchaseOrder, long>().CountAsync(Query.For<PurchaseOrder>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<PurchaseDocument, long>().CountAsync(Query.For<PurchaseDocument>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<InventoryDocument, long>().CountAsync(Query.For<InventoryDocument>(), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().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<Item, long>().ListAsync(Query.For<Item>().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<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => goodIds.Contains(s.ItemId)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.GroupBy(s => s.PartyId).ToDictionary(g => g.Key, g => (IReadOnlyList<long>)[.. g.Select(s => s.ItemId).Distinct()]);
|
||||
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(r => r.Code, r => r.Id, StringComparer.Ordinal);
|
||||
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var warehouse = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().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<string, long> Parties, IReadOnlyList<Item> Goods, IReadOnlyDictionary<long, IReadOnlyList<long>> 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<Item> 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<long, decimal?>();
|
||||
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<DocumentRecord> 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<DocumentRecord> ReceiveAsync(DocumentRecord order, DateOnly date, string reference, IReadOnlyCollection<long>? 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<DocumentRecord> CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection<long>? 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<DocumentRecord> SaveAsync(DocumentRecord record)
|
||||
{
|
||||
record.Header.IsDemo = true;
|
||||
return owner.Engine.SaveAsync(Seed, company, record, cancellationToken);
|
||||
}
|
||||
|
||||
private Task<DocumentRecord> ConfirmAsync(DocumentRecord record) =>
|
||||
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,9 @@ public abstract class DocumentHeader : Entity<long>, IDemoMarkable
|
||||
/// <summary>The warehouse.</summary>
|
||||
public long? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The destination warehouse of a transfer.</summary>
|
||||
public long? ToWarehouseId { get; set; }
|
||||
|
||||
/// <summary>The warehouse reason.</summary>
|
||||
public long? InventoryReasonId { get; set; }
|
||||
|
||||
@@ -220,9 +223,15 @@ public abstract class DocumentHeader : Entity<long>, IDemoMarkable
|
||||
/// <summary>The ledger entry, once posted (M7).</summary>
|
||||
public long? GlEntryId { get; set; }
|
||||
|
||||
/// <summary>The VAT protocol of a supplier invoice.</summary>
|
||||
/// <summary>The VAT protocol of a supplier invoice: its progressive number in the purchase register of the year.</summary>
|
||||
public long? VatProtocol { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public DateOnly? VatDate { get; set; }
|
||||
|
||||
/// <summary>When the document was confirmed or issued.</summary>
|
||||
public DateTime? ConfirmedAt { get; set; }
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// A posting to the stock (SPEC §11.6, ADR 0035, <c>inventory_entries</c>): the movements one confirmed document wrote.
|
||||
/// Cancelling the document removes its entry; the balances are then computed again from the movements left.
|
||||
/// </summary>
|
||||
public sealed class InventoryEntry : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The date of the movements: the date of the document.</summary>
|
||||
public DateOnly EntryDate { get; set; }
|
||||
|
||||
/// <summary>The family of the document that posted it.</summary>
|
||||
public DocumentFamily? SourceFamily { get; set; }
|
||||
|
||||
/// <summary>The document that posted it.</summary>
|
||||
public long? SourceDocumentId { get; set; }
|
||||
|
||||
/// <summary>The kind of that document.</summary>
|
||||
public DocumentKind? SourceKind { get; set; }
|
||||
|
||||
/// <summary>The number of that document, as printed.</summary>
|
||||
public string? SourceNumber { get; set; }
|
||||
|
||||
/// <summary>The warehouse reason.</summary>
|
||||
public long? InventoryReasonId { get; set; }
|
||||
|
||||
/// <summary>The customer or supplier of the document.</summary>
|
||||
public long? PartyId { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A movement of one item in one warehouse (<c>inventory_entry_lines</c>), in the base unit of the item: positive
|
||||
/// loads, negative unloads. A transfer writes two lines.
|
||||
/// </summary>
|
||||
public sealed class InventoryEntryLine : Entity<long>
|
||||
{
|
||||
/// <summary>The entry.</summary>
|
||||
public long EntryId { get; set; }
|
||||
|
||||
/// <summary>The date, as the entry (kept here to read the history of an item without joins).</summary>
|
||||
public DateOnly EntryDate { get; set; }
|
||||
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The warehouse.</summary>
|
||||
public long WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The quantity in the base unit: positive for loads, negative for unloads.</summary>
|
||||
public decimal Quantity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public bool Valued { get; set; }
|
||||
|
||||
/// <summary>The unit cost in euro.</summary>
|
||||
public decimal UnitCost { get; set; }
|
||||
|
||||
/// <summary>The value of the movement in euro, with the sign of the quantity.</summary>
|
||||
public decimal Value { get; set; }
|
||||
|
||||
/// <summary>The document line that wrote it.</summary>
|
||||
public long? SourceLineId { get; set; }
|
||||
|
||||
/// <summary>The order of the lines in the entry.</summary>
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What an item has in a warehouse (<c>item_balances</c>), kept in step with the movements and the open orders:
|
||||
/// on hand, committed to customers, ordered from suppliers, average cost and value.
|
||||
/// </summary>
|
||||
public sealed class ItemBalance : Entity<long>
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The warehouse.</summary>
|
||||
public long WarehouseId { get; set; }
|
||||
|
||||
/// <summary>The quantity on hand.</summary>
|
||||
public decimal OnHand { get; set; }
|
||||
|
||||
/// <summary>The quantity in the confirmed customer orders still to deliver.</summary>
|
||||
public decimal Committed { get; set; }
|
||||
|
||||
/// <summary>The quantity in the confirmed supplier orders still to receive.</summary>
|
||||
public decimal Ordered { get; set; }
|
||||
|
||||
/// <summary>The quantity sent towards this warehouse and not yet arrived (transfers are immediate: kept for later).</summary>
|
||||
public decimal InTransit { get; set; }
|
||||
|
||||
/// <summary>The weighted average cost of the item.</summary>
|
||||
public decimal AverageCost { get; set; }
|
||||
|
||||
/// <summary>The value of the quantity on hand at the average cost.</summary>
|
||||
public decimal Value { get; set; }
|
||||
|
||||
/// <summary>The last purchase cost.</summary>
|
||||
public decimal? LastCost { get; set; }
|
||||
|
||||
/// <summary>The date of the last load.</summary>
|
||||
public DateOnly? LastLoadDate { get; set; }
|
||||
|
||||
/// <summary>The date of the last unload.</summary>
|
||||
public DateOnly? LastUnloadDate { get; set; }
|
||||
|
||||
/// <summary>What can be promised: on hand less committed.</summary>
|
||||
public decimal Available => OnHand - Committed;
|
||||
}
|
||||
|
||||
/// <summary>The state of a physical inventory.</summary>
|
||||
public enum StockTakeStatus
|
||||
{
|
||||
/// <summary>Counting: the quantities can be entered.</summary>
|
||||
Open = 0,
|
||||
|
||||
/// <summary>Posted: the differences became adjustments.</summary>
|
||||
Posted = 1,
|
||||
|
||||
/// <summary>Abandoned.</summary>
|
||||
Cancelled = 2,
|
||||
}
|
||||
|
||||
/// <summary>A physical inventory of a warehouse (SPEC §11.6, mockup 038, <c>stock_takes</c>).</summary>
|
||||
public sealed class StockTake : Entity<long>, IDemoMarkable
|
||||
{
|
||||
/// <summary>The date the count refers to: the book quantities are those of the evening of that day.</summary>
|
||||
public DateOnly TakeDate { get; set; }
|
||||
|
||||
/// <summary>The warehouse counted.</summary>
|
||||
public long WarehouseId { get; set; }
|
||||
|
||||
/// <summary>A description, such as <c>Inventario di fine anno</c>.</summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The item category counted; every stocked item when empty.</summary>
|
||||
public long? CategoryId { get; set; }
|
||||
|
||||
/// <summary>The state.</summary>
|
||||
public StockTakeStatus Status { get; set; }
|
||||
|
||||
/// <summary>The warehouse entry that loads what was found more than the books, once posted.</summary>
|
||||
public long? AdjustmentDocumentId { get; set; }
|
||||
|
||||
/// <summary>The warehouse entry that unloads what was found less than the books, once posted.</summary>
|
||||
public long? LossDocumentId { get; set; }
|
||||
|
||||
/// <summary>When it was posted.</summary>
|
||||
public DateTime? PostedAt { get; set; }
|
||||
|
||||
/// <summary>Who posted it.</summary>
|
||||
public string? PostedBy { get; set; }
|
||||
|
||||
/// <summary>Notes.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsDemo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A line of a physical inventory (<c>stock_take_lines</c>).</summary>
|
||||
public sealed class StockTakeLine : Entity<long>
|
||||
{
|
||||
/// <summary>The inventory.</summary>
|
||||
public long StockTakeId { get; set; }
|
||||
|
||||
/// <summary>The item.</summary>
|
||||
public long ItemId { get; set; }
|
||||
|
||||
/// <summary>The quantity the books say at the date of the count.</summary>
|
||||
public decimal BookQuantity { get; set; }
|
||||
|
||||
/// <summary>The quantity counted; empty until counted.</summary>
|
||||
public decimal? CountedQuantity { get; set; }
|
||||
|
||||
/// <summary>The unit cost used for the adjustment: the average cost at the date.</summary>
|
||||
public decimal UnitCost { get; set; }
|
||||
|
||||
/// <summary>Notes of the counter.</summary>
|
||||
public string? Notes { get; set; }
|
||||
|
||||
/// <summary>The order on the list (by item code).</summary>
|
||||
public int SortOrder { get; set; }
|
||||
|
||||
/// <summary>The difference to adjust: counted less book, zero while not counted.</summary>
|
||||
public decimal Difference => CountedQuantity is { } counted ? counted - BookQuantity : 0m;
|
||||
}
|
||||
|
||||
/// <summary>How the stock is valued at a date (SPEC §11.6).</summary>
|
||||
public enum StockValuationMethod
|
||||
{
|
||||
/// <summary>Weighted average cost, moved by every purchase (the one the balances keep).</summary>
|
||||
WeightedAverage = 0,
|
||||
|
||||
/// <summary>The last purchase cost.</summary>
|
||||
LastCost = 1,
|
||||
|
||||
/// <summary>The standard cost of the item.</summary>
|
||||
StandardCost = 2,
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
namespace Khaemhat.Core.Inventory;
|
||||
|
||||
/// <summary>A movement of one item, in the order of the history.</summary>
|
||||
/// <param name="Id">The movement.</param>
|
||||
/// <param name="Date">The date.</param>
|
||||
/// <param name="WarehouseId">The warehouse.</param>
|
||||
/// <param name="Quantity">Positive loads, negative unloads, in the base unit.</param>
|
||||
/// <param name="Valued">The cost comes from the document.</param>
|
||||
/// <param name="UnitCost">The cost of a valued movement.</param>
|
||||
public sealed record CostedMovement(long Id, DateOnly Date, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
|
||||
|
||||
/// <summary>What one warehouse holds after the history.</summary>
|
||||
/// <param name="OnHand">The quantity on hand.</param>
|
||||
/// <param name="LastLoad">The date of the last load.</param>
|
||||
/// <param name="LastUnload">The date of the last unload.</param>
|
||||
public sealed record WarehouseStock(decimal OnHand, DateOnly? LastLoad, DateOnly? LastUnload);
|
||||
|
||||
/// <summary>The history of an item run through the weighted average.</summary>
|
||||
/// <param name="UnitCosts">The unit cost of each movement: its own when valued, the average of its moment otherwise.</param>
|
||||
/// <param name="Warehouses">What each warehouse holds.</param>
|
||||
/// <param name="AverageCost">The average cost at the end.</param>
|
||||
/// <param name="LastCost">The cost of the last valued load.</param>
|
||||
/// <param name="OnHand">The quantity on hand in every warehouse together.</param>
|
||||
public sealed record CostedHistory(
|
||||
IReadOnlyDictionary<long, decimal> UnitCosts, IReadOnlyDictionary<long, WarehouseStock> Warehouses, decimal AverageCost, decimal? LastCost, decimal OnHand);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class StockCostCalculator
|
||||
{
|
||||
/// <summary>The decimals of unit costs.</summary>
|
||||
public const int CostDecimals = 4;
|
||||
|
||||
/// <summary>Runs the history of an item.</summary>
|
||||
/// <param name="movements">The movements, in date and posting order.</param>
|
||||
/// <param name="initialCost">The cost used before the first valued load (the standard cost of the item, or zero).</param>
|
||||
/// <returns>The costs and the stock.</returns>
|
||||
public static CostedHistory Run(IEnumerable<CostedMovement> movements, decimal initialCost = 0m)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(movements);
|
||||
var costs = new Dictionary<long, decimal>();
|
||||
var warehouses = new Dictionary<long, WarehouseStock>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The value of a quantity at a unit cost, in euro to the cent.</summary>
|
||||
/// <param name="quantity">The quantity.</param>
|
||||
/// <param name="unitCost">The unit cost.</param>
|
||||
/// <returns>The value.</returns>
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Core.Inventory;
|
||||
|
||||
/// <summary>A document line as the stock sees it: an item, a quantity in its base unit, a warehouse, a cost.</summary>
|
||||
/// <param name="LineId">The document line.</param>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Quantity">The quantity in the base unit of the item (positive).</param>
|
||||
/// <param name="WarehouseId">The warehouse of the line.</param>
|
||||
/// <param name="UnitCost">The cost per base unit in euro written on the document, if any.</param>
|
||||
public sealed record StockLineInput(long LineId, long ItemId, decimal Quantity, long WarehouseId, decimal? UnitCost);
|
||||
|
||||
/// <summary>A movement to write: one item, one warehouse, a signed quantity.</summary>
|
||||
/// <param name="SourceLineId">The document line.</param>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="WarehouseId">The warehouse.</param>
|
||||
/// <param name="Quantity">Positive loads, negative unloads.</param>
|
||||
/// <param name="Valued">The cost comes from the document and moves the average.</param>
|
||||
/// <param name="UnitCost">The cost of a valued movement; zero for the others (valued at the average).</param>
|
||||
public sealed record StockMovement(long? SourceLineId, long ItemId, long WarehouseId, decimal Quantity, bool Valued, decimal UnitCost);
|
||||
|
||||
/// <summary>What the warehouse reason of a document does.</summary>
|
||||
/// <param name="Effect">Load, unload or nothing on the quantity.</param>
|
||||
/// <param name="AffectsValue">Purchases and sales move the value; transfers and goods on approval only quantities.</param>
|
||||
/// <param name="IsTransfer">A transfer between two warehouses.</param>
|
||||
public sealed record StockReason(StockEffect Effect, bool AffectsValue, bool IsTransfer)
|
||||
{
|
||||
/// <summary>The reason of a row of <c>inventory_reasons</c>.</summary>
|
||||
/// <param name="reason">The row.</param>
|
||||
/// <returns>The reason.</returns>
|
||||
public static StockReason Of(InventoryReason reason)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(reason);
|
||||
return new StockReason(reason.Effect, reason.AffectsValue, reason.IsTransfer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class StockEffectMatrix
|
||||
{
|
||||
private static readonly HashSet<DocumentKind> 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<DocumentKind> Costing =
|
||||
[DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice, DocumentKind.InventoryEntry];
|
||||
|
||||
/// <summary>Whether documents of a kind move the stock when their reason says so.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Whether they do.</returns>
|
||||
public static bool MovesStock(DocumentKind kind) => Moving.Contains(kind);
|
||||
|
||||
/// <summary>Whether the open lines of a kind are committed to customers.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Whether they are.</returns>
|
||||
public static bool Commits(DocumentKind kind) => kind == DocumentKind.SalesOrder;
|
||||
|
||||
/// <summary>Whether the open lines of a kind are ordered from suppliers.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Whether they are.</returns>
|
||||
public static bool Orders(DocumentKind kind) => kind == DocumentKind.PurchaseOrder;
|
||||
|
||||
/// <summary>Whether a document in a state still holds quantities committed or ordered.</summary>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns>Whether it is open.</returns>
|
||||
public static bool IsOpenOrder(DocumentStatus status) => status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled;
|
||||
|
||||
/// <summary>The movements of a document.</summary>
|
||||
/// <param name="kind">The kind of the document.</param>
|
||||
/// <param name="reason">Its warehouse reason.</param>
|
||||
/// <param name="toWarehouseId">The destination of a transfer.</param>
|
||||
/// <param name="lines">The stocked lines.</param>
|
||||
/// <returns>The movements; none when the kind or the reason does not move the stock.</returns>
|
||||
/// <exception cref="InvalidOperationException">A transfer without a destination different from the origin.</exception>
|
||||
public static IReadOnlyList<StockMovement> Movements(DocumentKind kind, StockReason? reason, long? toWarehouseId, IEnumerable<StockLineInput> lines)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
if (reason is null || !MovesStock(kind))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new List<StockMovement>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="InventoryEntry"/> to <c>inventory_entries</c>.</summary>
|
||||
public sealed class InventoryEntryMap : EntityMap<InventoryEntry>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public InventoryEntryMap()
|
||||
{
|
||||
ToTable("inventory_entries");
|
||||
Map(x => x.SourceNumber).MaxLength(30);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="InventoryEntryLine"/> to <c>inventory_entry_lines</c>.</summary>
|
||||
public sealed class InventoryEntryLineMap : EntityMap<InventoryEntryLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public InventoryEntryLineMap() => ToTable("inventory_entry_lines");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="ItemBalance"/> to <c>item_balances</c>.</summary>
|
||||
public sealed class ItemBalanceMap : EntityMap<ItemBalance>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public ItemBalanceMap() => ToTable("item_balances");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="StockTake"/> to <c>stock_takes</c>.</summary>
|
||||
public sealed class StockTakeMap : EntityMap<StockTake>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public StockTakeMap()
|
||||
{
|
||||
ToTable("stock_takes");
|
||||
Map(x => x.Description).MaxLength(100);
|
||||
Map(x => x.PostedBy).MaxLength(100);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="StockTakeLine"/> to <c>stock_take_lines</c>.</summary>
|
||||
public sealed class StockTakeLineMap : EntityMap<StockTakeLine>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public StockTakeLineMap()
|
||||
{
|
||||
ToTable("stock_take_lines");
|
||||
Map(x => x.Notes).MaxLength(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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")];
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -273,3 +273,41 @@ public interface IPlaceDirectory
|
||||
/// <summary>The municipalities.</summary>
|
||||
IReadOnlyList<MunicipalityTemplate> Municipalities { get; }
|
||||
}
|
||||
|
||||
/// <summary>What a received invoice tells about the self-invoice it may need.</summary>
|
||||
/// <param name="SupplierCountry">The country of the supplier (ISO 3166-1 alpha-2).</param>
|
||||
/// <param name="SupplierInEu">The supplier is in another member state of the European Union.</param>
|
||||
/// <param name="Goods">The invoice is mostly for goods (otherwise services).</param>
|
||||
/// <param name="Natures">The VAT natures of its lines (codes of the country's e-invoice format), if any.</param>
|
||||
/// <param name="Received">The day it was received or registered.</param>
|
||||
public sealed record SelfInvoiceCase(string SupplierCountry, bool SupplierInEu, bool Goods, IReadOnlyCollection<string> Natures, DateOnly Received);
|
||||
|
||||
/// <summary>The self-invoice a received invoice needs.</summary>
|
||||
/// <param name="DocumentTypeCode">The document type of the base tables, such as <c>AF17</c>.</param>
|
||||
/// <param name="Reason">Why, in the language of the users.</param>
|
||||
/// <param name="Deadline">The last day to issue it.</param>
|
||||
public sealed record SelfInvoiceAdvice(string DocumentTypeCode, string Reason, DateOnly Deadline);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface ISelfInvoiceRules
|
||||
{
|
||||
/// <summary>The document types of self-invoices, in the order of the menu.</summary>
|
||||
IReadOnlyList<string> DocumentTypeCodes { get; }
|
||||
|
||||
/// <summary>The VAT code (of the base tables) of the ordinary rate, proposed on the lines of an integration.</summary>
|
||||
string OrdinaryTaxCode { get; }
|
||||
|
||||
/// <summary>The self-invoice a received invoice needs, if any.</summary>
|
||||
/// <param name="input">The invoice.</param>
|
||||
/// <returns>The advice, or <see langword="null"/> when none is needed.</returns>
|
||||
SelfInvoiceAdvice? Advise(SelfInvoiceCase input);
|
||||
|
||||
/// <summary>The last day to issue a self-invoice of a type for an invoice received on a day.</summary>
|
||||
/// <param name="documentTypeCode">The type.</param>
|
||||
/// <param name="received">The day the invoice was received (or the operation took place).</param>
|
||||
/// <returns>The deadline.</returns>
|
||||
DateOnly Deadline(string documentTypeCode, DateOnly received);
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
/// <summary>
|
||||
/// Reads the e-invoice files received from suppliers: an optional feature of a country pack, like
|
||||
/// <see cref="IEInvoiceFormat"/>. The reader only reads: it never contacts a service and never resolves external
|
||||
/// references.
|
||||
/// </summary>
|
||||
public interface IIncomingInvoiceReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the file looks like one the reader understands (Italy: <c>.xml</c>, <c>.p7m</c> in DER or as base64
|
||||
/// text). The content is sniffed, not only the name.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the file, extension included.</param>
|
||||
/// <param name="content">The content, or at least its first bytes.</param>
|
||||
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
|
||||
bool CanRead(string fileName, ReadOnlySpan<byte> content);
|
||||
|
||||
/// <summary>Reads a file.</summary>
|
||||
/// <param name="fileName">The name of the file, extension included.</param>
|
||||
/// <param name="content">The whole content.</param>
|
||||
/// <returns>The file with its invoices.</returns>
|
||||
/// <exception cref="IncomingInvoiceException">The file is not readable, not an invoice, or misses mandatory data;
|
||||
/// <see cref="IncomingInvoiceException.Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</exception>
|
||||
IncomingInvoiceFile Read(string fileName, byte[] content);
|
||||
}
|
||||
|
||||
/// <summary>A received e-invoice file that cannot be read; <see cref="Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</summary>
|
||||
public sealed class IncomingInvoiceException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public IncomingInvoiceException()
|
||||
: this(IncomingInvoiceErrors.NotReadable, "The file is not readable.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public IncomingInvoiceException(string message)
|
||||
: this(IncomingInvoiceErrors.NotReadable, message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public IncomingInvoiceException(string message, Exception innerException)
|
||||
: this(IncomingInvoiceErrors.NotReadable, message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a code.</summary>
|
||||
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public IncomingInvoiceException(string code, string message)
|
||||
: base(message) => Code = code;
|
||||
|
||||
/// <summary>Creates the exception with a code and its cause.</summary>
|
||||
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public IncomingInvoiceException(string code, string message, Exception? innerException)
|
||||
: base(message, innerException) => Code = code;
|
||||
|
||||
/// <summary>The text code of the error, one of <see cref="IncomingInvoiceErrors"/>.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>The codes of <see cref="IncomingInvoiceException"/>.</summary>
|
||||
public static class IncomingInvoiceErrors
|
||||
{
|
||||
/// <summary>Neither XML nor a signed envelope: garbage, an empty file, a truncated download.</summary>
|
||||
public const string NotReadable = "incoming.not-readable";
|
||||
|
||||
/// <summary>A well-formed XML document that is not an e-invoice.</summary>
|
||||
public const string NotInvoice = "incoming.not-invoice";
|
||||
|
||||
/// <summary>A signed envelope whose content cannot be extracted.</summary>
|
||||
public const string SignatureBroken = "incoming.signature-broken";
|
||||
|
||||
/// <summary>An e-invoice that misses mandatory data (date, number, document type...).</summary>
|
||||
public const string Invalid = "incoming.invalid";
|
||||
}
|
||||
|
||||
/// <summary>A received e-invoice file: the transmission header, the two parties and one or more invoices.</summary>
|
||||
/// <param name="FileName">The name of the file as received.</param>
|
||||
/// <param name="TransmissionFormat">The transmission format (Italy: <c>FPR12</c>, <c>FPA12</c>, <c>FSM10</c>).</param>
|
||||
/// <param name="ProgressiveNumber">The progressive number of the transmission given by the sender.</param>
|
||||
/// <param name="RecipientCode">The recipient code of the transmission.</param>
|
||||
/// <param name="Supplier">The supplier who issued the invoices.</param>
|
||||
/// <param name="Customer">The customer the invoices are addressed to (normally the company).</param>
|
||||
/// <param name="Invoices">The invoices, one per body of the file (a batch has more than one).</param>
|
||||
/// <param name="Signature">The signature of the envelope, or <see langword="null"/> for an unsigned file.</param>
|
||||
/// <param name="Xml">The XML of the invoice, taken out of the envelope when the file was signed.</param>
|
||||
public sealed record IncomingInvoiceFile(
|
||||
string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
|
||||
IncomingParty Supplier, IncomingParty Customer, IReadOnlyList<IncomingInvoice> Invoices,
|
||||
IncomingSignature? Signature, byte[] Xml);
|
||||
|
||||
/// <summary>
|
||||
/// The signature of a signed file. <see cref="Verified"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="Verified">Whether the digest and the signature match the content.</param>
|
||||
/// <param name="Signer">The name of the signer, from the certificate.</param>
|
||||
/// <param name="SignerTaxCode">The tax code of the signer, when the certificate carries it.</param>
|
||||
/// <param name="SignedAt">The signing time declared by the signer, if any (not a trusted timestamp).</param>
|
||||
/// <param name="CertificateNotBefore">The start of validity of the certificate.</param>
|
||||
/// <param name="CertificateNotAfter">The end of validity of the certificate.</param>
|
||||
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
|
||||
public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
|
||||
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
|
||||
|
||||
/// <summary>A party of the invoice (supplier or customer) as written in the file.</summary>
|
||||
/// <param name="CountryCode">The country of the VAT number.</param>
|
||||
/// <param name="VatNumber">The VAT number without the country prefix.</param>
|
||||
/// <param name="TaxCode">The tax code.</param>
|
||||
/// <param name="Name">The company name, when the party is a company.</param>
|
||||
/// <param name="FirstName">The first name, when the party is a person.</param>
|
||||
/// <param name="LastName">The last name, when the party is a person.</param>
|
||||
/// <param name="Address">The street of the registered office.</param>
|
||||
/// <param name="StreetNumber">The street number.</param>
|
||||
/// <param name="PostalCode">The postal code.</param>
|
||||
/// <param name="City">The city.</param>
|
||||
/// <param name="Province">The province.</param>
|
||||
/// <param name="Country">The country of the registered office.</param>
|
||||
/// <param name="TaxRegime">The tax regime (supplier only).</param>
|
||||
/// <param name="Email">The e-mail address (supplier only).</param>
|
||||
/// <param name="Phone">The phone number (supplier only).</param>
|
||||
/// <param name="ReaOffice">The office of the companies register.</param>
|
||||
/// <param name="ReaNumber">The number in the companies register.</param>
|
||||
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)
|
||||
{
|
||||
/// <summary>The company name, or first and last name of a person.</summary>
|
||||
public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||
}
|
||||
|
||||
/// <summary>An invoice of the file (one body).</summary>
|
||||
/// <param name="DocumentType">The document type (Italy: <c>TD01</c>, <c>TD04</c>...).</param>
|
||||
/// <param name="Currency">The currency code.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="Number">The number of the document.</param>
|
||||
/// <param name="Total">The total amount declared by the supplier, if any.</param>
|
||||
/// <param name="Rounding">The rounding on the total, if any.</param>
|
||||
/// <param name="Causals">The free-text causals.</param>
|
||||
/// <param name="Art73">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).</param>
|
||||
/// <param name="Withholdings">The withholding taxes.</param>
|
||||
/// <param name="StampDuty">The stamp duty, if any.</param>
|
||||
/// <param name="SocialSecurity">The social security contributions.</param>
|
||||
/// <param name="Discounts">The discounts and surcharges on the whole document.</param>
|
||||
/// <param name="Orders">The purchase orders referred to.</param>
|
||||
/// <param name="Contracts">The contracts referred to.</param>
|
||||
/// <param name="RelatedInvoices">The invoices referred to (the invoice a credit note corrects).</param>
|
||||
/// <param name="DeliveryNotes">The delivery notes referred to.</param>
|
||||
/// <param name="Lines">The lines.</param>
|
||||
/// <param name="TaxSummary">The tax summary, one row per rate or nature.</param>
|
||||
/// <param name="Payments">The payment installments.</param>
|
||||
/// <param name="Attachments">The attached files.</param>
|
||||
public sealed record IncomingInvoice(
|
||||
string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
|
||||
IReadOnlyList<string> Causals, bool Art73,
|
||||
IReadOnlyList<IncomingWithholding> Withholdings, IncomingStampDuty? StampDuty,
|
||||
IReadOnlyList<IncomingSocialSecurity> SocialSecurity, IReadOnlyList<IncomingDiscount> Discounts,
|
||||
IReadOnlyList<IncomingReference> Orders, IReadOnlyList<IncomingReference> Contracts,
|
||||
IReadOnlyList<IncomingReference> RelatedInvoices, IReadOnlyList<IncomingReference> DeliveryNotes,
|
||||
IReadOnlyList<IncomingLine> Lines, IReadOnlyList<IncomingTaxSummary> TaxSummary,
|
||||
IReadOnlyList<IncomingPayment> Payments, IReadOnlyList<IncomingAttachment> Attachments);
|
||||
|
||||
/// <summary>A line of an invoice.</summary>
|
||||
/// <param name="Number">The line number.</param>
|
||||
/// <param name="Codes">The item codes (type and value).</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Quantity">The quantity, if given.</param>
|
||||
/// <param name="Unit">The unit of measure, if given.</param>
|
||||
/// <param name="UnitPrice">The unit price.</param>
|
||||
/// <param name="TotalPrice">The total of the line, net of tax.</param>
|
||||
/// <param name="TaxRate">The tax rate in percent (zero with a nature).</param>
|
||||
/// <param name="Nature">The reason of a zero rate (Italy: <c>N2.2</c>...).</param>
|
||||
/// <param name="Discounts">The discounts and surcharges of the line.</param>
|
||||
/// <param name="Withheld">Whether the line is subject to withholding tax.</param>
|
||||
/// <param name="LineType">The kind of line (Italy: <c>SC</c> discount, <c>PR</c> premium, <c>AB</c> rebate,
|
||||
/// <c>AC</c> ancillary cost).</param>
|
||||
/// <param name="PeriodStart">The start of the period the line refers to.</param>
|
||||
/// <param name="PeriodEnd">The end of the period the line refers to.</param>
|
||||
/// <param name="AdministrativeReference">The administrative reference (cost centre, internal code).</param>
|
||||
public sealed record IncomingLine(
|
||||
int Number, IReadOnlyList<IncomingItemCode> Codes, string Description, decimal? Quantity, string? Unit,
|
||||
decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList<IncomingDiscount> Discounts,
|
||||
bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference);
|
||||
|
||||
/// <summary>A code of the item of a line.</summary>
|
||||
/// <param name="Type">The kind of code (<c>EAN</c>, <c>SKU</c>, the supplier's code...).</param>
|
||||
/// <param name="Value">The code.</param>
|
||||
public sealed record IncomingItemCode(string Type, string Value);
|
||||
|
||||
/// <summary>A discount or surcharge.</summary>
|
||||
/// <param name="IsSurcharge">Whether it is a surcharge (Italy: <c>MG</c>) instead of a discount (<c>SC</c>).</param>
|
||||
/// <param name="Percent">The percentage, if given.</param>
|
||||
/// <param name="Amount">The amount, if given.</param>
|
||||
public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount);
|
||||
|
||||
/// <summary>A row of the tax summary.</summary>
|
||||
/// <param name="Rate">The tax rate in percent.</param>
|
||||
/// <param name="Nature">The reason of a zero rate.</param>
|
||||
/// <param name="Taxable">The taxable amount.</param>
|
||||
/// <param name="Tax">The tax.</param>
|
||||
/// <param name="Exigibility">When the tax is due (Italy: <c>I</c> immediate, <c>D</c> deferred, <c>S</c> split payment).</param>
|
||||
/// <param name="LegalReference">The law that justifies the nature.</param>
|
||||
/// <param name="ExpensesAmount">Ancillary expenses, if any.</param>
|
||||
/// <param name="Rounding">The rounding, if any.</param>
|
||||
public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility,
|
||||
string? LegalReference, decimal? ExpensesAmount, decimal? Rounding);
|
||||
|
||||
/// <summary>A payment installment.</summary>
|
||||
/// <param name="Conditions">The payment conditions (Italy: <c>TP01</c> installments, <c>TP02</c> full, <c>TP03</c> advance).</param>
|
||||
/// <param name="Method">The payment method (Italy: <c>MP05</c> bank transfer...).</param>
|
||||
/// <param name="DueDate">The due date, if given.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
/// <param name="Iban">The IBAN to pay to, if given.</param>
|
||||
/// <param name="Bic">The BIC, if given.</param>
|
||||
/// <param name="Beneficiary">The beneficiary, if different from the supplier.</param>
|
||||
public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount,
|
||||
string? Iban, string? Bic, string? Beneficiary);
|
||||
|
||||
/// <summary>A reference to another document (order, contract, invoice, delivery note).</summary>
|
||||
/// <param name="Id">The number of the document.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="LineNumbers">The lines of the invoice the reference applies to; empty when it applies to all.</param>
|
||||
/// <param name="Cig">The tender code, if any (public administration).</param>
|
||||
/// <param name="Cup">The project code, if any (public administration).</param>
|
||||
public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList<int> LineNumbers, string? Cig, string? Cup);
|
||||
|
||||
/// <summary>A withholding tax.</summary>
|
||||
/// <param name="Type">The kind of withholding (Italy: <c>RT01</c>...).</param>
|
||||
/// <param name="Amount">The amount withheld.</param>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="Reason">The payment reason (Italy: <c>A</c>...), if given.</param>
|
||||
public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason);
|
||||
|
||||
/// <summary>The stamp duty of an invoice.</summary>
|
||||
/// <param name="Virtual">Whether it is paid virtually by the issuer.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
public sealed record IncomingStampDuty(bool Virtual, decimal Amount);
|
||||
|
||||
/// <summary>A social security contribution added to the invoice.</summary>
|
||||
/// <param name="Fund">The fund (Italy: <c>TC01</c>...).</param>
|
||||
/// <param name="Rate">The rate of the contribution in percent.</param>
|
||||
/// <param name="Amount">The amount of the contribution.</param>
|
||||
/// <param name="Taxable">The amount the contribution is computed on, if given.</param>
|
||||
/// <param name="TaxRate">The tax rate applied to the contribution.</param>
|
||||
/// <param name="Withheld">Whether the contribution is subject to withholding tax.</param>
|
||||
/// <param name="Nature">The reason of a zero tax rate.</param>
|
||||
public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate,
|
||||
bool Withheld, string? Nature);
|
||||
|
||||
/// <summary>A file attached to the invoice.</summary>
|
||||
/// <param name="Name">The name of the attachment.</param>
|
||||
/// <param name="Format">The format declared by the supplier (such as <c>PDF</c>), if any.</param>
|
||||
/// <param name="Description">The description, if any.</param>
|
||||
/// <param name="Content">The decoded content.</param>
|
||||
public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public interface IIncomingInvoiceRules
|
||||
{
|
||||
/// <summary>The code of the document type that registers an invoice of this type of the format.</summary>
|
||||
/// <param name="formatType">The type in the file (TD01...).</param>
|
||||
/// <returns>The document type code, or none when the type is not registered as a purchase (a self-invoice).</returns>
|
||||
string? DocumentTypeCode(string formatType);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the FatturaPA files received from suppliers (SPEC §11.9, issue #57): ordinary invoices v1.2.x
|
||||
/// (<c>FPR12</c>, <c>FPA12</c>), simplified invoices (<c>FSM10</c>), plain <c>.xml</c> or signed CAdES <c>.p7m</c>
|
||||
/// (binary or base64 text, also nested).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>Elements are matched by local name, whatever the namespace or prefix (<c>p:</c>, <c>ns2:</c>, 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.</para>
|
||||
/// <para>Amounts use the invariant culture (<c>.</c> separator) and dates <c>yyyy-MM-dd</c>. 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 <c>Divisa</c> is read as
|
||||
/// <c>EUR</c>; an attachment whose content is not valid base64 is kept with an empty content.</para>
|
||||
/// <para>For signed files the signature is checked for integrity only (see <see cref="CmsSignedData"/>): no trust chain
|
||||
/// and no revocation check.</para>
|
||||
/// <para>Simplified invoices (<c>FSM10</c>): each <c>DatiBeniServizi</c> becomes a line with no quantity whose unit and
|
||||
/// total price are <c>Importo</c> minus the tax, because there <c>Importo</c> includes the tax. The tax is
|
||||
/// <c>DatiIVA/Imposta</c> or, when only the rate is given, the tax included in <c>Importo</c> at that rate; the rate is
|
||||
/// <c>DatiIVA/Aliquota</c> 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 <c>Importo</c> and <c>DatiFatturaRettificata</c> becomes the related invoice.</para>
|
||||
/// </remarks>
|
||||
public sealed class FatturaPaReader : IIncomingInvoiceReader
|
||||
{
|
||||
/// <summary>The largest file read, as for signed envelopes (50 MB).</summary>
|
||||
public const int MaxSize = CmsSignedData.MaxSize;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanRead(string fileName, ReadOnlySpan<byte> content) =>
|
||||
!content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content));
|
||||
|
||||
/// <inheritdoc />
|
||||
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<byte> content)
|
||||
{
|
||||
if (content.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
|
||||
{
|
||||
content = content[3..];
|
||||
}
|
||||
else if (content.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]) || content.StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var trimmed = content.TrimStart((ReadOnlySpan<byte>)[(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<byte>)[0xEF, 0xBB, 0xBF]))
|
||||
{
|
||||
return new UTF8Encoding(false).GetString(xml, 3, xml.Length - 3);
|
||||
}
|
||||
|
||||
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]))
|
||||
{
|
||||
return Encoding.Unicode.GetString(xml, 2, xml.Length - 2);
|
||||
}
|
||||
|
||||
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[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("<?xml", StringComparison.Ordinal);
|
||||
var end = start < 0 ? -1 : 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<IncomingDiscount> 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<IncomingReference> 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<int> 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<IncomingPayment> 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<IncomingAttachment> 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<XElement> 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);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class IncomingInvoiceRulesIt : IIncomingInvoiceRules
|
||||
{
|
||||
private static readonly HashSet<string> Invoices = new(StringComparer.Ordinal) { "TD01", "TD02", "TD03", "TD05", "TD06", "TD24", "TD25", "TD26", "TD27" };
|
||||
private static readonly HashSet<string> CreditNotes = new(StringComparer.Ordinal) { "TD04", "TD08" };
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? DocumentTypeCode(string formatType)
|
||||
{
|
||||
var type = formatType?.Trim().ToUpperInvariant() ?? string.Empty;
|
||||
return Invoices.Contains(type) ? "FF" : CreditNotes.Contains(type) ? "NCF" : null;
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
@@ -15,6 +15,9 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
public ItalyFiscalPack()
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
|
||||
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
|
||||
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
|
||||
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class SelfInvoiceRulesIt : ISelfInvoiceRules
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<string> DocumentTypeCodes { get; } = ["AF16", "AF17", "AF18", "AF19", "AF20", "AF21", "AF22", "AF23", "AF28", "AF29"];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string OrdinaryTaxCode => "22";
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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));
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A structure that is not a readable CMS SignedData, or whose content cannot be extracted.</summary>
|
||||
public sealed class CmsFormatException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public CmsFormatException()
|
||||
: base("Not a CMS SignedData structure.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public CmsFormatException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public CmsFormatException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A signer of a CMS SignedData with what its certificate says and the result of the check.</summary>
|
||||
/// <param name="Name">The name of the signer: common name, else given name and surname, else organization, else
|
||||
/// serial number of the subject.</param>
|
||||
/// <param name="TaxCode">The tax code of the signer, from the subject's <c>SERIALNUMBER</c> (OID 2.5.4.5) without
|
||||
/// the <c>TINIT-</c> or <c>IT:</c> prefix, when present.</param>
|
||||
/// <param name="Subject">The subject of the certificate, or <see langword="null"/> when it was not found.</param>
|
||||
/// <param name="Issuer">The issuer of the certificate, or <see langword="null"/> when it was not found.</param>
|
||||
/// <param name="CertificateNotBefore">The start of validity of the certificate.</param>
|
||||
/// <param name="CertificateNotAfter">The end of validity of the certificate.</param>
|
||||
/// <param name="SigningTime">The <c>signingTime</c> signed attribute: what the signer's clock said, not a trusted timestamp.</param>
|
||||
/// <param name="Verified">Whether the digest of the content and the signature match.</param>
|
||||
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
|
||||
/// <param name="Certificate">The DER of the signer certificate, or <see langword="null"/> when it was not found.</param>
|
||||
public sealed record CmsSigner(
|
||||
string? Name, string? TaxCode, string? Subject, string? Issuer,
|
||||
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, DateTimeOffset? SigningTime,
|
||||
bool Verified, string? Problem, byte[]? Certificate);
|
||||
|
||||
/// <summary>The content of one or more nested CMS SignedData envelopes and their signers.</summary>
|
||||
/// <param name="Content">The content of the innermost envelope.</param>
|
||||
/// <param name="Signers">The signers, outermost envelope first.</param>
|
||||
/// <param name="Layers">How many envelopes were opened (two for <c>.xml.p7m.p7m</c>).</param>
|
||||
public sealed record CmsContent(byte[] Content, IReadOnlyList<CmsSigner> Signers, int Layers)
|
||||
{
|
||||
/// <summary>Whether there is at least one signer and every signer of every envelope is verified.</summary>
|
||||
public bool Verified => Signers.Count > 0 && Signers.All(s => s.Verified);
|
||||
|
||||
/// <summary>The first problem found, or <see langword="null"/> when <see cref="Verified"/>.</summary>
|
||||
public string? Problem => Signers.Count == 0 ? "The envelope has no signer." : Signers.FirstOrDefault(s => s.Problem is not null)?.Problem;
|
||||
|
||||
/// <summary>The signer of the outermost envelope, or <see langword="null"/> when there is none.</summary>
|
||||
public CmsSigner? Signer => Signers.Count > 0 ? Signers[0] : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A minimal reader of CMS SignedData (RFC 5652, PKCS #7), the envelope of CAdES signed files such as <c>.p7m</c>,
|
||||
/// written on <c>System.Formats.Asn1</c> because <c>System.Security.Cryptography.Pkcs</c> is a separate package
|
||||
/// (SPEC §1.2).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>It accepts DER and BER (indefinite lengths, content split in constructed chunks), the base64 text of the
|
||||
/// binary with or without line breaks and <c>-----BEGIN</c> armour, and nested envelopes (<c>.p7m.p7m</c>), opened
|
||||
/// until the content is no longer CMS.</para>
|
||||
/// <para>It checks integrity only: the <c>messageDigest</c> 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 <b>not</b> 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 <see cref="CmsSigner.Verified"/> false and the
|
||||
/// problem; only unreadable structures throw <see cref="CmsFormatException"/>. Detached signatures (no content) are
|
||||
/// not supported.</para>
|
||||
/// </remarks>
|
||||
public static class CmsSignedData
|
||||
{
|
||||
/// <summary>The largest envelope read, 50 MB.</summary>
|
||||
public const int MaxSize = 50 * 1024 * 1024;
|
||||
|
||||
/// <summary>The most nested envelopes opened.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Whether the bytes look like a CMS SignedData, in binary or as base64 text. Only the start is looked at.</summary>
|
||||
/// <param name="data">The content, or at least its first hundred bytes.</param>
|
||||
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
|
||||
public static bool LooksLikeCms(ReadOnlySpan<byte> data)
|
||||
{
|
||||
if (LooksLikeBinaryCms(data))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Base64 text: decode the first characters and look again.
|
||||
Span<byte> 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<byte> 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]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="data">The envelope.</param>
|
||||
/// <returns>The content of the innermost envelope and the signers.</returns>
|
||||
/// <exception cref="CmsFormatException">The data is not a CMS SignedData, is too large, nests too deep, has no
|
||||
/// content, or cannot be decoded.</exception>
|
||||
public static CmsContent Read(byte[] data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var current = data;
|
||||
var signers = new List<CmsSigner>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the base64 text form of a binary structure: whitespace and line breaks are skipped, <c>-----BEGIN</c>
|
||||
/// and <c>-----END</c> lines dropped, a UTF-8 byte order mark ignored.
|
||||
/// </summary>
|
||||
/// <param name="text">The text, as bytes.</param>
|
||||
/// <returns>The decoded bytes, or <see langword="null"/> when the text is not base64.</returns>
|
||||
public static byte[]? DecodeBase64Text(ReadOnlySpan<byte> 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<byte> 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<CmsSigner> 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<byte[]>();
|
||||
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<byte[]> 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<byte[]> 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<X509SubjectKeyIdentifierExtension>().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<byte[]> 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<byte[]> SignedAttributesAsSet(byte[] signedAttributes)
|
||||
{
|
||||
var forms = new List<byte[]>();
|
||||
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-<tax code>; older Italian certificates use IT:<tax code>.
|
||||
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<byte> SkipBom(ReadOnlySpan<byte> data) =>
|
||||
data.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]) ? data[3..] : data;
|
||||
|
||||
private static ReadOnlySpan<byte> SkipArmour(ReadOnlySpan<byte> data)
|
||||
{
|
||||
var trimmed = data.TrimStart((ReadOnlySpan<byte>)[(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';
|
||||
}
|
||||
@@ -19,6 +19,9 @@
|
||||
case WidgetIds.SystemStatus:
|
||||
<SystemStatusWidget Definition="Definition" />
|
||||
break;
|
||||
case WidgetIds.Understock:
|
||||
<UnderstockWidget Definition="Definition" />
|
||||
break;
|
||||
default:
|
||||
<ComingWidget Definition="Definition" />
|
||||
break;
|
||||
|
||||
@@ -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. *@
|
||||
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
|
||||
<Actions>
|
||||
@if (_rows is { Count: > 0 })
|
||||
{
|
||||
<span class="badge @(_rows.Any(r => r.Level == StockLevel.Out) ? "red" : "amber")">@T.Number(_rows.Count)</span>
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (_failed)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="alert" /> @T["Dashboard.Feed.Error"]</p>
|
||||
}
|
||||
else if (_rows is null)
|
||||
{
|
||||
<p class="kh-wempty muted">@T["Dashboard.Feed.Loading"]</p>
|
||||
}
|
||||
else if (_rows.Count == 0)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Dashboard.Widgets.Understock.Empty"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="list kh-wlist">
|
||||
@foreach (var row in _rows)
|
||||
{
|
||||
<a class="li" href="magazzino/giacenze?articolo=@row.ItemId">
|
||||
<span class="kh-tone @(row.Level == StockLevel.Out ? "err" : "warn")" aria-hidden="true"></span>
|
||||
<div class="grow">
|
||||
<div class="t"><span class="code">@row.Code</span> @row.Description</div>
|
||||
<div class="s">@T.Format("Dashboard.Widgets.Understock.Line", T.Number(row.Available), T.Number(row.MinimumStock ?? row.ReorderPoint ?? 0m))</div>
|
||||
</div>
|
||||
<span class="badge @(row.Level == StockLevel.Out ? "red" : "amber")">@T["Inventory.Levels." + row.Level]</span>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
<div class="kh-wfoot"><a href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Dashboard.Widgets.Understock.Reorder"]</a></div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhWidget>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<StockRow>? _rows;
|
||||
private bool _failed;
|
||||
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<KhOption<string>> TargetChoices => [.. Targets.Select(t => new KhOption<string>(t.Key, TargetName(t.Key)))];
|
||||
|
||||
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["Inventory.Reorder.Title"]" Icon="refresh" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(InventoryService.StockPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhStrip Items="Stats" Label="@T["Inventory.Reorder.Title"]" />
|
||||
|
||||
@if (_orders.Count > 0)
|
||||
{
|
||||
<div class="callout ok kh-pad" role="status">
|
||||
<KhIcon Name="check-circle" />
|
||||
<span>
|
||||
@T.Format("Inventory.Reorder.Created", _orders.Count)
|
||||
@foreach (var order in _orders)
|
||||
{
|
||||
<span> </span><a href="@SalesScreens.RecordUrl(order.Record.Header.Kind, order.Record.Header.Id)">@order.Supplier</a>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<KhPanel Title="@T["Inventory.Reorder.Lines"]" Icon="list">
|
||||
<Actions>
|
||||
<span class="muted sm">@T.Format("Inventory.Reorder.Selected", Chosen.Count(), T.Money(ChosenValue))</span>
|
||||
<button type="button" class="btn" disabled="@_busy" @onclick="LoadAsync"><KhIcon Name="refresh" /> @T["Inventory.Reorder.Refresh"]</button>
|
||||
@if (CanOrder)
|
||||
{
|
||||
<button type="button" class="btn primary" disabled="@(_busy || !Chosen.Any())" @onclick="CreateAsync"><KhIcon Name="truck" /> @T["Inventory.Reorder.Create"]</button>
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (_lines.Count == 0)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T["Inventory.Reorder.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap kh-scrollx">
|
||||
<table class="grid" aria-label="@T["Inventory.Reorder.Lines"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" class="kh-check"><input type="checkbox" checked="@_lines.All(l => l.Chosen)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col">@T["Items.Radar.Unit"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.Available"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.OrderedColumn"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.Minimum"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.ReorderPoint"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Reorder.Quantity"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Reorder.Price"]</th>
|
||||
<th scope="col">@T["Inventory.Reorder.Expected"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in _lines)
|
||||
{
|
||||
var row = line.Proposal;
|
||||
<tr class="@(line.Chosen ? "sel" : null)">
|
||||
<td class="kh-check"><input type="checkbox" checked="@line.Chosen" aria-label="@row.Code" @onchange="e => line.Chosen = e.Value is true" /></td>
|
||||
<td class="code">@row.Code</td>
|
||||
<td>@row.Description</td>
|
||||
<td>@PartyScreens.Describe(_lookups.Units, row.UnitOfMeasureId)</td>
|
||||
<td class="num @(row.Available < 0m ? "err" : null)">@Qty(row.Available)</td>
|
||||
<td class="num">@Qty(row.Ordered)</td>
|
||||
<td class="num">@(row.MinimumStock is { } m ? Qty(m) : null)</td>
|
||||
<td class="num">@(row.ReorderPoint is { } p ? Qty(p) : null)</td>
|
||||
<td class="num">
|
||||
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.Reorder.Quantity"] + " " + row.Code)"
|
||||
value="@Qty(line.Quantity)" @onchange="e => SetQuantity(line, e.Value?.ToString())" />
|
||||
</td>
|
||||
<td class="kh-cellpick">
|
||||
<KhHotlink TItem="PartyRow" Name="@("Supplier" + row.ItemId)" Value="line.Supplier" ValueChanged="v => line.Supplier = v" Span="12"
|
||||
Search="SearchAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Placeholder="@T["Inventory.Reorder.ChooseSupplier"]" />
|
||||
</td>
|
||||
<td class="num">@(row.Price is { } price ? T.Money(price) : null)</td>
|
||||
<td>@(row.ExpectedDate is { } date ? T.Date(date) : null)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
<p class="muted sm kh-pad">@T["Inventory.Reorder.Hint"]</p>
|
||||
}
|
||||
|
||||
@code {
|
||||
private List<Line> _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<Line> 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<KhStat> 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),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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<IReadOnlyList<PartyRow>> 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; }
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["Inventory.Stock.Title"]" Icon="box" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(InventoryService.StockPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhStrip Items="Stats" Label="@T["Inventory.Stock.Title"]" />
|
||||
<KhForm Layout="KhFormLayout.Grid" Class="kh-pagefilters">
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="Warehouse" Options="_warehouses" Empty="@T["Inventory.Stock.AllWarehouses"]"
|
||||
Value="@PartyScreens.Text(_warehouse)" ValueChanged="SetWarehouseAsync" Span="4" />
|
||||
<KhCheck Label="@T["Inventory.Stock.IncludeEmpty"]" Name="IncludeEmpty" Value="_includeEmpty" ValueChanged="SetIncludeEmptyAsync" Span="4" />
|
||||
</KhForm>
|
||||
|
||||
<KhRadar TItem="StockRow" @ref="_radar" Id="stock" Columns="Columns" Source="ListAsync" KeyOf="r => r.ItemId" Selectable="false" OnOpen="OpenMovementsAsync"
|
||||
QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Inventory.Stock.Search"]" ExportName="giacenze" Label="@T["Inventory.Stock.Title"]">
|
||||
<Toolbar>
|
||||
<a class="btn" href="magazzino/riordino"><KhIcon Name="refresh" /> @T["Shell.Menu.Inventory.Reorder"]</a>
|
||||
<a class="btn" href="magazzino/inventario"><KhIcon Name="file-check" /> @T["Shell.Menu.Inventory.StockTake"]</a>
|
||||
@if (_costs)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="OpenValuation"><KhIcon Name="euro" /> @T["Inventory.Valuation.Title"]</button>
|
||||
}
|
||||
@if (Session.Permissions.Allows(InventoryService.PostPermission))
|
||||
{
|
||||
<button type="button" class="btn" disabled="@_busy" @onclick="RebuildAsync"><KhIcon Name="layers" /> @T["Inventory.Rebuild.Action"]</button>
|
||||
}
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
|
||||
@if (_rebuild is { } progress)
|
||||
{
|
||||
<div class="callout info kh-pad" role="status">
|
||||
<KhIcon Name="layers" />
|
||||
<span>@T.Format("Inventory.Rebuild.Progress", T["Inventory.Rebuild.Phases." + progress.Phase], T.Number(progress.Done), T.Number(progress.Total))</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<KhDialog Open="_item is not null" Title="@MovementsTitle" Icon="layers" Size="lg" OnClose="() => _item = null">
|
||||
<ChildContent>
|
||||
@if (_balances is { Count: > 1 })
|
||||
{
|
||||
<KhStrip Items="BalanceStats" Label="@T["Inventory.Movements.ByWarehouse"]" />
|
||||
}
|
||||
@if (_movements is null)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (_movements.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Inventory.Movements.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap kh-dialoggrid">
|
||||
<table class="grid" aria-label="@T["Inventory.Movements.Title"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Inventory.Movements.Date"]</th>
|
||||
<th scope="col">@T["Inventory.Movements.Document"]</th>
|
||||
<th scope="col">@T["Inventory.Fields.Reason"]</th>
|
||||
<th scope="col">@T["Inventory.Movements.Party"]</th>
|
||||
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
|
||||
@if (_costs)
|
||||
{
|
||||
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
|
||||
}
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Balance"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var move in _movements)
|
||||
{
|
||||
<tr>
|
||||
<td>@T.Date(move.Date)</td>
|
||||
<td>
|
||||
@if (move.Kind is { } kind && move.DocumentId is { } document)
|
||||
{
|
||||
<a href="@SalesScreens.RecordUrl(kind, document)">@T["Sales.Kinds." + kind] <span class="mono">@move.Number</span></a>
|
||||
}
|
||||
</td>
|
||||
<td class="code">@move.ReasonCode</td>
|
||||
<td>@move.PartyName</td>
|
||||
<td>@PartyScreens.Describe(_warehouses, move.WarehouseId)</td>
|
||||
<td class="num @(move.Quantity < 0m ? "err" : "ok")">@Qty(move.Quantity)</td>
|
||||
@if (_costs)
|
||||
{
|
||||
<td class="num">@Cost(move.UnitCost)</td>
|
||||
}
|
||||
<td class="num"><b>@Qty(move.Balance)</b></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
@if (_item is { } item)
|
||||
{
|
||||
<a class="btn" href="@ItemScreens.RecordUrl(item.ItemId)"><KhIcon Name="box" /> @T["Inventory.Movements.OpenItem"]</a>
|
||||
}
|
||||
<button type="button" class="btn primary" @onclick="() => _item = null">@T["Common.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
<KhDialog Open="_valuationOpen" Title="@T["Inventory.Valuation.Title"]" Icon="euro" Size="lg" OnClose="() => _valuationOpen = false">
|
||||
<ChildContent>
|
||||
<KhForm Layout="KhFormLayout.Grid">
|
||||
<KhDateBox Label="@T["Inventory.Valuation.Date"]" Name="ValuationDate" Value="_valuationDate" ValueChanged="v => _valuationDate = v" Span="4" Required="true" />
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Valuation.Method"]" Name="Method" Options="Methods" Value="@_method.ToString()" Span="4"
|
||||
ValueChanged="SetMethod" />
|
||||
<div class="c4 kh-endrow">
|
||||
<button type="button" class="btn primary" disabled="@_busy" @onclick="ValueAsync"><KhIcon Name="chart" /> @T["Inventory.Valuation.Compute"]</button>
|
||||
</div>
|
||||
</KhForm>
|
||||
@if (_valuation is { } rows)
|
||||
{
|
||||
<KhStrip Items="ValuationStats" Label="@T["Inventory.Valuation.Title"]" />
|
||||
<div class="gridwrap kh-dialoggrid">
|
||||
<table class="grid" aria-label="@T["Inventory.Valuation.Title"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Stock.Value"]</th>
|
||||
<th scope="col">@T["Inventory.Valuation.Class"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var row in rows)
|
||||
{
|
||||
<tr>
|
||||
<td class="code">@row.Code</td>
|
||||
<td>@row.Description</td>
|
||||
<td class="num">@Qty(row.Quantity)</td>
|
||||
<td class="num">@T.Money(row.UnitCost)</td>
|
||||
<td class="num">@T.Money(row.Value)</td>
|
||||
<td><KhBadge Tone="@(row.AbcClass switch { 'A' => KhTone.Ok, 'B' => KhTone.Info, _ => KhTone.Neutral })">@row.AbcClass</KhBadge></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
<p class="muted sm">@T["Inventory.Valuation.Hint"]</p>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn primary" @onclick="() => _valuationOpen = false">@T["Common.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private static readonly ListFields<StockRow> Fields = new ListFields<StockRow>()
|
||||
.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<StockRow> _source = new([], Fields);
|
||||
private IReadOnlyList<StockRow> _rows = [];
|
||||
private ItemLookups _lookups = ItemLookups.Empty;
|
||||
private IReadOnlyList<KhOption<string>> _warehouses = [];
|
||||
private KhRadar<StockRow>? _radar;
|
||||
private long? _warehouse;
|
||||
private bool _includeEmpty;
|
||||
private bool _costs;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
private RebuildProgress? _rebuild;
|
||||
|
||||
private StockRow? _item;
|
||||
private IReadOnlyList<MovementRow>? _movements;
|
||||
private IReadOnlyList<ItemBalance>? _balances;
|
||||
|
||||
private bool _valuationOpen;
|
||||
private DateOnly? _valuationDate;
|
||||
private StockValuationMethod _method = StockValuationMethod.WeightedAverage;
|
||||
private IReadOnlyList<ValuationRow>? _valuation;
|
||||
|
||||
/// <summary>An item to open at once, from the dashboard.</summary>
|
||||
[SupplyParameterFromQuery(Name = "articolo")]
|
||||
public long? ItemId { get; set; }
|
||||
|
||||
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
|
||||
private IReadOnlyList<KhStat> 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<KhStat>(),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhStat> BalanceStats => _balances is null ? [] :
|
||||
[.. _balances.Select(b => new KhStat(PartyScreens.Describe(_warehouses, b.WarehouseId) ?? string.Empty, Qty(b.OnHand)))];
|
||||
|
||||
private IReadOnlyList<KhStat> 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<KhOption<string>> 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<KhColumn<StockRow>> 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 => @<KhBadge Tone="ToneOf(r.Level)">@T["Inventory.Levels." + r.Level]</KhBadge>,
|
||||
},
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> 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<StockLevel>().Select(l => new KhOption<string>(l.ToString(), T["Inventory.Levels." + l])),
|
||||
]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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<Warehouse>(actor, company)).Select(w => new KhOption<string>(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<StockRow>(_rows, Fields);
|
||||
}
|
||||
|
||||
private Task<ListPage<StockRow>> 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<StockValuationMethod>(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<RebuildProgress>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@Title" Icon="file-check" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(InventoryService.EntryReadPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else if (Id is null)
|
||||
{
|
||||
<div class="kh-import">
|
||||
<div class="kh-import-side">
|
||||
<KhPanel Title="@T["Inventory.StockTake.New"]" Icon="plus">
|
||||
@if (CanWrite)
|
||||
{
|
||||
<KhForm Layout="KhFormLayout.Grid" Validation="_validation" Class="kh-import-options">
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Fields.Warehouse"]" Name="WarehouseId" Options="_warehouses" Value="@PartyScreens.Text(_warehouse)"
|
||||
ValueChanged="v => _warehouse = PartyScreens.Id(v)" Span="12" Required="true" />
|
||||
<KhDateBox Label="@T["Inventory.StockTake.Date"]" Name="TakeDate" Value="_date" ValueChanged="v => _date = v" Span="6" Required="true" />
|
||||
<KhSelect TValue="string" Label="@T["Items.Radar.Category"]" Name="CategoryId" Options="_lookups.Categories" Empty="@T["Inventory.StockTake.AllCategories"]"
|
||||
Value="@PartyScreens.Text(_category)" ValueChanged="v => _category = PartyScreens.Id(v)" Span="6" />
|
||||
<KhTextBox Label="@T["Inventory.StockTake.Description"]" Name="Description" Value="@_description" ValueChanged="v => _description = v" Span="12"
|
||||
Hint="@T["Inventory.StockTake.DescriptionHint"]" />
|
||||
<div class="c12 kh-endrow">
|
||||
<button type="button" class="btn primary" disabled="@(_busy || _warehouse is null || _date is null)" @onclick="CreateAsync">
|
||||
<KhIcon Name="file-check" /> @T["Inventory.StockTake.Open"]
|
||||
</button>
|
||||
</div>
|
||||
</KhForm>
|
||||
}
|
||||
<p class="muted sm kh-pad">@T["Inventory.StockTake.Hint"]</p>
|
||||
</KhPanel>
|
||||
</div>
|
||||
<div class="kh-import-main">
|
||||
<KhPanel Title="@T["Inventory.StockTake.List"]" Icon="list">
|
||||
@if (_takes.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Inventory.StockTake.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Inventory.StockTake.List"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Inventory.StockTake.Date"]</th>
|
||||
<th scope="col">@T["Inventory.StockTake.Description"]</th>
|
||||
<th scope="col">@T["Inventory.Fields.Warehouse"]</th>
|
||||
<th scope="col">@T["Items.Radar.State"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var take in _takes)
|
||||
{
|
||||
<tr>
|
||||
<td>@T.Date(take.TakeDate)</td>
|
||||
<td><a href="magazzino/inventario/@take.Id">@take.Description</a></td>
|
||||
<td>@PartyScreens.Describe(_warehouses, take.WarehouseId)</td>
|
||||
<td><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</KhPanel>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
else if (_view is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="alert" Class="lg" /><h1>@T["Inventory.StockTake.Missing"]</h1><p><a href="magazzino/inventario">@T["Inventory.StockTake.List"]</a></p></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
var take = _view.Take;
|
||||
<div class="kh-import">
|
||||
<div class="kh-import-side">
|
||||
<KhPanel Title="@take.Description" Icon="file-check">
|
||||
<KhVSteps Items="Steps" Current="Step" Label="@T["Inventory.StockTake.Procedure"]" />
|
||||
<dl class="kh-facts">
|
||||
<dt>@T["Inventory.Fields.Warehouse"]</dt><dd>@PartyScreens.Describe(_warehouses, take.WarehouseId)</dd>
|
||||
<dt>@T["Inventory.StockTake.Date"]</dt><dd>@T.Date(take.TakeDate)</dd>
|
||||
<dt>@T["Items.Radar.Category"]</dt><dd>@(PartyScreens.Describe(_lookups.Categories, take.CategoryId) ?? T["Inventory.StockTake.AllCategories"])</dd>
|
||||
<dt>@T["Items.Radar.State"]</dt><dd><KhBadge Tone="ToneOf(take.Status)">@T["Inventory.StockTake.States." + take.Status]</KhBadge></dd>
|
||||
@if (take.Status == StockTakeStatus.Posted)
|
||||
{
|
||||
<dt>@T["Inventory.StockTake.Movements"]</dt>
|
||||
<dd>
|
||||
@if (take.AdjustmentDocumentId is { } gain)
|
||||
{
|
||||
<a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, gain)">@StockTakeService.GainReason</a>
|
||||
}
|
||||
@if (take.LossDocumentId is { } loss)
|
||||
{
|
||||
<span> </span><a href="@SalesScreens.RecordUrl(DocumentKind.InventoryEntry, loss)">@StockTakeService.LossReason</a>
|
||||
}
|
||||
</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (IsOpen && CanWrite)
|
||||
{
|
||||
<div class="kh-endrow kh-pad">
|
||||
<button type="button" class="btn" disabled="@_busy" @onclick="CancelAsync"><KhIcon Name="x-circle" /> @T["Inventory.StockTake.Cancel"]</button>
|
||||
</div>
|
||||
}
|
||||
</KhPanel>
|
||||
</div>
|
||||
<div class="kh-import-main">
|
||||
<KhStrip Items="Stats" Label="@T["Inventory.StockTake.Procedure"]" />
|
||||
<KhPanel Title="@T["Inventory.StockTake.Lines"]" Icon="list">
|
||||
<ChildContent>
|
||||
<div class="kh-taketools">
|
||||
<input type="search" class="in kh-searchbox" placeholder="@T["Inventory.Stock.Search"]" aria-label="@T["Inventory.Stock.Search"]"
|
||||
value="@_search" @oninput="e => _search = e.Value?.ToString()" />
|
||||
<select class="in" aria-label="@T["Inventory.StockTake.Show"]" @onchange="e => _show = e.Value?.ToString() ?? string.Empty">
|
||||
<option value="" selected="@(_show.Length == 0)">@T["Inventory.StockTake.ShowAll"]</option>
|
||||
<option value="todo" selected="@(_show == "todo")">@T["Inventory.StockTake.ShowToCount"]</option>
|
||||
<option value="diff" selected="@(_show == "diff")">@T["Inventory.StockTake.ShowDifferences"]</option>
|
||||
</select>
|
||||
@if (IsOpen && CanWrite)
|
||||
{
|
||||
<label class="btn kh-filebtn">
|
||||
<KhIcon Name="upload" /> @T["Inventory.StockTake.Import"]
|
||||
<InputFile OnChange="ImportAsync" accept=".csv,.txt,text/csv,text/plain" disabled="@_busy" />
|
||||
</label>
|
||||
<button type="button" class="btn" disabled="@(_busy || _counts.Count == 0)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Inventory.StockTake.Save"]</button>
|
||||
@if (Session.Permissions.Allows(InventoryService.PostPermission))
|
||||
{
|
||||
<button type="button" class="btn primary" disabled="@_busy" @onclick="PostAsync"><KhIcon Name="check-circle" /> @T["Inventory.StockTake.Post"]</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="gridwrap kh-scrollx">
|
||||
<table class="grid" aria-label="@T["Inventory.StockTake.Lines"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col">@T["Items.Radar.Unit"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.Book"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.Counted"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.Difference"]</th>
|
||||
@if (_costs)
|
||||
{
|
||||
<th scope="col" class="num">@T["Inventory.Movements.UnitCost"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.StockTake.DifferenceValue"]</th>
|
||||
}
|
||||
<th scope="col">@T["Items.Radar.State"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in Shown)
|
||||
{
|
||||
var id = line.Line.Id;
|
||||
var counted = CountOf(line);
|
||||
var difference = counted is { } c ? c - line.Line.BookQuantity : 0m;
|
||||
<tr class="@(counted is not null && difference != 0m ? "hl" : null)">
|
||||
<td class="code">@line.Code</td>
|
||||
<td>@line.Description</td>
|
||||
<td>@PartyScreens.Describe(_lookups.Units, line.UnitOfMeasureId)</td>
|
||||
<td class="num">@Qty(line.Line.BookQuantity)</td>
|
||||
<td class="num">
|
||||
@if (IsOpen && CanWrite)
|
||||
{
|
||||
<input type="text" inputmode="decimal" class="in num kh-countbox" aria-label="@(T["Inventory.StockTake.Counted"] + " " + line.Code)"
|
||||
value="@(counted is { } v ? Qty(v) : null)" @onchange="e => SetCount(id, e.Value?.ToString())" />
|
||||
}
|
||||
else
|
||||
{
|
||||
@(counted is { } v ? Qty(v) : "—")
|
||||
}
|
||||
</td>
|
||||
<td class="num @(difference < 0m ? "err" : difference > 0m ? "ok" : null)">@(counted is null ? null : Qty(difference))</td>
|
||||
@if (_costs)
|
||||
{
|
||||
<td class="num">@T.Money(line.Line.UnitCost)</td>
|
||||
<td class="num">@(counted is null ? null : T.Money(Math.Round(difference * line.Line.UnitCost, 2)))</td>
|
||||
}
|
||||
<td>
|
||||
@if (counted is null)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Neutral">@T["Inventory.StockTake.ToCount"]</KhBadge>
|
||||
}
|
||||
else if (difference == 0m)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Ok">@T["Inventory.StockTake.Matches"]</KhBadge>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["Inventory.StockTake.Differs"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly KhValidation _validation = new();
|
||||
private readonly Dictionary<long, decimal?> _counts = [];
|
||||
private IReadOnlyList<StockTake> _takes = [];
|
||||
private IReadOnlyList<KhOption<string>> _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;
|
||||
|
||||
/// <summary>The stock take shown, or none for the list.</summary>
|
||||
[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<KhStep> 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<KhStat> 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<KhStat>(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<StockTakeLineView> 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,
|
||||
});
|
||||
|
||||
/// <inheritdoc />
|
||||
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<Warehouse>(actor, company)).Select(w => new KhOption<string>(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<long?> DefaultWarehouseAsync(Actor actor, string company) =>
|
||||
(await Tables.ActiveAsync<Warehouse>(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)));
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["Purchases.Import.Title"]" Icon="upload" />
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Inventory.NoCompany"]</h1></div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(PurchaseService.WritePermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kh-import">
|
||||
<div class="kh-import-side">
|
||||
<KhPanel Title="@T["Purchases.Import.Procedure"]" Icon="upload">
|
||||
<KhVSteps Items="Steps" Current="_step" Label="@T["Purchases.Import.Procedure"]" />
|
||||
<div class="kh-import-options">
|
||||
<div class="f c12">
|
||||
<label for="kh-incoming-files">@T["Purchases.Import.Files"]</label>
|
||||
<InputFile id="kh-incoming-files" class="in" OnChange="ReadAsync" multiple accept=".xml,.p7m,.zip" disabled="@_busy" />
|
||||
<span class="muted sm">@T["Purchases.Import.FilesHint"]</span>
|
||||
</div>
|
||||
</div>
|
||||
</KhPanel>
|
||||
</div>
|
||||
<div class="kh-import-main">
|
||||
@if (_results.Count > 0)
|
||||
{
|
||||
<KhPanel Title="@T["Purchases.Import.Results"]" Icon="check-circle">
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Purchases.Import.Results"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.SupplierNumber"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Draft"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Check"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var result in _results)
|
||||
{
|
||||
<tr>
|
||||
<td>
|
||||
@result.Candidate.File.Supplier.DisplayName
|
||||
@if (result.SupplierCreated)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Purchases.Import.NewSupplier"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
<td class="code">@result.Candidate.Invoice.Number</td>
|
||||
@if (result.Record is { } record)
|
||||
{
|
||||
<td><a href="@SalesScreens.RecordUrl(record.Header.Kind, record.Header.Id)">@T["Sales.Kinds." + record.Header.Kind] · @T.Money(record.Header.TotalAmount)</a></td>
|
||||
<td>@string.Join(" ", result.Warnings.Select(w => T[w]))</td>
|
||||
}
|
||||
else
|
||||
{
|
||||
<td colspan="2" class="err"><KhIcon Name="alert-circle" /> @(T.Contains(result.Error ?? string.Empty) ? T[result.Error!] : result.Error)</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="kh-endrow kh-pad">
|
||||
<a class="btn" href="acquisti/fatture"><KhIcon Name="euro" /> @T["Sales.Sections.PurchaseInvoices.Title"]</a>
|
||||
<button type="button" class="btn" @onclick="Restart"><KhIcon Name="refresh" /> @T["Purchases.Import.Again"]</button>
|
||||
</div>
|
||||
</KhPanel>
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (_rejected.Count > 0)
|
||||
{
|
||||
<div class="callout warn kh-pad" role="alert">
|
||||
<KhIcon Name="alert" />
|
||||
<div>
|
||||
<b>@T.Format("Purchases.Import.Rejected", _rejected.Count)</b>
|
||||
<ul class="kh-plainlist">
|
||||
@foreach (var file in _rejected)
|
||||
{
|
||||
<li><span class="code">@file.FileName</span> · @(T.Contains(file.Error) ? T[file.Error] : file.Error)</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<KhPanel Title="@T["Purchases.Import.Invoices"]" Icon="file">
|
||||
<Actions>
|
||||
<span class="muted sm">@T.Format("Purchases.Import.Selected", _selected.Count, T.Money(SelectedTotal))</span>
|
||||
<button type="button" class="btn primary" disabled="@(_selected.Count == 0 || _busy)" @onclick="ImportAsync">
|
||||
<KhIcon Name="download" /> @T["Purchases.Import.Register"]
|
||||
</button>
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (_invoices.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Purchases.Import.Start"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Purchases.Import.Invoices"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" class="kh-check"><input type="checkbox" checked="@(_selected.Count == Importable.Count() && _selected.Count > 0)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col">@T["Purchases.Import.VatNumber"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Type"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.SupplierNumber"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.SupplierDate"]</th>
|
||||
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
|
||||
<th scope="col">@T["Purchases.Import.Check"]</th>
|
||||
<th scope="col"><span class="sr-only">@T["Purchases.Import.View"]</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (var i = 0; i < _invoices.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var invoice = _invoices[i];
|
||||
<tr class="@(invoice.CanImport ? null : "muted")">
|
||||
<td class="kh-check">
|
||||
<input type="checkbox" checked="@_selected.Contains(index)" disabled="@(!invoice.CanImport)" aria-label="@invoice.Invoice.Number"
|
||||
@onchange="e => Toggle(index, e.Value is true)" />
|
||||
</td>
|
||||
<td>
|
||||
@invoice.File.Supplier.DisplayName
|
||||
@if (invoice.SupplierId is null)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Purchases.Import.NewSupplier"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
<td class="code">@(invoice.File.Supplier.CountryCode)@invoice.File.Supplier.VatNumber</td>
|
||||
<td><span class="code">@invoice.Invoice.DocumentType</span> @(invoice.DocumentTypeCode is { } code ? "→ " + code : null)</td>
|
||||
<td class="code">@invoice.Invoice.Number</td>
|
||||
<td>@T.Date(invoice.Invoice.Date)</td>
|
||||
<td class="num">@T.Money(invoice.Total)</td>
|
||||
<td>
|
||||
@if (invoice.Problems.Count == 0)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Ok">@T["Purchases.Import.Ready"]</KhBadge>
|
||||
}
|
||||
@foreach (var problem in invoice.Problems)
|
||||
{
|
||||
<KhBadge Tone="@(invoice.CanImport ? KhTone.Warning : KhTone.Error)">@T[problem + ".short"]</KhBadge>
|
||||
}
|
||||
</td>
|
||||
<td><button type="button" class="btn sm" @onclick="() => _shown = invoice"><KhIcon Name="eye" /> @T["Purchases.Import.View"]</button></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<KhDialog Open="_shown is not null" Title="@ShownTitle" Icon="file" Size="lg" OnClose="() => _shown = null">
|
||||
<ChildContent>
|
||||
@if (_shown is { } shown)
|
||||
{
|
||||
var supplier = shown.File.Supplier;
|
||||
var invoice = shown.Invoice;
|
||||
<div class="kh-einvoice">
|
||||
<dl class="kh-facts">
|
||||
<dt>@T["Purchases.Fields.Supplier"]</dt>
|
||||
<dd><b>@supplier.DisplayName</b><br />@supplier.Address @supplier.StreetNumber, @supplier.PostalCode @supplier.City @(supplier.Province is null ? null : "(" + supplier.Province + ")")</dd>
|
||||
<dt>@T["Purchases.Import.VatNumber"]</dt><dd class="code">@supplier.CountryCode@supplier.VatNumber @(supplier.TaxCode is null ? null : " · " + supplier.TaxCode)</dd>
|
||||
<dt>@T["Purchases.Import.Type"]</dt><dd><span class="code">@invoice.DocumentType</span> · @invoice.Currency</dd>
|
||||
<dt>@T["Purchases.Fields.SupplierNumber"]</dt><dd>@invoice.Number · @T.Date(invoice.Date)</dd>
|
||||
@if (invoice.Causals.Count > 0)
|
||||
{
|
||||
<dt>@T["Purchases.Import.Causal"]</dt><dd>@string.Join(" ", invoice.Causals)</dd>
|
||||
}
|
||||
@if (shown.File.Signature is { } signature)
|
||||
{
|
||||
<dt>@T["Purchases.Import.Signature"]</dt>
|
||||
<dd>
|
||||
<KhBadge Tone="@(signature.Verified ? KhTone.Ok : KhTone.Warning)">@T[signature.Verified ? "Purchases.Import.SignatureOk" : "Purchases.Import.SignatureKo"]</KhBadge>
|
||||
@signature.Signer
|
||||
</dd>
|
||||
}
|
||||
</dl>
|
||||
<div class="gridwrap kh-dialoggrid">
|
||||
<table class="grid" aria-label="@T["Purchases.Import.Lines"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">@T["Items.Fields.Code"]</th>
|
||||
<th scope="col">@T["Items.Fields.Description"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Movements.Quantity"]</th>
|
||||
<th scope="col" class="num">@T["Inventory.Reorder.Price"]</th>
|
||||
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
|
||||
<th scope="col" class="num">@T["Purchases.Import.Rate"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in invoice.Lines)
|
||||
{
|
||||
<tr>
|
||||
<td>@line.Number</td>
|
||||
<td class="code">@string.Join(" ", line.Codes.Select(c => c.Value))</td>
|
||||
<td>@line.Description</td>
|
||||
<td class="num">@(line.Quantity is { } q ? q.ToString("#,##0.###", T.Culture) + " " + line.Unit : null)</td>
|
||||
<td class="num">@T.Money(line.UnitPrice)</td>
|
||||
<td class="num">@T.Money(line.TotalPrice)</td>
|
||||
<td class="num">@(line.Nature ?? line.TaxRate.ToString("0.##", T.Culture) + "%")</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<KhStrip Items="SummaryOf(invoice)" Label="@T["Purchases.Import.Summary"]" />
|
||||
@if (invoice.Payments.Count > 0)
|
||||
{
|
||||
<ul class="kh-plainlist muted sm">
|
||||
@foreach (var payment in invoice.Payments)
|
||||
{
|
||||
<li>@T["Purchases.Import.Payment"] @(payment.DueDate is { } due ? T.Date(due) : null) · @T.Money(payment.Amount) @(payment.Iban is null ? null : " · " + payment.Iban)</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn primary" @onclick="() => _shown = null">@T["Common.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly HashSet<int> _selected = [];
|
||||
private List<IncomingCandidate> _invoices = [];
|
||||
private List<IncomingRejected> _rejected = [];
|
||||
private List<IncomingImported> _results = [];
|
||||
private IncomingCandidate? _shown;
|
||||
private bool _loaded;
|
||||
private bool _busy;
|
||||
private int _step;
|
||||
|
||||
private IReadOnlyList<KhStep> 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<int> 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<KhStat> 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))),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<DocumentRecord, DocumentLine>
|
||||
@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. *@
|
||||
<KhPageTitle Text="@PageTitle" Icon="@(_section?.Icon ?? "file")" />
|
||||
@@ -46,8 +52,8 @@ else
|
||||
var h = Record.Header;
|
||||
<KhRecordLayout Page="this">
|
||||
<Heading>
|
||||
<KhDocHead KindIcon="@_section.Icon" KindLabel="@_definition.Type.Description" Number="@(h.DocumentNumber ?? T["Sales.DraftNumber"])"
|
||||
PartyName="@(_party?.Name ?? T["Sales.NoParty"])" PartyCode="@_party?.Code" PartyLines="PartyLines"
|
||||
<KhDocHead KindIcon="@_section.Icon" KindLabel="@_definition.Type.Description" Number="@SalesScreens.Number(T, h.DocumentNumber, h.Status)"
|
||||
PartyName="@(IsInternal ? (PartyScreens.Describe(_lookups.InventoryReasons, h.InventoryReasonId) ?? T["Inventory.NoReason"]) : _party?.Name ?? T["Sales.NoParty"])" PartyCode="@_party?.Code" PartyLines="PartyLines"
|
||||
TotalLabel="@T[ShowsNet ? "Sales.Totals.Net" : "Sales.Totals.Total"]" TotalValue="@T.Money(ShowsNet ? h.NetAmount : h.TotalAmount)" SubValues="HeadStats">
|
||||
<Facts>
|
||||
<span>@T["Sales.Fields.DocumentDate"] <b>@T.Date(h.DocumentDate)</b></span>
|
||||
@@ -104,7 +110,29 @@ else
|
||||
@switch (ActiveTab)
|
||||
{
|
||||
case TabIds.Lines:
|
||||
@if (h.PartyId is null && !IsReadOnly)
|
||||
@if (_differences.Count > 0)
|
||||
{
|
||||
<div class="callout warn kh-doc-callout"><KhIcon Name="alert" />
|
||||
<span>@(_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))
|
||||
{
|
||||
<br /><span class="sm">@T.Format("Purchases.PriceDifferences.Line", difference.LineNumber, difference.Description, difference.SourceNumber ?? string.Empty,
|
||||
T.Money(difference.SourcePrice), T.Money(difference.InvoicePrice))</span>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
@if (_selfAdvice is { } advice)
|
||||
{
|
||||
<div class="callout info kh-doc-callout"><KhIcon Name="refresh" />
|
||||
<span>@T.Format("Purchases.SelfInvoices.Advice", advice.DocumentTypeCode, Sentence(advice.Reason), T.Date(advice.Deadline))</span>
|
||||
@if (Session.Permissions.Allows(PurchaseService.WritePermission) && DocumentStateMachine.IsInForce(h.Status))
|
||||
{
|
||||
<button type="button" class="btn" @onclick="CreateSelfInvoiceAsync"><KhIcon Name="plus" /> @T["Purchases.SelfInvoices.Create"]</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (h.PartyId is null && !IsReadOnly && !IsInternal)
|
||||
{
|
||||
<div class="callout info kh-doc-callout"><KhIcon Name="info" /> <span>@T["Sales.Hints.PartyFirst"]</span>
|
||||
<button type="button" class="btn" @onclick="() => ShowTabAsync(TabIds.Header)">@T["Sales.Actions.ChooseParty"]</button></div>
|
||||
@@ -143,9 +171,17 @@ else
|
||||
{
|
||||
<KhDateBox Label="@T["Sales.Fields.DeliveryDate"]" Name="DeliveryDate" Value="h.DeliveryDate" ValueChanged="v => Change(() => h.DeliveryDate = v)" Span="4" />
|
||||
}
|
||||
<KhTextBox Label="@T["Sales.Fields.ExternalReference"]" Name="ExternalReference" Value="@h.ExternalReference" ValueChanged="v => Change(() => h.ExternalReference = v)"
|
||||
Span="8" MaxLength="60" Hint="@T["Sales.Hints.ExternalReference"]" />
|
||||
<KhDateBox Label="@T["Sales.Fields.ExternalDate"]" Name="ExternalDate" Value="h.ExternalDate" ValueChanged="v => Change(() => h.ExternalDate = v)" Span="4" />
|
||||
<KhTextBox Label="@T[IsPurchase ? "Purchases.Fields.SupplierNumber" : "Sales.Fields.ExternalReference"]" Name="ExternalReference" Value="@h.ExternalReference"
|
||||
ValueChanged="v => Change(() => h.ExternalReference = v)" Span="8" MaxLength="40" Required="@IsRegistered"
|
||||
Hint="@T[IsPurchase ? "Purchases.Hints.SupplierNumber" : "Sales.Hints.ExternalReference"]" Mono="@IsPurchase" />
|
||||
<KhDateBox Label="@T[IsPurchase ? "Purchases.Fields.SupplierDate" : "Sales.Fields.ExternalDate"]" Name="ExternalDate" Value="h.ExternalDate"
|
||||
ValueChanged="v => Change(() => h.ExternalDate = v)" Span="4" Required="@IsRegistered" />
|
||||
@if (IsRegistered)
|
||||
{
|
||||
<KhTextBox Label="@T["Purchases.Fields.Protocol"]" Name="VatProtocol" Value="@(h.VatProtocol?.ToString(T.Culture) ?? T["Sales.NumberOnConfirm"])" ReadOnly="true" Mono="true" Span="4" />
|
||||
<KhDateBox Label="@T["Purchases.Fields.VatDate"]" Name="VatDate" Value="h.VatDate" ValueChanged="v => Change(() => h.VatDate = v)" Span="4"
|
||||
Hint="@T["Purchases.Hints.VatDate"]" />
|
||||
}
|
||||
@if (IsNote)
|
||||
{
|
||||
<KhTextBox Label="@T["Sales.Fields.RelatedNumber"]" Name="RelatedNumber" Value="@h.RelatedNumber" ValueChanged="v => Change(() => h.RelatedNumber = v)"
|
||||
@@ -153,11 +189,31 @@ else
|
||||
<KhDateBox Label="@T["Sales.Fields.RelatedDate"]" Name="RelatedDate" Value="h.RelatedDate" ValueChanged="v => Change(() => h.RelatedDate = v)" Span="4" />
|
||||
}
|
||||
</KhFieldGroup>
|
||||
@if (IsInternal)
|
||||
{
|
||||
<KhFieldGroup Title="@T["Inventory.Groups.Movement"]" Icon="layers">
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Fields.Reason"]" Name="InventoryReasonId" Options="_lookups.InventoryReasons" Empty="" Span="6" Required="true"
|
||||
Value="@PartyScreens.Text(h.InventoryReasonId)" ValueChanged="v => Change(() => h.InventoryReasonId = PartyScreens.Id(v))" />
|
||||
<KhSelect TValue="string" Label="@T[IsTransfer ? "Inventory.Fields.FromWarehouse" : "Inventory.Fields.Warehouse"]" Name="WarehouseId" Options="_lookups.Warehouses" Empty="" Span="6"
|
||||
Value="@PartyScreens.Text(h.WarehouseId)" ValueChanged="v => Change(() => h.WarehouseId = PartyScreens.Id(v))" />
|
||||
@if (IsTransfer)
|
||||
{
|
||||
<KhSelect TValue="string" Label="@T["Inventory.Fields.ToWarehouse"]" Name="ToWarehouseId" Options="_lookups.Warehouses" Empty="" Span="6" Required="true"
|
||||
Value="@PartyScreens.Text(h.ToWarehouseId)" ValueChanged="v => Change(() => h.ToWarehouseId = PartyScreens.Id(v))" />
|
||||
}
|
||||
<p class="muted sm c12"><KhIcon Name="info" /> @T["Inventory.Hints.Movement"]</p>
|
||||
</KhFieldGroup>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhFieldGroup Title="@T["Sales.Groups.Party"]" Icon="users">
|
||||
<KhHotlink TItem="PartyRow" Label="@T["Sales.Fields.PartyId"]" Name="PartyId" Span="12" Required="true" Value="_party" ValueChanged="SetPartyAsync"
|
||||
<KhHotlink TItem="PartyRow" Label="@T[SalesScreens.PartyLabel(_section.Direction)]" Name="PartyId" Span="12" Required="true" Value="_party" ValueChanged="SetPartyAsync"
|
||||
Search="SearchPartiesAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenParty" ReadOnly="@(Record.Lines.Any(l => l.SourceLineId is not null))" />
|
||||
<KhSelect TValue="string" Label="@T["Sales.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="6"
|
||||
Value="@PartyScreens.Text(h.SalespersonId)" ValueChanged="v => Change(() => h.SalespersonId = PartyScreens.Id(v))" />
|
||||
@if (!IsPurchase)
|
||||
{
|
||||
<KhSelect TValue="string" Label="@T["Sales.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="6"
|
||||
Value="@PartyScreens.Text(h.SalespersonId)" ValueChanged="v => Change(() => h.SalespersonId = PartyScreens.Id(v))" />
|
||||
}
|
||||
<KhSelect TValue="string" Label="@T["Sales.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_lookups.Currencies" Span="6"
|
||||
Value="@h.CurrencyCode" ValueChanged="SetCurrency" />
|
||||
@if (h.PartyId is not null)
|
||||
@@ -203,6 +259,7 @@ else
|
||||
<p class="muted sm c9">@T["Sales.Hints.Withholding"]</p>
|
||||
</KhFieldGroup>
|
||||
}
|
||||
}
|
||||
</KhForm>
|
||||
break;
|
||||
|
||||
@@ -297,11 +354,11 @@ else
|
||||
<td class="code">
|
||||
@if (SalesScreens.RecordUrl(link.Kind, link.Id) is { } url)
|
||||
{
|
||||
<a href="@url">@(link.DocumentNumber ?? T["Sales.DraftNumber"])</a>
|
||||
<a href="@url">@SalesScreens.Number(T, link.DocumentNumber, link.Status)</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
@(link.DocumentNumber ?? T["Sales.DraftNumber"])
|
||||
@SalesScreens.Number(T, link.DocumentNumber, link.Status)
|
||||
}
|
||||
</td>
|
||||
<td>@T.Date(link.Date)</td>
|
||||
|
||||
@@ -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<DocumentAction> _actions = [];
|
||||
private IReadOnlyList<LinkedDocument> _links = [];
|
||||
private IReadOnlyList<PriceDifference> _differences = [];
|
||||
private SelfInvoiceAdvice? _selfAdvice;
|
||||
private IReadOnlyList<AuditItem> _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;
|
||||
|
||||
/// <inheritdoc />
|
||||
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<string> PartyLines
|
||||
@@ -847,10 +907,10 @@ public sealed partial class SalesDocumentPage
|
||||
|
||||
private async Task<IReadOnlyList<PartyRow>> 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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@Title" Icon="@(_section?.Icon ?? "cart")" />
|
||||
|
||||
@if (!_loaded)
|
||||
@@ -36,7 +39,11 @@ else if (!CanRead)
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhRadar TItem="DocumentRow" @key="_section.Segment" Id="@("sales." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
|
||||
@if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "autofatture")
|
||||
{
|
||||
<Khaemhat.Web.Components.Purchases.PendingSelfInvoicesPanel />
|
||||
}
|
||||
<KhRadar TItem="DocumentRow" @key="_section.Area + _section.Segment" Id="@(_section.Area == SalesScreens.BasePath ? "sales." + _section.Segment : _section.Area + "." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
|
||||
OnOpen="Open" QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Sales.Radar.Search"]" ExportName="@_section.Segment"
|
||||
Label="@Title">
|
||||
<Toolbar>
|
||||
@@ -44,10 +51,14 @@ else
|
||||
{
|
||||
<button type="button" class="btn primary" @onclick="New"><KhIcon Name="plus" /> @T["Sales.Sections." + _section.Key + ".New"]</button>
|
||||
}
|
||||
@if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write"))
|
||||
@if (_section.Area == SalesScreens.BasePath && _section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write"))
|
||||
{
|
||||
<a class="btn" href="@SalesScreens.DeferredInvoicingUrl"><KhIcon Name="layers" /> @T["Sales.Deferred.Title"]</a>
|
||||
}
|
||||
@if (_section.Area == SalesScreens.PurchasesPath && _section.Segment == "fatture" && Session.Permissions.Allows("purchases.invoice.write"))
|
||||
{
|
||||
<a class="btn" href="acquisti/importa-fatture"><KhIcon Name="upload" /> @T["Shell.Menu.Purchases.Import"]</a>
|
||||
}
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
|
||||
@@ -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<KhColumn<DocumentRow>> 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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
<KhPanel Title="@T["Purchases.SelfInvoices.Pending"]" Icon="refresh" Class="kh-pendingself">
|
||||
<Actions><span class="badge @(pending.Any(p => p.Advice.Deadline < Today) ? "red" : "amber")">@T.Number(pending.Count)</span></Actions>
|
||||
<ChildContent>
|
||||
<div class="gridwrap">
|
||||
<table class="grid" aria-label="@T["Purchases.SelfInvoices.Pending"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Invoice"]</th>
|
||||
<th scope="col">@T["Purchases.Fields.Supplier"]</th>
|
||||
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Type"]</th>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Reason"]</th>
|
||||
<th scope="col">@T["Purchases.SelfInvoices.Deadline"]</th>
|
||||
<th scope="col"><span class="sr-only">@T["Purchases.SelfInvoices.Create"]</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var item in pending)
|
||||
{
|
||||
var row = item.Invoice;
|
||||
<tr>
|
||||
<td class="code"><a href="@SalesScreens.RecordUrl(row.Kind, row.Id)">@row.DocumentNumber</a> · @T.Date(row.Date)</td>
|
||||
<td>@row.PartyName</td>
|
||||
<td class="num">@T.Money(row.Taxable)</td>
|
||||
<td class="code">@item.Advice.DocumentTypeCode</td>
|
||||
<td>@item.Advice.Reason</td>
|
||||
<td><KhBadge Tone="@(item.Advice.Deadline < Today ? KhTone.Error : item.Advice.Deadline <= Today.AddDays(5) ? KhTone.Warning : KhTone.Neutral)">@T.Date(item.Advice.Deadline)</KhBadge></td>
|
||||
<td>
|
||||
@if (CanWrite)
|
||||
{
|
||||
<button type="button" class="btn sm primary" disabled="@_busy" @onclick="() => CreateAsync(item)"><KhIcon Name="plus" /> @T["Purchases.SelfInvoices.Create"]</button>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
}
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<PendingSelfInvoice>? _pending;
|
||||
private bool _busy;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(PurchaseService.WritePermission);
|
||||
|
||||
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,12 @@ public sealed class DocumentLookups
|
||||
/// <summary>Warehouses.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Warehouses { get; private init; } = [];
|
||||
|
||||
/// <summary>Warehouse reasons (causali di magazzino).</summary>
|
||||
public IReadOnlyList<KhOption<string>> InventoryReasons { get; private init; } = [];
|
||||
|
||||
/// <summary>The ids of the reasons that move goods between two warehouses.</summary>
|
||||
public IReadOnlySet<long> TransferReasons { get; private init; } = new HashSet<long>();
|
||||
|
||||
/// <summary>Carriers.</summary>
|
||||
public IReadOnlyList<KhOption<string>> Carriers { get; private init; } = [];
|
||||
|
||||
@@ -68,6 +74,8 @@ public sealed class DocumentLookups
|
||||
Salespeople = await ReadAsync<Salesperson>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
BankAccounts = await ReadAsync<BankAccount>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
Warehouses = await ReadAsync<Warehouse>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
InventoryReasons = await ReadAsync<InventoryReason>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
TransferReasons = (await tables.ActiveAsync<InventoryReason>(actor, company, cancellationToken).ConfigureAwait(false)).Where(r => r.IsTransfer).Select(r => r.Id).ToHashSet(),
|
||||
Carriers = await ReadAsync<Carrier>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
ShippingTerms = await ReadAsync<ShippingTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
TransportReasons = await ReadAsync<TransportReason>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
|
||||
|
||||
@@ -5,24 +5,37 @@ using Khaemhat.Web.Ui;
|
||||
|
||||
namespace Khaemhat.Web.Documents;
|
||||
|
||||
/// <summary>A radar of the sales menu and the document types it holds.</summary>
|
||||
/// <summary>A radar of the documents menus (sales, purchases, warehouse) and the document types it holds.</summary>
|
||||
/// <param name="Segment">The path segment, such as <c>fatture</c>.</param>
|
||||
/// <param name="Family">The family of the documents.</param>
|
||||
/// <param name="Kinds">The kinds shown.</param>
|
||||
/// <param name="NewTypes">The document types a user can create from the radar, the first being the usual one.</param>
|
||||
/// <param name="Icon">The icon.</param>
|
||||
/// <param name="Key">The key of the texts under <c>Sales.Sections</c>.</param>
|
||||
public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList<DocumentKind> Kinds, IReadOnlyList<string> NewTypes, string Icon, string Key);
|
||||
/// <param name="Area">The menu area, such as <c>vendite</c> or <c>acquisti</c>.</param>
|
||||
public sealed record SalesSection(
|
||||
string Segment, DocumentFamily Family, IReadOnlyList<DocumentKind> Kinds, IReadOnlyList<string> NewTypes, string Icon, string Key, string Area = SalesScreens.BasePath)
|
||||
{
|
||||
/// <summary>Whose documents: customers, suppliers or nobody.</summary>
|
||||
public DocumentDirection Direction => DocumentBehaviors.Of(Kinds[0]).Direction;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under
|
||||
/// <c>/vendite</c>, 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
|
||||
/// <c>/vendite</c>, <c>/acquisti</c> and <c>/magazzino</c>, 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).
|
||||
/// </summary>
|
||||
public static class SalesScreens
|
||||
{
|
||||
/// <summary>The menu area.</summary>
|
||||
/// <summary>The sales area.</summary>
|
||||
public const string BasePath = "vendite";
|
||||
|
||||
/// <summary>The purchases area.</summary>
|
||||
public const string PurchasesPath = "acquisti";
|
||||
|
||||
/// <summary>The warehouse area.</summary>
|
||||
public const string InventoryPath = "magazzino";
|
||||
|
||||
/// <summary>The deferred invoicing of the delivery notes.</summary>
|
||||
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),
|
||||
];
|
||||
|
||||
/// <summary>The radar of a path segment.</summary>
|
||||
/// <summary>The sales radar of a path segment.</summary>
|
||||
/// <param name="segment">The segment.</param>
|
||||
/// <returns>The radar, or <see langword="null"/>.</returns>
|
||||
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);
|
||||
|
||||
/// <summary>The radar of an area and a path segment.</summary>
|
||||
/// <param name="area">The area, such as <c>acquisti</c>.</param>
|
||||
/// <param name="segment">The segment.</param>
|
||||
/// <returns>The radar, or <see langword="null"/>.</returns>
|
||||
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));
|
||||
|
||||
/// <summary>The area of a relative address: its first segment.</summary>
|
||||
/// <param name="relativePath">The address relative to the base, such as <c>acquisti/fatture/3</c>.</param>
|
||||
/// <returns>The area.</returns>
|
||||
public static string AreaOf(string? relativePath)
|
||||
{
|
||||
var path = relativePath ?? string.Empty;
|
||||
var end = path.IndexOfAny(['/', '?', '#']);
|
||||
return end < 0 ? path : path[..end];
|
||||
}
|
||||
|
||||
/// <summary>The key of the label of the party for a direction: customer, supplier.</summary>
|
||||
/// <param name="direction">The direction.</param>
|
||||
/// <returns>The key of the text.</returns>
|
||||
public static string PartyLabel(DocumentDirection direction) => direction == DocumentDirection.Purchase ? "Purchases.Fields.Supplier" : "Sales.Fields.PartyId";
|
||||
|
||||
/// <summary>The radar that holds a kind of document.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>The address of a document.</summary>
|
||||
@@ -93,6 +134,20 @@ public static class SalesScreens
|
||||
return texts["Sales.Kinds." + kind];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="number">The document number.</param>
|
||||
/// <param name="status">The state.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Number(ITexts texts, string? number, DocumentStatus status)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return number ?? texts[status == DocumentStatus.Draft ? "Sales.DraftNumber" : "Sales.NoNumber"];
|
||||
}
|
||||
|
||||
/// <summary>The label and tone of a state; a quotation shows its outcome (accepted, refused, expired).</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="kind">The kind.</param>
|
||||
|
||||
@@ -146,6 +146,12 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<AutoFillService>();
|
||||
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
|
||||
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.InventoryService>();
|
||||
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseService>();
|
||||
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseInvoiceImportService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.StockTakeService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.ReorderService>();
|
||||
services.AddSingleton<IScheduledJob, Khaemhat.Application.Inventory.InventoryRebuildJob>();
|
||||
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
|
||||
|
||||
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
|
||||
@@ -178,6 +184,8 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
|
||||
services.AddSingleton<DemoSalesSeeder>();
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
|
||||
services.AddSingleton<DemoPurchasesSeeder>();
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoPurchasesSeeder>());
|
||||
services.AddSingleton<CompanyService>();
|
||||
services.AddSingleton<CompanyContextResolver>();
|
||||
services.AddScoped<ICompanyContext, WebCompanyContext>();
|
||||
|
||||
@@ -132,6 +132,7 @@ public static class SeedCommand
|
||||
|
||||
// The demo documents go through the document engine, after the masters they use.
|
||||
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
|
||||
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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."
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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": {
|
||||
|
||||
@@ -74,7 +74,9 @@
|
||||
"_": "Acquisti",
|
||||
"Orders": "Ordini fornitori",
|
||||
"Receipts": "Ricevimenti merce",
|
||||
"Invoices": "Fatture passive"
|
||||
"Invoices": "Fatture passive",
|
||||
"Import": "Importa fatture",
|
||||
"SelfInvoices": "Autofatture"
|
||||
},
|
||||
"Inventory": {
|
||||
"_": "Magazzino",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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; }
|
||||
@@ -0,0 +1,104 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Inventory;
|
||||
|
||||
/// <summary>Which documents move the stock and how the weighted average values it (issue #59, ADR 0035).</summary>
|
||||
[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<InvalidOperationException>(() => StockEffectMatrix.Movements(DocumentKind.InventoryEntry, Transfer, null, [new StockLineInput(1, 100, 3m, 1, null)]));
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => 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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Tests.Security;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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 = """
|
||||
<FatturaElettronicaHeader>
|
||||
<DatiTrasmissione>
|
||||
<IdTrasmittente><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdTrasmittente>
|
||||
<ProgressivoInvio>00042</ProgressivoInvio>
|
||||
<FormatoTrasmissione>FPR12</FormatoTrasmissione>
|
||||
<CodiceDestinatario>ABC1234</CodiceDestinatario>
|
||||
</DatiTrasmissione>
|
||||
<CedentePrestatore>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdFiscaleIVA>
|
||||
<CodiceFiscale>01234567890</CodiceFiscale>
|
||||
<Anagrafica><Denominazione>Ferramenta Piemontese S.r.l.</Denominazione></Anagrafica>
|
||||
<RegimeFiscale>RF01</RegimeFiscale>
|
||||
</DatiAnagrafici>
|
||||
<Sede>
|
||||
<Indirizzo>Via Roma</Indirizzo><NumeroCivico>12</NumeroCivico><CAP>10121</CAP>
|
||||
<Comune>Torino</Comune><Provincia>TO</Provincia><Nazione>IT</Nazione>
|
||||
</Sede>
|
||||
<IscrizioneREA><Ufficio>TO</Ufficio><NumeroREA>123456</NumeroREA><StatoLiquidazione>LN</StatoLiquidazione></IscrizioneREA>
|
||||
<Contatti><Telefono>011 1234567</Telefono><Email>amministrazione@ferramenta.example</Email></Contatti>
|
||||
</CedentePrestatore>
|
||||
<CessionarioCommittente>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>09876543210</IdCodice></IdFiscaleIVA>
|
||||
<Anagrafica><Denominazione>Officine Esempio S.p.A.</Denominazione></Anagrafica>
|
||||
</DatiAnagrafici>
|
||||
<Sede><Indirizzo>Corso Milano</Indirizzo><CAP>20121</CAP><Comune>Milano</Comune><Provincia>MI</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</CessionarioCommittente>
|
||||
</FatturaElettronicaHeader>
|
||||
""";
|
||||
|
||||
private const string OrdinaryBody = """
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento>
|
||||
<TipoDocumento>TD01</TipoDocumento>
|
||||
<Divisa>EUR</Divisa>
|
||||
<Data>2026-03-15</Data>
|
||||
<Numero>FT/2026/123</Numero>
|
||||
<ScontoMaggiorazione><Tipo>SC</Tipo><Percentuale>2.00</Percentuale></ScontoMaggiorazione>
|
||||
<ScontoMaggiorazione><Tipo>MG</Tipo><Importo>1.50</Importo></ScontoMaggiorazione>
|
||||
<ImportoTotaleDocumento>116.90</ImportoTotaleDocumento>
|
||||
<Causale>Fornitura di marzo</Causale>
|
||||
<Causale>Consegna in cantiere</Causale>
|
||||
</DatiGeneraliDocumento>
|
||||
<DatiOrdineAcquisto>
|
||||
<RiferimentoNumeroLinea>1</RiferimentoNumeroLinea>
|
||||
<RiferimentoNumeroLinea>2</RiferimentoNumeroLinea>
|
||||
<IdDocumento>ORD-77</IdDocumento>
|
||||
<Data>2026-03-01</Data>
|
||||
<CodiceCUP>J11B26000010001</CodiceCUP>
|
||||
<CodiceCIG>Z1234567AB</CodiceCIG>
|
||||
</DatiOrdineAcquisto>
|
||||
<DatiDDT>
|
||||
<NumeroDDT>DDT-501</NumeroDDT>
|
||||
<DataDDT>2026-03-10</DataDDT>
|
||||
<RiferimentoNumeroLinea>1</RiferimentoNumeroLinea>
|
||||
</DatiDDT>
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>1</NumeroLinea>
|
||||
<CodiceArticolo><CodiceTipo>SKU</CodiceTipo><CodiceValore>B-M8-ZN</CodiceValore></CodiceArticolo>
|
||||
<CodiceArticolo><CodiceTipo>EAN</CodiceTipo><CodiceValore>8001234567895</CodiceValore></CodiceArticolo>
|
||||
<Descrizione>Bulloni M8 zincati</Descrizione>
|
||||
<Quantita>100.00</Quantita>
|
||||
<UnitaMisura>PZ</UnitaMisura>
|
||||
<PrezzoUnitario>0.500000</PrezzoUnitario>
|
||||
<ScontoMaggiorazione><Tipo>SC</Tipo><Percentuale>10.00</Percentuale></ScontoMaggiorazione>
|
||||
<PrezzoTotale>45.00</PrezzoTotale>
|
||||
<AliquotaIVA>22.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>2</NumeroLinea>
|
||||
<Descrizione>Manuale tecnico di carpenteria</Descrizione>
|
||||
<Quantita>2.00</Quantita>
|
||||
<PrezzoUnitario>25.00</PrezzoUnitario>
|
||||
<PrezzoTotale>50.00</PrezzoTotale>
|
||||
<AliquotaIVA>4.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>3</NumeroLinea>
|
||||
<TipoCessionePrestazione>AC</TipoCessionePrestazione>
|
||||
<Descrizione>Contributo ambientale imballi</Descrizione>
|
||||
<DataInizioPeriodo>2026-03-01</DataInizioPeriodo>
|
||||
<DataFinePeriodo>2026-03-31</DataFinePeriodo>
|
||||
<PrezzoUnitario>10.00</PrezzoUnitario>
|
||||
<PrezzoTotale>10.00</PrezzoTotale>
|
||||
<AliquotaIVA>0.00</AliquotaIVA>
|
||||
<Natura>N2.2</Natura>
|
||||
<RiferimentoAmministrazione>CC-12</RiferimentoAmministrazione>
|
||||
</DettaglioLinee>
|
||||
<DatiRiepilogo>
|
||||
<AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>45.00</ImponibileImporto><Imposta>9.90</Imposta><EsigibilitaIVA>I</EsigibilitaIVA>
|
||||
</DatiRiepilogo>
|
||||
<DatiRiepilogo>
|
||||
<AliquotaIVA>4.00</AliquotaIVA><ImponibileImporto>50.00</ImponibileImporto><Imposta>2.00</Imposta><EsigibilitaIVA>I</EsigibilitaIVA>
|
||||
</DatiRiepilogo>
|
||||
<DatiRiepilogo>
|
||||
<AliquotaIVA>0.00</AliquotaIVA><Natura>N2.2</Natura><ImponibileImporto>10.00</ImponibileImporto><Imposta>0.00</Imposta>
|
||||
<RiferimentoNormativo>Non soggetto art. 15 DPR 633/72</RiferimentoNormativo>
|
||||
</DatiRiepilogo>
|
||||
</DatiBeniServizi>
|
||||
<DatiPagamento>
|
||||
<CondizioniPagamento>TP01</CondizioniPagamento>
|
||||
<DettaglioPagamento>
|
||||
<ModalitaPagamento>MP05</ModalitaPagamento>
|
||||
<DataScadenzaPagamento>2026-04-30</DataScadenzaPagamento>
|
||||
<ImportoPagamento>58.45</ImportoPagamento>
|
||||
<IBAN>IT60X0542811101000000123456</IBAN>
|
||||
</DettaglioPagamento>
|
||||
<DettaglioPagamento>
|
||||
<Beneficiario>Ferramenta Piemontese S.r.l.</Beneficiario>
|
||||
<ModalitaPagamento>MP05</ModalitaPagamento>
|
||||
<DataScadenzaPagamento>2026-05-31</DataScadenzaPagamento>
|
||||
<ImportoPagamento>58.45</ImportoPagamento>
|
||||
<IBAN>IT60X0542811101000000123456</IBAN>
|
||||
<BIC>BPMOIT22XXX</BIC>
|
||||
</DettaglioPagamento>
|
||||
</DatiPagamento>
|
||||
</FatturaElettronicaBody>
|
||||
""";
|
||||
|
||||
private static string Prefixed(params string[] bodies) =>
|
||||
$"""<?xml version="1.0" encoding="UTF-8"?><p:FatturaElettronica versione="FPR12" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:p="{Namespace}">{Header}{string.Concat(bodies)}</p:FatturaElettronica>""";
|
||||
|
||||
private static string Body(string type, string number, string date, string generalExtra = "", string documentExtra = "", string goods = "", string extra = "") => $"""
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento>
|
||||
<TipoDocumento>{type}</TipoDocumento><Divisa>EUR</Divisa><Data>{date}</Data><Numero>{number}</Numero>{documentExtra}
|
||||
</DatiGeneraliDocumento>{generalExtra}
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi>{(goods.Length > 0 ? goods : SimpleGoods)}</DatiBeniServizi>{extra}
|
||||
</FatturaElettronicaBody>
|
||||
""";
|
||||
|
||||
private const string SimpleGoods = """
|
||||
<DettaglioLinee><NumeroLinea>1</NumeroLinea><Descrizione>Consulenza</Descrizione><PrezzoUnitario>100.00</PrezzoUnitario><PrezzoTotale>100.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA></DettaglioLinee>
|
||||
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>100.00</ImponibileImporto><Imposta>22.00</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
|
||||
""";
|
||||
|
||||
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 = """
|
||||
<DatiFattureCollegate><IdDocumento>FT/2026/123</IdDocumento><Data>2026-03-15</Data></DatiFattureCollegate>
|
||||
<DatiContratto><IdDocumento>CTR-2026-01</IdDocumento></DatiContratto>
|
||||
""";
|
||||
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("<p:FatturaElettronica", "<FatturaElettronica", StringComparison.Ordinal)
|
||||
.Replace("</p:FatturaElettronica", "</FatturaElettronica", StringComparison.Ordinal)
|
||||
.Replace("xmlns:p=", "xmlns=", StringComparison.Ordinal);
|
||||
var everyElementPrefixed = System.Text.RegularExpressions.Regex
|
||||
.Replace(defaultNamespace, "<(/?)(?=[A-Za-z])", "<$1ns2:")
|
||||
.Replace("xmlns=", "xmlns:ns2=", StringComparison.Ordinal);
|
||||
var noDeclaration = defaultNamespace[defaultNamespace.IndexOf("?>", StringComparison.Ordinal)..][2..];
|
||||
|
||||
byte[] withBom = [0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes("\r\n " + prefixed)];
|
||||
var variants = new List<byte[]>
|
||||
{
|
||||
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 = """
|
||||
<DettaglioLinee><NumeroLinea>1</NumeroLinea><Descrizione>Caffè in grani € 1 al kg</Descrizione><PrezzoUnitario>10.00</PrezzoUnitario><PrezzoTotale>10.00</PrezzoTotale><AliquotaIVA>10.00</AliquotaIVA></DettaglioLinee>
|
||||
<DatiRiepilogo><AliquotaIVA>10.00</AliquotaIVA><ImponibileImporto>10.00</ImponibileImporto><Imposta>1.00</Imposta></DatiRiepilogo>
|
||||
""";
|
||||
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 = """
|
||||
<DatiRitenuta><TipoRitenuta>RT01</TipoRitenuta><ImportoRitenuta>208.00</ImportoRitenuta><AliquotaRitenuta>20.00</AliquotaRitenuta><CausalePagamento>A</CausalePagamento></DatiRitenuta>
|
||||
<DatiBollo><BolloVirtuale>SI</BolloVirtuale><ImportoBollo>2.00</ImportoBollo></DatiBollo>
|
||||
<DatiCassaPrevidenziale>
|
||||
<TipoCassa>TC01</TipoCassa><AlCassa>4.00</AlCassa><ImportoContributoCassa>40.00</ImportoContributoCassa>
|
||||
<ImponibileCassa>1000.00</ImponibileCassa><AliquotaIVA>22.00</AliquotaIVA><Ritenuta>SI</Ritenuta>
|
||||
</DatiCassaPrevidenziale>
|
||||
<ImportoTotaleDocumento>1270.88</ImportoTotaleDocumento>
|
||||
<Arrotondamento>0.01</Arrotondamento>
|
||||
<Art73>SI</Art73>
|
||||
""";
|
||||
var goods = """
|
||||
<DettaglioLinee><NumeroLinea>1</NumeroLinea><Descrizione>Parere legale</Descrizione><PrezzoUnitario>1000.00</PrezzoUnitario><PrezzoTotale>1000.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA><Ritenuta>SI</Ritenuta></DettaglioLinee>
|
||||
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>1040.00</ImponibileImporto><Imposta>228.80</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
|
||||
""";
|
||||
var xml = Prefixed(Body("TD06", "12/2026", "2026-04-02", documentExtra: document, goods: goods))
|
||||
.Replace("<Denominazione>Ferramenta Piemontese S.r.l.</Denominazione>", "<Nome>Giulia</Nome><Cognome>Bianchi</Cognome>", 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 = $"""
|
||||
<Allegati>
|
||||
<NomeAttachment>FT_2026_5.pdf</NomeAttachment>
|
||||
<FormatoAttachment>PDF</FormatoAttachment>
|
||||
<DescrizioneAttachment>Copia di cortesia</DescrizioneAttachment>
|
||||
<Attachment>{Convert.ToBase64String(pdf, Base64FormattingOptions.InsertLineBreaks)}
|
||||
</Attachment>
|
||||
</Allegati>
|
||||
""";
|
||||
|
||||
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 = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<p:FatturaElettronicaSemplificata versione="FSM10" xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.0">
|
||||
<FatturaElettronicaHeader>
|
||||
<DatiTrasmissione>
|
||||
<IdTrasmittente><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdTrasmittente>
|
||||
<ProgressivoInvio>S0001</ProgressivoInvio>
|
||||
<FormatoTrasmissione>FSM10</FormatoTrasmissione>
|
||||
<CodiceDestinatario>0000000</CodiceDestinatario>
|
||||
</DatiTrasmissione>
|
||||
<CedentePrestatore>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdFiscaleIVA>
|
||||
<Denominazione>Bar Centrale di Rossi Mario</Denominazione>
|
||||
<Sede><Indirizzo>Piazza Castello</Indirizzo><CAP>10123</CAP><Comune>Torino</Comune><Provincia>TO</Provincia><Nazione>IT</Nazione></Sede>
|
||||
<RegimeFiscale>RF01</RegimeFiscale>
|
||||
</CedentePrestatore>
|
||||
<CessionarioCommittente>
|
||||
<IdentificativiFiscali><IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>09876543210</IdCodice></IdFiscaleIVA></IdentificativiFiscali>
|
||||
<AltriDatiIdentificativi>
|
||||
<Denominazione>Officine Esempio S.p.A.</Denominazione>
|
||||
<Sede><Indirizzo>Corso Milano</Indirizzo><CAP>20121</CAP><Comune>Milano</Comune><Provincia>MI</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</AltriDatiIdentificativi>
|
||||
</CessionarioCommittente>
|
||||
</FatturaElettronicaHeader>
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento><TipoDocumento>TD08</TipoDocumento><Divisa>EUR</Divisa><Data>2026-05-04</Data><Numero>S/18</Numero></DatiGeneraliDocumento>
|
||||
<DatiFatturaRettificata><NumeroFR>S/12</NumeroFR><DataFR>2026-04-28</DataFR><ElementiRettificati>Importo</ElementiRettificati></DatiFatturaRettificata>
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi><Descrizione>Pranzo di lavoro</Descrizione><Importo>122.00</Importo><DatiIVA><Imposta>22.00</Imposta></DatiIVA></DatiBeniServizi>
|
||||
<DatiBeniServizi><Descrizione>Quotidiani e riviste</Descrizione><Importo>52.00</Importo><DatiIVA><Aliquota>4.00</Aliquota></DatiIVA></DatiBeniServizi>
|
||||
<DatiBeniServizi><Descrizione>Francobolli</Descrizione><Importo>30.00</Importo><DatiIVA><Imposta>0.00</Imposta></DatiIVA><Natura>N2.2</Natura></DatiBeniServizi>
|
||||
</FatturaElettronicaBody>
|
||||
</p:FatturaElettronicaSemplificata>
|
||||
""";
|
||||
|
||||
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("<FatturaElettronica><Header></FatturaElettronica>"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Dtd_IsRefused()
|
||||
{
|
||||
var xml = """<?xml version="1.0"?><!DOCTYPE x [<!ENTITY e SYSTEM "file:///etc/passwd">]><FatturaElettronica>&e;</FatturaElettronica>""";
|
||||
|
||||
AssertError(IncomingInvoiceErrors.NotReadable, Encoding.UTF8.GetBytes(xml));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_OtherXml_IsNotAnInvoice() =>
|
||||
AssertError(IncomingInvoiceErrors.NotInvoice, Encoding.UTF8.GetBytes("""<?xml version="1.0"?><Ordine><Numero>1</Numero></Ordine>"""));
|
||||
|
||||
[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 = $"""<FatturaElettronica xmlns="{Namespace}">{Body("TD01", "7", "2026-01-10")}</FatturaElettronica>""";
|
||||
var noBody = $"""<FatturaElettronica xmlns="{Namespace}">{Header}</FatturaElettronica>""";
|
||||
|
||||
foreach (var xml in new[] { noNumber, badDate, noHeader, noBody })
|
||||
{
|
||||
AssertError(IncomingInvoiceErrors.Invalid, Encoding.UTF8.GetBytes(xml));
|
||||
}
|
||||
|
||||
var ex = Assert.ThrowsExactly<IncomingInvoiceException>(() => 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<FatturaPaReader>(new ItalyFiscalPack().GetFeature<IIncomingInvoiceReader>());
|
||||
|
||||
private static void AssertError(string code, byte[] content)
|
||||
{
|
||||
var ex = Assert.ThrowsExactly<IncomingInvoiceException>(() => Reader.Read(FileName, content));
|
||||
Assert.AreEqual(code, ex.Code, ex.Message);
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,9 @@
|
||||
<ProjectReference Include="../../src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- The builder of signed envelopes is shared with the CMS tests: the p7m files are made in the test, never downloaded. -->
|
||||
<ItemGroup>
|
||||
<Compile Include="../Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs" Link="Shared/CmsTestSigner.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,167 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Security;
|
||||
|
||||
/// <summary>The reader of CMS SignedData envelopes (.p7m) used for received e-invoices (issue #57).</summary>
|
||||
[TestClass]
|
||||
public sealed class CmsSignedDataTests
|
||||
{
|
||||
private static readonly byte[] Content = Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?><FatturaElettronica>contenuto firmato</FatturaElettronica>");
|
||||
|
||||
[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("<?xml version=\"1.0\"?><FatturaElettronica>contenuto alterato</FatturaElettronica>");
|
||||
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("<Linea>Bulloni M8 zincati</Linea>", 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<CmsFormatException>(() => CmsSignedData.Read(Encoding.UTF8.GetBytes("questo non è un file firmato")));
|
||||
Assert.ThrowsExactly<CmsFormatException>(() => CmsSignedData.Read([]));
|
||||
Assert.ThrowsExactly<CmsFormatException>(() => 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<CmsFormatException>(() => 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using System.Formats.Asn1;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Security;
|
||||
|
||||
/// <summary>How <see cref="CmsTestSigner.Sign"/> builds the envelope.</summary>
|
||||
internal sealed record CmsTestOptions
|
||||
{
|
||||
/// <summary>BER with indefinite lengths and the content split in chunks, as many signing programs write.</summary>
|
||||
public bool Ber { get; init; }
|
||||
|
||||
/// <summary>Identify the signer by subject key identifier instead of issuer and serial number.</summary>
|
||||
public bool BySubjectKeyIdentifier { get; init; }
|
||||
|
||||
/// <summary>Whether to sign attributes (contentType, messageDigest, signingTime) or the content directly.</summary>
|
||||
public bool SignedAttributes { get; init; } = true;
|
||||
|
||||
/// <summary>Content put in the envelope instead of the signed one (to simulate tampering).</summary>
|
||||
public byte[]? TamperedContent { get; init; }
|
||||
|
||||
/// <summary>Flip a bit of the signature.</summary>
|
||||
public bool BreakSignature { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds CMS SignedData envelopes (CAdES .p7m) in the tests with <see cref="AsnWriter"/> and self-signed certificates:
|
||||
/// no fixture is downloaded and no package is needed. Shared with the tests of the FatturaPA reader.
|
||||
/// </summary>
|
||||
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<X509Certificate2> RsaCertificate = new(() => Create(ecdsa: false));
|
||||
private static readonly Lazy<X509Certificate2> EcdsaCertificate = new(() => Create(ecdsa: true));
|
||||
|
||||
/// <summary>A self-signed RSA certificate of "Mario Rossi" with SERIALNUMBER=TINIT-RSSMRA80A01H501U.</summary>
|
||||
public static X509Certificate2 Rsa => RsaCertificate.Value;
|
||||
|
||||
/// <summary>A self-signed ECDSA P-256 certificate of the same person.</summary>
|
||||
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<X509SubjectKeyIdentifierExtension>().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<AsnWriter> 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<AsnWriter> 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];
|
||||
}
|
||||
@@ -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<ValidationFailedException>(() => sales.NewAsync(Root, company, "OC"), "An order is not a sale document.");
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<ImportService>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
var stockService = app.Services.GetRequiredService<Khaemhat.Application.Inventory.InventoryService>();
|
||||
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<ImportFileException>(() => 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<SeedRunner>().RunAsync(company, SeedKind.Demo);
|
||||
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
|
||||
await app.Services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, context);
|
||||
var seeder = app.Services.GetRequiredService<DemoPurchasesSeeder>();
|
||||
await seeder.SeedAsync(company, context);
|
||||
|
||||
var editor = app.Services.GetRequiredService<DocumentEditor>();
|
||||
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<PurchaseService>().PendingSelfInvoicesAsync(Root, company);
|
||||
Assert.HasCount(1, pending);
|
||||
var inventory = app.Services.GetRequiredService<InventoryService>();
|
||||
Assert.IsNotEmpty(await inventory.StockAsync(Root, company, new StockFilter()));
|
||||
Assert.IsNotEmpty(await app.Services.GetRequiredService<ReorderService>().ProposalsAsync(Root, company));
|
||||
var take = (await app.Services.GetRequiredService<StockTakeService>().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<List<DocumentRow>> AllAsync(DocumentEditor editor, string company)
|
||||
{
|
||||
var all = new List<DocumentRow>();
|
||||
foreach (var family in new[] { DocumentFamily.PurchaseOrder, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
|
||||
{
|
||||
all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues<DocumentKind>()], new ListQuery { Limit = 200 })).Items);
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<DocumentEngine>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
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<InventoryReason>(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<DocumentEngine>();
|
||||
var copies = app.Services.GetRequiredService<DocumentCopyService>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
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<DocumentRecord> 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<long> ItemAsync(WebApplication app, string company, string code, string description, decimal? minimum)
|
||||
{
|
||||
var items = app.Services.GetRequiredService<ItemService>();
|
||||
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<long> PartyAsync(WebApplication app, string company, PartyKind kind, string name, string vatNumber)
|
||||
{
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<DocumentEngine>();
|
||||
var copies = app.Services.GetRequiredService<DocumentCopyService>();
|
||||
var purchases = app.Services.GetRequiredService<PurchaseService>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
var vat22 = (await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<DocumentEngine>();
|
||||
var purchases = app.Services.GetRequiredService<PurchaseService>();
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
var taxes = await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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) => $"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<p:FatturaElettronica versione="FPR12" xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2">
|
||||
<FatturaElettronicaHeader>
|
||||
<DatiTrasmissione>
|
||||
<IdTrasmittente><IdPaese>IT</IdPaese><IdCodice>01234567897</IdCodice></IdTrasmittente>
|
||||
<ProgressivoInvio>00042</ProgressivoInvio><FormatoTrasmissione>FPR12</FormatoTrasmissione><CodiceDestinatario>0000000</CodiceDestinatario>
|
||||
</DatiTrasmissione>
|
||||
<CedentePrestatore>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>01234567897</IdCodice></IdFiscaleIVA>
|
||||
<Anagrafica><Denominazione>Ferramenta Piemontese S.r.l.</Denominazione></Anagrafica>
|
||||
<RegimeFiscale>RF01</RegimeFiscale>
|
||||
</DatiAnagrafici>
|
||||
<Sede><Indirizzo>Via Roma</Indirizzo><NumeroCivico>12</NumeroCivico><CAP>10121</CAP><Comune>Torino</Comune><Provincia>TO</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</CedentePrestatore>
|
||||
<CessionarioCommittente>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>02987654304</IdCodice></IdFiscaleIVA>
|
||||
<Anagrafica><Denominazione>Azienda di prova</Denominazione></Anagrafica>
|
||||
</DatiAnagrafici>
|
||||
<Sede><Indirizzo>Corso Milano</Indirizzo><CAP>20121</CAP><Comune>Milano</Comune><Provincia>MI</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</CessionarioCommittente>
|
||||
</FatturaElettronicaHeader>
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento>
|
||||
<TipoDocumento>{type}</TipoDocumento><Divisa>EUR</Divisa><Data>{date}</Data><Numero>{number}</Numero>
|
||||
<ImportoTotaleDocumento>{total}</ImportoTotaleDocumento><Causale>Fornitura di marzo</Causale>
|
||||
</DatiGeneraliDocumento>
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi>{lines}{summary}</DatiBeniServizi>
|
||||
</FatturaElettronicaBody>
|
||||
</p:FatturaElettronica>
|
||||
""";
|
||||
|
||||
private const string Lines = """
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>1</NumeroLinea>
|
||||
<CodiceArticolo><CodiceTipo>SKU</CodiceTipo><CodiceValore>VALV-01</CodiceValore></CodiceArticolo>
|
||||
<Descrizione>Valvola a sfera 1/2</Descrizione><Quantita>10.00</Quantita><UnitaMisura>PZ</UnitaMisura><PrezzoUnitario>4.000000</PrezzoUnitario>
|
||||
<ScontoMaggiorazione><Tipo>SC</Tipo><Percentuale>10.00</Percentuale></ScontoMaggiorazione>
|
||||
<PrezzoTotale>36.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>2</NumeroLinea><Descrizione>Spese di trasporto</Descrizione><PrezzoUnitario>15.00</PrezzoUnitario><PrezzoTotale>15.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
""";
|
||||
|
||||
private const string Summary = """
|
||||
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>51.00</ImponibileImporto><Imposta>11.22</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
|
||||
""";
|
||||
|
||||
[TestMethod]
|
||||
public async Task Import_AddsTheSupplier_MatchesItemsAndTaxes_AndRefusesTheSameInvoiceTwice()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var import = app.Services.GetRequiredService<PurchaseInvoiceImportService>();
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var attachments = app.Services.GetRequiredService<AttachmentService>();
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
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("<FatturaElettronica>"))]);
|
||||
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<IIncomingInvoiceRules>(rules);
|
||||
}
|
||||
|
||||
private static async Task Add(ZipArchive archive, string name, byte[] content)
|
||||
{
|
||||
await using var stream = archive.CreateEntry(name).Open();
|
||||
await stream.WriteAsync(content);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The physical stock take, the reorder proposal and the rebuild of the warehouse on a real instance (issue #60).
|
||||
/// </summary>
|
||||
[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<DocumentEngine>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
var takes = app.Services.GetRequiredService<StockTakeService>();
|
||||
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<ValidationFailedException>(() => 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<ValidationFailedException>(() => takes.SaveCountsAsync(Root, company, take.Take.Id, new Dictionary<long, decimal?>()));
|
||||
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<DocumentEngine>();
|
||||
var reorder = app.Services.GetRequiredService<ReorderService>();
|
||||
var items = app.Services.GetRequiredService<ItemService>();
|
||||
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<ValidationFailedException>(() => 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<DocumentEngine>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
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<RebuildPhase>();
|
||||
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<AccessDeniedException>(() => stock.RebuildAsync(reader, company));
|
||||
|
||||
var job = app.Services.GetServices<Khaemhat.Application.Jobs.IScheduledJob>().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<T> which posts to the thread pool.
|
||||
private sealed class SyncProgress(Action<RebuildProgress> report) : IProgress<RebuildProgress>
|
||||
{
|
||||
public void Report(RebuildProgress value) => report(value);
|
||||
}
|
||||
}
|
||||